-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy patheemicrogpt.c
More file actions
1791 lines (1641 loc) · 73.8 KB
/
eemicrogpt.c
File metadata and controls
1791 lines (1641 loc) · 73.8 KB
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
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Everything else is just efficiency.
The most extreme way to train a GPT in pure, dependency-free C.
This file is the everything else.
Optimized for Apple Silicon with SME2 (M4+), with scalar Neon fallback.
@entgpt
*/
//
// Compile (scalar): clang -O3 -ffast-math -o eemicrogpt eemicrogpt.c -lm
// Compile (SME2): clang -O3 -mcpu=native+sme2 -ffast-math -o eemicrogpt eemicrogpt.c -lm
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <mach/mach_time.h>
#include <arm_neon.h>
// ============================================================
// Architecture constants (matching microgpt)
// ============================================================
#ifndef D_MODEL
#define D_MODEL 64
#endif
#ifndef N_HEADS
#define N_HEADS 4
#endif
#define HEAD_DIM (D_MODEL / N_HEADS)
#define D_FF (4 * D_MODEL)
#define VOCAB 27 // 26 letters (0..25) + boundary token (26)
#define BOUNDARY 26 // boundary/null token index (B in microgpt)
#define MAX_SEQ 16
#ifndef BATCH
#define BATCH 16
#endif
#ifndef N_STEPS
#define N_STEPS 1000
#endif
#ifndef LR_INIT
#define LR_INIT 0.01f
#endif
#define BETA1 0.85f
#define BETA2 0.99f
#define EPS 1e-8f
#define INV_SQRT_HD (1.0f / sqrtf((float)HEAD_DIM))
#ifdef __ARM_FEATURE_SME2
#include <arm_sme.h>
#ifndef USE_SME2
#if D_MODEL >= 64
#define USE_SME2 1
#else
#define USE_SME2 0
#endif
#endif
#else
#define USE_SME2 0
#endif
// ============================================================
// RNG: xorshift64
// ============================================================
static uint64_t rng_state = 42;
static uint64_t xorshift64(void) {
uint64_t x = rng_state;
x ^= x << 13;
x ^= x >> 7;
x ^= x << 17;
rng_state = x;
return x;
}
static float randf(void) {
return (float)(xorshift64() & 0xFFFFFF) / (float)0xFFFFFF;
}
static float rand_normal(void) {
float u1 = randf() + 1e-10f;
float u2 = randf();
return sqrtf(-2.0f * logf(u1)) * cosf(2.0f * (float)M_PI * u2);
}
// ============================================================
// Model parameters
// microgpt stores weights as W[out][in] (each row dotted with input).
// We store as W[out][in] to match, and our linear() handles this.
// ============================================================
typedef struct {
float tok_emb[VOCAB][D_MODEL]; // token embeddings: te[V][E]
float pos_emb[MAX_SEQ][D_MODEL]; // position embeddings: pe[T][E]
// Attention weights
float Wq[D_MODEL][D_MODEL]; // query projection: q[E][E]
float Wk[D_MODEL][D_MODEL]; // key projection
float Wv[D_MODEL][D_MODEL]; // value projection
float Wo[D_MODEL][D_MODEL]; // output projection
// FFN weights
// microgpt: S["01"] = M(E*4, E) = [64][16], S["02"] = M(E, E*4) = [16][64]
float Wf1[D_FF][D_MODEL]; // expand: [64][16], out=64, in=16
float Wf2[D_MODEL][D_FF]; // contract: [16][64], out=16, in=64
// LM head: microgpt S["lm"] = M(V, E) = [27][16]
float Wlm[VOCAB][D_MODEL]; // lm head: [27][16]
} Model;
// ============================================================
// Activation cache for backprop
// ============================================================
typedef struct {
int tokens[BATCH][MAX_SEQ];
int seq_lens[BATCH]; // number of tokens including boundary
float raw_emb[BATCH][MAX_SEQ][D_MODEL]; // tok_emb + pos_emb (before first norm)
float emb[BATCH][MAX_SEQ][D_MODEL]; // after first RMS norm (= residual stream input)
float emb_rms[BATCH][MAX_SEQ]; // RMS values for first norm backward
float norm1[BATCH][MAX_SEQ][D_MODEL]; // after second RMS norm (pre-attention)
float norm1_rms[BATCH][MAX_SEQ]; // RMS values for norm1 backward
float Q[BATCH][MAX_SEQ][D_MODEL];
float K[BATCH][MAX_SEQ][D_MODEL];
float V[BATCH][MAX_SEQ][D_MODEL];
float attn_scores[BATCH][N_HEADS][MAX_SEQ][MAX_SEQ]; // post-softmax
float attn_out[BATCH][MAX_SEQ][D_MODEL]; // attention value aggregation output
float res1[BATCH][MAX_SEQ][D_MODEL]; // after first residual (attn + emb)
float norm2[BATCH][MAX_SEQ][D_MODEL]; // after RMS norm pre-FFN
float norm2_rms[BATCH][MAX_SEQ];
float ff_pre_relu[BATCH][MAX_SEQ][D_FF]; // FFN hidden before ReLU
float ff_hidden[BATCH][MAX_SEQ][D_FF]; // FFN hidden after ReLU
float res2[BATCH][MAX_SEQ][D_MODEL]; // after second residual (FFN + res1)
float logits[BATCH][MAX_SEQ][VOCAB];
float probs[BATCH][MAX_SEQ][VOCAB];
float loss;
} Cache;
// ============================================================
// Gradients (mirrors Model)
// ============================================================
typedef struct {
float tok_emb[VOCAB][D_MODEL];
float pos_emb[MAX_SEQ][D_MODEL];
float Wq[D_MODEL][D_MODEL];
float Wk[D_MODEL][D_MODEL];
float Wv[D_MODEL][D_MODEL];
float Wo[D_MODEL][D_MODEL];
float Wf1[D_FF][D_MODEL];
float Wf2[D_MODEL][D_FF];
float Wlm[VOCAB][D_MODEL];
} Grads;
static int param_count(void) {
return sizeof(Model) / sizeof(float);
}
// ============================================================
// Data loading
// ============================================================
#define MAX_NAMES 40000
static int all_tokens[MAX_NAMES][MAX_SEQ];
static int all_lengths[MAX_NAMES];
static int num_names = 0;
static void load_names(const char *path) {
FILE *f = fopen(path, "r");
if (!f) { fprintf(stderr, "Cannot open %s\n", path); exit(1); }
char line[256];
while (fgets(line, sizeof(line), f) && num_names < MAX_NAMES) {
int len = (int)strlen(line);
while (len > 0 && (line[len-1] == '\n' || line[len-1] == '\r')) len--;
if (len == 0) continue;
// microgpt encoding: t = [B] + [char indices] + [B]
// Where B = 26 (boundary token), chars = 0..25 (a=0, b=1, ..., z=25)
// Sequence: [BOUNDARY, char0, char1, ..., charN-1, BOUNDARY, pad...]
int *tok = all_tokens[num_names];
memset(tok, 0, MAX_SEQ * sizeof(int));
int pos = 0;
tok[pos++] = BOUNDARY; // start boundary
for (int i = 0; i < len && pos < MAX_SEQ - 1; i++) {
char c = line[i];
if (c >= 'a' && c <= 'z') tok[pos++] = c - 'a';
else if (c >= 'A' && c <= 'Z') tok[pos++] = c - 'A';
}
tok[pos++] = BOUNDARY; // end boundary
all_lengths[num_names] = pos; // total length including both boundaries
// Clamp
if (all_lengths[num_names] > MAX_SEQ)
all_lengths[num_names] = MAX_SEQ;
num_names++;
}
fclose(f);
}
// ============================================================
// Initialization (microgpt uses gauss(0, 0.08))
// ============================================================
static void gauss_init(float *w, int count, float std) {
for (int i = 0; i < count; i++)
w[i] = rand_normal() * std;
}
static void init_model(Model *m) {
memset(m, 0, sizeof(Model));
float std = 0.08f;
gauss_init((float*)m->tok_emb, VOCAB * D_MODEL, std);
gauss_init((float*)m->pos_emb, MAX_SEQ * D_MODEL, std);
gauss_init((float*)m->Wq, D_MODEL * D_MODEL, std);
gauss_init((float*)m->Wk, D_MODEL * D_MODEL, std);
gauss_init((float*)m->Wv, D_MODEL * D_MODEL, std);
gauss_init((float*)m->Wo, D_MODEL * D_MODEL, std);
gauss_init((float*)m->Wf1, D_FF * D_MODEL, std);
gauss_init((float*)m->Wf2, D_MODEL * D_FF, std);
gauss_init((float*)m->Wlm, VOCAB * D_MODEL, std);
}
// ============================================================
// Forward pass primitives
// ============================================================
static inline __attribute__((always_inline)) void rms_norm(float *out, const float *x, int n, float *rms_out) {
float sum_sq = 0.0f;
for (int i = 0; i < n; i++) sum_sq += x[i] * x[i];
float rms = sqrtf(sum_sq / (float)n + 1e-5f);
if (rms_out) *rms_out = rms;
float inv_rms = 1.0f / rms;
for (int i = 0; i < n; i++) out[i] = x[i] * inv_rms;
}
// y[j] = sum_i W[j][i] * x[i] for j=0..out_dim-1
// W is stored as W[out_dim][in_dim] (row-major), matching microgpt's li(x,w)
static inline __attribute__((always_inline)) void linear(
float * __restrict__ y, const float * __restrict__ W,
const float * __restrict__ x, int out_dim, int in_dim
) {
for (int j = 0; j < out_dim; j++) {
float32x4_t acc = vdupq_n_f32(0);
const float *row = W + j * in_dim;
for (int i = 0; i < in_dim; i += 4)
acc = vfmaq_f32(acc, vld1q_f32(row + i), vld1q_f32(x + i));
y[j] = vaddvq_f32(acc);
}
}
// y[j] = base[j] + sum_i W[j][i] * x[i] — fused matvec + residual
static inline __attribute__((always_inline)) void linear_residual(
float * __restrict__ y, const float * __restrict__ base,
const float * __restrict__ W, const float * __restrict__ x, int out_dim, int in_dim
) {
for (int j = 0; j < out_dim; j++) {
float32x4_t acc = vdupq_n_f32(0);
const float *row = W + j * in_dim;
for (int i = 0; i < in_dim; i += 4)
acc = vfmaq_f32(acc, vld1q_f32(row + i), vld1q_f32(x + i));
y[j] = base[j] + vaddvq_f32(acc);
}
}
// Fused linear + ReLU: pre_relu[j] = W@x, hidden[j] = max(0, pre_relu[j])
static inline __attribute__((always_inline)) void linear_relu(
float * __restrict__ pre_relu, float * __restrict__ hidden,
const float * __restrict__ W, const float * __restrict__ x, int out_dim, int in_dim
) {
for (int j = 0; j < out_dim; j++) {
float32x4_t acc = vdupq_n_f32(0);
const float *row = W + j * in_dim;
for (int i = 0; i < in_dim; i += 4)
acc = vfmaq_f32(acc, vld1q_f32(row + i), vld1q_f32(x + i));
float val = vaddvq_f32(acc);
pre_relu[j] = val;
hidden[j] = val > 0.0f ? val : 0.0f;
}
}
// 2-position batched linear: shares weight loads across 2 input vectors
static inline __attribute__((always_inline)) void linear_2(
float * __restrict__ y0, float * __restrict__ y1,
const float * __restrict__ W,
const float * __restrict__ x0, const float * __restrict__ x1,
int out_dim, int in_dim
) {
for (int j = 0; j < out_dim; j++) {
float32x4_t a0 = vdupq_n_f32(0), a1 = vdupq_n_f32(0);
const float *row = W + j * in_dim;
for (int i = 0; i < in_dim; i += 4) {
float32x4_t w = vld1q_f32(row + i);
a0 = vfmaq_f32(a0, w, vld1q_f32(x0 + i));
a1 = vfmaq_f32(a1, w, vld1q_f32(x1 + i));
}
y0[j] = vaddvq_f32(a0);
y1[j] = vaddvq_f32(a1);
}
}
// 2-position batched linear + ReLU: shares weight loads across 2 input vectors
static inline __attribute__((always_inline)) void linear_relu_2(
float * __restrict__ pr0, float * __restrict__ h0,
float * __restrict__ pr1, float * __restrict__ h1,
const float * __restrict__ W,
const float * __restrict__ x0, const float * __restrict__ x1,
int out_dim, int in_dim
) {
for (int j = 0; j < out_dim; j++) {
float32x4_t a0 = vdupq_n_f32(0), a1 = vdupq_n_f32(0);
const float *row = W + j * in_dim;
for (int i = 0; i < in_dim; i += 4) {
float32x4_t w = vld1q_f32(row + i);
a0 = vfmaq_f32(a0, w, vld1q_f32(x0 + i));
a1 = vfmaq_f32(a1, w, vld1q_f32(x1 + i));
}
float v0 = vaddvq_f32(a0), v1 = vaddvq_f32(a1);
pr0[j] = v0; h0[j] = v0 > 0.0f ? v0 : 0.0f;
pr1[j] = v1; h1[j] = v1 > 0.0f ? v1 : 0.0f;
}
}
// 2-position batched linear + residual: shares weight loads across 2 input vectors
static inline __attribute__((always_inline)) void linear_residual_2(
float * __restrict__ y0, const float * __restrict__ b0,
float * __restrict__ y1, const float * __restrict__ b1,
const float * __restrict__ W,
const float * __restrict__ x0, const float * __restrict__ x1,
int out_dim, int in_dim
) {
for (int j = 0; j < out_dim; j++) {
float32x4_t a0 = vdupq_n_f32(0), a1 = vdupq_n_f32(0);
const float *row = W + j * in_dim;
for (int i = 0; i < in_dim; i += 4) {
float32x4_t w = vld1q_f32(row + i);
a0 = vfmaq_f32(a0, w, vld1q_f32(x0 + i));
a1 = vfmaq_f32(a1, w, vld1q_f32(x1 + i));
}
y0[j] = b0[j] + vaddvq_f32(a0);
y1[j] = b1[j] + vaddvq_f32(a1);
}
}
// Fast scalar exp approximation (relative error ~1e-4, matching the vector version)
static inline float fast_expf_s(float x) {
x *= 1.442695041f; // log2(e)
if (x < -126.0f) x = -126.0f;
if (x > 126.0f) x = 126.0f;
float xf = __builtin_floorf(x);
float r = x - xf;
int xi = (int)xf;
union { float f; int32_t i; } u;
u.i = (xi + 127) << 23;
float p = 0.0558011f;
p = 0.2402265f + p * r;
p = 0.6931472f + p * r;
p = 1.0f + p * r;
return u.f * p;
}
// Fast vectorized exp approximation (relative error ~1e-4, sufficient for softmax)
// Uses exp(x) = exp2(x * log2(e)) with polynomial refinement
static inline float32x4_t fast_expq_f32(float32x4_t x) {
const float32x4_t log2e = vdupq_n_f32(1.442695041f);
x = vmulq_f32(x, log2e); // x * log2(e) = log2(exp(x))
// Clamp to avoid overflow/underflow
x = vmaxq_f32(x, vdupq_n_f32(-126.0f));
x = vminq_f32(x, vdupq_n_f32(126.0f));
// Split into integer and fractional parts
float32x4_t xf = vrndmq_f32(x); // floor
float32x4_t r = vsubq_f32(x, xf); // fractional part [0, 1)
int32x4_t xi = vcvtq_s32_f32(xf);
// 2^integer via bit shift into float exponent
int32x4_t pow2i = vshlq_n_s32(vaddq_s32(xi, vdupq_n_s32(127)), 23);
float32x4_t pow2f = vreinterpretq_f32_s32(pow2i);
// 2^fractional via degree-3 minimax polynomial on [0, 1)
// p(r) ≈ 1 + 0.6931472*r + 0.2402265*r^2 + 0.0558011*r^3
float32x4_t p = vdupq_n_f32(0.0558011f);
p = vfmaq_f32(vdupq_n_f32(0.2402265f), p, r);
p = vfmaq_f32(vdupq_n_f32(0.6931472f), p, r);
p = vfmaq_f32(vdupq_n_f32(1.0f), p, r);
return vmulq_f32(pow2f, p);
}
static inline __attribute__((always_inline)) void softmax(float *out, const float *x, int n) {
float max_val = x[0];
for (int i = 1; i < n; i++)
if (x[i] > max_val) max_val = x[i];
float sum = 0.0f;
#if MAX_SEQ == 16
if (n == MAX_SEQ) {
// Specialized Neon path for n=16 (attention softmax)
float32x4_t vmax = vdupq_n_f32(max_val);
float32x4_t v0 = fast_expq_f32(vsubq_f32(vld1q_f32(x), vmax));
float32x4_t v1 = fast_expq_f32(vsubq_f32(vld1q_f32(x+4), vmax));
float32x4_t v2 = fast_expq_f32(vsubq_f32(vld1q_f32(x+8), vmax));
float32x4_t v3 = fast_expq_f32(vsubq_f32(vld1q_f32(x+12), vmax));
sum = vaddvq_f32(vaddq_f32(vaddq_f32(v0, v1), vaddq_f32(v2, v3)));
float32x4_t inv = vdupq_n_f32(1.0f / sum);
vst1q_f32(out, vmulq_f32(v0, inv));
vst1q_f32(out+4, vmulq_f32(v1, inv));
vst1q_f32(out+8, vmulq_f32(v2, inv));
vst1q_f32(out+12, vmulq_f32(v3, inv));
return;
}
#endif
{
float32x4_t vmax = vdupq_n_f32(max_val);
float32x4_t vsum = vdupq_n_f32(0.0f);
int i;
for (i = 0; i + 3 < n; i += 4) {
float32x4_t v = fast_expq_f32(vsubq_f32(vld1q_f32(x + i), vmax));
vst1q_f32(out + i, v);
vsum = vaddq_f32(vsum, v);
}
sum = vaddvq_f32(vsum);
for (; i < n; i++) {
out[i] = expf(x[i] - max_val);
sum += out[i];
}
}
float inv_sum = 1.0f / sum;
for (int i = 0; i < n; i++) out[i] *= inv_sum;
}
// Transposed weight copies for backward dot-product matvecs (and SME2 FMOPA).
// Maintained outside Model struct so Adam doesn't touch them.
static float Wq_T[D_MODEL][D_MODEL];
static float Wk_T[D_MODEL][D_MODEL];
static float Wv_T[D_MODEL][D_MODEL];
static float Wo_T[D_MODEL][D_MODEL];
static float Wf1_T[D_MODEL][D_FF]; // Wf1[D_FF][D_MODEL] transposed
static float Wf2_T[D_FF][D_MODEL]; // Wf2[D_MODEL][D_FF] transposed
static void sync_transposed_weights(Model *m) {
for (int i = 0; i < D_MODEL; i++)
for (int j = 0; j < D_MODEL; j++) {
Wq_T[j][i] = m->Wq[i][j];
Wk_T[j][i] = m->Wk[i][j];
Wv_T[j][i] = m->Wv[i][j];
Wo_T[j][i] = m->Wo[i][j];
}
for (int i = 0; i < D_FF; i++)
for (int j = 0; j < D_MODEL; j++)
Wf1_T[j][i] = m->Wf1[i][j];
for (int i = 0; i < D_MODEL; i++)
for (int j = 0; j < D_FF; j++)
Wf2_T[j][i] = m->Wf2[i][j];
}
// ============================================================
// SME2 FMOPA matmul functions (generalized for any D_MODEL multiple of 16)
// ============================================================
#if USE_SME2
// C[M][16] = W_T[K][M] @ X[K][16] using tiled FMOPA
// FMOPA: ZA[i][j] += left[i] * right[j]
// For tile bi: ZA[i_local][j] += W_T[k][bi+i_local] * X[k][j]
// = W[bi+i_local][k] * X[k][j] ✓
// QKV projections in one streaming session
__arm_locally_streaming __arm_new("za")
static void sme2_qkv_project(
float *Q_out, float *K_out, float *V_out, const float *X
) {
svbool_t pred = svptrue_b32();
// Q = Wq @ X: Q[D_MODEL][MAX_SEQ]
for (int bi = 0; bi < D_MODEL; bi += 16) {
svzero_za();
for (int k = 0; k < D_MODEL; k++) {
svfloat32_t wt = svld1_f32(pred, (float*)Wq_T + k * D_MODEL + bi);
svfloat32_t x = svld1_f32(pred, X + k * MAX_SEQ);
svmopa_za32_f32_m(0, pred, pred, wt, x);
}
for (int i = 0; i < 16; i++) {
svfloat32_t row = svread_hor_za32_f32_m(svdup_f32(0), pred, 0, i);
svst1_f32(pred, Q_out + (bi + i) * MAX_SEQ, row);
}
}
// K = Wk @ X
for (int bi = 0; bi < D_MODEL; bi += 16) {
svzero_za();
for (int k = 0; k < D_MODEL; k++) {
svfloat32_t wt = svld1_f32(pred, (float*)Wk_T + k * D_MODEL + bi);
svfloat32_t x = svld1_f32(pred, X + k * MAX_SEQ);
svmopa_za32_f32_m(0, pred, pred, wt, x);
}
for (int i = 0; i < 16; i++) {
svfloat32_t row = svread_hor_za32_f32_m(svdup_f32(0), pred, 0, i);
svst1_f32(pred, K_out + (bi + i) * MAX_SEQ, row);
}
}
// V = Wv @ X
for (int bi = 0; bi < D_MODEL; bi += 16) {
svzero_za();
for (int k = 0; k < D_MODEL; k++) {
svfloat32_t wt = svld1_f32(pred, (float*)Wv_T + k * D_MODEL + bi);
svfloat32_t x = svld1_f32(pred, X + k * MAX_SEQ);
svmopa_za32_f32_m(0, pred, pred, wt, x);
}
for (int i = 0; i < 16; i++) {
svfloat32_t row = svread_hor_za32_f32_m(svdup_f32(0), pred, 0, i);
svst1_f32(pred, V_out + (bi + i) * MAX_SEQ, row);
}
}
}
// O projection: O[D_MODEL][MAX_SEQ] = Wo @ X
__arm_locally_streaming __arm_new("za")
static void sme2_o_project(float *O_out, const float *X) {
svbool_t pred = svptrue_b32();
for (int bi = 0; bi < D_MODEL; bi += 16) {
svzero_za();
for (int k = 0; k < D_MODEL; k++) {
svfloat32_t wt = svld1_f32(pred, (float*)Wo_T + k * D_MODEL + bi);
svfloat32_t x = svld1_f32(pred, X + k * MAX_SEQ);
svmopa_za32_f32_m(0, pred, pred, wt, x);
}
for (int i = 0; i < 16; i++) {
svfloat32_t row = svread_hor_za32_f32_m(svdup_f32(0), pred, 0, i);
svst1_f32(pred, O_out + (bi + i) * MAX_SEQ, row);
}
}
}
// FFN expand: H[D_FF][MAX_SEQ] = Wf1[D_FF][D_MODEL] @ X[D_MODEL][MAX_SEQ]
// Using Wf1_T[D_MODEL][D_FF]. Tiles over D_FF output rows.
__arm_locally_streaming __arm_new("za")
static void sme2_ffn_expand(float *H, const float *X) {
svbool_t pred = svptrue_b32();
for (int bi = 0; bi < D_FF; bi += 16) {
svzero_za();
for (int k = 0; k < D_MODEL; k++) {
svfloat32_t wt = svld1_f32(pred, (float*)Wf1_T + k * D_FF + bi);
svfloat32_t x = svld1_f32(pred, X + k * MAX_SEQ);
svmopa_za32_f32_m(0, pred, pred, wt, x);
}
for (int i = 0; i < 16; i++) {
svfloat32_t row = svread_hor_za32_f32_m(svdup_f32(0), pred, 0, i);
svst1_f32(pred, H + (bi + i) * MAX_SEQ, row);
}
}
}
// FFN contract: Y[D_MODEL][MAX_SEQ] = Wf2[D_MODEL][D_FF] @ H[D_FF][MAX_SEQ]
// Using Wf2_T[D_FF][D_MODEL]. Tiles over D_MODEL output rows.
__arm_locally_streaming __arm_new("za")
static void sme2_ffn_contract(float *Y, const float *H) {
svbool_t pred = svptrue_b32();
for (int bi = 0; bi < D_MODEL; bi += 16) {
svzero_za();
for (int k = 0; k < D_FF; k++) {
svfloat32_t wt = svld1_f32(pred, (float*)Wf2_T + k * D_MODEL + bi);
svfloat32_t h = svld1_f32(pred, H + k * MAX_SEQ);
svmopa_za32_f32_m(0, pred, pred, wt, h);
}
for (int i = 0; i < 16; i++) {
svfloat32_t row = svread_hor_za32_f32_m(svdup_f32(0), pred, 0, i);
svst1_f32(pred, Y + (bi + i) * MAX_SEQ, row);
}
}
}
// ---- Backward helpers ----
// General outer product sum: dW[M][N] = sum_{t=0}^{MAX_SEQ-1} left[t][:M] outer right[t][:N]
// left is [MAX_SEQ][M], right is [MAX_SEQ][N]
__arm_locally_streaming __arm_new("za")
static void sme2_outer_sum(float *dW, const float *left, const float *right, int M, int N) {
svbool_t pred = svptrue_b32();
for (int bi = 0; bi < M; bi += 16) {
for (int bj = 0; bj < N; bj += 16) {
svzero_za();
for (int t = 0; t < MAX_SEQ; t++) {
svfloat32_t l = svld1_f32(pred, left + t * M + bi);
svfloat32_t r = svld1_f32(pred, right + t * N + bj);
svmopa_za32_f32_m(0, pred, pred, l, r);
}
for (int i = 0; i < 16; i++) {
svfloat32_t row = svread_hor_za32_f32_m(svdup_f32(0), pred, 0, i);
svst1_f32(pred, dW + (bi + i) * N + bj, row);
}
}
}
}
// General batched matmul: C[M][MAX_SEQ] = W^T @ X[K][MAX_SEQ]
// W_T_flat points to the "transposed weight" stored as [K][M] (row-major).
// For forward: pass explicit transposed copy (Wq_T, etc.)
// For backward input grads: pass ORIGINAL weight (Wf2, Wf1, Wo) directly.
__arm_locally_streaming __arm_new("za")
static void sme2_matmul(float *C, const float *W_T_flat, const float *X, int M, int K) {
svbool_t pred = svptrue_b32();
for (int bi = 0; bi < M; bi += 16) {
svzero_za();
for (int k = 0; k < K; k++) {
svfloat32_t w = svld1_f32(pred, W_T_flat + k * M + bi);
svfloat32_t x = svld1_f32(pred, X + k * MAX_SEQ);
svmopa_za32_f32_m(0, pred, pred, w, x);
}
for (int i = 0; i < 16; i++) {
svfloat32_t row = svread_hor_za32_f32_m(svdup_f32(0), pred, 0, i);
svst1_f32(pred, C + (bi + i) * MAX_SEQ, row);
}
}
}
// Batched QKV input gradient:
// dnorm1[D_MODEL][MAX_SEQ] = Wq_T @ dQ_T + Wk_T @ dK_T + Wv_T @ dV_T
// All inputs/outputs in [D_MODEL][MAX_SEQ] layout.
__arm_locally_streaming __arm_new("za")
static void sme2_qkv_input_grad(
float *dnorm1, const float *dQ_T, const float *dK_T, const float *dV_T
) {
svbool_t pred = svptrue_b32();
for (int bi = 0; bi < D_MODEL; bi += 16) {
svzero_za();
// Accumulate Wq_T @ dQ_T + Wk_T @ dK_T + Wv_T @ dV_T
for (int k = 0; k < D_MODEL; k++) {
svfloat32_t wq = svld1_f32(pred, (float*)Wq_T + k * D_MODEL + bi);
svfloat32_t dq = svld1_f32(pred, dQ_T + k * MAX_SEQ);
svmopa_za32_f32_m(0, pred, pred, wq, dq);
}
for (int k = 0; k < D_MODEL; k++) {
svfloat32_t wk = svld1_f32(pred, (float*)Wk_T + k * D_MODEL + bi);
svfloat32_t dk = svld1_f32(pred, dK_T + k * MAX_SEQ);
svmopa_za32_f32_m(0, pred, pred, wk, dk);
}
for (int k = 0; k < D_MODEL; k++) {
svfloat32_t wv = svld1_f32(pred, (float*)Wv_T + k * D_MODEL + bi);
svfloat32_t dv = svld1_f32(pred, dV_T + k * MAX_SEQ);
svmopa_za32_f32_m(0, pred, pred, wv, dv);
}
for (int i = 0; i < 16; i++) {
svfloat32_t row = svread_hor_za32_f32_m(svdup_f32(0), pred, 0, i);
svst1_f32(pred, dnorm1 + (bi + i) * MAX_SEQ, row);
}
}
}
// Fused backward: all 6 weight grad outer-product sums + QKV input grads
// in a single streaming session (eliminates 7 SMSTART/SMSTOP transitions per batch item).
// Accumulates directly into Grads using SVE loads/adds/stores.
__arm_locally_streaming __arm_new("za")
static void sme2_backward_wgrads_and_input_grads(
Grads *g, float *dnorm1_out, // [D_MODEL][MAX_SEQ]
const float *dQ, const float *dK, const float *dV, // [MAX_SEQ][D_MODEL]
const float *norm1_b, // [MAX_SEQ][D_MODEL]
const float *do_proj_all, const float *attn_out_b, // [MAX_SEQ][D_MODEL]
const float *dff_out_all, const float *ff_hidden_b, // [MAX_SEQ][D_MODEL], [MAX_SEQ][D_FF]
const float *dff_hidden_all, const float *norm2_b // [MAX_SEQ][D_FF], [MAX_SEQ][D_MODEL]
) {
svbool_t pred = svptrue_b32();
// --- Helper macro: outer-product sum with accumulation into grad array ---
// dW[M][N] += sum_t left[t][:M] outer right[t][:N]
#define OUTER_SUM_ACCUM(dW, left, right, M, N) \
for (int bi = 0; bi < (M); bi += 16) { \
for (int bj = 0; bj < (N); bj += 16) { \
svzero_za(); \
for (int t = 0; t < MAX_SEQ; t++) { \
svfloat32_t l = svld1_f32(pred, (left) + t * (M) + bi); \
svfloat32_t r = svld1_f32(pred, (right) + t * (N) + bj); \
svmopa_za32_f32_m(0, pred, pred, l, r); \
} \
for (int i = 0; i < 16; i++) { \
svfloat32_t row = svread_hor_za32_f32_m(svdup_f32(0), pred, 0, i); \
svfloat32_t cur = svld1_f32(pred, (dW) + (bi + i) * (N) + bj); \
svst1_f32(pred, (dW) + (bi + i) * (N) + bj, svadd_f32_x(pred, cur, row)); \
} \
} \
}
// 1. dWq += sum_t outer(dQ[t], norm1[t])
OUTER_SUM_ACCUM((float*)g->Wq, dQ, norm1_b, D_MODEL, D_MODEL)
// 2. dWk += sum_t outer(dK[t], norm1[t])
OUTER_SUM_ACCUM((float*)g->Wk, dK, norm1_b, D_MODEL, D_MODEL)
// 3. dWv += sum_t outer(dV[t], norm1[t])
OUTER_SUM_ACCUM((float*)g->Wv, dV, norm1_b, D_MODEL, D_MODEL)
// 4. dWo += sum_t outer(do_proj[t], attn_out[t])
OUTER_SUM_ACCUM((float*)g->Wo, do_proj_all, attn_out_b, D_MODEL, D_MODEL)
// 5. dWf2 += sum_t outer(dff_out[t], ff_hidden[t])
OUTER_SUM_ACCUM((float*)g->Wf2, dff_out_all, ff_hidden_b, D_MODEL, D_FF)
// 6. dWf1 += sum_t outer(dff_hidden[t], norm2[t])
OUTER_SUM_ACCUM((float*)g->Wf1, dff_hidden_all, norm2_b, D_FF, D_MODEL)
#undef OUTER_SUM_ACCUM
// --- QKV input grads: transpose dQ/dK/dV then compute dnorm1 ---
// Transpose [MAX_SEQ][D_MODEL] → [D_MODEL][MAX_SEQ] using SVE
float dQ_T[D_MODEL][MAX_SEQ], dK_T[D_MODEL][MAX_SEQ], dV_T[D_MODEL][MAX_SEQ];
// Scalar transpose (valid in streaming mode — avoids SMSTOP/SMSTART)
for (int t = 0; t < MAX_SEQ; t++)
for (int d = 0; d < D_MODEL; d++) {
dQ_T[d][t] = dQ[t * D_MODEL + d];
dK_T[d][t] = dK[t * D_MODEL + d];
dV_T[d][t] = dV[t * D_MODEL + d];
}
// dnorm1[D_MODEL][MAX_SEQ] = Wq_T @ dQ_T + Wk_T @ dK_T + Wv_T @ dV_T
for (int bi = 0; bi < D_MODEL; bi += 16) {
svzero_za();
for (int k = 0; k < D_MODEL; k++) {
svfloat32_t wq = svld1_f32(pred, (float*)Wq_T + k * D_MODEL + bi);
svfloat32_t dq = svld1_f32(pred, (float*)dQ_T + k * MAX_SEQ);
svmopa_za32_f32_m(0, pred, pred, wq, dq);
}
for (int k = 0; k < D_MODEL; k++) {
svfloat32_t wk = svld1_f32(pred, (float*)Wk_T + k * D_MODEL + bi);
svfloat32_t dk = svld1_f32(pred, (float*)dK_T + k * MAX_SEQ);
svmopa_za32_f32_m(0, pred, pred, wk, dk);
}
for (int k = 0; k < D_MODEL; k++) {
svfloat32_t wv = svld1_f32(pred, (float*)Wv_T + k * D_MODEL + bi);
svfloat32_t dv = svld1_f32(pred, (float*)dV_T + k * MAX_SEQ);
svmopa_za32_f32_m(0, pred, pred, wv, dv);
}
for (int i = 0; i < 16; i++) {
svfloat32_t row = svread_hor_za32_f32_m(svdup_f32(0), pred, 0, i);
svst1_f32(pred, dnorm1_out + (bi + i) * MAX_SEQ, row);
}
}
}
#endif // USE_SME2
#if !USE_SME2
#endif // !USE_SME2
// ============================================================
// Forward pass
// Matches microgpt flow:
// x = rms(tok_emb[t] + pos_emb[p])
// r = x; y = rms(x)
// QKV on y, attention, O proj
// x = o_proj + r
// r = x; FFN(rms(x)) + r
// logits = lm(x)
// ============================================================
static float forward(Model *m, Cache *c) {
#if USE_SME2
// Operation-sequential: process all batch items per operation for L1 cache reuse
// Weights (~210 KB at d=64) exceed L1 (128 KB), so keeping one weight set hot helps
// 1-3. Embeddings + RMS norms for all batch items
for (int b = 0; b < BATCH; b++) {
int slen = c->seq_lens[b];
for (int t = 0; t < slen; t++) {
int tok = c->tokens[b][t];
for (int d = 0; d < D_MODEL; d++)
c->raw_emb[b][t][d] = m->tok_emb[tok][d] + m->pos_emb[t][d];
rms_norm(c->emb[b][t], c->raw_emb[b][t], D_MODEL, &c->emb_rms[b][t]);
rms_norm(c->norm1[b][t], c->emb[b][t], D_MODEL, &c->norm1_rms[b][t]);
}
}
// 4. QKV projections for all batch items (Wq_T, Wk_T, Wv_T stay hot in L1)
for (int b = 0; b < BATCH; b++) {
float X_T[D_MODEL][MAX_SEQ], Q_T[D_MODEL][MAX_SEQ], K_T[D_MODEL][MAX_SEQ], V_T[D_MODEL][MAX_SEQ];
for (int t = 0; t < MAX_SEQ; t++)
for (int d = 0; d < D_MODEL; d++)
X_T[d][t] = c->norm1[b][t][d];
sme2_qkv_project((float*)Q_T, (float*)K_T, (float*)V_T, (float*)X_T);
for (int t = 0; t < MAX_SEQ; t++)
for (int d = 0; d < D_MODEL; d++) {
c->Q[b][t][d] = Q_T[d][t];
c->K[b][t][d] = K_T[d][t];
c->V[b][t][d] = V_T[d][t];
}
}
// 5. Attention for all batch items (no weight matrices, just activations)
for (int b = 0; b < BATCH; b++) {
int slen = c->seq_lens[b];
for (int h = 0; h < N_HEADS; h++) {
int hoff = h * HEAD_DIM;
for (int t = 0; t < slen; t++) {
float max_score = -1e30f;
#if HEAD_DIM == 4
float32x4_t qt = vld1q_f32(&c->Q[b][t][hoff]);
for (int s = 0; s <= t; s++) {
float32x4_t ks = vld1q_f32(&c->K[b][s][hoff]);
float score = vaddvq_f32(vmulq_f32(qt, ks)) * INV_SQRT_HD;
c->attn_scores[b][h][t][s] = score;
if (score > max_score) max_score = score;
}
float sum = 0.0f;
float32x4_t vacc = vdupq_n_f32(0.0f);
for (int s = 0; s <= t; s++) {
float e = fast_expf_s(c->attn_scores[b][h][t][s] - max_score);
c->attn_scores[b][h][t][s] = e;
sum += e;
vacc = vfmaq_n_f32(vacc, vld1q_f32(&c->V[b][s][hoff]), e);
}
float inv_sum = 1.0f / sum;
for (int s = 0; s <= t; s++)
c->attn_scores[b][h][t][s] *= inv_sum;
vst1q_f32(&c->attn_out[b][t][hoff], vmulq_n_f32(vacc, inv_sum));
#else
for (int s = 0; s <= t; s++) {
float score = 0.0f;
for (int d = 0; d < HEAD_DIM; d++)
score += c->Q[b][t][hoff + d] * c->K[b][s][hoff + d];
score *= INV_SQRT_HD;
c->attn_scores[b][h][t][s] = score;
if (score > max_score) max_score = score;
}
float sum = 0.0f;
for (int d = 0; d < HEAD_DIM; d++) c->attn_out[b][t][hoff + d] = 0.0f;
for (int s = 0; s <= t; s++) {
float e = fast_expf_s(c->attn_scores[b][h][t][s] - max_score);
c->attn_scores[b][h][t][s] = e;
sum += e;
for (int d = 0; d < HEAD_DIM; d++)
c->attn_out[b][t][hoff + d] += e * c->V[b][s][hoff + d];
}
float inv_sum = 1.0f / sum;
for (int s = 0; s <= t; s++)
c->attn_scores[b][h][t][s] *= inv_sum;
for (int d = 0; d < HEAD_DIM; d++)
c->attn_out[b][t][hoff + d] *= inv_sum;
#endif
}
}
}
// 6. O projection + residual for all batch items (Wo_T stays hot)
for (int b = 0; b < BATCH; b++) {
int slen = c->seq_lens[b];
float A_T[D_MODEL][MAX_SEQ], O_T[D_MODEL][MAX_SEQ];
for (int t = 0; t < MAX_SEQ; t++)
for (int d = 0; d < D_MODEL; d++)
A_T[d][t] = c->attn_out[b][t][d];
sme2_o_project((float*)O_T, (float*)A_T);
for (int t = 0; t < slen; t++)
for (int d = 0; d < D_MODEL; d++)
c->res1[b][t][d] = c->emb[b][t][d] + O_T[d][t];
}
// 7. RMS norm (pre-FFN) for all batch items
for (int b = 0; b < BATCH; b++) {
int slen = c->seq_lens[b];
for (int t = 0; t < slen; t++)
rms_norm(c->norm2[b][t], c->res1[b][t], D_MODEL, &c->norm2_rms[b][t]);
}
// 8. FFN for all batch items (Wf1_T, Wf2_T stay hot)
for (int b = 0; b < BATCH; b++) {
int slen = c->seq_lens[b];
float N2_T[D_MODEL][MAX_SEQ];
for (int t = 0; t < MAX_SEQ; t++)
for (int d = 0; d < D_MODEL; d++)
N2_T[d][t] = c->norm2[b][t][d];
float H[D_FF][MAX_SEQ];
sme2_ffn_expand((float*)H, (float*)N2_T);
for (int t = 0; t < slen; t++) {
for (int j = 0; j < D_FF; j++) {
c->ff_pre_relu[b][t][j] = H[j][t];
float v = H[j][t] > 0.0f ? H[j][t] : 0.0f;
c->ff_hidden[b][t][j] = v;
H[j][t] = v;
}
}
float Y[D_MODEL][MAX_SEQ];
sme2_ffn_contract((float*)Y, (float*)H);
for (int t = 0; t < slen; t++)
for (int d = 0; d < D_MODEL; d++)
c->res2[b][t][d] = c->res1[b][t][d] + Y[d][t];
}
// 9. LM head + softmax for all batch items (Wlm stays hot)
for (int b = 0; b < BATCH; b++) {
int slen = c->seq_lens[b];
int t = 0;
for (; t + 1 < slen; t += 2) {
linear_2(c->logits[b][t], c->logits[b][t+1], (float*)m->Wlm, c->res2[b][t], c->res2[b][t+1], VOCAB, D_MODEL);
softmax(c->probs[b][t], c->logits[b][t], VOCAB);
softmax(c->probs[b][t+1], c->logits[b][t+1], VOCAB);
}
if (t < slen) {
linear(c->logits[b][t], (float*)m->Wlm, c->res2[b][t], VOCAB, D_MODEL);
softmax(c->probs[b][t], c->logits[b][t], VOCAB);
}
}
#else
// Batch-sequential for non-SME2 (data fits L1 at small D_MODEL)
for (int b = 0; b < BATCH; b++) {
int slen = c->seq_lens[b];
// 1-3. Embeddings + RMS norms (element-wise, not matmuls)
for (int t = 0; t < slen; t++) {
int tok = c->tokens[b][t];
for (int d = 0; d < D_MODEL; d++)
c->raw_emb[b][t][d] = m->tok_emb[tok][d] + m->pos_emb[t][d];
rms_norm(c->emb[b][t], c->raw_emb[b][t], D_MODEL, &c->emb_rms[b][t]);
rms_norm(c->norm1[b][t], c->emb[b][t], D_MODEL, &c->norm1_rms[b][t]);
}
// 4. QKV projections
{
int t = 0;
for (; t + 1 < slen; t += 2) {
linear_2(c->Q[b][t], c->Q[b][t+1], (float*)m->Wq, c->norm1[b][t], c->norm1[b][t+1], D_MODEL, D_MODEL);
linear_2(c->K[b][t], c->K[b][t+1], (float*)m->Wk, c->norm1[b][t], c->norm1[b][t+1], D_MODEL, D_MODEL);
linear_2(c->V[b][t], c->V[b][t+1], (float*)m->Wv, c->norm1[b][t], c->norm1[b][t+1], D_MODEL, D_MODEL);
}
if (t < slen) {
linear(c->Q[b][t], (float*)m->Wq, c->norm1[b][t], D_MODEL, D_MODEL);
linear(c->K[b][t], (float*)m->Wk, c->norm1[b][t], D_MODEL, D_MODEL);
linear(c->V[b][t], (float*)m->Wv, c->norm1[b][t], D_MODEL, D_MODEL);
}
}
// 5. Multi-head causal attention (fused: QK dots + softmax + V weighted sum)
for (int h = 0; h < N_HEADS; h++) {
int hoff = h * HEAD_DIM;
for (int t = 0; t < slen; t++) {
float max_score = -1e30f;
#if HEAD_DIM == 4
float32x4_t qt = vld1q_f32(&c->Q[b][t][hoff]);
for (int s = 0; s <= t; s++) {
float32x4_t ks = vld1q_f32(&c->K[b][s][hoff]);
float score = vaddvq_f32(vmulq_f32(qt, ks)) * INV_SQRT_HD;
c->attn_scores[b][h][t][s] = score;
if (score > max_score) max_score = score;
}
float sum = 0.0f;
float32x4_t vacc = vdupq_n_f32(0.0f);
for (int s = 0; s <= t; s++) {
float e = fast_expf_s(c->attn_scores[b][h][t][s] - max_score);
c->attn_scores[b][h][t][s] = e;
sum += e;
vacc = vfmaq_n_f32(vacc, vld1q_f32(&c->V[b][s][hoff]), e);
}
float inv_sum = 1.0f / sum;
for (int s = 0; s <= t; s++)
c->attn_scores[b][h][t][s] *= inv_sum;
vst1q_f32(&c->attn_out[b][t][hoff], vmulq_n_f32(vacc, inv_sum));
#else
for (int s = 0; s <= t; s++) {
float score = 0.0f;
for (int d = 0; d < HEAD_DIM; d++)
score += c->Q[b][t][hoff + d] * c->K[b][s][hoff + d];
score *= INV_SQRT_HD;
c->attn_scores[b][h][t][s] = score;
if (score > max_score) max_score = score;
}
float sum = 0.0f;
for (int d = 0; d < HEAD_DIM; d++) c->attn_out[b][t][hoff + d] = 0.0f;
for (int s = 0; s <= t; s++) {
float e = fast_expf_s(c->attn_scores[b][h][t][s] - max_score);
c->attn_scores[b][h][t][s] = e;
sum += e;
for (int d = 0; d < HEAD_DIM; d++)
c->attn_out[b][t][hoff + d] += e * c->V[b][s][hoff + d];
}
float inv_sum = 1.0f / sum;
for (int s = 0; s <= t; s++)
c->attn_scores[b][h][t][s] *= inv_sum;
for (int d = 0; d < HEAD_DIM; d++)
c->attn_out[b][t][hoff + d] *= inv_sum;
#endif
}
}
// 6. O projection + residual
{
int t = 0;
for (; t + 1 < slen; t += 2)
linear_residual_2(c->res1[b][t], c->emb[b][t],
c->res1[b][t+1], c->emb[b][t+1],
(float*)m->Wo, c->attn_out[b][t], c->attn_out[b][t+1], D_MODEL, D_MODEL);
if (t < slen)
linear_residual(c->res1[b][t], c->emb[b][t], (float*)m->Wo, c->attn_out[b][t], D_MODEL, D_MODEL);
}
// 7. RMS norm (pre-FFN)
for (int t = 0; t < slen; t++)
rms_norm(c->norm2[b][t], c->res1[b][t], D_MODEL, &c->norm2_rms[b][t]);
// 8. FFN: expand + ReLU + contract + residual
{
int t = 0;
for (; t + 1 < slen; t += 2) {
linear_relu_2(c->ff_pre_relu[b][t], c->ff_hidden[b][t],
c->ff_pre_relu[b][t+1], c->ff_hidden[b][t+1],
(float*)m->Wf1, c->norm2[b][t], c->norm2[b][t+1], D_FF, D_MODEL);
linear_residual_2(c->res2[b][t], c->res1[b][t],
c->res2[b][t+1], c->res1[b][t+1],
(float*)m->Wf2, c->ff_hidden[b][t], c->ff_hidden[b][t+1], D_MODEL, D_FF);
}
if (t < slen) {
linear_relu(c->ff_pre_relu[b][t], c->ff_hidden[b][t], (float*)m->Wf1, c->norm2[b][t], D_FF, D_MODEL);
linear_residual(c->res2[b][t], c->res1[b][t], (float*)m->Wf2, c->ff_hidden[b][t], D_MODEL, D_FF);
}
}
// 9. LM head + softmax