File size: 25,674 Bytes
68888be
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
// CPU reference backend, written for clarity first: the CUDA backend is checked
// against it, and it is the fallback without a GPU. Dense weights are expanded to
// float32 at load; bit-plane weights stay packed and are decoded a row at a time.
#include <algorithm>
#include <atomic>
#include <cmath>
#include <cstring>
#include <vector>

#include "common/base.h"
#include "common/numeric.h"
#include "common/threads.h"
#include "gpu/backend.h"
#include "io/os_info.h"

namespace hk {
namespace {

struct CpuTensor : Tensor {
    std::vector<float> d;
    float* row(int r) { return d.data() + (size_t)r * (size_t)cols; }
    const float* row(int r) const { return d.data() + (size_t)r * (size_t)cols; }
};

struct CpuWeight : Weight {
    std::vector<float> dense;                // F32 / BF16 / F16, expanded
    std::vector<uint8_t> scales, planes[4];  // PLANES, as stored
    PlanesView view() const {
        PlanesView v;
        v.scales = scales.data();
        for (int p = 0; p < desc.planes.nplanes; ++p) v.planes[p] = planes[p].data();
        return v;
    }
    int64_t bytes() const {
        int64_t n = (int64_t)dense.size() * 4 + (int64_t)scales.size();
        for (int p = 0; p < 4; ++p) n += (int64_t)planes[p].size();
        return n;
    }
    // row r as floats: a pointer into dense storage, or decoded into tmp
    const float* row(int r, std::vector<float>& tmp) const {
        if (desc.fmt != WFmt::PLANES) return dense.data() + (size_t)r * (size_t)desc.cols;
        tmp.resize((size_t)desc.cols);
        planes_decode_row(desc.planes, view(), r, tmp.data());
        return tmp.data();
    }
};

inline const CpuTensor* T(const Tensor* t) { return static_cast<const CpuTensor*>(t); }
inline CpuTensor* T(Tensor* t) { return static_cast<CpuTensor*>(t); }
inline const CpuWeight* W(const Weight* w) { return static_cast<const CpuWeight*>(w); }

// eight partial sums, so the compiler can vectorize without -ffast-math
inline float dot(const float* a, const float* b, int n) {
    float acc[8] = {0, 0, 0, 0, 0, 0, 0, 0};
    int i = 0;
    for (; i + 8 <= n; i += 8)
        for (int j = 0; j < 8; ++j) acc[j] += a[i + j] * b[i + j];
    float s = ((acc[0] + acc[4]) + (acc[1] + acc[5])) + ((acc[2] + acc[6]) + (acc[3] + acc[7]));
    for (; i < n; ++i) s += a[i] * b[i];
    return s;
}

inline void axpy_row(float* y, const float* x, float a, int n) {
    for (int i = 0; i < n; ++i) y[i] += a * x[i];
}

class CpuBackend : public Backend {
   public:
    const char* name() const override { return "cpu"; }
    bool is_gpu() const override { return false; }
    std::string device_name() const override { return strfmt("CPU, %d threads", ThreadPool::global().size()); }
    int64_t mem_total() const override { return system_ram_bytes(); }
    int64_t mem_used() const override { return used_.load(); }
    int64_t mem_free() const override { return std::max<int64_t>(0, system_ram_bytes() - used_.load()); }
    int64_t dense_bytes(int64_t values, int) const override { return values * 4; }   // everything is float32 here

