Repository navigation
Expand file tree
/
Copy pathverify.cpp
More file actions
5454 lines (5335 loc) · 312 KB
/
Copy pathverify.cpp
File metadata and controls
5454 lines (5335 loc) · 312 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/verify.cpp - see include/strata/core/verify.hpp.
// HostGraphLaunch (the graph launched by the calling thread, or by a helper thread so this one can serve the doorbells): CUDA builds,
// and the Windows HIP build (STRATA_VERIFY_ASYNC_LAUNCH=1 launches from a helper thread; STRATA_LAUNCH_PROBE=1 logs the launch timing).
#if (!defined(STRATA_USE_HIP) && !defined(STRATA_HIP_GFX906)) || (defined(STRATA_USE_HIP) && !defined(STRATA_HIP_GFX906) && defined(_WIN32))
#define STRATA_VERIFY_HGL 1
#endif
#include "strata/core/batch_rows.hpp"
#include "strata/core/sm75_series.hpp"
#include "strata/core/sm120_series.hpp"
#include "strata/core/defaults_026.hpp"
#include "strata/kernels/gfx_arch.hpp"
#include "strata/core/verify.hpp"
#include "strata/core/window_evict.hpp"
#include "strata/core/expert_nibble.hpp"
#include "strata/core/pin_budget.hpp"
#if defined(STRATA_VERIFY_HGL)
#include "strata/core/host_graph_launch.hpp"
#endif
#include "strata/core/remote_expert_opt.hpp"
#include "strata/core/dma_batch.hpp"
#include "strata/core/spec_prob.hpp"
#include "strata/core/spec_proposal.hpp"
#if defined(_WIN32)
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <windows.h>
#include <intrin.h>
#endif
#include "strata/core/native_head.hpp"
#include "strata/core/on_device.hpp"
#include "strata/core/peer_experts.hpp"
#include "strata/kernels/iq_kernels.hpp"
#include "strata/kernels/cpu/expert_layout.hpp"
#include "strata/kernels/cpu/hadamard.hpp"
#include "strata/kernels/bf16_gemv.hpp"
#include "strata/kernels/native_router.hpp"
#include "strata/kernels/native_moe.hpp"
#include "strata/kernels/cpu/expert.hpp"
#include "strata/kernels/elementwise.hpp"
#include "strata/kernels/qsa_prompt_attn.hpp"
#include "strata/kernels/fused_gr.hpp"
#include "strata/kernels/route_prior.hpp"
#include "strata/kernels/cvec.hpp"
#include "strata/kernels/gr.hpp"
#include "strata/kernels/kv_q4.hpp"
#include "strata/kernels/kv_q8.hpp"
#include "strata/kernels/native_mmvq.hpp"
#include "strata/core/dispatch_stats.hpp"
#include "strata/kernels/native_gr_postops.hpp"
#include "strata/kernels/native_ple_postops.hpp"
#include "strata/kernels/native_qsa.hpp"
#include "strata/kernels/native_qsa_indexer.hpp"
#include "strata/kernels/native_rope.hpp"
#include "strata/kernels/ngram.hpp"
#include "strata/kernels/pdl.hpp"
#include "strata/kernels/ple.hpp"
#include "strata/kernels/qsa.hpp"
#include "strata/kernels/qsa_decode_attn.hpp"
#include "strata/kernels/qsa_select.hpp"
#include "strata/kernels/quantize_act.hpp"
#include "strata/kernels/rope.hpp"
#include "strata/kernels/s2_expert_grouped.hpp"
#include "strata/kernels/sampler.hpp"
#include "strata/core/progress.hpp"
#include "strata/kernels/shared_expert.hpp"
#include "strata/kernels/verify_kernels.hpp"
#if defined(STRATA_HAVE_DFLASH2)
#include "strata/kernels/dflash2.hpp"
#endif
#include <algorithm>
#include <atomic>
#include <map>
#include <set>
#include <mutex>
#include <string>
#include <optional>
#include <thread>
#include <vector>
#include <chrono>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <exception>
#include "strata/platform/cpu_relax.hpp"
#if defined(STRATA_GPU_METAL)
// The Metal backend's decode window (metal/src/engine/window.cpp): this file's init/run/commit hand over to it.
namespace strata::metal_engine {
void window_destroy(void* w);
void* window_create();
bool window_init(void* w, const strata::core::ModelGeometry& g, strata::core::SessionState& ss, int max_t, int64_t max_cells,
int64_t* n_vocab, std::string& err);
bool window_run(void* w, int T, const int32_t* tokens, int64_t pos0, bool head, int32_t* out, std::string& err);
bool window_commit(void* w, int n_keep, std::string& err);
bool window_copy_logits(void* w, int t, float* host);
void window_set_sampling(void* w, const strata::kernels::SamplerParams* sp, const int32_t* hist, int hist_len);
bool window_sample_slot_row(void* w, int row, const strata::kernels::SamplerParams& sp, const int32_t* hist, int hist_len, int32_t* tok, std::string& err);
bool window_init_slots(void* w, const std::vector<strata::core::SessionState*>& slots, std::string& err);
bool window_run_slots(void* w, const int* rows, int S, const int32_t* tokens, const int64_t* pos, int32_t* out, std::string& err);
bool window_taps(void* w, const std::vector<int>& layers, const float** tap_dev, std::string& err); // dflash2.inc
} // namespace strata::metal_engine
#endif
namespace strata::core {
namespace {
constexpr float EPS = 1e-6f;
using Clock = std::chrono::steady_clock;
double ms_since(Clock::time_point t) { return std::chrono::duration<double, std::milli>(Clock::now() - t).count(); }
const bool g_dbg = std::getenv("STRATA_VERIFY_DEBUG") != nullptr;
inline bool g_lfuse() { static const bool on = [] { const char* v = std::getenv("STRATA_LFUSE"); return v != nullptr && v[0] == '1'; }(); return on; }
// STRATA_ROUTE_RESIDENT=<margin logits> (+ STRATA_ROUTE_RESIDENT_RANKS=lo-hi, default 6-9): residency-biased routing.
struct RouteResidentCfg;
RouteResidentCfg& route_resident_cfg();
struct RouteResidentCfg {
float margin = 0.0f;
int lo = 6, hi = 9;
// #1578: one counter block per GPU. A layer split inits a verifier per stage; a block allocated on whichever device
// was current at the first init is unreachable from the other stage's kernels without P2P (illegal memory access).
// The Verifier asks for its device's block in init (outside graph capture) and keeps the pointer: a launch never
// picks the block by the host thread's current device. nullptr (the allocation failed): the kernel runs without counters.
std::mutex mu;
std::map<int, unsigned long long*> blocks;
unsigned long long* stats_on(int dev) {
if (margin <= 0.0f || dev < 0) return nullptr;
std::lock_guard<std::mutex> lk(mu);
const auto it = blocks.find(dev);
if (it != blocks.end()) return it->second;
unsigned long long* p = nullptr;
{
const OnDevice on(dev);
if (cudaMalloc((void**) &p, 8 * sizeof(unsigned long long)) != cudaSuccess ||
cudaMemset(p, 0, 8 * sizeof(unsigned long long)) != cudaSuccess) {
(void) cudaGetLastError();
if (p != nullptr) cudaFree(p);
p = nullptr;
std::fprintf(stderr, "route-resident: the counters could not be allocated on GPU %d; it runs without them\n", dev);
}
}
if (blocks.empty()) {
std::atexit([] {
RouteResidentCfg& c = route_resident_cfg();
for (const auto& kv : c.blocks) {
if (kv.second == nullptr) continue;
unsigned long long h[8] = {}; // (the counter block allocated above: 8 words)
if (cudaSetDevice(kv.first) != cudaSuccess || cudaDeviceSynchronize() != cudaSuccess ||
cudaMemcpy(h, kv.second, sizeof(h), cudaMemcpyDeviceToHost) != cudaSuccess) {
(void) cudaGetLastError();
continue;
}
char who[32] = "";
if (c.blocks.size() > 1) std::snprintf(who, sizeof who, " (GPU %d)", kv.first);
std::fprintf(stderr, "route-resident%s: margin=%g ranks=%d-%d windows T>8 (prompt reads): tail_nonres=%llu swaps=%llu (%.1f%%) nonres_entries before=%llu after=%llu\n",
who, c.margin, c.lo, c.hi, h[0], h[1], h[0] ? 100.0 * h[1] / h[0] : 0.0, h[2], h[3]);
std::fprintf(stderr, "route-resident%s: margin=%g ranks=%d-%d windows T<=8 (decode): tail_nonres=%llu swaps=%llu (%.1f%%) nonres_entries before=%llu after=%llu\n",
who, c.margin, c.lo, c.hi, h[4], h[5], h[4] ? 100.0 * h[5] / h[4] : 0.0, h[6], h[7]);
}
});
}
blocks[dev] = p;
return p;
}
};
RouteResidentCfg& route_resident_cfg() {
static RouteResidentCfg c;
static const bool parsed = [] {
if (const char* v = std::getenv("STRATA_ROUTE_RESIDENT")) c.margin = (float) std::atof(v);
if (const char* v = std::getenv("STRATA_ROUTE_RESIDENT_RANKS")) std::sscanf(v, "%d-%d", &c.lo, &c.hi);
return true;
}();
(void) parsed;
return c;
}
inline bool g_lfuse_gate() { static const bool on = [] { const char* v = std::getenv("STRATA_LFUSE_GATE"); return v == nullptr || v[0] != '0'; }(); return on; }
inline bool g_lfuse_pair() { static const bool on = [] { const char* v = std::getenv("STRATA_LFUSE_PAIR"); return v == nullptr || v[0] != '0'; }(); return on; }
inline bool g_qdedup() { static const bool on = [] { const char* v = std::getenv("STRATA_VERIFY_QDEDUP"); return v != nullptr && std::atoi(v) != 0; }(); return on; }
// S26 STRATA_QFUSE=1: activation q8_1 images written by their producers (the GDN output norm) - the same bytes
// fork F4 (Eddoursul): 2-4 token dense projections read an interleaved copy of the q8_1 activations (bitwise the same
// outputs); STRATA_MMVQ_IL=0 keeps native_mmvq's multi-column kernels
inline bool g_mmvq_il() { static const bool on = [] { const char* v = std::getenv("STRATA_MMVQ_IL"); return v == nullptr || v[0] != '0'; }(); return on; }
// STRATA_SELECT_LONG=1 (opt-in): a window graph past select_long_at() cells takes the long-context QSA select
// (qsa_block_topk_long's multi-CTA top-k through topk_scratch_, qsa_block_scores_long's shuffle-free decode scorer;
// both compute capability 6.x by default, the same ids and score bits). Each costs ~6 more kernels a call, which only
// a longer context pays back (4x GP100: 0.5 ms a window more at 1K, even at 30K, 4.0-4.7 ms less at 300K), so the
// verifier keeps a second set of window graphs for it. Off: no scratch, no second graphs.
inline bool select_long_on() {
static const bool on = [] {
const char* v = std::getenv("STRATA_SELECT_LONG");
if (v == nullptr || v[0] != '1') return false;
if (strata::kernels::qsa_topk_multi_scratch_ints(1) <= 0) { // a build without the multi-CTA kernels: no second graphs
std::fprintf(stderr, "strata verify: STRATA_SELECT_LONG=1 needs the CUDA build with STRATA_EXPERIMENTAL_SM60; "
"ignored\n");
return false;
}
return true;
}();
return on;
}
// STRATA_SELECT_LONG_AT: the threshold in cells (default 65536; 0: always)
inline int64_t select_long_at() {
static const int64_t at = [] {
const char* v = std::getenv("STRATA_SELECT_LONG_AT");
return v != nullptr && v[0] != 0 ? (int64_t) std::atoll(v) : (int64_t) 65536;
}();
return at;
}
// 143-amdk: STRATA_QFUSE_HC - only the hyper-connection read writes its consumer's q8_1 image (not the GDN recurrence): gfx12 default (=0 / 1 forces off / on)
inline bool g_qfuse_hc() {
#if defined(STRATA_USE_HIP)
static const bool on = [] {
const char* v = std::getenv("STRATA_QFUSE_HC");
if (v != nullptr) return std::atoi(v) != 0;
int dev = 0;
cudaDeviceProp p;
return cudaGetDevice(&dev) == cudaSuccess && cudaGetDeviceProperties(&p, dev) == cudaSuccess &&
strata::kernels::gfx_arch_is_gfx12(p.gcnArchName);
}();
return on;
#else
return false;
#endif
}
// STRATA_GRAPH_PRIO=1 (opt-in): the window graph's kernel nodes keep their capturing stream's
// priority (side_ high, sh_cs_ low). Unset / 0: every node at the launch stream's priority, as before.
[[maybe_unused]] inline bool graph_prio_on() { // (every HIP caller is guarded off)
#if defined(STRATA_USE_HIP) || defined(STRATA_HIP_GFX906) || defined(STRATA_GPU_METAL)
return false;
#else
static const bool on = [] { const char* v = std::getenv("STRATA_GRAPH_PRIO"); return v != nullptr && std::atoi(v) != 0; }();
return on;
#endif
}
// STRATA_GRAPH_PRIO: the capture and graph queries by CUDA version (13 renamed the edge-data forms: the same split as
// verify_kernels.cu's and the PDL edge check above). Nothing is returned for the edge data.
#if !defined(STRATA_USE_HIP) && !defined(STRATA_HIP_GFX906) && !defined(STRATA_GPU_METAL)
inline cudaError_t prio_capture_deps(cudaStream_t s, cudaStreamCaptureStatus* st, const cudaGraphNode_t** deps, size_t* n) {
#if CUDART_VERSION >= 13000
return cudaStreamGetCaptureInfo(s, st, nullptr, nullptr, deps, nullptr, n);
#elif CUDART_VERSION >= 12030
return cudaStreamGetCaptureInfo_v3(s, st, nullptr, nullptr, deps, nullptr, n);
#else
return cudaStreamGetCaptureInfo_v2(s, st, nullptr, nullptr, deps, n);
#endif
}
inline cudaError_t prio_node_deps(cudaGraphNode_t node, cudaGraphNode_t* deps, size_t* n) {
#if CUDART_VERSION >= 13000
return cudaGraphNodeGetDependencies(node, deps, nullptr, n);
#elif CUDART_VERSION >= 12030
return cudaGraphNodeGetDependencies_v2(node, deps, nullptr, n);
#else
return cudaGraphNodeGetDependencies(node, deps, n);
#endif
}
#endif
// fork 34a35db + b063c13 (Eddoursul), STRATA_SIDE_MIXER=1 / =2: the mixer's work that reads only the layer's input on
// branches of the window's graph (bitwise the same outputs); 0 = in line, and no branch stream is created. Unset: 2 on a
// compute capability 12.0 card (sm120_series.hpp; STRATA_SM120_PERF=0 turns it off), 0 elsewhere.
inline int g_side_mixer() {
static const int env = [] { const char* v = std::getenv("STRATA_SIDE_MIXER"); return v ? std::max(0, std::min(2, std::atoi(v))) : -1; }();
if (env >= 0) return env;
#if defined(STRATA_USE_HIP) || defined(STRATA_GPU_METAL)
return 0;
#else
static int per_dev[64]; // 0 unknown, else mode + 1
int dev = 0;
if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) { cudaGetLastError(); return 0; }
if (!per_dev[dev]) {
int maj = 0, mnr = 0;
const bool ok = cudaDeviceGetAttribute(&maj, cudaDevAttrComputeCapabilityMajor, dev) == cudaSuccess &&
cudaDeviceGetAttribute(&mnr, cudaDevAttrComputeCapabilityMinor, dev) == cudaSuccess;
if (!ok) cudaGetLastError();
per_dev[dev] = 1 + (ok && strata::sm120_default(maj, mnr) ? 2 : 0);
}
return per_dev[dev] - 1;
#endif
}
// STRATA_ROUTE_PRIOR=lambda: residency-biased routing (the top-10 picked again with a logit bonus for the resident
// experts; route_prior.cu). OFF unless asked for (STRATA_ROUTE_PRIOR=1.5, strata::kRoutePriorSmallCard in sm120_series.hpp, is the value the
// app's Expert-settings row writes): 0.2.7 turned 1.5 on by itself on a discrete NVIDIA card of 13 GiB or less, and the owner took that default
// back on 2026-10-29 (#4402: repetition loops and weaker results in long agent sessions). With nothing set this is 0.2.6's behaviour, exactly.
// Measured on an RTX 3060 12 GB only (IQ3_XXS; at 1.5 story +15%, code +37% decode against off). Any value in the variable wins on every card.
// The value is read once.
inline float g_route_prior() {
static const char* const env_s = std::getenv("STRATA_ROUTE_PRIOR");
static const float lambda = strata::route_prior_resolve(env_s, false, false, 0.0);
return lambda;
}
inline bool g_qfuse() { static const bool on = [] { const char* v = std::getenv("STRATA_QFUSE"); return v != nullptr && std::atoi(v) != 0; }(); return on; }
#define VDBG(...) do { if (g_dbg) { std::fprintf(stderr, "verify dbg: " __VA_ARGS__); std::fflush(stderr); } } while (0)
struct Bump {
uint8_t* base = nullptr;
uint64_t used = 0;
template <typename T> T* take(uint64_t n) {
T* p = base ? (T*) (base + used) : nullptr;
used += (n * sizeof(T) + 255) & ~255ull;
return p;
}
};
// #649 (HIP, opt-in A/Bs for the gfx1030 verify timeouts; CUDA never reads them)
// STRATA_VERIFY_COHERENT=1 the handshake words and rows in explicitly coherent (fine-grained) host memory
// STRATA_DOORBELL_STORE=1 the GPU stores each step's ring instead of read-modify-writing it over PCIe
bool env_on(const char* name) {
const char* e = std::getenv(name);
return e != nullptr && e[0] != 0 && e[0] != '0';
}
#if defined(STRATA_USE_HIP)
const bool g_coherent = env_on("STRATA_VERIFY_COHERENT");
const bool g_doorbell_store = env_on("STRATA_DOORBELL_STORE");
#endif
const bool g_trace = env_on("STRATA_VERIFY_TRACE");
// STRATA_LAUNCH_PROBE (STRIX-TDR): process start, and the first windows' launch timing
const Clock::time_point g_proc_t0 = Clock::now();
Clock::time_point probe_proc_t0() { return g_proc_t0; }
const bool g_no_multi_gr = env_on("STRATA_NO_MULTI_GR"); // #783 PR-g: per-token GR reads/writes and generic-T kernels again
const bool g_no_batch_kv = env_on("STRATA_NO_BATCH_KV_STEP"); // #783 PR-d: per-token K/V and indexer appends again
// STRATA_BATCH_SELF_COMMIT=1 (opt-in): a batch window whose rows are each another slot's one token keeps them itself,
// as a one-token window does (record_window): the GDN conv histories and states advance inside the window graph, and
// no commit graph runs after it. Such a window's commit is unconditional (each slot keeps its one row), and the rest
// of the commit graph only repeats what the window wrote: the indexer tails are put back and appended again from the
// same rows, the PLE histories are put back to the window's own snapshot.
// Read at the first use, not at program start: the engine sets the Windows gfx1151 parallel-request defaults (arch_defaults.cpp) in main(),
// after namespace-scope constants are initialised, so a constant here would never see them.
bool batch_self_commit_on() { static const bool v = env_on("STRATA_BATCH_SELF_COMMIT"); return v; }
#define g_batch_self_commit (batch_self_commit_on())
// STRATA_QSA_SLOTS=1 (opt-in): in a batch window, a QSA layer's block scores, top-k and attention run as one launch
// each over the window's rows (up to 8 per launch, each row reading its own slot's indexer keys and K/V) instead of
// one call per row; every row is computed by the same kernel with the same arithmetic as its own call. Not with a
// streamed KV cache (a row's block resolve could evict the blocks an earlier row of the same slot selected).
bool qsa_slots_on() { static const bool v = env_on("STRATA_QSA_SLOTS"); return v; }
#define g_qsa_slots (qsa_slots_on())
// every row of a batch window is another slot's (no slot has proposal rows)
bool one_row_per_slot(const int* rows, int S) {
for (int i = 0; i < S; ++i)
for (int j = i + 1; j < S; ++j)
if (rows[i] == rows[j]) return false;
return S >= 1;
}
bool batch_self_commits(const int* rows, int S) { return g_batch_self_commit && one_row_per_slot(rows, S); }
// The shared expert runs on its own stream, forked off and joined back per layer (`sh_fork` in record_window). The
// overlap pays off on CUDA, where it was added (cfd3b72). On HIP a cross-stream event dependency costs more than the
// shared expert takes to run, so there the fork starts off: same binary, same 48,067-token prompt, three runs each on a
// Radeon AI PRO R9700 (gfx1201, ROCm 6.4.3), the fork off decodes at 62.9 t/s against 43.4 t/s with it on. The
// profiler turns the fork off to time the stages, so a profiled run never showed that. #816 reports the same fall on a
// gfx1030 (RX 6800, Windows, 42.5 -> 56.4 t/s). STRATA_SH_STREAM overrides either default: `=1` forks, `=0` does not.
// Strix Halo (gfx1151, unified memory) is the exception: the fork pays there (+1.8% UD-IQ4_XS, +6.7% UD-Q4_K_XL decode
// at 8K, ids identical), so the gfx1151 arch table sets STRATA_SH_STREAM=1 on Linux. On Windows gfx1151 the fork is slower (0.2.7,
// Qwen IQ3_S: decode -6.4% with it, ids identical), so there the table leaves it out and this default (off on HIP) applies.
// Read on first use, after that table ran.
bool sh_stream_on() {
static const bool on = [] {
if (const char* v = std::getenv("STRATA_SH_STREAM")) return v[0] != '0';
#if defined(STRATA_USE_HIP)
return false;
#else
return true;
#endif
}();
return on;
}
// 0.2.2: the zero-doorbell window graph has one host wait, the PLE flag (layer 1's wait kernel spins until the host has read
// the window's PLE rows). Raised after the launch returns, it can deadlock HIP on the very first launch of a graph: the
// stall report of a hung first window (gfx1151, 910-token prompt, about 1 run in 6) shows the host inside hipGraphLaunch
// waiting for a runtime lock while the runtime's worker waits for the GPU, which is spinning on this flag; the raise that
// would free it sits behind the launch. So the first launch of each window graph reads the rows and raises the flag BEFORE
// the launch (the wait then passes at once); later launches keep the order that overlaps the read with layer 0 (reading
// first costs about 1.4% decode on gfx1151). Mode 0: never, 1: every launch, 2: the first launch of each graph. Default:
// 2 on HIP, 0 elsewhere (the CUDA path is unchanged). STRATA_VERIFY_EARLY_PLE_FLAG=0 / 1 / 2 forces a mode.
int early_ple_flag_mode() {
static const int mode = [] {
if (const char* v = std::getenv("STRATA_VERIFY_EARLY_PLE_FLAG")) return std::atoi(v) < 0 ? 0 : std::min(2, std::atoi(v));
#if defined(STRATA_USE_HIP)
return 2;
#else
return 0;
#endif
}();
return mode;
}
// A one-token window always keeps its token, so its graph advances the sequence state itself (the GDN conv history
// and recurrence state) and Verifier::commit launches no commit graph after it (eddoursul's fork, F7). CUDA only:
// HIP keeps the commit graph after every window (STRATA_ONE_TOKEN_COMMIT=0 does too).
// The head's hyper-connection read for the window's tokens in one launch set (CUDA; HIP: opt-in STRATA_HEAD_MIX_MULTI=1, which the
// gfx12 table sets; =0 keeps gr_read per token): bitwise the same sums.
bool head_mix_multi_enabled() {
#if defined(STRATA_USE_HIP)
static const bool on = [] {
const char* v = std::getenv("STRATA_HEAD_MIX_MULTI");
return v != nullptr && std::atoi(v) != 0;
}();
return on;
#else
static const bool on = [] {
const char* v = std::getenv("STRATA_HEAD_MIX_MULTI");
return v == nullptr || std::atoi(v) != 0;
}();
return on;
#endif
}
// 143-amdk: the wait for a host flag folded into the copy that follows it (wait_copy_i32_from_mapped,
// copy_rows_from_mapped_after): same reads, same values, one kernel node fewer each. A dependent kernel costs ~2.4 us in a
// gfx1201 graph whatever it does; measured on gfx12 only, so it is on there by default. STRATA_FUSE_WAIT=0 / 1 forces it
// off / on (HIP builds; a CUDA build never fuses).
// the Turing series (STRATA_SM75_PERF=1, sm75_series.hpp) defaults of the CUDA build's switches below, read per device
bool device_is_sm75() {
#if defined(STRATA_USE_HIP)
return false;
#else
static int per_dev[64]; // 0 unknown, 1 no, 2 yes
int dev = 0;
if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) return false;
if (!per_dev[dev]) {
int maj = 0, mnr = 0;
const bool ok = cudaDeviceGetAttribute(&maj, cudaDevAttrComputeCapabilityMajor, dev) == cudaSuccess &&
cudaDeviceGetAttribute(&mnr, cudaDevAttrComputeCapabilityMinor, dev) == cudaSuccess;
if (!ok) cudaGetLastError();
per_dev[dev] = ok && strata::sm75_default(maj, mnr) ? 2 : 1; // a Turing card with STRATA_SM75_PERF=1
}
return per_dev[dev] == 2;
#endif
}
bool fuse_wait_on() {
#if defined(STRATA_USE_HIP)
static const int env = [] {
const char* v = std::getenv("STRATA_FUSE_WAIT");
return v != nullptr ? (std::atoi(v) != 0 ? 1 : 0) : -1;
}();
if (env >= 0) return env != 0;
static int per_dev[64]; // 0 unknown, 1 no, 2 yes
int dev = 0;
if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) return false;
if (!per_dev[dev]) {
cudaDeviceProp p;
per_dev[dev] = cudaGetDeviceProperties(&p, dev) == cudaSuccess && strata::kernels::gfx_arch_is_gfx12(p.gcnArchName) ? 2 : 1;
}
return per_dev[dev] == 2;
#else
// CUDA: STRATA_FUSE_WAIT=1 folds both waits (the plan's and the CPU rows'), =2 only the plan's, =0 neither. Turing
// default 2 (RTX 2080 Ti, Flash-Next Q2_0, two runs each: +0.6..+1.4 % decode); the rows' version makes every row
// block of the copy poll the flag over PCIe and was -1.5 % there, so it stays opt-in.
static const int env = [] { const char* v = std::getenv("STRATA_FUSE_WAIT"); return v != nullptr ? std::atoi(v) : -1; }();
if (env >= 0) return env == 1 || env == 2;
return device_is_sm75();
#endif
}
// 143-amdk's rows version of the folded wait (copy_rows_from_mapped_after): HIP with fuse_wait_on, CUDA STRATA_FUSE_WAIT=1
bool fuse_rows_on() {
#if defined(STRATA_USE_HIP)
return fuse_wait_on();
#else
static const bool on = [] { const char* v = std::getenv("STRATA_FUSE_WAIT"); return v != nullptr && std::atoi(v) == 1; }();
return on;
#endif
}
// 143-amdk: STRATA_FUSE_CONVAB=1 - the GDN conv and the a/b projections in one launch. Opt-in: measured -0.3% on gfx1201 (the a/b dot chain is the longer one).
bool fuse_convab_on() {
#if defined(STRATA_USE_HIP)
static const bool on = [] { const char* v = std::getenv("STRATA_FUSE_CONVAB"); return v != nullptr && std::atoi(v) != 0; }();
return on;
#else
return false;
#endif
}
// 143-amdk: STRATA_FUSE_HITS - moe_hit_add folded into the combine (gfx12 default; =0 / 1 forces off / on)
bool fuse_hits_on() {
#if defined(STRATA_USE_HIP)
static const int env = [] { const char* v = std::getenv("STRATA_FUSE_HITS"); return v != nullptr ? (std::atoi(v) != 0 ? 1 : 0) : -1; }();
if (env >= 0) return env != 0;
static int per_dev[64]; // 0 unknown, 1 no, 2 yes
int dev = 0;
if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) return false;
if (!per_dev[dev]) {
cudaDeviceProp p;
per_dev[dev] = cudaGetDeviceProperties(&p, dev) == cudaSuccess && strata::kernels::gfx_arch_is_gfx12(p.gcnArchName) ? 2 : 1;
}
return per_dev[dev] == 2;
#else
return false;
#endif
}
bool one_token_self_commit() {
#if defined(STRATA_USE_HIP)
static const bool on = [] {
const char* v = std::getenv("STRATA_ONE_TOKEN_COMMIT"); // HIP: opt-in (=1)
return v != nullptr && std::atoi(v) != 0;
}();
return on;
#else
static const bool on = [] {
const char* v = std::getenv("STRATA_ONE_TOKEN_COMMIT");
return v == nullptr || std::atoi(v) != 0;
}();
return on;
#endif
}
bool mapped(size_t bytes, void** h, void** d) {
#if defined(STRATA_USE_HIP)
if (g_coherent) {
if (hipHostMalloc(h, bytes, hipHostMallocMapped | hipHostMallocCoherent |
(peer_portable() ? hipHostMallocPortable : 0)) != hipSuccess)
return false;
std::memset(*h, 0, bytes);
return cudaHostGetDevicePointer(d, *h, 0) == cudaSuccess;
}
#endif
if (strata::core::host_alloc_guarded(h, bytes, cudaHostAllocMapped | (peer_portable() ? cudaHostAllocPortable : 0)) != cudaSuccess) return false; // multi-GPU: portable only with a peer - the peer card writes its rows into them
std::memset(*h, 0, bytes);
return cudaHostGetDevicePointer(d, *h, 0) == cudaSuccess;
}
strata::kernels::QsaShapes shapes_of(const ModelGeometry& g) { return qsa_shapes(g); }
const WeightRef* need(const LayerView& v, const char* suffix, std::string& err) {
const WeightRef* r = v.get(suffix);
if (r == nullptr && err.empty()) err = v.name(suffix) + " is missing";
return r;
}
bool native_of(const WeightRef* w, const std::string& name, std::string& err) {
if (w == nullptr) return false;
if (w->native_data == nullptr) {
err = "verify: " + name + " is not served natively (run with --native)";
return false;
}
return true;
}
} // namespace
namespace {
std::atomic<const Verifier*> g_diag_verifier{nullptr};
void diag_active_verifier(std::FILE* f) {
if (const Verifier* v = g_diag_verifier.load()) v->diag(f);
}
// #267: every live verifier (a layer split has one per stage), for the release before the engine ends
constexpr int kLiveMax = 16;
std::atomic<Verifier*> g_live[kLiveMax];
void release_live_verifiers(std::FILE* f) {
for (auto& slot : g_live)
if (Verifier* v = slot.load()) {
const Clock::time_point t0 = Clock::now();
const bool done = v->release_gpu_waits(5000);
if (f != nullptr)
std::fprintf(f, "strata: released the verify window's GPU waits (#267): the GPU %s\n",
done ? ("finished in " + std::to_string((long long) ms_since(t0)) + " ms").c_str()
: "did not finish within 5 s");
}
if (f != nullptr) std::fflush(f);
}
// #649: the host side of STRATA_VERIFY_TRACE - a ring of the last kTraceN handshake events of every verifier
struct TraceEv {
int64_t t_ns;
const void* who;
int64_t window, step, layer, aux;
uint32_t seq, flag, a, b;
const char* what;
};
constexpr uint64_t kTraceN = 4096;
TraceEv g_trace_ring[kTraceN];
std::atomic<uint64_t> g_trace_next{0};
int64_t trace_now_ns() {
return std::chrono::duration_cast<std::chrono::nanoseconds>(Clock::now().time_since_epoch()).count();
}
std::string released_note(bool drained) {
return drained ? "; its GPU waits were released and the GPU finished (#267)"
: "; its GPU waits were released but the GPU did not finish within 5 s (#267)";
}
// #267 test hook: STRATA_TEST_VERIFY_STALL=N withholds the last layer's flag in the N-th window (1-based), so the
// GPU spins on a flag nobody raises - the bounded window wait and the release are then what ends it. Unset: never.
const int64_t g_test_stall = [] {
const char* e = std::getenv("STRATA_TEST_VERIFY_STALL");
return e != nullptr ? (int64_t) std::atoll(e) : (int64_t) 0;
}();
// The overlapped split's hand-off wait on the GPU is bounded: STRATA_SPLIT_WAIT_MS (default 30000, 0 = no bound).
// The host's own per-layer wait (20 s, #267) normally ends a stalled window first; this bound is the backstop for
// a host that is gone (a killed process must not leave a kernel spinning on its card).
const unsigned long long g_split_wait_ns = [] {
const char* e = std::getenv("STRATA_SPLIT_WAIT_MS");
return (unsigned long long) (e != nullptr ? std::atoll(e) : 30000) * 1000000ull;
}();
// test hook: STRATA_TEST_HANDOFF_DROP=N - the writing stage's N-th window (1-based) leaves its hand-off flag down, as
// if the publish were lost; the reading stage's bounded wait (or the host's) must then end the window cleanly.
const int64_t g_test_drop = [] {
const char* e = std::getenv("STRATA_TEST_HANDOFF_DROP");
return e != nullptr ? (int64_t) std::atoll(e) : (int64_t) 0;
}();
} // namespace
bool Verifier::release_gpu_waits(int timeout_ms) {
released_.store(true);
trace_ev("RELEASE", -1, -1, timeout_ms);
// the words the spin kernels read (wait_flag_ge, wait_flag_ge_or) are mapped host memory, so a store here
// reaches them with no API call; UINT32_MAX is past every ring. (E-6's skip words are device memory, but
// wait_flag_ge_or also returns on its flag.) A host function raising flag B later only raises.
for (uint32_t* p : {h_flag_, h_flagA_, h_flagB_, hflag_in_h_}) // + an overlapped split's hand-off wait
if (p != nullptr) *(volatile uint32_t*) p = UINT32_MAX;
std::atomic_thread_fence(std::memory_order_seq_cst);
strata_store_fence();
const OnDevice on_device(device_);
const Clock::time_point t0 = Clock::now();
for (cudaStream_t s : {cs_, copy_}) {
if (s == nullptr) continue;
while (cudaStreamQuery(s) == cudaErrorNotReady) {
if (ms_since(t0) > timeout_ms) {
trace_ev("RELEASE-NOT-DRAINED", -1, -1, (int64_t) ms_since(t0));
return false;
}
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
}
trace_ev("RELEASE-DRAINED", -1, -1, (int64_t) ms_since(t0)); // aux: ms the GPU took to finish once released
return true;
}
void Verifier::trace_ev(const char* what, int64_t step, int64_t layer, int64_t aux) const {
if (!g_trace) return;
auto rd = [](const uint32_t* p) { return p ? *(const volatile uint32_t*) p : 0u; };
TraceEv& e = g_trace_ring[g_trace_next.fetch_add(1) % kTraceN];
e = {trace_now_ns(), this, windows, step, layer, aux, rd(h_seq_), rd(h_flag_), rd(h_flagA_), rd(h_flagB_), what};
}
void Verifier::trace_dump(std::FILE* f) const {
if (!g_trace || f == nullptr) return;
static const char* names[kProfPer] = {"pre", "hc-read0", "qkv gemv", "conv", "ab", "z", "rec", "kv-idx",
"k/v rope", "kv append", "q", "scores+topk", "kv-resolve", "attention",
"gate", "", "out-proj", "router+ring", "shared", "waitA", "VRAM hits", "waitB",
"PCIe grp", "waitCPU", "combine", "", "head", "", "", "", "", "", ""};
const uint64_t end = g_trace_next.load();
const uint64_t n = end < 160 ? end : 160;
std::fprintf(f, "strata verify trace (#649): the last %llu handshake events (host clock, us before the last; "
"words: seq = GPU rang, flag = CPU served, A = plan, B = copies)\n", (unsigned long long) n);
const int64_t t_last = n ? g_trace_ring[(end - 1) % kTraceN].t_ns : 0;
for (uint64_t i = end - n; i < end; ++i) {
const TraceEv& e = g_trace_ring[i % kTraceN];
if (e.what == nullptr) continue;
std::fprintf(f, " %10.1f %-20s v%p window %lld step %lld layer %lld aux %lld | seq %u flag %u A %u B %u\n",
(double) (t_last - e.t_ns) / 1000.0, e.what, e.who, (long long) e.window, (long long) e.step,
(long long) e.layer, (long long) e.aux, e.seq, e.flag, e.a, e.b);
}
if (trace_h_ == nullptr || g_ == nullptr) return;
// the breadcrumbs: every stamp point the GPU passed in this window (ns of the GPU clock after the window's first)
unsigned long long t0 = ~0ull;
for (size_t i = 0; i < trace_n_; ++i) {
const unsigned long long t = *(const volatile unsigned long long*) (trace_h_ + i);
if (t != 0 && t < t0) t0 = t;
}
if (t0 == ~0ull) {
std::fprintf(f, "strata verify trace: no GPU breadcrumb in this window (the GPU never started it)\n");
return;
}
int64_t last_l = -1;
for (int64_t l = 0; l <= g_->n_layers; ++l)
for (int i = 0; i < kProfPer; ++i)
for (int grp = 0; grp < 2; ++grp)
if (trace_h_[(size_t) ((l * kProfPer + i) * 2 + grp)] != 0) last_l = l;
std::fprintf(f, "strata verify trace: GPU breadcrumbs (us after the window's first), the GPU got as far as layer "
"%lld:\n", (long long) last_l);
for (int64_t l = std::max<int64_t>(0, last_l - 2); l <= std::min<int64_t>(g_->n_layers, last_l + 1); ++l)
for (int grp = 0; grp < 2; ++grp) {
std::string line;
char b[64];
for (int i = 0; i < kProfPer; ++i) {
const unsigned long long t = trace_h_[(size_t) ((l * kProfPer + i) * 2 + grp)];
if (t == 0) continue;
std::snprintf(b, sizeof b, " %s(%d)=%.1f", names[i], i, (double) (t - t0) / 1000.0);
line += b;
}
if (!line.empty())
std::fprintf(f, " layer %lld group %d:%s\n", (long long) l, grp, line.c_str());
}
std::fflush(f);
}
void Verifier::diag(std::FILE* f) const {
auto rd = [](const uint32_t* p) { return p ? *(const volatile uint32_t*) p : 0u; };
// #251: outside a verify stage these are the LAST window's numbers (it finished), not the stalled work's
const char* where = progress().where.load();
const bool current = where != nullptr && std::strncmp(where, "verify window", 13) == 0;
std::fprintf(f, " verify window%s: %d tokens at position %lld, host at layer step %u; the GPU rang %u; flags: "
"served %u, plan (A) %u, copies (B) %u\n", current ? "" : " (last window, not the current stage)",
last_t_, (long long) last_pos0_, cur_layer_ + 1, rd(h_seq_), rd(h_flag_), rd(h_flagA_), rd(h_flagB_));
trace_dump(f); // #649: STRATA_VERIFY_TRACE=1 only
}
Verifier::~Verifier() {
#if defined(STRATA_GPU_METAL)
strata::metal_engine::window_destroy(metal_);
metal_ = nullptr;
#endif
const Verifier* self = this;
g_diag_verifier.compare_exchange_strong(self, nullptr);
for (auto& slot : g_live) {
Verifier* me = this;
slot.compare_exchange_strong(me, nullptr);
}
if (cs_) cudaStreamSynchronize(cs_);
if (sh_cs_) cudaStreamSynchronize(sh_cs_);
for (auto& row : exec_)
for (auto& e : row)
if (e) cudaGraphExecDestroy(e);
for (auto& row : exec_nr_)
for (auto& e : row)
if (e) cudaGraphExecDestroy(e);
if (commit_exec_) cudaGraphExecDestroy(commit_exec_);
for (auto& kv : exec_bm_)
if (kv.second) cudaGraphExecDestroy(kv.second);
for (auto& kv : commit_bm_)
if (kv.second) cudaGraphExecDestroy(kv.second);
if (arena_b_) cudaFree(arena_b_);
if (h_commitb_) cudaFreeHost(h_commitb_);
for (auto* m : {&save_bm_, &dcommit_bm_})
for (auto& kv : *m)
if (kv.second) cudaGraphExecDestroy(kv.second);
if (dc_arena_) cudaFree(dc_arena_);
if (h_commitd_) cudaFreeHost(h_commitd_);
if (qcnt_) cudaFree(qcnt_);
if (d_spec_) cudaFree(d_spec_);
if (tap_file_) std::fclose(tap_file_);
#if !defined(STRATA_GPU_METAL) // (on Metal tap_dev_ is the window's unified-memory buffer, not an allocation of this object)
if (tap_dev_) cudaFree(tap_dev_);
#endif
if (tap_scratch_) cudaFree(tap_scratch_);
if (h_tap_) cudaFreeHost(h_tap_);
if (logit_bias_device_) cudaFree(logit_bias_device_);
for (float* b : slot_bias_dev_) if (b) cudaFree(b);
if (slot_hist_d_) cudaFree(slot_hist_d_);
if (cs_ && cs_ != ext_stream_) cudaStreamDestroy(cs_); // set_stream: the stage's stream, shared, not ours
if (sh_cs_) cudaStreamDestroy(sh_cs_);
if (copy_) { cudaStreamSynchronize(copy_); cudaStreamDestroy(copy_); }
if (side_) cudaStreamDestroy(side_);
if (side2_) cudaStreamDestroy(side2_);
for (cudaEvent_t e : {mfork_, mjoin_, pfork_, pjoin_})
if (e) cudaEventDestroy(e);
if (commit_done_) cudaEventDestroy(commit_done_);
if (ev_done_) cudaEventDestroy(ev_done_);
if (ev_commit_) cudaEventDestroy(ev_commit_);
if (prof_pin_) cudaFreeHost(prof_pin_);
if (ev_fork_) cudaEventDestroy(ev_fork_);
if (ev_join_) cudaEventDestroy(ev_join_);
for (cudaStream_t s : df_side_)
if (s) cudaStreamDestroy(s);
if (df_fork_) cudaEventDestroy(df_fork_);
for (cudaEvent_t e : df_join_)
if (e) cudaEventDestroy(e);
if (arena_) cudaFree(arena_);
if (hcount_d_) cudaFree(hcount_d_);
void* hosts[] = {h_tok_, h_step_, h_pos_, h_commit_, h_ple_, h_out_, h_x_, h_ids_, h_w_, h_seq_, h_flag_, h_ymiss_,
h_flagA_, h_plan_, h_flagB_, h_plan_err_, h_nf_, herr_h_, hdrop_h_, h_bal_};
for (void* h : hosts)
if (h) cudaFreeHost(h);
}
int Verifier::tap_total() const {
int n = 0;
if (g_ == nullptr) return 0;
for (int l : tap_req_) if (l >= 0 && l < g_->n_layers - 1) ++n;
return n;
}
bool Verifier::tapping_chain() const {
if (g_ == nullptr || tap_req_.empty()) return false;
int have = 0;
for (const Verifier* v = this; v != nullptr; v = v->next_) {
have += (int) v->tap_layers_.size();
if (v->tap_layers_.size() > 0 && !v->tap_on_) return false;
if (v->le_ >= g_->n_layers) break;
}
return have == tap_total();
}
bool Verifier::gather_taps_host(float* dst, int row0, int rows, std::string& err) {
const int64_t N = g_->n_embd;
const int nt_all = tap_total();
for (Verifier* v = this; v != nullptr; v = v->next_) {
if (!v->tap_layers_.empty() && v->tap_on_) {
const OnDevice on_stage(v->device_);
if (v->tap_cs_ == nullptr &&
(cudaStreamCreateWithFlags(&v->tap_cs_, cudaStreamNonBlocking) != cudaSuccess ||
cudaEventCreateWithFlags(&v->tap_ev_, cudaEventDisableTiming) != cudaSuccess)) {
err = "verify: the tap gather stream could not be created";
return false;
}
int slot0 = 0;
for (int l : tap_req_) if (l >= 0 && l < g_->n_layers - 1 && l < v->lb_) ++slot0;
const int64_t nv = (int64_t) v->tap_layers_.size();
for (int r = 0; r < rows; ++r) {
const cudaError_t ce = cudaMemcpyAsync(dst + ((size_t) r * (size_t) nt_all + (size_t) slot0) * (size_t) N,
v->tap_dev_ + (size_t) (row0 + r) * (size_t) (nv * N), (size_t) (nv * N) * 4,
cudaMemcpyDeviceToHost, v->tap_cs_);
if (ce != cudaSuccess) { err = std::string("verify: the tap gather to the host: ") + cudaGetErrorString(ce); return false; }
}
if (cudaStreamSynchronize(v->tap_cs_) != cudaSuccess) { err = "verify: the tap gather to the host did not finish"; return false; }
}
if (v->le_ >= g_->n_layers) break;
}
return true;
}
bool Verifier::gather_taps(float* landing, int landing_device, int row0, int rows, int dst_row0, cudaStream_t wait_stream, std::string& err) {
const int64_t N = g_->n_embd;
const int nt_all = tap_total();
for (Verifier* v = this; v != nullptr; v = v->next_) {
if (!v->tap_layers_.empty() && v->tap_on_) {
const OnDevice on_stage(v->device_);
if (v->tap_cs_ == nullptr &&
(cudaStreamCreateWithFlags(&v->tap_cs_, cudaStreamNonBlocking) != cudaSuccess ||
cudaEventCreateWithFlags(&v->tap_ev_, cudaEventDisableTiming) != cudaSuccess)) {
err = "verify: the tap gather stream could not be created";
return false;
}
// this stage's first tap among all of them: the requested layers below its first layer
int slot0 = 0;
for (int l : tap_req_) if (l >= 0 && l < g_->n_layers - 1 && l < v->lb_) ++slot0;
const int64_t nv = (int64_t) v->tap_layers_.size();
for (int r = 0; r < rows; ++r) {
const float* src = v->tap_dev_ + (size_t) (row0 + r) * (size_t) (nv * N);
float* dst = landing + ((size_t) (dst_row0 + r) * (size_t) nt_all + (size_t) slot0) * (size_t) N;
const cudaError_t ce = v->device_ == landing_device
? cudaMemcpyAsync(dst, src, (size_t) (nv * N) * 4, cudaMemcpyDeviceToDevice, v->tap_cs_)
: cudaMemcpyPeerAsync(dst, landing_device, src, v->device_, (size_t) (nv * N) * 4, v->tap_cs_);
if (ce != cudaSuccess) { err = std::string("verify: the tap gather copy: ") + cudaGetErrorString(ce); return false; }
}
if (cudaEventRecord(v->tap_ev_, v->tap_cs_) != cudaSuccess) { err = "verify: the tap gather event"; return false; }
const OnDevice on_dst(landing_device);
if (cudaStreamWaitEvent(wait_stream, v->tap_ev_, 0) != cudaSuccess) { err = "verify: the drafter stream cannot wait on a stage's taps"; return false; }
}
if (v->le_ >= g_->n_layers) break;
}
return true;
}
// STRATA_TAP_FILE: one record per row of the window: int32 position, int32 input token, then n_taps x n_embd floats
void Verifier::tap_write(int T, const int32_t* tokens, int64_t pos0) {
if (tap_file_ == nullptr) return;
const size_t per = tap_layers_.size() * (size_t) g_->n_embd;
for (int t = 0; t < T; ++t) {
const int32_t hdr[2] = {(int32_t) (pos0 + t), tokens[t]};
std::fwrite(hdr, sizeof hdr, 1, tap_file_);
std::fwrite(h_tap_ + (size_t) t * per, sizeof(float), per, tap_file_);
}
std::fflush(tap_file_);
}
bool Verifier::set_logit_bias(const std::vector<float>& bias, std::string& err) {
if (next_ && !next_->set_logit_bias(bias, err)) return false;
if (le_ >= 0 && le_ < g_->n_layers) return true; // (the Metal window never sets le_: -1 = the last stage)
const OnDevice on_device(device_);
if (!bias.empty() && bias.size() != (size_t) n_vocab_) {
err = "logit_bias vocabulary size mismatch"; return false;
}
if (bias != logit_bias_host_ && !bias.empty()) {
const size_t bytes = bias.size() * sizeof(float);
if ((!logit_bias_device_ && cudaMalloc((void**) &logit_bias_device_, bytes) != cudaSuccess) ||
cudaMemcpy(logit_bias_device_, bias.data(), bytes, cudaMemcpyHostToDevice) != cudaSuccess) {
err = "cannot upload logit_bias"; return false;
}
}
logit_bias_host_ = bias;
sampling_.logit_bias = bias.empty() ? nullptr : logit_bias_device_;
return true;
}
bool Verifier::init(const WeightTable& wt, const ModelGeometry& g, SessionState& ss, const VerifyHits& hits,
const NativeHead* head, int max_t, std::string& err) {
g_diag_verifier.store(this);
diag_verify_fn().store(&diag_active_verifier);
for (auto& slot : g_live) {
Verifier* none = nullptr;
if (slot.load() == this || slot.compare_exchange_strong(none, this)) break;
}
release_gpu_fn().store(&release_live_verifiers);
cudaGetDevice(&device_); // a layer split's stage on another GPU: its streams, graphs and buffers live there
rr_stats_ = route_resident_cfg().stats_on(device_); // STRATA_ROUTE_RESIDENT: this GPU's counters, outside graph capture
strata::kernels::fused_gr_check(); // once per card: which bitwise-equal hyper-connection read runs there
strata::kernels::fused_gr_persist_init(); // opt-in STRATA_HC_PERSIST=1 (HIP)
wt_ = &wt;
g_ = &g;
ss_ = &ss;
hits_ = hits;
head_ = head;
max_t_ = max_t;
sampling_.greedy = true; // a fresh verifier samples greedily until set_sampling says otherwise
sampling_.temperature = 0.0f;
#if defined(STRATA_GPU_METAL)
if (metal_ == nullptr) metal_ = strata::metal_engine::window_create();
if (!strata::metal_engine::window_init(metal_, g, ss, max_t, ss.qsa_states[ss.qsa_primary()].max_cells, &n_vocab_, err)) return false;
if (!tap_req_.empty()) { // DFlash2: the Metal window writes the taps itself (metal/src/engine/dflash2.inc); tap_dev() is its unified-memory buffer
const float* tp = nullptr;
if (!strata::metal_engine::window_taps(metal_, tap_req_, &tp, err)) return false;
tap_layers_ = tap_req_;
tap_dev_ = const_cast<float*>(tp);
tap_on_ = true;
}
return true;
#endif
// a window past kVerifyMaxT tokens runs as two token groups of at most kVerifyMaxT (record_window): the CPU experts
// see one group at a time (and take a wider group as jobs of at most cpu::MAXT tokens)
if (max_t < 2 || max_t > strata::kernels::kVerifyLongT) {
err = "verify: the window must hold 2.." + std::to_string(strata::kernels::kVerifyLongT) + " tokens";
return false;
}
if (hits.d_res == nullptr || hits.cache_base == nullptr || hits.blob <= 0) {
err = "verify: needs the profile-filled VRAM expert tier (--expert-profile and --expert-cache); with "
"--expert-cache auto, no VRAM was left for it - the 'no VRAM is left for the expert cache' line above "
"says how much is short and what makes room (a smaller --max-context, --kv q4_0, setup --draft-vocab en, "
"images on the CPU)";
return false;
}
std::string why;
if (!layer_verify_compatible(why)) {
err = "verify: " + why + " (the verify window reproduces the default native decode path)";
return false;
}
if (!strata::kernels::fused_gr_supported(g.n_embd, g.hc, g.hc_lr) || ss.k != (int) strata::core::kCompiledGeometry.n_expert_used || g.ssm_state_size != 128 ||
g.ssm_d_conv != 4) {
err = "verify: geometry differs from the artifact's";
return false;
}
if (le_ < 0) le_ = g.n_layers;
if (lb_ < 0 || lb_ >= le_ || le_ > g.n_layers || (lb_ > 0 && hand_in_ == nullptr) ||
(le_ < g.n_layers && hand_out_ == nullptr)) {
err = "verify: the stage's layer range or its hand-off buffers are wrong";
return false;
}
const WeightRef* wo = wt.find("output.weight");
if (wo == nullptr) { err = "verify: output.weight is missing"; return false; }
n_vocab_ = wo->ne1;
const strata::kernels::QsaShapes s = shapes_of(g);
cap_ = strata::kernels::qsa_selection_width(strata::kernels::kTopkMaxCells, s);
max_blocks_ = ss.qsa_states[ss.qsa_primary()].max_cells / s.idx_block + 2;
attn_scratch_floats_ = (int64_t) strata::kernels::qsa_decode_attn_scratch_floats(cap_, s);
const uint64_t T = (uint64_t) max_t, N = (uint64_t) g.n_embd, HC = (uint64_t) g.hc, K = (uint64_t) ss.k;
const uint64_t C = (uint64_t) g.ssm_conv_channels, ZV = (uint64_t) g.ssm_value_dim, HV = (uint64_t) g.ssm_v_heads;
const uint64_t NH = (uint64_t) g.n_head, HD = (uint64_t) g.head_dim, NKV = (uint64_t) g.n_head_kv;
const uint64_t IQ = (uint64_t) g.idx_q_heads, ID = (uint64_t) g.idx_key_dim;
const uint64_t nG = (uint64_t) g.n_gdn_layers(), nQ = (uint64_t) g.n_qsa_layers();
const uint64_t HS = (uint64_t) strata::kernels::NG_HIST * strata::kernels::NG_HC_DIM;
const uint64_t TS = (uint64_t) (s.idx_block - 1) * ID;
const int max_in = (int) std::max<uint64_t>(std::max<uint64_t>(N, ZV), NH * HD);
// ---- mapped staging
bool ok = mapped(T * 4, (void**) &h_tok_, (void**) &m_tok_) &&
mapped(T * strata::kernels::kStepCount * 4, (void**) &h_step_, (void**) &m_step_) &&
mapped(T * (NH + NKV + IQ) * 4, (void**) &h_pos_, (void**) &m_pos_) &&
mapped((2 + T) * 4 + 16, (void**) &h_commit_, (void**) &m_commit_) &&
mapped(T * N * 4, (void**) &h_ple_, (void**) &m_ple_) &&
mapped(T * 4 + 16, (void**) &h_out_, (void**) &m_out_) &&
mapped((size_t) strata::kernels::kVerifyLongT * strata::kernels::kNonfiniteBlocks * 4, (void**) &h_nf_,
(void**) &m_nf_) &&
mapped(T * N * 4, (void**) &h_x_, (void**) &m_x_) &&
mapped(T * K * 4, (void**) &h_ids_, (void**) &m_ids_) &&
mapped(T * K * 4, (void**) &h_w_, (void**) &m_w_) &&
mapped(64, (void**) &h_seq_, (void**) &m_seq_) &&
mapped(64, (void**) &h_flag_, (void**) &m_flag_) &&
mapped(64, (void**) &h_flagA_, (void**) &m_flagA_) &&
mapped(64, (void**) &h_flagB_, (void**) &m_flagB_) &&
mapped(64, (void**) &h_plan_err_, (void**) &m_plan_err_) &&
mapped(T * K * N * 4, (void**) &h_ymiss_, (void**) &m_ymiss_);
if (!ok) { err = "verify: mapped staging allocation failed " + strata::core::pin_exhausted_hint(); return false; }
// DFlash2 taps: set_taps (the drafter) or STRATA_TAP_FILE (the research dump); off, and nothing is allocated or captured, otherwise
const char* tap_path = std::getenv("STRATA_TAP_FILE");
if (tap_path != nullptr && tap_path[0] == '\0') tap_path = nullptr;
// A layer split's stage taps the requested layers inside its own range [lb_, le_) into its own buffer [max_t][its taps][n_embd];
// gather_taps() lands every stage's rows on the drafter's card. The research dump (STRATA_TAP_FILE) needs the whole model in one verifier.
const bool tap_whole = lb_ == 0 && le_ == g.n_layers;
if (!tap_whole) tap_path = nullptr;
if (tap_path != nullptr || !tap_req_.empty()) {
tap_layers_.clear();
if (tap_path == nullptr) {
for (int l : tap_req_) if (l >= lb_ && l < le_ && l < g.n_layers - 1) tap_layers_.push_back(l);
} else {
const char* tl = std::getenv("STRATA_TAP_LAYERS");
std::string list = tl != nullptr && tl[0] != '\0' ? tl : "5,15,25,35,45";
for (size_t i = 0; i < list.size();) {
const size_t j = list.find(',', i);
const int l = std::atoi(list.substr(i, j == std::string::npos ? std::string::npos : j - i).c_str());
if (l >= 0 && l < g.n_layers - 1) tap_layers_.push_back(l);
if (j == std::string::npos) break;
i = j + 1;
}
}
tap_slot_.assign((size_t) g.n_layers, -1);