Repository navigation
Expand file tree
/
Copy pathds4_qwen4_cuda.cuh
More file actions
2356 lines (2239 loc) · 117 KB
/
Copy pathds4_qwen4_cuda.cuh
File metadata and controls
2356 lines (2239 loc) · 117 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. Included by ds4_cuda.cu so model residency, streams
* and temporary allocations have the same lifetime as the other CUDA paths. */
#include "ds4_qwen4_vision.h"
namespace qwen4_cuda {
__device__ __forceinline__ float sum(float x);
__device__ __forceinline__ float sigmoid(float x);
template<unsigned TYPE>
__device__ __forceinline__ float dot(const char *row, const float *x, unsigned n,
const uint64_t *grid = NULL, const uint8_t *signs = NULL);
__device__ float injection(const float *inj, unsigned hc, unsigned stream);
struct rope_args { float freq[32], scale; unsigned nrot; };
static float rope_freq[32];
static float rope_scale = 1;
static bool rope_set;
static rope_args rope(unsigned nrot, float base) {
rope_args r = {};
r.nrot = nrot;
r.scale = rope_set ? rope_scale : 1;
for (unsigned i = 0; i < nrot / 2; i++)
r.freq[i] = rope_set ? rope_freq[i] : powf(base, -2.0f * i / nrot);
return r;
}
__device__ void apply_rope(float *row, const uint32_t *pos, rope_args r) {
const unsigned i = threadIdx.x;
if (i < r.nrot / 2) {
const float theta = (float)pos[i % 3] * r.freq[i];
const float c = cosf(theta) * r.scale, s = sinf(theta) * r.scale;
const float a = row[i], b = row[i + r.nrot / 2];
row[i] = a * c - b * s;
row[i + r.nrot / 2] = a * s + b * c;
}
__syncwarp();
}
__global__ void attn_prep(float *qout, float *gate, __half *kc, __half *vc,
float *iqout, float *ikc, const float *qg, const float *kp, const float *vp,
const float *iq, const float *ik, const uint32_t *pos3,
const float *gq, const float *gk, const float *giq,
unsigned H, unsigned Hkv, unsigned D, unsigned Hi, unsigned Di,
unsigned pos0, float eps, rope_args rp) {
const unsigned slot = blockIdx.x, t = blockIdx.y, pos = pos0 + t, lane = threadIdx.x;
__shared__ float row[256];
if (slot == H + Hkv + Hi) {
for (unsigned i = lane; i < Di; i += 32) ikc[(uint64_t)pos * Di + i] = ik[(uint64_t)t * Di + i];
return;
}
const bool isq = slot < H, isk = !isq && slot < H + Hkv;
const unsigned h = isq ? slot : isk ? slot - H : slot - H - Hkv;
const unsigned dim = isq || isk ? D : Di;
const float *src = isq ? qg + ((uint64_t)t * H + h) * 2 * D :
isk ? kp + ((uint64_t)t * Hkv + h) * D : iq + ((uint64_t)t * Hi + h) * Di;
const float *gamma = isq ? gq : isk ? gk : giq;
const unsigned npt = dim / 32;
float ss = 0;
for (unsigned i = 0; i < npt; i++) { const float v = src[lane * npt + i]; ss += v * v; }
const float inv = rsqrtf(sum(ss) / dim + eps);
for (unsigned i = lane; i < dim; i += 32) row[i] = src[i] * inv * gamma[i];
__syncwarp();
apply_rope(row, pos3 + (uint64_t)pos * 4, rp);
for (unsigned i = lane; i < dim; i += 32) {
if (isq) {
qout[((uint64_t)t * H + h) * D + i] = row[i];
gate[((uint64_t)t * H + h) * D + i] = src[D + i];
} else if (isk) {
kc[((uint64_t)pos * Hkv + h) * D + i] = __float2half_rn(row[i]);
vc[((uint64_t)pos * Hkv + h) * D + i] = __float2half_rn(vp[((uint64_t)t * Hkv + h) * D + i]);
} else iqout[((uint64_t)t * Hi + h) * Di + i] = row[i];
}
}
__global__ void block_key(__half *out, const float *ik, const uint32_t *pos3,
const float *gamma, unsigned block0, unsigned ratio, unsigned D, float eps, rope_args rp) {
const unsigned b = block0 + blockIdx.x, lane = threadIdx.x, npt = D / 32;
__shared__ float row[128];
float ss = 0, v[4];
for (unsigned i = 0; i < npt; i++) {
float a = 0;
for (unsigned t = 0; t < ratio; t++) a += ik[((uint64_t)b * ratio + t) * D + lane * npt + i];
v[i] = a / ratio;
ss += v[i] * v[i];
}
const float inv = rsqrtf(sum(ss) / D + eps);
for (unsigned i = 0; i < npt; i++) row[lane * npt + i] = v[i] * inv * gamma[lane * npt + i];
__syncwarp();
apply_rope(row, pos3 + (uint64_t)b * ratio * 4, rp);
for (unsigned i = lane; i < D; i += 32) out[(uint64_t)b * D + i] = __float2half_rn(row[i]);
}
__global__ void idx_score(float *out, const float *q, const __half *key,
unsigned N, unsigned H, unsigned D, unsigned pos0, unsigned ratio) {
const unsigned b = blockIdx.x * 4 + threadIdx.x / 32, t = blockIdx.y, lane = threadIdx.x & 31;
if (b >= N) return;
float score = 0;
if (b >= (pos0 + t + 1) / ratio) score = -3e38f;
else for (unsigned h = 0; h < H; h++) {
float a = 0;
for (unsigned i = lane; i < D; i += 32)
a += q[((uint64_t)t * H + h) * D + i] * __half2float(key[(uint64_t)b * D + i]);
score += fmaxf(sum(a), 0);
}
if (!lane) out[(uint64_t)t * N + b] = score;
}
__global__ void tile_max(unsigned *out, const float *scores, unsigned N, unsigned tiles) {
const unsigned tile = blockIdx.x * blockDim.x + threadIdx.x, t = blockIdx.y;
if (tile >= tiles) return;
unsigned v = 0;
for (unsigned i = tile * 8; i < min(N, tile * 8 + 8); i++)
v = max(v, __float_as_uint(fmaxf(scores[(uint64_t)t * N + i], 0)));
out[(uint64_t)t * tiles + tile] = v;
}
/* Exact radix threshold and stable gather, with the same greater-than then
* equal-score ordering as Metal. No context-dependent candidate truncation. */
__global__ void idx_select(int *out, const float *score, unsigned N, unsigned K) {
const unsigned tid = threadIdx.x, t = blockIdx.x;
__shared__ unsigned hist[256], gt[256], eq[256], threshold, need;
const float *row = score + (uint64_t)t * N;
if (!tid) { threshold = 0; need = K; }
__syncthreads();
for (unsigned pass = 0; pass < 4; pass++) {
const unsigned shift = 24 - 8 * pass, mask = pass ? (0xffffffffu << (shift + 8)) : 0;
hist[tid] = 0;
__syncthreads();
for (unsigned i = tid; i < N; i += 256) {
const unsigned key = __float_as_uint(fmaxf(row[i], 0));
if ((key & mask) == threshold) atomicAdd(hist + ((key >> shift) & 255), 1u);
}
__syncthreads();
if (!tid) for (int d = 255; d >= 0; d--) {
if (hist[d] >= need) { threshold |= (unsigned)d << shift; break; }
need -= hist[d];
}
__syncthreads();
}
const unsigned chunk = (N + 255) / 256, begin = min(N, tid * chunk), end = min(N, begin + chunk);
unsigned ng = 0, ne = 0;
for (unsigned i = begin; i < end; i++) {
const unsigned key = __float_as_uint(fmaxf(row[i], 0));
ng += key > threshold; ne += key == threshold;
}
gt[tid] = ng; eq[tid] = ne;
__syncthreads();
if (!tid) {
unsigned pg = 0, pe = 0;
for (unsigned i = 0; i < 256; i++) {
const unsigned g = gt[i], e = eq[i];
gt[i] = pg; eq[i] = pe; pg += g; pe += e;
}
}
__syncthreads();
unsigned g = gt[tid], e = eq[tid];
for (unsigned i = begin; i < end; i++) {
const unsigned key = __float_as_uint(fmaxf(row[i], 0));
if (key > threshold) out[(uint64_t)t * K + g++] = i;
else if (key == threshold) { if (e < need) out[(uint64_t)t * K + K - need + e] = i; e++; }
}
}
__global__ void idx_expand(int *out, unsigned *count, const int *blocks,
unsigned K, unsigned ratio, unsigned pos0, unsigned stride) {
const unsigned t = blockIdx.x, pos = pos0 + t, tail = (pos + 1) / ratio * ratio;
for (unsigned i = threadIdx.x; i < K * ratio; i += blockDim.x)
out[(uint64_t)t * stride + i] = blocks[(uint64_t)t * K + i / ratio] * ratio + i % ratio;
for (unsigned i = tail + threadIdx.x; i <= pos; i += blockDim.x)
out[(uint64_t)t * stride + K * ratio + i - tail] = i;
if (!threadIdx.x) count[t] = K * ratio + pos + 1 - tail;
}
template<unsigned D>
__global__ void attention(float *out, float *partial, const float *q, const float *gate,
const __half *kc, const __half *vc, const int *sel, const unsigned *counts,
unsigned H, unsigned Hkv, unsigned pos0, unsigned stride, bool sparse,
unsigned splits, unsigned per, float scale) {
const unsigned h = blockIdx.x * 4 + threadIdx.x / 32, t = blockIdx.y, split = blockIdx.z;
if (h >= H) return;
const unsigned lane = threadIdx.x & 31, kh = h / (H / Hkv), n = sparse ? counts[t] : pos0 + t + 1;
float qv[D / 32], acc[D / 32] = {}, m = -3e38f, denom = 0;
for (unsigned i = 0; i < D / 32; i++) qv[i] = q[((uint64_t)t * H + h) * D + lane + 32 * i] * scale;
for (unsigned j = split * per; j < min(n, (split + 1) * per); j++) {
const unsigned p = sparse ? (unsigned)sel[(uint64_t)t * stride + j] : j;
if (p > pos0 + t) continue;
float score = 0;
for (unsigned i = 0; i < D / 32; i++) score += qv[i] * __half2float(kc[((uint64_t)p * Hkv + kh) * D + lane + 32 * i]);
score = sum(score);
const float nm = fmaxf(m, score), correction = expf(m - nm), w = expf(score - nm);
denom = denom * correction + w;
for (unsigned i = 0; i < D / 32; i++) acc[i] = acc[i] * correction + w * __half2float(vc[((uint64_t)p * Hkv + kh) * D + lane + 32 * i]);
m = nm;
}
if (splits == 1) {
for (unsigned i = 0; i < D / 32; i++) {
const uint64_t p = ((uint64_t)t * H + h) * D + lane + 32 * i;
out[p] = (denom > 0 ? acc[i] / denom : 0) * sigmoid(gate[p]);
}
} else {
float *dst = partial + (((uint64_t)t * H + h) * splits + split) * (D + 2);
if (!lane) { dst[0] = m; dst[1] = denom; }
for (unsigned i = 0; i < D / 32; i++) dst[2 + lane + 32 * i] = acc[i];
}
}
__global__ void attn_merge(float *out, const float *partial, const float *gate,
unsigned H, unsigned D, unsigned splits) {
const unsigned h = blockIdx.x, t = blockIdx.y, d = threadIdx.x;
if (d >= D) return;
const float *p = partial + ((uint64_t)t * H + h) * splits * (D + 2);
float m = -3e38f, denom = 0, acc = 0;
for (unsigned s = 0; s < splits; s++) m = fmaxf(m, p[s * (D + 2)]);
for (unsigned s = 0; s < splits; s++) {
const float *row = p + s * (D + 2);
const float w = row[1] > 0 ? expf(row[0] - m) : 0;
denom += row[1] * w; acc += row[2 + d] * w;
}
const uint64_t i = ((uint64_t)t * H + h) * D + d;
out[i] = (denom > 0 ? acc / denom : 0) * sigmoid(gate[i]);
}
/* The heads in a KV group share the same selected keys. Keep their output
* accumulators in registers and use tensor cores for both products. Scaled
* residual components retain the fine part of the FP32 queries/probabilities;
* K and V are already half, so neither requires further rounding. */
__global__ void attention_group(float *out, const float *q, const float *gate,
const __half *kc, const __half *vc, const int *sel, const unsigned *counts,
unsigned H, unsigned Hkv, unsigned pos0, unsigned stride, bool sparse, float scale) {
#if __CUDA_ARCH__ >= 800
const unsigned D = 256, tid = threadIdx.x, lane = tid&31, warp = tid/32;
const unsigned t = blockIdx.y, kh = blockIdx.x, group = H/Hkv;
const unsigned qr = tid/16, col = tid%16, h = kh*group+qr;
const unsigned n = sparse ? counts[t] : pos0+t+1;
__shared__ __align__(32) __half qh[16][264], ql[16][264], kv[32][264];
union Scores { float part[2][16][32]; __half prob[2][16][40]; };
__shared__ __align__(32) Scores scores;
__shared__ float qs[16], max_score[16], denom[16], correction[16];
__shared__ unsigned positions[32];
float mx = 0;
for (unsigned d = col; d < D; d += 16)
if (qr < group) mx = fmaxf(mx,fabsf(q[((uint64_t)t*H+h)*D+d]*scale));
for (unsigned off = 8; off; off /= 2) mx = fmaxf(mx,__shfl_xor_sync(0xffffffff,mx,off,16));
const int exp = mx > 0 ? max(-120,min(120,(int)((__float_as_uint(mx)>>23)&255)-127)) : 0;
const float inv = ldexpf(1,-exp);
if (!col) { qs[qr] = ldexpf(1,exp); max_score[qr] = -3e38f; denom[qr] = 0; }
for (unsigned d = col; d < D; d += 16) {
const float v = qr < group ? q[((uint64_t)t*H+h)*D+d]*scale*inv : 0;
qh[qr][d] = __float2half_rn(v);
ql[qr][d] = __float2half_rn((v-__half2float(qh[qr][d]))*4096);
}
float result[4][4] = {};
__syncthreads();
for (unsigned j0 = 0; j0 < n; j0 += 32) {
if (tid < 32) {
const unsigned j = j0+tid;
const unsigned p = j < n ? (sparse ? (unsigned)sel[(uint64_t)t*stride+j] : j) : UINT_MAX;
positions[t
10BC8
id] = p <= pos0+t ? p : UINT_MAX;
}
__syncthreads();
for (unsigned i = tid*8; i < 32*D; i += 256*8) {
const unsigned r = i/D, d = i%D, p = positions[r];
tt_cp_async_16B(&kv[r][d],kc+((uint64_t)(p == UINT_MAX ? 0 : p)*Hkv+kh)*D+d,p != UINT_MAX);
}
tt_cp_async_commit();
tt_cp_async_wait_group<0>();
__syncthreads();
float hi[4] = {}, lo[4] = {};
const unsigned split = warp/4, key0 = (warp%4)*8;
for (unsigned k = split*128; k < (split+1)*128; k += 16) {
uint32_t ah[4], al[4], b[2];
tt_ldmatrix_x4(ah,&qh[lane%16][k+(lane/16)*8]);
tt_ldmatrix_x4(al,&ql[lane%16][k+(lane/16)*8]);
tt_ldmatrix_x2(b,&kv[key0+lane%8][k+((lane%16)/8)*8]);
tt_mma_m16n8k16_f16_f32(hi,ah,b);
tt_mma_m16n8k16_f16_f32(lo,al,b);
}
#pragma unroll
for (unsigned i = 0; i < 4; i++)
scores.part[split][tt_mma_c_i(lane,i)][key0+tt_mma_c_j(lane,i)] = hi[i]+lo[i]*0x1p-12f;
__syncthreads();
float prob[2], peak = max_score[qr];
#pragma unroll
for (unsigned i = 0; i < 2; i++) {
const unsigned key = col+i*16;
prob[i] = positions[key] != UINT_MAX ?
(scores.part[0][qr][key]+scores.part[1][qr][key])*qs[qr] : -3e38f;
peak = fmaxf(peak,prob[i]);
}
for (unsigned off = 8; off; off /= 2) peak = fmaxf(peak,__shfl_xor_sync(0xffffffff,peak,off,16));
const float old = expf(max_score[qr]-peak);
float total = 0;
#pragma unroll
for (unsigned i = 0; i < 2; i++) {
prob[i] = positions[col+i*16] != UINT_MAX ? expf(prob[i]-peak) : 0;
total += prob[i];
}
for (unsigned off = 8; off; off /= 2) total += __shfl_xor_sync(0xffffffff,total,off,16);
__syncthreads();
if (!col) {
correction[qr] = old;
max_score[qr] = peak;
denom[qr] = denom[qr]*old+total;
}
#pragma unroll
for (unsigned i = 0; i < 2; i++) {
const __half p = __float2half_rn(prob[i]);
scores.prob[0][qr][col+i*16] = p;
scores.prob[1][qr][col+i*16] = __float2half_rn((prob[i]-__half2float(p))*4096);
}
for (unsigned i = tid*8; i < 32*D; i += 256*8) {
const unsigned r = i/D, d = i%D, p = positions[r];
tt_cp_async_16B(&kv[r][d],vc+((uint64_t)(p == UINT_MAX ? 0 : p)*Hkv+kh)*D+d,p != UINT_MAX);
}
tt_cp_async_commit();
tt_cp_async_wait_group<0>();
__syncthreads();
#pragma unroll
for (unsigned tile = 0; tile < 4; tile++) {
float hi[4] = {}, lo[4] = {};
#pragma unroll
for (unsigned k = 0; k < 32; k += 16) {
uint32_t ah[4], al[4], b[2];
tt_ldmatrix_x4(ah,&scores.prob[0][lane%16][k+(lane/16)*8]);
tt_ldmatrix_x4(al,&scores.prob[1][lane%16][k+(lane/16)*8]);
tt_ldmatrix_x2_trans(b,&kv[k+lane%16][warp*32+tile*8]);
tt_mma_m16n8k16_f16_f32(hi,ah,b);
tt_mma_m16n8k16_f16_f32(lo,al,b);
}
#pragma unroll
for (unsigned i = 0; i < 4; i++) result[tile][i] =
result[tile][i]*correction[tt_mma_c_i(lane,i)]+(hi[i]+lo[i]*0x1p-12f);
}
__syncthreads();
}
#pragma unroll
for (unsigned tile = 0; tile < 4; tile++) {
#pragma unroll
for (unsigned i = 0; i < 4; i++) {
const unsigned r = tt_mma_c_i(lane,i), d = warp*32+tile*8+tt_mma_c_j(lane,i);
if (r < group) {
const uint64_t dst = ((uint64_t)t*H+kh*group+r)*D+d;
out[dst] = (denom[r] > 0 ? result[tile][i]/denom[r] : 0)*sigmoid(gate[dst]);
}
}
}
#endif
}
static bool tensor(const ds4_gpu_tensor *t, uint64_t bytes) {
return t && t->ptr && bytes <= t->bytes;
}
static uint64_t row_bytes(uint32_t type, uint64_t n) {
switch (type) {
case 0: return n * 4;
case 1: case 30: return n * 2;
case 2: return n % 32 ? 0 : n / 32 * 18;
case 8: return n % 32 ? 0 : n / 32 * 34;
case 39: return n % 32 ? 0 : n / 32 * 17;
case 10: return n % 256 ? 0 : n / 256 * 84;
case 12: return n % 256 ? 0 : n / 256 * 144;
case 16: return n % 256 ? 0 : n / 256 * 66;
default: return 0;
}
}
static const char *weight(const void *map, uint64_t size, uint64_t off, uint64_t bytes) {
if (!map || !bytes || off > size || bytes > size - off) return NULL;
return cuda_resolve_weight_ptr(map, off, bytes, 0, "Qwen weights");
}
static int launched(void) { return cuda_ok(cudaGetLastError(), "Qwen kernel"); }
__device__ __forceinline__ float sum(float x) {
for (int d = 16; d; d >>= 1) x += __shfl_xor_sync(0xffffffff, x, d);
return x;
}
__device__ __forceinline__ float block_sum(float x, float *shared) {
x = sum(x);
if (!(threadIdx.x & 31)) shared[threadIdx.x / 32] = x;
__syncthreads();
float result = 0;
for (unsigned i = 0; i < blockDim.x / 32; i++) result += shared[i];
__syncthreads();
return result;
}
__device__ __forceinline__ float sigmoid(float x) {
const float e = expf(-fabsf(x));
return x >= 0 ? 1.0f / (1.0f + e) : e / (1.0f + e);
}
__device__ __forceinline__ float silu(float x) { return x * sigmoid(x); }
__device__ __forceinline__ float softplus(float x) {
return x > 20 ? x : x < -20 ? expf(x) : log1pf(expf(x));
}
/* These readers preserve the GGUF values, including padded Q2_K down rows.
* Templates remove unused formats from each matrix kernel. */
template<unsigned TYPE>
__device__ __forceinline__ float value(const char *row, unsigned i,
const uint64_t *grid_table = NULL, const uint8_t *sign_table = NULL) {
if (TYPE == 0) return ((const float *)row)[i];
if (TYPE == 1) return __half2float(((const __half *)row)[i]);
if (TYPE == 30) return __bfloat162float(((const __nv_bfloat16 *)row)[i]);
if (TYPE == 8) {
const char *b = row + (i / 32) * 34;
return __half2float(*(const __half *)b) * (float)((const int8_t *)b)[2 + i % 32];
}
if (TYPE == 2) {
const uint8_t *b = (const uint8_t *)row + (i / 32) * 18;
return __half2float(*(const __half *)b) *
(float)((int)((b[2 + i % 16] >> (4 * (i % 32 / 16))) & 15) - 8);
}
if (TYPE == 39) {
const uint8_t *b = (const uint8_t *)row + (i / 32) * 17;
const unsigned q = (b[1 + i % 16] >> (4 * (i % 32 / 16))) & 15;
const float levels[8] = {0, .5f, 1, 1.5f, 2, 3, 4, 6};
const float scale = b[0] == 0 ? 0x1p-127f : __uint_as_float((unsigned)b[0] << 23);
return (q & 8 ? -levels[q & 7] : levels[q & 7]) * scale;
}
if (TYPE == 10) {
const cuda_block_q2_K *b = (const cuda_block_q2_K *)row + i / 256;
const unsigned j = i % 256, sc = b->scales[j / 16];
const unsigned q = (b->qs[j / 128 * 32 + j % 32] >> (2 * (j % 128 / 32))) & 3;
return dev_f16_to_f32(b->d) * (sc & 15) * q - dev_f16_to_f32(b->dmin) * (sc >> 4);
}
if (TYPE == 12) {
const cuda_block_q4_K *b = (const cuda_block_q4_K *)row + i / 256;
const unsigned j = i % 256, group = j / 32;
unsigned sc, mn;
if (group < 4) { sc = b->scales[group] & 63; mn = b->scales[group + 4] & 63; }
else {
sc = (b->scales[group + 4] & 15) | ((b->scales[group - 4] >> 6) << 4);
mn = (b->scales[group + 4] >> 4) | ((b->scales[group] >> 6) << 4);
}
const unsigned q = (b->qs[j / 64 * 32 + j % 32] >> (4 * (group & 1))) & 15;
return dev_f16_to_f32(b->d) * sc * q - dev_f16_to_f32(b->dmin) * mn;
}
if (TYPE == 16) {
const cuda_block_iq2_xxs *b = (const cuda_block_iq2_xxs *)row + i / 256;
const unsigned j = i % 256, group = j / 32, sub = j % 32 / 8;
const uint16_t *p = b->qs + group * 4;
const unsigned grid_ids = (unsigned)p[0] | ((unsigned)p[1] << 16);
const unsigned signs_scale = (unsigned)p[2] | ((unsigned)p[3] << 16);
const unsigned gi = (grid_ids >> (8 * sub)) & 255, si = (signs_scale >> (7 * sub)) & 127;
const uint64_t grid = grid_table ? grid_table[gi] : cuda_iq2xxs_grid[gi];
const unsigned signs = sign_table ? sign_table[si] : cuda_ksigns_iq2xs[si];
float v = (float)((grid >> (8 * (j & 7))) & 255);
if (signs & (1u << (j & 7))) v = -v;
return dev_f16_to_f32(b->d) * (.5f + (signs_scale >> 28)) * .25f * v;
}
return 0;
}
__device__ __forceinline__ float scalar(const char *row, unsigned i, unsigned type) {
switch (type) {
case 0: return value<0>(row, i);
case 1: return value<1>(row, i);
case 2: return value<2>(row, i);
case 8: return value<8>(row, i);
case 30: return value<30>(row, i);
case 39: return value<39>(row, i);
default: return 0;
}
}
template<unsigned TYPE>
__device__ __forceinline__ float4 value4(const char *row, unsigned i,
const uint64_t *grid_table, const uint8_t *sign_table) {
float4 out;
float *v = (float *)&out;
if (TYPE == 1) {
const uint2 bits = *(const uint2 *)(row+i*2);
const float2 a = __half22float2(*(__half2 *)&bits.x), b = __half22float2(*(__half2 *)&bits.y);
out = make_float4(a.x,a.y,b.x,b.y);
} else if (TYPE == 0) {
out = *(const float4 *)(row+i*4);
} else if (TYPE == 8) {
const char *b = row+(i/32)*34;
const float scale = __half2float(*(const __half *)b);
const uint16_t *q = (const uint16_t *)(b+2+i%32);
out = make_float4((float)(int8_t)q[0]*scale,(float)(int8_t)(q[0]>>8)*scale,
(float)(int8_t)q[1]*scale,(float)(int8_t)(q[1]>>8)*scale);
} else if (TYPE == 39) {
const uint8_t *b = (const uint8_t *)row+(i/32)*17;
const float scale = b[0] == 0 ? 0x1p-127f : __uint_as_float((unsigned)b[0]<<23);
unsigned packed;
memcpy(&packed,b+1+i%16,4);
#pragma unroll
for (unsigned k = 0; k < 4; k++) {
const unsigned q = (packed>>(k*8+(i%32/16)*4))&15, mag = q&7;
const float level = mag < 2 ? .5f*mag : __uint_as_float(((mag/2+126)<<23)|((mag&1)<<22));
v[k] = (q&8 ? -level : level)*scale;
}
} else if (TYPE == 16) {
const cuda_block_iq2_xxs *b = (const cuda_block_iq2_xxs *)row+i/256;
const unsigned j = i%256, sub = (j%32)/8;
const uint16_t *p = b->qs+(j/32)*4;
const unsigned ids = (unsigned)p[0]|((unsigned)p[1]<<16);
const unsigned ss = (unsigned)p[2]|((unsigned)p[3]<<16);
const uint64_t grid = grid_table[(ids>>(8*sub))&255];
const unsigned signs = sign_table[(ss>>(7*sub))&127];
const float scale = dev_f16_to_f32(b->d)*(.5f+(ss>>28))*.25f;
/* Apply four signs before conversion. IQ2's nonzero magnitudes keep
* the packed negations from carrying into neighboring bytes. */
const unsigned offset = j&7;
const unsigned bits = (((signs>>offset)&15)*0x00204081u)&0x01010101u;
const unsigned packed = (((unsigned)(grid>>(8*offset)))^(bits*255u))+bits;
#pragma unroll
for (unsigned k = 0; k < 4; k++) {
v[k] = scale*(float)(int8_t)(packed>>(8*k));
}
} else if (TYPE == 10 || TYPE == 12) {
const unsigned j = i%256;
unsigned sc, mn, qs, shift;
float d, dm;
if (TYPE == 10) {
const cuda_block_q2_K *b = (const cuda_block_q2_K *)row+i/256;
const unsigned s = b->scales[j/16];
sc = s&15; mn = s>>4;
d = dev_f16_to_f32(b->d); dm = dev_f16_to_f32(b->dmin);
qs = *(const unsigned *)(b->qs+(j/128)*32+j%32);
shift = 2*((j%128)/32);
} else {
const cuda_block_q4_K *b = (const cuda_block_q4_K *)row+i/256;
const unsigned group = j/32;
if (group < 4) { sc = b->scales[group]&63; mn = b->scales[group+4]&63; }
else {
sc = (b->scales[group+4]&15)|((b->scales[group-4]>>6)<<4);
mn = (b->scales[group+4]>>4)|((b->scales[group]>>6)<<4);
}
d = dev_f16_to_f32(b->d); dm = dev_f16_to_f32(b->dmin);
qs = *(const unsigned *)(b->qs+(j/64)*32+j%32);
shift = 4*(group&1);
}
const float scale = d*sc, offset = dm*mn;
#pragma unroll
for (unsigned k = 0; k < 4; k++) v[k] = scale*((qs>>(8*k+shift))&(TYPE == 10 ? 3 : 15))-offset;
} else {
#pragma unroll
for (unsigned k = 0; k < 4; k++) v[k] = value<TYPE>(row,i+k,grid_table,sign_table);
}
return out;
}
static uint64_t expert_row_bytes(unsigned type, unsigned K) {
if (type == 10 && K % 32) return 0;
return row_bytes(type, type == 10 ? ((uint64_t)K + 255) / 256 * 256 : K);
}
__global__ void router(int *selected, float *weights, const float *logits,
const float *x, const char *gate, float *shared_gate,
unsigned NE, unsigned NS, unsigned K, unsigned type) {
const unsigned t = blockIdx.x, tid = threadIdx.x;
__shared__ float p[512], maxima[256], red[32];
__shared__ unsigned ids[256];
float mx = -FLT_MAX;
for (unsigned e = tid; e < NE; e += 256) mx = fmaxf(mx, logits[(uint64_t)t * NE + e]);
maxima[tid] = mx;
__syncthreads();
for (unsigned stride = 128; stride; stride /= 2) {
if (tid < stride) maxima[tid] = fmaxf(maxima[tid], maxima[tid + stride]);
__syncthreads();
}
mx = maxima[0];
float ps = 0;
for (unsigned e = tid; e < NE; e += 256) { p[e] = expf(logits[(uint64_t)t * NE + e] - mx); ps += p[e]; }
const float total = block_sum(ps, red);
for (unsigned e = tid; e < NE; e += 256) p[e] /= total;
if (K) {
float v = 0;
for (unsigned i = tid; i < K; i += 256) v += scalar(gate, i, type) * x[(uint64_t)t * K + i];
v = block_sum(v, red);
if (!tid) shared_gate[t] = v;
}
__syncthreads();
for (unsigned s = 0; s < NS; s++) {
float best = -1;
unsigned id = UINT_MAX;
for (unsigned e = tid; e < NE; e += 256) if (p[e] > best) { best = p[e]; id = e; }
maxima[tid] = best; ids[tid] = id;
__syncthreads();
for (unsigned stride = 128; stride; stride /= 2) {
if (tid < stride && (maxima[tid + stride] > maxima[tid] ||
(maxima[tid + stride] == maxima[tid] && ids[tid + stride] < ids[tid]))) {
maxima[tid] = maxima[tid + stride]; ids[tid] = ids[tid + stride];
}
__syncthreads();
}
if (!tid) {
selected[(uint64_t)t * NS + s] = ids[0];
weights[(uint64_t)t * NS + s] = maxima[0];
p[ids[0]] = -1;
}
__syncthreads();
}
if (tid < NS) {
float denom = 0;
for (unsigned s = 0; s < NS; s++) denom += weights[(uint64_t)t * NS + s];
red[tid] = denom;
}
__syncthreads();
if (tid < NS) weights[(uint64_t)t * NS + tid] /= red[tid];
}
template<unsigned TYPE, bool DOWN>
__global__ void moe_mv(float *out, const float *x, const int *selected,
const char *w0, const char *w1, const char *sh0, const char *sh1,
unsigned shared_type, unsigned NE, unsigned NS, unsigned K, unsigned M,
uint64_t rb, uint64_t srb) {
const unsigned row = blockIdx.x * 4 + threadIdx.x / 32, slot = blockIdx.y, t = blockIdx.z;
__shared__ uint64_t grid_table[TYPE == 16 ? 256 : 1];
__shared__ uint8_t sign_table[TYPE == 16 ? 128 : 1];
if (TYPE == 16) {
for (unsigned i = threadIdx.x; i < 256; i += blockDim.x) grid_table[i] = cuda_iq2xxs_grid[i];
for (unsigned i = threadIdx.x; i < 128; i += blockDim.x) sign_table[i] = cuda_ksigns_iq2xs[i];
__syncthreads();
}
if (row >= M) return;
const bool shared = slot == NS;
const unsigned stride = NS + (shared_type != UINT_MAX);
const uint64_t pair = (uint64_t)t * stride + slot;
const float *xt = x + (DOWN ? pair : t) * K;
float a = 0, b = 0;
if (shared) {
for (unsigned i = threadIdx.x & 31; i < K; i += 32) {
a += scalar(sh0 + row * srb, i, shared_type) * xt[i];
if (!DOWN) b += scalar(sh1 + row * srb, i, shared_type) * xt[i];
}
a = sum(a); b = sum(b);
} else {
const int e = selected[(uint64_t)t * NS + slot];
if (e >= 0 && (unsigned)e < NE) {
const uint64_t off = ((uint64_t)e * M + row) * rb;
if ((TYPE == 16 || TYPE == 10 || TYPE == 12 || TYPE == 39) && !((uintptr_t)xt&15)) {
for (unsigned i = (threadIdx.x&31)*4; i < K; i += 128) {
const float4 xv = *(const float4 *)(xt+i);
const float4 av = value4<TYPE>(w0+off,i,grid_table,sign_table);
a += av.x*xv.x; a += av.y*xv.y; a += av.z*xv.z; a += av.w*xv.w;
if (!DOWN) {
const float4 bv = value4<TYPE>(w1+off,i,grid_table,sign_table);
b += bv.x*xv.x; b += bv.y*xv.y; b += bv.z*xv.z; b += bv.w*xv.w;
}
}
a = sum(a); b = sum(b);
} else {
a = dot<TYPE>(w0+off,xt,K,grid_table,sign_table);
if (!DOWN) b = dot<TYPE>(w1+off,xt,K,grid_table,sign_table);
}
}
}
if (!(threadIdx.x & 31)) out[pair * M + row] = DOWN ? a : silu(a) * b;
}
static int moe_mv_dispatch(float *out, const float *x, const int *sel,
const char *w0, const char *w1, const char *s0, const char *s1,
unsigned type, unsigned st, unsigned NE, unsigned T, unsigned NS, unsigned K, unsigned M, bool down) {
const uint64_t rb = expert_row_bytes(type, K), srb = row_bytes(st, K);
const dim3 grid((M + 3) / 4, NS + (st != UINT_MAX), T);
#define QWEN_MOE(TYPE) case TYPE: \
if (down) moe_mv<TYPE, true><<<grid,128,0,cuda_decode_stream()>>>(out,x,sel,w0,w1,s0,s1,st,NE,NS,K,M,rb,srb); \
else moe_mv<TYPE, false><<<grid,128,0,cuda_decode_stream()>>>(out,x,sel,w0,w1,s0,s1,st,NE,NS,K,M,rb,srb); break
switch (type) {
QWEN_MOE(0); QWEN_MOE(1); QWEN_MOE(2); QWEN_MOE(8); QWEN_MOE(10);
QWEN_MOE(12); QWEN_MOE(16); QWEN_MOE(30); QWEN_MOE(39);
default: return 0;
}
#undef QWEN_MOE
return launched();
}
__global__ void moe_reduce(float *out, float *R, const float *inj, const float *part,
const float *weights, const float *gate, const float *shared,
unsigned NS, unsigned stride, unsigned D, unsigned hc) {
const unsigned d = blockIdx.x * blockDim.x + threadIdx.x, t = blockIdx.y;
__shared__ float inject[4];
if (threadIdx.x < hc) inject[threadIdx.x] = injection(inj + (uint64_t)t * hc * hc * 8, hc, threadIdx.x);
__syncthreads();
if (d >= D) return;
float v = 0;
for (unsigned s = 0; s < NS; s++) v += weights[(uint64_t)t * NS + s] * part[((uint64_t)t * stride + s) * D + d];
if (gate) v += sigmoid(gate[t]) * (shared ? shared[(uint64_t)t * D + d] : part[((uint64_t)t * stride + NS) * D + d]);
out[(uint64_t)t * D + d] = v;
for (unsigned s = 0; s < hc; s++) R[((uint64_t)t * hc + s) * D + d] += inject[s] * v;
}
__global__ void expert_lists(int *lists, int *counts, const int *selected,
unsigned pairs, unsigned NE, unsigned cap) {
__shared__ unsigned counters[512];
for (unsigned e = threadIdx.x; e < NE; e += blockDim.x) counters[e] = 0;
__syncthreads();
for (unsigned p = threadIdx.x; p < pairs; p += blockDim.x) {
const unsigned e = (unsigned)selected[p];
if (e < NE) {
const unsigned i = atomicAdd(counters + e, 1u);
if (i < cap) lists[(uint64_t)e * cap + i] = p;
}
}
__syncthreads();
for (unsigned e = threadIdx.x; e < NE; e += blockDim.x) counts[e] = min(counters[e], cap);
}
/* Tiles share dequantized weights across 16 tokens without requantizing the
* activations. Expert counts determine the work; no expert list is truncated. */
template<unsigned TYPE, bool DOWN, bool EXPERT>
__global__ void matrix(float *out, const float *x, const char *w0, const char *w1,
const int *lists, const int *counts, unsigned T, unsigned NS, unsigned NO,
unsigned K, unsigned M, unsigned cap, uint64_t rb) {
const unsigned r = threadIdx.x % 16, c = threadIdx.x / 16, e = blockIdx.y;
const unsigned row = blockIdx.x * 16 + r;
const unsigned count = EXPERT ? (unsigned)counts[e] : T;
__shared__ float a[16][33], b[16][33], v[16][33];
for (unsigned t0 = blockIdx.z * 16; t0 < count; t0 += gridDim.z * 16) {
const unsigned item = t0 + c;
const int pair = EXPERT && item < count ? lists[(uint64_t)e * cap + item] : (int)item;
const unsigned tok = EXPERT ? pair / NS : item, slot = EXPERT ? pair % NS : 0;
float acc = 0, up = 0;
for (unsigned k0 = 0; k0 < K; k0 += 32) {
for (unsigned j = threadIdx.x; j < 16 * 32; j += 256) {
const unsigned rr = j / 32, kk = j % 32, global_row = blockIdx.x * 16 + rr;
const unsigned logical = k0 + kk;
const char *wr = w0 + ((uint64_t)(EXPERT ? e : 0) * M + global_row) * rb;
a[rr][kk] = global_row < M && logical < K ? value<TYPE>(wr, logical) : 0;
if (EXPERT && !DOWN) {
const char *ur = w1 + ((uint64_t)e * M + global_row) * rb;
b[rr][kk] = global_row < M && logical < K ? value<TYPE>(ur, logical) : 0;
}
const unsigned ti = t0 + rr;
const int pp = EXPERT && ti < count ? lists[(uint64_t)e * cap + ti] : (int)ti;
const unsigned tt = EXPERT ? pp / NS : ti, ss = EXPERT ? pp % NS : 0;
const uint64_t xx = DOWN && EXPERT ? (uint64_t)tt * NO + ss : tt;
v[rr][kk] = ti < count && logical < K ? x[xx * K + logical] : 0;
}
__syncthreads();
#pragma unroll
for (unsigned k = 0; k < 32; k++) {
acc += a[r][k] * v[c][k];
if (EXPERT && !DOWN) up += b[r][k] * v[c][k];
}
__syncthreads();
}
if (row < M && item < count) {
const uint64_t op = EXPERT ? (uint64_t)tok * NO + slot : item;
out[op * M + row] = EXPERT && !DOWN ? silu(acc) * up : acc;
}
}
}
__global__ void expert_tiles(unsigned *prefix, const int *counts, unsigned NE, unsigned nt) {
unsigned n = 0;
prefix[0] = 0;
for (unsigned e = 0; e < NE; e++) {
n += ((unsigned)counts[e]+nt-1)/nt;
prefix[e+1] = n;
}
}
/* Two TF32 components retain the fine part of each FP32 operand. Keep the
* correction products in their own accumulator: repeatedly adding them to
* the much larger leading product loses their precision on tensor cores. */
template<unsigned TYPE>
__global__ void matrix_tc(float *out, const float *x, const char *w0,
unsigned T, unsigned K, unsigned M, uint64_t rb) {
#if __CUDA_ARCH__ >= 800
namespace wm = nvcuda::wmma;
const unsigned tid = threadIdx.x, warp = tid/32, r0 = blockIdx.x*64;
/* Padding separates the banks of adjacent rows in the TF32 fragment
* loads. The leading planes also hold the completed output tiles. */
__shared__ __align__(32) float ah[64][36], al[64][36];
__shared__ __align__(32) float bh[16][36], bl[16][36];
for (unsigned t0 = blockIdx.z*16; t0 < T; t0 += gridDim.z*16) {
wm::fragment<wm::accumulator,16,16,8,float> acc, corr, total;
wm::fill_fragment(acc,0);
wm::fill_fragment(corr,0);
wm::fill_fragment(total,0);
for (unsigned k0 = 0; k0 < K; k0 += 32) {
for (unsigned j = tid; j < 64*32; j += 128) {
const unsigned r = j/32, kk = j%32, row = r0+r, col = k0+kk;
const uint64_t off = (uint64_t)row*rb;
const float a = row < M && col < K ? value<TYPE>(w0+off,col) : 0;
ah[r][kk] = wm::__float_to_tf32(a);
al[r][kk] = wm::__float_to_tf32(a-ah[r][kk]);
}
for (unsigned j = tid; j < 16*32; j += 128) {
const unsigned item = t0+j/32, kk = j%32, col = k0+kk;
const float b = item < T && col < K ? x[(uint64_t)item*K+col] : 0;
bh[j/32][kk] = wm::__float_to_tf32(b);
bl[j/32][kk] = wm::__float_to_tf32(b-bh[j/32][kk]);
}
__syncthreads();
#pragma unroll
for (unsigned k = 0; k < 32; k += 8) {
wm::fragment<wm::matrix_a,16,16,8,wm::precision::tf32,wm::row_major> a, alo;
wm::fragment<wm::matrix_b,16,16,8,wm::precision::tf32,wm::col_major> b, blo;
wm::load_matrix_sync(a,&ah[warp*16][k],36);
wm::load_matrix_sync(alo,&al[warp*16][k],36);
wm::load_matrix_sync(b,&bh[0][k],36);
wm::load_matrix_sync(blo,&bl[0][k],36);
wm::mma_sync(corr,alo,blo,corr);
wm::mma_sync(corr,alo,b,corr);
wm::mma_sync(corr,a,blo,corr);
wm::mma_sync(acc,a,b,acc);
}
__syncthreads();
/* Bound tensor-core accumulation depth. CUDA FP32 adds the
* partial sums, avoiding drift on long HC projection rows. */
if ((k0+32)%256 == 0 || k0+32 >= K) {
for (unsigned i = 0; i < acc.num_elements; i++) {
total.x[i] += acc.x[i] + corr.x[i];
}
wm::fill_fragment(acc,0);
wm::fill_fragment(corr,0);
}
}
wm::store_matrix_sync(&ah[warp*16][0],total,36,wm::mem_row_major);
__syncthreads();
for (unsigned j = tid; j < 64*16; j += 128) {
const unsigned row = r0+j/16, item = t0+j%16;
if (row < M && item < T) out[(uint64_t)item*M+row] = ah[j/16][j%16];
}
__syncthreads();
}
#endif
}
__device__ __forceinline__ void mma_tf32(float (&c)[4], const unsigned (&a)[4], const unsigned (&b)[2]) {
#if __CUDA_ARCH__ >= 800
asm volatile("mma.sync.aligned.m16n8k8.row.col.f32.tf32.tf32.f32 "
"{%0,%1,%2,%3}, {%4,%5,%6,%7}, {%8,%9}, {%0,%1,%2,%3};"
: "+f"(c[0]), "+f"(c[1]), "+f"(c[2]), "+f"(c[3])
: "r"(a[0]), "r"(a[1]), "r"(a[2]), "r"(a[3]), "r"(b[0]), "r"(b[1]));
#endif
}
template<unsigned TYPE, bool DOWN, unsigned NC>
__global__ void matrix_reg(float *out, const float *x, const char *w0, const char *w1,
const int *lists, const int *counts, const unsigned *tiles, unsigned NE,
unsigned NS, unsigned NO, unsigned K, unsigned M, unsigned cap, uint64_t rb) {
#if __CUDA_ARCH__ >= 800
const unsigned lane = threadIdx.x&31, warp = threadIdx.x/32;
const unsigned row_tiles = (M+31)/32, job = blockIdx.x/row_tiles;
if (job >= tiles[NE]) return;
__shared__ uint64_t grid_table[TYPE == 16 ? 256 : 1];
__shared__ uint8_t sign_table[TYPE == 16 ? 128 : 1];
if (TYPE == 16) {
for (unsigned i = threadIdx.x; i < 256; i += blockDim.x) grid_table[i] = cuda_iq2xxs_grid[i];
for (unsigned i = threadIdx.x; i < 128; i += blockDim.x) sign_table[i] = cuda_ksigns_iq2xs[i];
__syncthreads();
}
unsigned e = 0, end = NE;
while (e < end) {
const unsigned mid = (e+end)/2;
if (tiles[mid+1] <= job) e = mid+1;
else end = mid;
}
const unsigned count = counts[e], t0 = (job-tiles[e])*16*NC;
const unsigned r0 = (blockIdx.x%row_tiles)*32+(warp%2)*16, c0 = t0+(warp/2)*8*NC;
if (r0 >= M || c0 >= count) return;
float acc[NC][4] = {}, corr[NC][4] = {}, total[NC][4] = {};
float uacc[NC][4] = {}, ucorr[NC][4] = {}, utotal[NC][4] = {};
const float *xp[NC];
#pragma unroll
for (unsigned nc = 0; nc < NC; nc++) {
const unsigned item = c0+nc*8+lane/4;
const unsigned pair = item < count ? lists[(uint64_t)e*cap+item] : 0;
xp[nc] = x+(DOWN ? (uint64_t)(pair/NS)*NO+pair%NS : pair/NS)*K;
}
for (unsigned k0 = 0; k0 < K; k0 += 8) {
unsigned a[4], al[4], u[4], ul[4], b[2], bl[2];
#pragma unroll
for (unsigned i = 0; i < 4; i++) {
const unsigned r = r0+lane/4+(i%2)*8, k = k0+lane%4+(i/2)*4;
const uint64_t off = ((uint64_t)e*M+r)*rb;
const float v = r < M && k < K ? value<TYPE>(w0+off,k,grid_table,sign_table) : 0;
const float hi = nvcuda::wmma::__float_to_tf32(v);
a[i] = __float_as_uint(hi);
al[i] = __float_as_uint(nvcuda::wmma::__float_to_tf32(v-hi));
if (!DOWN) {
const float v = r < M && k < K ? value<TYPE>(w1+off,k,grid_table,sign_table) : 0;
const float hi = nvcuda::wmma::__float_to_tf32(v);
u[i] = __float_as_uint(hi);
ul[i] = __float_as_uint(nvcuda::wmma::__float_to_tf32(v-hi));
}
}
#pragma unroll
for (unsigned nc = 0; nc < NC; nc++) {
if (c0+nc*8 >= count) continue;
const unsigned item = c0+nc*8+lane/4;
#pragma unroll
for (unsigned i = 0; i < 2; i++) {
const unsigned k = k0+lane%4+i*4;
const float v = item < count && k < K ? xp[nc][k] : 0;
const float hi = nvcuda::wmma::__float_to_tf32(v);
b[i] = __float_as_uint(hi);
bl[i] = __float_as_uint(nvcuda::wmma::__float_to_tf32(v-hi));
}
mma_tf32(corr[nc],al,bl);
mma_tf32(corr[nc],al,b);
mma_tf32(corr[nc],a,bl);
mma_tf32(acc[nc],a,b);
if (!DOWN) {
mma_tf32(ucorr[nc],ul,bl);
mma_tf32(ucorr[nc],ul,b);
mma_tf32(ucorr[nc],u,bl);
mma_tf32(uacc[nc],u,b);
}
if ((k0+8)%256 == 0 || k0+8 >= K) {
#pragma unroll
for (unsigned i = 0; i < 4; i++) {
total[nc][i] += acc[nc][i]+corr[nc][i];
acc[nc][i] = corr[nc][i] = 0;
if (!DOWN) { utotal[nc][i] += uacc[nc][i]+ucorr[nc][i]; uacc[nc][i] = ucorr[nc][i] = 0; }
}
}
}
}
#pragma unroll
for (unsigned nc = 0; nc < NC; nc++) {
#pragma unroll
for (unsigned i = 0; i < 4; i++) {
const unsigned row = r0+lane/4+(i/2)*8, item = c0+nc*8+(lane%4)*2+(i%2);
if (row < M && item < count) {
const unsigned pair = lists[(uint64_t)e*cap+item];
out[((uint64_t)(pair/NS)*NO+pair%NS)*M+row] = DOWN ? total[nc][i] : silu(total[nc][i])*utotal[nc][i];
}
}
}
#endif
}
/* Match the half operands of the production Metal expert tiles. Products
* accumulate in FP32; only the matrix operands are rounded to half. */
template<unsigned TYPE, bool DOWN, unsigned NT, unsigned NR = 64>
__global__ void matrix_half_tile(float *out, const float *x, const char *w0, const char *w1,
const int *lists, const int *counts, const unsigned *tiles, unsigned NE,
unsigned NS, unsigned NO, unsigned K, unsigned M, unsigned cap, uint64_t rb) {
#if __CUDA_ARCH__ >= 800
namespace wm = nvcuda::wmma;
const unsigned tid = threadIdx.x, warp = tid/32, nr = (M+NR-1)/NR, job = blockIdx.x/nr;
if (job >= tiles[NE]) return;
unsigned e = 0, end = NE;
while (e < end) {
const unsigned mid = (e+end)/2;
if (tiles[mid+1] <= job) e = mid+1; else end = mid;
}
const unsigned count = counts[e], t0 = (job-tiles[e])*NT, r0 = (blockIdx.x%nr)*NR;
const unsigned wr = warp%(NR/16), wc = warp/(NR/16);
constexpr unsigned NC = NT/(8/(NR/16));
union Tile {
__half ab[(NR+(DOWN ? 0 : NR)+NT)*72];
float c[NR][NT];
};
__shared__ __align__(32) Tile tile;
__half (*a)[72] = (__half (*)[72])tile.ab;
__half (*u)[72] = a+NR;
__half (*b)[72] = a+NR+(DOWN ? 0 : NR);
__shared__ uint64_t grid_table[TYPE == 16 ? 256 : 1];
__shared__ uint8_t sign_table[TYPE == 16 ? 128 : 1];
if (TYPE == 16) {
for (unsigned i = tid; i < 256; i += 256) grid_table[i] = cuda_iq2xxs_grid[i];
for (unsigned i = tid; i < 128; i += 256) sign_table[i] = cuda_ksigns_iq2xs[i];
__syncthreads();
}
wm::fragment<wm::accumulator,16,16,16,float> acc[NC/16], up[NC/16];
#pragma unroll
for (unsigned j = 0; j < NC/16; j++) {
wm::fill_fragment(acc[j],0);
if (!DOWN) wm::fill_fragment(up[j],0);
}
for (unsigned k0 = 0; k0 < K; k0 += 64) {
for (unsigned i = tid*4; i < NR*64; i += 256*4) {
const unsigned row = r0+i/64, k = k0+i%64;
const uint64_t off = ((uint64_t)e*M+row)*rb;
const float4 av = row < M && k < K ? value4<TYPE>(w0+off,k,grid_table,sign_table) : make_float4(0,0,0,0);
*(__half2 *)&a[i/64][i%64] = __floats2half2_rn(av.x,av.y);
*(__half2 *)&a[i/64][i%64+2] = __floats2half2_rn(av.z,av.w);
if (!DOWN) {
const float4 uv = row < M && k < K ? value4<TYPE>(w1+off,k,grid_table,sign_table) : make_float4(0,0,0,0);
*(__half2 *)&u[i/64][i%64] = __floats2half2_rn(uv.x,uv.y);
*(__half2 *)&u[i/64][i%64+2] = __floats2half2_rn(uv.z,uv.w);
}
}
for (unsigned i = tid; i < NT*64; i += 256) {
const unsigned item = t0+i/64, k = k0+i%64;
const unsigned pair = item < count ? lists[(uint64_t)e*cap+item] : 0;
const uint64_t row = DOWN ? (uint64_t)(pair/NS)*NO+pair%NS : pair/NS;
b[i/64][i%64] = __float2half_rn(item < count && k < K ? x[row*K+k] : 0);
}
__syncthreads();
#pragma unroll
for (unsigned k = 0; k < 64; k += 16) {
wm::fragment<wm::matrix_a,16,16,16,__half,wm::row_major> af, uf;
wm::load_matrix_sync(af,&a[wr*16][k],72);
if (!DOWN) wm::load_matrix_sync(uf,&u[wr*16][k],72);
#pragma unroll