    Tensor* alloc(int rows, int cols) override {
        HK_CHECK(rows >= 0 && cols >= 0, "bad tensor shape %d x %d", rows, cols);
        auto* t = new CpuTensor();
        t->rows = rows;
        t->cols = cols;
        t->d.assign((size_t)rows * (size_t)cols, 0.0f);
        used_ += (int64_t)t->d.size() * 4;
        return t;
    }
    void release(Tensor* t) override {
        if (!t) return;
        used_ -= (int64_t)T(t)->d.size() * 4;
        delete t;
    }
    void upload(Tensor* t, int row0, int nrows, const float* src) override {
        check_rows(t, row0, nrows);
        memcpy(T(t)->row(row0), src, (size_t)nrows * (size_t)t->cols * 4);
    }
    void download(const Tensor* t, int row0, int nrows, float* dst) override {
        check_rows(t, row0, nrows);
        memcpy(dst, T(t)->row(row0), (size_t)nrows * (size_t)t->cols * 4);
    }
    void copy(Tensor* dst, int drow, int dcol, const Tensor* src, int srow, int scol, int nrows, int ncols) override {
        HK_CHECK(drow >= 0 && dcol >= 0 && srow >= 0 && scol >= 0 && drow + nrows <= dst->rows && dcol + ncols <= dst->cols &&
                     srow + nrows <= src->rows && scol + ncols <= src->cols,
                 "copy block out of range");
        for (int r = 0; r < nrows; ++r)
            memmove(T(dst)->row(drow + r) + dcol, T(src)->row(srow + r) + scol, (size_t)ncols * 4);
    }
    void fill(Tensor* t, float v) override { std::fill(T(t)->d.begin(), T(t)->d.end(), v); }

    Weight* load(const WeightDesc& d, const WeightData& data) override {
        auto* w = new CpuWeight();
        w->desc = d;
        const size_t n = (size_t)d.rows * (size_t)d.cols;
        switch (d.fmt) {
            case WFmt::F32:
                w->dense.resize(n);
                memcpy(w->dense.data(), data.dense, n * 4);
                break;
            case WFmt::BF16:
                w->dense.resize(n);
                parallel_for((int64_t)n, 1 << 16, [&](int64_t b, int64_t e) {
                    for (int64_t i = b; i < e; ++i) w->dense[(size_t)i] = bf16_to_f32(load_le16(data.dense + 2 * i));
                });
                break;
            case WFmt::F16:
                w->dense.resize(n);
                parallel_for((int64_t)n, 1 << 16, [&](int64_t b, int64_t e) {
                    for (int64_t i = b; i < e; ++i) w->dense[(size_t)i] = f16_to_f32(load_le16(data.dense + 2 * i));
                });
                break;
            case WFmt::PLANES: {
                const PlanesDesc& p = d.planes;
                HK_CHECK(p.rows == d.rows && p.cols == d.cols, "planes descriptor does not match the weight shape");
                HK_CHECK(p.cols % 32 == 0 && p.group % 32 == 0 && p.cols % p.group == 0, "planes weight %d x %d: bad grouping",
                         p.rows, p.cols);
                w->scales.assign(data.planes.scales, data.planes.scales + p.scale_bytes());
                for (int i = 0; i < p.nplanes; ++i)
                    w->planes[i].assign(data.planes.planes[i], data.planes.planes[i] + p.plane_bytes());
                break;
            }
        }
        used_ += w->bytes();
        return w;
    }
    void unload(Weight* w) override {
        if (!w) return;
        used_ -= W(w)->bytes();
        delete w;
    }

    void linear(const Weight* Wt, const Tensor* X, Tensor* Y, float alpha, bool accumulate) override {
        const CpuWeight* w = W(Wt);
        const int rows = w->desc.rows, cols = w->desc.cols, n = X->rows;
        HK_CHECK(X->cols == cols && Y->cols == rows && Y->rows == n, "linear: shapes X %dx%d, W %dx%d, Y %dx%d", X->rows,
                 X->cols, rows, cols, Y->rows, Y->cols);
        const CpuTensor* x = T(X);
        CpuTensor* y = T(Y);
        // one weight row at a time: decode once, use it for every input row
        int64_t grain = std::max<int64_t>(1, (int64_t)(1 << 18) / std::max<int64_t>(1, (int64_t)cols * n));
        parallel_for(rows, grain, [&](int64_t b, int64_t e) {
            std::vector<float> tmp;
            for (int64_t o = b; o < e; ++o) {
                const float* wr = w->row((int)o, tmp);
                for (int t = 0; t < n; ++t) {
                    float v = alpha * dot(wr, x->row(t), cols);
                    float* dst = y->row(t) + o;
                    *dst = accumulate ? *dst + v : v;
                }
            }
        });
    }

