File size: 28,699 Bytes
5b65ff7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
#include "ga_encoder.h"

#include "ga_kernels.h"
#include "ga_math.h"

#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define GA_NORM_EPS 1e-6f
#define GA_ROPE_BASE 10000.0f
#define GA_LAYER_BLEND 0.25f
#define GA_MIN_GROUP 8 /* smallest int8 scale group the activation scratch is sized for */

static const int32_t *config_list(ga_weights *w, const char *name, int expected)
{
    int count;
    const int32_t *values = ga_weights_i32(w, name, &count);
    if (values && count != expected) {
        ga_weights_fail(w, "%s: expected %d values", name, expected);
        return NULL;
    }
    return values;
}

/* int8 weights the backend cannot multiply directly, widened to f32 at load. */
static const float *dequantize(ga_weights *w, const ga_lin *lin)
{
    float *wide = ga_weights_alloc(w, (size_t)lin->out * lin->in * sizeof(float));
    int groups = lin->in / lin->group;
    if (!wide || !lin->wscale)
        return NULL;
    for (int r = 0; r < lin->out; r++)
        for (int c = 0; c < lin->in; c++)
            wide[(size_t)r * lin->in + c] = (float)lin->wq[(size_t)r * lin->in + c] *
                                             lin->wscale[(size_t)r * groups + c / lin->group];
    return wide;
}

/* Scales of an int8 linear: [out] (one group per row) or [out, in / group]. */
static void load_scales(ga_lin *lin, ga_weights *w, const char *name)
{
    const ga_entry *e = ga_weights_find(w, name);
    int groups = e && e->ndim == 2 ? (int)e->dims[1] : 1;
    if (!e || (int)e->dims[0] != lin->out || groups < 1 || lin->in % groups) {
        ga_weights_fail(w, "bad %s", name);
        return;
    }
    lin->group = lin->in / groups;
    if (lin->in > GA_I8_MAX_K) {
        ga_weights_fail(w, "%s: int8 rows longer than %d", name, GA_I8_MAX_K);
        return;
    }
    if (lin->group < GA_MIN_GROUP) {
        ga_weights_fail(w, "%s: int8 group %d < %d", name, lin->group, GA_MIN_GROUP);
        return;
    }
    lin->wscale = ga_weights_flat(w, (size_t)lin->out * groups, "%s", name);
}

/* Weights in the int8 kernel's layout: as stored, or packed in pairs for i8mm. */
static const int8_t *kernel_weights(ga_weights *w, const ga_lin *lin)
{
    int8_t *packed;
    if (!lin->wq || !ga_kernel_i8_pairs(lin->group))
        return lin->wq;
    packed = ga_weights_alloc(w, (size_t)(lin->out + 1) / 2 * 2 * lin->in);
    if (packed)
        ga_kernel_i8_pack_weights(lin->wq, lin->out, lin->in, packed);
    return packed;
}

/* Scales in the int8 kernel's layout. */
static const float *kernel_scales(ga_weights *w, const ga_lin *lin)
{
    int groups = lin->in / lin->group;
    float *out = ga_weights_alloc(w, (size_t)(lin->out + 3) / 4 * 4 * groups * sizeof(float));
    if (out && lin->wscale)
        ga_kernel_i8_interleave_scales(lin->wscale, lin->out, groups, out);
    return out;
}

/* Weights as stored (int8, f16 or f32), in the form the backend multiplies best. */
static ga_lin load_linear(ga_weights *w, int out, int in, int stack, int layer,
                          const char *name)
{
    ga_lin lin;
    memset(&lin, 0, sizeof(lin));
    lin.in = in;
    lin.out = out;
    lin.b = ga_weights_mat(w, out, 0, "encoders.%d.layers.%d.%s.bias", stack, layer, name);
    lin.wq = ga_weights_mat_i8(w, out, in, "encoders.%d.layers.%d.%s.weight", stack, layer,
                               name);
    if (lin.wq) {
        char scales[128];
        snprintf(scales, sizeof(scales), "encoders.%d.layers.%d.%s.wscale", stack, layer, name);
        load_scales(&lin, w, scales);
        if (!ga_math_reads_i8()) {
            lin.w = dequantize(w, &lin);
            lin.wq = NULL;
        } else {
            lin.wscale = kernel_scales(w, &lin);
            lin.wq = kernel_weights(w, &lin);
        }
        return lin;
    }
    lin.wh = ga_math_reads_f16()
                 ? ga_weights_mat_f16(w, out, in, "encoders.%d.layers.%d.%s.weight", stack,
                                      layer, name)
                 : NULL;
    if (!lin.wh)
        lin.w = ga_weights_mat(w, out, in, "encoders.%d.layers.%d.%s.weight", stack, layer,
                               name);
    return lin;
}

