Repository navigation
Expand file tree
/
Copy pathlayer.cpp
More file actions
1652 lines (1621 loc) · 118 KB
/
Copy pathlayer.cpp
File metadata and controls
1652 lines (1621 loc) · 118 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
// src/core/layer.cpp - the GDN layer, composed. See the header for the operation order and its traps.
#include "strata/core/layer.hpp"
#include "strata/core/pin_budget.hpp"
#include "strata/core/native_dense.hpp"
#include "strata/core/native_head.hpp"
#include "strata/kernels/bf16_bits.hpp"
#include "strata/kernels/bf16_gemv.hpp"
#include "strata/kernels/elementwise.hpp"
#include "strata/kernels/gdn.hpp"
#include "strata/kernels/qsa.hpp"
#include "strata/kernels/kv_q4.hpp"
#include "strata/kernels/kv_q8.hpp"
#include "strata/kernels/quantize_act.hpp"
#include "strata/kernels/fuse_decode.hpp"
#include "strata/kernels/rope.hpp"
#include "strata/kernels/router_top10.hpp"
#include "strata/kernels/s2_gemv_q8.hpp"
#include "strata/kernels/s_gemv.hpp"
#include "strata/kernels/shared_expert.hpp"
#include "strata/kernels/native_mmvq.hpp"
#include "strata/kernels/native_moe.hpp"
#include "strata/kernels/native_gdn.hpp"
#include "strata/kernels/native_gdn_preprocess.hpp"
#include "strata/kernels/native_router.hpp"
#include "strata/kernels/native_qsa.hpp"
#include "strata/kernels/native_qsa_indexer.hpp"
#include "strata/kernels/mrope.hpp"
#include "strata/kernels/native_rope.hpp"
#include "strata/kernels/native_flash_attn.hpp"
#include "strata/kernels/fused_gr.hpp"
#include "strata/kernels/cvec.hpp"
#include "strata/kernels/qsa_decode_attn.hpp"
#include "strata/kernels/fused_gdn.hpp"
#include "strata/kernels/qsa_select.hpp"
#include <algorithm>
#include <cstdlib>
#include <exception>
#include <filesystem>
#include <cuda_runtime.h>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <limits>
#ifndef _WIN32
#include <sys/mman.h>
#endif
#include <memory>
#include <vector>
namespace strata::core {
namespace { bool g_shared_early = true; bool g_fused_gr = false; bool g_fast_attn = true; bool g_publish_kernel = true; bool g_fused_gdn = true; bool g_fast_select = true; }
namespace {constexpr int Q8K_BYTES_PER_BLOCK = 292;
constexpr int Q8K_ELEMS_PER_BLOCK = 256;
constexpr float RMS_EPS = 1e-6f;
const std::string EMBEDDING_NAME = "token_embd.weight";
// qwen4exp.attention.layer_norm_rms_epsilon, used for BOTH norms here
/// A Q8_K buffer needs `n` a multiple of 256 and `n/256` blocks of 292 bytes.
uint64_t q8k_bytes(int64_t n) { return (uint64_t) (n / Q8K_ELEMS_PER_BLOCK) * Q8K_BYTES_PER_BLOCK; }
/// `s_gemv_q8k` takes the canonical-form attributes; a `WeightRef` carries them, and a tensor that is NOT
/// quantized has none. Returns false and names the tensor rather than building a form out of zeroes - which
/// would decode every code as `0 + bias` and produce a perfectly finite wrong answer.
bool sform_of(const WeightRef& r, strata::kernels::SForm& f, const std::string& name, std::string& err) { if (!r.quantized()) { err = name + " is not a quantized tensor, so it has no S-form"; return false; } f.code_bits = r.code_bits; f.code_bias = r.code_bias; f.group_elems = r.group_elems; f.codebook = r.codebook_iq4nl ? strata::kernels::Codebook::Iq4Nl : strata::kernels::Codebook::Affine; f.has_offset = r.has_offset; f.act_kind = r.act_kind;
// carried, not derived - see the note on `SForm::act_kind`
return true;}
/// The three canonical planes of a quantized tensor, located INSIDE the loaded region.
//
//
// **THIS FUNCTION USED TO RE-DERIVE THE LAYOUT, AND THAT IS HOW A WIDTH BUG SURVIVED A ROUND.** It computed
/// `n_groups = n_in / group_elems` and then `scales_bytes = n_out * n_groups * sizeof(float)` - 4 bytes per
/// scale for every tensor. 90 of the 303 quantized tensors hold fp16 scales in the pack (all 58 Q2_0 expert
/// tensors, plus Q4_0, Q5_0, Q8_0 and IQ4_NL), so for those the computed plane was TWICE the real one and the
/// three planes did not add up to the tensor. The first diagnosis was "the manifest's `group_elems` must be
/// wrong, the real group is 64"; it is not, and an audit of all 303 tensors against `scales_fp16` found zero
/// inconsistencies. **The unexamined input was the scale WIDTH, not the group COUNT.**
//
//
// The loader now widens fp16 scales to f32 on the way into the arena and records the resulting plane sizes in
/// the `WeightRef`, so this function has nothing left to derive - it reads what was loaded. The redundancy is
/// deliberate: the sizes come from ONE place (the index, checked against the manifest by `pack_index.py` and
/// against the span by the loader), and this function only checks that they describe the tensor it was given.
//
//
// **THE PLANE KEY IS `offsets`, NOT `mins`, AND THAT COST 136 MiB.** `tools/pack_index.py` and
/// `tools/pack_budget.py` both looked for `mins` and both therefore omitted the offset plane of 54 Q4_K/Q5_K
/// tensors - so the arena was sized without it AND the bytes were never copied. Two tools agreeing is only
/// evidence when they do not share the assumption that is wrong. This function refuses rather than guessing,
/// which is what caught it.
struct Planes { const uint8_t* codes = nullptr; const float* scales = nullptr; const float* offset = nullptr;
///< null when the form has none
};
bool plane_ptrs(const WeightRef& r, const std::string& name, Planes& out, std::string& err) {
// S2, S4 AND S8 ALL SPLIT THE SAME WAY. The plane LOCATION does not depend on the code width - the three
// sizes come from the index and are checked against the tensor below - so the guard is here to catch a
// tensor that is not quantized at all, not to pick a decoder. WHICH KERNEL reads the planes is the
// caller's choice and the two differ: an S2 tensor's activation contract is Q8_0 (`s2_gemv_q8`) while a
// K-quant's is Q8_K (`s_gemv_q8k`). This used to accept only 4 and 8, which refused `attn_q` - a Q2_0
// tensor and the reason the QSA layer could not be composed at all.
if (r.code_bits != 2 && r.code_bits != 4 && r.code_bits != 8) { err = name + ": code_bits " + std::to_string(r.code_bits) + " is not an S2/S4/S8 form"; return false; } const uint64_t end = r.codes_bytes + r.scales_bytes + r.offset_bytes; if (r.codes_bytes == 0 || r.scales_bytes == 0 || end != r.bytes) { char buf[320]; std::snprintf(buf, sizeof buf, "%s: the planes add up to %llu B but the tensor is %llu B (codes %llu, scales %llu, " "offsets %llu) - what the loader recorded is not the layout that was loaded", name.c_str(), (unsigned long long) end, (unsigned long long) r.bytes, (unsigned long long) r.codes_bytes, (unsigned long long) r.scales_bytes, (unsigned long long) r.offset_bytes); err = buf; return false; } if (r.has_offset != (r.offset_bytes != 0)) { err = name + ": has_offset is " + std::to_string(r.has_offset ? 1 : 0) + " but the offset plane is " + std::to_string(r.offset_bytes) + " B"; return false; } const uint8_t* base = (const uint8_t*) r.data; out.codes = base; out.scales = (const float*) (base + r.codes_bytes); out.offset = r.offset_bytes ? (const float*) (base + r.codes_bytes + r.scales_bytes) : nullptr; return true;}
constexpr int TPR = 32;
bool native_bf16_projections = false;
bool native_flash_attn_short = false;
void project_bf16(const float* x, const uint16_t* x_bf16, const uint16_t* weights, float* out,
int64_t n_in, int64_t n_out, bool split, void* stream) {
using namespace strata::kernels;
if (native_bf16_projections) bf16_gemv_fp32_mmvf(x, weights, out, n_in, n_out, stream);
else if (split) bf16_gemv_split(x_bf16, weights, out, n_in, n_out, TPR, stream);
else bf16_gemv(x_bf16, weights, out, n_in, n_out, stream);
}
#if defined(STRATA_EXPERIMENTAL_SM60)
// TWO BF16 projections of the SAME x in ONE kernel (`ssm_alpha`/`ssm_beta`, `indexer.q`/`indexer.k`).
// `bf16_gemv_pair` reproduces the warp-per-row accumulation, which is what `bf16_gemv_split` at TPR 32
// always runs and what plain `bf16_gemv` runs at n_out >= 64 - below that the plain entry uses the naive
// one-thread-per-row sum and the pair would round differently, so those shapes keep two calls.
void project_bf16_pair(const float* x, const uint16_t* x_bf16, const uint16_t* w1, float* o1, int64_t n_out1,
const uint16_t* w2, float* o2, int64_t n_out2, int64_t n_in, bool split, void* stream) {
using namespace strata::kernels;
if (native_bf16_projections) {
bf16_gemv_fp32_mmvf(x, w1, o1, n_in, n_out1, stream);
bf16_gemv_fp32_mmvf(x, w2, o2, n_in, n_out2, stream);
} else if (split || (n_out1 >= 64 && n_out2 >= 64)) {
bf16_gemv_pair(x_bf16, w1, o1, n_out1, w2, o2, n_out2, n_in, stream);
} else {
bf16_gemv(x_bf16, w1, o1, n_in, n_out1, stream);
bf16_gemv(x_bf16, w2, o2, n_in, n_out2, stream);
}
}
#endif
///< threads per row for the row-split GEMVs.
/// **MEASURED, NOT ASSUMED, AND 64 IS NOT BETTER.** `dense_pass.exe` drives the same split kernels at
/// threads_per_row 64 and reports 248.5 GB/s, so matching it looked like free performance. It is not:
/// TPR=64 gives 11.75 tok/s against 32's 11.99 with experts, and 20.19 against 20.26 without - identical
/// inside noise and marginally worse on both. That is also what the stage table predicts, because the GEMVs
/// are only ~16% of a token, so a few percent there cannot move the total. Kept at 32; the sweep that would
/// actually settle it is per-tensor, not global, and belongs with the fusion work rather than before it.
///< threads per row for the row-split GEMVs
/// Writes the sequence number into MAPPED PINNED memory. A KERNEL, not cudaEventRecord - round 199 found
/// that an event record inside a capture is silently dropped, while this is captured normally and the host can
/// read its result MID-GRAPH. One thread: it is a store.
// (the ring kernel lives in src/kernels/cuda/elementwise.cu; this file is HOST code)
/// WHICH ACTIVATION A QUANTIZED WEIGHT WANTS, AND IT IS A PROPERTY OF THE **TENSOR**, NOT OF ITS ROLE.
//
//
// Rounds 205-215 ran `gdn_layer` and `qsa_layer` on the assumption that a name implies a family: `attn_qkv` is
/// a K-quant, `attn_q` is Q2_0, and so on. **The pack does not work that way.** The same name is quantized
/// per LAYER, and the spread is wide:
//
//
// attn_qkv IQ4_XS x13, Q3_K x18, Q2_0 x1, Q4_K x4 (36 GDN layers)
/// attn_gate Q3_K x25, IQ4_XS x4, Q4_K x3, Q2_0 x4
/// attn_q Q3_K x6, IQ4_XS x4, Q2_0 x2 (12 QSA layers)
//
//
// `docs/activation-contract.md` fixes the rule per TYPE, and it is short:
//
//
// code_bits == 2 -> Q8_0, via `quantize_q8_0` + `s2_gemv_q8`
/// anything else quantized -> Q8_K, via `quantize_q8_K` + `s_gemv_q8k_split`
//
//
// Getting it wrong is worth 0.6-1.4% on the GEMV - a plausible vector, not a broken one - which is exactly
/// what Gate C1 exists to find and what nothing before C1 would have. `s_gemv_q8k`'s own guard is what caught
/// it here (`code_bits 2 has no Q8_K contract`).
//
//
// `x80` and `xq8k` are the two quantized images of the SAME activation; a caller produces both once and this
/// picks. Producing only the one it thinks it needs is how the assumption gets baked in again.
bool gemv_quantized(const WeightRef& w, const Planes& p, const strata::kernels::SForm& f, const uint8_t* x80, const uint8_t* xq8k, float* y, int64_t n_in, int64_t n_out, const std::string& name, void* stream, std::string& err, const float* x_f32 = nullptr, bool x_q8_1_ready = false) {
using namespace strata::kernels;
if (w.native_data) {
if (!x_f32 || !w.native_q8_1 || !stream || n_in != w.ne0 || n_out != w.ne1) {
err = name + ": native projection requires matching FP32 input and session scratch";
return false;
}
try {
// Plan v0.3 P3: a caller whose previous native projection quantized the SAME x into the shared
// scratch, with no native projection in between, passes x_q8_1_ready and the quantize is skipped.
if (!x_q8_1_ready) native_quantize_q8_1(x_f32, w.native_q8_1, (int) n_in, 1, stream);
native_mmvq(w.native_type, w.native_data, w.native_q8_1, y,
(int) n_in, (int) n_out, 1, stream);
} catch (const std::exception& error) {
err = name + ": " + error.what();
return false;
}
return true;
}
if ((w.code_bits == 2 || !w.wants_q8k()) ? !x80 : !xq8k) {
err = name + ": missing canonical quantized activation";
return false;
}
if (w.code_bits == 2) {
// S2 carries no offset plane and no SForm: its attributes are fixed (2 bits, group 64, bias -1), which
// is why `s2_gemv_q8` takes neither.
if (w.has_offset || p.offset != nullptr) { err = name + ": an S2 form must have no offset plane"; return false; } if (w.group_elems != 64 || w.code_bias != -1) { err = name + ": an S2 form must be group 64 with bias -1, this one is group " + std::to_string(w.group_elems) + " with bias " + std::to_string(w.code_bias); return false; } s2_gemv_q8(x80, p.codes, p.scales, y, n_in, n_out, TPR, stream); return true; }
// **A LEGACY 4/8-BIT FORM WANTS Q8_0, NOT Q8_K, AND `code_bits` CANNOT TELL YOU WHICH.** This used to be
// `code_bits == 2 ? Q8_0 : Q8_K`, which is CORRECT ONLY BY LUCK: every legacy tensor in this pack apart
// from `ffn_down_shexp` is Q2_0, whose attributes happen to be S2's. Q5_0 and Q5_K are both 8-bit with
// bias -16 and differ only in `has_offset`; IQ4_NL and IQ4_XS differ in NOTHING the S-form carries. The
// kind therefore comes from the manifest's `source_type`, through the index (LEDGER L54/L55).
if (!w.wants_q8k()) { s_gemv_q8_0_split(x80, p.codes, p.scales, p.offset, y, n_in, n_out, f, stream); return true; } s_gemv_q8k_split(xq8k, p.codes, p.scales, p.offset, y, n_in, n_out, f, stream); return true;}}
// namespace
void layer_set_native_bf16(bool enabled) { native_bf16_projections = enabled; }
void layer_set_native_flash_attn_short(bool enabled) { native_flash_attn_short = enabled; }
namespace { bool g_kv_int8 = false, g_kv_q4 = false, g_kv_hybrid = false, g_kv_int8_rot = false; }
void qsa_set_kv_int8(bool enabled) { g_kv_int8 = enabled; }
void qsa_set_kv_int8_rotate(bool enabled) { g_kv_int8_rot = enabled; }
bool qsa_kv_int8() { return g_kv_int8; }
void qsa_set_kv_q4(bool enabled) { g_kv_q4 = enabled; }
bool qsa_kv_q4() { return g_kv_q4; }
void qsa_set_kv_hybrid(bool enabled) { g_kv_hybrid = enabled; }
bool qsa_kv_hybrid() { return g_kv_hybrid; }
uint64_t gdn_buffers_bytes(const ModelGeometry& g) { const int64_t C = g.ssm_conv_channels; const int64_t V = g.ssm_value_dim; const uint64_t parts[] = { q8k_bytes(g.n_embd),
// x_q8k
(uint64_t) (g.n_embd / 32) * 34,
// x_q8_0
(uint64_t) g.n_embd * 2,
// x_bf16
(uint64_t) C * 4,
// qkv
(uint64_t) C * 4,
// conv_out
(uint64_t) C * 4,
// h
(uint64_t) g.ssm_v_heads * 4,
// alpha
(uint64_t) g.ssm_v_heads * 4,
// beta
(uint64_t) g.ssm_v_heads * 4,
// gate
(uint64_t) g.ssm_v_heads * g.ssm_state_size * 4,
// o
(uint64_t) V * 4,
// z
(uint64_t) V * 4,
// y
q8k_bytes(V),
// y_q8k
(uint64_t) (V / 32) * 34,
// y_q8_0
(uint64_t) g.ssm_state_size * g.ssm_v_heads * g.ssm_state_size * 4,
// state
(uint64_t) C * (g.ssm_d_conv - 1) * 4,
// conv_state
}; uint64_t total = 0; for (uint64_t v : parts) total += (v + 15) & ~(uint64_t) 15; return total;}
uint64_t gdn_buffers_init(const ModelGeometry& g, void* base, GdnBuffers& b) { const int64_t C = g.ssm_conv_channels; const int64_t V = g.ssm_value_dim; const uint64_t parts[] = { q8k_bytes(g.n_embd), (uint64_t) (g.n_embd / 32) * 34, (uint64_t) g.n_embd * 2, (uint64_t) C * 4, (uint64_t) C * 4, (uint64_t) C * 4, (uint64_t) g.ssm_v_heads * 4, (uint64_t) g.ssm_v_heads * 4, (uint64_t) g.ssm_v_heads * 4, (uint64_t) g.ssm_v_heads * g.ssm_state_size * 4, (uint64_t) V * 4, (uint64_t) V * 4, q8k_bytes(V), (uint64_t) (V / 32) * 34, (uint64_t) g.ssm_state_size * g.ssm_v_heads * g.ssm_state_size * 4, (uint64_t) C * (g.ssm_d_conv - 1) * 4, }; uint8_t* p = (uint8_t*) base; void* ptr[16]; uint64_t total = 0; for (int i = 0; i < 16; ++i) { ptr[i] = p; const uint64_t al = (parts[i] + 15) & ~(uint64_t) 15; p += al; total += al; } b.x_q8k = (uint8_t*) ptr[0]; b.x_q8_0 = (uint8_t*) ptr[1]; b.x_bf16 = (uint16_t*) ptr[2]; b.qkv = (float*) ptr[3]; b.conv_out = (float*) ptr[4]; b.h = (float*) ptr[5]; b.alpha = (float*) ptr[6]; b.beta = (float*) ptr[7]; b.gate = (float*) ptr[8]; b.o = (float*) ptr[9]; b.z = (float*) ptr[10]; b.y = (float*) ptr[11]; b.y_q8k = (uint8_t*) ptr[12]; b.y_q8_0 = (uint8_t*) ptr[13]; b.state = (float*) ptr[14]; b.conv_state = (float*) ptr[15]; return total;}
void gdn_buffers_zero_state(const GdnBuffers& b, const ModelGeometry& g, void* stream) { const uint64_t st = (uint64_t) g.ssm_state_size * g.ssm_v_heads * g.ssm_state_size * sizeof(float); const uint64_t cs = (uint64_t) g.ssm_conv_channels * (g.ssm_d_conv - 1) * sizeof(float); cudaMemsetAsync(b.state, 0, st, (cudaStream_t) stream); cudaMemsetAsync(b.conv_state, 0, cs, (cudaStream_t) stream);}
// Forward-declared because `gdn_layer` and `qsa_layer` are both defined above the timer's own definition, and
// the sub-stage marks live inside them.
static void st_begin(int64_t layer, int slot, void* stream);
static void st_end(int64_t layer, int slot, void* stream);
bool gdn_layer(const WeightTable& tables, const ModelGeometry& g, int64_t layer, const GdnBuffers& b, const float* mixed, float* out, void* stream, std::string& err) { const LayerView v(tables, layer); const int64_t C = g.ssm_conv_channels;
// ---- resolve. Every one of these was shape-checked by `check_layer` at load time, so a miss here is a
// NAME problem and not a geometry one, and the message says which name.
const WeightRef* w_qkv = v.get("attn_qkv.weight"); const WeightRef* w_gate = v.get("attn_gate.weight"); const WeightRef* w_out = v.get("ssm_out.weight"); const WeightRef* w_alpha = v.get("ssm_alpha.weight"); const WeightRef* w_beta = v.get("ssm_beta.weight"); const WeightRef* w_conv = v.get("ssm_conv1d.weight"); const WeightRef* w_norm = v.get("ssm_norm.weight"); const WeightRef* w_dt = v.get("ssm_dt.bias"); const WeightRef* w_a = v.get("ssm_a"); const char* missing = !w_qkv ? "attn_qkv.weight" : !w_gate ? "attn_gate.weight" : !w_out ? "ssm_out.weight" : !w_alpha ? "ssm_alpha.weight" : !w_beta ? "ssm_beta.weight" : !w_conv ? "ssm_conv1d.weight" : !w_norm ? "ssm_norm.weight" : !w_dt ? "ssm_dt.bias" : !w_a ? "ssm_a" : nullptr; if (missing) { err = v.name(missing) + " is missing"; return false; }
// The conv kernel and the two norms are F32 source types, and the loader copied them verbatim - so their
// device bytes ARE f32 and can be handed straight to the kernels that want `const float*`.
const float* conv_kernel = (const float*) w_conv->data; const float* ssm_norm = (const float*) w_norm->data; const float* dt = (const float*) w_dt->data; const float* ssm_a = (const float*) w_a->data; strata::kernels::SForm f_qkv, f_gate, f_out; if (!sform_of(*w_qkv, f_qkv, v.name("attn_qkv.weight"), err)) return false; if (!sform_of(*w_gate, f_gate, v.name("attn_gate.weight"), err)) return false; if (!sform_of(*w_out, f_out, v.name("ssm_out.weight"), err)) return false; Planes p_qkv, p_gate, p_out; if (!plane_ptrs(*w_qkv, v.name("attn_qkv.weight"), p_qkv, err)) return false; if (!plane_ptrs(*w_gate, v.name("attn_gate.weight"), p_gate, err)) return false; if (!plane_ptrs(*w_out, v.name("ssm_out.weight"), p_out, err)) return false; using namespace strata::kernels; cudaStream_t st = (cudaStream_t) stream;
// ---- 1. the activation, in EVERY format a weight on this layer might ask for. BOTH quantized images are
// produced, because which one is wanted is a property of the TENSOR and the pack mixes them by
// layer - producing only the "right" one is how the per-role assumption gets baked back in.
st_begin(layer, 8, stream);
// Plan v0.3 P3: the canonical activation images only when a canonical projection reads them.
if (!w_qkv->native_data || !w_gate->native_data) {
#if defined(STRATA_EXPERIMENTAL_SM60)
if (strata::kernels::fuse_decode()) {
quantize_act_images(mixed, g.n_embd, b.x_q8_0, b.x_q8k, nullptr, stream); // ONE pass, was two kernels
} else
#endif
{
quantize_q8_K(mixed, b.x_q8k, g.n_embd, stream);
quantize_q8_0(mixed, b.x_q8_0, g.n_embd, stream);
}
}
st_end(layer, 8, stream);
// ---- 2. qkv = wqkv @ x, with the activation THIS layer's `attn_qkv` asks for
st_begin(layer, 9, stream); if (!gemv_quantized(*w_qkv, p_qkv, f_qkv, b.x_q8_0, b.x_q8k, b.qkv, g.n_embd, C, v.name("attn_qkv.weight"), stream, err, mixed)) return false; st_end(layer, 9, stream);
// ---- 3. conv, then SiLU on the WHOLE conv output - before the q|k|v split, which is what
// `ref/gdn.py` L262 says and what makes the split a reshape rather than a copy.
st_begin(layer, 10, stream);
// Plan v0.3 P3: under the native contract, conv + SiLU + both L2 norms are one kernel, and alpha/beta with their
// epilogues another (`fused_gdn.hpp`).
const bool fused_pre = g_fused_gdn && native_gdn_enabled() && native_bf16_projections && g.ssm_d_conv == 4 &&
g.ssm_state_size == 128;
if (fused_pre) {
fused_gdn_conv_l2(b.conv_state, b.qkv, conv_kernel, b.h, (int) C, (int) (2 * g.ssm_k_heads), RMS_EPS, stream);
} else
try {
if (native_gdn_enabled()) native_gdn_conv_silu(b.conv_state, b.qkv, conv_kernel, b.conv_out, b.h, C, g.ssm_d_conv, stream);
else {
gdn_conv_step(b.conv_state, b.qkv, conv_kernel, b.conv_out, C, g.ssm_d_conv, stream);
cudaMemcpyAsync(b.h, b.conv_out, (size_t) C * 4, cudaMemcpyDeviceToDevice, st);
silu_inplace(b.h, C, stream);
}
} catch (const std::exception& error) { err = v.name("gdn_conv_silu") + ": " + error.what(); return false; }
st_end(layer, 10, stream);
// ---- 4. q,k = l2_norm; v is NOT normalised. The three views are contiguous runs of the same buffer:
// q at [0, 2048), k at [2048, 4096), v at [4096, 10240), each 128-wide heads. const
st_begin(layer, 11, stream); int64_t qk = g.ssm_state_size * g.ssm_k_heads;
if (!fused_pre) try {
if (native_gdn_enabled()) {
native_gdn_l2_norm(b.h, g.ssm_k_heads, g.ssm_state_size, RMS_EPS, stream);
native_gdn_l2_norm(b.h + qk, g.ssm_k_heads, g.ssm_state_size, RMS_EPS, stream);
} else {
gdn_l2_norm(b.h, g.ssm_k_heads, g.ssm_state_size, RMS_EPS, stream);
gdn_l2_norm(b.h + qk, g.ssm_k_heads, g.ssm_state_size, RMS_EPS, stream);
}
} catch (const std::exception& error) { err = v.name("gdn_l2_norm") + ": " + error.what(); return false; }
// The recurrence needs another 1/sqrt(S) beyond Q/K normalization. The legacy
// recurrence consumes prescaled Q; pinned CUDA applies it after the readout dot.
// Keep the scale at that backend-specific boundary to preserve rounding order.
if (!native_gdn_enabled()) scale_inplace(b.h, qk, 1.0f / std::sqrt((float) g.ssm_state_size), stream);
st_end(layer, 11, stream);
// ---- 5. beta and the gate. The weights are BF16. Native single-token CUDA MMVF
// consumes F32 activations; the legacy path rounds them to BF16 first.
//
// THE ROW-SPLIT FORM, and here the case is stronger than the router's: `ssm_v_heads` is **48**, so
// the plain one-thread-per-row form puts 48 threads on a 48-SM GPU and each walks 2,560 elements
// alone. Measured 0.1072 ms each, against 0.0277 for the split - and there are two of them, in all
// 36 GDN layers.
st_begin(layer, 12, stream);
if (fused_pre) {
fused_gdn_ab(mixed, (const uint16_t*) w_alpha->data, (const uint16_t*) w_beta->data, dt, ssm_a, b.gate, b.beta,
(int) g.n_embd, (int) g.ssm_v_heads, stream);
} else {
if (!native_bf16_projections) f32_to_bf16_bulk(mixed, b.x_bf16, g.n_embd, stream);
#if defined(STRATA_EXPERIMENTAL_SM60)
if (strata::kernels::fuse_decode()) {
project_bf16_pair(mixed, b.x_bf16, (const uint16_t*) w_alpha->data, b.alpha, g.ssm_v_heads,
(const uint16_t*) w_beta->data, b.beta, g.ssm_v_heads, g.n_embd, true, stream);
} else
#endif
{
project_bf16(mixed, b.x_bf16, (const uint16_t*) w_alpha->data, b.alpha, g.n_embd, g.ssm_v_heads, true, stream);
project_bf16(mixed, b.x_bf16, (const uint16_t*) w_beta->data, b.beta, g.n_embd, g.ssm_v_heads, true, stream);
}
}
if (!fused_pre) try {
if (native_gdn_enabled()) {
native_gdn_beta_gate(b.beta, g.ssm_v_heads, stream);
native_gdn_gate(b.alpha, dt, ssm_a, b.gate, g.ssm_v_heads, stream);
} else {
gdn_beta_gate(b.beta, g.ssm_v_heads, stream);
gdn_gate(b.alpha, dt, ssm_a, b.gate, 1, g.ssm_v_heads, stream);
}
} catch (const std::exception& error) { err = v.name("gdn_gate") + ": " + error.what(); return false; }
st_end(layer, 12, stream); st_begin(layer, 13, stream);
GdnShapes gs{g.ssm_state_size, g.ssm_k_heads, g.ssm_v_heads};
// Plan v0.3 P3: with the native contract the step and the output norm are one kernel (after the z GEMV).
const bool fused_gdn = g_fused_gdn && native_gdn_enabled() && g.ssm_state_size == 128;
if (!fused_gdn) try {
if (native_gdn_enabled()) native_gdn_step(b.state, b.h, b.h + qk, b.h + 2 * qk, b.gate, b.beta, b.o, gs, stream);
else gdn_step(b.state, b.h, b.h + qk, b.h + 2 * qk, b.gate, b.beta, b.o, gs, stream);
} catch (const std::exception& error) {
err = v.name("gdn_step") + ": " + error.what();
return false;
}
st_end(layer, 13, stream); st_begin(layer, 14, stream);
// ---- 6. the recurrence. q and k are the (16, 128) views; v is the (48, 128) view. The stage marks for
// it live at the end of the alpha/beta/gate line above, because the gate and the step are one sequence.
// ---- 7. z, then y = rms_norm(o) * ssm_norm * sigmoid(z). SIGMOID, not SiLU.
// qkv's native quantize of `mixed` is still in the shared q8_1 scratch: nothing native ran in between.
if (!gemv_quantized(*w_gate, p_gate, f_gate, b.x_q8_0, b.x_q8k, b.z, g.n_embd, g.ssm_value_dim, v.name("attn_gate.weight"), stream, err, mixed,
w_qkv->native_data != nullptr && w_gate->native_data != nullptr)) return false;
try {
if (fused_gdn) fused_gdn_step_norm(b.state, b.h, b.h + qk, b.h + 2 * qk, b.gate, b.beta, b.z, ssm_norm, RMS_EPS, b.y,
(int) g.ssm_k_heads, (int) g.ssm_v_heads, stream);
else if (native_gdn_enabled()) native_gdn_out_norm(b.o, b.z, ssm_norm, b.y, g.ssm_v_heads, g.ssm_state_size, RMS_EPS, stream);
else gdn_out_norm(b.o, b.z, ssm_norm, b.y, g.ssm_v_heads, g.ssm_state_size, RMS_EPS, stream);
} catch (const std::exception& error) { err = v.name("gdn_out_norm") + ": " + error.what(); return false; }
st_end(layer, 14, stream);
// ---- 8. out = ssm_out @ y, whose activation is whatever THIS layer's `ssm_out` asks for
st_begin(layer, 15, stream);
if (!w_out->native_data) {
#if defined(STRATA_EXPERIMENTAL_SM60)
if (strata::kernels::fuse_decode()) {
quantize_act_images(b.y, g.ssm_value_dim, b.y_q8_0, b.y_q8k, nullptr, stream); // ONE pass, was two
} else
#endif
{
quantize_q8_K(b.y, b.y_q8k, g.ssm_value_dim, stream);
quantize_q8_0(b.y, b.y_q8_0, g.ssm_value_dim, stream);
}
} if (!gemv_quantized(*w_out, p_out, f_out, b.y_q8_0, b.y_q8k, out, g.ssm_value_dim, g.n_embd, v.name("ssm_out.weight"), stream, err, b.y)) return false; st_end(layer, 15, stream); return true;}
// ================================ the MoE block ================================
uint64_t moe_buffers_bytes(const ModelGeometry& g, int64_t k) { const uint64_t parts[] = { (uint64_t) g.n_embd * 2,
// x_bf16
(uint64_t) g.n_embd * 2,
// x_f16
(uint64_t) g.n_expert * 4,
// logits
(uint64_t) k * 4,
// ids (int32)
(uint64_t) k * 4,
// weights
(uint64_t) g.n_embd * 4,
// shared
strata::kernels::shared_expert_scratch_bytes(g.n_ff),
// the shared expert's own scratch
(uint64_t) (g.n_embd / 32) * 34,
// x_q8_0
q8k_bytes(g.n_embd),
// x_q8k
}; uint64_t total = 0; for (uint64_t v : parts) total += (v + 15) & ~(uint64_t) 15; return total;}
uint64_t moe_buffers_init(const ModelGeometry& g, int64_t k, void* base, MoEBuffers& b) { const uint64_t parts[] = { (uint64_t) g.n_embd * 2, (uint64_t) g.n_embd * 2, (uint64_t) g.n_expert * 4, (uint64_t) k * 4, (uint64_t) k * 4, (uint64_t) g.n_embd * 4, strata::kernels::shared_expert_scratch_bytes(g.n_ff), (uint64_t) (g.n_embd / 32) * 34, q8k_bytes(g.n_embd), }; uint8_t* p = (uint8_t*) base; void* ptr[9]; uint64_t total = 0; for (int i = 0; i < 9; ++i) { ptr[i] = p; const uint64_t al = (parts[i] + 15) & ~(uint64_t) 15; p += al; total += al; } b.x_bf16 = (uint16_t*) ptr[0]; b.x_f16 = (uint16_t*) ptr[1]; b.logits = (float*) ptr[2]; b.ids = (int*) ptr[3]; b.weights = (float*) ptr[4]; b.shared = (float*) ptr[5]; b.sh_scratch = (float*) ptr[6]; b.x_q8_0 = (uint8_t*) ptr[7]; b.x_q8k = (uint8_t*) ptr[8]; return total;}
bool moe_route(const WeightTable& tables, const ModelGeometry& g, int64_t layer, int64_t k, const MoEBuffers& b, const float* x, void* stream, std::string& err, const Doorbell* db) { using namespace strata::kernels; const LayerView v(tables, layer); const WeightRef* w_router = v.get("ffn_gate_inp.weight"); if (w_router == nullptr) { err = v.name("ffn_gate_inp.weight") + " is missing"; return false; } if (k < 1 || k > 64) { err = "moe_route: k must be 1..64"; return false; }
// ---- the router's activation. The router's weight is BF16 and that is the one `ref/moe.py` singles out.
if (!native_bf16_projections) f32_to_bf16_bulk(x, b.x_bf16, g.n_embd, stream);
// ---- logits = ffn_gate_inp @ bf16(x). The weight is BF16, so this is `bf16_gemv` and not `s_gemv` -
// and using the fp16 activation here instead is the 8.100e-03 error that flips a selection.
//
// **THE ROW-SPLIT VARIANT, BECAUSE THE PLAIN ONE'S PARALLELISM IS THE OUTPUT WIDTH.** `bf16_gemv` is
// one thread per output row: for the router that is 512 threads over 48 SMs, each walking 2,560
// elements sequentially, and it measured **0.2711 ms for a 2.6 MB weight** - about 65x its
// memory-bound floor and the largest single item left inside the MoE after the top-10 was fixed.
// `bf16_gemv_split` exists for precisely this case; its own header says so. Measured here:
// LEDGER L41 -> L42.
project_bf16(x, b.x_bf16, (const uint16_t*) w_router->data, b.logits, g.n_embd, g.n_expert, true, stream);
// ---- routing: softmax over ALL experts, stable descending argsort with ties by index, gather, renormalise
// the native fused router is canonical-512x10 only; anything else takes the generic top-k kernel
if (native_router_enabled() && g.n_expert == 512 && k == 10) {
try { native_router_top10(b.logits, b.ids, b.weights, stream); }
catch (const std::exception& error) { err = v.name("router") + ": " + error.what(); return false; }
} else router_top10(b.logits, 1, (int) g.n_expert, (int) k, b.ids, b.weights, stream);
// ---- THE DOORBELL, AND IT IS THE WHOLE POINT OF THE PROTOCOL. The routed experts' INPUT (`x`) and the
// miss list (`ids`, `weights`) are published to the host HERE, before anything that depends on them,
// so a CPU pool can start on them while the GPU keeps working. Both the copy and the ring are
// captured into `G[l]` like anything else - a kernel writing mapped pinned memory, which round 209
// measured the host seeing 0.050 ms into a 39.8 ms graph.
if (db != nullptr && g_publish_kernel) {
strata::kernels::doorbell_publish(x, b.ids, b.weights, g.n_embd, k, db->d_x_f, db->d_ids, db->d_weights, db->d_seq,
stream);
} else if (db != nullptr) { if (cudaMemcpyAsync(db->d_x_f, x, (size_t) g.n_embd * 4, cudaMemcpyDeviceToDevice, (cudaStream_t) stream) != cudaSuccess || cudaMemcpyAsync(db->d_ids, b.ids, (size_t) k * 4, cudaMemcpyDeviceToDevice, (cudaStream_t) stream) != cudaSuccess || cudaMemcpyAsync(db->d_weights, b.weights, (size_t) k * 4, cudaMemcpyDeviceToDevice, (cudaStream_t) stream) != cudaSuccess) { err = "moe_route: the doorbell handoff copy failed"; return false; }
// THE RING IS LAST, so a host that sees it knows every byte above is in place. Ordering within a
// stream is what makes that true; it is not a timing assumption.
// THE RING LIVES IN A .cu: this file is compiled by the HOST compiler, where `__global__` and `<<<>>>` do
// not exist. The sequence value is read from the HOST copy and incremented, which is what makes the
// write idempotent across replays of the same graph - a captured literal would ring the same number
// forever and the host would never see a change.
strata::kernels::doorbell_ring(db->d_seq, stream); } return true;}
// The verify window's routing: n tokens' logits in one BF16 projection and their top-k in one launch, each token
// bitwise what `moe_route` gives it (the projection is the same kernel per column, the top-k kernel is per token).
// Anything else (a native router, the canonical BF16 GEMVs, a doorbell) takes the per-token `moe_route`.
bool moe_route_window(const WeightTable& tables, const ModelGeometry& g, int64_t layer, int64_t k, const MoEBuffers& b,
const float* x, float* logits, int32_t* ids, float* weights, int n, void* stream, std::string& err) {
using namespace strata::kernels;
const bool batched = native_bf16_projections && !(native_router_enabled() && g.n_expert == 512 && k == 10) &&
!std::getenv("STRATA_ROUTE_PER_TOKEN");
if (!batched || n == 1) {
for (int t = 0; t < n; ++t) {
MoEBuffers mb = b;
mb.logits = logits + t * g.n_expert; mb.ids = ids + t * k; mb.weights = weights + t * k;
if (!moe_route(tables, g, layer, k, mb, x + t * g.n_embd, stream, err, nullptr)) return false;
}
return true;
}
const LayerView v(tables, layer);
const WeightRef* w_router = v.get("ffn_gate_inp.weight");
if (w_router == nullptr) { err = v.name("ffn_gate_inp.weight") + " is missing"; return false; }
if (std::getenv("STRATA_ROUTE_PROJ_PER_TOKEN"))
for (int t = 0; t < n; ++t)
bf16_gemv_fp32_mmvf(x + t * g.n_embd, (const uint16_t*) w_router->data, logits + t * g.n_expert, g.n_embd,
g.n_expert, stream);
else
bf16_gemv_fp32_mmvf_cols(x, (const uint16_t*) w_router->data, logits, g.n_embd, g.n_expert, n, stream);
router_top10(logits, n, (int) g.n_expert, (int) k, ids, weights, stream);
return true;
}
bool moe_shared(const WeightTable& tables, const ModelGeometry& g, int64_t layer, const MoEBuffers& b, const float* x, void* stream, std::string& err) { using namespace strata::kernels; const LayerView v(tables, layer); const WeightRef* w_ginp = v.get("ffn_gate_inp_shexp.weight"); const WeightRef* w_sgate = v.get("ffn_gate_shexp.weight"); const WeightRef* w_sup = v.get("ffn_up_shexp.weight"); const WeightRef* w_sdown = v.get("ffn_down_shexp.weight"); const char* missing = !w_ginp ? "ffn_gate_inp_shexp.weight" : !w_sgate ? "ffn_gate_shexp.weight" : !w_sup ? "ffn_up_shexp.weight" : !w_sdown ? "ffn_down_shexp.weight" : nullptr; if (missing) { err = v.name(missing) + " is missing"; return false; }
// ---- the shared expert. Its three weights are quantized, so they need their planes.
SForm f_gate, f_up, f_down; if (!sform_of(*w_sgate, f_gate, v.name("ffn_gate_shexp.weight"), err)) return false; if (!sform_of(*w_sup, f_up, v.name("ffn_up_shexp.weight"), err)) return false; if (!sform_of(*w_sdown, f_down, v.name("ffn_down_shexp.weight"), err)) return false; Planes p_gate, p_up, p_down; if (!plane_ptrs(*w_sgate, v.name("ffn_gate_shexp.weight"), p_gate, err)) return false; if (!plane_ptrs(*w_sup, v.name("ffn_up_shexp.weight"), p_up, err)) return false; if (!plane_ptrs(*w_sdown, v.name("ffn_down_shexp.weight"), p_down, err)) return false;
// `ffn_gate_inp_shexp` is a 1-D BF16 vector, so THE ARENA HOLDS 2 BYTES PER ELEMENT, not 4 - the loader
// re-rounded it to the engine form like any other BF16 tensor. Reading it as f32 is 5120 bytes past the
// end of a 5120-byte tensor inside a 4.5 GiB arena, where nothing faults. Refuse here rather than trust
// the layout check to have run: this function is reachable without it.
if (w_ginp->kind != WeightKind::Bf16InF32) { err = v.name("ffn_gate_inp_shexp.weight") + " is engine form " + std::to_string((int) w_ginp->kind) + " (" + std::to_string(w_ginp->bytes) + " B); the scalar gate reads it as bf16, so it must be form 1 (" + std::to_string((uint64_t) g.n_embd * 2) + " B)"; return false; }
// THE SHARED EXPERT'S WEIGHTS ARE NOT ONE FAMILY: `ffn_gate_shexp` is Q2_0 on 21 layers and a K-quant on
// the rest, `ffn_up_shexp` Q2_0 on 13, and `ffn_down_shexp` is LEGACY in every layer (IQ4_NL/Q4_0/Q5_0/
// Q8_0/Q2_0, `n_in` 640 so Q8_K is impossible). So BOTH quantized images of the activation are produced
// and each projection takes the one its own form asks for.
// ONE pass over `x` produces the bf16 image and both quantized images (was three kernels): which quantized
// one is wanted is a property of the TENSOR and the pack mixes them by layer, so both are produced.
if (!w_sgate->native_data || !w_sup->native_data) {
#if defined(STRATA_EXPERIMENTAL_SM60)
if (strata::kernels::fuse_decode()) {
quantize_act_images(x, g.n_embd, b.x_q8_0, b.x_q8k, b.x_bf16, stream); // ONE pass, was three kernels
} else
#endif
{
f32_to_bf16_bulk(x, b.x_bf16, g.n_embd, stream);
quantize_q8_K(x, b.x_q8k, g.n_embd, stream);
quantize_q8_0(x, b.x_q8_0, g.n_embd, stream);
}
} else {
f32_to_bf16_bulk(x, b.x_bf16, g.n_embd, stream);
}
NativeSharedWeights native;
native.gate_type = w_sgate->native_type; native.gate_data = w_sgate->native_data;
native.up_type = w_sup->native_type; native.up_data = w_sup->native_data;
native.down_type = w_sdown->native_type; native.down_data = w_sdown->native_data;
// The NativeDense owner publishes one shared workspace for this ordered session stream.
native.q8_1 = w_sgate->native_q8_1 ? w_sgate->native_q8_1 :
w_sup->native_q8_1 ? w_sup->native_q8_1 : w_sdown->native_q8_1;
try {
shared_expert(b.x_q8_0, b.x_q8k, b.x_bf16, f_gate, p_gate.codes, p_gate.scales, p_gate.offset,
f_up, p_up.codes, p_up.scales, p_up.offset, f_down, p_down.codes, p_down.scales,
p_down.offset, (const uint16_t*) w_ginp->data, b.sh_scratch, b.shared,
g.n_embd, g.n_ff, /*tpr=*/32, stream, x, &native);
} catch (const std::exception& error) {
err = v.name("shared_expert") + ": " + error.what();
return false;
}
return true;
}
bool moe_combine_parts(const ModelGeometry& g, int64_t layer, int64_t k, const MoEBuffers& b, const float* parts,
float* out, void* stream, std::string& err) {
using namespace strata::kernels;
if (k < 1 || k > 64) { err = "moe_finish: k must be 1..64"; return false; }
// ---- the combination: sum of w[i] * parts[i], plus the shared output ADDED PLAIN.
//
// **`parts` IS COMBINED WITH `b.weights`, WHICH `moe_route` WROTE FOR *THIS* LAYER.** That is the whole
// reason this is a separate function: a caller that passes the previous layer's expert vectors gets
// `sum_j w_l[j] * expert_{ids_{l-1},j}(x_{l-1})`, which is finite, fluent and not the model.
try {
if (native_moe_combine_enabled()) native_moe_combine(parts, b.weights, b.shared, out, g.n_embd, k, stream);
else moe_combine(parts, b.weights, b.shared, out, g.n_embd, k, stream);
} catch (const std::exception& error) {
err = "blk." + std::to_string(layer) + ".moe_combine" + ": " + error.what();
return false;
}
return true;}
bool moe_finish(const WeightTable& tables, const ModelGeometry& g, int64_t layer, int64_t k, const MoEBuffers& b,
const float* x, const float* parts, float* out, void* stream, std::string& err) {
if (k < 1 || k > 64) { err = "moe_finish: k must be 1..64"; return false; }
if (!moe_shared(tables, g, layer, b, x, stream, err)) return false;
return moe_combine_parts(g, layer, k, b, parts, out, stream, err);
}
bool layer_verify_compatible(std::string& why) {
// Plan v0.3 P6: the verify window reproduces exactly this configuration's per-token arithmetic.
if (!native_bf16_projections) why = "the native BF16 projections are off";
else if (!g_fused_gr) why = "the fused hyper-connection read is off";
else if (!g_fused_gdn || !strata::kernels::native_gdn_enabled()) why = "the fused native GDN kernels are off";
else if (!g_fast_attn || native_flash_attn_short) why = "the split-K decode attention is off";
else if (!g_fast_select) why = "the block top-k selection is off";
else if (!strata::kernels::native_qsa_indexer_enabled()) why = "the native QSA indexer is off";
else return true;
return false;
}
void layer_set_publish_kernel(bool enabled) { g_publish_kernel = enabled; }
void layer_set_fused_gdn(bool enabled) { g_fused_gdn = enabled; }
void layer_set_fast_select(bool enabled) { g_fast_select = enabled; }
void layer_set_fast_attn(bool enabled) { g_fast_attn = enabled; }
void layer_set_fused_gr(bool enabled) { g_fused_gr = enabled; }
bool layer_fused_gr() { return g_fused_gr; }
void layer_set_shared_early(bool enabled) { g_shared_early = enabled; }
bool layer_shared_early() { return g_shared_early; }
bool moe_layer(const WeightTable& tables, const ModelGeometry& g, int64_t layer, int64_t k, const MoEBuffers& b, const float* x, const float* parts, float* out, void* stream, std::string& err, const Doorbell* db) {
// The two halves in sequence. `moe_route` publishes `ids`/`weights` for THIS layer and `moe_finish`
// combines `parts` with them, so a caller of this wrapper must have `parts` ready BEFORE the call - which
// is what `session_token` (the uncaptured path) does and what the captured loop CANNOT, which is why the
// loop uses the halves separately.
if (!moe_route(tables, g, layer, k, b, x, stream, err, db)) return false; return moe_finish(tables, g, layer, k, b, x, parts, out, stream, err);}
// ================================ the QSA mixer ================================
namespace {using strata::kernels::QsaIndexerBuffers;using strata::kernels::QsaShapes;
// `qsa_shapes(g)` (layout.hpp): the geometry the QSA kernels want, every field from the model's geometry
uint64_t align_up16(uint64_t n) { return (n + 15) & ~15ull; }
/// One cursor over an arena, so every region is 16-byte aligned without a list of hand-added offsets.
struct Cursor { uint8_t* p; uint64_t used = 0; template <typename T> T* take(uint64_t count) { T* r = (T*) (p + used); used = align_up16(used + count * sizeof(T)); return r; } uint8_t* take_bytes(uint64_t n) { uint8_t* r = p + used; used = align_up16(used + n); return r; }};
// `TPR` and `gemv_quantized` live in the FIRST anonymous namespace, above, because `gdn_layer` needs the
// dispatch too and the two must not be able to drift.
}
// namespace
namespace {
// KV streaming (docs/kv-streaming-design.md): 0 keeps every cell in VRAM.
int64_t g_kv_resident = 0;
uint64_t g_kv_host_bytes = 0;
// The KV host copy: pinned and device-mapped. cudaHostAlloc is the default, but under WSL2 the driver caps what
// cudaHostAlloc(Mapped) may pin at about 1 GiB in all, while cudaHostRegister of ordinary memory is not capped there:
// the expert arena registers tens of GiB the same way (pinned.cu). So under WSL2, detected as generate.cpp's
// under_wddm() does (/dev/dxg, the device its GPU goes through to the Windows driver), the copy is anonymous memory
// registered Portable|Mapped before any page is touched, which also leaves WSL's small cudaHostAlloc budget to the
// staging buffers. Elsewhere cudaHostAlloc stays first. Either way the other method is the fallback when the first
// is refused. STRATA_KV_HOST_REGISTER=1/0 forces registering first or cudaHostAlloc first. Like the cudaHostAlloc
// copy it lives as long as the process.
uint8_t* kv_host_alloc(uint64_t bytes) {
auto host_alloc = [](uint64_t n) -> uint8_t* {
uint8_t* h = nullptr;
if (strata::core::host_alloc_guarded((void**) &h, n, cudaHostAllocMapped | cudaHostAllocPortable) == cudaSuccess) return h;
(void) cudaGetLastError();
return nullptr;
};
#ifdef _WIN32
return host_alloc(bytes);
#else
static const bool register_first = [] {
const char* e = std::getenv("STRATA_KV_HOST_REGISTER");
if (e != nullptr && (e[0] == '0' || e[0] == '1')) return e[0] == '1';
return std::filesystem::exists("/dev/dxg");
}();
auto register_anon = [](uint64_t n) -> uint8_t* {
void* m = mmap(nullptr, (size_t) n, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
if (m == MAP_FAILED) return nullptr;
if (cudaHostRegister(m, (size_t) n, cudaHostRegisterPortable | cudaHostRegisterMapped) != cudaSuccess) {
(void) cudaGetLastError();
munmap(m, (size_t) n);
return nullptr;
}
static bool said = false;
if (!said) {
std::fprintf(stderr, "strata: KV streaming: the host copy is pinned with cudaHostRegister\n");
said = true;
}
return (uint8_t*) m;
};
if (register_first) {
if (uint8_t* m = register_anon(bytes)) return m;
return host_alloc(bytes);
}
if (uint8_t* h = host_alloc(bytes)) return h;
return register_anon(bytes);
#endif
}
// ---- the elastic K/V (--kv-grow): one VMM range per state, each pool array at a chunk boundary in it
bool g_kv_elastic = false;
int64_t g_kv_elastic_init = 16384;
struct ElasticPool {
strata::core::VmmRange range;
std::vector<uint64_t> off, per_slot; // each array's offset in the range (whole chunks) and bytes per page slot
int64_t n_slots = 0, page_size = 0;
};
std::vector<std::unique_ptr<ElasticPool>> g_pools;
int64_t pool_chunks(const ElasticPool& p, size_t a, int64_t slots) {
const uint64_t G = strata::core::vmm_granularity();
return (int64_t) (((uint64_t) slots * p.per_slot[a] + G - 1) / G);
}
int64_t pool_slots(const ElasticPool& p, int64_t cells) {
return std::min<int64_t>(p.n_slots, std::max<int64_t>((cells + p.page_size - 1) / p.page_size, 1));
}
/// Whole page slots every array of the pool has mapped.
int64_t pool_slots_mapped(const ElasticPool& p) {
const uint64_t G = strata::core::vmm_granularity();
int64_t slots = p.n_slots;
for (size_t a = 0; a < p.off.size(); ++a) {
const int64_t c0 = (int64_t) (p.off[a] / G);
const int64_t end = a + 1 < p.off.size() ? (int64_t) (p.off[a + 1] / G) : p.range.chunks();
int64_t c = 0;
while (c0 + c < end && p.range.mapped(c0 + c)) ++c;
slots = std::min<int64_t>(slots, (int64_t) ((uint64_t) c * G / p.per_slot[a]));
}
return slots;
}
bool pool_grow(ElasticPool& p, int64_t cells, const std::function<strata::core::VmmChunk()>& take) {
const uint64_t G = strata::core::vmm_granularity();
const int64_t slots = pool_slots(p, cells);
for (size_t a = 0; a < p.off.size(); ++a) {
const int64_t c0 = (int64_t) (p.off[a] / G), c1 = c0 + pool_chunks(p, a, slots);
std::vector<int64_t> fresh;
for (int64_t c = c0; c < c1; ++c)
if (!p.range.mapped(c)) fresh.push_back(c);
if (fresh.empty()) continue;
if (!p.range.map_range(c0, c1, take)) {
std::fprintf(stderr, "strata: the elastic K/V could not map %zu chunks (the driver has no VRAM left)\n",
fresh.size());
return false;
}
// what the chunk held before (another pool's cells, an expert) is not K/V: zeroed, as a new session is
for (const int64_t c : fresh)
if (cudaMemset(p.range.base() + (uint64_t) c * G, 0, (size_t) G) != cudaSuccess) {
std::fprintf(stderr, "strata: the elastic K/V could not clear a chunk: %s\n",
cudaGetErrorString(cudaGetLastError()));
return false;
}
}
return true;
}
} // namespace
void qsa_set_kv_elastic(bool enabled, int64_t init_cells) {
g_kv_elastic = enabled && strata::core::vmm_available();
if (init_cells > 0) g_kv_elastic_init = init_cells;
}
bool qsa_kv_elastic() { return g_kv_elastic; }
int64_t qsa_kv_elastic_cells() {
int64_t cells = std::numeric_limits<int64_t>::max();
for (const auto& p : g_pools) cells = std::min<int64_t>(cells, pool_slots_mapped(*p) * p->page_size);
return cells;
}
int64_t qsa_kv_elastic_need(int64_t cells) {
const uint64_t G = strata::core::vmm_granularity();
int64_t n = 0;
for (const auto& p : g_pools) {
const int64_t slots = pool_slots(*p, cells);
for (size_t a = 0; a < p->off.size(); ++a) {
const int64_t c0 = (int64_t) (p->off[a] / G), c1 = c0 + pool_chunks(*p, a, slots);
for (int64_t c = c0; c < c1; ++c) n += !p->range.mapped(c);
}
}
return n;
}
bool qsa_kv_elastic_grow(int64_t cells, const std::function<strata::core::VmmChunk()>& take) {
for (auto& p : g_pools)
if (!pool_grow(*p, cells, take)) return false;
return cudaDeviceSynchronize() == cudaSuccess;
}
int64_t qsa_kv_elastic_shrink(int64_t cells, const std::function<void(strata::core::VmmChunk)>& give) {
const uint64_t G = strata::core::vmm_granularity();
int64_t n = 0;
for (auto& p : g_pools) {
const int64_t slots = pool_slots(*p, cells);
for (size_t a = 0; a < p->off.size(); ++a) {
const int64_t c0 = (int64_t) (p->off[a] / G), c1 = c0 + pool_chunks(*p, a, slots);
const int64_t end = a + 1 < p->off.size() ? (int64_t) (p->off[a + 1] / G) : p->range.chunks();
for (int64_t c = c1; c < end; ++c)
if (const strata::core::VmmChunk h = p->range.unmap(c)) { give(h); ++n; }
}
}
return n;
}
uint64_t qsa_kv_elastic_mapped_bytes() {
uint64_t n = 0;
for (const auto& p : g_pools) n += (uint64_t) p->range.mapped_count() * strata::core::vmm_granularity();
return n;
}
uint64_t qsa_kv_elastic_full_bytes() {
uint64_t n = 0;
for (const auto& p : g_pools) n += (uint64_t) p->range.chunks() * strata::core::vmm_granularity();
return n;
}
namespace {
/// How one state holds its K/V: `mode` as in QsaState::kv_mode, `slots` VRAM pages of `pages` logical ones.
struct KvPlan {
int mode = 0;
int64_t pages = 0, slots = 0, pooled_rows = 0;
};
KvPlan kv_plan(const QsaShapes& s, int64_t max_cells, int64_t ring_cells) {
KvPlan p;
p.pages = (max_cells + s.page_size - 1) / s.page_size;
p.slots = p.pages;
p.pooled_rows = max_cells / s.idx_block + 2;
if (g_kv_resident <= 0 || ring_cells < 0) return p; // ring_cells < 0: always fully resident
// A/B only: STRATA_KV_RING_OFF keeps the drafter fully resident, STRATA_KV_MAIN_OFF the main layers
static const bool ring_off = std::getenv("STRATA_KV_RING_OFF") != nullptr;
static const bool main_off = std::getenv("STRATA_KV_MAIN_OFF") != nullptr;
if (ring_cells > 0 ? ring_off : main_off) return p;
if (ring_cells > 0) {
const int64_t r = (ring_cells + s.page_size - 1) / s.page_size;
if (r < p.pages) { p.mode = 2; p.slots = r; p.pooled_rows = 2; } // the drafter has no indexer
} else {
const int64_t r = (std::max(g_kv_resident, qsa_kv_resident_min()) + s.page_size - 1) / s.page_size;
if (r < p.pages) { p.mode = 1; p.slots = r; }
}
return p;
}
uint64_t kv_pool_bytes(const QsaShapes& s, int64_t pages, bool hybrid, bool int8) {
if (hybrid) { // K8V4: the INT8 K half (codes + scales) plus the Q4_0 V half (kv_q4.hpp's rotation)
const uint64_t rows = (uint64_t) pages * s.page_size * s.n_head_kv;
return rows * (uint64_t) s.head_dim + rows * (uint64_t) (s.head_dim / strata::kernels::KV_Q8_GROUP) * 2 +
rows * strata::kernels::kv_q4_bytes_per_head((int) s.head_dim) + 64;
}
if (g_kv_q4) return (uint64_t) pages * s.page_size * strata::kernels::kv_q4_bytes_per_cell(s) + 64;
return int8 ? (uint64_t) pages * s.page_size * strata::kernels::kv_q8_bytes_per_cell(s) + 64
: (uint64_t) pages * s.n_head_kv * s.page_size * s.head_dim * 2 * 2;
}
} // namespace
void qsa_set_kv_resident(int64_t cells) { g_kv_resident = cells > 0 ? cells : 0; }
int64_t qsa_kv_resident() { return g_kv_resident; }
// The least KV window a streamed session keeps in VRAM (cells): 4096 (was 20480; a window of 4096 and of 8192 gave the same tokens as 20480 with the cache fixed and route tail
// skip off, 2 requests at 128K, 20K- and 8K-token prompts; setup still writes 32768, fit_start walks 20480 / 8192 / 4096 only on a card that is short). STRATA_KV_RESIDENT_MIN=N overrides (the
// selection reads at most idx_top_k + idx_block - 1 cells per row, so a window of a few thousand cells holds it; the pool must hold the blocks of every row of a verify window).
int64_t qsa_kv_resident_min() {
static const int64_t v = [] {
const char* e = std::getenv("STRATA_KV_RESIDENT_MIN");
const long long n = e != nullptr ? std::atoll(e) : 0;
#if defined(STRATA_GPU_METAL)
return n >= 1024 ? (int64_t) n : (int64_t) 20480; // a Mac keeps the old floor: its pool is the host's RAM (strata/core/spill_gate.hpp)
#else
return n >= 1024 ? (int64_t) n : (int64_t) 4096;
#endif
}();
return v;
}
uint64_t qsa_kv_host_bytes() { return g_kv_host_bytes; }
uint64_t qsa_state_bytes(const ModelGeometry& g, int64_t max_cells, bool with_rope, int64_t ring_cells) {
const QsaShapes s = qsa_shapes(g);
const KvPlan p = kv_plan(s, max_cells, ring_cells);
uint64_t n = 0;
if (!(g_kv_elastic && p.mode == 0)) // the elastic K/V's pools are in their own VMM range
n += kv_pool_bytes(s, p.slots, g_kv_hybrid && ring_cells <= 0,
g_kv_int8 || g_kv_hybrid) + 4 * 16; // K/V pools (the VRAM slots)
n += (uint64_t) p.pages * 4; // page_table
if (p.mode == 1) n += strata::kernels::kv_stream_map_bytes(p.slots) + 6 * 16; // the residency map
n += (uint64_t) (s.idx_block - 1) * s.idx_dim * 4; // tail
n += (uint64_t) s.idx_dim * 4; // dead
n += (uint64_t) p.pooled_rows * s.idx_dim * 4; // pooled
n += 16; // block_pos
if (with_rope) n += (uint64_t) max_cells * (s.n_rot / 2) * 4 * 2; // cos + sin tables
n += strata::kernels::qsa_step_bytes() + 16; // counts and aligned attention status
n += (uint64_t) s.n_head * 4; // pos_dev
return align_up16(n) + 256;
}
uint64_t qsa_state_init(const ModelGeometry& g, int64_t max_cells, void* base, QsaState& st,
const QsaState* share_rope, int64_t ring_cells) {
const QsaShapes s = qsa_shapes(g);
const KvPlan p = kv_plan(s, max_cells, ring_cells);
const int64_t pages = p.pages;
Cursor c{(uint8_t*) base};
st.kv_int8 = g_kv_int8 && !g_kv_q4;
st.kv_q4 = g_kv_q4;
// Hybrid K8V4, main layers only (the drafter's state is created with the globals toggled to INT8 -
// mtp.cpp). A streamed one keeps its host copy in the same three runs (kv_stream.cu, kKvHybrid).
if (g_kv_hybrid && ring_cells <= 0) {
st.kv_hybrid = true;
st.kv_int8 = false;
st.kv_q4 = false;
}
st.kv_rot = st.kv_q4 || (st.kv_int8 && g_kv_int8_rot); // K8V4 rotates only V (below)
st.kv_mode = p.mode;
st.n_slots = p.slots;
const uint64_t rows = (uint64_t) p.slots * s.n_head_kv * s.page_size; // VRAM rows: the slots
const uint64_t q4_row = strata::kernels::kv_q4_bytes_per_head((int) s.head_dim);
st.kv_elastic = -1;
if (g_kv_elastic && p.mode == 0) {
// the elastic K/V: each array at a chunk boundary of the state's own range, the first cells mapped
const uint64_t slot_rows = (uint64_t) s.n_head_kv * s.page_size;
const uint64_t scale_row = (uint64_t) (s.head_dim / strata::kernels::KV_Q8_GROUP) * 2;
std::vector<uint64_t> per; // bytes per page slot of each array, in the order they are assigned below
if (st.kv_hybrid) per = {slot_rows * s.head_dim, slot_rows * scale_row, slot_rows * q4_row};
else if (st.kv_q4) per = {slot_rows * q4_row, slot_rows * q4_row};
else if (st.kv_int8) per = {slot_rows * s.head_dim, slot_rows * s.head_dim, slot_rows * scale_row, slot_rows * scale_row};
else per = {slot_rows * s.head_dim * 2, slot_rows * s.head_dim * 2};
auto pool = std::make_unique<ElasticPool>();
const uint64_t G = strata::core::vmm_granularity();
uint64_t at = 0;
for (const uint64_t b : per) {
pool->off.push_back(at);
at += ((uint64_t) p.slots * b + G - 1) / G * G;
}
pool->per_slot = per;
pool->n_slots = p.slots;
pool->page_size = s.page_size;
if (!pool->range.reserve(at) || !pool_grow(*pool, g_kv_elastic_init, [] { return (strata::core::VmmChunk) 0; })) {
std::fprintf(stderr, "strata: the elastic K/V could not reserve or map its pools\n");
return 0;
}
uint8_t* b = pool->range.base();
const uint64_t* o = pool->off.data();
if (st.kv_hybrid) { st.k_q = (int8_t*) (b + o[0]); st.k_scale = (uint16_t*) (b + o[1]); st.v_q4 = b + o[2]; }
else if (st.kv_q4) { st.k_q4 = b + o[0]; st.v_q4 = b + o[1]; }
else if (st.kv_int8) {
st.k_q = (int8_t*) (b + o[0]);
st.v_q = (int8_t*) (b + o[1]);
st.k_scale = (uint16_t*) (b + o[2]);
st.v_scale = (uint16_t*) (b + o[3]);
} else { st.k_pool = (uint16_t*) (b + o[0]); st.v_pool = (uint16_t*) (b + o[1]); }
st.kv_elastic = (int32_t) g_pools.size();
g_pools.push_back(std::move(pool));
} else if (st.kv_hybrid) {
st.k_q = c.take<int8_t>(rows * s.head_dim);
st.k_scale = c.take<uint16_t>(rows * (s.head_dim / strata::kernels::KV_Q8_GROUP));
st.v_q4 = c.take<uint8_t>(rows * q4_row);
} else if (st.kv_q4) {
st.k_q4 = c.take<uint8_t>(rows * q4_row);
st.v_q4 = c.take<uint8_t>(rows * q4_row);
} else if (st.kv_int8) { // st, not the global: the drafter's ring is INT8 under --kv k8v4 too
st.k_q = c.take<int8_t>(rows * s.head_dim);
st.v_q = c.take<int8_t>(rows * s.head_dim);
st.k_scale = c.take<uint16_t>(rows * (s.head_dim / strata::kernels::KV_Q8_GROUP));
st.v_scale = c.take<uint16_t>(rows * (s.head_dim / strata::kernels::KV_Q8_GROUP));
} else {
st.k_pool = c.take<uint16_t>(rows * s.head_dim);
st.v_pool = c.take<uint16_t>(rows * s.head_dim);
}
st.page_table = c.take<int32_t>((uint64_t) pages);
st.n_pages = pages;
st.max_cells = max_cells;
st.map = strata::kernels::KvStreamMap{};
st.map.page_table = st.page_table;
st.map.n_blocks = pages;
st.map.n_slots = p.slots;
if (p.mode == 1) {
st.map.slot_block = c.take<int32_t>((uint64_t) p.slots);
st.map.slot_stamp = c.take<int32_t>((uint64_t) p.slots);
st.map.slot_ref = c.take<int32_t>((uint64_t) p.slots);
st.map.miss_block = c.take<int32_t>((uint64_t) p.slots);
st.map.miss_slot = c.take<int32_t>((uint64_t) p.slots);
st.map.ctl = c.take<int32_t>((uint64_t) strata::kernels::kKvCtlInts);
}
st.idx_tail = c.take<float>((uint64_t) (s.idx_block - 1) * s.idx_dim);
st.idx_dead = c.take<float>((uint64_t) s.idx_dim);
st.idx_pooled_rows = p.pooled_rows;
st.idx_pooled = c.take<float>((uint64_t) p.pooled_rows * s.idx_dim);
st.idx_block_pos = c.take<int32_t>(1);
if (share_rope != nullptr) {
st.cos_tab = share_rope->cos_tab;
st.sin_tab = share_rope->sin_tab;
} else {
st.cos_tab = c.take<float>((uint64_t) max_cells * (s.n_rot / 2));
st.sin_tab = c.take<float>((uint64_t) max_cells * (s.n_rot / 2));
}
st.step = c.take<int32_t>((uint64_t) strata::kernels::kStepCount);
st.attention_status = c.take<int32_t>(1);
st.pos_dev = c.take<int32_t>((uint64_t) s.n_head);
// the pinned staging the uploads copy FROM - see the note on `host_step` in the header
if (strata::core::host_alloc_guarded((void**) &st.host_step, strata::kernels::qsa_step_bytes() + sizeof(int32_t),
cudaHostAllocMapped | cudaHostAllocPortable) != cudaSuccess ||
strata::core::host_alloc_guarded((void**) &st.host_pos, (size_t) s.n_head * 4, cudaHostAllocMapped | cudaHostAllocPortable) !=
cudaSuccess) {
return 0; // the caller sees a zero byte count; a half-built state is worse than none
}
st.host_step[strata::kernels::kStepCount] = 0;
// KV streaming: the authoritative K/V of every cell, pinned and device-mapped, in the identity layout
st.host = strata::kernels::KvHostPools{};
if (p.mode != 0) {
const uint64_t hrows = (uint64_t) pages * s.n_head_kv * s.page_size;
const uint64_t bytes = (uint64_t) pages * strata::kernels::kv_block_bytes(s, qsa_kv_format(st)) + 4 * 256;
uint8_t* h = nullptr;
uint8_t* d = nullptr;
if ((h = kv_host_alloc(bytes)) == nullptr ||
cudaHostGetDevicePointer((void**) &d, h, 0) != cudaSuccess) {
// both cudaHostRegister and cudaHostAlloc were refused (kv_host_alloc): usually not enough free RAM
if (p.mode == 1) std::fprintf(stderr, "strata: KV streaming: cannot pin %.2f GiB of RAM for a layer's KV copy "
"(%.2f GiB pinned so far): RAM or the driver refused to pin it - lower the context, "
"or run without --kv-resident\n", (double) bytes / 1073741824.0,
(double) g_kv_host_bytes / 1073741824.0);
return 0;
}
g_kv_host_bytes += bytes;
Cursor hc{d};
if (st.kv_hybrid) {
st.host.k_q = hc.take<int8_t>(hrows * s.head_dim);
st.host.k_scale = hc.take<uint16_t>(hrows * (s.head_dim / strata::kernels::KV_Q8_GROUP));
st.host.v_q4 = hc.take<uint8_t>(hrows * q4_row);
} else if (st.kv_q4) {
st.host.k_q4 = hc.take<uint8_t>(hrows * q4_row);
st.host.v_q4 = hc.take<uint8_t>(hrows * q4_row);
} else if (st.kv_int8) {
st.host.k_q = hc.take<int8_t>(hrows * s.head_dim);
st.host.v_q = hc.take<int8_t>(hrows * s.head_dim);
st.host.k_scale = hc.take<uint16_t>(hrows * (s.head_dim / strata::kernels::KV_Q8_GROUP));
st.host.v_scale = hc.take<uint16_t>(hrows * (s.head_dim / strata::kernels::KV_Q8_GROUP));
} else {
st.host.k_pool = hc.take<uint16_t>(hrows * s.head_dim);
st.host.v_pool = hc.take<uint16_t>(hrows * s.head_dim);
}
}
// THE ROPE TABLE IS BUILT ON THE HOST IN FLOAT64 and uploaded once, because the reference computes its
// frequencies in float64 and reproducing that on device means double-precision `pow`/`cos` that need not
// agree with the host's libm. A table shorter than the sequence would have the rotation read past it.
// The process's rope scaling (none by default) is INSIDE the table - the rotation kernels cannot tell.
if (share_rope == nullptr) {
std::vector<float> hc((size_t) max_cells * (s.n_rot / 2)), hs((size_t) max_cells * (s.n_rot / 2));
strata::kernels::build_rope_table((int) s.n_rot, strata::kernels::rope_scaling(), (int) max_cells,
hc.data(), hs.data());
cudaMemcpy(st.cos_tab, hc.data(), hc.size() * 4, cudaMemcpyHostToDevice);
cudaMemcpy(st.sin_tab, hs.data(), hs.size() * 4, cudaMemcpyHostToDevice);
st.owns_rope = true;
if (s.n_rot == 64) // the native and prompt-path rope kernels read it (mrope.hpp, STRATA_ROPE_TABLE=1)
strata::kernels::rope_table_set(st.cos_tab, st.sin_tab, (int) max_cells, strata::kernels::rope_scaling());
}
// the page table starts as the IDENTITY, which is the simplest legal mapping and what a caller that does
// not page at all wants; a streamed state starts with nothing resident, a ring at `block % n_slots`.
if (p.mode == 0) {
std::vector<int32_t> tab((size_t) pages);
for (int64_t i = 0; i < pages; ++i) tab[(size_t) i] = (int32_t) i;
cudaMemcpy(st.page_table, tab.data(), tab.size() * 4, cudaMemcpyHostToDevice);
} else if (p.mode == 1) {
strata::kernels::kv_stream_reset(st.map, nullptr);
} else {
strata::kernels::kv_ring_table(st.page_table, pages, p.slots, nullptr);
}
cudaDeviceSynchronize();
return c.used;
}
void qsa_state_zero(const QsaState& st, const ModelGeometry& g, void* stream) {
const QsaShapes s = qsa_shapes(g);
cudaStream_t cs = (cudaStream_t) stream;
// an elastic state zeroes what is mapped (the rest is zeroed when it is mapped)
const int64_t live_slots = st.kv_elastic >= 0 ? pool_slots_mapped(*g_pools[(size_t) st.kv_elastic]) : st.n_slots;
const size_t rows = (size_t) live_slots * s.n_head_kv * s.page_size;
if (st.kv_hybrid) {
cudaMemsetAsync(st.k_q, 0, rows * s.head_dim, cs);
cudaMemsetAsync(st.k_scale, 0, rows * (s.head_dim / strata::kernels::KV_Q8_GROUP) * 2, cs);
cudaMemsetAsync(st.v_q4, 0, rows * strata::kernels::kv_q4_bytes_per_head((int) s.head_dim), cs);
} else if (st.kv_q4) {
cudaMemsetAsync(st.k_q4, 0, rows * strata::kernels::kv_q4_bytes_per_head((int) s.head_dim), cs);
cudaMemsetAsync(st.v_q4, 0, rows * strata::kernels::kv_q4_bytes_per_head((int) s.head_dim), cs);
} else if (st.kv_int8) {
cudaMemsetAsync(st.k_q, 0, rows * s.head_dim, cs);
cudaMemsetAsync(st.v_q, 0, rows * s.head_dim, cs);
cudaMemsetAsync(st.k_scale, 0, rows * (s.head_dim / strata::kernels::KV_Q8_GROUP) * 2, cs);
cudaMemsetAsync(st.v_scale, 0, rows * (s.head_dim / strata::kernels::KV_Q8_GROUP) * 2, cs);
} else {
cudaMemsetAsync(st.k_pool, 0, rows * s.head_dim * 2, cs);