    void gather(const Weight* Wt, const int32_t* ids, int n, Tensor* Y) override {
        const CpuWeight* w = W(Wt);
        HK_CHECK(Y->rows >= n && Y->cols == w->desc.cols, "gather: output shape mismatch");
        std::vector<float> tmp;
        for (int i = 0; i < n; ++i) {
            HK_CHECK(ids[i] >= 0 && ids[i] < w->desc.rows, "gather: row %d out of range", ids[i]);
            memcpy(T(Y)->row(i), w->row(ids[i], tmp), (size_t)w->desc.cols * 4);
        }
    }

    void gemm(const Tensor* A, bool ta, const Tensor* B, bool tb, float alpha, float beta, Tensor* C) override {
        const CpuTensor *a = T(A), *b = T(B);
        CpuTensor* c = T(C);
        const int m = ta ? a->cols : a->rows, k = ta ? a->rows : a->cols;
        const int kb = tb ? b->cols : b->rows, n = tb ? b->rows : b->cols;
        HK_CHECK(k == kb && c->rows == m && c->cols == n, "gemm: shape mismatch (%d x %d) * (%d x %d) -> %d x %d", m, k, kb, n,
                 c->rows, c->cols);
        // small matrices: plain loops with an explicit transposed copy
        std::vector<float> at, bt;
        const float* ap = a->d.data();
        if (ta) {  // make A row-major [m, k]
            at.resize((size_t)m * (size_t)k);
            for (int i = 0; i < m; ++i)
                for (int j = 0; j < k; ++j) at[(size_t)i * k + j] = a->d[(size_t)j * a->cols + i];
            ap = at.data();
        }
        // B^T as [n, k] rows, so each output is a dot product
        bt.resize((size_t)n * (size_t)k);
        for (int j = 0; j < n; ++j)
            for (int l = 0; l < k; ++l) bt[(size_t)j * k + l] = tb ? b->d[(size_t)j * b->cols + l] : b->d[(size_t)l * b->cols + j];
        parallel_for(m, std::max<int64_t>(1, (1 << 16) / std::max(1, n * k)), [&](int64_t r0, int64_t r1) {
            for (int64_t i = r0; i < r1; ++i)
                for (int j = 0; j < n; ++j) {
                    float v = alpha * dot(ap + (size_t)i * k, bt.data() + (size_t)j * k, k);
                    float* dst = c->row((int)i) + j;
                    *dst = beta == 0.0f ? v : beta * *dst + v;
                }
        });
    }

    void rmsnorm(const Tensor* X, const Weight* wt, float eps, int group, Tensor* Y) override {
        const CpuWeight* w = W(wt);
        HK_CHECK(X->cols % group == 0 && (int)w->dense.size() >= group && Y->rows == X->rows && Y->cols == X->cols,
                 "rmsnorm: shape mismatch (cols %d, group %d, weight %zu)", X->cols, group, w->dense.size());
        const float* g = w->dense.data();
        parallel_for(X->rows, 16, [&](int64_t b, int64_t e) {
            for (int64_t r = b; r < e; ++r) {
                const float* x = T(X)->row((int)r);
                float* y = T(Y)->row((int)r);
                for (int c0 = 0; c0 < X->cols; c0 += group) {
                    double ss = 0;
                    for (int j = 0; j < group; ++j) ss += (double)x[c0 + j] * x[c0 + j];
                    float inv = 1.0f / std::sqrt((float)(ss / group) + eps);
                    for (int j = 0; j < group; ++j) y[c0 + j] = x[c0 + j] * inv * g[j];
                }
            }
        });
    }