static void load_conv_module(ga_layer *l, ga_weights *w, int dim, int s, int i)
{
    char name[128];
    const ga_entry *e;
    const float *raw;
    float *weight;
    snprintf(name, sizeof(name), "encoders.%d.layers.%d.conv_module.depthwise_conv.weight", s,
             i);
    e = ga_weights_find(w, name);
    if (!e)
        return;
    if (e->ndim != 2 || (int)e->dims[0] != dim || !(e->dims[1] & 1u)) {
        ga_weights_fail(w, "bad %s", name);
        return;
    }
    l->kernel = (int)e->dims[1];
    raw = ga_weights_mat(w, dim, l->kernel, "%s", name);
    weight = ga_weights_alloc(w, (size_t)dim * l->kernel * sizeof(float));
    if (!raw || !weight)
        return;
    for (int c = 0; c < dim; c++)
        for (int k = 0; k < l->kernel; k++)
            weight[(size_t)k * dim + c] = raw[(size_t)c * l->kernel + k];
    l->dw_weight = weight;
    l->dw_bias = ga_weights_mat(w, dim, 0,
                                "encoders.%d.layers.%d.conv_module.depthwise_conv.bias", s, i);
    l->mean_weight = ga_weights_mat(
        w, dim, 0, "encoders.%d.layers.%d.conv_module.weighted_mean.weights", s, i);
    l->conv_in = load_linear(w, 2 * dim, dim, s, i, "conv_module.in_proj");
    l->conv_out = load_linear(w, dim, dim, s, i, "conv_module.out_proj");
    l->ff2_in = load_linear(w, l->ff1_in.out, dim, s, i, "feed_forward2.in_proj");
    l->ff2_out = load_linear(w, dim, l->ff1_in.out, s, i, "feed_forward2.out_proj");
}

static void load_layer(ga_layer *l, ga_weights *w, const ga_stack *st, int s, int i)
{
    char name[128];
    const ga_entry *e;
    int dim = st->dim, hidden;
    snprintf(name, sizeof(name), "encoders.%d.layers.%d.feed_forward1.in_proj.weight", s, i);
    e = ga_weights_find(w, name);
    if (!e || e->ndim != 2) {
        ga_weights_fail(w, "missing tensor %s", name);
        return;
    }
    hidden = (int)e->dims[0];
    l->ff1_in = load_linear(w, hidden, dim, s, i, "feed_forward1.in_proj");
    l->ff1_out = load_linear(w, dim, hidden, s, i, "feed_forward1.out_proj");
    l->qk = load_linear(w, 2 * st->heads * st->qdim, dim, s, i, "self_attn.qk_in_proj");
    l->vg = load_linear(w, 3 * st->heads * st->vdim, dim, s, i, "self_attn.vg_in_proj");
    l->attn_out = load_linear(w, dim, st->heads * st->vdim, s, i, "self_attn.out_proj");
    l->in_norm =
        ga_weights_mat(w, dim, 0, "encoders.%d.layers.%d.self_attn.in_norm.weight", s, i);
    l->norm = ga_weights_mat(w, dim, 0, "encoders.%d.layers.%d.norm.weight", s, i);
    load_conv_module(l, w, dim, s, i);
}

