-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathrunner.cpp
More file actions
2341 lines (2214 loc) · 117 KB
/
Copy pathrunner.cpp
File metadata and controls
2341 lines (2214 loc) · 117 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Ported from: vllm/v1/worker/gpu/model_runner.py @ e24d1b24
// (initialize_kv_cache / execute_model / sample_tokens / sample /
// postprocess_sampled — the T0 slice) + the decode-first reorder from
// vllm/v1/attention/backends/utils.py::reorder_batch_to_split_decodes_and_prefills.
// See include/vllm/v1/worker/gpu/runner.h for scope, the V1-algorithm / MRV2-
// contract composition, the four-way ordering contract, and the deferred paths.
#include "vllm/v1/worker/gpu/runner.h"
#include <algorithm>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <numeric>
#include <set>
#include <stdexcept>
#include <unordered_map>
#include <unordered_set>
#include "vllm/model_executor/models/qwen3_5_internal.h"
#include "vllm/model_executor/models/qwen3_5_mtp.h" // SPEC-MTP I5d-pre: Qwen3_5MTPModel complete type for the owned draft member
#include "vllm/platforms/interface.h" // GetPlatform(device.type) per-tensor memory-model seam
#include "vllm/v1/kv_cache_dtype.h" // ResolveKvCacheDType (VT_KV_CACHE_F32 A/B)
#include "vllm/v1/kv_offload/lmcache/lmcache_connector.h" // KV-EXTERNAL-CACHE worker store/load
#include "vllm/v1/sample/ops/bad_words.h" // apply_allowed_token_ids (-inf mask)
#include "vllm/v1/worker/gpu/async_runner_flag.h" // VT_ASYNC_RUNNER predicate
#include "vllm/v1/spec_decode/rejection_sampler.h" // SPEC-REJECTION I3 verify half
#include "vllm/v1/worker/gpu/spec_decode/mtp/speculator.h" // SPEC-MTP I5d MtpProposePrefill
#include "vllm/v1/worker/gpu/spec_decode/dflash/speculator.h" // SPEC-DFLASH D5 DflashProposeBlock
#include "vllm/v1/spec_decode/ngram_proposer.h" // SPEC-NGRAM D3 NgramPropose
#include "vt/backend.h" // vt::Backend / GetBackend (VT_GPU_SAMPLE=0 download)
#include "vt/dtype.h" // VT_CHECK
#include "vt/tensor.h"
#ifdef VLLM_CPP_CUDA
#include "vt/cuda/combine_tokens.h" // W3 device combine/scatter (removes the sync)
#endif
namespace vllm::v1 {
// Logits-gather A/B toggle (perf). Default ON: the forward gathers the
// per-request last-token hidden rows BEFORE lm_head (prefill/mixed), so lm_head
// runs on num_reqs rows and only [num_reqs,vocab] is Downloaded. VT_LOGITS_GATHER=0
// restores the old full [num_actual_tokens,vocab] path (lm_head over all tokens,
// full D2H, host re-gather in sample_tokens). Both are token-for-token identical.
static bool LogitsGatherEnabled() {
static const bool on = [] {
const char* e = std::getenv("VT_LOGITS_GATHER");
return e == nullptr || e[0] != '0';
}();
return on;
}
// GPU-sampling A/B toggle (perf). Default ON: the forward keeps the [num_reqs,
// vocab] logits ON DEVICE and the sampler (argmax / temperature / top-k/top-p —
// all device kernels, mirroring vllm/v1/sample/sampler.py which never copies the
// full logits to host) reads them directly; only the sampled token ids (~num_reqs
// * 4 bytes) cross to host. VT_GPU_SAMPLE=0 restores the OLD path: Download the
// full [num_reqs, vocab] logits to host, then sample from the host copy — for the
// A/B on the same binary. Token-for-token identical (same on-device sampler
// kernels either way; only the logits' residence differs). Requires the
// gather-before-lm_head path (default); with VT_LOGITS_GATHER=0 the forward
// already returns host logits, so this toggle is a no-op there.
static bool GpuSampleEnabled() {
static const bool on = [] {
const char* e = std::getenv("VT_GPU_SAMPLE");
return e == nullptr || e[0] != '0';
}();
return on;
}
// Async-scheduling device-input default (ENG-ASYNC-SCHED W3 runner leaf).
// VT_ASYNC_RUNNER gates the combine_sampled_and_draft_tokens device-input +
// async sampler-output path at runner construction, which advertises
// runner_supports_async() so LoadedEngine resolves an AsyncScheduler + mcb=2.
// DEFAULT ON since the 2026-07-17 flip (mirror vLLM's async-scheduling default,
// vllm/config/vllm.py:992-1044; DGX-proven token-exact); VT_ASYNC_RUNNER=0 is the
// runner-level rollback to the synchronous host path (byte-identical pre-flip
// streams). Read at CONSTRUCTION (not per-step), honoring the env value live at
// each runner build so the DGX A/B — and the CPU construction-matrix test — can
// flip it per engine. The parse is factored into the pure, CPU-unit-tested
// AsyncRunnerFlagIsOn predicate (async_runner_flag.h). Tests may also toggle the
// flag directly via set_async_input_combine.
static bool AsyncRunnerEnvDefault() {
return AsyncRunnerFlagIsOn(std::getenv("VT_ASYNC_RUNNER"));
}
// GDN step-geometry diagnostic (default OFF). When VT_GDN_DIAG_STEP_LOG=1, each
// execute_model step prints the request count and the live/free recurrent-state
// slot geometry to std::cerr. Read ONCE (never per-step getenv); bounded to the
// packed-GDN c16 diagnostic checkpoint (see .agents/specs/gdn-packed-decode.md).
static bool GdnDiagStepLogEnabled() {
static const bool on = [] {
const char* e = std::getenv("VT_GDN_DIAG_STEP_LOG");
return e != nullptr && e[0] == '1' && e[1] == '\0';
}();
return on;
}
// ─── Decode-first reorder (utils.py::reorder_batch_to_split_decodes_and_prefills)
bool reorder_batch_to_split_decodes_and_prefills(
InputBatch& input_batch, const SchedulerOutput& scheduler_output,
int decode_threshold) {
const int num_reqs = input_batch.num_reqs();
if (num_reqs <= 1) {
return false;
}
// Per-request classification, in the current (dense) input_batch order.
std::vector<int32_t> req_regions(static_cast<size_t>(num_reqs), 0);
int num_decodes = 0, num_short = 0, num_long = 0, num_prefills = 0;
for (int i = 0; i < num_reqs; ++i) {
const std::string& req_id = *input_batch.req_ids[static_cast<size_t>(i)];
const int num_scheduled = scheduler_output.num_scheduled_tokens.at(req_id);
const int num_computed =
input_batch.num_computed_tokens_cpu[static_cast<size_t>(i)];
const int num_prompt =
input_batch.num_prompt_tokens[static_cast<size_t>(i)];
const bool has_context = num_computed > 0;
const bool is_below = num_scheduled <= decode_threshold;
const bool done_prefilling = num_computed >= num_prompt;
// Mutually exclusive (exactly one True). Desired order:
// decode(0) -> short_extend(1) -> long_extend(2) -> prefill(3).
if (!has_context) {
req_regions[static_cast<size_t>(i)] = 3; // pure prefill (first chunk)
++num_prefills;
} else if (!is_below) {
req_regions[static_cast<size_t>(i)] = 2; // long_extend
++num_long;
} else if (!done_prefilling) {
req_regions[static_cast<size_t>(i)] = 1; // short_extend
++num_short;
} else {
req_regions[static_cast<size_t>(i)] = 0; // decode
++num_decodes;
}
}
// target_regions = repeat([0,1,2,3], [nd, ns, nl, np]).
std::vector<int32_t> target_regions(static_cast<size_t>(num_reqs), 0);
{
int off = 0;
const int counts[4] = {num_decodes, num_short, num_long, num_prefills};
for (int region = 0; region < 4; ++region) {
for (int k = 0; k < counts[region]; ++k) {
target_regions[static_cast<size_t>(off++)] =
static_cast<int32_t>(region);
}
}
}
// orig_indices = ascending indices whose region != target (need to move).
std::vector<int> orig_indices;
for (int i = 0; i < num_reqs; ++i) {
if (req_regions[static_cast<size_t>(i)] !=
target_regions[static_cast<size_t>(i)]) {
orig_indices.push_back(i);
}
}
if (orig_indices.empty()) {
return false;
}
// src_indices = orig_indices sorted (stable) by their region — the source
// order the swap chains consume. Stable keeps ascending index within a region.
std::vector<int> src_indices = orig_indices;
std::stable_sort(src_indices.begin(), src_indices.end(), [&](int a, int b) {
return req_regions[static_cast<size_t>(a)] <
req_regions[static_cast<size_t>(b)];
});
// src_dest_map = {src: dst} in src_indices insertion order (dst = orig_indices
// by position). Iterate in that insertion order, following each swap chain.
std::unordered_map<int, int> dest;
for (size_t k = 0; k < src_indices.size(); ++k) {
dest[src_indices[k]] = orig_indices[k];
}
for (int src : src_indices) {
int dst = dest[src];
while (src != dst) {
input_batch.swap_states(src, dst);
const auto it = dest.find(dst);
const int next_dst = (it != dest.end()) ? it->second : dst;
dest[dst] = dst; // mark dst done
dst = next_dst;
}
}
return true;
}
// ─── apply_grammar_bitmask ──────────────────────────────────────────────────
// Ported from: vllm/v1/structured_output/utils.py::apply_grammar_bitmask @
// e24d1b24. See runner.h for the compacted-vs-dense contract + the bit sense.
void apply_grammar_bitmask(
const GrammarOutput& grammar_output,
const std::vector<std::string>& req_ids,
const std::map<std::string, std::vector<int32_t>>&
scheduled_spec_decode_tokens,
vt::Queue& queue, vt::Tensor& logits) {
const TokenBitmask& bitmask = grammar_output.grammar_bitmask;
// No structured request scheduled this step => nothing to mask (no-op).
if (grammar_output.structured_output_request_ids.empty() ||
bitmask.num_seqs == 0) {
return;
}
const int64_t num_logits = logits.shape[0];
const int64_t vocab = logits.shape[1];
// struct_out_req_batch_indices: for each structured req, the logit row = its
// dense batch index + the cumulative spec-token offset ahead of it
// (utils.py:112-120). At T0 scheduled_spec_decode_tokens is empty, so the
// offset stays 0 and logit_index == batch_index.
const std::set<std::string> struct_out_req_ids(
grammar_output.structured_output_request_ids.begin(),
grammar_output.structured_output_request_ids.end());
std::unordered_map<std::string, int> struct_out_req_batch_indices;
{
int cumulative_offset = 0;
for (int batch_index = 0;
batch_index < static_cast<int>(req_ids.size()); ++batch_index) {
const std::string& req_id = req_ids[static_cast<size_t>(batch_index)];
const int logit_index = batch_index + cumulative_offset;
const auto sit = scheduled_spec_decode_tokens.find(req_id);
if (sit != scheduled_spec_decode_tokens.end()) {
cumulative_offset += static_cast<int>(sit->second.size());
}
if (struct_out_req_ids.count(req_id) != 0) {
struct_out_req_batch_indices[req_id] = logit_index;
}
}
}
// Reorder the compacted bitmask onto the dense logits rows and unpack it into a
// per-row EXCLUDE mask (utils.py:124-140 reorder + the bit unpack). Rows for
// non-structured requests stay all-false (all tokens allowed). The
// apply_allowed_token_ids op reads TRUE == "exclude this token" (-> -inf), so a
// token is excluded exactly when its grammar bit is CLEAR (forbidden).
std::vector<std::vector<uint8_t>> exclude(
static_cast<size_t>(num_logits),
std::vector<uint8_t>(static_cast<size_t>(vocab), 0));
int cumulative_index = 0;
for (const std::string& req_id :
grammar_output.structured_output_request_ids) {
int num_spec_tokens = 0;
const auto sit = scheduled_spec_decode_tokens.find(req_id);
if (sit != scheduled_spec_decode_tokens.end()) {
num_spec_tokens = static_cast<int>(sit->second.size());
}
const auto bit = struct_out_req_batch_indices.find(req_id);
if (bit != struct_out_req_batch_indices.end()) {
const int logit_idx = bit->second;
for (int i = 0; i < 1 + num_spec_tokens; ++i) {
const int bitmask_row = cumulative_index + i;
const int logit_row = logit_idx + i;
if (logit_row < 0 || logit_row >= static_cast<int>(num_logits) ||
bitmask_row < 0 || bitmask_row >= bitmask.num_seqs) {
continue;
}
const int32_t* words =
bitmask.data.data() +
static_cast<size_t>(bitmask_row) *
static_cast<size_t>(bitmask.num_words);
std::vector<uint8_t>& row = exclude[static_cast<size_t>(logit_row)];
for (int64_t t = 0; t < vocab; ++t) {
const int32_t word = words[static_cast<size_t>(t >> 5)];
const bool allowed =
((word >> static_cast<int>(t & 31)) & 1) != 0;
if (!allowed) row[static_cast<size_t>(t)] = 1;
}
}
}
cumulative_index += 1 + num_spec_tokens;
}
// Set every forbidden token's logit to -inf (reuse the M1.7 sampler op; CPU +
// CUDA counterparts both exist — CUDA path is dgx-pending like the sampler).
apply_allowed_token_ids(queue, logits, exclude);
}
// ─── GPUModelRunner ─────────────────────────────────────────────────────────
namespace {
// Per-group block sizes from the KVCacheConfig groups, in group order (the
// InputBatch / MultiGroupBlockTable expect one entry per KV cache group).
std::vector<int> group_block_sizes(const KVCacheConfig& cfg) {
std::vector<int> sizes;
sizes.reserve(cfg.kv_cache_groups.size());
for (const auto& g : cfg.kv_cache_groups) {
sizes.push_back(g.kv_cache_spec->block_size);
}
return sizes;
}
} // namespace
GPUModelRunner::GPUModelRunner(
const HfConfig& config, LoadedModel& model,
const KVCacheConfig& kv_cache_config, vt::Queue queue, int max_num_reqs,
int max_model_len, int max_num_batched_tokens,
std::optional<vllm::SpeculativeConfig> spec_config,
std::unique_ptr<vllm::Qwen3_5MTPModel> draft_model,
std::vector<PagedKvCache> draft_kv)
: config_(config),
model_(&model),
spec_config_(std::move(spec_config)),
draft_model_(std::move(draft_model)),
draft_attn_kv_(std::move(draft_kv)),
queue_(queue),
input_batch_(max_num_reqs, max_model_len, max_num_batched_tokens,
static_cast<int>(config.vocab_size),
group_block_sizes(kv_cache_config),
group_block_sizes(kv_cache_config)) {
max_num_reqs_ = max_num_reqs;
max_num_batched_tokens_ = max_num_batched_tokens;
// SPEC-MTP I5e: the async input-combine splices the device-resident
// last_sampled token over each decode row's input id with
// num_new_sampled_tokens==1; it is NOT spec-aware and would overwrite the
// draft token at a verify step's draft position with the committed token.
// Speculative decode already forces SYNC scheduling and gets its drafts
// spliced into token_ids_cpu by update_req_spec_token_ids + prepare_inputs,
// so force the sync host input path here. Byte-identical for non-spec
// (spec_config_ is nullopt there, so this is AsyncRunnerEnvDefault()).
async_input_combine_ = AsyncRunnerEnvDefault() && !spec_config_.has_value();
initialize_kv_cache(kv_cache_config);
ModelRegistry::Prepare(*model_, config_, queue_);
}
GPUModelRunner::GPUModelRunner(
const HfConfig& config, std::unique_ptr<LoadedModel> owned_model,
const KVCacheConfig& kv_cache_config, vt::Queue queue, int max_num_reqs,
int max_model_len, int max_num_batched_tokens,
std::optional<vllm::SpeculativeConfig> spec_config,
std::unique_ptr<vllm::Qwen3_5MTPModel> draft_model,
std::vector<PagedKvCache> draft_kv)
: config_(config),
owned_model_(std::move(owned_model)),
model_(owned_model_.get()),
spec_config_(std::move(spec_config)),
draft_model_(std::move(draft_model)),
draft_attn_kv_(std::move(draft_kv)),
queue_(queue),
input_batch_(max_num_reqs, max_model_len, max_num_batched_tokens,
static_cast<int>(config.vocab_size),
group_block_sizes(kv_cache_config),
group_block_sizes(kv_cache_config)) {
max_num_reqs_ = max_num_reqs;
max_num_batched_tokens_ = max_num_batched_tokens;
// SPEC-MTP I5e: the async input-combine splices the device-resident
// last_sampled token over each decode row's input id with
// num_new_sampled_tokens==1; it is NOT spec-aware and would overwrite the
// draft token at a verify step's draft position with the committed token.
// Speculative decode already forces SYNC scheduling and gets its drafts
// spliced into token_ids_cpu by update_req_spec_token_ids + prepare_inputs,
// so force the sync host input path here. Byte-identical for non-spec
// (spec_config_ is nullopt there, so this is AsyncRunnerEnvDefault()).
async_input_combine_ = AsyncRunnerEnvDefault() && !spec_config_.has_value();
initialize_kv_cache(kv_cache_config);
ModelRegistry::Prepare(*model_, config_, queue_);
}
GPUModelRunner::GPUModelRunner(const HfConfig& config,
const Qwen3_5MoeWeights& weights,
const KVCacheConfig& kv_cache_config,
vt::Queue queue, int max_num_reqs,
int max_model_len, int max_num_batched_tokens)
: GPUModelRunner(config, BorrowQwen3_5MoeLoadedModel(weights),
kv_cache_config, queue, max_num_reqs, max_model_len,
max_num_batched_tokens) {}
GPUModelRunner::GPUModelRunner(const HfConfig& config,
const Qwen3_5DenseWeights& weights,
const KVCacheConfig& kv_cache_config,
vt::Queue queue, int max_num_reqs,
int max_model_len, int max_num_batched_tokens)
: GPUModelRunner(config, BorrowQwen3_5DenseLoadedModel(weights),
kv_cache_config, queue, max_num_reqs, max_model_len,
max_num_batched_tokens) {}
GPUModelRunner::CacheBuffer::CacheBuffer(vt::Device device, vt::Queue& queue,
size_t bytes,
bool backend_resident)
: device_(device), backend_resident_(backend_resident) {
if (!backend_resident_) {
host_data_.assign(bytes, uint8_t{0});
return;
}
backend_data_ = vt::Alloc(device_, std::max<size_t>(bytes, 1));
try {
if (bytes != 0) {
vt::GetBackend(device_.type).Memset(queue, backend_data_, 0, bytes);
}
} catch (...) {
vt::Free(device_, backend_data_);
backend_data_ = nullptr;
throw;
}
}
GPUModelRunner::CacheBuffer::~CacheBuffer() {
if (backend_data_ != nullptr) {
vt::Free(device_, backend_data_);
}
}
void GPUModelRunner::initialize_kv_cache(const KVCacheConfig& kv_cache_config) {
num_blocks_ = kv_cache_config.num_blocks;
// GDN mamba-state slots = max concurrent sequences (one recurrent state per
// sequence), decoupled from the attention num_blocks. Guard against a 0 (e.g.
// a test path that skipped the ctor arg) by falling back to num_blocks.
//
// SPEC-MTP I5d: under speculation each sequence needs num_spec+1 CONSECUTIVE
// GDN state slots (the k+1 draft-timestep snapshots the recurrent rollback
// selects among, spec §3). Size the compact pool max_num_reqs*(num_spec+1) and
// let remap_gdn_state_slots hand each sequence a base of num_spec+1 slots.
const int spec_cols = spec_on() ? num_spec() + 1 : 1;
const int64_t base_slots = max_num_reqs_ > 0 ? max_num_reqs_ : num_blocks_;
gdn_state_slots_ = base_slots * spec_cols;
gdn_slot_of_req_.clear();
gdn_free_slots_.clear();
gdn_free_slots_.reserve(static_cast<size_t>(base_slots));
// The free list holds each sequence's BASE state slot. Under speculation a
// base owns spec_cols (== num_spec+1) consecutive slots, so bases step by
// spec_cols; without speculation spec_cols==1 and this is the pre-spec pool.
for (int64_t b = base_slots - 1; b >= 0; --b)
gdn_free_slots_.push_back(static_cast<int32_t>(b * spec_cols));
// Resolve the full-attn + GDN(mamba) KV group ids (T0 gate models: exactly one
// of each). The block-table group order == kv_cache_groups order.
//
// SPEC-MTP I5d-pre LATENT-BUG FIX: the previous loop assigned
// `full_attn_group_id_` on EVERY full-attn/MLA group, so it kept the LAST one.
// With num_spec>0 the MTP draft adds a THIRD group (`fa_draft`, appended at
// index num_hidden_layers — qwen3_5_common.cpp:99-104), which the old code
// would then wrongly select as the TARGET attention group. Select the TARGET
// deterministically instead: the FIRST (index 0) non-eagle full-attn/MLA group,
// so a later-appended draft group can never displace it. With num_spec==0
// (every run today) there is exactly ONE full-attn group, so this is
// byte-identical to the old behavior — the first and only group is chosen.
for (int g = 0; g < static_cast<int>(kv_cache_config.kv_cache_groups.size());
++g) {
const auto& group = kv_cache_config.kv_cache_groups[static_cast<size_t>(g)];
const KVCacheSpecKind kind = group.kv_cache_spec->kind();
// MLA campaign W7: an `MLAAttentionSpec` group IS the model's attention
// group. Upstream registers MLA against the ordinary FullAttentionManager
// (`vllm/v1/core/single_type_kv_cache_manager.py:1539`), so block table,
// prefix caching and eviction are identical and the ONLY difference is the
// page cost/shape — which the spec-driven allocation below already reads
// off the spec. Additive condition: no existing arch changes group.
if (kind == KVCacheSpecKind::kFullAttention ||
kind == KVCacheSpecKind::kMlaAttention) {
// Skip a draft (eagle) group and keep the FIRST match as the target.
if (!group.is_eagle_group && full_attn_group_id_ < 0) {
full_attn_group_id_ = g;
}
} else if (kind == KVCacheSpecKind::kMamba) {
gdn_group_id_ = g;
}
}
// Allocate one PagedKvCache per full-attn layer and one GdnStateCache per GDN
// layer, in LAYER ORDER (matches Qwen3_5Model::Forward's per-layer fa_idx /
// gdn_idx indexing). As in upstream, MambaSpec is the source of truth for the
// recurrent tensors' order, shapes, dtypes, and page bytes.
const int64_t Hk = config_.linear_num_key_heads;
const int64_t Hv = config_.linear_num_value_heads;
const int64_t Dk = config_.linear_key_head_dim;
const int64_t Dv = config_.linear_value_head_dim;
const int64_t Kw = config_.linear_conv_kernel_dim;
const int64_t key_dim = Hk * Dk;
const int64_t value_dim = Hv * Dv;
const int64_t conv_dim = 2 * key_dim + value_dim;
// SPEC-MTP I5d: conv state row width, (Kw-1)+num_spec under speculation.
const int64_t conv_state_len = spec_on() ? (Kw - 1 + num_spec()) : (Kw - 1);
const MambaSpec* mamba_spec = nullptr;
if (gdn_group_id_ >= 0) {
mamba_spec = dynamic_cast<const MambaSpec*>(
kv_cache_config.kv_cache_groups[static_cast<size_t>(gdn_group_id_)]
.kv_cache_spec.get());
VT_CHECK(mamba_spec != nullptr,
"runner: GDN cache group must carry a MambaSpec");
VT_CHECK(mamba_spec->shapes.size() == 2 &&
mamba_spec->dtypes.size() == 2,
"runner: Qwen3.5 MambaSpec must contain conv then temporal state");
// SPEC-MTP I5d: the conv state row is widened to (Kw-1)+num_spec when
// speculation is on (MakeQwen3_5KVCacheSpec / mamba_utils.py:226), so accept
// the spec-driven width rather than the fixed Kw-1. The SSM state shape is
// unchanged (the extra draft snapshots live in extra SLOTS, not a wider row).
const std::vector<int64_t> expected_conv_shape{conv_dim, conv_state_len};
const std::vector<int64_t> expected_ssm_shape{Hv, Dv, Dk};
VT_CHECK(mamba_spec->shapes[0] == expected_conv_shape &&
mamba_spec->shapes[1] == expected_ssm_shape,
"runner: Qwen3.5 MambaSpec shapes disagree with model config");
gdn_conv_cache_dtype_ = mamba_spec->dtypes[0];
gdn_ssm_cache_dtype_ = mamba_spec->dtypes[1];
const auto supported_state_dtype = [](vt::DType dtype) {
return dtype == vt::DType::kF16 || dtype == vt::DType::kBF16 ||
dtype == vt::DType::kF32;
};
VT_CHECK(supported_state_dtype(gdn_conv_cache_dtype_) &&
supported_state_dtype(gdn_ssm_cache_dtype_),
"runner: Qwen3.5 MambaSpec state dtypes must be floating");
}
// SPEC-DRIVEN attention-cache sizing and layout (MLA campaign W1).
//
// Upstream never reconstructs the KV shape from the HF config: every layer's
// cache bytes come from its SPEC (`vllm/v1/kv_cache_interface.py:380-398`
// `real_page_size_bytes` -> `page_size_bytes`), and the tensor shape comes
// from the BACKEND (`get_kv_cache_shape`). That abstraction is exactly why
// `vllm/v1/worker/gpu_model_runner.py` contains **no `use_mla` branch at all**
// (only an import at :58, an isinstance at :977 and comments at :1085/:7133)
// even though MLA's cache is 1-head, 576-wide and has NO separate V — MLA is
// registered against the ordinary `FullAttentionManager`
// (`vllm/v1/core/single_type_kv_cache_manager.py:1539`), so block table,
// prefix caching and eviction are untouched and the whole cost lands in the
// ALLOCATOR and the ops.
//
// We previously hardcoded `num_blocks * 2 * block * Hkv * Dh` with Hkv/Dh
// read from `config_` — the factor 2 (K+V) and the HF-config reconstruction
// are the two things MLA cannot express. Now: bytes come from
// `spec->page_size_bytes()` and the cache VIEW comes from the spec's own
// fields. Behaviour-preserving by construction for every existing model —
// `FullAttentionSpec::real_page_size_bytes` is
// `block * num_kv_heads * (head_size + head_size_v) * es`, which with
// `head_size_v == head_size` is byte-for-byte the old expression.
int64_t fa_block_size = 0;
int64_t Hkv = 0;
int64_t Dh = 0;
int64_t fa_page_bytes = 0;
vt::DType kv_dtype = ResolveKvCacheDType();
if (full_attn_group_id_ >= 0) {
const KVCacheSpec* fa_spec =
kv_cache_config.kv_cache_groups[static_cast<size_t>(full_attn_group_id_)]
.kv_cache_spec.get();
const auto* attn_spec = dynamic_cast<const AttentionSpec*>(fa_spec);
VT_CHECK(attn_spec != nullptr,
"runner: full-attention cache group must carry an AttentionSpec");
fa_block_size = attn_spec->block_size;
Hkv = attn_spec->num_kv_heads;
Dh = attn_spec->head_size;
kv_dtype = attn_spec->dtype;
fa_page_bytes = attn_spec->page_size_bytes();
// The PagedKvCache view carries ONE head_size, so an asymmetric-V full
// attention layer cannot be viewed by it. MLA's own view (a later W) is a
// sibling struct; until then, refuse rather than mis-view.
if (const auto* full_spec = dynamic_cast<const FullAttentionSpec*>(fa_spec)) {
VT_CHECK(full_spec->head_size_v == full_spec->head_size,
"runner: asymmetric head_size_v is not expressible in the "
"PagedKvCache view");
}
VT_CHECK(fa_page_bytes > 0,
"runner: full-attention spec reported a non-positive page size");
// Positive signal that the SPEC (not the HF config) drove this allocation:
// opt-in, one line, never on the hot path.
if (const char* dbg = std::getenv("VT_KV_ALLOC_LOG");
dbg != nullptr && dbg[0] == '1') {
std::fprintf(stderr,
"[kv-alloc] source=spec kind=%d block_size=%lld "
"num_kv_heads=%lld head_size=%lld dtype=%d "
"page_size_bytes=%lld num_blocks=%lld\n",
static_cast<int>(fa_spec->kind()),
static_cast<long long>(fa_block_size),
static_cast<long long>(Hkv), static_cast<long long>(Dh),
static_cast<int>(kv_dtype),
static_cast<long long>(fa_page_bytes),
static_cast<long long>(num_blocks_));
}
}
// Recorded for the gates: the exact per-block byte cost the allocator used,
// sourced from the spec. `fa_page_size_bytes() > 0` is the runtime proof that
// the spec-driven path RAN (a compiled-but-unexercised path leaves it 0).
fa_page_size_bytes_ = fa_page_bytes;
const vt::Device dev = queue_.device;
const char* device_cache_env = std::getenv("VT_DEVICE_KV_CACHE");
// W0b-1 / work row M3a: this read `is_cuda()`, which is the SAME defect the
// `dense_attn_block.h` ResidentWeight fix corrected — "not NVIDIA" was being
// used to mean "no device memory". On kMETAL (and kVULKAN, kXPU) the KV cache
// fell into `host_data_`, and the first device kernel to touch it —
// vt::ReshapeAndCache — was handed a HOST pointer. On Metal that surfaces as
// "k_cache points outside every Metal allocation"; on a discrete-memory
// backend it would be a silent wrong answer or a fault.
//
// Device residency is a property of HAVING a device, not of the vendor, so the
// predicate is `!is_cpu()`. kCPU keeps the host vector (it has no device pool
// and the host IS the device) and kCUDA behaviour is bit-identical — the dgx
// regression set is the evidence, not this comment.
kv_cache_backend_resident_ =
!vllm::platforms::GetPlatform(dev.type).is_cpu() &&
(device_cache_env == nullptr || device_cache_env[0] != '0');
full_attn_buf_.clear();
ssm_buf_.clear();
conv_buf_.clear();
// A full-attention-only model (e.g. dense Qwen3ForCausalLM) has NO
// linear-attention (GDN/Mamba) KV group and an EMPTY layer_types — indexing
// layer_types[l] would be out of bounds. Drive "is this layer GDN?" off the
// resolved KV-group structure (gdn_group_id_ >= 0 ⇔ the model has a mamba
// group), then the per-layer layer_types tag. This is model-shape-agnostic:
// the hybrid gate models keep a GDN group, so their path is byte-identical.
const bool has_mamba_group = gdn_group_id_ >= 0;
// PER-LAYER KV head_dim (Gemma-4 G1b). When the model publishes a per-layer
// attention spec (heterogeneous head_dim: sliding 256 / global 512), each
// non-GDN layer allocates + views its OWN head_size/num_kv_heads/page_size.
// EMPTY for every uniform-KV model => `has_per_layer` is false => the loop
// uses the single group spec (Hkv/Dh/fa_page_bytes) for every layer, which is
// byte-identical to before this field existed (proven by the CPU paged-engine
// suite staying green). The block table / manager are head_dim-independent, so
// a single group + per-layer allocation is correct with no per-group changes.
const bool has_per_layer = !kv_cache_config.per_layer_attn_specs.empty();
if (has_per_layer) {
VT_CHECK(kv_cache_config.per_layer_attn_specs.size() ==
static_cast<size_t>(config_.num_hidden_layers),
"runner: per_layer_attn_specs must have one entry per hidden layer");
}
// Per-full-attn-buffer view geometry, parallel to full_attn_buf_ (built here
// so the views loop below need not re-derive per-layer dims). In the uniform
// case every entry is {Hkv, Dh, kv_dtype} — identical to today.
struct FaDims {
int64_t num_kv_heads;
int64_t head_size;
vt::DType dtype;
};
std::vector<FaDims> fa_dims;
for (int64_t l = 0; l < config_.num_hidden_layers; ++l) {
const bool is_gdn =
has_mamba_group && !config_.layer_types.empty() &&
config_.layer_types[static_cast<size_t>(l)] == "linear_attention";
if (is_gdn) {
VT_CHECK(mamba_spec != nullptr,
"runner: linear-attention layer has no MambaSpec");
// Raw buffers use their independent cache dtypes. Zero bytes are +0.0f
// for every supported floating storage type.
const size_t ssm_es = vt::SizeOf(gdn_ssm_cache_dtype_);
const size_t conv_es = vt::SizeOf(gdn_conv_cache_dtype_);
const int64_t conv_row_elems = conv_dim * conv_state_len;
const int64_t ssm_row_elems = Hv * Dv * Dk;
ssm_buf_.push_back(std::make_unique<CacheBuffer>(
dev, queue_,
static_cast<size_t>(gdn_state_slots_ * ssm_row_elems) * ssm_es,
kv_cache_backend_resident_));
conv_buf_.push_back(std::make_unique<CacheBuffer>(
dev, queue_,
static_cast<size_t>(gdn_state_slots_ * conv_row_elems) * conv_es,
kv_cache_backend_resident_));
} else {
// Bytes come from the SPEC, not from HF-config arithmetic: exactly
// `num_blocks * spec->page_size_bytes()`, mirroring upstream's
// `kv_cache_interface.py:380-398` sizing contract. For a symmetric
// FullAttentionSpec this is byte-identical to the old
// `num_blocks * 2 * block * Hkv * Dh * sizeof(kv_dtype)`; for a future
// MLAAttentionSpec it drops the factor 2 with no allocator change.
// 0 bytes == 0.0 in both bf16 and f32.
//
// PER-LAYER (Gemma-4 G1b): the layer's own spec supplies its page bytes +
// view geometry when published; otherwise the single group spec (uniform
// path). `l_page` collapses to `fa_page_bytes` and `{l_Hkv,l_Dh,l_dtype}`
// to `{Hkv,Dh,kv_dtype}` when `has_per_layer` is false — byte-identical.
int64_t l_Hkv = Hkv;
int64_t l_Dh = Dh;
int64_t l_page = fa_page_bytes;
vt::DType l_dtype = kv_dtype;
if (has_per_layer) {
const std::shared_ptr<AttentionSpec>& sp =
kv_cache_config.per_layer_attn_specs[static_cast<size_t>(l)];
VT_CHECK(sp != nullptr,
"runner: non-GDN layer has no per-layer attention spec");
l_Hkv = sp->num_kv_heads;
l_Dh = sp->head_size;
l_dtype = sp->dtype;
l_page = sp->page_size_bytes();
// Same guard as the group spec: the PagedKvCache view carries ONE
// head_size, so an asymmetric-V layer is not expressible in it.
if (const auto* full_sp = dynamic_cast<const FullAttentionSpec*>(sp.get())) {
VT_CHECK(full_sp->head_size_v == full_sp->head_size,
"runner: asymmetric head_size_v is not expressible in the "
"per-layer PagedKvCache view");
}
VT_CHECK(l_page > 0,
"runner: per-layer attention spec reported a non-positive page");
}
full_attn_buf_.push_back(std::make_unique<CacheBuffer>(
dev, queue_,
static_cast<size_t>(num_blocks_) * static_cast<size_t>(l_page),
kv_cache_backend_resident_));
fa_dims.push_back(FaDims{l_Hkv, l_Dh, l_dtype});
}
}
// Build the views over the (now stable) backing storage. `fa_dims` is parallel
// to `full_attn_buf_`; in the uniform case every entry is {Hkv, Dh, kv_dtype}.
VT_CHECK(fa_dims.size() == full_attn_buf_.size(),
"runner: per-layer KV view geometry out of sync with buffers");
attn_kv_.clear();
for (size_t i = 0; i < full_attn_buf_.size(); ++i) {
PagedKvCache kv;
kv.data = full_attn_buf_[i]->data();
kv.dtype = fa_dims[i].dtype;
kv.num_blocks = num_blocks_;
kv.block_size = fa_block_size;
kv.num_kv_heads = fa_dims[i].num_kv_heads;
kv.head_size = fa_dims[i].head_size;
attn_kv_.push_back(kv);
}
// SPEC-MTP I5d: allocate the MTP draft's own paged KV layer (the `fa_draft`
// group). It is sized exactly like a target full-attn layer and the propose
// forward reuses the target's block table / slot mapping over it
// (speculator.py:222-234). Allocated ONLY when speculation is on and the ctor
// did not already supply a draft KV (tests may). num_spec==0 has no fa_draft
// group, so this is never entered on the production default path.
draft_attn_buf_.clear();
if (spec_on() && draft_attn_kv_.empty() && full_attn_group_id_ >= 0 &&
fa_page_bytes > 0) {
for (int g = 0;
g < static_cast<int>(kv_cache_config.kv_cache_groups.size()); ++g) {
if (g == full_attn_group_id_) continue;
const auto& group = kv_cache_config.kv_cache_groups[static_cast<size_t>(g)];
if (group.kv_cache_spec->kind() != KVCacheSpecKind::kFullAttention) {
continue; // the GDN group and any non-attn group are not the draft.
}
draft_attn_buf_.push_back(std::make_unique<CacheBuffer>(
dev, queue_,
static_cast<size_t>(num_blocks_) * static_cast<size_t>(fa_page_bytes),
kv_cache_backend_resident_));
PagedKvCache dkv;
dkv.data = draft_attn_buf_.back()->data();
dkv.dtype = kv_dtype;
dkv.num_blocks = num_blocks_;
dkv.block_size = fa_block_size;
dkv.num_kv_heads = Hkv;
dkv.head_size = Dh;
draft_attn_kv_.push_back(dkv);
break; // exactly one fa_draft group at k=1.
}
}
gdn_state_.clear();
for (size_t g = 0; g < ssm_buf_.size(); ++g) {
GdnStateCache gs;
gs.ssm_state = vt::Tensor::Contiguous(ssm_buf_[g]->data(),
gdn_ssm_cache_dtype_,
dev, {gdn_state_slots_, Hv, Dv, Dk});
gs.conv_state = vt::Tensor::Contiguous(conv_buf_[g]->data(),
gdn_conv_cache_dtype_,
dev,
{gdn_state_slots_, conv_dim,
conv_state_len});
gdn_state_.push_back(gs);
}
}
std::vector<int32_t> GPUModelRunner::gather_block_table(int group_id,
int num_reqs,
int* num_cols) const {
const BlockTable& bt = input_batch_.block_table[group_id];
const int cols = bt.max_num_blocks_per_req;
*num_cols = cols;
const std::vector<int32_t>& dev = bt.get_device_tensor(); // committed rows
const size_t n = static_cast<size_t>(num_reqs) * static_cast<size_t>(cols);
return std::vector<int32_t>(dev.begin(),
dev.begin() + static_cast<std::ptrdiff_t>(n));
}
void GPUModelRunner::remap_gdn_state_slots(
std::vector<int32_t>& gdn_bt, int gdn_cols, int num_reqs,
const std::vector<std::optional<std::string>>& req_ids) {
if (gdn_cols <= 0 || num_reqs <= 0) return;
// The persistent batch holds EVERY live sequence in its [0, num_reqs) prefix.
// Key the compact state slot on the sequence IDENTITY (req_id), never the
// block-table col-0 block-id: once a sequence exceeds one mamba block that
// column collapses to the shared null block-id 0 (MambaManager skips all but
// the last block), so block-id keying maps every long concurrent sequence to
// ONE slot — the captured c16 "duplicate live GDN state index" fatal and,
// pre-validator, silent cross-request recurrent-state corruption.
// Reused member scratch (buckets persist across steps) — no per-step set
// allocation. Cleared then refilled with this step's live request ids.
std::unordered_set<std::string>& alive = gdn_alive_scratch_;
alive.clear();
alive.reserve(static_cast<size_t>(num_reqs));
for (int r = 0; r < num_reqs; ++r) {
// req_ids[r] is populated for every active [0, num_reqs) row after condense.
VT_CHECK(req_ids[static_cast<size_t>(r)].has_value(),
"GDN remap: active batch row is missing its request id");
alive.insert(*req_ids[static_cast<size_t>(r)]);
}
// Reclaim slots of sequences no longer in the batch (finished / preempted):
// a slot is released only after its owning request leaves.
for (auto it = gdn_slot_of_req_.begin(); it != gdn_slot_of_req_.end();) {
if (alive.find(it->first) == alive.end()) {
gdn_free_slots_.push_back(it->second);
it = gdn_slot_of_req_.erase(it);
} else {
++it;
}
}
// Assign/reuse a compact BASE slot per live sequence. Without speculation the
// base is written into col 0 (the only column the GDN metadata builder reads).
// SPEC-MTP I5d: under speculation each sequence owns num_spec+1 CONSECUTIVE
// slots [base, base+num_spec]; write them into cols 0..num_spec so the spec
// GDN builder reads the k+1 draft-timestep state slots (gdn_attn.py:266-269).
const int spec_cols = spec_on() ? num_spec() + 1 : 1;
for (int r = 0; r < num_reqs; ++r) {
const std::string& rid = *req_ids[static_cast<size_t>(r)];
const size_t off = static_cast<size_t>(r) * static_cast<size_t>(gdn_cols);
auto it = gdn_slot_of_req_.find(rid);
int32_t base;
if (it != gdn_slot_of_req_.end()) {
base = it->second;
} else {
VT_CHECK(!gdn_free_slots_.empty(),
"GDN state slots exhausted: live sequences exceed max_num_reqs");
base = gdn_free_slots_.back();
gdn_free_slots_.pop_back();
gdn_slot_of_req_.emplace(rid, base);
}
for (int c = 0; c < spec_cols && c < gdn_cols; ++c) {
gdn_bt[off + static_cast<size_t>(c)] = base + c;
}
}
}
std::optional<ModelRunnerOutput> GPUModelRunner::execute_model(
const SchedulerOutput& scheduler_output) {
// update_states: admit new reqs (incl. prefill_token_ids) + apply cached diffs
// + remove finished/unscheduled + condense (M1.5).
update_states(input_batch_, scheduler_output);
// Reset the stash. A 0-token step (e.g. an aborted-request flush) runs no
// forward — mark num_reqs == 0 so sample_tokens returns an empty output
// (mirrors upstream execute_model's total==0 early return).
exec_state_ = ExecuteModelState{};
if (scheduler_output.total_num_scheduled_tokens == 0 ||
input_batch_.num_reqs() == 0) {
return std::nullopt;
}
// DECODE-FIRST REORDER (four-way ordering contract) — before any metadata.
reorder_batch_to_split_decodes_and_prefills(input_batch_, scheduler_output);
// SPEC-MTP I5d: splice the scheduler's drafts for THIS verify step into
// token_ids_cpu after each request's committed prefix (gpu_input_batch.py:
// 484-509 update_req_spec_token_ids) so prepare_inputs reads the k draft tokens
// at the verify positions. No-op on the default path (empty map / no speculator).
if (spec_on()) {
const int nr = input_batch_.num_reqs();
for (int i = 0; i < nr; ++i) {
const std::string& req_id = *input_batch_.req_ids[static_cast<size_t>(i)];
input_batch_.update_req_spec_token_ids(
i, req_id, scheduler_output.scheduled_spec_decode_tokens);
}
}
// Build the flattened dense-order step inputs (M1.5).
StepInputs step = prepare_inputs(input_batch_, scheduler_output);
const int num_reqs = input_batch_.num_reqs();
// Async-scheduling device-input path (ENG-ASYNC-SCHED W3 runner leaf). When
// engaged, overwrite each decode row's input token id with the GPU-resident-
// analog last_sampled_tokens (combine_sampled_and_draft_tokens) instead of the
// host token_ids_cpu value prepare_inputs read — so step N+1 need not wait on
// step N's sampled token crossing to the host. idx_mapping is identity: our
// persistent batch is already condensed dense (batch row == req_state slot).
// Runs on the HOST side of input prep, BEFORE the forward and OUTSIDE any
// CUDA-graph capture (input prep always precedes the decode graph replay), so
// it is capture-safe. Default OFF: production keeps the byte-identical sync
// host path (both give the same id, since sample_tokens writes the same token
// to token_ids_cpu and last_sampled_tokens).
// Non-null only on the W4 discrete-CUDA path below: the device input-id buffer
// the combine patched, handed to the forward so it embeds the spliced ids
// instead of the (deliberately stale) host vector.
const int32_t* device_input_ids = nullptr;
if (async_input_combine_ && num_reqs > 0) {
#ifdef VLLM_CPP_CUDA
// S7: the DEVICE combine splices input ids from device-ADDRESSABLE host
// arrays (pageable on GB10's UMA) — an INTEGRATED-GPU property, not just
// "is CUDA". is_integrated_gpu() is byte-identical on the only registered
// CUDA platform (GB10 reports integrated) yet correctly decouples: a future
// DISCRETE GPU answers false and takes the host combine, which is the right
// path there (its host arrays are NOT device-addressable). Definition lives
// in the allowlisted CUDA platform leg, so the device token drops.
if (vllm::platforms::GetPlatform(queue_.device.type).is_integrated_gpu()) {
// DEVICE combine (W3 DGX leaf): splice each decode row's input id from the
// device-resident-analog last_sampled_tokens on the MAIN queue, BEFORE the
// forward (which embeds input_token_ids on the same queue → sees the patch)
// and OUTSIDE any decode-graph capture. idx_mapping is identity (condensed-
// dense batch), passed as nullptr. All inputs live in `step` (moved to
// exec_state_, buffer preserved) / persistent InputBatch members, so they
// outlive the async launch. On GB10's pageable memory the host arrays are
// device-addressable; this removes the sample_tokens_async pre-scatter
// Synchronize (see below). num_new_sampled_tokens == 1 (T0 non-spec).
vt::cuda::LaunchCombineSampledAndDraftTokens(
queue_, step.input_token_ids.data(), /*idx_mapping=*/nullptr,
input_batch_.last_sampled_tokens.data(), step.query_start_loc.data(),
step.seq_lens.data(), input_batch_.prefill_len.data(), num_reqs,
/*num_new_sampled_tokens=*/1);
} else if (AsyncDeviceInputs* dev = get_or_create_async_device_inputs();
dev != nullptr) {
// W4 DISCRETE device combine. Same kernel, same semantics; the difference
// is WHERE the operands live. `last_sampled` is already on the device (the
// previous step's scatter wrote it there and nothing read it back), so the
// three host-known inputs plus the freshly built input_ids are uploaded
// through the pinned staging buffer, the recorded structural edits are
// replayed first so the mirror's row order matches this step's batch, and
// the combine patches the DEVICE input_ids the forward will embed.
//
// Ordering, all on the MAIN queue and therefore exact: replay -> uploads
// -> combine -> forward. The forward is handed `device_input_ids` below,
// so the host copy of step.input_token_ids is deliberately left stale for
// decode rows; nothing on this path reads it (the rejection-sampler path
// that does is spec-only, and spec forces the sync runner).
replay_last_sampled_ops(*dev);
const int64_t num_tokens =
static_cast<int64_t>(step.input_token_ids.size());
VT_CHECK(num_tokens <= dev->input_ids_capacity,
"async device mirror: step tokens exceed max_num_batched_tokens");
VT_CHECK(num_reqs <= dev->max_reqs,
"async device mirror: step requests exceed max_num_reqs");
stage_upload(*dev, dev->input_ids, step.input_token_ids.data(), num_tokens);
stage_upload(*dev, dev->query_start_loc, step.query_start_loc.data(),
static_cast<int64_t>(num_reqs) + 1);
stage_upload(*dev, dev->seq_lens, step.seq_lens.data(), num_reqs);
stage_upload(*dev, dev->prefill_len, input_batch_.prefill_len.data(),
num_reqs);
vt::cuda::LaunchCombineSampledAndDraftTokens(
queue_, dev->input_ids, /*idx_mapping=*/nullptr, dev->last_sampled,
dev->query_start_loc, dev->seq_lens, dev->prefill_len, num_reqs,
/*num_new_sampled_tokens=*/1);
device_input_ids = dev->input_ids;
} else
#endif
{
std::vector<int32_t> idx_mapping(static_cast<size_t>(num_reqs));
std::iota(idx_mapping.begin(), idx_mapping.end(), 0);
combine_sampled_and_draft_tokens(
step.input_token_ids, idx_mapping, input_batch_.last_sampled_tokens,
step.query_start_loc, step.seq_lens, input_batch_.prefill_len,
/*num_new_sampled_tokens=*/1);
}
}
// W4: the structural-op log has exactly one consumer, the device mirror's
// replay above. On every other configuration (integrated GPU, CPU backend, the
// VT_ASYNC_DEVICE_MIRROR=0 rollback, async off) nothing drains it, so drop it
// here rather than let it grow for the life of a serving process. Deliberately
// NOT cleared when the mirror is on: a step with no requests replays nothing,
// and its ops must survive to the next step that does.
if (!async_device_mirror()) input_batch_.last_sampled_ops.clear();
// Full-attention KV group metadata (M1.6 MakeCommonAttentionMetadata).
int fa_cols = 0;
const std::vector<int32_t> fa_bt =
gather_block_table(full_attn_group_id_, num_reqs, &fa_cols);
CommonAttentionMetadata attn_meta = MakeCommonAttentionMetadata(
step, fa_bt, fa_cols, /*causal=*/true, full_attn_group_id_);
// GDN KV group metadata: the same step over the GDN group's block table,
// segmented decode-first by the GDN builder (M1.6 Task 4). GATED on the model
// HAVING a linear-attention (GDN/Mamba) KV group: a full-attention-only model
// (dense Qwen3ForCausalLM) has gdn_group_id_ < 0 and no GDN block-table group,
// so gather_block_table(gdn_group_id_) / remap / the metadata build must be
// skipped — gdn_meta stays default-empty (num_prefill_tokens == 0, all state
// arrays nullopt) and no GDN state is wired. The hybrid gate models keep a GDN
// group (gdn_group_id_ >= 0), so this block runs exactly as before —
// behavior-preserving / byte-identical for the hybrid path.
GDNAttentionMetadata gdn_meta;
if (gdn_group_id_ >= 0) {
int gdn_cols = 0;
std::vector<int32_t> gdn_bt =
gather_block_table(gdn_group_id_, num_reqs, &gdn_cols);
// SPEC-MTP I5d: the spec GDN builder reads cols 0..num_spec of the block
// table as the k+1 draft-timestep state slots. Our compact per-sequence pool
// OWNS the slot ids (the physical mamba block-id is irrelevant, see the remap
// rationale), so widen the block-table view to num_spec+1 columns when the
// real GDN block table is narrower, and let remap fill all k+1 slots.
if (spec_on() && gdn_cols < num_spec() + 1) {
const int wide = num_spec() + 1;
std::vector<int32_t> widened(
static_cast<size_t>(num_reqs) * static_cast<size_t>(wide), 0);
for (int r = 0; r < num_reqs; ++r) {
widened[static_cast<size_t>(r) * static_cast<size_t>(wide)] =
gdn_bt[static_cast<size_t>(r) * static_cast<size_t>(gdn_cols)];
}
gdn_bt = std::move(widened);
gdn_cols = wide;
}
// Remap col 0 to a compact per-sequence state slot in [0, gdn_state_slots_),
// keyed on the request identity so the GDN state cache is sized by
// max_num_reqs (one recurrent state per sequence) rather than the attention
// num_blocks, and no two live sequences ever collide on one slot. Only col 0
// (state indices) is read downstream.
remap_gdn_state_slots(gdn_bt, gdn_cols, num_reqs, input_batch_.req_ids);
if (GdnDiagStepLogEnabled()) {
std::cerr << "[VT_GDN_DIAG] step num_reqs=" << num_reqs
<< " gdn_free_slots=" << gdn_free_slots_.size()
<< " gdn_live_slots=" << gdn_slot_of_req_.size() << "\n";
}
const CommonAttentionMetadata gdn_cam = MakeCommonAttentionMetadata(
step, gdn_bt, gdn_cols, /*causal=*/true, gdn_group_id_);
if (spec_on()) {