    void layernorm(const Tensor* X, const Weight* wt, const Weight* bt, float eps, Tensor* Y) override {
        const int n = X->cols;
        HK_CHECK((int)W(wt)->dense.size() >= n && (int)W(bt)->dense.size() >= n && Y->rows == X->rows && Y->cols == n,
                 "layernorm: shape mismatch");
        const float* g = W(wt)->dense.data();
        const float* b = W(bt)->dense.data();
        for (int r = 0; r < X->rows; ++r) {
            const float* x = T(X)->row(r);
            float* y = T(Y)->row(r);
            double mean = 0;
            for (int j = 0; j < n; ++j) mean += x[j];
            mean /= n;
            double var = 0;
            for (int j = 0; j < n; ++j) var += (x[j] - mean) * (x[j] - mean);
            var /= n;
            float inv = 1.0f / std::sqrt((float)var + eps);
            for (int j = 0; j < n; ++j) y[j] = (float)(x[j] - mean) * inv * g[j] + b[j];
        }
    }

    void axpy(Tensor* Y, const Tensor* X, float a) override {
        HK_CHECK(Y->rows == X->rows && Y->cols == X->cols, "axpy: shape mismatch");
        axpy_row(T(Y)->d.data(), T(X)->d.data(), a, (int)T(Y)->d.size());
    }

    void mul_sigmoid(Tensor* Y, const Tensor* G) override {
        HK_CHECK(Y->rows == G->rows && Y->cols == G->cols, "mul_sigmoid: shape mismatch");
        float* y = T(Y)->d.data();
        const float* g = T(G)->d.data();
        for (size_t i = 0; i < T(Y)->d.size(); ++i) y[i] *= sigmoidf(g[i]);
    }

    void glu(const Tensor* G, const Tensor* U, const Act& act, Tensor* Y) override {
        HK_CHECK(G->rows == U->rows && G->cols == U->cols && Y->rows == G->rows && Y->cols == G->cols, "glu: shape mismatch");
        const float* g = T(G)->d.data();
        const float* u = T(U)->d.data();
        float* y = T(Y)->d.data();
        const size_t n = T(G)->d.size();
        if (act.kind == ActKind::SILU) {
            for (size_t i = 0; i < n; ++i) y[i] = g[i] * sigmoidf(g[i]) * u[i];
        } else {
            for (size_t i = 0; i < n; ++i) {
                float a = act.beta * std::tanh(g[i] / act.beta) * sigmoidf(g[i]);
                float b = act.lbeta > 0 ? act.lbeta * std::tanh(u[i] / act.lbeta) : u[i];
                y[i] = a * b;
            }
        }
    }

    void take_rows(const Tensor* X, const int32_t* rows, int n, Tensor* Y) override {
        HK_CHECK(Y->rows >= n && Y->cols == X->cols, "take_rows: shape mismatch");
        for (int i = 0; i < n; ++i) {
            HK_CHECK(rows[i] >= 0 && rows[i] < X->rows, "take_rows: row out of range");
            memcpy(T(Y)->row(i), T(X)->row(rows[i]), (size_t)X->cols * 4);
        }
    }
    void scatter_add_rows(Tensor* Y, const int32_t* rows, const float* coef, int n, const Tensor* X) override {
        HK_CHECK(X->rows >= n && Y->cols == X->cols, "scatter_add_rows: shape mismatch");
        for (int i = 0; i < n; ++i) {
            HK_CHECK(rows[i] >= 0 && rows[i] < Y->rows, "scatter_add_rows: row out of range");
            axpy_row(T(Y)->row(rows[i]), T(X)->row(i), coef[i], X->cols);
        }
    }

    void kda_conv(const Tensor* P, const Weight* wt, Tensor* ring, Tensor* Y) override {
        const CpuWeight* w = W(wt);
        const int C = P->cols, K = w->desc.cols, n = P->rows;
        HK_CHECK(w->desc.rows == C && ring->rows == K - 1 && ring->cols == C && Y->rows == n && Y->cols == C,
                 "kda_conv: shape mismatch");
        const CpuTensor* p = T(P);
        CpuTensor* rg = T(ring);
        CpuTensor* y = T(Y);
        // seq(i) for i in [0, K-1) is the ring, then the new rows
        auto seq = [&](int i) -> const float* { return i < K - 1 ? rg->row(i) : p->row(i - (K - 1)); };
        const float* k = w->dense.data();
        for (int t = 0; t < n; ++t) {
            float* out = y->row(t);
            for (int c = 0; c < C; ++c) out[c] = 0;
            for (int i = 0; i < K; ++i) {
                const float* s = seq(t + i);
                for (int c = 0; c < C; ++c) out[c] += k[(size_t)c * K + i] * s[c];
            }
            for (int c = 0; c < C; ++c) out[c] = out[c] * sigmoidf(out[c]);
        }
        // new ring: the last K-1 rows of the sequence
        std::vector<float> nr((size_t)(K - 1) * C);
        for (int i = 0; i < K - 1; ++i) memcpy(nr.data() + (size_t)i * C, seq(n + i), (size_t)C * 4);
        memcpy(rg->d.data(), nr.data(), nr.size() * 4);
    }