static void load_stack(ga_stack *st, ga_weights *w, int s, int feat)
{
    char name[64];
    const ga_entry *e;
    const float *scale;
    float *transposed;
    snprintf(name, sizeof(name), "encoders.%d.proj.weight", s);
    e = ga_weights_find(w, name);
    if (!e || e->ndim != 2 || (int)e->dims[1] != st->ds * feat) {
        ga_weights_fail(w, "bad %s", name);
        return;
    }
    st->dim = (int)e->dims[0];
    st->in_dim = (int)e->dims[1];
    st->proj = ga_weights_mat(w, st->dim, st->in_dim, "%s", name);
    st->residual_scales =
        ga_weights_mat(w, st->n_layers + 1, 0, "encoders.%d.residual_scales", s);
    scale = ga_weights_mat(w, 1, 0, "encoders.%d.input_scale", s);
    st->layers = ga_weights_alloc(w, (size_t)st->n_layers * sizeof(ga_layer));
    transposed = ga_weights_alloc(w, (size_t)st->dim * st->in_dim * sizeof(float));
    if (ga_weights_failed(w))
        return;
    for (int r = 0; r < st->dim; r++)
        for (int c = 0; c < st->in_dim; c++)
            transposed[(size_t)c * st->dim + r] = st->proj[(size_t)r * st->in_dim + c];
    st->proj_t = transposed;
    st->input_scale = scale[0];
    for (int i = 0; i < st->n_layers && !ga_weights_failed(w); i++)
        load_layer(&st->layers[i], w, st, s, i);
}

int ga_encoder_init(ga_encoder *e, ga_weights *w, int feat)
{
    int count;
    const int32_t *ds = ga_weights_i32(w, "config.downsampling", &count);
    const int32_t *layers = config_list(w, "config.num_layers", count);
    const int32_t *heads = config_list(w, "config.num_heads", count);
    const int32_t *qdim = config_list(w, "config.query_head_dim", count);
    const int32_t *vdim = config_list(w, "config.value_head_dim", count);
    const float *scale = ga_weights_mat(w, 1, 0, "out_norm.scale");
    const float *eps = ga_weights_mat(w, 1, 0, "out_norm.eps_sq");
    memset(e, 0, sizeof(*e));
    if (ga_weights_failed(w))
        return -1;
    e->feat = feat;
    e->n_stacks = count;
    e->out_scale = scale[0];
    e->out_eps_sq = eps[0];
    e->stacks = ga_weights_alloc(w, (size_t)count * sizeof(ga_stack));
    if (!e->stacks)
        return -1;
    for (int s = 0; s < count && !ga_weights_failed(w); s++) {
        ga_stack *st = &e->stacks[s];
        st->ds = ds[s];
        st->n_layers = layers[s];
        st->heads = heads[s];
        st->qdim = qdim[s];
        st->vdim = vdim[s];
        if (st->ds < 1 || st->n_layers < 1 || st->heads < 1 || st->qdim < 2 || (st->qdim & 1)) {
            ga_weights_fail(w, "bad stack %d config", s);
            break;
        }
        load_stack(st, w, s, feat);
    }
    return ga_weights_failed(w) ? -1 : 0;
}

static size_t max_size(size_t a, size_t b)
{
    return a > b ? a : b;
}

void ga_encoder_state_reset(const ga_encoder *e, ga_encoder_state *s)
{
    for (int i = 0; i < e->n_stacks; i++)
        s->n_past[i] = 0;
}

void ga_encoder_state_free(const ga_encoder *e, ga_encoder_state *s)
{
    if (s->layers)
        for (int i = 0; i < e->n_stacks; i++) {
            for (int j = 0; s->layers[i] && j < e->stacks[i].n_layers; j++) {
                free(s->layers[i][j].keys);
                free(s->layers[i][j].values);
                free(s->layers[i][j].conv);
            }
            free(s->layers[i]);
        }
    free(s->layers);
    free(s->n_past);
    memset(s, 0, sizeof(*s));
}

