Repository navigation
Expand file tree
/
Copy pathmtp.cpp
More file actions
2054 lines (1991 loc) · 107 KB
/
Copy pathmtp.cpp
File metadata and controls
2054 lines (1991 loc) · 107 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/mtp.cpp - see include/strata/core/mtp.hpp.
#include "strata/core/mtp.hpp"
#include "strata/core/pin_budget.hpp"
#include "strata/kernels/qsa_prompt_attn.hpp"
#include "strata/core/coupled_draft.hpp"
#include "strata/core/spec_prob.hpp"
#include "strata/core/on_device.hpp"
#include "strata/core/progress.hpp"
#include "strata/core/native_head.hpp"
#include "strata/core/peer_experts.hpp"
#include "strata/platform/memory.hpp"
#include "strata/kernels/bf16_gemv.hpp"
#include "strata/kernels/cpu/expert.hpp"
#include "strata/kernels/elementwise.hpp"
#include "strata/kernels/fused_gr.hpp"
#include "strata/kernels/gr.hpp"
#include "strata/kernels/kv_q4.hpp"
#include "strata/kernels/kv_q8.hpp"
#include "strata/kernels/native_moe.hpp"
#include "strata/kernels/native_mmvq.hpp"
#include "strata/kernels/native_qsa.hpp"
#include "strata/kernels/native_rope.hpp"
#include "strata/kernels/native_router.hpp"
#include "strata/kernels/qsa.hpp"
#include "strata/kernels/qsa_decode_attn.hpp"
#include "strata/kernels/quantize_act.hpp"
#include "strata/kernels/rope.hpp"
#include "strata/kernels/router_top10.hpp"
#include "strata/kernels/s2_expert_grouped.hpp"
#include "strata/kernels/sampler.hpp"
#include "strata/kernels/shared_expert.hpp"
#include "strata/kernels/verify_kernels.hpp"
#include "strata/kernels/ngram.hpp"
#include "strata/kernels/gfx_arch.hpp"
#include <algorithm>
#include <atomic>
#include <chrono>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <exception>
#include <fstream>
#include <sstream>
#include <vector>
#include "strata/platform/cpu_relax.hpp"
#ifdef STRATA_NATIVE_EXPERTS
#include "ggml.h" // --mtp-q4: the head rows' and projections' formats, dequantized and requantized at load
#endif
#if defined(STRATA_GPU_METAL)
// The Metal backend's MTP drafter (metal/src/engine/window.cpp, beside the decode window it reads): load, prefill and
// draft hand over to it; bind has nothing to bind there.
namespace strata::metal_engine {
bool mtp_load(const std::string& rt_dir, int max_t, std::string& err);
void mtp_bind_state(strata::core::QsaState& st);
bool mtp_prefill(const int32_t* next_tokens, int64_t n, int64_t cell0, std::string& err);
bool mtp_draft(int T, const int32_t* tokens, int64_t p, int a, int max_steps, int32_t* drafts, float* probs, float min_p,
int* n_drafts, std::string& err);
} // namespace strata::metal_engine
#endif
namespace strata::core {
namespace {
constexpr float EPS = 1e-6f;
// #783 PR-i: STRATA_MTP_CATCHUP_ALL=1 catches the drafter's K/V up for the whole verified window, rejected rows included
bool mtp_catchup_all() {
static const bool on = [] {
const char* v = std::getenv("STRATA_MTP_CATCHUP_ALL");
return v != nullptr && v[0] != '\0' && v[0] != '0';
}();
return on;
}
// STRATA_MTP_Q8_SM60=1 (opt-in, with STRATA_Q8_SM60=1): the drafter's own Q8_0 matrices (the draft head's subset,
// the projections) run on the Pascal GEMV too (the drafts differ in rounding only: the Pascal kernel sums in another
// order; the replies do not depend on the drafts)
bool mtp_q8_sm60() {
static const bool on = [] {
const char* v = std::getenv("STRATA_MTP_Q8_SM60");
return v != nullptr && v[0] == '1';
}();
return on;
}
constexpr int GGML_Q8_0 = 8;
constexpr int GGML_Q4_0 = 2;
using Clock = std::chrono::steady_clock;
double ms_since(Clock::time_point t) { return std::chrono::duration<double, std::milli>(Clock::now() - t).count(); }
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;
}
};
bool mapped(size_t bytes, void** h, void** d) {
if (strata::core::host_alloc_guarded(h, bytes, cudaHostAllocMapped | (peer_portable() ? cudaHostAllocPortable : 0)) != cudaSuccess) return false;
std::memset(*h, 0, bytes);
return cudaHostGetDevicePointer(d, *h, 0) == cudaSuccess;
}
strata::kernels::QsaShapes shapes_of(const ModelGeometry& g) { return qsa_shapes(g); }
// 64-bit seek/tell on a `FILE*`: `fseek`/`ftell` take a 32-bit `long` on Windows and would wrap past 2 GiB.
#if defined(_WIN32)
#define STRATA_FILE_SEEK64(f, o, w) _fseeki64((f), (long long) (o), (w))
#define STRATA_FILE_TELL64(f) _ftelli64(f)
#else
#define STRATA_FILE_SEEK64(f, o, w) fseeko((f), (off_t) (o), (w))
#define STRATA_FILE_TELL64(f) ftello(f)
#endif
bool read_file(const std::string& path, std::vector<uint8_t>& out) {
// Loader fix (0.1.15+loaderfix.2): `ifstream::read` reaches the disk as 4095-byte reads on MSVC - the same
// split `load_experts_ranges` had - so the drafter's 111 MiB dense blob paid 4 KiB per operation on a cold
// start. `fread` passes a request bigger than the stream buffer straight to `ReadFile()`.
FILE* f = std::fopen(path.c_str(), "rb");
if (f == nullptr) return false;
// A `FILE*` has no destructor and the short-read path below returns early: the guard closes on every path.
struct Closer {
FILE* f;
~Closer() { if (f != nullptr) std::fclose(f); }
} closer{f};
if (STRATA_FILE_SEEK64(f, 0, SEEK_END) != 0) return false;
const long long n = (long long) STRATA_FILE_TELL64(f);
if (n < 0 || STRATA_FILE_SEEK64(f, 0, SEEK_SET) != 0) return false;
#if !defined(_WIN32)
strata::platform::advise_willneed(fileno(f), 0, (uint64_t) n);
#endif
out.resize((size_t) n);
return n == 0 || std::fread(out.data(), 1, (size_t) n, f) == (size_t) n;
}
} // namespace
MtpDrafter::~MtpDrafter() {
if (cs_) cudaStreamSynchronize(cs_);
for (auto& e : prefill_exec_) if (e) cudaGraphExecDestroy(e);
for (auto& e : prefill_dev_exec_) if (e) cudaGraphExecDestroy(e);
if (pf_dev_) cudaFree(pf_dev_);
if (dense4_) cudaFree(dense4_);
for (auto& e : round_exec_) if (e) cudaGraphExecDestroy(e);
for (auto& e : step_exec_) if (e) cudaGraphExecDestroy(e);
for (auto& e : round_exec_c_) if (e) cudaGraphExecDestroy(e);
for (auto& e : step_exec_c_) if (e) cudaGraphExecDestroy(e);
if (cparams_) cudaFree(cparams_);
if (cring_) cudaFree(cring_);
if (dinv_) cudaFree(dinv_);
if (cscratch_) cudaFree(cscratch_);
if (h_cparams_) cudaFreeHost(h_cparams_);
if (h_chist_) cudaFreeHost(h_chist_);
if (h_q_) cudaFreeHost(h_q_);
if (cs_) cudaStreamDestroy(cs_);
if (side_) cudaStreamDestroy(side_);
if (sh_fork_) cudaEventDestroy(sh_fork_);
if (sh_join_) cudaEventDestroy(sh_join_);
if (owns_weights_ && dense_) {
for (const auto& t : tensors_) // the STRATA_MTP_Q8_SM60 registrations first (a no-op for the rest)
if (t.kind == "q8_0") strata::kernels::native_q8_0_sm60_release(dense_ + t.off);
cudaFree(dense_);
}
if (owns_weights_ && experts_) cudaFree(experts_);
if (experts_host_) cudaFreeHost(experts_host_); // the prompt room's host snapshot (the device copy never left)
if (state_arena_) cudaFree(state_arena_);
if (arena_) cudaFree(arena_);
if (head_logits_) cudaFree(head_logits_);
if (owns_draft_head_ && dhead_) {
strata::kernels::native_q6_k_unpack(dhead_);
strata::kernels::native_q8_0_sm60_release(dhead_);
cudaFree(dhead_);
}
if (owns_draft_head_ && dvocab_) cudaFree(dvocab_);
if (ev_chain_) cudaEventDestroy(ev_chain_);
for (cudaEvent_t e : ev_step_) if (e) cudaEventDestroy(e);
void* hosts[] = {h_tok_, h_step_, h_pos_, h_row_, h_out_, h_prob_, h_force_, h_floor_};
for (void* h : hosts) if (h) cudaFreeHost(h);
}
const float* MtpDrafter::f32(const char* name) const {
for (const auto& t : tensors_) if (t.name == name && t.kind == "f32") return (const float*) (dense_ + t.off);
return nullptr;
}
const uint16_t* MtpDrafter::bf16(const char* name) const {
for (const auto& t : tensors_) if (t.name == name && t.kind == "bf16") return (const uint16_t*) (dense_ + t.off);
return nullptr;
}
const void* MtpDrafter::q8(const char* name) const {
for (const auto& t : tensors_) if (t.name == name && t.kind == "q8_0") return dense_ + t.off;
return nullptr;
}
const void* MtpDrafter::wq(const char* name, int& type) const {
if (dense4_ != nullptr)
for (const auto& e : q4_off_)
if (e.first == name) { type = GGML_Q4_0; return dense4_ + e.second; }
type = GGML_Q8_0;
return q8(name);
}
// --mtp-q4: every Q8_0 tensor of dense.bin as Q4_0 (ggml's reference quantizer), in one device buffer
bool MtpDrafter::make_q4_dense(const std::vector<uint8_t>& blob, std::string& err) {
#ifdef STRATA_NATIVE_EXPERTS
uint64_t total = 0;
std::vector<std::pair<const Tensor*, uint64_t>> plan;
for (const auto& t : tensors_) {
if (t.kind != "q8_0" || t.cols % 32 != 0) continue;
plan.push_back({&t, total});
total += ((uint64_t) t.rows * (uint64_t) (t.cols / 32) * 18 + 255) & ~255ull;
}
std::vector<uint8_t> host((size_t) total);
std::vector<float> row;
const auto* q8t = ggml_get_type_traits(GGML_TYPE_Q8_0);
for (const auto& [t, off] : plan) {
row.resize((size_t) t->cols);
const uint64_t in_row = (uint64_t) (t->cols / 32) * 34, out_row = (uint64_t) (t->cols / 32) * 18;
for (int64_t r = 0; r < t->rows; ++r) {
q8t->to_float(blob.data() + t->off + (uint64_t) r * in_row, row.data(), t->cols);
ggml_quantize_chunk(GGML_TYPE_Q4_0, row.data(), host.data() + off + (uint64_t) r * out_row, 0, 1, t->cols,
nullptr);
}
q4_off_.push_back({t->name, off});
}
if (cudaMalloc((void**) &dense4_, (size_t) total) != cudaSuccess) { err = "mtp: the Q4_0 projections do not fit"; return false; }
cudaMemcpy(dense4_, host.data(), (size_t) total, cudaMemcpyHostToDevice);
vram_ += total;
std::fprintf(stderr, "strata mtp: --mtp-q4: %zu projections as Q4_0 (%.1f MiB)\n", plan.size(), (double) total / 1048576.0);
return true;
#else
(void) blob;
err = "mtp: --mtp-q4 needs a build with native experts (ggml)";
return false;
#endif
}
// --mtp-q4: the draft head's subset rows as Q4_0 (dequantized from the main head's format)
bool MtpDrafter::make_q4_head(std::string& err) {
#ifdef STRATA_NATIVE_EXPERTS
const int64_t N = g_->n_embd;
const auto* tt = ggml_get_type_traits((ggml_type) head_->type());
if (tt == nullptr || tt->to_float == nullptr || N % 32 != 0) { err = "mtp: --mtp-q4 cannot read the head's format"; return false; }
const size_t in_row = head_->row_bytes(), out_row = (size_t) (N / 32) * 18;
std::vector<uint8_t> src((size_t) n_dvocab_ * in_row), dst((size_t) n_dvocab_ * out_row);
if (cudaMemcpy(src.data(), dhead_, src.size(), cudaMemcpyDeviceToHost) != cudaSuccess) { err = "mtp: reading the draft head"; return false; }
std::vector<float> row((size_t) N);
for (int64_t r = 0; r < n_dvocab_; ++r) {
tt->to_float(src.data() + (size_t) r * in_row, row.data(), N);
ggml_quantize_chunk(GGML_TYPE_Q4_0, row.data(), dst.data() + (size_t) r * out_row, 0, 1, N, nullptr);
}
// the Q4_0 rows replace the subset in place (they are smaller)
if (cudaMemcpy(dhead_, dst.data(), dst.size(), cudaMemcpyHostToDevice) != cudaSuccess) { err = "mtp: writing the draft head"; return false; }
dhead_type_ = GGML_Q4_0;
std::fprintf(stderr, "strata mtp: --mtp-q4: draft head over %lld tokens as Q4_0 (%.1f MiB read per step, was %.1f)\n",
(long long) n_dvocab_, (double) dst.size() / 1048576.0, (double) src.size() / 1048576.0);
return true;
#else
err = "mtp: --mtp-q4 needs a build with native experts (ggml)";
return false;
#endif
}
bool MtpDrafter::load(const std::string& rt_dir, const ModelGeometry& g, SessionState& ss, int max_t, std::string& err,
int64_t window, const MtpDrafter* shared) {
#if defined(STRATA_GPU_METAL)
(void) window; (void) shared;
g_ = &g;
ss_ = &ss;
max_t_ = max_t;
if (!strata::metal_engine::mtp_load(rt_dir, max_t, err)) return false;
strata::metal_engine::mtp_bind_state(st_); // the parked conversation's draft K/V is the window's own buffers
return true;
#endif
cudaGetDevice(&device_); // a layer split's last stage on another GPU: the drafter lives there
g_ = &g;
ss_ = &ss;
if (ple_ss_ == nullptr) ple_ss_ = &ss;
max_t_ = max_t;
rt_dir_ = rt_dir;
// (the draft layer's kernels - the resident grouping, the grouped experts, the fused reads - are built for the narrow window)
if (max_t < 1 || max_t > strata::kernels::kVerifyNarrowT) { err = "mtp: max_t out of range"; return false; }
if (shared != nullptr) {
if (shared->device_ != device_ || shared->g_ != &g || shared->dense_ == nullptr ||
shared->experts_ == nullptr || shared->rt_dir_ != rt_dir) {
err = "mtp: incompatible shared weights";
return false;
}
dense_ = shared->dense_;
experts_ = shared->experts_;
tensors_ = shared->tensors_;
owns_weights_ = false;
owns_draft_head_ = false;
}
// Loader fix (0.1.15+loaderfix.2): the two reads below are the whole “drafter files” cost; reporting
// them apart from the rest of the stage is what makes the next regression visible.
const auto t_files = std::chrono::steady_clock::now();
// ---- the index and the dense weights
if (shared == nullptr) {
std::ifstream idx(rt_dir + "/dense.txt");
if (!idx) { err = "mtp: cannot open " + rt_dir + "/dense.txt (run tools/mtp_rt.py)"; return false; }
std::string line;
while (std::getline(idx, line)) {
if (line.empty()) continue;
std::istringstream is(line);
Tensor t;
is >> t.name >> t.kind >> t.rows >> t.cols >> t.off >> t.bytes;
if (!is) { err = "mtp: malformed dense.txt line: " + line; return false; }
tensors_.push_back(t);
}
std::vector<uint8_t> blob;
if (!read_file(rt_dir + "/dense.bin", blob)) { err = "mtp: cannot read dense.bin"; return false; }
const cudaError_t alloc = cudaMalloc((void**) &dense_, blob.size());
if (alloc != cudaSuccess) {
size_t free_bytes = 0, total_bytes = 0;
const cudaError_t info = cudaMemGetInfo(&free_bytes, &total_bytes);
err = "mtp: dense weights allocation failed (" + std::string(cudaGetErrorString(alloc)) +
"), requested " + std::to_string(blob.size() >> 20) + " MiB, CUDA0 free " +
(info == cudaSuccess ? std::to_string(free_bytes >> 20) + " MiB" : "unknown");
return false;
}
cudaMemcpy(dense_, blob.data(), blob.size(), cudaMemcpyHostToDevice);
vram_ += blob.size();
if (q4_ && !make_q4_dense(blob, err)) return false;
}
// ---- the 512 routed experts, one blob each
if (shared == nullptr) {
const uint64_t bytes = (uint64_t) g.n_expert * strata::kernels::cpu::BLOB;
// Loader fix (0.1.15+loaderfix.2): each 64 MiB read below reached the disk as ~16k 4095-byte reads under
// MSVC's `basic_filebuf::xsgetn`, which is what made 675 MiB of drafter experts take minutes.
FILE* f = std::fopen((rt_dir + "/experts.bin").c_str(), "rb");
if (f == nullptr) { err = "mtp: cannot open experts.bin"; return false; }
struct Closer {
FILE* f;
~Closer() { if (f != nullptr) std::fclose(f); }
} closer{f};
if (cudaMalloc((void**) &experts_, bytes) != cudaSuccess) { err = "mtp: the 512 experts do not fit in VRAM"; return false; }
#if !defined(_WIN32)
strata::platform::advise_willneed(fileno(f), 0, bytes);
#endif
std::vector<uint8_t> chunk(64u << 20);
for (uint64_t off = 0; off < bytes;) {
const uint64_t n = std::min<uint64_t>(chunk.size(), bytes - off);
if (std::fread(chunk.data(), 1, (size_t) n, f) != (size_t) n) { err = "mtp: experts.bin is truncated"; return false; }
cudaMemcpy(experts_ + off, chunk.data(), n, cudaMemcpyHostToDevice);
off += n;
}
vram_ += bytes;
}
const char* required[] = {"fc_embedding.weight", "fc_hidden.weight", "self_attn.q_proj.weight", "self_attn.k_proj.weight",
"self_attn.v_proj.weight", "self_attn.o_proj.weight", "mlp.shared_expert.gate_proj.weight",
"mlp.shared_expert.up_proj.weight", "mlp.shared_expert.down_proj.weight"};
for (const char* n : required) if (!q8(n)) { err = std::string("mtp: ") + n + " is missing (q8_0)"; return false; }
// STRATA_MTP_Q8_SM60=1: the projections on the Pascal GEMV (--batch's shared drafters read the same pointers), as
// packed copies like the main model's: the prompt path's draft_kv reads four of them in the GGUF layout (MMQ);
// --mtp-q4 reads its Q4_0 copies instead
if (shared == nullptr && dense4_ == nullptr && mtp_q8_sm60()) {
int packed = 0;
uint64_t packed_bytes = 0;
for (const char* n : required)
for (const auto& t : tensors_)
if (t.name == n && t.kind == "q8_0" &&
strata::kernels::native_q8_0_sm60_pack_quiet(dense_ + t.off, (int) t.cols, (int) t.rows,
("MTP " + t.name).c_str())) {
++packed;
packed_bytes += t.bytes; // a copy is the same 34 bytes per 32 values
}
vram_ += packed_bytes;
if (packed > 0)
std::fprintf(stderr, "strata mtp: %d of %zu projections on the Pascal Q8_0 GEMV (STRATA_MTP_Q8_SM60=1, %.1f "
"MiB more VRAM)\n", packed, sizeof(required) / sizeof(required[0]),
(double) packed_bytes / 1048576.0);
}
// ---- the layer's own K/V (dense attention: no indexer state is read)
const strata::kernels::QsaShapes s = shapes_of(g);
const int64_t max_cells = ss.qsa_states[ss.qsa_primary()].max_cells;
// KV streaming: the drafter only reads its last `window` cells, so with streaming on its K/V is a ring of the
// window (plus the cells a round writes ahead of its queries) over a host copy, refilled on a resume. The host copy
// is pinned after the expert arena has pinned what it could: if it does not fit, the K/V stays whole in VRAM.
int64_t ring = (window > 0 && window < max_cells) ? window + 4 * (int64_t) max_t + 64 : 0;
// K8V4 never applies to the drafter: its own attention paths (below, and verify.cpp) handle whole formats
// only, whatever ring shape it takes (0, a window, or the -1 fully-resident fallback).
const bool kv_hybrid_was = qsa_kv_hybrid();
const bool kv_int8_was = qsa_kv_int8();
qsa_set_kv_hybrid(false);
if (kv_hybrid_was) qsa_set_kv_int8(true); // the drafter under --kv k8v4: plain INT8
uint64_t sb = qsa_state_bytes(g, max_cells, false, ring);
if (cudaMalloc(&state_arena_, sb) != cudaSuccess) { err = "mtp: the K/V state does not fit"; return false; }
if (qsa_state_init(g, max_cells, state_arena_, st_, &ss.qsa_states[ss.qsa_primary()], ring) == 0) {
if (st_.kv_mode == 0) { err = "mtp: state init failed"; return false; }
std::fprintf(stderr, "strata mtp: no pinned RAM left for the draft layer's K/V copy; keeping it in VRAM\n");
cudaGetLastError();
cudaFree(state_arena_);
st_ = QsaState{};
ring = -1; // fully resident
sb = qsa_state_bytes(g, max_cells, false, ring);
if (cudaMalloc(&state_arena_, sb) != cudaSuccess) { err = "mtp: the K/V state does not fit"; return false; }
if (qsa_state_init(g, max_cells, state_arena_, st_, &ss.qsa_states[ss.qsa_primary()], ring) == 0) { err = "mtp: state init failed"; return false; }
}
qsa_set_kv_int8(kv_int8_was);
qsa_set_kv_hybrid(kv_hybrid_was);
qsa_state_zero(st_, g, nullptr);
cudaDeviceSynchronize();
vram_ += sb;
// ---- buffers
window_ = (window > 0 && window < max_cells) ? window : 0;
if (floor_on_ && !mapped(64, (void**) &h_floor_, (void**) &m_floor_)) { err = "mtp: the window floor does not fit"; return false; }
cap_ = (((window_ > 0 ? window_ : max_cells) + 63) / 64) * 64;
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 NH = (uint64_t) g.n_head, HD = (uint64_t) g.head_dim, NKV = (uint64_t) g.n_head_kv;
const uint64_t R2 = 2 * T; // step/pos rows: T catch-up rows + up to T-2 chain steps
bool ok = mapped(T * 4 + 64, (void**) &h_tok_, (void**) &m_tok_) &&
mapped(R2 * 4 * 4 + 64, (void**) &h_step_, (void**) &m_step_) &&
mapped(R2 * NH * 4 + 64, (void**) &h_pos_, (void**) &m_pos_) &&
mapped(64, (void**) &h_row_, (void**) &m_row_) &&
mapped(T * 4 + 64, (void**) &h_out_, (void**) &m_out_) &&
mapped(T * 4 + 64, (void**) &h_prob_, (void**) &m_prob_) &&
(!force_on_ || mapped(64, (void**) &h_force_, (void**) &m_force_));
if (!ok) { err = "mtp: mapped staging failed"; return false; }
if (h_force_ != nullptr) for (int j = 0; j < 16; ++j) h_force_[j] = -1;
auto carve = [&](Bump& b) {
tok_ = b.take<int32_t>(T); step_ = b.take<int32_t>(R2 * 4); pos_ = b.take<int32_t>(R2 * NH); row_ = b.take<int32_t>(4);
ident_ = b.take<int32_t>(T * (uint64_t) cap_);
Rin_ = b.take<float>(T * HC * N); R_ = b.take<float>(T * HC * N);
emb_ = b.take<float>(T * N); en_ = b.take<float>(T * N); e2_ = b.take<float>(T * N);
hn_ = b.take<float>(T * HC * N); h2_ = b.take<float>(T * HC * N);
mixed_ = b.take<float>(T * N); inj_ = b.take<float>(T * HC); inj2_ = b.take<float>(T * HC);
lo_ = b.take<float>(T * (uint64_t) g.hc_lr); rs_ = b.take<float>(T * HC); bo_ = b.take<float>(T * N);
xn_ = b.take<float>(T * HC * N);
xq_ = b.take<uint8_t>(strata::kernels::native_q8_1_bytes((int) (NH * HD), 8));
qfull_ = b.take<float>(T * NH * 2 * HD); qcur_ = b.take<float>(T * NH * HD);
kcur_ = b.take<float>(T * NKV * HD); vcur_ = b.take<float>(T * NKV * HD);
attn_ = b.take<float>(T * NH * HD); attn32_ = b.take<float>(T * NH * HD);
attn_scratch_ = b.take<float>((uint64_t) attn_scratch_floats_); // the full layer runs one row at a time
logits_ = b.take<float>(T * (uint64_t) g.n_expert); w_ = b.take<float>(T * K); ids_ = b.take<int32_t>(T * K);
shared_ = b.take<float>(T * N); parts_ = b.take<float>(T * K * N); y_ = b.take<float>(T * N);
sample_ = b.take<float>(T * N);
{
const strata::kernels::GrShapes gsh{g.n_embd, g.hc, g.hc_lr};
uint8_t* gr_mem = b.take<uint8_t>(strata::kernels::gr_workspace_bytes(gsh));
if (gr_mem != nullptr) strata::kernels::gr_workspace_init(gsh, gr_mem, own_gr_);
}
hit_slot_ = b.take<int32_t>(T * K); hit_dst_ = b.take<int32_t>(T * K); hit_count_ = b.take<int32_t>(4);
grp_ptr_ = b.take<unsigned long long>(T * K); grp_start_ = b.take<int32_t>(T * K + 1);
grp_counts_ = b.take<int32_t>(4);
hit_xq_ = b.take<uint8_t>(T * (N / 32) * 34); hit_xs_ = b.take<float>(T * (N / 32));
hit_scratch_ = b.take<uint8_t>(strata::kernels::moe_hit_grouped_scratch_bytes((int64_t) (T * K), g.n_embd, g.n_ff));
sh_scratch_ = (float*) b.take<uint8_t>(strata::kernels::shared_expert_scratch_bytes(g.n_ff));
x_bf16_ = b.take<uint16_t>(N);
out_ids_ = b.take<int32_t>(T + 4);
probs_ = b.take<float>(T + 4);
arg_scratch_ = b.take<uint8_t>(strata::kernels::argmax_rows_scratch_bytes((int) T));
top_scratch_ = b.take<uint8_t>(strata::kernels::row_top_prob_scratch_bytes((int) T));
dummy_inj_ = b.take<float>(HC);
};
Bump count;
carve(count);
if (cudaMalloc(&arena_, count.used) != cudaSuccess) { err = "mtp: buffers do not fit"; return false; }
cudaMemset(arena_, 0, count.used);
Bump real;
real.base = (uint8_t*) arena_;
carve(real);
vram_ += count.used;
{
std::vector<int32_t> id((size_t) (T * (uint64_t) cap_));
for (uint64_t t = 0; t < T; ++t)
for (int64_t i = 0; i < cap_; ++i) id[(size_t) (t * (uint64_t) cap_ + (uint64_t) i)] = (int32_t) i;
cudaMemcpy(ident_, id.data(), id.size() * 4, cudaMemcpyHostToDevice);
}
// --pipeline-windows 2 (the forcing graphs): the chain shares its card with stage 1's windows and the next launch
// on stage 0 waits for it, so its stream gets the highest priority there (STRATA_MTP_PRIORITY=0: the default)
bool prio = false;
#if !defined(STRATA_USE_HIP) && !defined(STRATA_HIP_GFX906) && !defined(STRATA_GPU_METAL) // (HIP, Metal: the default priority)
static const bool hi_prio = [] { const char* v = std::getenv("STRATA_MTP_PRIORITY"); return v == nullptr || std::atoi(v) != 0; }();
int prio_lo = 0, prio_hi = 0;
if (force_on_ && hi_prio && cudaDeviceGetStreamPriorityRange(&prio_lo, &prio_hi) == cudaSuccess)
prio = cudaStreamCreateWithPriority(&cs_, cudaStreamNonBlocking, prio_hi) == cudaSuccess;
cudaGetLastError();
#endif
#if defined(STRATA_USE_HIP) && !defined(STRATA_HIP_GFX906)
// engine-latency, STRATA_MTP_HIP_PRIO (default on gfx1200/gfx1201, =1 elsewhere opt-in, =0 off): the draft stream at the
// highest priority. ROCm hands out hardware queues per priority (GPU_MAX_HW_QUEUES per level), so the drafter gets a
// queue of its own: its round no longer waits behind the commit graph that the verifier's stream launched just before
// it (the commit is only needed by the next window, and now runs beside the draft). R9700, UD-Q4_K_XL: draft wall
// 5.8 -> 3.5 ms a window (notes-latency.md).
{
static const bool hip_prio = [] {
if (const char* v = std::getenv("STRATA_MTP_HIP_PRIO"); v != nullptr && *v != 0) return std::atoi(v) != 0;
int dev = 0;
cudaDeviceProp prop{};
return cudaGetDevice(&dev) == cudaSuccess && cudaGetDeviceProperties(&prop, dev) == cudaSuccess &&
strata::kernels::gfx_arch_is_gfx12(prop.gcnArchName);
}();
int lo = 0, hi = 0;
if (hip_prio && hipDeviceGetStreamPriorityRange(&lo, &hi) == hipSuccess)
prio = hipStreamCreateWithPriority(&cs_, hipStreamNonBlocking, hi) == hipSuccess;
(void) cudaGetLastError();
}
#endif
if (!prio && cudaStreamCreateWithFlags(&cs_, cudaStreamNonBlocking) != cudaSuccess) { err = "mtp: stream"; return false; }
#if !defined(STRATA_USE_HIP)
if (cudaStreamCreateWithFlags(&side_, cudaStreamNonBlocking) != cudaSuccess ||
cudaEventCreateWithFlags(&sh_fork_, cudaEventDisableTiming) != cudaSuccess ||
cudaEventCreateWithFlags(&sh_join_, cudaEventDisableTiming) != cudaSuccess) {
err = "mtp: streams";
return false;
}
#else
// HIP keeps the shared expert on cs_, so nothing uses this branch stream, and #1240 stopped creating it and its two
// events (an R9700 lost prompt speed with them after the first request). On gfx103x the stream's existence alone
// makes prompts read faster: RX 6800, Windows, STRATA_HIP_PROMPT_F16=1, a 7.9K-token prompt at 798-808 tok/s
// with it and 584-596 without, all of it in the prompt path's "wait copy" phase (3,081 -> 75 ms); the two events
// change nothing. So gfx103x creates the stream and no other HIP card does. STRATA_MTP_SIDE_STREAM=1 / =0 forces
// either.
{
int dev = 0;
cudaDeviceProp prop{};
bool on = cudaGetDevice(&dev) == cudaSuccess && cudaGetDeviceProperties(&prop, dev) == cudaSuccess &&
std::strncmp(prop.gcnArchName, "gfx103", 6) == 0;
if (const char* v = std::getenv("STRATA_MTP_SIDE_STREAM"); v != nullptr && *v != 0) on = std::atoi(v) != 0;
if (on && cudaStreamCreateWithFlags(&side_, cudaStreamNonBlocking) != cudaSuccess) {
err = "mtp: streams";
return false;
}
}
#endif
const double files_s = std::chrono::duration<double>(std::chrono::steady_clock::now() - t_files).count();
if (shared != nullptr) {
std::fprintf(stderr, "strata mtp: shared draft weights, %.0f MiB of private state and buffers\n",
(double) vram_ / 1048576.0);
} else {
std::fprintf(stderr, "strata mtp: draft layer loaded, %.0f MiB of VRAM (experts %.0f, dense %.0f), files read in %.2f s (%.0f MiB/s)\n",
(double) vram_ / 1048576.0, (double) g.n_expert * strata::kernels::cpu::BLOB / 1048576.0,
(double) tensors_.back().off / 1048576.0, files_s,
files_s > 0 ? ((double) g.n_expert * strata::kernels::cpu::BLOB + (double) tensors_.back().off) /
1048576.0 / files_s : 0.0);
}
return true;
}
namespace {
// STRATA_MTP_FULL_HEAD=1 (a diagnostic): draft over the whole vocabulary (the main head itself) instead of
// rt/draft_vocab.bin's subset - the reference head, to measure what the subset costs in acceptance
bool full_head_env() {
static const bool on = [] { const char* v = std::getenv("STRATA_MTP_FULL_HEAD"); return v && v[0] == '1'; }();
return on;
}
} // namespace
bool MtpDrafter::top2_env() {
static const bool on = [] { const char* v = std::getenv("STRATA_MTP_TOP2"); return v && v[0] == '1'; }();
return on;
}
// STRATA_MTP_TOP2=1 (a diagnostic for tree drafts): draft j's runner-up under the draft layer, from the head logits
// the step just wrote (row 0), on the host. Slow; only for measuring what a second branch would have caught.
void MtpDrafter::record_top2(int j) {
const int64_t nv = dhead_ != nullptr ? n_dvocab_ : n_vocab_;
if ((int64_t) lg_host_.size() < nv) lg_host_.resize((size_t) nv);
if ((int) top2_.size() < max_t_) top2_.assign((size_t) max_t_, -1);
if (j < 0 || j >= max_t_) return;
if (cudaMemcpy(lg_host_.data(), head_logits_, (size_t) nv * sizeof(float), cudaMemcpyDeviceToHost) != cudaSuccess) {
top2_[(size_t) j] = -1;
return;
}
int64_t b1 = -1, b2 = -1;
for (int64_t i = 0; i < nv; ++i) {
const float v = lg_host_[(size_t) i];
if (b1 < 0 || v > lg_host_[(size_t) b1]) { b2 = b1; b1 = i; }
else if (b2 < 0 || v > lg_host_[(size_t) b2]) b2 = i;
}
top2_[(size_t) j] = b2 < 0 ? -1 : dhead_ != nullptr ? dvocab_host_[(size_t) b2] : (int32_t) b2;
}
// ---- the prompt room (see the header): the 512 experts leave the device while a prompt is read, and come back
uint64_t MtpDrafter::experts_bytes() const {
if (!owns_weights_ || g_ == nullptr || experts_ == nullptr) return 0; // a shared drafter's experts are the owner's
return (uint64_t) g_->n_expert * strata::kernels::cpu::BLOB;
}
bool MtpDrafter::experts_lend(std::string& err) {
const uint64_t bytes = experts_bytes();
if (bytes == 0) { err = "mtp: the 512 experts are not this drafter's to lend"; return false; }
if (experts_lent_) return true;
const OnDevice on_device(device_);
if (!idle(err)) return false;
if (chain_live_) { err = "mtp: a chain is in flight"; return false; }
if (experts_host_ == nullptr) {
// taken once and kept: the room opens and closes around every long prompt, and a second read of experts.bin
// (675 MiB) per prompt is what this avoids
if (cudaMallocHost(&experts_host_, (size_t) bytes) != cudaSuccess) {
(void) cudaGetLastError();
err = "mtp: the 512 experts have no room in pinned host memory (they stay the decode's)";
return false;
}
experts_host_bytes_ = bytes;
}
// The block stays in VRAM, where it is: the prompt path's room slots ARE these bytes (set_ring_room_base), so
// this snapshot is what they are worth again once the prompt has read over them.
if (cudaMemcpy(experts_host_, experts_, (size_t) bytes, cudaMemcpyDeviceToHost) != cudaSuccess) {
(void) cudaGetLastError();
err = "mtp: copying the 512 experts to host memory failed (they stay the decode's)";
return false;
}
experts_lent_ = true;
return true;
}
bool MtpDrafter::experts_reclaim(std::string& err) {
if (!experts_lent_) return true;
const OnDevice on_device(device_);
if (!idle(err)) return false;
// IN PLACE: the address is the one the round and step graphs were captured with, so there is nothing to drop
if (cudaMemcpy(experts_, experts_host_, (size_t) experts_host_bytes_, cudaMemcpyHostToDevice) != cudaSuccess) {
(void) cudaGetLastError();
err = "mtp: copying the 512 experts back failed";
return false;
}
experts_lent_ = false;
return true;
}
uint64_t MtpDrafter::bind_bytes(uint64_t head_row_bytes, int64_t n_vocab) const {
uint64_t bytes = head_logits_ ? 0 : (uint64_t) max_t_ * (uint64_t) n_vocab * sizeof(float);
if (dhead_ == nullptr && owns_draft_head_ && !full_head_env()) {
if (FILE* f = std::fopen(vocab_file().c_str(), "rb")) {
std::fseek(f, 0, SEEK_END);
const long size = std::ftell(f);
std::fclose(f);
if (size >= 4 && size % 4 == 0) bytes += (uint64_t) (size / 4) * head_row_bytes + (uint64_t) size;
}
}
// coupled draft sampling (STRATA_SPEC_COUPLED=1 only): an upper bound - the id -> subset map, the penalty ring,
// the split scratch (64 lists of 64 entries at most) and the parameters
if (coupled_draft_env() && cparams_ == nullptr)
bytes += (uint64_t) n_vocab * 4 + (uint64_t) (kCoupledHistCap + max_t_) * 4 + 64ull * 64ull * 8ull + 4096;
return bytes;
}
bool MtpDrafter::draft_head_view(const NativeHead* head, const std::string& vocab_path, DraftHeadView& out) const {
if (head == nullptr || head != head_ || dhead_ == nullptr || dvocab_ == nullptr || !owns_draft_head_ || !dhead_plain_) return false;
if (dhead_type_ != head->type() || vocab_path != vocab_file()) return false;
if (head->device() >= 0 && head->device() != device_) return false;
if (dvocab_host_.size() != (size_t) n_dvocab_) return false;
out.rows = dhead_;
out.vocab_dev = dvocab_;
out.vocab_host = &dvocab_host_;
out.n = n_dvocab_;
out.type = dhead_type_;
return true;
}
bool MtpDrafter::setup_coupled(std::string& err) {
const int64_t nv = dhead_ != nullptr ? n_dvocab_ : n_vocab_;
const size_t scratch = strata::kernels::coupled_draft_scratch_bytes((int) nv);
if (scratch == 0) {
std::fprintf(stderr, "strata mtp: STRATA_SPEC_COUPLED: %lld draft logits are too wide for the coupled sampler; "
"argmax drafts\n", (long long) nv);
return true;
}
const size_t ring = (size_t) (kCoupledHistCap + max_t_) * sizeof(int32_t);
if (cudaMalloc((void**) &cparams_, sizeof(strata::kernels::SamplerParams)) != cudaSuccess ||
cudaMalloc((void**) &cring_, ring) != cudaSuccess || cudaMalloc(&cscratch_, scratch) != cudaSuccess ||
!mapped(sizeof(strata::kernels::SamplerParams), (void**) &h_cparams_, (void**) &m_cparams_) ||
!mapped((size_t) kCoupledHistCap * sizeof(int32_t), (void**) &h_chist_, (void**) &m_chist_)) {
err = "mtp: the coupled draft sampler's buffers do not fit";
return false;
}
if (spec_prob_env() &&
!mapped((size_t) max_t_ * (size_t) kSpecQStride * sizeof(int32_t), (void**) &h_q_, (void**) &m_q_)) {
err = "mtp: the draft distributions' buffer does not fit";
return false;
}
cudaMemset(cring_, 0xff, ring); // -1: no token
std::fill(h_chist_, h_chist_ + kCoupledHistCap, -1);
vram_ += sizeof(strata::kernels::SamplerParams) + ring + scratch;
if (dhead_ != nullptr) { // token id -> subset index (-1: not in the draft head), for the penalties
std::vector<int32_t> sub((size_t) n_dvocab_), inv((size_t) n_vocab_, -1);
cudaMemcpy(sub.data(), dvocab_, sub.size() * sizeof(int32_t), cudaMemcpyDeviceToHost);
for (size_t i = 0; i < sub.size(); ++i)
if (sub[i] >= 0 && sub[i] < n_vocab_ && inv[(size_t) sub[i]] < 0) inv[(size_t) sub[i]] = (int32_t) i;
if (cudaMalloc((void**) &dinv_, inv.size() * sizeof(int32_t)) != cudaSuccess) {
err = "mtp: the coupled draft sampler's token map does not fit";
return false;
}
cudaMemcpy(dinv_, inv.data(), inv.size() * sizeof(int32_t), cudaMemcpyHostToDevice);
vram_ += inv.size() * sizeof(int32_t);
}
if (cudaDeviceSynchronize() != cudaSuccess) {
err = std::string("mtp: coupled setup: ") + cudaGetErrorString(cudaGetLastError());
return false;
}
coupled_ok_ = true;
if (spec_prob_env())
std::fprintf(stderr, "strata mtp: probabilistic draft acceptance on (STRATA_SPEC_PROB): sampled requests draft by "
"sampling the draft head's distribution over %lld tokens; %s\n", (long long) nv,
spec_gate_pick()
? "pick gate: masked mu offers, min(1, p/mu) acceptance and (p-mu)+ rejection/NULL residuals"
: "top gate (compatibility): q offers, min(1, p/q) acceptance and (p-q)+ rejection residuals");
else
std::fprintf(stderr, "strata mtp: coupled draft sampling on (STRATA_SPEC_COUPLED): sampled requests draft with the "
"target's chain and Philox draw over %lld tokens\n", (long long) nv);
return true;
}
void MtpDrafter::set_draft_sampling(const strata::kernels::SamplerParams& sp) {
coupled_active_ = coupled_ok_ && !sp.greedy && sp.temperature > 0.0f && sp.temperature >= spec_min_temp();
if (!coupled_active_) return;
*h_cparams_ = sp; // read by the next round graph (after the previous one has synced)
std::fill(h_chist_, h_chist_ + kCoupledHistCap, -1);
}
void MtpDrafter::set_draft_history(const int32_t* tail, int64_t n_tail, int32_t next) {
if (!coupled_active_) return;
const int h = coupled_hist_len(h_cparams_->penalty_last_n, kCoupledHistCap);
coupled_hist_base(tail, n_tail, next, h, h_chist_ + (kCoupledHistCap - h));
}
namespace {
// #474: what to change when the draft head's token subset does not fit the VRAM left - a smaller subset that setup
// ships (data/draft_vocab_*.bin; their token counts below), and how to pick it. The start used to stop at "the draft
// head does not fit" with no hint. Text only, after the failure: nothing changes for a start that fits.
void draft_head_hint(int64_t n_tokens, int64_t row_bytes) {
size_t free_b = 0, total_b = 0;
const bool have_free = cudaMemGetInfo(&free_b, &total_b) == cudaSuccess;
auto mib = [&](int64_t n) { return (double) (n * row_bytes) / 1048576.0; };
std::string free_s;
if (have_free) {
char b[64];
std::snprintf(b, sizeof(b), " and %.0f MiB is free", (double) free_b / 1048576.0);
free_s = b;
}
std::fprintf(stderr, "strata mtp: the draft head over %lld tokens needs %.0f MiB of VRAM%s.\n",
(long long) n_tokens, mib(n_tokens), free_s.c_str());
struct Subset { const char* name; int64_t tokens; const char* what; };
static const Subset smaller[] = {{"cyrillic", 58963, "English, code and the Cyrillic script"},
{"en", 40525, "English and code"}};
std::string opts;
for (const Subset& s : smaller)
if (s.tokens < n_tokens) {
char b[160];
std::snprintf(b, sizeof(b), "%s--draft-vocab %s (%s, ~%.0f MiB)", opts.empty() ? "" : " or ", s.name,
s.what, mib(s.tokens));
opts += b;
}
if (!opts.empty())
std::fprintf(stderr, "strata mtp: hint: a smaller draft vocabulary needs less VRAM: %s. Start once with it - "
"START-HERE.bat --draft-vocab en (Windows) or ./setup.sh --draft-vocab en - and the model "
"keeps it (\"draft_vocab\" in its strata-*.json config); or a smaller --context in "
"setup.\n",
opts.c_str());
else
std::fprintf(stderr, "strata mtp: hint: this is already the smallest shipped draft vocabulary: a smaller "
"--context (or closing what else uses the GPU) leaves it room.\n");
}
} // namespace
bool MtpDrafter::bind(const WeightTable& wt, const NativeHead* head, const float* window_R, std::string& err,
const MtpDrafter* shared) {
#if defined(STRATA_GPU_METAL)
(void) wt; (void) head; (void) window_R; (void) err; (void) shared;
return true;
#endif
const OnDevice on_device(device_);
wt_ = &wt;
head_ = head;
window_R_ = window_R;
const WeightRef* wo = wt.find("output.weight");
if (!wo) { err = "mtp: output.weight is missing"; return false; }
n_vocab_ = wo->ne1;
if (head == nullptr || !head->loaded()) { err = "mtp: the draft layer needs the native head (--native)"; return false; }
if (head_logits_ == nullptr &&
cudaMalloc((void**) &head_logits_, (size_t) max_t_ * (size_t) n_vocab_ * sizeof(float)) != cudaSuccess) {
err = "mtp: the draft logits do not fit";
return false;
}
if (shared != nullptr) {
if (shared->head_ != head || shared->device_ != device_ ||
shared->n_vocab_ != n_vocab_) {
err = "mtp: incompatible shared draft head";
return false;
}
dhead_ = shared->dhead_;
dhead_type_ = shared->dhead_type_; // the subset's type (the main head's, or Q4_0): -1 failed every --batch-mtp step
dvocab_ = shared->dvocab_;
n_dvocab_ = shared->n_dvocab_;
owns_draft_head_ = false;
}
// the draft head's token subset, when tools/draft_vocab.py wrote one
if (dhead_ == nullptr && shared == nullptr && !full_head_env()) {
std::vector<uint8_t> raw;
if (read_file(vocab_file(), raw) && raw.size() >= 4 && raw.size() % 4 == 0) {
n_dvocab_ = (int64_t) (raw.size() / 4);
const int64_t row_bytes = (int64_t) head->row_bytes(); // a vocabulary row of the native head
if (cudaMalloc((void**) &dvocab_, raw.size()) != cudaSuccess ||
cudaMalloc((void**) &dhead_, (size_t) (n_dvocab_ * row_bytes)) != cudaSuccess) {
err = "mtp: the draft head does not fit";
draft_head_hint(n_dvocab_, row_bytes);
return false;
}
cudaMemcpy(dvocab_, raw.data(), raw.size(), cudaMemcpyHostToDevice);
dvocab_host_.resize((size_t) n_dvocab_);
std::memcpy(dvocab_host_.data(), raw.data(), raw.size());
const int head_dev = head->device();
if (head_dev >= 0 && head_dev != device_) {
// the main head is on another card (the drafter on the first stage of a layer split, 0.1.44): the rows are
// gathered where the head is and the subset copied over once
void* tmp = nullptr;
int32_t* dv = nullptr;
bool ok_x = true;
{
const OnDevice on_head(head_dev);
ok_x = cudaMalloc((void**) &tmp, (size_t) (n_dvocab_ * row_bytes)) == cudaSuccess &&
cudaMalloc((void**) &dv, raw.size()) == cudaSuccess &&
cudaMemcpy(dv, raw.data(), raw.size(), cudaMemcpyHostToDevice) == cudaSuccess;
if (ok_x) {
strata::kernels::gather_rows((const uint8_t*) head->weights(), row_bytes, dv, n_dvocab_,
(uint8_t*) tmp, nullptr);
ok_x = cudaDeviceSynchronize() == cudaSuccess;
}
}
ok_x = ok_x && cudaMemcpy(dhead_, tmp, (size_t) (n_dvocab_ * row_bytes), cudaMemcpyDeviceToDevice) == cudaSuccess;
{
const OnDevice on_head(head_dev);
if (tmp) cudaFree(tmp);
if (dv) cudaFree(dv);
}
if (!ok_x) { err = "mtp: the draft head's rows could not be copied from the head's card"; return false; }
} else {
strata::kernels::gather_rows((const uint8_t*) head->weights(), row_bytes, dvocab_, n_dvocab_, dhead_, nullptr);
}
cudaDeviceSynchronize();
vram_ += (uint64_t) (n_dvocab_ * row_bytes) + raw.size();
std::fprintf(stderr, "strata mtp: draft head over %lld tokens (%.1f MiB)\n", (long long) n_dvocab_,
(double) (n_dvocab_ * row_bytes) / 1048576.0);
dhead_type_ = head->type();
dhead_plain_ = !q4_head_;
if (q4_head_ && !make_q4_head(err)) return false;
if (dhead_type_ == 14 && strata::kernels::native_q6_k_packed_enabled()) { // STRATA_Q6_PACKED=1
dhead_plain_ = false;
strata::kernels::native_q6_k_pack(dhead_, (int) (row_bytes / 210) * 256, (int) n_dvocab_,
"MTP draft head");
}
// STRATA_MTP_Q8_SM60=1: the subset on the Pascal GEMV like the main head, but packed in place - nothing but
// record_rest's native_mmvq reads it (the prompt path never does), and a copy would cost its size again
if (dhead_type_ == GGML_Q8_0 && owns_draft_head_ && mtp_q8_sm60() && row_bytes == g_->n_embd / 32 * 34 &&
strata::kernels::native_q8_0_sm60_pack_in_place(dhead_, (int) g_->n_embd, (int) n_dvocab_,
"MTP draft head"))
{
dhead_plain_ = false;
std::fprintf(stderr, "strata mtp: the draft head on the Pascal Q8_0 GEMV (STRATA_MTP_Q8_SM60=1)\n");
}
}
}
if (coupled_draft_env() && cparams_ == nullptr && !setup_coupled(err)) return false;
return true;
}
// STRATA_MTP_PROFILE=1 (measurement only): GPU stamps between the draft layer's stages in the round graph and in every
// step graph (each stamp is one more node, so the totals run a little high); the per-stage averages are printed every
// 300 rounds with STRATA_DRAFT_TIMING's line. Off: no stamp is recorded and nothing changes.
namespace {
constexpr int kMpSlots = 24;
constexpr int kMpGraphs = 17; // the round graph (0) and the steps 1..16
const char* const kMpNames[kMpSlots] = {"-", "embed+fc_emb", "hnorm+fc_hidden+add", "hc-read attn", "k/v+append",
"q+norm-rope", "attention", "gate+o_proj", "hc-read mlp", "router",
"experts", "shared", "combine+write", "hc-read mixer", "head gemv",
"argmax+prob", "select", "", "", "", "", "", "", ""};
struct MtpProf {
bool on = false;
unsigned long long* d = nullptr;
std::vector<unsigned long long> h;
int base = -1; // the graph being captured (-1: none, no stamps)
double sum[2][kMpSlots] = {};
int64_t n[2] = {0, 0};
MtpProf() {
const char* e = std::getenv("STRATA_MTP_PROFILE");
on = e != nullptr && e[0] == '1';
}
void init() {
if (!on || d != nullptr) return;
if (cudaMalloc((void**) &d, (size_t) kMpSlots * kMpGraphs * 8) != cudaSuccess) { on = false; d = nullptr; (void) cudaGetLastError(); return; }
cudaMemset(d, 0, (size_t) kMpSlots * kMpGraphs * 8);
h.assign((size_t) kMpSlots * kMpGraphs, 0);
}
void stamp(int i, cudaStream_t cs) const {
if (on && d != nullptr && base >= 0) strata::kernels::gpu_stamp(d, base * kMpSlots + i, cs);
}
void collect(int n_steps_run) { // after the round's sync: the round graph and steps 1..n_steps_run-1
if (!on || d == nullptr) return;
cudaMemcpy(h.data(), d, h.size() * 8, cudaMemcpyDeviceToHost);
for (int gi = 0; gi < n_steps_run && gi < kMpGraphs; ++gi) {
const unsigned long long* s = h.data() + (size_t) gi * kMpSlots;
const int k = gi == 0 ? 0 : 1;
unsigned long long prev = s[0];
if (prev == 0) continue;
for (int i = 1; i < kMpSlots; ++i) {
if (s[i] == 0 || s[i] < prev) continue;
sum[k][i] += (double) (s[i] - prev);
prev = s[i];
}
++n[k];
}
}
void report() {
for (int k = 0; k < 2; ++k) {
if (n[k] == 0) continue;
std::string out;
char b[96];
double tot = 0;
for (int i = 1; i < kMpSlots; ++i) {
if (sum[k][i] <= 0) continue;
tot += sum[k][i];
std::snprintf(b, sizeof b, " %s %.3f", kMpNames[i], sum[k][i] / 1e6 / (double) n[k]);
out += b;
}
std::fprintf(stderr, "strata mtp profile (%s, ms per graph over %lld):%s | total %.3f\n", k == 0 ? "round" : "step",
(long long) n[k], out.c_str(), tot / 1e6 / (double) n[k]);
for (double& x : sum[k]) x = 0;
n[k] = 0;
}
}
};
MtpProf g_mp;
// STRATA_VERIFY_NODES=1 also lists the draft graphs' nodes (kernel names on HIP; counts on CUDA)
void mtp_list_nodes(cudaGraph_t graph, const char* what) {
if (std::getenv("STRATA_VERIFY_NODES") == nullptr || graph == nullptr) return;
#if defined(STRATA_GPU_METAL)
(void) what; // Metal has no graph nodes to list
#else
#if defined(STRATA_USE_HIP)
using NodeT = hipGraphNode_t;
using NodeTypeT = hipGraphNodeType;
#define MTP_GET_NODES hipGraphGetNodes
#define MTP_NODE_TYPE hipGraphNodeGetType
#else
using NodeT = cudaGraphNode_t;
using NodeTypeT = cudaGraphNodeType;
#define MTP_GET_NODES cudaGraphGetNodes
#define MTP_NODE_TYPE cudaGraphNodeGetType
#endif
size_t nn = 0;
MTP_GET_NODES(graph, nullptr, &nn);
std::vector<NodeT> nodes(nn);
MTP_GET_NODES(graph, nodes.data(), &nn);
std::vector<std::pair<std::string, int>> kinds;
for (NodeT nd : nodes) {
NodeTypeT ty;
MTP_NODE_TYPE(nd, &ty);
std::string name = "type" + std::to_string((int) ty);
#if defined(STRATA_USE_HIP)
if (ty == hipGraphNodeTypeKernel) {
hipKernelNodeParams kp{};
if (hipGraphKernelNodeGetParams(nd, &kp) == hipSuccess && kp.func != nullptr) {
const char* fn = hipKernelNameRefByPtr(kp.func, nullptr);
if (fn != nullptr) name = fn;
}
}
#else
if (ty == cudaGraphNodeTypeKernel) name = "kernel";
#endif
bool found = false;
for (auto& k : kinds)
if (k.first == name) { ++k.second; found = true; break; }
if (!found) kinds.push_back({name, 1});
}
#undef MTP_GET_NODES
#undef MTP_NODE_TYPE
std::fprintf(stderr, "strata mtp: the %s graph has %zu nodes:", what, nn);
for (auto& k : kinds) std::fprintf(stderr, "\n %4d x %.110s", k.second, k.first.c_str());
std::fprintf(stderr, "\n");
#endif
}
bool mtp_qfuse_hc_on() {
static const int env = [] {
// only STRATA_QFUSE_HC (not STRATA_QFUSE, which the gfx1151 table sets): the draft layer's q8_1 images from the hyper-connection
// read were run on gfx1201 only (#3264), so every other target keeps the separate quantize unless asked
if (const char* v = std::getenv("STRATA_QFUSE_HC")) return std::atoi(v) != 0 ? 1 : 0;
return -1;
}();
if (env >= 0) return env != 0;
#if defined(STRATA_USE_HIP)
static int per_dev[64];
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