    void kda_gate(const Tensor* Z, const Weight* A_log, const Weight* dt_bias, int heads, bool bounded, float lb,
                  Tensor* G) override {
        const int HD = Z->cols, D = HD / heads;
        HK_CHECK(HD % heads == 0 && (int)W(A_log)->dense.size() >= heads && (int)W(dt_bias)->dense.size() >= HD &&
                     G->rows == Z->rows && G->cols == HD,
                 "kda_gate: shape mismatch");
        const float* a = W(A_log)->dense.data();
        const float* bias = W(dt_bias)->dense.data();
        for (int t = 0; t < Z->rows; ++t) {
            const float* z = T(Z)->row(t);
            float* g = T(G)->row(t);
            for (int h = 0; h < heads; ++h) {
                float ea = std::exp(a[h]);
                for (int k = 0; k < D; ++k) {
                    float v = z[h * D + k] + bias[h * D + k];
                    g[h * D + k] = bounded ? lb * sigmoidf(ea * v) : -ea * softplusf(v);
                }
            }
        }
    }

    void kda_recur(const Tensor* Q, const Tensor* K, const Tensor* V, const Tensor* G, const Tensor* Blogit, int heads,
                   Tensor* S, Tensor* O) override {
        const int n = Q->rows, HD = Q->cols, D = HD / heads;
        HK_CHECK(HD % heads == 0 && K->cols == HD && V->cols == HD && G->cols == HD && Blogit->cols == heads && S->rows == HD &&
                     S->cols == D && O->rows == n && O->cols == HD && K->rows == n && V->rows == n && G->rows == n &&
                     Blogit->rows == n,
                 "kda_recur: shape mismatch");
        const float qscale = 1.0f / std::sqrt((float)D);
        parallel_for(heads, 1, [&](int64_t h0, int64_t h1) {
            std::vector<float> qn((size_t)D), kn((size_t)D), u((size_t)D), dlt((size_t)D);
            for (int64_t h = h0; h < h1; ++h) {
                float* s = T(S)->row((int)h * D);  // D rows of D
                for (int t = 0; t < n; ++t) {
                    const float* q = T(Q)->row(t) + h * D;
                    const float* k = T(K)->row(t) + h * D;
                    const float* v = T(V)->row(t) + h * D;
                    const float* g = T(G)->row(t) + h * D;
                    float beta = sigmoidf(T(Blogit)->row(t)[h]);
                    // F.normalize: x / max(||x||, 1e-12)
                    float qq = std::sqrt(dot(q, q, D)), kk = std::sqrt(dot(k, k, D));
                    float qi = qscale / std::max(qq, 1e-12f), ki = 1.0f / std::max(kk, 1e-12f);
                    for (int i = 0; i < D; ++i) {
                        qn[(size_t)i] = q[i] * qi;
                        kn[(size_t)i] = k[i] * ki;
                    }
                    // decay rows, u = S^T k
                    for (int j = 0; j < D; ++j) u[(size_t)j] = 0;
                    for (int i = 0; i < D; ++i) {
                        float dec = std::exp(g[i]);
                        float* si = s + (size_t)i * D;
                        float ki2 = kn[(size_t)i];
                        for (int j = 0; j < D; ++j) {
                            si[j] *= dec;
                            u[(size_t)j] += ki2 * si[j];
                        }
                    }
                    for (int j = 0; j < D; ++j) dlt[(size_t)j] = beta * (v[j] - u[(size_t)j]);
                    // rank-1 update and output o = S^T q
                    float* o = T(O)->row(t) + h * D;
                    for (int j = 0; j < D; ++j) o[j] = 0;
                    for (int i = 0; i < D; ++i) {
                        float* si = s + (size_t)i * D;
                        float ki2 = kn[(size_t)i], qi2 = qn[(size_t)i];
                        for (int j = 0; j < D; ++j) {
                            si[j] += ki2 * dlt[(size_t)j];
                            o[j] += qi2 * si[j];
                        }
                    }
                }
            }
        });
    }