int ga_encoder_state_init(const ga_encoder *e, ga_encoder_state *s, int chunk, int left)
{
    memset(s, 0, sizeof(*s));
    s->chunk = chunk;
    s->left = left;
    s->n_past = calloc((size_t)e->n_stacks, sizeof(int));
    s->layers = calloc((size_t)e->n_stacks, sizeof(ga_layer_state *));
    if (!s->n_past || !s->layers) {
        ga_encoder_state_free(e, s);
        return -1;
    }
    for (int i = 0; i < e->n_stacks; i++) {
        const ga_stack *st = &e->stacks[i];
        size_t rows = (size_t)(left + chunk) / st->ds;
        size_t q = (size_t)st->heads * st->qdim, v = (size_t)st->heads * st->vdim;
        if (chunk % st->ds || left % st->ds) {
            ga_encoder_state_free(e, s);
            return -1;
        }
        s->layers[i] = calloc((size_t)st->n_layers, sizeof(ga_layer_state));
        if (!s->layers[i]) {
            ga_encoder_state_free(e, s);
            return -1;
        }
        for (int j = 0; j < st->n_layers; j++) {
            ga_layer_state *ls = &s->layers[i][j];
            ls->keys = calloc(rows * q, sizeof(float));
            ls->values = calloc(rows * v, sizeof(float));
            ls->conv = st->layers[j].kernel ? calloc(rows * st->dim, sizeof(float)) : NULL;
            if (!ls->keys || !ls->values || (st->layers[j].kernel && !ls->conv)) {
                ga_encoder_state_free(e, s);
                return -1;
            }
        }
    }
    return 0;
}

void ga_encoder_work_free(ga_encoder_work *w)
{
    free(w->rope_cos);
    free(w->rope_sin);
    free(w->shapes);
    free(w->x);
    free(w->bypass);
    free(w->orig);
    free(w->wide);
    free(w->tmp);
    free(w->query);
    free(w->keys);
    free(w->scores);
    free(w->attn);
    free(w->gate);
    free(w->mean);
    free(w->xq);
    free(w->xq_scale);
    memset(w, 0, sizeof(*w));
}

static int init_rope(const ga_encoder *e, ga_encoder_work *w)
{
    int positions = w->left + w->chunk, half = 0;
    for (int i = 0; i < e->n_stacks; i++)
        if (e->stacks[i].qdim / 2 > half)
            half = e->stacks[i].qdim / 2;
    w->rope_stride = positions * half;
    w->rope_cos = malloc((size_t)e->n_stacks * w->rope_stride * sizeof(float));
    w->rope_sin = malloc((size_t)e->n_stacks * w->rope_stride * sizeof(float));
    if (!w->rope_cos || !w->rope_sin)
        return -1;
    for (int i = 0; i < e->n_stacks; i++) {
        int qdim = e->stacks[i].qdim;
        for (int p = 0; p < positions; p++)
            for (int k = 0; k < qdim / 2; k++) {
                float freq = 1.0f / powf(GA_ROPE_BASE, (float)(2 * k) / (float)qdim);
                float angle = (float)p * freq;
                size_t at = (size_t)i * w->rope_stride + (size_t)p * (qdim / 2) + k;
                w->rope_cos[at] = cosf(angle);
                w->rope_sin[at] = sinf(angle);
            }
    }
    return 0;
}

int ga_encoder_work_init(const ga_encoder *e, ga_encoder_work *w, int chunk, int left,
                         int batch)
{
    size_t dim = 0, wide = 0, hq = 0, hv = 0, hist = 0, heads = 0, in_max = 0;
    size_t rows = (size_t)batch * chunk;
    memset(w, 0, sizeof(*w));
    w->chunk = chunk;
    w->left = left;
    w->batch = batch;
    if (batch < 1 || init_rope(e, w) != 0) {
        ga_encoder_work_free(w);
        return -1;
    }
    for (int i = 0; i < e->n_stacks; i++) {
        const ga_stack *st = &e->stacks[i];
        size_t q = (size_t)st->heads * st->qdim, v = (size_t)st->heads * st->vdim;
        dim = max_size(dim, (size_t)st->dim);
        hq = max_size(hq, q);
        hv = max_size(hv, v);
        hist = max_size(hist, (size_t)(left + chunk) / st->ds);
        heads = max_size(heads, (size_t)st->heads);
        wide = max_size(wide, max_size(2 * q, 3 * v));
        for (int j = 0; j < st->n_layers; j++)
            wide = max_size(wide, max_size((size_t)st->layers[j].ff1_in.out, 2 * (size_t)st->dim));
        in_max = max_size(in_max, max_size(dim, max_size(hv, wide)));
    }
    w->shapes = malloc((size_t)batch * sizeof(ga_step_shape));
    w->x = malloc(rows * dim * sizeof(float));
    w->bypass = malloc(rows * dim * sizeof(float));
    w->orig = malloc(rows * dim * sizeof(float));
    w->tmp = malloc(rows * dim * sizeof(float));
    w->mean = malloc(rows * dim * sizeof(float));
    w->wide = malloc(rows * wide * sizeof(float));
    w->query = malloc(rows * hq * sizeof(float));
    w->keys = malloc((size_t)batch * hist * hq * sizeof(float));
    w->scores = malloc((size_t)batch * heads * chunk * hist * sizeof(float));
    w->attn = malloc(rows * hv * sizeof(float));
    w->gate = malloc(rows * max_size(hv, dim) * sizeof(float));
    w->xq = malloc((rows + 1) * in_max);
    w->xq_scale = malloc(rows * (in_max / GA_MIN_GROUP + 1) * sizeof(float));
    w->keys_stride = hist * hq;
    w->scores_stride = (size_t)chunk * hist;
    if (!w->shapes || !w->x || !w->bypass || !w->orig || !w->tmp || !w->mean || !w->wide ||
        !w->query || !w->keys || !w->scores || !w->attn || !w->gate || !w->xq ||
        !w->xq_scale) {
        ga_encoder_work_free(w);
        return -1;
    }
    return 0;
}

