okami.mom/strata

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

Niko1221Merge f-027-gh-eng: GitHub engine items for 0.2.76ca60e9a0

main
12.3 KiB308 linesraw
1// src/kernels/cpu/tq_cpu.cpp - see include/strata/kernels/cpu/tq_cpu.hpp: the state table, the scalar reference
2// kernel, the activation unpacking and the run-time ISA choice.  Compiled for the baseline x86-64 (no AVX), so
3// everything here runs on any CPU; the AVX2 / AVX-512 kernels are in their own translation units.
4#include "strata/kernels/cpu/tq_cpu.hpp"
5#include "strata/kernels/cpu/expert_layout.hpp"
6
7#include "tq_states.hpp"
8#include "tq_computed.hpp"
9#include "ggml-common-tq.h"
10
11#include <cmath>
12#include <cstdlib>
13#include <cstring>
14#include <memory>
15#include <mutex>
16#include <string>
17#include <vector>
18
19// The AVX2 / AVX-512 units (tq_avx2.cpp, tq_avx512.cpp) exist on x86-64 builds only; anything else (arm64: the Metal build)
20// runs the scalar kernel.
21#if defined(__x86_64__) || defined(_M_X64)
22#define STRATA_TQ_X86 1
23#endif
24
25namespace strata::kernels::cpu {
26namespace {
27
28alignas(64) int16_t g_table[(tq_detail::kTqStateMask + 1) * 4];
29alignas(64) int16_t g_table_c[(tq_detail::kTqStateMask + 1) * 4];
30
31void fill_table() {
32    for (uint32_t s = 0; s <= tq_detail::kTqStateMask; ++s) {
33        const uint32_t x = s * 0x9e3779b1u;
34        const uint32_t pts[2] = {x >> 21, (x >> 10) & 2047u};   // the hash's two codebook points
35        for (int h = 0; h < 2; ++h)
36            for (int j = 0; j < 2; ++j) {
37                // fp16 * 2^13 is exact in float; round half away from zero, as the fork's ggml-cpu table does
38                const float v = tq_detail::tq_half_to_float(tq_lut_f16[2 * pts[h] + j]) * 8192.0f;
39                g_table[4 * s + 2 * h + j] = (int16_t) (v < 0.0f ? v - 0.5f : v + 0.5f);
40            }
41    }
42}
43
44void fill_table_computed() {
45    for (uint32_t s = 0; s <= tq_detail::kTqStateMask; ++s) tq_detail::comp_state4(s, g_table_c + 4 * s);
46}
47
48int env_isa_cap() {
49    const char* e = std::getenv("STRATA_TQ_ISA");
50    if (e == nullptr || *e == 0) return 2;
51    const std::string v(e);
52    if (v == "scalar") return 0;
53    if (v == "avx2") return 1;
54    return 2;
55}
56
57template <int KB>
58void rows_scalar_t(const int16_t* tab, const uint8_t* w, size_t row_bytes, int n, const tq_detail::TqAct* const* a, int nt,
59                   float* const* out, int r0, int r1) {
60    const int nb = n / 128;
61    constexpr size_t bsz = 2 + 4 * KB;
62    for (int r = r0; r < r1; ++r) {
63        const uint8_t* x = w + (size_t) r * row_bytes;
64        float acc[kTqMaxTokens][4] = {};
65        for (int i = 0; i < nb; ++i) {
66            const uint8_t* blk = x + (size_t) i * bsz;
67            const float dx = tq_detail::tq_half_to_float(tq_detail::tq_ld16(blk));
68            uint32_t st[32];
69            tq_detail::tq_states<KB>(blk + 2, st);
70            for (int t = 0; t < nt; ++t) {
71                const int16_t* q = a[t]->q + 128 * i;
72                for (int k = 0; k < 4; ++k) {
73                    int32_t s = 0;
74                    for (int j = 0; j < 8; ++j) {
75                        const int16_t* wv = tab + 4 * st[8 * k + j];
76                        const int16_t* qv = q + 32 * k + 4 * j;
77                        s += wv[0] * qv[0] + wv[1] * qv[1] + wv[2] * qv[2] + wv[3] * qv[3];
78                    }
79                    const float sc = dx * a[t]->d[4 * i + k];
80                    acc[t][k] = std::fma((float) s, sc, acc[t][k]);
81                }
82            }
83        }
84        for (int t = 0; t < nt; ++t)
85            out[t][r] = ((acc[t][0] + acc[t][1]) + (acc[t][2] + acc[t][3])) * (1.0f / 8192.0f);
86    }
87}
88
89// TQP (Gyro-L): 64 pair-trellis steps of 2 weights; a 32-value group is 16 steps.  The table row holds the
90// TQ2_T state's two pairs; TQP uses the first pair only (weight 2t+j = lut[2*hyb(2*s)+j]).
91template <int KB>
92void rows_scalar_tqp_t(const uint8_t* w, size_t row_bytes, int n, const tq_detail::TqAct* const* a, int nt,
93                       float* const* out, int r0, int r1) {
94    const int nb = n / 128;
95    constexpr size_t bsz = 2 + 8 * KB;
96    const int16_t* tab = tq_state_table();
97    for (int r = r0; r < r1; ++r) {
98        const uint8_t* x = w + (size_t) r * row_bytes;
99        float acc[kTqMaxTokens][4] = {};
100        for (int i = 0; i < nb; ++i) {
101            const uint8_t* blk = x + (size_t) i * bsz;
102            const float dx = tq_detail::tq_half_to_float(tq_detail::tq_ld16(blk));
103            uint32_t st[64];
104            tq_detail::tq_states_tqp<KB>(blk + 2, st);
105            for (int t = 0; t < nt; ++t) {
106                const int16_t* q = a[t]->q + 128 * i;
107                for (int k = 0; k < 4; ++k) {
108                    int32_t s = 0;
109                    for (int j = 0; j < 16; ++j) {   // step 16k+j: two weights
110                        const int16_t* wv = tab + 4 * st[16 * k + j];
111                        const int16_t* qv = q + 32 * k + 2 * j;
112                        s += wv[0] * qv[0] + wv[1] * qv[1];
113                    }
114                    const float sc = dx * a[t]->d[4 * i + k];
115                    acc[t][k] = std::fma((float) s, sc, acc[t][k]);
116                }
117            }
118        }
119        for (int t = 0; t < nt; ++t)
120            out[t][r] = ((acc[t][0] + acc[t][1]) + (acc[t][2] + acc[t][3])) * (1.0f / 8192.0f);
121    }
122}
123
124}  // namespace
125
126const int16_t* tq_state_table() {
127    static std::once_flag once;
128    std::call_once(once, fill_table);
129    return g_table;
130}
131
132const int16_t* tq_state_table_computed() {
133    static std::once_flag once;
134    std::call_once(once, fill_table_computed);
135    return g_table_c;
136}
137
138const int16_t* tq_state_table_for(int t) { return (t == kTqTypeK5X || t == kTqTypeK4X) ? tq_state_table_computed() : tq_state_table(); }
139
140bool tq_supported(int t) noexcept {
141    return t == 144 || t == 145 || t == 146 || t == 147 || t == 148 || t == 149 ||
142           t == kTqTypeK5X || t == kTqTypeK4X || t == kTqTypeK5T || t == kTqTypeK4T;
143}
144
145int tq_kbits(int t) noexcept {
146    if (t == 148) return 6;                                   // TQP6
147    if (t == 144) return 8;
148    if (t == 146 || t == 149) return 7;
149    if (t == 145) return 6;
150    if (t == 147 || t == kTqTypeK5X || t == kTqTypeK5T) return 5;
151    if (t == kTqTypeK4X || t == kTqTypeK4T) return 4;
152    return 0;
153}
154
155bool tq_isa_ok(TqIsa isa) {
156#if defined(STRATA_TQ_X86)
157    switch (isa) {
158        case TqIsa::avx512: return cpu_avx512_ok();
159        case TqIsa::avx2: return cpu_avx2_ok();
160        default: return true;
161    }
162#else
163    return isa == TqIsa::scalar;   // arm64 (the Metal build): the AVX units are not compiled, the scalar kernel runs
164#endif
165}
166
167TqIsa tq_isa() {
168    static const TqIsa isa = [] {
169        const int cap = env_isa_cap();
170        if (cap >= 2 && tq_isa_ok(TqIsa::avx512)) return TqIsa::avx512;
171        if (cap >= 1 && tq_isa_ok(TqIsa::avx2)) return TqIsa::avx2;
172        return TqIsa::scalar;
173    }();
174    return isa;
175}
176
177bool tq_kernels_enabled() {
178    static const bool on = [] {
179        if (const char* e = std::getenv("STRATA_NO_TQ_KERNELS"); e != nullptr && std::atoi(e) != 0) return false;
180        // Every CPU runs them: the scalar kernel (baseline x86-64) where there is no AVX2.  A ggml built from upstream
181        // has no vec_dot for the trellis types to fall back to, so a CPU without AVX2 must not be sent there.
182        return true;
183    }();
184    return on;
185}
186
187const char* tq_isa_name(TqIsa isa) {
188    return isa == TqIsa::avx512 ? "avx512" : isa == TqIsa::avx2 ? "avx2" : "scalar";
189}
190
191namespace tq_detail {
192
193void unpack_act(const void* q8_0, int n, TqAct& a) {
194    const uint8_t* p = (const uint8_t*) q8_0;
195    for (int b = 0; b < n / 32; ++b, p += 34) {   // block_q8_0: fp16 d, 32 x int8
196        a.d[b] = tq_half_to_float(tq_ld16(p));
197        const int8_t* q = (const int8_t*) (p + 2);
198        for (int j = 0; j < 32; ++j) a.q[32 * b + j] = q[j];
199    }
200}
201
202void tq_rows_scalar(int kb, const int16_t* tab, const uint8_t* w, size_t row_bytes, int n, const TqAct* const* a, int nt,
203                    float* const* out, int r0, int r1) {
204    if (kb == 8) rows_scalar_t<8>(tab, w, row_bytes, n, a, nt, out, r0, r1);
205    else if (kb == 6) rows_scalar_t<6>(tab, w, row_bytes, n, a, nt, out, r0, r1);
206    else if (kb == 5) rows_scalar_t<5>(tab, w, row_bytes, n, a, nt, out, r0, r1);   // experimental TQK5X / TQK5T
207    else if (kb == 4) rows_scalar_t<4>(tab, w, row_bytes, n, a, nt, out, r0, r1);   // experimental TQK4X / TQK4T
208    else rows_scalar_t<7>(tab, w, row_bytes, n, a, nt, out, r0, r1);
209}
210
211void tq_rows_scalar_tqp(int kb, const uint8_t* w, size_t row_bytes, int n, const TqAct* const* a, int nt,
212                        float* const* out, int r0, int r1) {
213    if (kb == 5) rows_scalar_tqp_t<5>(w, row_bytes, n, a, nt, out, r0, r1);
214    else if (kb == 6) rows_scalar_tqp_t<6>(w, row_bytes, n, a, nt, out, r0, r1);
215    else rows_scalar_tqp_t<7>(w, row_bytes, n, a, nt, out, r0, r1);
216}
217
218}  // namespace tq_detail
219
220namespace {
221
222// the activations of one call, unpacked once for all its rows
223struct ActSet {
224    tq_detail::TqAct act[kTqMaxTokens];
225    const tq_detail::TqAct* ptr[kTqMaxTokens];
226};
227
228ActSet& unpack_all(const void* const* act, int n, int nt) {
229    thread_local std::unique_ptr<ActSet> set;
230    if (!set) set.reset(new ActSet);
231    for (int t = 0; t < nt; ++t) {
232        tq_detail::unpack_act(act[t], n, set->act[t]);
233        set->ptr[t] = &set->act[t];
234    }
235    return *set;
236}
237
238void rows_on(TqIsa isa, int kb, const int16_t* tab, const uint8_t* w, size_t row_bytes, int n,
239             const tq_detail::TqAct* const* a, int nt, float* const* out, int r0, int r1) {
240    switch (isa) {
241#if defined(STRATA_TQ_X86)
242        case TqIsa::avx512: tq_detail::tq_rows_avx512(kb, tab, w, row_bytes, n, a, nt, out, r0, r1); break;
243        case TqIsa::avx2: tq_detail::tq_rows_avx2(kb, tab, w, row_bytes, n, a, nt, out, r0, r1); break;
244#endif
245        default: tq_detail::tq_rows_scalar(kb, tab, w, row_bytes, n, a, nt, out, r0, r1); break;
246    }
247}
248
249// The pair layout (types 147-149): AVX2 and AVX-512 both take the AVX2 pair kernel; scalar, and any build without the
250// x86 units (arm64: the Metal build), the scalar one.
251void rows_pair_on(TqIsa isa, int kb, const uint8_t* w, size_t row_bytes, int n, const tq_detail::TqAct* const* a, int nt,
252                  float* const* out, int r0, int r1) {
253#if defined(STRATA_TQ_X86)
254    if (isa != TqIsa::scalar) {
255        tq_detail::tq_rows_avx2_tqp(kb, w, row_bytes, n, a, nt, out, r0, r1);
256        return;
257    }
258#else
259    (void) isa;
260#endif
261    tq_detail::tq_rows_scalar_tqp(kb, w, row_bytes, n, a, nt, out, r0, r1);
262}
263
264}  // namespace
265
266void tq_rows(TqIsa isa, int ggml_type, const uint8_t* w, size_t row_bytes, int n, const void* const* act, int nt,
267             float* const* out, int r0, int r1) {
268    if (!tq_isa_ok(isa)) std::abort();   // a caller bug: asked for an ISA this CPU does not have
269    const int16_t* tab = tq_state_table_for(ggml_type);
270    const ActSet& s = unpack_all(act, n, nt);
271    if (ggml_type >= 147 && ggml_type <= 149) {   // Gyro-L pair trellis: the AVX2 pair kernel (scalar is the reference)
272        const int kb = tq_kbits(ggml_type);
273        rows_pair_on(isa, kb, w, row_bytes, n, s.ptr, nt, out, r0, r1);
274        return;
275    }
276    rows_on(isa, tq_kbits(ggml_type), tab, w, row_bytes, n, s.ptr, nt, out, r0, r1);
277}
278
279void tq_gu_rows(TqIsa isa, int ggml_type, const uint8_t* blob, size_t gu_row, size_t up_off, int n,
280                const void* const* act, int nt, float* const* ff, int r0, int r1) {
281    if (!tq_isa_ok(isa)) std::abort();
282    const int16_t* tab = tq_state_table_for(ggml_type);
283    const ActSet& s = unpack_all(act, n, nt);
284    thread_local std::vector<float> gbuf, ubuf;
285    const size_t nr = (size_t) r1;   // row r of token t at [t * r1 + r]
286    if (gbuf.size() < nr * kTqMaxTokens) { gbuf.resize(nr * kTqMaxTokens); ubuf.resize(nr * kTqMaxTokens); }
287    float* gp[kTqMaxTokens];
288    float* up[kTqMaxTokens];
289    for (int t = 0; t < nt; ++t) {
290        gp[t] = gbuf.data() + (size_t) t * nr;
291        up[t] = ubuf.data() + (size_t) t * nr;
292    }
293    const int kb = tq_kbits(ggml_type);
294    const bool pair = ggml_type >= 147 && ggml_type <= 149;   // Gyro-L pair trellis: its own kernels
295    auto rows = [&](const uint8_t* w, float* const* o) {
296        if (pair) rows_pair_on(isa, kb, w, gu_row, n, s.ptr, nt, o, r0, r1);
297        else rows_on(isa, kb, tab, w, gu_row, n, s.ptr, nt, o, r0, r1);
298    };
299    rows(blob, gp);
300    rows(blob + up_off, up);
301    for (int t = 0; t < nt; ++t)
302        for (int r = r0; r < r1; ++r) {
303            const float g = gp[t][r], u = up[t][r];
304            ff[t][r] = (g / (1.f + std::exp(-g))) * u;   // native_gu_rows' SwiGLU expression
305        }
306}
307
308}  // namespace strata::kernels::cpu