Repository navigation
Expand file tree
/
Copy pathvulkan_ops.cpp
More file actions
2729 lines (2603 loc) · 138 KB
/
Copy pathvulkan_ops.cpp
File metadata and controls
2729 lines (2603 loc) · 138 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
// Vulkan backend — op kernels: descriptor binding + dispatch of the committed
// SPIR-V in vulkan_spirv.h, plus the `RegisterOp` table entries. BACKEND-VULKAN,
// W0 skeleton. Self-registering TU, copying the `src/vt/cpu/cpu_ops.cpp`
// Registrar idiom exactly, so adding this backend edited NO existing kernel file.
//
// WHAT THIS TU COVERS (deliberately a SEAM PROOF, not a model):
// kAdd, kRelu, kSiluAndMul, kCastBf16, kCastF32, kLayerNorm, kRmsNorm and the
// single kFusedChain registration that inherits the portable fusion catalog.
// That set spans every structural class the seam has to get right: flat
// elementwise, a rank-1 broadcast, a dtype-converting copy, TWO different row
// reductions, an optional in-place residual stream, and the recipe interpreter.
// It matches the Metal skeleton's set exactly, so the two backends are directly
// comparable through tests/vt/test_backend_cross_device.cpp.
//
// SINCE THEN this TU has grown the dense path (both GEMM orientations plus the
// decode GEMV and coopmat tactics), the attention block (paged attention, the KV
// write, the QKV split, the rotary apply), the two ends of the model (embedding
// and greedy argmax), and — this row, BACKEND-VULKAN-GDN — six of the GDN /
// conv1d glue ops that Qwen3.6-27B needs.
//
// WHAT IS STILL NOT REGISTERED: the quant tier, MoE, the sampler beyond greedy
// argmax, the GDN recurrences themselves, and the ops listed in the
// BACKEND-VULKAN-GDN block comment further down. None of them THROW any more:
// since the portable reference tier landed, a missed GetOp on this
// unified-memory device installs the CPU kernel as a priority -1000 provider, so
// an unregistered op is CORRECT AND SLOW rather than fatal.
//
// BINDING MODEL: every tensor operand occupies TWO consecutive descriptor
// bindings onto the SAME VkBuffer — a uint32_t view and a uint16_t view — and
// its BYTE OFFSET travels in the push constants. See
// src/vt/vulkan/shaders/vt_common.glsl § STORAGE MODEL for why.
#include <algorithm>
#include <atomic>
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <mutex>
#include <set>
#include <string>
#include <vector>
#include "vulkan_buffers.h"
#include "vulkan_context.h"
#include "vt/ops.h"
#include "vt/quant.h"
namespace vt::vulkan {
namespace {
// Gated on the same flag as the dispatch profile; costs nothing when unset.
const bool kCoopMatWhy = [] {
const char* v = std::getenv("VT_VULKAN_DISPATCH_STATS");
return v != nullptr && std::strcmp(v, "0") != 0;
}();
// Storage dtype -> the shader-side code (vt_common.glsl VT_DT_*).
uint32_t DtypeCode(DType d) {
switch (d) {
case DType::kF32: return 0;
case DType::kF16: return 1;
case DType::kBF16: return 2;
default: break;
}
VT_CHECK(false, "vulkan: unsupported storage dtype (f32/f16/bf16 only in the W0 skeleton)");
return 0;
}
// Collects the (buffer, byte-offset) pairs for a dispatch. Each Add() appends
// the SAME buffer twice — bindings 2k and 2k+1, the u32 and u16 views — and
// returns the byte offset for the push-constant block.
class Binder {
public:
uint32_t Add(const Tensor& t, const char* what) {
Resolved r = Resolve(t.data, what);
buffers_.push_back(r.buffer);
buffers_.push_back(r.buffer);
// f32 access indexes a uint32_t[] view, so a f32 operand's byte offset must
// be 4-byte aligned; 16-bit access only needs 2. Tensor storage always
// satisfies this (allocations are 64-byte aligned and views advance by whole
// elements), but a violation would silently read shifted data.
VT_CHECK(t.dtype != DType::kF32 || r.offset % 4 == 0,
std::string("vulkan: ") + what + " has a byte offset that is not 4-byte aligned");
VT_CHECK(r.offset % 2 == 0,
std::string("vulkan: ") + what + " has an odd byte offset");
return r.offset;
}
// A raw buffer bound ONCE (no 16-bit view): the fused-chain step list.
void AddRaw(void* buffer) { buffers_.push_back(buffer); }
// ONE MORE VIEW of an operand already added, for a shader that reads the same
// memory at a THIRD width (vt_matmul_vec's 64-bit packed loads). Deliberately
// separate from Add: this appends a SINGLE binding, and it must land after
// every operand's u32/u16 pair, so the caller is choosing the descriptor index
// rather than getting one implicitly.
uint32_t AddAlias(const Tensor& t, const char* what) {
Resolved r = Resolve(t.data, what);
buffers_.push_back(r.buffer);
return r.offset;
}
// A tensor bound through the uint32_t view ONLY, for shaders that declare a
// single binding per operand because the operand is integer (embedding ids,
// sampler token ids) or f32-by-contract (logits). Binding the unused 16-bit
// view would need the shader to declare it too, and a descriptor a shader does
// not declare must not be written.
uint32_t AddU32Only(const Tensor& t, const char* what) {
Resolved r = Resolve(t.data, what);
buffers_.push_back(r.buffer);
VT_CHECK(r.offset % 4 == 0,
std::string("vulkan: ") + what + " has a byte offset that is not 4-byte aligned");
return r.offset;
}
// A tensor bound through the uint32_t view ONLY, for BYTE-granular reads: an
// i8 operand (GDN's has_initial_state) may legitimately start at any byte, so
// AddU32Only's 4-byte assertion would reject a valid tensor. The shader
// recovers the byte with a shift, which is exact because every buffer is bound
// WHOLE at offset 0 and the returned offset is therefore a plain byte address
// into it (vt_common.glsl § STORAGE MODEL). Deliberately NOT VK_KHR_8bit_storage:
// this backend does not probe for it, and requiring it would narrow the set of
// devices the backend registers on for the sake of one boolean array.
uint32_t AddByteView(const Tensor& t, const char* what) {
Resolved r = Resolve(t.data, what);
buffers_.push_back(r.buffer);
return r.offset;
}
// A tensor bound through the uint16_t view ONLY, the mirror of AddU32Only for
// an operand every consumer reads at 16 bits: an fp16 scale vector, or the
// EXL3 trellis, whose i8 BYTES are read as the uint32 pairs exl3_dq.cuh reads
// and never as f32. Binding the unused 32-bit view would need the shader to
// declare it too, and glslang strips a block nothing references — which the
// generator then reports as a binding HOLE rather than passing silently.
// The 2-byte assertion is Add()'s, and it is the real constraint here.
uint32_t AddU16Only(const Tensor& t, const char* what) {
Resolved r = Resolve(t.data, what);
buffers_.push_back(r.buffer);
VT_CHECK(r.offset % 2 == 0,
std::string("vulkan: ") + what + " has an odd byte offset");
return r.offset;
}
const void* const* data() const { return buffers_.data(); }
uint32_t count() const { return static_cast<uint32_t>(buffers_.size()); }
private:
std::vector<const void*> buffers_;
};
// ---- Host mirrors of the shaders' push-constant blocks. Field order and types
// must match the GLSL declarations EXACTLY. GLSL `uint`/`float` are 4-byte with
// 4-byte alignment and every block below is a run of 4-byte scalars, so the std430
// push-constant layout coincides with the C++ layout with no padding surprises.
struct AddParams {
uint32_t n, d, a_dt, b_dt, out_dt, bcast, a_off, b_off, out_off;
};
struct UnaryParams {
uint32_t n, a_dt, out_dt, a_off, out_off;
};
// vt_cast carries its dtype pair in specialization constants instead, so its
// push block is only the shape and the two offsets.
struct CastParams {
uint32_t n, a_off, out_off;
};
struct MatmulParams {
uint32_t m, n, k, a_off, b_off, out_off;
};
// VK4 keep-quant: native TQ2_0 keep-quant GEMV/gemm (vt_matmul_bt_tq2.comp).
struct MatmulBTQuantTQ2Params {
uint32_t n; // output columns (weight rows)
uint32_t m; // output rows (tokens)
uint32_t nb; // k / 256
uint32_t a_off, w_off, out_off;
};
struct MatmulBTQuantTQ2GroupedParams {
uint32_t m; // output rows (tokens)
uint32_t n; // output columns (weight rows)
uint32_t nb; // k / 256
uint32_t e; // num experts
uint32_t bcast; // 1 = all rows share activation row 0
uint32_t a_off, w_off, eid_off, out_off;
};
// VK4 keep-quant Phase 2: fused gate+up+SwiGLU grouped MoE (TQ2_0 weights, bf16
// activation, on-device Q8_K quantize, f32 output). Push-constant block for
// vt_moe_gate_up_swiglu_grouped_tq2.comp.
struct MoeGateUpSwiGLUGroupedTQ2Params {
uint32_t m; // P (output rows = T * top_k)
uint32_t n; // I (output cols = moe_intermediate_size)
uint32_t nb; // K / 256
uint32_t e; // num experts
uint32_t bcast; // 1 = all rows share activation row 0
uint32_t gather_k; // >0 = activation is [T, H], row p reads row p/gather_k
uint32_t a_off; // activation (f32/bf16) byte offset
uint32_t gw_off; // gate weight (TQ2_0) byte offset
uint32_t uw_off; // up weight (TQ2_0) byte offset
uint32_t eid_off; // expert_ids (i32) byte offset
uint32_t out_off; // output (f32) byte offset
float limit; // SwiGLU clamp limit
};
struct EmbeddingParams {
uint32_t t, h, table_off, ids_off, out_off;
};
struct ArgmaxParams {
uint32_t n, v, logits_off, out_off;
};
struct QkvSplitParams {
uint32_t tokens, q_dim, k_dim, v_dim, src_off, q_off, k_off, v_off;
};
struct RopeFromCacheParams {
uint32_t tokens, half_dim, rotary_dim, hq, hk;
uint32_t q_s0, q_s1, k_s0, k_s1;
uint32_t q_off, k_off, c_off, p_off;
};
// VK4: the rotary TABLE build (vt_rope_cos_sin_cache.comp). The angle
// construction travels as f64 scalars — GLSL `double` push members are 8-byte
// aligned, so the five uints above land on a 40-byte boundary and the doubles
// pack from offset 40 with no internal padding (std430 scalar alignment).
struct RopeCosSinCacheParams {
uint32_t tokens, half_dim, rotary_dim;
uint32_t pos_off, out_off;
double base;
double l3_sf, l3_lo, l3_hi, l3_omax;
};
// VK4: vt_rope_neox.comp — the DIRECT-ANGLE apply (no cos|sin table). Same f64
// tail as the cache builder: three uints then five uints land the doubles on
// their 8-byte boundary with no internal padding.
// VK4: vt_moe_combine.comp — the routed-expert weighted sum. All-f32 accumulate,
// one invocation per output element, shared term via spec-const gate.
struct MoeCombineParams {
uint32_t tokens, h, k;
float routed_scale;
uint32_t out_off, e_off, w_off, s_off;
};
// VK4: vt_moe_router_topk.comp — softmax+topk+renorm, one workgroup per row.
struct MoeRouterTopKParams {
uint32_t tokens, e, k;
uint32_t logits_off, w_off, i_off;
};
struct RopeNeoxParams {
uint32_t tokens, half_dim, rotary_dim, hq, hk;
uint32_t q_off, k_off, p_off;
double base;
double l3_sf, l3_lo, l3_hi, l3_omax;
};
struct ReshapeAndCacheParams {
uint32_t num_slots, n_elems, block_size;
uint32_t k_blk, k_pg, v_blk, v_pg;
uint32_t k_tok, v_tok;
uint32_t k_off, v_off, kc_off, vc_off, sm_off;
};
struct PagedAttnParams {
uint32_t total_q, hq, d, block_size, qpk, num_reqs;
uint32_t causal;
int32_t window_left, window_right;
uint32_t kc_blk, kc_pg, kc_hd;
uint32_t vc_blk, vc_pg, vc_hd;
uint32_t bt_row, bt_col;
uint32_t q_off, k_off, v_off, out_off;
uint32_t bt_off, sl_off, qsl_off;
float scale;
float softcap;
};
struct SiluMulParams {
uint32_t t, d, x_dt, out_dt, x_off, out_off;
};
struct RmsParams {
uint32_t t, h, x_dt, w_dt, out_dt, res_dt, has_res, gemma, x_off, w_off, out_off, res_off;
float eps;
};
struct LayerNormParams {
uint32_t rows, d, x_dt, w_dt, b_dt, out_dt, has_w, has_b, x_off, w_off, b_off, out_off;
float eps;
};
struct FcParams {
uint32_t t, h, nsteps, x_dt, w_dt, res_dt, out_dt, x_off, w_off, res_off, out_off;
float eps;
};
// --- The GDN / conv1d family (BACKEND-VULKAN-GDN). Same rule as above: field
// order and types must match the GLSL push-constant blocks EXACTLY.
struct SigmoidGateParams {
uint32_t n, a_off, g_off, o_off;
};
struct RmsNormGatedParams {
uint32_t rows, d, x_dt, z_dt, w_dt, out_dt, sigmoid_gate, gate_group, gate_outer;
uint32_t x_off, z_off, w_off, out_off;
float eps;
};
struct GdnStateGatherParams {
uint32_t rows, work_row, work_inner, cache_inner, cache_row, n_cache_rows;
uint32_t work_dt, cache_dt, his_mode;
uint32_t work_off, cache_off, idx_off, his_off;
};
struct GdnStateScatterParams {
uint32_t rows, work_row, work_inner, cache_inner, cache_row, n_cache_rows;
uint32_t work_dt, cache_dt;
uint32_t cache_off, work_off, idx_off;
};
struct ConvUpdateParams {
uint32_t batch, c_dim, k, width, state_len, x_rs, n_state_rows;
uint32_t has_bias, has_idx, silu;
uint32_t out_dt, x_dt, w_dt, bias_dt, st_dt;
uint32_t out_off, x_off, w_off, bias_off, st_off, idx_off;
};
struct GdnPostConvParams {
uint32_t t, hk, dk, hv, dv, key_dim, value_dim, conv_dim, a_rs, b_rs;
uint32_t conv_off, q_off, k_off, v_off, a_off, b_off;
uint32_t g_off, beta_off, alog_off, dtb_off;
float eps;
};
// The fused full-attention preamble (BACKEND-VULKAN-QKNORM).
struct AttnQkNormRopeGateParams {
uint32_t hq, hkv, dh, rot, half_dim, qgate_rs, kf_rs, gemma;
uint32_t qg_off, kf_off, qo_off, ko_off, go_off, qn_off, kn_off, cs_off;
float eps;
};
// ONE block for BOTH recurrences: vt_gdn_prefill and vt_gdn_decode share their
// step body through an include, so they must also share their push layout. The
// prefill shader ignores has_idx / n_state_rows (they are the decode state-row
// indirection) rather than each op carrying a block that drifts from the other.
struct GdnRecurrenceParams {
uint32_t hk, dk, hv, dv, nv, ratio, has_idx, n_state_rows;
uint32_t q_off, k_off, v_off, out_off, g_off, beta_off, state_off, meta_off;
float scale;
};
// BACKEND-VULKAN-EXL3 (#2530). vt_exl3_had.comp and vt_exl3_gemm.comp.
struct Exl3HadParams {
uint32_t nblocks, blocks_per_row, cols, total_groups, has_pre, has_post;
uint32_t in_off, out_off, pre_off, post_off;
float r_scale;
};
struct Exl3GemmParams {
uint32_t m, k, n, bits, codebook, tiles_n, raw_off, ah_off, tr_off;
};
// Vulkan only GUARANTEES 128 bytes of push-constant space (maxPushConstantsSize);
// staying inside it is what keeps this backend portable without a probe.
static_assert(sizeof(RmsParams) <= 128, "push constants must fit the guaranteed 128 bytes");
static_assert(sizeof(LayerNormParams) <= 128, "push constants must fit the guaranteed 128 bytes");
static_assert(sizeof(FcParams) <= 128, "push constants must fit the guaranteed 128 bytes");
static_assert(sizeof(PagedAttnParams) <= 128,
"push constants must fit the guaranteed 128 bytes");
static_assert(sizeof(ConvUpdateParams) <= 128,
"push constants must fit the guaranteed 128 bytes");
// The widest block in the backend at 84 bytes: the fused post-conv carries ten
// operand offsets. If it ever needs an eleventh, the step list has to move to the
// scratch buffer the way vt_fused_chain's does.
static_assert(sizeof(GdnPostConvParams) <= 128,
"push constants must fit the guaranteed 128 bytes");
static_assert(sizeof(RmsNormGatedParams) <= 128,
"push constants must fit the guaranteed 128 bytes");
static_assert(sizeof(GdnStateGatherParams) <= 128,
"push constants must fit the guaranteed 128 bytes");
static_assert(sizeof(GdnRecurrenceParams) <= 128,
"push constants must fit the guaranteed 128 bytes");
static_assert(sizeof(AttnQkNormRopeGateParams) <= 128,
"push constants must fit the guaranteed 128 bytes");
static_assert(sizeof(Exl3HadParams) <= 128, "push constants must fit the guaranteed 128 bytes");
static_assert(sizeof(Exl3GemmParams) <= 128, "push constants must fit the guaranteed 128 bytes");
// Maximum M per dispatch chunk for dense GEMM/GEMV. The Intel Arc hangcheck is
// ~2s. Measured at 2368 tokens: one scalar GEMM takes ~1.1s. So at 4096 rows
// a single chunk takes ~1.9s — too close to the limit. 2048 rows gives ~0.95s
// per chunk, leaving comfortable margin under the 2s hangcheck.
constexpr uint32_t kMaxMPerChunkDense = 2048;
// Maximum P per dispatch chunk for MoE kernels. Each workgroup processes ALL P
// rows, so per-workgroup time scales with P. Measured: at P=9472 (1184 tokens),
// the MoE takes ~1.5s per layer. So at P=2048, each chunk takes ~0.32s per
// layer — safe under the 2s hangcheck with margin for L2 cache effects.
constexpr uint32_t kMaxPPerChunkMoe = 2048;
// Chunk a matmul dispatch over M to prevent any single command buffer from
// exceeding the GPU hangcheck timeout. Each chunk adjusts a_off and out_off
// to point at the correct rows. The shader is unaware of chunking.
// Flushes between chunks only when the accumulated GPU time would exceed ~1.5s.
// Also flushes at the start when the total estimated time exceeds 1.5s, to
// isolate the GEMM from preceding dispatches in the same command buffer.
template <typename DispatchFn>
void ChunkedMatmulDispatch(int64_t m, int64_t n, int64_t k, DType a_dt,
DType out_dt, uint32_t a_off, uint32_t out_off,
DispatchFn dispatch) {
const size_t a_elem = vt::SizeOf(a_dt);
const size_t o_elem = vt::SizeOf(out_dt);
const uint32_t m_total = static_cast<uint32_t>(m);
// Estimate GPU time per row: 2*N*K flops at ~200 GFLOP/s
const double flops_per_row = 2.0 * static_cast<double>(n) * static_cast<double>(k);
const double gpu_time_per_row_sec = flops_per_row / 200e9;
const double total_est_sec = m_total * gpu_time_per_row_sec;
// Flush when accumulated time exceeds 1.0s (conservative margin under 2s
// hangcheck, accounting for other ops that may share the command buffer).
constexpr double kFlushAtAccumSec = 1.0;
// Flush at the start if this GEMM alone would exceed the threshold, to
// isolate it from preceding dispatches (e.g. attention or previous GEMM).
if (total_est_sec >= kFlushAtAccumSec) {
VulkanContext::Get().FlushBatch("chunked-matmul-start");
}
double accum_sec = 0.0;
for (uint32_t i_start = 0; i_start < m_total; i_start += kMaxMPerChunkDense) {
const uint32_t m_chunk = std::min(kMaxMPerChunkDense, m_total - i_start);
const uint32_t a_chunk = a_off + i_start * static_cast<uint32_t>(k) *
static_cast<uint32_t>(a_elem);
const uint32_t out_chunk = out_off + i_start * static_cast<uint32_t>(n) *
static_cast<uint32_t>(o_elem);
if (accum_sec >= kFlushAtAccumSec) {
VulkanContext::Get().FlushBatch("chunk-accum");
accum_sec = 0.0;
}
dispatch(m_chunk, a_chunk, out_chunk);
accum_sec += m_chunk * gpu_time_per_row_sec;
}
}
template <typename P>
void Go(const char* name, const Binder& b, const P& p, uint32_t groups,
const uint32_t* spec = nullptr, uint32_t spec_count = 0) {
VulkanContext::Get().Dispatch(name, b.data(), b.count(), &p, sizeof(P), groups, spec,
spec_count);
}
// ---------------------------------------------------------------------------
// Kernels. Every argument was already validated by the vt:: wrapper in
// src/vt/ops.cpp before GetOp dispatched here, so these only translate.
// ---------------------------------------------------------------------------
// cpu_layernorm.cpp:87-99 AddKernel.
void AddKernel(Queue&, Tensor& out, const Tensor& a, const Tensor& b) {
const int64_t n = a.Numel();
const int64_t d = a.rank == 0 ? 1 : a.shape[a.rank - 1];
const bool bcast = b.rank == 1 && a.rank != 1;
Binder bind;
const uint32_t a_off = bind.Add(a, "add: a");
const uint32_t b_off = bind.Add(b, "add: b");
const uint32_t out_off = bind.Add(out, "add: out");
AddParams p{static_cast<uint32_t>(n), static_cast<uint32_t>(d),
DtypeCode(a.dtype), DtypeCode(b.dtype),
DtypeCode(out.dtype), bcast ? 1u : 0u,
a_off, b_off,
out_off};
Go("vt_add", bind, p, FlatGroupCount(n));
}
// cpu_layernorm.cpp:75-85 ReluKernel.
void ReluKernel(Queue&, Tensor& out, const Tensor& x) {
const int64_t n = x.Numel();
Binder bind;
const uint32_t x_off = bind.Add(x, "relu: x");
const uint32_t out_off = bind.Add(out, "relu: out");
UnaryParams p{static_cast<uint32_t>(n), DtypeCode(x.dtype), DtypeCode(out.dtype), x_off,
out_off};
Go("vt_relu", bind, p, FlatGroupCount(n));
}
// cpu_ops.cpp:1436-1451 CastBf16Kernel / CastF32Kernel — one shader serves both
// (the CPU pair is likewise the same LoadF32/StoreF32 body twice).
void CastKernel(Queue&, Tensor& out, const Tensor& in) {
const int64_t n = out.Numel();
Binder bind;
const uint32_t in_off = bind.Add(in, "cast: in");
const uint32_t out_off = bind.Add(out, "cast: out");
// The dtype pair rides SPECIALIZATION CONSTANTS rather than push constants, so
// the per-element dtype branch is folded away at pipeline creation and each
// (src, dst) pair is its own cached pipeline. Ascending constantID order, which
// is what GetPipeline binds against the module's declared SpecIds.
const uint32_t spec[2] = {DtypeCode(in.dtype), DtypeCode(out.dtype)};
CastParams p{static_cast<uint32_t>(n), in_off, out_off};
Go("vt_cast", bind, p, FlatGroupCount(n), spec, 2);
}
// ─── EXL3, BACKEND-VULKAN-EXL3 (#2530) ───────────────────────────────────────
//
// The fused chain, step for step as `Exl3GemmKernelCpu` runs it:
// 1. A_had = had_r_128(A, pre_scale = suh)
// 2. C_raw = A_had @ reconstruct(trellis) [f32 accumulation]
// 3. C = had_r_128(C_raw, post_scale = svh)
// Argument validation (shapes, dtypes, contiguity, the 16/128 multiples) is done
// once in `vt::Exl3Gemm` for every backend and is not repeated here. What IS
// checked is what selects device code: `bits` and `codebook` reach the shader as
// values and an out-of-range one would decode SILENTLY, because a shader cannot
// throw.
//
// See src/vt/vulkan/shaders/vt_exl3_gemm.comp for why the donor is the portable
// CPU reference and not cuda_exl3.cu, and .agents/specs/backend-vulkan-exl3.md
// for the byte-equality contract this arm carries instead of the CUDA arm's
// 1.0e-3 RMS bound.
// 1/sqrt(128) spelled as upstream spells it (hadamard.cu:107) and as
// cpu_exl3_kernels.cpp spells it. Kept as the literal and NEVER recomputed: a
// recomputed 1/sqrt(128) can differ in the last f32 bit, and that bit is the
// difference between this arm's byte gate passing and failing.
constexpr float kExl3InvSqrt128 = 0.088388347648f;
// The f32 [m, n] staging buffer between steps 2 and 3. The CPU arm holds it in a
// std::vector; a device needs the same bytes somewhere. GROW-ONLY and
// process-wide, which is the discipline rocm_exl3.hip's EnsureRawScratch
// documents.
//
// NAMED AS A COST rather than hidden. A fused kernel would not need it. A fused
// kernel is the later speed row; this one buys the end of the reference tier.
//
// THE FLUSH BEFORE A GROW IS LOAD-BEARING. Dispatches are BATCHED into an open
// command buffer, so the previous buffer may still be bound by work that has not
// executed. Freeing it under an open batch is a use-after-free with no error and
// no crash — the same hazard Backend::Copy's FlushIfBatchTouches exists for.
float* EnsureExl3RawScratch(size_t need) {
static std::mutex mu;
static void* base = nullptr;
static size_t bytes = 0;
std::lock_guard<std::mutex> lock(mu);
if (need <= bytes) return static_cast<float*>(base);
void* buffer = nullptr;
void* memory = nullptr;
void* fresh = VulkanContext::Get().AllocBuffer(need, &buffer, &memory);
RegisterAllocation(fresh, need, buffer, memory);
if (base != nullptr) {
VulkanContext::Get().FlushBatch("exl3 raw scratch grow");
void* old_buffer = nullptr;
void* old_memory = nullptr;
if (UnregisterAllocation(base, &old_buffer, &old_memory))
VulkanContext::Get().FreeBuffer(old_buffer, old_memory);
}
base = fresh;
bytes = need;
return static_cast<float*>(base);
}
// One `had_r_128` dispatch. `pre` and `post` are optional and at most one is set,
// which is upstream's own instantiation (hadamard.cu:112-172) and what
// `vt::Exl3HadR128` checks; an absent one is bound aliasing `in`, because a
// descriptor the shader statically uses must be valid even on the path that
// never reads it.
void Exl3HadDispatch(void* out, DType out_dtype, const void* in, DType in_dtype,
const Tensor* pre, const Tensor* post, const Device& device, float r_scale,
int64_t rows, int64_t cols) {
const int64_t blocks_per_row = cols / 128;
const int64_t nblocks = rows * blocks_per_row;
if (nblocks <= 0) return;
const int64_t total_groups = (nblocks + 3) / 4;
Tensor tin = Tensor::Contiguous(const_cast<void*>(in), in_dtype, device, {rows, cols});
Tensor tout = Tensor::Contiguous(out, out_dtype, device, {rows, cols});
Binder bind;
const uint32_t in_off = bind.Add(tin, "exl3_had: in");
const uint32_t out_off = bind.Add(tout, "exl3_had: out");
const uint32_t pre_off =
pre != nullptr ? bind.AddU16Only(*pre, "exl3_had: pre_scale") : bind.AddU16Only(tin, "exl3_had: in");
const uint32_t post_off = post != nullptr ? bind.AddU16Only(*post, "exl3_had: post_scale")
: bind.AddU16Only(tin, "exl3_had: in");
const uint32_t spec[2] = {in_dtype == DType::kF16 ? 1u : 0u,
out_dtype == DType::kF16 ? 1u : 0u};
Exl3HadParams p{static_cast<uint32_t>(nblocks),
static_cast<uint32_t>(blocks_per_row),
static_cast<uint32_t>(cols),
static_cast<uint32_t>(total_groups),
pre != nullptr ? 1u : 0u,
post != nullptr ? 1u : 0u,
in_off,
out_off,
pre_off,
post_off,
r_scale};
// The shader carries a grid-stride loop, so the workgroup count is a
// PERFORMANCE choice and never a correctness one. 65535 is the Vulkan-
// guaranteed maxComputeWorkGroupCount[0], so this launch is valid on any
// conformant device no matter how large the tensor is.
const uint32_t groups = static_cast<uint32_t>(total_groups > 65535 ? 65535 : total_groups);
Go("vt_exl3_had", bind, p, groups, spec, 2);
}
void Exl3GemmKernelVulkan(Queue& q, Tensor& c, const Tensor& a, const Tensor& trellis,
const Tensor& suh, const Tensor& svh, Tensor& a_had,
const Exl3GemmArgs& args) {
const int64_t m = a.shape[0];
const int64_t k = a.shape[1];
const int64_t n = c.shape[1];
if (m == 0 || k == 0 || n == 0) return;
VT_CHECK(args.bits >= 1 && args.bits <= 8,
"vt vulkan exl3: bits must be in [1, 8]; got " + std::to_string(args.bits));
VT_CHECK(args.codebook >= 0 && args.codebook <= 2,
"vt vulkan exl3: codebook " + std::to_string(args.codebook) +
" is not implemented (0 == 3INST, 1 == MCG, 2 == mul1). Upstream defines "
"no other value: `decode_3inst<cb>` (codebook.cuh:56-90) has arms for 0, "
"1 and 2 and falls off the end for anything else.");
// 1. the input transform, into the caller's scratch (which may alias A).
Exl3HadDispatch(a_had.data, a_had.dtype, a.data, a.dtype, &suh, nullptr, q.device,
kExl3InvSqrt128, m, k);
// 2. the matmul against the decoded trellis, f32 accumulators.
float* raw = EnsureExl3RawScratch(static_cast<size_t>(m) * static_cast<size_t>(n) *
sizeof(float));
Tensor traw = Tensor::Contiguous(raw, DType::kF32, q.device, {m, n});
Binder bind;
const uint32_t raw_off = bind.AddU32Only(traw, "exl3_gemm: raw");
const uint32_t ah_off = bind.AddU16Only(a_had, "exl3_gemm: a_had");
const uint32_t tr_off = bind.AddU16Only(trellis, "exl3_gemm: trellis");
Exl3GemmParams p{static_cast<uint32_t>(m),
static_cast<uint32_t>(k),
static_cast<uint32_t>(n),
static_cast<uint32_t>(args.bits),
static_cast<uint32_t>(args.codebook),
static_cast<uint32_t>(n / 16),
raw_off,
ah_off,
tr_off};
// The grid is FLATTENED because Dispatch takes group_count_x only: one
// workgroup per (16-column output tile, 8-row block), and the shader
// decomposes the id with the same `tiles_n` it is handed here.
const int64_t groups = (n / 16) * ((m + 7) / 8);
Go("vt_exl3_gemm", bind, p, static_cast<uint32_t>(groups));
// 3. the output transform — had_ff for an f32 C, had_fh for an fp16 one, the
// same two arms the CPU reference picks between off `c.dtype`.
Exl3HadDispatch(c.data, c.dtype, raw, DType::kF32, nullptr, &svh, q.device, kExl3InvSqrt128, m,
n);
}
// cpu_ops.cpp:252-264 SiluAndMulKernel.
void SiluAndMulKernel(Queue&, Tensor& out, const Tensor& x) {
const int64_t t = x.shape[0], d = x.shape[1] / 2;
Binder bind;
const uint32_t x_off = bind.Add(x, "silu_and_mul: x");
const uint32_t out_off = bind.Add(out, "silu_and_mul: out");
SiluMulParams p{static_cast<uint32_t>(t), static_cast<uint32_t>(d), DtypeCode(x.dtype),
DtypeCode(out.dtype), x_off, out_off};
Go("vt_silu_and_mul", bind, p, FlatGroupCount(t * d));
}
// WHICH RmsNorm MODULE THIS DISPATCH USES.
//
// `vt_rms_norm` is the portable 128-invocation module; `vt_rms_norm_wide` is the
// same body at 1024 invocations with a subgroup reduction. The choice is a
// DEVICE CAPABILITY question (VulkanContext::wide_reduce), not a shape question:
// the wide module is never wrong, only unavailable.
//
// VulkanContext::rms_norm_override() is the A/B lever over that decision
// (VT_VULKAN_RMSNORM=base|wide, or the setter the unit gate uses); it exists so
// the two arms are switchable inside ONE binary, because a cross-BUILD comparison
// is the shape that produced a false 1.2x reading for the subgroup tactic earlier
// in this campaign (see vulkan_context.cpp § kRingDepth).
const char* RmsNormShader() {
const VulkanContext& ctx = VulkanContext::Get();
const int forced = ctx.rms_norm_override();
if (forced < 0) return "vt_rms_norm";
if (forced > 0 || ctx.wide_reduce()) {
VT_CHECK(ctx.wide_reduce(),
"vulkan: the wide RmsNorm module was forced but this device does not "
"support 1024-invocation workgroups with compute subgroup arithmetic");
return "vt_rms_norm_wide";
}
return "vt_rms_norm";
}
// cpu_ops.cpp:225-250 RmsNormKernel. One workgroup per token row.
void RmsNormKernel(Queue&, Tensor& out, const Tensor& x, const Tensor& w,
const RmsNormArgs& args, Tensor* residual) {
const int64_t t = x.shape[0], h = x.shape[1];
Binder bind;
const uint32_t x_off = bind.Add(x, "rmsnorm: x");
const uint32_t w_off = bind.Add(w, "rmsnorm: weight");
const uint32_t out_off = bind.Add(out, "rmsnorm: out");
// Bindings 6/7 are always written: a descriptor a shader statically uses must
// be valid even on the code path that never reads it. With has_res == 0 they
// alias `out` and are dead.
const uint32_t res_off =
residual != nullptr ? bind.Add(*residual, "rmsnorm: residual") : bind.Add(out, "rmsnorm: out");
RmsParams p{static_cast<uint32_t>(t),
static_cast<uint32_t>(h),
DtypeCode(x.dtype),
DtypeCode(w.dtype),
DtypeCode(out.dtype),
residual != nullptr ? DtypeCode(residual->dtype) : 0u,
residual != nullptr ? 1u : 0u,
args.gemma ? 1u : 0u,
x_off,
w_off,
out_off,
res_off,
args.eps};
Go(RmsNormShader(), bind, p, static_cast<uint32_t>(t));
}
// cpu_layernorm.cpp:49-73 LayerNormKernel.
void LayerNormKernel(Queue&, Tensor& out, const Tensor& x, const Tensor* weight,
const Tensor* bias, const LayerNormArgs& args) {
const int64_t d = x.shape[x.rank - 1];
const int64_t rows = d == 0 ? 0 : x.Numel() / d;
Binder bind;
const uint32_t x_off = bind.Add(x, "layer_norm: x");
const uint32_t w_off =
weight != nullptr ? bind.Add(*weight, "layer_norm: weight") : bind.Add(x, "layer_norm: x");
const uint32_t b_off =
bias != nullptr ? bind.Add(*bias, "layer_norm: bias") : bind.Add(x, "layer_norm: x");
const uint32_t out_off = bind.Add(out, "layer_norm: out");
LayerNormParams p{static_cast<uint32_t>(rows),
static_cast<uint32_t>(d),
DtypeCode(x.dtype),
weight != nullptr ? DtypeCode(weight->dtype) : 0u,
bias != nullptr ? DtypeCode(bias->dtype) : 0u,
DtypeCode(out.dtype),
weight != nullptr ? 1u : 0u,
bias != nullptr ? 1u : 0u,
x_off,
w_off,
b_off,
out_off,
args.eps};
Go("vt_layer_norm", bind, p, static_cast<uint32_t>(rows));
}
// cpu_ops.cpp:1649-1702 FusedChainInterpKernel — the Tier-1 interpreter. ONE
// registration; every Tier-1-able recipe in include/vt/recipes.h realizes
// through it, and every non-Tier-1 recipe realizes through the device-agnostic
// Tier-0 composite in src/vt/ops.cpp, which re-enters this backend's standalone
// ops. That is the whole "2 lines -> all 10 recipes" property the spike claims.
void FusedChainKernel(Queue&, Tensor& out, const Tensor& x, const Tensor& weight,
Tensor* residual, const FusedRecipe& r, float eps) {
const int64_t t = x.shape[0], h = x.shape[1];
VT_CHECK(r.n >= 1 && r.n <= kMaxFusedSteps, "vulkan fused_chain: bad step count");
// Words per step, matching VT_STEP_WORDS in vt_fused_chain.comp.
constexpr uint32_t kStepWords = 5;
std::vector<uint32_t> steps(static_cast<size_t>(r.n) * kStepWords, 0u);
for (int s = 0; s < r.n; ++s) {
const FStep& st = r.steps[s];
uint32_t op = 0;
switch (st.op) {
case FOp::kAdd: op = 0; break;
case FOp::kMul: op = 1; break;
case FOp::kSilu: op = 2; break;
case FOp::kSigmoid: op = 3; break;
case FOp::kRmsNorm:
// Mirrors the CPU interpreter's assertion (cpu_ops.cpp:1674): the shader
// hard-codes the mean-square reduction, so any other kind must not reach it.
VT_CHECK(st.reduce == FReduce::kMeanSquare,
"vulkan fused_chain: rmsnorm needs kMeanSquare");
op = 4;
break;
default:
VT_CHECK(false, "vulkan fused_chain: non-Tier-1 opcode reached the interpreter");
}
// Canonical operand indices (cpu_ops.cpp:1621-1643): 0=x 1=weight 2=residual
// 3=out, with 2 and 3 the only writable slots.
VT_CHECK(st.out == 2 || st.out == 3, "vulkan fused_chain: step writes a read-only operand");
VT_CHECK(st.in[0] <= 3 && st.in[1] <= 3, "vulkan fused_chain: operand index out of range");
VT_CHECK(residual != nullptr || (st.out != 2 && st.in[0] != 2 && st.in[1] != 2),
"vulkan fused_chain: recipe touches the residual slot but none was bound");
const size_t base = static_cast<size_t>(s) * kStepWords;
steps[base + 0] = op;
steps[base + 1] = st.out;
steps[base + 2] = st.in[0];
steps[base + 3] = st.in[1];
steps[base + 4] = st.gemma ? 1u : 0u;
}
VulkanContext& ctx = VulkanContext::Get();
const size_t step_bytes = steps.size() * sizeof(uint32_t);
VT_CHECK(step_bytes <= VulkanContext::kScratchBytes,
"vulkan fused_chain: step list exceeds the scratch buffer");
std::memcpy(ctx.ScratchData(), steps.data(), step_bytes);
Binder bind;
const uint32_t x_off = bind.Add(x, "fused_chain: x");
const uint32_t w_off = bind.Add(weight, "fused_chain: weight");
const uint32_t res_off = residual != nullptr ? bind.Add(*residual, "fused_chain: residual")
: bind.Add(out, "fused_chain: out");
const uint32_t out_off = bind.Add(out, "fused_chain: out");
bind.AddRaw(ctx.ScratchBuffer());
FcParams p{static_cast<uint32_t>(t),
static_cast<uint32_t>(h),
static_cast<uint32_t>(r.n),
DtypeCode(x.dtype),
DtypeCode(weight.dtype),
residual != nullptr ? DtypeCode(residual->dtype) : 0u,
DtypeCode(out.dtype),
x_off,
w_off,
res_off,
out_off,
eps};
Go("vt_fused_chain", bind, p, static_cast<uint32_t>(t));
}
// cpu_ops.cpp:187-260 MatmulChunked / MatmulKernel / MatmulBTKernel. One
// invocation per OUTPUT ELEMENT with the whole K reduction on it, which is what
// the CPU kernel does too (it deliberately never splits a K reduction across
// threads), so the accumulation ORDER matches rather than merely the tolerance.
//
// The naive body is the portable correctness tier on purpose; the tiled and
// cooperative-matrix ports (llama.cpp mul_mm.comp / mul_mm_cm2.comp) are VK-C,
// which needs exactly this as its same-device A/B reference.
// TACTIC SELECTION (VK-C). Every condition below is a HARD requirement of the
// cooperative-matrix path, not a heuristic, and failing any one of them means the
// scalar kernel -- which is always correct -- runs instead:
//
// * the device reports the EXACT configuration the committed coopmat SPIR-V is
// written to (16x16x16, bf16/bf16/f32/f32, SUBGROUP). Vulkan matches
// configurations exactly, so "close enough" does not exist;
// * subgroup size is 32, because the shader's workgroup is a literal 32 (see
// the shader for why the size cannot travel as a specialization constant at
// this target);
// * BOTH operands are bf16. Every configuration GB10 reports takes
// bf16/f16/int8 inputs, so f32 operands can never use this path -- a hardware
// constraint, not a policy;
// * K is a multiple of 16. A ragged K tail cannot be masked inside a
// cooperative-matrix load, and silently truncating it would drop terms from
// the dot product. Ragged M and N are fine: the shader bounds-checks its
// store.
//
// MEASURED: GB10 satisfies all four; llvmpipe -- the only Vulkan device CI can
// reach -- fails the first, so CI exercises the scalar tactic and this selection
// returning false is the property CI can actually gate.
bool CoopMatMatmulUsable(const Tensor& a, const Tensor& b, int64_t k, int64_t m, int64_t n) {
// VT_VULKAN_COOPMAT=0 forces the scalar tactic. This exists for ONE reason: a
// same-binary A/B. Comparing the two tactics across two builds would confound
// the kernel with everything else that differs between them, and the project's
// benchmark protocol wants the arms to differ in exactly one thing. Default is
// ON -- absent or any value other than "0" leaves selection to the capability
// probe, so production behaviour is unchanged by the lever's existence.
static const bool kDisabled = [] {
const char* v = std::getenv("VT_VULKAN_COOPMAT");
return v != nullptr && std::strcmp(v, "0") == 0;
}();
if (kDisabled) return false;
const VulkanContext& ctx = VulkanContext::Get();
// WHY IT DECLINED, reported once per distinct reason under
// VT_VULKAN_DISPATCH_STATS. A 27B prefill measured 99.9% of GPU time in the
// UNTILED SCALAR kernel at ~96 GFLOP/s -- roughly 1% of what this device can do
// -- because this predicate was returning false for every GEMM, and reading the
// source did not reveal which clause. Shapes were whole tiles and activations
// were bf16, so the obvious two candidates were both excluded by inspection and
// the answer still had to be measured. A selection predicate that can silently
// route an entire model onto the correctness tier should be able to say so.
if (kCoopMatWhy) {
const char* why = nullptr;
if (!ctx.coopmat_bf16_f32()) why = "device reports no bf16->f32 16x16x16 SUBGROUP config";
else if (ctx.subgroup_size() != 32) why = "subgroup size is not 32";
else if (a.dtype != DType::kBF16) why = "operand a is not bf16";
else if (b.dtype != DType::kBF16) why = "operand b is not bf16";
else if (k % 16 != 0) why = "K is not a multiple of 16";
else if (m < 16) why = "M is below one 16-row tile";
else if (n % 16 != 0) why = "N is not a multiple of 16";
if (why != nullptr) {
static std::mutex seen_mu;
static std::set<std::string> seen;
std::string key = std::string(why) + "|" + std::to_string(static_cast<int>(a.dtype)) +
"," + std::to_string(static_cast<int>(b.dtype));
std::lock_guard<std::mutex> g(seen_mu);
if (seen.insert(key).second) {
std::fprintf(stderr,
"[vt vulkan] coopmat DECLINED: %s (a.dtype=%d b.dtype=%d "
"m=%lld k=%lld n=%lld)\n",
why, static_cast<int>(a.dtype), static_cast<int>(b.dtype),
(long long)m, (long long)k, (long long)n);
std::fflush(stderr);
}
}
}
return ctx.coopmat_bf16_f32() && ctx.subgroup_size() == 32 &&
a.dtype == DType::kBF16 && b.dtype == DType::kBF16 && k % 16 == 0 &&
// M AND N MUST ALSO BE WHOLE TILES. `coopMatLoad` reads a FULL 16x16
// tile with no masking, so a partial tile reads past the end of the
// operand -- and the store being bounds-checked does not save it,
// because the fault happens on the LOAD. MEASURED: lm_head at M=1
// (single decode token) read 15 rows (~30 KB) past a small activation
// buffer, faulted the GPU, and the fence NEVER SIGNALLED -- an infinite
// vkWaitForFences, which presents as a hang, not as an error.
//
// The original correctness gate used M=20, N=12 precisely to exercise
// ragged shapes and PASSED, because there the out-of-bounds read stayed
// inside the allocation and its garbage rows were discarded by the
// bounds-checked store. Raggedness alone was not enough; the read has to
// leave the allocation to fault.
//
// M NEED ONLY BE AT LEAST ONE WHOLE TILE, not a multiple of one. The
// shader slides a trailing tile back to start at M-16, so every read
// stays in bounds and the shared rows recompute to identical values.
//
// Requiring m % 16 == 0 here is what fixed the original hang, and it
// MEASURED as the entire prefill bottleneck: prompt length gives
// m = tokens + 1, so 513 % 16 == 1 sent every 27B prefill GEMM to the
// untiled scalar kernel -- 99.9% of GPU time at ~96 GFLOP/s, about 1% of
// this device. N stays whole because a ragged N would need the same
// treatment on the B operand and no shape in play needs it.
m >= 16 && n % 16 == 0;
}
// GEMV TACTIC SELECTION (VK-F). Same shape of contract as the coopmat predicate
// above -- every requirement is a hard one, and failing any of them runs the
// always-correct scalar kernel instead.
//
// The problem this solves is COALESCING, measured: vt_matmul was ~55% of all GPU
// time in an e2e decode run. It puts one invocation on each output element and
// loops K there, so for MatmulBT lane j reads b[j*k + q] and adjacent lanes land
// k*2 bytes apart -- each pulling its own cache line to use 2 bytes of it. The
// GEMV shader instead gives each output element a workgroup whose lanes stride K,
// so adjacent lanes read adjacent addresses.
//
// * MatmulBT ONLY. In the other orientation vt_matmul reads b[q*n + j], which
// is ALREADY coalesced across lanes; the GEMV shape would make that strided
// and strictly worse. This is not a universally better kernel and the
// predicate does not pretend otherwise.
// * m == 1, the decode shape. One workgroup per output element is the right
// trade only when there are few of them: at prefill m*n workgroups would each
// do k/128 multiplies, and prefill is the coopmat tactic's job anyway.
// * k >= the workgroup width, so the strided loop actually has work for every
// lane. Below that most lanes contribute a zero partial and the reduction
// costs more than the loop saves.
//
// ACCUMULATION ORDER: the K reduction becomes a tree, so this tactic does NOT
// share the CPU's accumulation order -- it sits in the NMSE tier alongside
// coopmat. That is why it is gated on a token-exactness run and not on an NMSE
// bound alone.
bool GemvMatmulUsable(bool bt, int64_t k, int64_t m) {
// VT_VULKAN_GEMV=0 forces the scalar tactic, for the same single reason the
// coopmat lever exists: a same-binary A/B, so the arms differ in exactly one
// thing. Default ON.
static const bool kDisabled = [] {
const char* v = std::getenv("VT_VULKAN_GEMV");
return v != nullptr && std::strcmp(v, "0") == 0;
}();
if (kDisabled) return false;
// WHY IT DECLINED, once per distinct reason, under VT_VULKAN_DISPATCH_STATS.
// Same reasoning as the coopmat predicate above: a 27B decode profile showed the
// UNTILED SCALAR kernel still taking 256 calls at 12.53 ms -- one per output
// token, and the largest single per-call cost in decode -- and no amount of
// reading the source says WHICH clause sent it there.
if (kCoopMatWhy) {
const char* why = nullptr;
if (!bt) why = "not MatmulBT (b is [K,N]; that layout is already coalesced)";
// M>1 now allowed for prefill — GEMV coalesces B reads
else if (k < static_cast<int64_t>(kWorkgroupSize)) why = "K is below one workgroup width";
if (why != nullptr) {
static std::mutex gseen_mu;
static std::set<std::string> gseen;
std::lock_guard<std::mutex> g(gseen_mu);
if (gseen.insert(std::string(why)).second) {
std::fprintf(stderr, "[vt vulkan] gemv DECLINED: %s (bt=%d m=%lld k=%lld)\n",
why, bt ? 1 : 0, (long long)m, (long long)k);
std::fflush(stderr);
}
}
}
if (!bt) return false; // MatmulBT only — M>1 now allowed for prefill
return k >= static_cast<int64_t>(kWorkgroupSize);
}
// GEMV VARIANT AXES (row BACKEND-VULKAN-GEMVROWS). Both are specialization
// constants on the SAME committed module, so every arm of an A/B lives in one
// binary; see shaders/vt_matmul_vec.comp for what each one can and cannot buy.
//
// Defaults are named here rather than spelled inline so a measured flip is one
// edit and the env lever keeps meaning "override the measured default".
//
// MEASURED, GB10, benchmarks/vulkan_gemv_ab.cpp over the 27B's own decode shapes,
// 9 arms x 4 rotated passes, each arm paired against the rows=1/pack=0 baseline
// measured IN THE SAME PASS (the box drifted 15.5% peak-to-peak between passes,
// so an unpaired ranking would have been noise):
//
// rows=1 pack=0 1.000x rows=2 pack=0 0.966x rows=4 pack=0 0.968x
// rows=1 pack=1 1.025x rows=2 pack=1 1.017x rows=4 pack=1 1.014x
// rows=1 pack=2 1.086x rows=2 pack=2 1.047x rows=4 pack=2 1.039x
//
// ROWS > 1 IS A MEASURED LOSS ON THIS DEVICE, in all four passes and at every
// pack width, so it ships OFF. It is kept as an axis rather than deleted because
// llama.cpp makes exactly this knob device-dependent -- ggml-vulkan.cpp:4705-4719
// sets `rm_stdq` to 2 on AMD GCN and on Intel and leaves it 1 elsewhere -- and the
// board this campaign is waiting on (VK-I) is one of the two it raises it for.
// Deleting the axis would mean rediscovering it there.
// The likely reason it loses here: halving the workgroup count halves the number
// of independent sequential read streams the memory controller sees, and each
// surviving workgroup interleaves reads from rows k*2 bytes apart. The activation
// re-reads it saves were L2 hits, which were never the constraint.
// BISECT HOOK (temporary): VT_VK_DISABLE=kMoeRouterTopK,kMoeCombine,... skips
// registering the named ops so they fall back to the reference tier.
bool VkOpDisabled(const char* op_name) {
const char* v = std::getenv("VT_VK_DISABLE");
if (v == nullptr || *v == '\0') return false;
const std::string s(v);
size_t pos = 0;
while (pos <= s.size()) {
size_t comma = s.find(',', pos);
std::string tok = s.substr(pos, comma == std::string::npos ? std::string::npos : comma - pos);
if (tok == op_name) return true;
if (comma == std::string::npos) break;
pos = comma + 1;
}
return false;
}
constexpr uint32_t kGemvRowsDefault = 1;
constexpr uint32_t kGemvPackDefault = 2;