/* First cached row a query may see: at most `keep` rows back. */
static int first_visible(const ga_step_shape *g, int query)
{
    int first = query + g->past - g->keep;
    return first < 0 ? 0 : first;
}

static void add_rows(float *x, const float *y, size_t n)
{
    for (size_t i = 0; i < n; i++)
        x[i] += y[i];
}

static void apply_linear(const ga_lin *lin, const float *x, int rows, float *y,
                         ga_encoder_work *w)
{
    if (lin->wq)
        ga_linear_i8(x, rows, lin->in, lin->wq, lin->wscale, lin->group, lin->b, lin->out, y,
                     w->xq, w->xq_scale, w->pool);
    else if (lin->wh)
        ga_linear_f16(x, rows, lin->in, lin->wh, lin->b, lin->out, y, w->pool);
    else
        ga_linear(x, rows, lin->in, lin->w, lin->b, lin->out, y, w->pool);
}

static void rotate(const float *in, float *out, int heads, int qdim, const float *cos,
                   const float *sin)
{
    for (int h = 0; h < heads; h++)
        for (int k = 0; k < qdim / 2; k++) {
            float a = in[h * qdim + 2 * k], b = in[h * qdim + 2 * k + 1];
            out[h * qdim + 2 * k] = a * cos[k] - b * sin[k];
            out[h * qdim + 2 * k + 1] = a * sin[k] + b * cos[k];
        }
}

/* Softmax over the visible key range of each query row; zero elsewhere. */
static void masked_softmax(float *scores, int keys, const ga_step_shape *g)
{
    int last = g->past + g->valid;
    for (int t = 0; t < g->frames; t++) {
        float *row = scores + (size_t)t * keys;
        int first = first_visible(g, t);
        float peak, sum = 0.0f;
        if (first >= last) {
            for (int i = 0; i < keys; i++)
                row[i] = 1.0f / (float)keys;
            continue;
        }
        peak = row[first];
        for (int i = first + 1; i < last; i++)
            if (row[i] > peak)
                peak = row[i];
        for (int i = 0; i < first; i++)
            row[i] = 0.0f;
        for (int i = first; i < last; i++) {
            row[i] = expf(row[i] - peak);
            sum += row[i];
        }
        for (int i = first; i < last; i++)
            row[i] /= sum;
        for (int i = last; i < keys; i++)
            row[i] = 0.0f;
    }
}

/* Drop the oldest rows so at most `keep` remain. */
static void trim_history(float *rows, size_t width, const ga_step_shape *g)
{
    int total = g->past + g->frames;
    if (total > g->keep)
        memmove(rows, rows + (size_t)(total - g->keep) * width,
                (size_t)g->keep * width * sizeof(float));
}

