Repository navigation
Expand file tree
/
Copy pathqwen4.metal
More file actions
5700 lines (5482 loc) · 277 KB
/
Copy pathqwen4.metal
File metadata and controls
5700 lines (5482 loc) · 277 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
/* Qwen3.8-Flash-Next kernels: hyper-connection mix/combine, gated delta net
* (conv, scan, gated norm), PLE n-gram gate + dilated conv, softmax top-k
* router, QSA indexer, gated GQA attention, routed/dense expert matmuls and
* the MTP input. Transients are f32; the GDN state is f32 [head][dv][dk]
* so each simdgroup lane owns a contiguous dk slice. Math mirrors the
* qwen4_ref_* scalar reference in ds4.c. */
static inline float qwen4_sigmoid(float x) {
if (x >= 0.0f) {
const float e = exp(-x);
return 1.0f / (1.0f + e);
}
const float e = exp(x);
return e / (1.0f + e);
}
static inline float qwen4_softplus(float x) {
if (x > 20.0f) return x;
if (x < -20.0f) return exp(x);
return log(1.0f + exp(x));
}
static inline float qwen4_silu(float x) {
return x * qwen4_sigmoid(x);
}
static inline float qwen4_row_dot(device const char *row, device const float *x,
uint weight_type, uint in_dim, ushort tiisg);
/* --- hyper-connections -------------------------------------------------- */
struct ds4_metal_args_qwen4_hc_norm {
uint32_t n_tokens;
uint32_t n_embd;
uint32_t n_hc;
uint32_t n_inject; /* 0 or n_hc: inject rows dotted with this stream's xn */
float eps;
uint32_t pad0;
uint32_t pad1;
uint32_t pad2;
};
#define QWEN4_HC_CHUNKS 8 /* threadgroups per stream; each recomputes the stream RMS */
/* element readers for the hc mixer weights: f16, f32 and q8_0 rows */
struct qwen4_w_f16 {
device const half *p;
qwen4_w_f16(device const char *base) : p((device const half *)base) {}
float at(uint64_t i) const { return (float)p[i]; }
};
struct qwen4_w_f32 {
device const float *p;
qwen4_w_f32(device const char *base) : p((device const float *)base) {}
float at(uint64_t i) const { return p[i]; }
};
struct qwen4_w_q8 {
device const char *p;
qwen4_w_q8(device const char *base) : p(base) {}
float at(uint64_t i) const {
device const char *b = p + (i >> 5) * 34;
return (float)(*(device const half *)b) * (float)b[2 + (i & 31u)];
}
};
/* Grouped RMSNorm of one (stream chunk, token): xn = R * rsqrt(mean(R^2)
* + eps) * gamma over the chunk, plus the chunk's partial dot with each
* inject row (consumers sum the hc*chunks partials and apply
* 2*sigmoid(./hc)). The low-rank projection itself is a GEMV on xn. */
template <typename W>
kernel void kernel_qwen4_hc_norm(
constant ds4_metal_args_qwen4_hc_norm & args,
device const float *R, /* [T][hc*E] */
device const float *gamma, /* [hc*E] */
device const char *w_inject, /* [n_inject][hc*E] */
device float *xn, /* [T][hc*E] */
device float *inj_part, /* [T][hc*chunks][n_inject] */
uint3 tgpig [[threadgroup_position_in_grid]],
ushort tid [[thread_index_in_threadgroup]],
ushort3 ntg [[threads_per_threadgroup]],
ushort sgitg [[simdgroup_index_in_threadgroup]],
ushort tiisg [[thread_index_in_simdgroup]]) {
const uint s = tgpig.x / QWEN4_HC_CHUNKS;
const uint chunk = tgpig.x % QWEN4_HC_CHUNKS;
const uint tok = tgpig.y;
if (s >= args.n_hc || tok >= args.n_tokens) return;
const uint E = args.n_embd, dim = E * args.n_hc;
const uint nth = ntg.x, nsg = nth / 32;
threadgroup float red[5][32];
device const float *r = R + ((uint64_t)tok * args.n_hc + s) * E;
device const float *g = gamma + s * E;
device float *o = xn + ((uint64_t)tok * args.n_hc + s) * E;
const W w(w_inject);
float ss = 0.0f;
/* eight of the thread's elements load before they are summed in order:
* one per loop trip left each load waiting on the previous add */
for (uint i0 = tid; i0 < E; i0 += 8u * nth) {
float v[8];
for (uint k = 0; k < 8u; k++) v[k] = r[min(i0 + k * nth, E - 1u)];
for (uint k = 0; k < 8u; k++) if (i0 + k * nth < E) ss += v[k] * v[k];
}
ss = simd_sum(ss);
if (tiisg == 0) red[0][sgitg] = ss;
threadgroup_barrier(mem_flags::mem_threadgroup);
float tot = 0.0f;
for (uint q = 0; q < nsg; q++) tot += red[0][q];
const float inv = rsqrt(tot / (float)E + args.eps);
const uint per = (E + QWEN4_HC_CHUNKS - 1) / QWEN4_HC_CHUNKS;
const uint i0 = chunk * per, i1 = min(E, i0 + per);
float acc[4] = { 0.0f, 0.0f, 0.0f, 0.0f };
for (uint i = i0 + tid; i < i1; i += nth) {
const float v = r[i] * inv * g[i];
o[i] = v;
for (uint j = 0; j < 4; j++) {
if (j < args.n_inject) acc[j] += w.at((uint64_t)j * dim + s * E + i) * v;
}
}
for (uint j = 0; j < 4; j++) {
if (j >= args.n_inject) break;
const float a = simd_sum(acc[j]);
if (tiisg == 0) red[1 + j][sgitg] = a;
}
threadgroup_barrier(mem_flags::mem_threadgroup);
if (tid < args.n_inject) {
float a = 0.0f;
for (uint q = 0; q < nsg; q++) a += red[1 + tid][q];
inj_part[((uint64_t)tok * args.n_hc * QWEN4_HC_CHUNKS + s * QWEN4_HC_CHUNKS + chunk) * args.n_inject + tid] = a;
}
}
#define QWEN4_HC_NORM_INSTANCE(SUFFIX, W) \
template [[host_name("kernel_qwen4_hc_norm_" #SUFFIX)]] \
kernel void kernel_qwen4_hc_norm<W>(constant ds4_metal_args_qwen4_hc_norm &, device const float *, \
device const float *, device const char *, device float *, device float *, uint3, ushort, ushort3, ushort, ushort);
QWEN4_HC_NORM_INSTANCE(f16, qwen4_w_f16)
QWEN4_HC_NORM_INSTANCE(f32, qwen4_w_f32)
QWEN4_HC_NORM_INSTANCE(q8, qwen4_w_q8)
/* Large batches have enough (token, stream) groups to compute the stream RMS
* once and reuse it for all eight chunks. Keep the 128-thread RMS reduction,
* each chunk's injection reduction, and the partial layout identical to the
* original kernel: combining the chunk dots would change rounding. */
template <typename W>
kernel void kernel_qwen4_hc_norm_reuse(
constant ds4_metal_args_qwen4_hc_norm & args,
device const float *R,
device const float *gamma,
device const char *w_inject,
device float *xn,
device float *inj_part,
uint3 tgpig [[threadgroup_position_in_grid]],
ushort tid [[thread_index_in_threadgroup]],
ushort3 ntg [[threads_per_threadgroup]],
ushort sgitg [[simdgroup_index_in_threadgroup]],
ushort tiisg [[thread_index_in_simdgroup]]) {
const uint s = tgpig.x;
const uint tok = tgpig.y;
if (s >= args.n_hc || tok >= args.n_tokens) return;
const uint E = args.n_embd, dim = E * args.n_hc;
const uint nth = ntg.x, nsg = nth / 32;
threadgroup float red[32];
/* This kernel uses 128 threads. Keep each chunk's four SIMD partials
* separate so its readers need no barrier before the next chunk writes. */
threadgroup float inject_red[QWEN4_HC_CHUNKS][4][4];
device const float *r = R + ((uint64_t)tok * args.n_hc + s) * E;
device const float *g = gamma + s * E;
device float *o = xn + ((uint64_t)tok * args.n_hc + s) * E;
const W w(w_inject);
float ss = 0.0f;
for (uint i = tid; i < E; i += nth) ss += r[i] * r[i];
ss = simd_sum(ss);
if (tiisg == 0) red[sgitg] = ss;
threadgroup_barrier(mem_flags::mem_threadgroup);
float tot = 0.0f;
for (uint q = 0; q < nsg; q++) tot += red[q];
const float inv = rsqrt(tot / (float)E + args.eps);
const uint per = (E + QWEN4_HC_CHUNKS - 1) / QWEN4_HC_CHUNKS;
for (uint chunk = 0; chunk < QWEN4_HC_CHUNKS; chunk++) {
const uint i0 = chunk * per, i1 = min(E, i0 + per);
float acc[4] = { 0.0f, 0.0f, 0.0f, 0.0f };
for (uint i = i0 + tid; i < i1; i += nth) {
const float v = r[i] * inv * g[i];
o[i] = v;
for (uint j = 0; j < 4; j++) {
if (j < args.n_inject) acc[j] += w.at((uint64_t)j * dim + s * E + i) * v;
}
}
for (uint j = 0; j < 4; j++) {
if (j >= args.n_inject) break;
const float a = simd_sum(acc[j]);
if (tiisg == 0) inject_red[chunk][j][sgitg] = a;
}
threadgroup_barrier(mem_flags::mem_threadgroup);
if (tid < args.n_inject) {
float a = 0.0f;
for (uint q = 0; q < nsg; q++) a += inject_red[chunk][tid][q];
inj_part[((uint64_t)tok * args.n_hc * QWEN4_HC_CHUNKS + s * QWEN4_HC_CHUNKS + chunk) * args.n_inject + tid] = a;
}
}
}
#define QWEN4_HC_NORM_REUSE_INSTANCE(SUFFIX, W) \
template [[host_name("kernel_qwen4_hc_norm_reuse_" #SUFFIX)]] \
kernel void kernel_qwen4_hc_norm_reuse<W>(constant ds4_metal_args_qwen4_hc_norm &, device const float *, \
device const float *, device const char *, device float *, device float *, uint3, ushort, ushort3, ushort, ushort);
QWEN4_HC_NORM_REUSE_INSTANCE(f16, qwen4_w_f16)
QWEN4_HC_NORM_REUSE_INSTANCE(f32, qwen4_w_f32)
QWEN4_HC_NORM_REUSE_INSTANCE(q8, qwen4_w_q8)
/* 2*sigmoid(inj/hc) with inj[s] = sum of the hc*chunks norm partials for s */
static inline float qwen4_hc_inject_weight(device const float *inj_part, uint hc, uint s) {
float a = 0.0f;
/* sixteen partials load before they are added in order: one per loop
* trip left each load waiting on the previous add */
const uint n = hc * QWEN4_HC_CHUNKS;
for (uint src0 = 0; src0 < n; src0 += 16u) {
float v[16];
for (uint k = 0; k < 16u; k++) v[k] = inj_part[min(src0 + k, n - 1u) * hc + s];
for (uint k = 0; k < 16u && src0 + k < n; k++) a += v[k];
}
return 2.0f * qwen4_sigmoid(a / (float)hc);
}
struct ds4_metal_args_qwen4_hc_gate
10BC8
_mix {
uint32_t n_tokens;
uint32_t n_embd;
uint32_t n_hc;
uint32_t n_rank;
};
/* mixed[d] = mean over streams of sigmoid(w_up[s*E+d] . silu(lo/hc)) *
* xn[s*E+d], lo being the raw low-rank projection. One simdgroup per d:
* the four 8-lane groups stream the four stream rows (contiguous n_rank
* weights each) and shuffle-reduce, first within the group, then across
* the streams. */
template <typename W>
kernel void kernel_qwen4_hc_gate_mix(
constant ds4_metal_args_qwen4_hc_gate_mix & args,
device const float *xn, /* [T][hc*E] */
device const float *lo, /* [T][n_rank] raw */
device const char *w_up, /* [hc*E][n_rank] */
device float *mixed, /* [T][E] */
uint3 tgpig [[threadgroup_position_in_grid]],
ushort3 ntg [[threads_per_threadgroup]],
ushort sgitg [[simdgroup_index_in_threadgroup]],
ushort tiisg [[thread_index_in_simdgroup]]) {
const uint hc = args.n_hc;
const uint E = args.n_embd;
const uint nsg = ntg.x / 32;
const uint d = tgpig.x * nsg + sgitg;
const uint tok = tgpig.y;
if (d >= E || tok >= args.n_tokens) return;
const uint s = tiisg / 8, lane = tiisg % 8;
device const float *l = lo + (uint64_t)tok * args.n_rank;
const W w(w_up);
const uint64_t row = (uint64_t)(s * E + d) * args.n_rank;
float acc = 0.0f;
for (uint r = lane; r < args.n_rank; r += 8) {
if constexpr (is_same<W, qwen4_w_f16>::value) {
#pragma clang fp reassociate(off)
#pragma clang fp contract(off)
/* Match the F16 prefetch/reuse kernels without depending on
* the device compiler to reassociate weight * silu(x). */
const float x = l[r] * (1.0f / (float)hc);
const float t = x * w.at(row + r);
const float u = t * qwen4_sigmoid(x);
acc = acc + u;
} else {
acc += w.at(row + r) * qwen4_silu(l[r] / (float)hc);
}
}
acc += simd_shuffle_xor(acc, 1);
acc += simd_shuffle_xor(acc, 2);
acc += simd_shuffle_xor(acc, 4);
float g = qwen4_sigmoid(acc) * xn[(uint64_t)tok * E * hc + s * E + d];
g += simd_shuffle_xor(g, 8);
g += simd_shuffle_xor(g, 16);
if (tiisg == 0) mixed[(uint64_t)tok * E + d] = g / (float)hc;
}
#define QWEN4_HC_MIX_INSTANCE(SUFFIX, W) \
template [[host_name("kernel_qwen4_hc_gate_mix_" #SUFFIX)]] \
kernel void kernel_qwen4_hc_gate_mix<W>(constant ds4_metal_args_qwen4_hc_gate_mix &, device const float *, \
device const float *, device const char *, device float *, uint3, ushort3, ushort, ushort);
QWEN4_HC_MIX_INSTANCE(f16, qwen4_w_f16)
QWEN4_HC_MIX_INSTANCE(f32, qwen4_w_f32)
QWEN4_HC_MIX_INSTANCE(q8, qwen4_w_q8)
/* F16 gate/mix with eight terms loaded ahead per lane round. The generic,
* prefetched and reuse kernels all pin acc += (x*w)*sigmoid(x) without FMA;
* loading ahead only overlaps memory reads with the sigmoid chain. */
kernel void kernel_qwen4_hc_gate_mix_f16_pf(
constant ds4_metal_args_qwen4_hc_gate_mix & args,
device const float *xn,
device const float *lo,
device const char *w_up,
device float *mixed,
uint3 tgpig [[threadgroup_position_in_grid]],
ushort3 ntg [[threads_per_threadgroup]],
ushort sgitg [[simdgroup_index_in_threadgroup]],
ushort tiisg [[thread_index_in_simdgroup]]) {
const uint hc = args.n_hc;
const uint E = args.n_embd;
const uint nsg = ntg.x / 32;
const uint d = tgpig.x * nsg + sgitg;
const uint tok = tgpig.y;
if (d >= E || tok >= args.n_tokens) return;
const uint s = tiisg / 8, lane = tiisg % 8;
device const float *l = lo + (uint64_t)tok * args.n_rank;
device const half *wr = (device const half *)w_up + (uint64_t)(s * E + d) * args.n_rank;
const float inv_hc = 1.0f / (float)hc;
float acc = 0.0f;
uint r = lane;
for (; r + 56u < args.n_rank; r += 64u) {
float wv[8], lv[8];
for (uint i = 0; i < 8; i++) { wv[i] = (float)wr[r + 8u * i]; lv[i] = l[r + 8u * i]; }
for (uint i = 0; i < 8; i++) {
#pragma clang fp reassociate(off)
#pragma clang fp contract(off)
const float x = lv[i] * inv_hc;
const float sig = qwen4_sigmoid(x);
const float t = x * wv[i];
const float u = t * sig;
acc = acc + u;
}
}
for (; r < args.n_rank; r += 8u) {
#pragma clang fp reassociate(off)
#pragma clang fp contract(off)
const float x = l[r] * inv_hc;
const float sig = qwen4_sigmoid(x);
const float t = x * (float)wr[r];
const float u = t * sig;
acc = acc + u;
}
acc += simd_shuffle_xor(acc, 1);
acc += simd_shuffle_xor(acc, 2);
acc += simd_shuffle_xor(acc, 4);
float g = qwen4_sigmoid(acc) * xn[(uint64_t)tok * E * hc + s * E + d];
g += simd_shuffle_xor(g, 8);
g += simd_shuffle_xor(g, 16);
if (tiisg == 0) mixed[(uint64_t)tok * E + d] = g / (float)hc;
}
/* Reuse the low-rank sigmoid across streams and output rows. Keep x and
* sigmoid(x) separate: storing silu(x) would change the single-row
* accumulation's (x * weight) * sigmoid(x) rounding. */
kernel void kernel_qwen4_hc_gate_mix_f16_reuse(
constant ds4_metal_args_qwen4_hc_gate_mix & args,
device const float *xn,
device const float *lo,
device const char *w_up,
device float *mixed,
threadgroup float2 *low_sig [[threadgroup(0)]],
uint3 tgpig [[threadgroup_position_in_grid]],
ushort tid [[thread_index_in_threadgroup]],
ushort3 ntg [[threads_per_threadgroup]],
ushort sgitg [[simdgroup_index_in_threadgroup]],
ushort tiisg [[thread_index_in_simdgroup]]) {
const uint hc = args.n_hc, E = args.n_embd, rank = args.n_rank;
const uint d = tgpig.x * (ntg.x / 32) + sgitg;
const uint tok = tgpig.y;
if (tok >= args.n_tokens) return;
device const float *l = lo + (uint64_t)tok * rank;
const float inv_hc = 1.0f / (float)hc;
for (uint r = tid; r < rank; r += ntg.x) {
#pragma clang fp reassociate(off)
#pragma clang fp contract(off)
const float x = l[r] * inv_hc;
low_sig[r] = float2(x, qwen4_sigmoid(x));
}
threadgroup_barrier(mem_flags::mem_threadgroup);
if (d >= E) return;
const uint s = tiisg / 8, lane = tiisg % 8;
device const half *wr = (device const half *)w_up + (uint64_t)(s * E + d) * rank;
float acc = 0.0f;
uint r = lane;
for (; r + 56u < rank; r += 64u) {
float wv[8];
float2 av[8];
for (uint i = 0; i < 8; i++) { wv[i] = (float)wr[r + 8u * i]; av[i] = low_sig[r + 8u * i]; }
for (uint i = 0; i < 8; i++) {
#pragma clang fp reassociate(off)
#pragma clang fp contract(off)
const float t = av[i].x * wv[i];
const float u = t * av[i].y;
acc = acc + u;
}
}
for (; r < rank; r += 8u) {
#pragma clang fp reassociate(off)
#pragma clang fp contract(off)
const float2 a = low_sig[r];
const float t = a.x * (float)wr[r];
const float u = t * a.y;
acc = acc + u;
}
acc += simd_shuffle_xor(acc, 1);
acc += simd_shuffle_xor(acc, 2);
acc += simd_shuffle_xor(acc, 4);
float g = qwen4_sigmoid(acc) * xn[(uint64_t)tok * E * hc + s * E + d];
g += simd_shuffle_xor(g, 8);
g += simd_shuffle_xor(g, 16);
if (tiisg == 0) mixed[(uint64_t)tok * E + d] = g / (float)hc;
}
/* Two-token MTP verification: reuse each up-projection weight for both
* rows, and activate the low-rank inputs once per threadgroup. */
template <typename W>
kernel void kernel_qwen4_hc_gate_mix_pair(
constant ds4_metal_args_qwen4_hc_gate_mix & args,
device const float *xn,
device const float *lo,
device const char *w_up,
device float *mixed,
threadgroup float2 *activated [[threadgroup(0)]],
uint3 tgpig [[threadgroup_position_in_grid]],
ushort tid [[thread_index_in_threadgroup]],
ushort3 ntg [[threads_per_threadgroup]],
ushort sgitg [[simdgroup_index_in_threadgroup]],
ushort tiisg [[thread_index_in_simdgroup]]) {
const uint E = args.n_embd, hc = args.n_hc, rank = args.n_rank;
const uint d = tgpig.x * (ntg.x / 32) + sgitg;
for (uint r = tid; r < rank; r += ntg.x) {
activated[r] = float2(qwen4_silu(lo[r] / (float)hc),
qwen4_silu(lo[rank + r] / (float)hc));
}
threadgroup_barrier(mem_flags::mem_threadgroup);
if (d >= E) return;
const uint s = tiisg / 8, lane = tiisg % 8;
const W w(w_up);
const uint64_t row = (uint64_t)(s * E + d) * rank;
float2 acc = 0.0f;
for (uint r = lane; r < rank; r += 8) {
if constexpr (is_same<W, qwen4_w_f16>::value) {
#pragma clang fp reassociate(off)
#pragma clang fp contract(off)
/* Paired F16 rows retain their original fused accumulation. */
acc = fma(float2(w.at(row + r)), activated[r], acc);
} else {
acc += w.at(row + r) * activated[r];
}
}
acc += simd_shuffle_xor(acc, 1);
acc += simd_shuffle_xor(acc, 2);
acc += simd_shuffle_xor(acc, 4);
float2 v = float2(qwen4_sigmoid(acc.x) * xn[s * E + d],
qwen4_sigmoid(acc.y) * xn[E * hc + s * E + d]);
v += simd_shuffle_xor(v, 8);
v += simd_shuffle_xor(v, 16);
if (tiisg == 0) {
mixed[d] = v.x / (float)hc;
mixed[E + d] = v.y / (float)hc;
}
}
/* Paired F16 gate/mix with eight weights and activated pairs loaded ahead.
* Both paired kernels pin the same FMA chain, unlike the single-row mixer. */
kernel void kernel_qwen4_hc_gate_mix_pair_f16_pf(
constant ds4_metal_args_qwen4_hc_gate_mix & args,
device const float *xn,
device const float *lo,
device const char *w_up,
device float *mixed,
threadgroup float2 *activated [[threadgroup(0)]],
uint3 tgpig [[threadgroup_position_in_grid]],
ushort tid [[thread_index_in_threadgroup]],
ushort3 ntg [[threads_per_threadgroup]],
ushort sgitg [[simdgroup_index_in_threadgroup]],
ushort tiisg [[thread_index_in_simdgroup]]) {
const uint E = args.n_embd, hc = args.n_hc, rank = args.n_rank;
const uint d = tgpig.x * (ntg.x / 32) + sgitg;
for (uint r = tid; r < rank; r += ntg.x) {
activated[r] = float2(qwen4_silu(lo[r] / (float)hc),
qwen4_silu(lo[rank + r] / (float)hc));
}
threadgroup_barrier(mem_flags::mem_threadgroup);
if (d >= E) return;
const uint s = tiisg / 8, lane = tiisg % 8;
device const half *wr = (device const half *)w_up + (uint64_t)(s * E + d) * rank;
float2 acc = 0.0f;
uint r = lane;
for (; r + 56u < rank; r += 64u) {
float wv[8];
float2 av[8];
for (uint i = 0; i < 8; i++) { wv[i] = (float)wr[r + 8u * i]; av[i] = activated[r + 8u * i]; }
for (uint i = 0; i < 8; i++) {
#pragma clang fp reassociate(off)
#pragma clang fp contract(off)
acc = fma(float2(wv[i]), av[i], acc);
}
}
for (; r < rank; r += 8u) {
#pragma clang fp reassociate(off)
#pragma clang fp contract(off)
acc = fma(float2((float)wr[r]), activated[r], acc);
}
acc += simd_shuffle_xor(acc, 1);
acc += simd_shuffle_xor(acc, 2);
acc += simd_shuffle_xor(acc, 4);
float2 v = float2(qwen4_sigmoid(acc.x) * xn[s * E + d],
qwen4_sigmoid(acc.y) * xn[E * hc + s * E + d]);
v += simd_shuffle_xor(v, 8);
v += simd_shuffle_xor(v, 16);
if (tiisg == 0) {
mixed[d] = v.x / (float)hc;
mixed[E + d] = v.y / (float)hc;
}
}
#define QWEN4_HC_MIX_PAIR_INSTANCE(SUFFIX, W) \
template [[host_name("kernel_qwen4_hc_gate_mix_pair_" #SUFFIX)]] \
kernel void kernel_qwen4_hc_gate_mix_pair<W>(constant ds4_metal_args_qwen4_hc_gate_mix &, device const float *, \
device const float *, device const char *, device float *, threadgroup float2 *, uint3, ushort, ushort3, ushort, ushort);
QWEN4_HC_MIX_PAIR_INSTANCE(f16, qwen4_w_f16)
QWEN4_HC_MIX_PAIR_INSTANCE(f32, qwen4_w_f32)
QWEN4_HC_MIX_PAIR_INSTANCE(q8, qwen4_w_q8)
struct ds4_metal_args_qwen4_hc_combine {
uint32_t n_tokens;
uint32_t n_embd;
uint32_t n_hc;
uint32_t pad0;
};
/* R[s][d] += 2*sigmoid(inj[s]/hc) * out[d]; the inject weights are reduced
* once per threadgroup. */
kernel void kernel_qwen4_hc_combine(
constant ds4_metal_args_qwen4_hc_combine & args,
device float *R, /* [T][hc*E] */
device const float *out, /* [T][E] */
device const float *inj, /* [T][hc*chunks][hc] norm partials */
uint3 tgpig [[threadgroup_position_in_grid]],
ushort tid [[thread_index_in_threadgroup]],
ushort3 ntg [[threads_per_threadgroup]]) {
const uint d = tgpig.x * ntg.x + tid;
const uint tok = tgpig.y;
if (tok >= args.n_tokens) return;
threadgroup float wgt[8];
if (tid < args.n_hc) {
wgt[tid] = qwen4_hc_inject_weight(inj + (uint64_t)tok * args.n_hc * QWEN4_HC_CHUNKS * args.n_hc, args.n_hc, tid);
}
threadgroup_barrier(mem_flags::mem_threadgroup);
if (d >= args.n_embd) return;
const float o = out[(uint64_t)tok * args.n_embd + d];
device float *r = R + (uint64_t)tok * args.n_embd * args.n_hc;
for (uint s = 0; s < args.n_hc; s++) r[s * args.n_embd + d] += wgt[s] * o;
}
/* --- gated delta net ---------------------------------------------------- */
struct ds4_metal_args_qwen4_conv_stream {
uint32_t n_tokens;
uint32_t n_channels;
uint32_t conv_kernel; /* <= 4 */
uint32_t apply_silu;
};
/* Depthwise causal conv over the token axis. x holds the raw inputs for
* all tokens and is overwritten with the (optionally silu'd) output; state
* holds the K-1 previous raw inputs oldest first and is advanced past the
* processed tokens. One thread per channel, tokens sequential. */
kernel void kernel_qwen4_conv_stream(
constant ds4_metal_args_qwen4_conv_stream & args,
device float *x, /* [T][C] */
device float *state, /* [K-1][C] */
device const float *weight, /* [C][K] */
uint3 tgpig [[threadgroup_position_in_grid]],
ushort tid [[thread_index_in_threadgroup]],
ushort3 ntg [[threads_per_threadgroup]]) {
const uint c = tgpig.x * ntg.x + tid;
if (c >= args.n_channels) return;
const uint C = args.n_channels;
const uint K = args.conv_kernel;
float win[3];
for (uint t = 0; t + 1 < K; t++) win[t] = state[t * C + c];
float taps[4];
for (uint t = 0; t < K; t++) taps[t] = weight[c * K + t];
for (uint tok = 0; tok < args.n_tokens; tok++) {
const float raw = x[tok * C + c];
float acc = taps[K - 1] * raw;
for (uint t = 0; t + 1 < K; t++) acc += taps[t] * win[t];
for (uint t = 0; t + 2 < K; t++) win[t] = win[t + 1];
win[K - 2] = raw;
x[tok * C + c] = args.apply_silu ? qwen4_silu(acc) : acc;
}
for (uint t = 0; t + 1 < K; t++) state[t * C + c] = win[t];
}
struct ds4_metal_args_qwen4_conv_stream_rows {
uint32_t n_rows;
uint32_t n_channels;
uint32_t conv_kernel;
uint32_t apply_silu;
uint32_t state_stride; /* floats between two slots of the history pool */
uint32_t x_stride; /* floats between two rows of the batch arena */
uint32_t pad0;
uint32_t pad1;
};
/* One decode token for every row of a batch, each against its own slot of the
* convolution history. Identical arithmetic to kernel_qwen4_conv_stream with
* n_tokens = 1, so the two agree bit for bit; the rows merely share a
* dispatch instead of taking one each. */
kernel void kernel_qwen4_conv_stream_rows(
constant ds4_metal_args_qwen4_conv_stream_rows & args,
device float *x,
device float *state,
device const float *weight,
device const uint *slots,
uint3 tgpig [[threadgroup_position_in_grid]],
ushort tid [[thread_index_in_threadgroup]],
ushort3 ntg [[threads_per_threadgroup]]) {
const uint c = tgpig.x * ntg.x + tid;
const uint row = tgpig.y;
if (c >= args.n_channels || row >= args.n_rows) return;
const uint C = args.n_channels;
const uint K = args.conv_kernel;
device float *st = state + (uint64_t)slots[row] * args.state_stride;
device float *xr = x + (uint64_t)row * args.x_stride;
float win[3];
for (uint t = 0; t + 1 < K; t++) win[t] = st[t * C + c];
float taps[4];
for (uint t = 0; t < K; t++) taps[t] = weight[c * K + t];
const float raw = xr[c];
float acc = taps[K - 1] * raw;
for (uint t = 0; t + 1 < K; t++) acc += taps[t] * win[t];
for (uint t = 0; t + 2 < K; t++) win[t] = win[t + 1];
win[K - 2] = raw;
xr[c] = args.apply_silu ? qwen4_silu(acc) : acc;
for (uint t = 0; t + 1 < K; t++) st[t * C + c] = win[t];
}
/* One entry per session of a batch for the *_rows2 kernels: its recurrent
* state and convolution history by GPU address (the caches stay private,
* so a session's snapshot can keep swapping places with its state), its
* first batch row and how many consecutive rows it owns (its token, then
* its draft). A non-zero snapshot address receives the state after the
* first token, as the verify kernels write it. */
struct ds4_metal_qwen4_gdn_row {
uint64_t state;
uint64_t hist;
uint64_t snap_state;
uint64_t snap_hist;
uint32_t row0;
uint32_t n_tok;
uint32_t pad0;
uint32_t pad1;
};
/* kernel_qwen4_conv_stream_rows over the table: one or two tokens in order
* per entry against its own history, the window after the first token
* written to the entry's snapshot when it has one. */
kernel void kernel_qwen4_conv_stream_rows2(
constant ds4_metal_args_qwen4_conv_stream_rows & args,
device float *x,
device const float *weight,
device const ds4_metal_qwen4_gdn_row *rows,
uint3 tgpig [[threadgroup_position_in_grid]],
ushort tid [[thread_index_in_threadgroup]],
ushort3 ntg [[threads_per_threadgroup]]) {
const uint c = tgpig.x * ntg.x + tid;
const uint r = tgpig.y;
if (c >= args.n_channels || r >= args.n_rows) return;
const ds4_metal_qwen4_gdn_row e = rows[r];
const uint C = args.n_channels;
const uint K = args.conv_kernel;
device float *st = reinterpret_cast<device float *>(e.hist);
float win[3];
for (uint t = 0; t + 1 < K; t++) win[t] = st[t * C + c];
float taps[4];
for (uint t = 0; t < K; t++) taps[t] = weight[c * K + t];
for (uint tok = 0; tok < e.n_tok; tok++) {
device float *xr = x + (uint64_t)(e.row0 + tok) * args.x_stride;
const float raw = xr[c];
float acc = taps[K - 1] * raw;
for (uint t = 0; t + 1 < K; t++) acc += taps[t] * win[t];
for (uint t = 0; t + 2 < K; t++) win[t] = win[t + 1];
win[K - 2] = raw;
xr[c] = args.apply_silu ? qwen4_silu(acc) : acc;
if (tok == 0 && e.snap_hist) {
device float *sh = reinterpret_cast<device float *>(e.snap_hist);
for (uint t = 0; t + 1 < K; t++) sh[t * C + c] = win[t];
}
}
for (uint t = 0; t + 1 < K; t++) st[t * C + c] = win[t];
}
#define QWEN4_CONV_BLOCK 64u
/* Only incoming block windows need a snapshot; raw rows inside each block
* stay private to its channel thread until they have entered the window. */
kernel void kernel_qwen4_conv_halo(
constant ds4_metal_args_qwen4_conv_stream &args,
device const float *x, device const float *state, device float *halo,
uint gid [[thread_position_in_grid]]) {
const uint C = args.n_channels, H = args.conv_kernel - 1u;
const uint blocks = 1u + (args.n_tokens - 1u) / QWEN4_CONV_BLOCK;
if (gid >= (uint64_t)blocks * H * C) return;
const uint block = gid / (H * C), t = gid / C % H, c = gid % C;
halo[gid] = block == 0 ? state[t * C + c] : x[(uint64_t)(block * QWEN4_CONV_BLOCK - H + t) * C + c];
}
kernel void kernel_qwen4_conv_blocked(
constant ds4_metal_args_qwen4_conv_stream &args,
device float *x, device float *state, device const float *weight,
device const float *halo,
uint gid [[thread_position_in_grid]]) {
const uint C = args.n_channels, K = args.conv_kernel;
const uint c = gid % C, block = gid / C, start = block * QWEN4_CONV_BLOCK;
if (start >= args.n_tokens) return;
float win[3], taps[4];
for (uint t = 0; t + 1u < K; t++) win[t] = halo[((uint64_t)block * (K - 1u) + t) * C + c];
for (uint t = 0; t < K; t++) taps[t] = weight[c * K + t];
const uint end = start + min(QWEN4_CONV_BLOCK, args.n_tokens - start);
for (uint tok = start; tok < end; tok++) {
const float raw = x[(uint64_t)tok * C + c];
float acc = taps[K - 1u] * raw;
for (uint t = 0; t + 1u < K; t++) acc += taps[t] * win[t];
for (uint t = 0; t + 2u < K; t++) win[t] = win[t + 1u];
win[K - 2u] = raw;
x[(uint64_t)tok * C + c] = args.apply_silu ? qwen4_silu(acc) : acc;
}
if (end == args.n_tokens) for (uint t = 0; t + 1u < K; t++) state[t * C + c] = win[t];
}
struct ds4_metal_args_qwen4_gdn_prep {
uint32_t n_tokens;
uint32_t n_k_head;
uint32_t n_v_head;
uint32_t head_dim;
};
/* After the conv: L2-normalize each q and k head (q also scaled by
* 1/sqrt(D)), turn the alpha/beta projections into the decay g =
* exp(ssm_a * softplus(a + dt_bias)) and beta = sigmoid(b). One simdgroup
* per (token, k-head); the v-head scalars are handled by the first head. */
kernel void kernel_qwen4_gdn_prep(
constant ds4_metal_args_qwen4_gdn_prep & args,
device float *qkv, /* [T][2*Hk*D + Hv*D], conv output, q/k normalized in place */
device float *a, /* [T][Hv]: alpha in, g out */
device float *b, /* [T][Hv]: b in, beta out */
device const float *ssm_a, /* [Hv] = -exp(A_log) */
device const float *dt_bias, /* [Hv] */
uint3 tgpig [[threadgroup_position_in_grid]],
ushort tiisg [[thread_index_in_simdgroup]]) {
const uint h = tgpig.x;
const uint tok = tgpig.y;
if (h >= args.n_k_head || tok >= args.n_tokens) return;
const uint D = args.head_dim;
const uint npt = D / 32;
const uint conv_dim = 2 * args.n_k_head * D + args.n_v_head * D;
device float *q = qkv + (uint64_t)tok * conv_dim + h * D + tiisg * npt;
device float *k = q + args.n_k_head * D;
float sq = 0.0f, sk = 0.0f;
for (uint i = 0; i < npt; i++) {
sq += q[i] * q[i];
sk += k[i] * k[i];
}
sq = simd_sum(sq);
sk = simd_sum(sk);
const float qs = rsqrt(sq + 1e-6f) * rsqrt((float)D);
const float ks = rsqrt(sk + 1e-6f);
for (uint i = 0; i < npt; i++) {
q[i] *= qs;
k[i] *= ks;
}
if (h == 0) {
device float *ga = a + (uint64_t)tok * args.n_v_head;
device float *gb = b + (uint64_t)tok * args.n_v_head;
for (uint j = tiisg; j < args.n_v_head; j += 32) {
ga[j] = exp(ssm_a[j] * qwen4_softplus(ga[j] + dt_bias[j]));
gb[j] = qwen4_sigmoid(gb[j]);
}
}
}
struct ds4_metal_args_qwen4_gdn_scan {
uint32_t n_tokens;
uint32_t n_k_head;
uint32_t n_v_head;
uint32_t head_dim;
uint32_t snap_tok; /* copy the state after this token into snap_state (UINT32_MAX: never) */
uint32_t snap2_tok; /* second snapshot point for 3-row MTP verifies (UINT32_MAX: never) */
uint32_t pad1;
uint32_t pad2;
};
/* Sequential gated delta scan. One simdgroup per (v-head, dv) state row;
* lane j owns S[dk = j*npt .. +npt-1] in registers for the whole token
* loop. Value head h reads key head h % Hk (tiled GGUF order). Per token:
* S *= g, u = S k, delta = beta (v - u), S += k delta, o = S q. */
kernel void kernel_qwen4_gdn_scan(
constant ds4_metal_args_qwen4_gdn_scan & args,
device const float *qkv, /* [T][2*Hk*D + Hv*D], q/k normalized */
device const float *ga, /* [T][Hv] decay g */
device const float *gb, /* [T][Hv] beta */
device float *state, /* [Hv][D][D] as [dv][dk] */
device float *out, /* [T][Hv*D] */
device float *snap_state,
device float *snap2_state,
uint3 tgpig [[threadgroup_position_in_grid]],
ushort tiisg [[thread_index_in_simdgroup]]) {
const uint dv = tgpig.x;
const uint h = tgpig.y;
if (dv >= args.head_dim || h >= args.n_v_head) return;
const uint D = args.head_dim;
const uint npt = D / 32;
const uint dk0 = tiisg * npt;
const uint kh = h % args.n_k_head;
const uint conv_dim = 2 * args.n_k_head * D + args.n_v_head * D;
float s[4];
device float *srow = state + ((uint64_t)h * D + dv) * D + dk0;
device float *snaprow = snap_state + ((uint64_t)h * D + dv) * D + dk0;
device float *snap2row = snap2_state + ((uint64_t)h * D + dv) * D + dk0;
for (uint i = 0; i < npt; i++) s[i] = srow[i];
for (uint tok = 0; tok < args.n_tokens; tok++) {
device const float *q = qkv + (uint64_t)tok * conv_dim + kh * D + dk0;
device const float *k = q + args.n_k_head * D;
device const float *v = qkv + (uint64_t)tok * conv_dim + 2 * args.n_k_head * D + h * D;
const float g = ga[(uint64_t)tok * args.n_v_head + h];
const float beta = gb[(uint64_t)tok * args.n_v_head + h];
float u = 0.0f;
for (uint i = 0; i < npt; i++) {
s[i] *= g;
u += s[i] * k[i];
}
u = simd_sum(u);
const float delta = (v[dv] - u) * beta;
float o = 0.0f;
for (uint i = 0; i < npt; i++) {
s[i] += k[i] * delta;
o += s[i] * q[i];
}
o = simd_sum(o);
if (tiisg == 0) out[((uint64_t)tok * args.n_v_head + h) * D + dv] = o;
if (tok == args.snap_tok) {
for (uint i = 0; i < npt; i++) snaprow[i] = s[i];
}
if (tok == args.snap2_tok) {
for (uint i = 0; i < npt; i++) snap2row[i] = s[i];
}
}
for (uint i = 0; i < npt; i++) srow[i] = s[i];
}
/* Scan for head_dim 128: one simdgroup per (v-head, 4 consecutive dv
* rows), so k/q/g/beta are loaded once per four state rows and the eight
* reductions per token overlap. Same math and state layout as above. */
struct ds4_metal_args_qwen4_gdn_scan_rows {
uint32_t n_rows;
uint32_t n_k_head;
uint32_t n_v_head;
uint32_t head_dim;
uint32_t state_stride; /* floats between two slots of the pool */
uint32_t qkv_stride; /* floats between two rows of the batch arena */
uint32_t out_stride;
uint32_t pad0;
};
/* One decode step for every row of a batch, each against its own slot of the
* recurrent state pool. Same arithmetic as kernel_qwen4_gdn_scan_r4 with
* n_tokens = 1, so the result is bit-identical to running that kernel once per
* row; what changes is that the rows share one dispatch, which is long enough
* to reach steady state where sixteen short ones were not. head_dim is 128,
* as in kernel_qwen4_gdn_scan_r4. */
kernel void kernel_qwen4_gdn_scan_rows(
constant ds4_metal_args_qwen4_gdn_scan_rows & args,
device const float *qkv,
device const float *ga,
device const float *gb,
device float *state,
device float *out,
device const uint *slots,
uint3 tgpig [[threadgroup_position_in_grid]],
ushort3 ntg [[threads_per_threadgroup]],
ushort sgitg [[simdgroup_index_in_threadgroup]],
ushort tiisg [[thread_index_in_simdgroup]]) {
const uint dv0 = (tgpig.x * (ntg.x / 32) + sgitg) * 4;
const uint h = tgpig.y;
const uint row = tgpig.z;
if (dv0 >= args.head_dim || h >= args.n_v_head || row >= args.n_rows) return;
const uint D = 128, dk0 = tiisg * 4;
const uint kh = h % args.n_k_head;
device float *srow = state + (uint64_t)slots[row] * args.state_stride +
((uint64_t)h * D + dv0) * D + dk0;
device const float *base = qkv + (uint64_t)row * args.qkv_stride;
const float4 q = *(device const float4 *)(base + kh * D + dk0);
const float4 k = *(device const float4 *)(base + (args.n_k_head + kh) * D + dk0);
const float4 v = *(device const float4 *)(base + 2 * args.n_k_head * D + h * D + dv0);
const float g = ga[(uint64_t)row * args.n_v_head + h];
const float beta = gb[(uint64_t)row * args.n_v_head + h];
float4 s[4];
for (uint r = 0; r < 4; r++) s[r] = *(device const float4 *)(srow + r * D);
float u[4], o[4];
for (uint r = 0; r < 4; r++) { s[r] *= g; u[r] = dot(s[r], k); }
for (uint r = 0; r < 4; r++) u[r] = simd_sum(u[r]);
for (uint r = 0; r < 4; r++) { s[r] += k * ((v[r] - u[r]) * beta); o[r] = dot(s[r], q); }
for (uint r = 0; r < 4; r++) o[r] = simd_sum(o[r]);
if (tiisg == 0) {
*(device float4 *)(out + (uint64_t)row * args.out_stride + (uint64_t)h * D + dv0) =
float4(o[0], o[1], o[2], o[3]);
}
for (uint r = 0; r < 4; r++) *(device float4 *)(srow + r * D) = s[r];
}
/* kernel_qwen4_gdn_scan_rows over the table: the per-token arithmetic of
* kernel_qwen4_gdn_scan_r4, one or two tokens in order per entry, the
* state after the first written to the entry's snapshot when it has one. */
kernel void kernel_qwen4_gdn_scan_rows2(
constant ds4_metal_args_qwen4_gdn_scan_rows & args,
device const float *qkv,
device const float *ga,
device const float *gb,
device float *out,
device const ds4_metal_qwen4_gdn_row *rows,
uint3 tgpig [[threadgroup_position_in_grid]],
ushort3 ntg [[threads_per_threadgroup]],
ushort sgitg [[simdgroup_index_in_threadgroup]],
ushort tiisg [[thread_index_in_simdgroup]]) {
const uint dv0 = (tgpig.x * (ntg.x / 32) + sgitg) * 4;
const uint h = tgpig.y;
const uint r = tgpig.z;
if (dv0 >= args.head_dim || h >= args.n_v_head || r >= args.n_rows) return;
const ds4_metal_qwen4_gdn_row e = rows[r];
const uint D = 128, dk0 = tiisg * 4;
const uint kh = h % args.n_k_head;
const uint64_t at = ((uint64_t)h * D + dv0) * D + dk0;
device float *srow = reinterpret_cast<device float *>(e.state) + at;
float4 s[4];
for (uint i = 0; i < 4; i++) s[i] = *(device const float4 *)(srow + i * D);
for (uint tok = 0; tok < e.n_tok; tok++) {
const uint row = e.row0 + tok;
device const float *base = qkv + (uint64_t)row * args.qkv_stride;
const float4 q = *(device const float4 *)(base + kh * D + dk0);
const float4 k = *(device const float4 *)(base + (args.n_k_head + kh) * D + dk0);
const float4 v = *(device const float4 *)(base + 2 * args.n_k_head * D + h * D + dv0);
const float g = ga[(uint64_t)row * args.n_v_head + h];
const float beta = gb[(uint64_t)row * args.n_v_head + h];
float u[4], o[4];
for (uint i = 0; i < 4; i++) { s[i] *= g; u[i] = dot(s[i], k); }
for (uint i = 0; i < 4; i++) u[i] = simd_sum(u[i]);
for (uint i = 0; i < 4; i++) { s[i] += k * ((v[i] - u[i]) * beta); o[i] = dot(s[i], q); }
for (uint i = 0; i < 4; i++) o[i] = simd_sum(o[i]);
if (tiisg == 0) {
*(device float4 *)(out + (uint64_t)row * args.out_stride + (uint64_t)h * D + dv0) =
float4(o[0], o[1], o[2], o[3]);
}
if (tok == 0 && e.snap_state) {
device float *snaprow = reinterpret_cast<device float *>(e.snap_state) + at;
for (uint i = 0; i < 4; i++) *(device float4 *)(snaprow + i * D) = s[i];
}
}
for (uint i = 0; i < 4; i++) *(device float4 *)(srow + i * D) = s[i];
}
kernel void kernel_qwen4_gdn_scan_r4(
constant ds4_metal_args_qwen4_gdn_scan & args,
device const float *qkv,
device const float *ga,
device const float *gb,
device float *state,
device float *out,
device float *snap_state,
device float *snap2_state,
uint3 tgpig [[threadgroup_position_in_grid]],
ushort3 ntg [[threads_per_threadgroup]],
ushort sgitg [[simdgroup_index_in_threadgroup]],
ushort tiisg [[thread_index_in_simdgroup]]) {
const uint dv0 = (tgpig.x * (ntg.x / 32) + sgitg) * 4;
const uint h = tgpig.y;
if (dv0 >= args.head_dim || h >= args.n_v_head) return;
const uint D = 128, dk0 = tiisg * 4;
const uint kh = h % args.n_k_head;
const uint conv_dim = 2 * args.n_k_head * D + args.n_v_head * D;
float4 s[4];
device float *srow = state + ((uint64_t)h * D + dv0) * D + dk0;
device float *snaprow = snap_state + ((uint64_t)h * D + dv0) * D + dk0;
device float *snap2row = snap2_state + ((uint64_t)h * D + dv0) * D + dk0;
for (uint r = 0; r < 4; r++) s[r] = *(device const float4 *)(srow + r * D);
for (uint tok = 0; tok < args.n_tokens; tok++) {
device const float *base = qkv + (uint64_t)tok * conv_dim;
const float4 q = *(device const float4 *)(base + kh * D + dk0);
const float4 k = *(device const float4 *)(base + (args.n_k_head + kh) * D + dk0);
const float4 v = *(device const float4 *)(base + 2 * args.n_k_head * D + h * D + dv0);
const float g = ga[(uint64_t)tok * args.n_v_head + h];
const float beta = gb[(uint64_t)tok * args.n_v_head + h];
float u[4], o[4];
for (uint r = 0; r < 4; r++) { s[r] *= g; u[r] = dot(s[r], k); }