okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
28ce98bf1
main
1// tools/trellis/tqenc.hpp - tail-biting Viterbi ENCODER for the trellis expert formats (TQ2_T, TQK6, TQK7 of the 2// agentionai llama.cpp fork, ggml types 144-146) and two experimental lower-rate versions (TQK5X, TQK4X, and the table-based TQK5T, TQK4T). 3// 4// Standalone (no ggml, no Strata engine): it only needs third_party/ggml/ggml-common-tq.h (the 2048-point codebook). 5// The decoders it must match are src/kernels/cpu/tq_states.hpp / tq_cpu.cpp (tools/trellis/tqenc_test.cpp checks 6// bit for bit against them, and the scalar / AVX2 / AVX-512 kernels against the encoder's own reconstruction). 7// 8// THE FORMAT (see tq_states.hpp, include/strata/kernels/cpu/tq_cpu.hpp, docs/GYRO.md): 9// block = 128 weights = {fp16 d (little endian); qs[4*K]}, 32 steps t of 4 weights (weights 4t..4t+3). 10// State of step t: 15 bits. weights = d * codebook(state); the state's hash x = state * 0x9e3779b1 picks two 11// points lut[x >> 21] and lut[(x >> 10) & 2047] (fp16 pairs) = four values. The decoder works on the int16 table 12// round(fp16 * 8192) (tq_state_table), so that table, divided by 8192, is the codebook here. 13// TQK (K = 4,5,6,7): state(t) = bits [(31-t)K, (31-t)K + 15) of the qs bit stream (LSB first), circular modulo 14// 32K bits. With u = 31 - t the states form a shift trellis: state(u+1) = (state(u) >> K) | (new K bits << 15// (15-K)); the K low bits of state(u) are stream symbol u. Tail-biting: state(0) closes the cycle. 16// TQ2_T (K = 8): state(t) = ((qs[(t+31)%32] << 8) | qs[t]) & 0x7fff: a shift trellis in the other direction 17// (state(t) = ((state(t-1) & 0x7f) << 8) | qs[t]). 18// Both are a "de Bruijn" trellis of 2^15 states with 2^K branches per state, so one Viterbi step is a min over G 19// groups of predecessors followed by a broadcast add (G = 2^(15-K) groups for TQK, 128 for TQ2_T), not 2^15 * 2^K 20// additions. Tail-biting = a cycle of 32 states: the group of state(0) as successor equals the group of state(31) 21// as predecessor. The search fixes that group c (exact: all G values; approximate: c taken from a free Viterbi pass 22// on the cyclically rotated sequence, QTIP's approach, optionally the best of several rotations). 23// 24// New experimental types (EXPERIMENTAL_VERSION 2; not in any ggml enum or GGUF reader; ids away from the fork's 143-149): 25// TQK5X (224, 22 bytes / 128 weights, 1.375 bpw) and TQK4X (225, 18 bytes, 1.125 bpw): the TQK rule with K = 5 / 4 and the 26// COMPUTED codebook (src/kernels/cpu/tq_computed.hpp: two LCG words per state masked into four fp16, no table); 27// TQK5T (226) and TQK4T (227): version 1, the same K = 5 / 4 layout with the fork's hashed point table (what the first 28// pilots used). Same bit order, circular stream, 15-bit mask and fp16 scale in all of them. 29#pragma once 30 31#include <cstddef> 32#include <cstdint> 33 34namespace tqenc { 35 36inline constexpr int kBlock = 128 ; 37inline constexpr int kStates = 1 <<15 ; 38inline constexpr int kExperimentalVersion = 2 ; 39 40// ggml type ids of the fork (decoders exist) and the experimental ones (encoder + Strata CPU decoder only) 41enum Type :int { 42TQ2_T = 144 ,TQK6 = 145 ,TQK7 = 146 ,// the fork's types (hashed point table) 43TQK5X = 224 ,TQK4X = 225 ,// experimental version 2: K = 5 / 4 with the computed (LUT-free) codebook, tq_computed.hpp 44TQK5T = 226 ,TQK4T = 227 // experimental version 1: K = 5 / 4 with the fork's point table (the first pilots) 45}; 46/// Whether the type's codebook is the computed one (TQK5X, TQK4X). 47bool type_computed (int type ); 48/// rms of the codebook values (the first scale guess is rms(block) / this): 1.072 for the table, 0.88 for the computed code. 49double codebook_rms (int type ); 50 51/// bits per step (8, 6, 7, 5, 4), 0 for any other type. 52int type_kbits (int type ); 53inline int block_bytes (int type ) {return type_kbits (type ) ?2 + 4 * type_kbits (type ) :0 ; } 54 55struct Params { 56int iters = 3 ;///< scale refinement rounds after the first search (path given d -> d given path) 57int ncand = 1 ;///< tail-biting start-group candidates (rotations 16, 8, 24, 12, 20, 4, 28 ...); 1 = QTIP's 58int exact = 0 ;///< 1: try every start group (the exact tail-biting optimum at the current scale; slow) 59int scale_tries = 1 ;///< initial scales d0 * {1, 0.9, 1.1, 0.8, 1.2, ...}: the best of the first n searches 60uint16_t fixed_scale = 0 ;///< nonzero: this fp16 scale is used as is (no refinement); tests, planted solutions 61}; 62 63struct BlockResult { 64double err = 0 ;///< sum_i h_i (w_i - rec_i)^2 for the stored block (h = 1 without importance weights) 65float scale = 0 ;///< the stored fp16 scale 66int searches = 0 ;///< Viterbi passes run 67int status = 0 ;///< 0 ok, 1 zero block (all weights zero or below fp16 resolution), 2 nonfinite input 68}; 69 70/// The codebook entry of a state as the decoder sees it: four floats (int16 table / 8192, exact). 71const float * codebook_state (int type ,uint32_t state );// 4 floats 72const int16_t * codebook_table (int type );// 32768 * 4 int16, the decoder's tq_state_table() 73/// The 2048 codebook points as the decoder sees them (x, y interleaved): round(fp16 * 8192) / 8192. The GPU encoder 74/// uploads this table; it must be built by the host compiler (ggml-common-tq.h makes its table __device__ under hipcc). 75const float * point_table ();// 4096 floats 76 77/// The state of step t (0..31) of a block's stream, by the decoder's rule, written bit by bit (independent of 78/// tq_states.hpp). qs = the 4K stream bytes. 79uint32_t block_state (int type ,const uint8_t * qs ,int t ); 80 81/// Decodes `nblocks` blocks (block_bytes(type) each) to 128 floats each: d * codebook, d the fp16 scale. 82void decode_blocks (int type ,const uint8_t * src ,int64_t nblocks ,float * out ); 83 84/// Encodes one block of 128 weights (importance weights h[128] or null) into block_bytes(type) bytes. 85BlockResult encode_block (int type ,const float * w ,const float * h ,uint8_t * dst ,const Params & p ); 86 87/// Encodes nblocks consecutive blocks on `nthreads` threads (0: hardware concurrency). err_out (nblocks doubles) and 88/// the returned sum of block errors are the objective sum h (w - rec)^2. Sets *nonfinite to the number of blocks 89/// with a NaN/Inf input weight (those are written as zero blocks). 90double encode_blocks (int type ,const float * w ,const float * h ,int64_t nblocks ,uint8_t * dst ,const Params & p , 91int nthreads ,double * err_out ,int64_t * nonfinite ,int64_t * zero_blocks ); 92 93/// TEST HOOK: one Viterbi pass over a scaled target (T[p][4] = weights / d of processing position p, H[p][4]) and the 94/// legal-path states by position. rot = first position processed, fixed_c = tail-biting group (-1 free). 95float debug_viterbi (int type ,const float (* T )[4 ],const float (* H )[4 ],int rot ,int fixed_c ,uint16_t * st ); 96/// Group sizes: predecessor groups G of a type; processing position p -> weight index of component j. 97int debug_groups (int type ); 98int debug_widx (int type ,int p ,int j ); 99/// the stream bytes (4K) of a state path by position, as the encoder packs them 100void debug_pack (int type ,const uint16_t * st ,uint8_t * qs ); 101 102// fp16 helpers (round to nearest even, like the hardware; exposed for the tests) 103uint16_t float_to_half (float f ); 104float half_to_float (uint16_t h ); 105 106}// namespace tqenc