/* Mean of the visible convolution inputs per query row, scaled per channel. */
static void context_mean(const ga_layer *l, const float *history, int dim, float *mean,
                         const ga_step_shape *g)
{
    int last = g->past + g->valid;
    for (int t = 0; t < g->frames; t++) {
        float *out = mean + (size_t)t * dim;
        int first = first_visible(g, t);
        int count = last - first;
        float scale = 1.0f / (float)(count > 1 ? count : 1);
        memset(out, 0, (size_t)dim * sizeof(float));
        for (int i = first; i < last; i++)
            add_rows(out, history + (size_t)i * dim, (size_t)dim);
        for (int c = 0; c < dim; c++)
            out[c] *= scale * l->mean_weight[c];
    }
}

/* Depthwise conv: full causal past, future taps stop at the chunk edge. */
static void depthwise(const ga_layer *l, const float *history, int dim, float *out,
                      const ga_step_shape *g)
{
    int radius = l->kernel / 2;
    for (int t = 0; t < g->frames; t++) {
        float *dst = out + (size_t)t * dim;
        memcpy(dst, l->dw_bias, (size_t)dim * sizeof(float));
        for (int k = 0; k < l->kernel; k++) {
            int row = g->past + t + k - radius;
            const float *src, *weight;
            if (row < 0 || t + k - radius >= g->frames)
                continue;
            src = history + (size_t)row * dim;
            weight = l->dw_weight + (size_t)k * dim;
            for (int c = 0; c < dim; c++)
                dst[c] += weight[c] * src[c];
        }
    }
}

/* One layer of one stack for every stream of a step; rows of stream b start at b * frames. */
typedef struct layer_ctx {
    const ga_stack *st;
    const ga_layer *l;
    ga_encoder_state *const *states;
    ga_encoder_work *w;
    int stack, layer, count, frames;
} layer_ctx;

static ga_layer_state *layer_state(const layer_ctx *c, int b)
{
    return &c->states[b]->layers[c->stack][c->layer];
}

typedef void (*unit_fn)(const layer_ctx *c, int unit);

typedef struct unit_task {
    const layer_ctx *ctx;
    unit_fn fn;
    int units;
} unit_task;

static void units_part(void *arg, int part, int parts)
{
    const unit_task *t = arg;
    for (int u = t->units * part / parts; u < t->units * (part + 1) / parts; u++)
        t->fn(t->ctx, u);
}

/* fn(c, u) for every u in [0, units), spread over the pool. */
static void run_units(const layer_ctx *c, int units, unit_fn fn)
{
    unit_task t = {c, fn, units};
    ga_pool_run(c->w->pool, units_part, &t);
}

static void feed_forward(const ga_lin *in, const ga_lin *out, float *x, int rows,
                         ga_encoder_work *w)
{
    apply_linear(in, x, rows, w->wide, w);
    ga_silu(w->wide, (size_t)rows * in->out, w->pool);
    apply_linear(out, w->wide, rows, w->tmp, w);
    add_rows(x, w->tmp, (size_t)rows * out->out);
}

/* Stream b: cache its new keys, rotate its queries and all its visible keys. */
static void stream_keys(const layer_ctx *c, int b)
{
    const ga_stack *st = c->st;
    const ga_step_shape *g = &c->w->shapes[b];
    ga_layer_state *ls = layer_state(c, b);
    int hq = st->heads * st->qdim, half = st->qdim / 2;
    float *keys = c->w->keys + (size_t)b * c->w->keys_stride;
    for (int t = 0; t < g->frames; t++) {
        size_t row = (size_t)b * g->frames + t;
        const float *qk = c->w->wide + row * 2 * hq;
        int pos = g->past + t;
        memcpy(ls->keys + (size_t)pos * hq, qk + hq, (size_t)hq * sizeof(float));
        rotate(qk, c->w->query + row * hq, st->heads, st->qdim, g->cos + (size_t)pos * half,
               g->sin + (size_t)pos * half);
    }
    for (int i = 0; i < g->past + g->frames; i++)
        rotate(ls->keys + (size_t)i * hq, keys + (size_t)i * hq, st->heads, st->qdim,
               g->cos + (size_t)i * half, g->sin + (size_t)i * half);
}

