okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-dsv41-rel (0be62ccad) into v0.2.3.1: DeepSeek V4.1-Flash on top of the released 0.2.3 line28ce98bf1

main
22.7 KiB601 linesraw
1// tools/trellis/tqenc.cpp - see tqenc.hpp.
2#include "tqenc.hpp"
3
4#include "ggml-common-tq.h"
5#include "tq_computed.hpp"
6
7#include <algorithm>
8#include <atomic>
9#include <cmath>
10#include <cstdlib>
11#include <cstring>
12#include <memory>
13#include <mutex>
14#include <thread>
15#include <vector>
16
17#if defined(__AVX2__) && defined(__FMA__)
18#include <immintrin.h>
19#define TQENC_AVX2 1
20#endif
21
22namespace tqenc {
23namespace {
24
25constexpr float kInf = 1e30f;
26
27// ---------------------------------------------------------------------------------------------------------------
28// fp16
29
30}  // namespace
31
32float half_to_float(uint16_t h) {
33    const uint32_t sign = (uint32_t) (h & 0x8000u) << 16;
34    uint32_t exp = (h >> 10) & 0x1fu, man = h & 0x3ffu, bits;
35    if (exp == 0x1fu) {
36        bits = sign | 0x7f800000u | (man << 13);
37    } else if (exp != 0) {
38        bits = sign | ((exp + 112u) << 23) | (man << 13);
39    } else if (man == 0) {
40        bits = sign;
41    } else {
42        const float m = (float) man * (1.0f / 16777216.0f);
43        return sign ? -m : m;
44    }
45    float f;
46    std::memcpy(&f, &bits, 4);
47    return f;
48}
49
50uint16_t float_to_half(float f) {
51    uint32_t x;
52    std::memcpy(&x, &f, 4);
53    const uint32_t sign = (x >> 16) & 0x8000u;
54    const uint32_t ax = x & 0x7fffffffu;
55    if (ax >= 0x7f800000u) return (uint16_t) (sign | 0x7c00u | (ax > 0x7f800000u ? 0x200u : 0u));   // inf / nan
56    if (ax >= 0x477ff000u) return (uint16_t) (sign | 0x7c00u);   // >= 65520 rounds to inf
57    if (ax < 0x33000001u) return (uint16_t) sign;                // <= 2^-25: rounds to zero (ties to even)
58    int e = (int) (ax >> 23) - 127;
59    uint32_t man = (ax & 0x7fffffu) | 0x800000u;
60    if (e < -14) {   // subnormal half
61        const int shift = -14 - e + 13;   // total right shift of the 24-bit mantissa
62        const uint32_t half = 1u << (shift - 1), rest = man & ((1u << shift) - 1);
63        uint32_t q = man >> shift;
64        if (rest > half || (rest == half && (q & 1))) ++q;
65        return (uint16_t) (sign | q);
66    }
67    uint32_t q = ((uint32_t) (e + 15) << 10) | ((man >> 13) & 0x3ffu);
68    const uint32_t rest = man & 0x1fffu;
69    if (rest > 0x1000u || (rest == 0x1000u && (q & 1))) ++q;   // a carry into the exponent is correct
70    return (uint16_t) (sign | q);
71}
72
73int type_kbits(int type) {
74    switch (type) {
75        case TQ2_T: return 8;
76        case TQK6: return 6;
77        case TQK7: return 7;
78        case TQK5X: case TQK5T: return 5;
79        case TQK4X: case TQK4T: return 4;
80        default: return 0;
81    }
82}
83
84bool type_computed(int type) { return type == TQK5X || type == TQK4X; }
85
86double codebook_rms(int type);
87
88namespace {
89
90// ---------------------------------------------------------------------------------------------------------------
91// codebook: the decoder's int16 table (round half away from zero of fp16 * 8192, as tq_cpu.cpp fill_table), SoA floats
92
93struct Codebook {
94    int16_t tab[kStates * 4];
95    alignas(64) float soa[4][kStates];
96    double rms = 1.072;   // of the weights: the first scale guess is rms(block) / this
97    explicit Codebook(bool computed) {
98        if (computed) {   // tq_computed.hpp
99            double ss = 0;
100            for (uint32_t s = 0; s < (uint32_t) kStates; ++s) {
101                strata::kernels::cpu::tq_detail::comp_state4(s, tab + 4 * s);
102                for (int j = 0; j < 4; ++j) {
103                    soa[j][s] = (float) tab[4 * s + j] * (1.0f / 8192.0f);
104                    ss += (double) soa[j][s] * soa[j][s];
105                }
106            }
107            rms = std::sqrt(ss / (4.0 * kStates));
108            return;
109        }
110        double ss = 0;
111        for (uint32_t s = 0; s < (uint32_t) kStates; ++s) {
112            const uint32_t x = s * 0x9e3779b1u;
113            const uint32_t pts[2] = {x >> 21, (x >> 10) & 2047u};
114            for (int h = 0; h < 2; ++h)
115                for (int j = 0; j < 2; ++j) {
116                    const float v = half_to_float(tq_lut_f16[2 * pts[h] + j]) * 8192.0f;
117                    const int16_t q = (int16_t) (v < 0.0f ? v - 0.5f : v + 0.5f);
118                    tab[4 * s + 2 * h + j] = q;
119                    soa[2 * h + j][s] = (float) q * (1.0f / 8192.0f);
120                    ss += (double) soa[2 * h + j][s] * soa[2 * h + j][s];
121                }
122        }
123        rms = std::sqrt(ss / (4.0 * kStates));
124    }
125};
126
127const Codebook& cb(bool computed) {
128    static const Codebook table(false), comp(true);
129    return computed ? comp : table;
130}
131
132struct Geo {
133    const Codebook* cbk = nullptr;
134    int K = 0;
135    bool t2 = false;   // TQ2_T (byte stream, the other shift direction)
136    int G = 0;         // predecessor groups
137};
138
139Geo geo_for(int type) {
140    Geo g;
141    g.cbk = &cb(type_computed(type));
142    g.K = type_kbits(type);
143    g.t2 = type == TQ2_T;
144    g.G = g.t2 ? 128 : (1 << (15 - g.K));
145    return g;
146}
147
148// group of a state as a successor / as a predecessor
149inline int gsucc(const Geo& g, uint32_t s) { return g.t2 ? (int) (s >> 8) : (int) (s & (uint32_t) (g.G - 1)); }
150inline int gpred(const Geo& g, uint32_t s) { return g.t2 ? (int) (s & 0x7f) : (int) (s >> g.K); }
151
152// weight index (0..127) of component j of processing position p
153inline int widx(const Geo& g, int p, int j) { return g.t2 ? 4 * p + j : 4 * (31 - p) + j; }
154
155struct Scratch {
156    alignas(64) float D[2][kStates];        // the two live columns of the DP
157    alignas(64) uint16_t bp[32][2048];      // per step and predecessor group: the best predecessor state
158    alignas(64) float m[2048];
159    alignas(64) int32_t am[2048];
160    alignas(64) float zero[kStates];
161};
162
163Scratch& scratch() {
164    thread_local std::unique_ptr<Scratch> s;
165    if (!s) {
166        s.reset(new Scratch);
167        std::memset(s->zero, 0, sizeof s->zero);
168        std::memset(s->m, 0, sizeof s->m);
169    }
170    return *s;
171}
172
173inline float min_range(const float* p, int n) {
174#if TQENC_AVX2
175    if (n >= 8) {
176        __m256 v = _mm256_loadu_ps(p);
177        for (int i = 8; i + 8 <= n; i += 8) v = _mm256_min_ps(v, _mm256_loadu_ps(p + i));
178        __m128 a = _mm_min_ps(_mm256_castps256_ps128(v), _mm256_extractf128_ps(v, 1));
179        a = _mm_min_ps(a, _mm_movehl_ps(a, a));
180        a = _mm_min_ss(a, _mm_shuffle_ps(a, a, 1));
181        return _mm_cvtss_f32(a);
182    }
183#endif
184    float m = p[0];
185    for (int i = 1; i < n; ++i) m = std::min(m, p[i]);
186    return m;
187}
188
189// out[i] = add[i] + sum_j h_j (t_j - cb_j[s0 + i])^2   for i in [0, n)
190inline void step_cost(const Codebook& C, float* out, const float* add, int s0, int n, const float* t, const float* h) {
191    const float *c0 = C.soa[0] + s0, *c1 = C.soa[1] + s0, *c2 = C.soa[2] + s0, *c3 = C.soa[3] + s0;
192    int i = 0;
193#if TQENC_AVX2
194    const __m256 t0 = _mm256_set1_ps(t[0]), t1 = _mm256_set1_ps(t[1]), t2 = _mm256_set1_ps(t[2]), t3 = _mm256_set1_ps(t[3]);
195    const __m256 h0 = _mm256_set1_ps(h[0]), h1 = _mm256_set1_ps(h[1]), h2 = _mm256_set1_ps(h[2]), h3 = _mm256_set1_ps(h[3]);
196    for (; i + 8 <= n; i += 8) {
197        const __m256 e0 = _mm256_sub_ps(t0, _mm256_loadu_ps(c0 + i)), e1 = _mm256_sub_ps(t1, _mm256_loadu_ps(c1 + i));
198        const __m256 e2 = _mm256_sub_ps(t2, _mm256_loadu_ps(c2 + i)), e3 = _mm256_sub_ps(t3, _mm256_loadu_ps(c3 + i));
199        __m256 a = _mm256_fmadd_ps(_mm256_mul_ps(h0, e0), e0, _mm256_loadu_ps(add + i));
200        a = _mm256_fmadd_ps(_mm256_mul_ps(h1, e1), e1, a);
201        a = _mm256_fmadd_ps(_mm256_mul_ps(h2, e2), e2, a);
202        a = _mm256_fmadd_ps(_mm256_mul_ps(h3, e3), e3, a);
203        _mm256_storeu_ps(out + i, a);
204    }
205#endif
206    for (; i < n; ++i) {
207        const float e0 = t[0] - c0[i], e1 = t[1] - c1[i], e2 = t[2] - c2[i], e3 = t[3] - c3[i];
208        out[i] = add[i] + h[0] * e0 * e0 + h[1] * e1 * e1 + h[2] * e2 * e2 + h[3] * e3 * e3;
209    }
210}
211
212// the broadcast variant: out[i] = a + cost(s0 + i)
213inline void step_cost_bc(const Codebook& C, float* out, float a, int s0, int n, const float* t, const float* h) {
214    alignas(32) float tmp[256];
215    for (int i = 0; i < n; ++i) tmp[i] = a;
216    step_cost(C, out, tmp, s0, n, t, h);
217}
218
219// min and first index of the minimum over p[0..n)
220inline float min_arg_range(const float* p, int n, int* arg) {
221    const float m = min_range(p, n);
222    int i = 0;
223#if TQENC_AVX2
224    const __m256 vm = _mm256_set1_ps(m);
225    for (; i + 8 <= n; i += 8) {
226        const int mask = _mm256_movemask_ps(_mm256_cmp_ps(_mm256_loadu_ps(p + i), vm, _CMP_EQ_OQ));
227        if (mask) { *arg = i + __builtin_ctz((unsigned) mask); return m; }
228    }
229#endif
230    for (; i < n; ++i)
231        if (p[i] == m) { *arg = i; return m; }
232    *arg = 0;
233    return m;
234}
235
236// T[p][4]: targets of processing position p (weights / d), H[p][4]: importance.  rot: the sequence is processed from
237// position rot (cyclically); fixed_c >= 0: tail-biting with the successor group of the first state and the predecessor
238// group of the last state both == fixed_c.  Writes the states by position into st[32]; returns the path cost.
239float viterbi(const Geo& g, const float (*T)[4], const float (*H)[4], int rot, int fixed_c, uint16_t* st) {
240    Scratch& sc = scratch();
241    const int K = g.K, G = g.G;
242    float* cur = sc.D[0];
243    // q = 0
244    {
245        const int p = rot & 31;
246        step_cost(*g.cbk, cur, sc.zero, 0, kStates, T[p], H[p]);
247        if (fixed_c >= 0) {
248            if (g.t2) {   // gsucc(s) = s >> 8 == c: the 256 states [c<<8, c<<8 + 256) allowed
249                for (int s = 0; s < kStates; ++s)
250                    if ((s >> 8) != fixed_c) cur[s] = kInf;
251            } else {      // s & (G-1) == c
252                for (int s = 0; s < kStates; ++s)
253                    if ((s & (G - 1)) != fixed_c) cur[s] = kInf;
254            }
255        }
256    }
257    for (int q = 1; q < 32; ++q) {
258        const float* prev = cur;
259        cur = sc.D[q & 1];
260        const int p = (rot + q) & 31;
261        float* m = sc.m;
262        uint16_t* bp = sc.bp[q];
263        if (g.t2) {
264            // m[a] = min over h of prev[a + 128 h], argmin h
265            for (int a = 0; a < 128; ++a) { m[a] = prev[a]; sc.am[a] = 0; }
266            for (int h = 1; h < 256; ++h) {
267                const float* row = prev + 128 * h;
268                int a = 0;
269#if TQENC_AVX2
270                const __m256i vh = _mm256_set1_epi32(h);
271                for (; a + 8 <= 128; a += 8) {
272                    const __m256 r = _mm256_loadu_ps(row + a), mm = _mm256_loadu_ps(m + a);
273                    const __m256 lt = _mm256_cmp_ps(r, mm, _CMP_LT_OQ);   // strictly smaller: the first minimum stays
274                    _mm256_storeu_ps(m + a, _mm256_blendv_ps(mm, r, lt));
275                    const __m256i old = _mm256_loadu_si256((const __m256i*) (sc.am + a));
276                    _mm256_storeu_si256((__m256i*) (sc.am + a), _mm256_castps_si256(_mm256_blendv_ps(
277                        _mm256_castsi256_ps(old), _mm256_castsi256_ps(vh), lt)));
278                }
279#endif
280                for (; a < 128; ++a)
281                    if (row[a] < m[a]) { m[a] = row[a]; sc.am[a] = h; }
282            }
283            for (int a = 0; a < 128; ++a) bp[a] = (uint16_t) (a + 128 * sc.am[a]);
284            for (int b = 0; b < 128; ++b) step_cost_bc(*g.cbk, cur + 256 * b, m[b], 256 * b, 256, T[p], H[p]);
285        } else {
286            const int span = 1 << K;
287            for (int a = 0; a < G; ++a) {
288                int arg;
289                m[a] = min_arg_range(prev + (size_t) a * span, span, &arg);
290                bp[a] = (uint16_t) ((a << K) + arg);
291            }
292            for (int base = 0; base < kStates; base += G) step_cost(*g.cbk, cur + base, m, base, G, T[p], H[p]);
293        }
294    }
295    // final state
296    const float* last = cur;
297    int best = -1;
298    float bc = 3e38f;
299    if (fixed_c < 0) {
300        for (int s = 0; s < kStates; ++s)
301            if (last[s] < bc) { bc = last[s]; best = s; }
302    } else if (g.t2) {
303        for (int h = 0; h < 256; ++h) {
304            const int s = fixed_c + 128 * h;
305            if (last[s] < bc) { bc = last[s]; best = s; }
306        }
307    } else {
308        for (int i = 0; i < (1 << K); ++i) {
309            const int s = (fixed_c << K) + i;
310            if (last[s] < bc) { bc = last[s]; best = s; }
311        }
312    }
313    if (best < 0 || bc >= kInf * 0.5f) return kInf;
314    uint32_t s = (uint32_t) best;
315    st[(rot + 31) & 31] = (uint16_t) s;
316    for (int q = 31; q >= 1; --q) {
317        s = sc.bp[q][gsucc(g, s)];
318        st[(rot + q - 1) & 31] = (uint16_t) s;
319    }
320    return bc;
321}
322
323// junction group of a free pass: gpred of the state at orig position 31 (== gsucc of the state at position 0)
324inline int junction_group(const Geo& g, const uint16_t* st) { return gpred(g, st[31]); }
325
326struct Search {
327    const Geo* g;
328    const Params* p;
329    float T[32][4];
330    float H[32][4];
331    uint16_t st[32];
332    int passes = 0;
333
334    // one tail-biting search at scale d (weights already divided: set_targets); returns the path cost in scaled units
335    float run() {
336        static const int rots[8] = {16, 8, 24, 12, 20, 4, 28, 0};
337        float best = kInf;
338        uint16_t tmp[32], free_st[32];
339        if (p->exact) {
340            for (int c = 0; c < g->G; ++c) {
341                const float v = viterbi(*g, T, H, 0, c, tmp);
342                ++passes;
343                if (v < best) { best = v; std::memcpy(st, tmp, sizeof tmp); }
344            }
345            return best;
346        }
347        int seen[8], ns = 0;
348        const int nc = std::max(1, std::min(p->ncand, 8));
349        for (int r = 0; r < nc; ++r) {
350            viterbi(*g, T, H, rots[r], -1, free_st);
351            ++passes;
352            const int c = junction_group(*g, free_st);
353            bool dup = false;
354            for (int i = 0; i < ns; ++i) dup |= seen[i] == c;
355            if (dup) continue;
356            seen[ns++] = c;
357            const float v = viterbi(*g, T, H, 0, c, tmp);
358            ++passes;
359            if (v < best) { best = v; std::memcpy(st, tmp, sizeof tmp); }
360        }
361        return best;
362    }
363};
364
365void pack_stream(const Geo& g, const uint16_t* st, uint8_t* qs) {
366    const int K = g.K;
367    std::memset(qs, 0, (size_t) 4 * K);
368    if (g.t2) {
369        for (int t = 0; t < 32; ++t) qs[t] = (uint8_t) (st[t] & 0xff);
370        return;
371    }
372    for (int u = 0; u < 32; ++u) {
373        const uint32_t x = st[u] & ((1u << K) - 1u);
374        for (int b = 0; b < K; ++b)
375            if ((x >> b) & 1u) qs[(u * K + b) >> 3] |= (uint8_t) (1u << ((u * K + b) & 7));
376    }
377}
378
379}  // namespace
380
381float debug_viterbi(int type, const float (*T)[4], const float (*H)[4], int rot, int fixed_c, uint16_t* st) {
382    return viterbi(geo_for(type), T, H, rot, fixed_c, st);
383}
384int debug_groups(int type) { return geo_for(type).G; }
385int debug_widx(int type, int p, int j) { return widx(geo_for(type), p, j); }
386void debug_pack(int type, const uint16_t* st, uint8_t* qs) { pack_stream(geo_for(type), st, qs); }
387
388const float* codebook_state(int type, uint32_t state) {
389    static thread_local float v[4];
390    for (int j = 0; j < 4; ++j) v[j] = cb(type_computed(type)).soa[j][state & 0x7fff];
391    return v;
392}
393
394const int16_t* codebook_table(int type) { return cb(type_computed(type)).tab; }
395double codebook_rms(int type) { return cb(type_computed(type)).rms; }
396
397const float* point_table() {
398    static float pts[4096];
399    static std::once_flag once;
400    std::call_once(once, [] {
401        for (int i = 0; i < 4096; ++i) {
402            const float x = half_to_float(tq_lut_f16[i]) * 8192.0f;
403            const int16_t q = (int16_t) (x < 0.0f ? x - 0.5f : x + 0.5f);
404            pts[i] = (float) q * (1.0f / 8192.0f);
405        }
406    });
407    return pts;
408}
409
410uint32_t block_state(int type, const uint8_t* qs, int t) {
411    const int K = type_kbits(type);
412    if (type == TQ2_T) return (((uint32_t) qs[(t + 31) & 31] << 8) | qs[t]) & 0x7fffu;
413    const int total = 32 * K;
414    uint32_t s = 0;
415    for (int i = 0; i < 15; ++i) {
416        const int b = ((31 - t) * K + i) % total;
417        s |= (uint32_t) ((qs[b >> 3] >> (b & 7)) & 1u) << i;
418    }
419    return s;
420}
421
422void decode_blocks(int type, const uint8_t* src, int64_t nblocks, float* out) {
423    const int K = type_kbits(type), bb = 2 + 4 * K;
424    for (int64_t b = 0; b < nblocks; ++b) {
425        const uint8_t* blk = src + (size_t) b * bb;
426        const uint16_t dh = (uint16_t) (blk[0] | (blk[1] << 8));
427        const float d = half_to_float(dh);
428        for (int t = 0; t < 32; ++t) {
429            const uint32_t s = block_state(type, blk + 2, t);
430            for (int j = 0; j < 4; ++j) out[b * 128 + 4 * t + j] = d * cb(type_computed(type)).soa[j][s];
431        }
432    }
433}
434
435BlockResult encode_block(int type, const float* w, const float* h, uint8_t* dst, const Params& prm) {
436    BlockResult r;
437    const Geo g = geo_for(type);
438    const int K = g.K, bb = 2 + 4 * K;
439    std::memset(dst, 0, (size_t) bb);
440    double sumw2 = 0, sumhw2 = 0, amax = 0;
441    for (int i = 0; i < 128; ++i) {
442        if (!std::isfinite(w[i]) || (h && !std::isfinite(h[i]))) { r.status = 2; r.err = NAN; return r; }
443        const double hi = h ? h[i] : 1.0;
444        sumw2 += (double) w[i] * w[i];
445        sumhw2 += hi * (double) w[i] * w[i];
446        amax = std::max(amax, (double) std::fabs(w[i]));
447    }
448    if (amax == 0.0) { r.status = 1; return r; }
449    const double rms = std::sqrt(sumw2 / 128.0);
450    // initial scale: the codebook has unit-ish rms
451    const double kCbRms = g.cbk->rms;
452    static const double mult[7] = {1.0, 0.9, 1.1, 0.8, 1.2, 0.7, 1.3};
453
454    Search se;
455    se.g = &g;
456    se.p = &prm;
457    for (int p = 0; p < 32; ++p)
458        for (int j = 0; j < 4; ++j) se.H[p][j] = h ? h[widx(g, p, j)] : 1.0f;
459
460    double best_err = 1e300;
461    uint16_t best_st[32] = {};
462    uint16_t best_d = 0;
463    bool have = false;
464
465    auto fit = [&](const uint16_t* st, uint16_t dh, double& err) {
466        // err of (st, dh): sum h (w - d cv)^2
467        const float d = half_to_float(dh);
468        double e = 0;
469        for (int p = 0; p < 32; ++p)
470            for (int j = 0; j < 4; ++j) {
471                const int wi = widx(g, p, j);
472                const float rec = d * g.cbk->soa[j][st[p]];
473                const double df = (double) w[wi] - rec;
474                e += (h ? h[wi] : 1.0) * df * df;
475            }
476        err = e;
477    };
478
479    const int tries = prm.fixed_scale ? 1 : std::max(1, std::min(prm.scale_tries, 7));
480    for (int tr = 0; tr < tries; ++tr) {
481        double dd = rms / kCbRms * mult[tr];
482        uint16_t dh = float_to_half((float) std::min(dd, 65504.0));
483        if (dh == 0) dh = 1;   // the smallest subnormal: weights below ~3e-8 are noise at this scale
484        if (prm.fixed_scale) dh = prm.fixed_scale;
485        for (int it = 0; it <= (prm.fixed_scale ? 0 : prm.iters); ++it) {
486            const float d = half_to_float(dh);
487            for (int p = 0; p < 32; ++p)
488                for (int j = 0; j < 4; ++j) se.T[p][j] = w[widx(g, p, j)] / d;
489            if (se.run() >= kInf * 0.5f) break;
490            double e;
491            fit(se.st, dh, e);
492            if (e < best_err) {
493                best_err = e;
494                best_d = dh;
495                std::memcpy(best_st, se.st, sizeof best_st);
496                have = true;
497            }
498            if (e == 0.0 || prm.fixed_scale) break;
499            // least-squares scale for this path
500            double num = 0, den = 0;
501            for (int p = 0; p < 32; ++p)
502                for (int j = 0; j < 4; ++j) {
503                    const int wi = widx(g, p, j);
504                    const double hi = h ? h[wi] : 1.0, c = g.cbk->soa[j][se.st[p]];
505                    num += hi * w[wi] * c;
506                    den += hi * c * c;
507                }
508            if (den <= 0 || num <= 0) break;
509            uint16_t nh = float_to_half((float) std::min(num / den, 65504.0));
510            if (nh == 0 || nh == dh) break;
511            double en;
512            fit(se.st, nh, en);
513            if (en < best_err) {
514                best_err = en;
515                best_d = nh;
516                std::memcpy(best_st, se.st, sizeof best_st);
517            }
518            if (en >= e) break;   // the scale step did not help this path: stop refining this start
519            dh = nh;
520        }
521        r.searches = se.passes;
522    }
523    if (!have || best_err >= sumhw2) {   // nothing beats a zero block (weights below the fp16 scale resolution)
524        std::memset(dst, 0, (size_t) bb);
525        r.status = 1;
526        r.err = sumhw2;
527        return r;
528    }
529    dst[0] = (uint8_t) (best_d & 0xff);
530    dst[1] = (uint8_t) (best_d >> 8);
531    pack_stream(g, best_st, dst + 2);
532    r.err = best_err;
533    r.scale = half_to_float(best_d);
534    r.searches = se.passes;
535    return r;
536}
537
538double encode_blocks(int type, const float* w, const float* h, int64_t nblocks, uint8_t* dst, const Params& p,
539                     int nthreads, double* err_out, int64_t* nonfinite, int64_t* zero_blocks) {
540    const int bb = block_bytes(type);
541    if (nthreads <= 0) nthreads = (int) std::max(1u, std::thread::hardware_concurrency());
542    nthreads = (int) std::min<int64_t>(nthreads, std::max<int64_t>(1, nblocks));
543    std::atomic<int64_t> next{0}, nf{0}, zb{0};
544    std::vector<double> sums((size_t) nthreads, 0.0);
545    auto work = [&](int ti) {
546        double s = 0;
547        for (;;) {
548            const int64_t b0 = next.fetch_add(4);
549            if (b0 >= nblocks) break;
550            const int64_t b1 = std::min(nblocks, b0 + 4);
551            for (int64_t b = b0; b < b1; ++b) {
552                const BlockResult r = encode_block(type, w + b * 128, h ? h + b * 128 : nullptr, dst + (size_t) b * bb, p);
553                if (r.status == 2) { nf.fetch_add(1); }
554                else s += r.err;
555                if (r.status == 1) zb.fetch_add(1);
556                if (err_out) err_out[b] = r.err;
557            }
558        }
559        sums[ti] = s;
560    };
561    std::vector<std::thread> th;
562    for (int i = 1; i < nthreads; ++i) th.emplace_back(work, i);
563    work(0);
564    for (auto& t : th) t.join();
565    if (nonfinite) *nonfinite = nf.load();
566    if (zero_blocks) *zero_blocks = zb.load();
567    double tot = 0;
568    for (double s : sums) tot += s;
569    return tot;
570}
571
572}  // namespace tqenc
573
574// ---------------------------------------------------------------------------------------------------------------
575// C API for the Python wrapper (tools/tqenc.py, ctypes)
576extern "C" {
577#if defined(_WIN32)
578#define TQE_EXPORT __declspec(dllexport)
579#else
580#define TQE_EXPORT __attribute__((visibility("default")))
581#endif
582TQE_EXPORT int tqe_block_bytes(int type) { return tqenc::block_bytes(type); }
583TQE_EXPORT int tqe_kbits(int type) { return tqenc::type_kbits(type); }
584TQE_EXPORT void tqe_decode(int type, const uint8_t* src, int64_t nblocks, float* out) {
585    tqenc::decode_blocks(type, src, nblocks, out);
586}
587// returns the summed block error; stats[0] = nonfinite blocks, stats[1] = zero blocks
588TQE_EXPORT double tqe_encode(int type, const float* w, const float* h, int64_t nblocks, uint8_t* dst, int iters,
589                             int ncand, int exact, int scale_tries, int nthreads, double* err_out, int64_t* stats) {
590    tqenc::Params p;
591    p.iters = iters;
592    p.ncand = ncand;
593    p.exact = exact;
594    p.scale_tries = scale_tries;
595    int64_t nf = 0, zb = 0;
596    const double e = tqenc::encode_blocks(type, w, h, nblocks, dst, p, nthreads, err_out, &nf, &zb);
597    if (stats) { stats[0] = nf; stats[1] = zb; }
598    return e;
599}
600TQE_EXPORT const int16_t* tqe_table(int type) { return tqenc::codebook_table(type); }
601}