    void mla_attend(const MlaShape& sh, const Tensor* Q, const Weight* kv_b, const Tensor* C, const Tensor* R, int S,
                    int pos0, const uint8_t* sel, Tensor* O) override {
        const int H = sh.heads, n = sh.nope, r = sh.rope, v = sh.vdim, kr = sh.kv_rank, qd = n + r, nq = Q->rows;
        const CpuWeight* kb = W(kv_b);
        HK_CHECK(kb->desc.fmt != WFmt::PLANES, "kv_b_proj must be a dense weight");
        HK_CHECK(Q->cols == H * qd && kb->desc.rows == H * (n + v) && kb->desc.cols == kr && C->cols == kr && R->cols == r &&
                     C->rows >= S && R->rows >= S && O->rows == nq && O->cols == H * v && pos0 + nq <= S,
                 "mla_attend: shape mismatch");
        const float scale = 1.0f / std::sqrt((float)qd);
        const float* wkb = kb->dense.data();
        parallel_for(nq, 1, [&](int64_t t0, int64_t t1) {
            std::vector<float> qa((size_t)kr), sc((size_t)S), mix((size_t)kr);
            for (int64_t t = t0; t < t1; ++t) {
                const int nkeys = pos0 + (int)t + 1;
                const float* q = T(Q)->row((int)t);
                float* out = T(O)->row((int)t);
                const uint8_t* mask = sel ? sel + (size_t)t * (size_t)S : nullptr;
                for (int h = 0; h < H; ++h) {
                    const float* qh = q + h * qd;
                    const float* wk = wkb + (size_t)h * (n + v) * kr;      // [n, kr]
                    const float* wv = wk + (size_t)n * kr;                 // [v, kr]
                    for (int c = 0; c < kr; ++c) qa[(size_t)c] = 0;
                    for (int i = 0; i < n; ++i) axpy_row(qa.data(), wk + (size_t)i * kr, qh[i], kr);
                    float mx = -1e30f;
                    for (int s = 0; s < nkeys; ++s) {
                        if (mask && !mask[s]) {
                            sc[(size_t)s] = -1e30f;
                            continue;
                        }
                        float a = (dot(qa.data(), T(C)->row(s), kr) + dot(qh + n, T(R)->row(s), r)) * scale;
                        sc[(size_t)s] = a;
                        mx = std::max(mx, a);
                    }
                    double sum = 0;
                    for (int s = 0; s < nkeys; ++s) {
                        float e = sc[(size_t)s] <= -1e29f ? 0.0f : std::exp(sc[(size_t)s] - mx);
                        sc[(size_t)s] = e;
                        sum += e;
                    }
                    float inv = sum > 0 ? (float)(1.0 / sum) : 0.0f;
                    for (int c = 0; c < kr; ++c) mix[(size_t)c] = 0;
                    for (int s = 0; s < nkeys; ++s)
                        if (sc[(size_t)s] != 0.0f) axpy_row(mix.data(), T(C)->row(s), sc[(size_t)s] * inv, kr);
                    for (int j = 0; j < v; ++j) out[h * v + j] = dot(wv + (size_t)j * kr, mix.data(), kr);
                }
            }
        });
    }