/* Stream b: gate its new values into the cache, keep the output gate. */
static void stream_values(const layer_ctx *c, int b)
{
    const ga_step_shape *g = &c->w->shapes[b];
    ga_layer_state *ls = layer_state(c, b);
    int hv = c->st->heads * c->st->vdim;
    for (int t = 0; t < g->frames; t++) {
        size_t row = (size_t)b * g->frames + t;
        float *vg = c->w->wide + row * 3 * hv;
        float *value = ls->values + (size_t)(g->past + t) * hv;
        ga_sigmoid(vg + hv, (size_t)2 * hv, NULL);
        for (int i = 0; i < hv; i++)
            value[i] = vg[i] * vg[hv + i];
        memcpy(c->w->gate + row * hv, vg + 2 * hv, (size_t)hv * sizeof(float));
    }
}

/* Unit = (stream, head): scores, softmax and weighted values, each with its own scores. */
static void stream_head(const layer_ctx *c, int unit)
{
    const ga_stack *st = c->st;
    int b = unit / st->heads, h = unit % st->heads;
    const ga_step_shape *g = &c->w->shapes[b];
    int hq = st->heads * st->qdim, hv = st->heads * st->vdim, keys = g->past + g->frames;
    size_t row = (size_t)b * g->frames;
    float *scores = c->w->scores + (size_t)unit * c->w->scores_stride;
    float scale = 1.0f / sqrtf((float)st->qdim);
    ga_gemm_nt(g->frames, keys, st->qdim, scale, c->w->query + row * hq + h * st->qdim, hq,
               c->w->keys + (size_t)b * c->w->keys_stride + h * st->qdim, hq, 0.0f, scores,
               keys, NULL);
    masked_softmax(scores, keys, g);
    ga_gemm_nn(g->frames, st->vdim, keys, 1.0f, scores, keys,
               layer_state(c, b)->values + h * st->vdim, hv, 0.0f,
               c->w->attn + row * hv + h * st->vdim, hv);
}

static void attention(const layer_ctx *c, float *x)
{
    const ga_stack *st = c->st;
    const ga_layer *l = c->l;
    ga_encoder_work *w = c->w;
    int rows = c->count * c->frames, hq = st->heads * st->qdim, hv = st->heads * st->vdim;

    ga_rms_norm(w->orig, rows, st->dim, l->in_norm, GA_NORM_EPS, w->tmp);
    apply_linear(&l->qk, w->tmp, rows, w->wide, w);
    run_units(c, c->count, stream_keys);
    apply_linear(&l->vg, x, rows, w->wide, w);
    run_units(c, c->count, stream_values);
    run_units(c, c->count * st->heads, stream_head);
    for (size_t i = 0; i < (size_t)rows * hv; i++)
        w->attn[i] *= w->gate[i];
    apply_linear(&l->attn_out, w->attn, rows, w->tmp, w);
    add_rows(x, w->tmp, (size_t)rows * st->dim);
    for (int b = 0; b < c->count; b++) {
        trim_history(layer_state(c, b)->keys, (size_t)hq, &w->shapes[b]);
        trim_history(layer_state(c, b)->values, (size_t)hv, &w->shapes[b]);
    }
}

/* Stream b: cache its convolution inputs, split the gate, context mean and depthwise. */
static void stream_conv(const layer_ctx *c, int b)
{
    const ga_step_shape *g = &c->w->shapes[b];
    ga_layer_state *ls = layer_state(c, b);
    int dim = c->st->dim;
    size_t row = (size_t)b * g->frames;
    float *fresh = ls->conv + (size_t)g->past * dim;
    for (int t = 0; t < g->frames; t++) {
        const float *in = c->w->wide + (row + t) * 2 * dim;
        float *dst = fresh + (size_t)t * dim;
        if (t < g->valid)
            memcpy(dst, in, (size_t)dim * sizeof(float));
        else
            memset(dst, 0, (size_t)dim * sizeof(float));
        memcpy(c->w->gate + (row + t) * dim, in + dim, (size_t)dim * sizeof(float));
    }
    context_mean(c->l, ls->conv, dim, c->w->mean + row * dim, g);
    depthwise(c->l, ls->conv, dim, c->w->tmp + row * dim, g);
}

static void convolution(const layer_ctx *c, float *x)
{
    const ga_layer *l = c->l;
    ga_encoder_work *w = c->w;
    int rows = c->count * c->frames, dim = c->st->dim;
    size_t total = (size_t)rows * dim;

    apply_linear(&l->conv_in, x, rows, w->wide, w);
    run_units(c, c->count, stream_conv);
    ga_sigmoid(w->gate, total, w->pool);
    for (size_t i = 0; i < total; i++)
        w->tmp[i] = (w->tmp[i] + w->mean[i]) * w->gate[i];
    ga_silu(w->tmp, total, w->pool);
    apply_linear(&l->conv_out, w->tmp, rows, w->mean, w);
    add_rows(x, w->mean, total);
    for (int b = 0; b < c->count; b++)
        trim_history(layer_state(c, b)->conv, (size_t)dim, &w->shapes[b]);
}

static void layer_step(const layer_ctx *c, float *x)
{
    const ga_layer *l = c->l;
    ga_encoder_work *w = c->w;
    int rows = c->count * c->frames;
    size_t total = (size_t)rows * c->st->dim;
    memcpy(w->orig, x, total * sizeof(float));
    feed_forward(&l->ff1_in, &l->ff1_out, x, rows, w);
    attention(c, x);
    if (l->kernel) {
        convolution(c, x);
        feed_forward(&l->ff2_in, &l->ff2_out, x, rows, w);
    }
    for (size_t i = 0; i < total; i++)
        x[i] = w->orig[i] + GA_LAYER_BLEND * (x[i] - w->orig[i]);
    ga_rms_norm(x, rows, c->st->dim, l->norm, GA_NORM_EPS, x);
}

static void stack_step(const ga_encoder *e, ga_encoder_state *const *states, int count,
                       ga_encoder_work *w, int index, float *io, const int *n_valid)
{
    const ga_stack *st = &e->stacks[index];
    layer_ctx c;
    int frames = w->chunk / st->ds, rows = count * frames;
    size_t total = (size_t)rows * st->dim;

    for (int b = 0; b < count; b++) {
        ga_step_shape *g = &w->shapes[b];
        g->frames = frames;
        g->valid = (n_valid[b] + st->ds - 1) / st->ds;
        g->past = states[b]->n_past[index];
        g->keep = w->left / st->ds;
        g->cos = w->rope_cos + (size_t)index * w->rope_stride;
        g->sin = w->rope_sin + (size_t)index * w->rope_stride;
        if (st->ds > 1 && n_valid[b] < w->chunk)
            memset(io + ((size_t)b * w->chunk + n_valid[b]) * e->feat, 0,
                   (size_t)(w->chunk - n_valid[b]) * e->feat * sizeof(float));
    }
    ga_linear(io, rows, st->in_dim, st->proj, NULL, st->dim, w->x, w->pool);
    for (size_t i = 0; i < total; i++) {
        w->bypass[i] = st->residual_scales[0] * w->x[i];
        w->x[i] *= st->input_scale;
    }
    c.st = st;
    c.states = states;
    c.w = w;
    c.stack = index;
    c.count = count;
    c.frames = frames;
    for (int i = 0; i < st->n_layers; i++) {
        float scale = st->residual_scales[i + 1];
        c.l = &st->layers[i];
        c.layer = i;
        layer_step(&c, w->x);
        for (size_t j = 0; j < total; j++)
            w->bypass[j] += scale * w->x[j];
    }
    ga_gemm_nt(rows, st->in_dim, st->dim, 1.0f, w->bypass, st->dim, st->proj_t, st->dim,
               1.0f, io, st->in_dim, w->pool);
    for (int b = 0; b < count; b++) {
        const ga_step_shape *g = &w->shapes[b];
        states[b]->n_past[index] = g->past + g->frames > g->keep ? g->keep : g->past + g->frames;
    }
}

void ga_encoder_step(const ga_encoder *e, ga_encoder_state *const *states, int count,
                     ga_encoder_work *w, float *x, const int *n_valid)
{
    for (int i = 0; i < e->n_stacks; i++)
        stack_step(e, states, count, w, i, x, n_valid);
    for (int t = 0; t < count * w->chunk; t++) {
        float *row = x + (size_t)t * e->feat;
        float sum = 0.0f, scale;
        for (int i = 0; i < e->feat; i++)
            sum += row[i] * row[i];
        scale = e->out_scale / sqrtf(sum / (float)e->feat + e->out_eps_sq);
        for (int i = 0; i < e->feat; i++)
            row[i] *= scale;
    }
}