    void dsa_scores(const Tensor* Qi, const Tensor* Wh, const Tensor* Keys, int S, int heads, Tensor* Sc) override {
        const int D = Keys->cols, nq = Qi->rows;
        HK_CHECK(Qi->cols == heads * D && Wh->rows == nq && Wh->cols == heads && Keys->rows >= S && Sc->rows == nq &&
                     Sc->cols >= S,
                 "dsa_scores: shape mismatch");
        parallel_for(nq, 1, [&](int64_t t0, int64_t t1) {
            for (int64_t t = t0; t < t1; ++t) {
                const float* q = T(Qi)->row((int)t);
                const float* w = T(Wh)->row((int)t);
                float* out = T(Sc)->row((int)t);
                for (int s = 0; s < S; ++s) {
                    const float* key = T(Keys)->row(s);
                    float acc = 0;
                    for (int h = 0; h < heads; ++h) {
                        float d = dot(q + h * D, key, D);
                        if (d > 0) acc += w[h] * d;
                    }
                    out[s] = acc;
                }
            }
        });
    }

    void attn_res(const Tensor* ps, Tensor* const* blocks, int nb, const Weight* wn, const Weight* wp, float eps,
                  Tensor* Y) override {
        const int d = ps->cols, n = ps->rows;
        HK_CHECK((int)W(wn)->dense.size() >= d && (int)W(wp)->dense.size() >= d && Y->rows == n && Y->cols == d,
                 "attn_res: shape mismatch");
        for (int i = 0; i < nb; ++i) HK_CHECK(blocks[i]->rows == n && blocks[i]->cols == d, "attn_res: block shape mismatch");
        std::vector<float> wq((size_t)d);
        for (int c = 0; c < d; ++c) wq[(size_t)c] = W(wn)->dense[(size_t)c] * W(wp)->dense[(size_t)c];
        parallel_for(n, 8, [&](int64_t t0, int64_t t1) {
            std::vector<float> sc((size_t)nb + 1), out((size_t)d);
            for (int64_t t = t0; t < t1; ++t) {
                float mx = -1e30f;
                for (int i = 0; i <= nb; ++i) {
                    const float* v = i < nb ? T(blocks[i])->row((int)t) : T(ps)->row((int)t);
                    float inv = 1.0f / std::sqrt(dot(v, v, d) / (float)d + eps);
                    sc[(size_t)i] = dot(v, wq.data(), d) * inv;
                    mx = std::max(mx, sc[(size_t)i]);
                }
                float sum = 0;
                for (int i = 0; i <= nb; ++i) {
                    sc[(size_t)i] = std::exp(sc[(size_t)i] - mx);
                    sum += sc[(size_t)i];
                }
                std::fill(out.begin(), out.end(), 0.0f);
                for (int i = 0; i <= nb; ++i) {
                    const float* v = i < nb ? T(blocks[i])->row((int)t) : T(ps)->row((int)t);
                    axpy_row(out.data(), v, sc[(size_t)i] / sum, d);
                }
                memcpy(T(Y)->row((int)t), out.data(), (size_t)d * 4);  // after reading ps: Y may alias it
            }
        });
    }

   private:
    static void check_rows(const Tensor* t, int row0, int nrows) {
        HK_CHECK(row0 >= 0 && nrows >= 0 && row0 + nrows <= t->rows, "row range [%d, +%d) outside a tensor with %d rows", row0,
                 nrows, t->rows);
    }
    std::atomic<int64_t> used_{0};
};

}  // namespace

std::unique_ptr<Backend> make_cpu_backend() { return std::unique_ptr<Backend>(new CpuBackend()); }

std::unique_ptr<Backend> Backend::create(const std::string& which) {
    HK_CHECK(which == "auto" || which == "cpu" || which == "cuda", "unknown backend \"%s\" (use auto, cpu or cuda)", which.c_str());
    if (which != "cpu") {
        std::string why;
        std::unique_ptr<Backend> b = make_cuda_backend(&why);
        if (b) return b;
        HK_CHECK(which == "auto", "CUDA backend unavailable: %s", why.c_str());
        HK_INFO("no CUDA backend (%s): running on the CPU", why.c_str());
    }
    return make_cpu_backend();
}

#if !defined(HK_USE_CUDA)
std::unique_ptr<Backend> make_cuda_backend(std::string* why) {
    if (why) *why = "this build was compiled without CUDA";
    return nullptr;
}
#endif

}  // namespace hk