-
Notifications
You must be signed in to change notification settings - Fork 127
Expand file tree
/
Copy pathforward_context.py
More file actions
2211 lines (2095 loc) · 91.7 KB
/
Copy pathforward_context.py
File metadata and controls
2211 lines (2095 loc) · 91.7 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
from __future__ import annotations
from contextlib import contextmanager
from dataclasses import dataclass
from typing import Any, Dict, Iterator, Tuple
import torch
from aiter import dtypes
try:
import triton
import triton.language as tl
except (ImportError, ModuleNotFoundError):
triton = None
tl = None
from atom.config import KVCacheTensor, get_current_atom_config
from atom.model_ops.attention_gdn import GatedDeltaNet
try:
from atom.model_ops.attention_mha import PagedAttentionImpl
except (ImportError, ModuleNotFoundError):
PagedAttentionImpl = type("PagedAttentionImpl", (), {})
try:
from atom.model_ops.paged_attention import Attention as PagedAttention
except (ImportError, ModuleNotFoundError):
try:
from atom.model_ops.paged_attention import PagedAttention
except (ImportError, ModuleNotFoundError):
PagedAttention = type("PagedAttention", (), {})
from atom.model_ops.attentions.gdn_attn import (
GDNAttentionMetadata,
compute_causal_conv1d_metadata,
)
from atom.utils.forward_context import (
AttentionMetaData,
Context,
_forward_kv_cache_context,
reset_forward_context,
set_forward_context,
set_kv_cache_data,
)
@dataclass
class AiterFlashAttentionPhaseMetadata:
max_query_len: int
max_seq_len: int
query_start_loc: torch.Tensor
AiterFlashAttentionDecodeMetadata = AiterFlashAttentionPhaseMetadata
AiterFlashAttentionPrefillMetadata = AiterFlashAttentionPhaseMetadata
@dataclass
class AiterFlashAttentionMetadataForPluginMode:
num_actual_tokens: int
num_actual_kv_tokens: int
max_query_len: int
query_start_loc: torch.Tensor
max_seq_len: int
seq_lens: torch.Tensor
slot_mapping: torch.Tensor
block_table: torch.Tensor
num_decodes: int
num_decode_tokens: int
num_prefills: int
num_prefill_tokens: int
num_extends: int
num_extend_tokens: int
decode_metadata: AiterFlashAttentionPhaseMetadata | None = None
prefill_metadata: AiterFlashAttentionPhaseMetadata | None = None
extend_metadata: Any = None
use_cascade: bool = False
common_prefix_len: int = 0
total_tokens: int = 0
context: Any = None
if triton is not None:
@triton.jit
def _expand_block_table_for_atom_indexer_kernel(
block_table,
output,
num_cols: tl.constexpr,
output_cols: tl.constexpr,
block_ratio: tl.constexpr,
BLOCK_RATIO: tl.constexpr,
):
row = tl.program_id(0)
col = tl.program_id(1)
offsets = tl.arange(0, BLOCK_RATIO)
value = tl.load(block_table + row * num_cols + col)
expanded = value * block_ratio + offsets
expanded = tl.where(value >= 0, expanded, -1)
tl.store(output + row * output_cols + col * block_ratio + offsets, expanded)
@triton.jit
def _recover_physical_block_table_from_kernel_kernel(
kernel_block_table,
output,
kernel_cols: tl.constexpr,
physical_cols: tl.constexpr,
block_ratio: tl.constexpr,
):
row = tl.program_id(0)
col = tl.program_id(1)
kernel_col = col * block_ratio
value = tl.load(
kernel_block_table + row * kernel_cols + kernel_col,
mask=kernel_col < kernel_cols,
other=-1,
)
physical = value // block_ratio
physical = tl.where(value >= 0, physical, -1)
tl.store(output + row * physical_cols + col, physical)
@dataclass(frozen=True)
class RTPForwardContext:
gdn_metadata: GDNAttentionMetadata | None
attn_metadata: AttentionMetaData
rtp_attn_inputs: Any
rtp_seq_size_per_block: int
rtp_kernel_seq_size_per_block: int
kv_cache_data: Dict[str, KVCacheTensor]
state_indices_cache: Dict[tuple[int, bool], torch.Tensor]
layer_group_map: Dict[int, int]
context: Context
num_tokens: int
mla_layer_map: Dict[int, Any]
LayerMaps = tuple[Dict[int, GatedDeltaNet], Dict[int, Any], Dict[int, Any]]
@staticmethod
def _non_empty_int32(
tensor: torch.Tensor | None, *, device: torch.device | None = None
) -> torch.Tensor | None:
if tensor is None or tensor.numel() == 0:
return None
kwargs = {"dtype": torch.int32, "non_blocking": True}
if device is not None:
kwargs["device"] = device
return tensor.to(**kwargs).contiguous()
@staticmethod
def _query_start_loc(attn_inputs: Any, *, device: torch.device) -> torch.Tensor:
input_lengths = RTPForwardContext._non_empty_int32(
getattr(attn_inputs, "input_lengths", None),
device=device,
)
cu_seqlens = RTPForwardContext._non_empty_int32(
getattr(attn_inputs, "cu_seqlens_device", None),
device=device,
)
if cu_seqlens is not None and cu_seqlens.numel() > 1:
# Decode steps may carry placeholder [0, 0] cu_seqlens from upper layers.
# Only trust cu_seqlens when it represents non-empty query tokens.
# In cuda-graph capture the .item() host-sync would abort capture
# (see rtp+atom_graph.md §2.4); under capture we always fall through
# to the input_lengths-based path below.
if not torch.cuda.is_current_stream_capturing() and bool(
(cu_seqlens[-1] > 0).item()
):
if (
input_lengths is not None
and cu_seqlens.numel() >= input_lengths.numel() + 1
):
return cu_seqlens[: input_lengths.numel() + 1]
return cu_seqlens
is_prefill = bool(getattr(attn_inputs, "is_prefill", False))
if is_prefill:
if input_lengths is None:
raise ValueError(
"RTP plugin requires attention_inputs.cu_seqlens or input_lengths "
"to build GDN query_start_loc."
)
prefix = torch.zeros((1,), dtype=torch.int32, device=input_lengths.device)
return torch.cat([prefix, input_lengths.cumsum(dim=0)], dim=0)
# Decode: query length is runtime step token count (usually 1 per sequence),
# not prompt input_lengths.
sequence_lengths_plus_1 = RTPForwardContext._non_empty_int32(
getattr(attn_inputs, "sequence_lengths_plus_1_device", None),
device=device,
)
sequence_lengths = RTPForwardContext._non_empty_int32(
getattr(attn_inputs, "sequence_lengths", None),
device=device,
)
if (
sequence_lengths_plus_1 is not None
and sequence_lengths is not None
and int(sequence_lengths_plus_1.numel()) == int(sequence_lengths.numel())
):
q_lens = (sequence_lengths_plus_1 - sequence_lengths).contiguous()
q_lens = torch.clamp(q_lens, min=1)
prefix = torch.zeros((1,), dtype=torch.int32, device=q_lens.device)
return torch.cat([prefix, q_lens.cumsum(dim=0)], dim=0)
if input_lengths is None:
raise ValueError(
"RTP decode requires sequence_lengths(+1) or input_lengths "
"to build GDN query_start_loc."
)
q_lens = torch.ones_like(
input_lengths, dtype=torch.int32, device=input_lengths.device
)
prefix = torch.zeros((1,), dtype=torch.int32, device=input_lengths.device)
return torch.cat([prefix, q_lens.cumsum(dim=0)], dim=0)
@staticmethod
def _state_indices(
attn_inputs: Any,
is_prefill: bool,
*,
device: torch.device,
seq_size_per_block: int,
group_id: int | None = None,
) -> torch.Tensor:
block_table = RTPForwardContext._select_block_table_for_layer(
attn_inputs=attn_inputs,
group_id=group_id,
)
if block_table is None or block_table.numel() == 0:
raise ValueError(
"RTP plugin requires kv_cache_kernel_block_id_device for GDN metadata."
)
if block_table.dim() == 1:
block_table = block_table.unsqueeze(0)
base = block_table.to(
device=device, dtype=torch.int32, non_blocking=True
).contiguous()
if base.dim() != 2:
raise ValueError(
"RTP plugin produced invalid GDN state indices shape "
f"(state_indices_shape={tuple(base.shape)})."
)
if seq_size_per_block <= 0:
raise ValueError(
f"RTP plugin got invalid seq_size_per_block={seq_size_per_block}."
)
if int(base.shape[0]) == 0 or int(base.shape[1]) == 0:
raise ValueError("RTP decode requires non-empty GDN state indices.")
input_lengths = RTPForwardContext._non_empty_int32(
getattr(attn_inputs, "input_lengths", None),
device=device,
)
if input_lengths is None:
raise ValueError(
"RTP plugin requires attention_inputs.input_lengths for GDN state indices."
)
if int(input_lengths.numel()) != int(base.shape[0]):
raise ValueError(
"RTP plugin input_lengths/block_table batch mismatch "
f"(input_lengths={int(input_lengths.numel())}, block_table={int(base.shape[0])})."
)
if is_prefill:
prefix_lengths = RTPForwardContext._non_empty_int32(
getattr(attn_inputs, "prefix_lengths_device", None),
device=device,
)
if prefix_lengths is None:
prefix_lengths = RTPForwardContext._non_empty_int32(
getattr(attn_inputs, "prefix_lengths", None),
device=device,
)
if prefix_lengths is None:
raise ValueError(
"RTP prefill requires attention_inputs.prefix_lengths for GDN state indices."
)
if int(prefix_lengths.numel()) != int(base.shape[0]):
raise ValueError(
"RTP plugin prefix_lengths/block_table batch mismatch "
f"(prefix_lengths={int(prefix_lengths.numel())}, block_table={int(base.shape[0])})."
)
last_token_idx = prefix_lengths + input_lengths - 1
else:
# RTP decode kernels use sequence_lengths_plus_1_d as canonical runtime value.
sequence_lengths_plus_1 = RTPForwardContext._non_empty_int32(
getattr(attn_inputs, "sequence_lengths_plus_1_device", None),
device=device,
)
if sequence_lengths_plus_1 is not None:
if int(sequence_lengths_plus_1.numel()) != int(base.shape[0]):
raise ValueError(
"RTP plugin sequence_lengths_plus_1_d/block_table batch mismatch "
f"(sequence_lengths_plus_1_d={int(sequence_lengths_plus_1.numel())}, "
f"block_table={int(base.shape[0])})."
)
last_token_idx = sequence_lengths_plus_1 - 1
else:
sequence_lengths = RTPForwardContext._non_empty_int32(
getattr(attn_inputs, "sequence_lengths", None),
device=device,
)
if sequence_lengths is None:
raise ValueError(
"RTP decode requires attention_inputs.sequence_lengths for GDN state indices."
)
if int(sequence_lengths.numel()) != int(base.shape[0]):
raise ValueError(
"RTP plugin sequence_lengths/block_table batch mismatch "
f"(sequence_lengths={int(sequence_lengths.numel())}, block_table={int(base.shape[0])})."
)
# Legacy fallback when sequence_lengths_plus_1_d is unavailable.
last_token_idx = sequence_lengths + input_lengths - 1
# Keep eager semantics strict (fail fast on malformed metadata).
# CUDA-graph warmup/replay may temporarily feed placeholder
# sequence_lengths_plus_1_d=0, so only graph-mode relaxes by clamping.
in_capture = torch.cuda.is_current_stream_capturing()
graph_mode = bool(getattr(attn_inputs, "is_cuda_graph", False))
relaxed_validation = in_capture or graph_mode
if relaxed_validation:
last_token_idx = torch.clamp(last_token_idx, min=0)
if not relaxed_validation and torch.any(last_token_idx < 0):
raise ValueError(
"RTP plugin produced negative token index for GDN state mapping."
)
block_col = torch.div(
last_token_idx,
int(seq_size_per_block),
rounding_mode="floor",
)
# Only graph mode clamps out-of-range columns for warmup/replay safety.
if relaxed_validation:
block_col = torch.clamp(block_col, max=max(int(base.shape[1]) - 1, 0))
if not relaxed_validation and (
torch.any(block_col < 0) or torch.any(block_col >= base.shape[1])
):
raise ValueError(
"RTP plugin block-table index out of range for GDN state mapping "
f"(max_col={int(base.shape[1]) - 1})."
)
row_idx = torch.arange(base.shape[0], device=device, dtype=torch.int64)
slot_ids = base[row_idx, block_col.to(dtype=torch.int64)]
if not relaxed_validation and torch.any(slot_ids < 0):
raise ValueError(
"RTP plugin resolved padded/invalid (-1) block slot for GDN state mapping."
)
return slot_ids.contiguous()
@staticmethod
def _select_block_table_for_layer(
attn_inputs: Any,
group_id: int | None = None,
) -> torch.Tensor | None:
by_group = getattr(
attn_inputs, "kv_cache_kernel_block_id_device_by_group", None
)
if by_group is not None and len(by_group):
gid = int(group_id) if group_id is not None else 0
if gid < 0 or gid >= len(by_group):
raise ValueError(
f"RTP plugin resolved invalid kv-cache group id {gid}."
)
return by_group[gid]
return getattr(attn_inputs, "kv_cache_kernel_block_id_device", None)
@staticmethod
def _recover_physical_block_table_from_kernel(
kernel_block_table: torch.Tensor,
*,
seq_size_per_block: int,
kernel_seq_size_per_block: int,
cg_bufs: dict | None = None,
) -> torch.Tensor:
if (
kernel_seq_size_per_block <= 0
or seq_size_per_block <= 0
or seq_size_per_block == kernel_seq_size_per_block
):
return kernel_block_table
if seq_size_per_block % kernel_seq_size_per_block != 0:
raise ValueError(
"RTP plugin cannot recover physical block_table from kernel block_table: "
f"seq_size_per_block={seq_size_per_block}, "
f"kernel_seq_size_per_block={kernel_seq_size_per_block}."
)
if kernel_block_table.dim() == 1:
kernel_block_table = kernel_block_table.unsqueeze(0)
if kernel_block_table.dim() != 2:
raise ValueError(
"RTP plugin invalid kernel block_table shape for physical recovery: "
f"{tuple(kernel_block_table.shape)}"
)
block_ratio = int(seq_size_per_block // kernel_seq_size_per_block)
bs_now = int(kernel_block_table.shape[0])
kernel_cols = int(kernel_block_table.shape[1])
if kernel_cols < block_ratio or kernel_cols % block_ratio != 0:
return kernel_block_table.to(
device=kernel_block_table.device, dtype=torch.int32, non_blocking=True
).contiguous()
physical_cols = (kernel_cols + block_ratio - 1) // block_ratio
in_capture = torch.cuda.is_current_stream_capturing()
if in_capture and cg_bufs is not None:
if triton is None:
raise RuntimeError(
"RTP plugin cuda-graph capture requires Triton for capture-safe "
"physical block_table recovery."
)
out_buf = cg_bufs.get("physical_block_table_i32")
if not isinstance(out_buf, torch.Tensor):
raise RuntimeError(
"RTP plugin capture requires prewarmed physical_block_table_i32."
)
if int(out_buf.shape[0]) < bs_now or int(out_buf.shape[1]) < physical_cols:
raise RuntimeError(
"RTP plugin prewarmed block_table_i32 buffer is too small for "
"physical recovery "
f"(buffer={tuple(out_buf.shape)}, required=({bs_now}, {physical_cols}))."
)
out_view = out_buf[:bs_now, :physical_cols]
_recover_physical_block_table_from_kernel_kernel[(bs_now, physical_cols)](
kernel_block_table,
out_view,
kernel_cols,
physical_cols,
block_ratio,
)
return out_view
sampled = kernel_block_table[:, : physical_cols * block_ratio : block_ratio]
recovered = torch.div(sampled, block_ratio, rounding_mode="floor")
recovered = torch.where(sampled >= 0, recovered, sampled)
return recovered.to(
device=kernel_block_table.device, dtype=torch.int32, non_blocking=True
).contiguous()
@staticmethod
def _build_layer_group_map(attn_inputs: Any) -> Dict[int, int]:
layer_to_group = getattr(attn_inputs, "kv_cache_layer_to_group", None)
if layer_to_group is None or int(layer_to_group.numel()) == 0:
return {}
layer_to_group_cpu = layer_to_group.detach().to(device="cpu")
return {idx: int(gid) for idx, gid in enumerate(layer_to_group_cpu.tolist())}
@staticmethod
def _layer_group_map_signature(attn_inputs: Any) -> tuple[Any, ...]:
layer_to_group = getattr(attn_inputs, "kv_cache_layer_to_group", None)
if layer_to_group is None:
return ("no_layer_to_group",)
return (
int(layer_to_group.data_ptr()),
int(layer_to_group.numel()),
)
@staticmethod
def _resolve_group_id(
*,
attn_inputs: Any,
layer_num: int | None,
layer_group_map: Dict[int, int] | None = None,
) -> int:
by_group = getattr(
attn_inputs, "kv_cache_kernel_block_id_device_by_group", None
)
if by_group is None or not len(by_group):
return 0
if layer_num is None:
return 0
if layer_group_map is not None and layer_num in layer_group_map:
return int(layer_group_map[layer_num])
return 0
@staticmethod
def state_indices_for_layer(
*,
attn_inputs: Any,
is_prefill: bool,
device: torch.device,
seq_size_per_block: int,
layer_num: int,
state_indices_cache: Dict[tuple[int, bool], torch.Tensor] | None = None,
layer_group_map: Dict[int, int] | None = None,
) -> torch.Tensor:
group_id = RTPForwardContext._resolve_group_id(
attn_inputs=attn_inputs,
layer_num=layer_num,
layer_group_map=layer_group_map,
)
cache_key = (int(group_id), bool(is_prefill))
if state_indices_cache is not None:
cached = state_indices_cache.get(cache_key)
if cached is not None:
return cached
state_indices = RTPForwardContext._state_indices(
attn_inputs=attn_inputs,
is_prefill=is_prefill,
device=device,
seq_size_per_block=seq_size_per_block,
group_id=group_id,
)
if state_indices_cache is not None:
state_indices_cache[cache_key] = state_indices
return state_indices
@staticmethod
def _build_gdn_metadata(
attn_inputs: Any,
*,
seq_size_per_block: int,
num_tokens: int,
state_indices_cache: Dict[tuple[int, bool], torch.Tensor] | None = None,
layer_group_map: Dict[int, int] | None = None,
) -> GDNAttentionMetadata:
block_table = getattr(attn_inputs, "kv_cache_kernel_block_id_device", None)
if block_table is None or block_table.numel() == 0:
raise ValueError(
"RTP plugin requires kv_cache_kernel_block_id_device for GDN metadata."
)
target_device = block_table.device
is_prefill = bool(getattr(attn_inputs, "is_prefill", False))
query_start_loc = RTPForwardContext._query_start_loc(
attn_inputs, device=target_device
)
state_indices = RTPForwardContext._state_indices(
attn_inputs=attn_inputs,
is_prefill=is_prefill,
device=target_device,
seq_size_per_block=seq_size_per_block,
)
if state_indices_cache is not None:
group_id = RTPForwardContext._resolve_group_id(
attn_inputs=attn_inputs,
layer_num=None,
layer_group_map=layer_group_map,
)
state_indices_cache[(int(group_id), bool(is_prefill))] = state_indices
if is_prefill:
prefix_lengths = RTPForwardContext._non_empty_int32(
getattr(attn_inputs, "prefix_lengths", None),
device=target_device,
)
if prefix_lengths is None:
raise ValueError(
"RTP prefill requires attention_inputs.prefix_lengths for GDN metadata."
)
has_initial_state = prefix_lengths > 0
nums_dict, batch_ptr, token_chunk_offset_ptr = (
compute_causal_conv1d_metadata(query_start_loc)
)
return GDNAttentionMetadata(
num_prefills=int(prefix_lengths.numel()),
num_prefill_tokens=num_tokens,
num_decodes=0,
num_decode_tokens=0,
num_spec_decodes=0,
num_spec_decode_tokens=0,
num_actual_tokens=num_tokens,
has_initial_state=has_initial_state,
spec_query_start_loc=None,
non_spec_query_start_loc=query_start_loc,
spec_state_indices_tensor=None,
non_spec_state_indices_tensor=state_indices,
spec_sequence_masks=None,
spec_token_indx=None,
non_spec_token_indx=None,
num_accepted_tokens=None,
nums_dict=nums_dict,
batch_ptr=batch_ptr,
token_chunk_offset_ptr=token_chunk_offset_ptr,
)
input_lengths = RTPForwardContext._non_empty_int32(
getattr(attn_inputs, "input_lengths", None),
device=target_device,
)
if input_lengths is None:
raise ValueError(
"RTP decode requires attention_inputs.input_lengths to derive batch size."
)
batch_size = int(input_lengths.numel())
return GDNAttentionMetadata(
num_prefills=0,
num_prefill_tokens=0,
num_decodes=batch_size,
num_decode_tokens=num_tokens,
num_spec_decodes=0,
num_spec_decode_tokens=0,
num_actual_tokens=num_tokens,
has_initial_state=None,
spec_query_start_loc=None,
non_spec_query_start_loc=query_start_loc,
spec_state_indices_tensor=None,
non_spec_state_indices_tensor=state_indices,
spec_sequence_masks=None,
spec_token_indx=None,
non_spec_token_indx=None,
num_accepted_tokens=None,
nums_dict=None,
batch_ptr=None,
token_chunk_offset_ptr=None,
)
@staticmethod
def _build_seq_lens(attn_inputs: Any, *, device: torch.device) -> torch.Tensor:
"""Build kernel seq_lens using RTP-native field priority.
Decode uses RTP's canonical sequence_lengths_plus_1_d first in both
eager and CUDA-graph paths. This keeps context_lens aligned with the
block-table slot/state-index calculation during graph replay.
"""
input_lengths = RTPForwardContext._non_empty_int32(
getattr(attn_inputs, "input_lengths", None),
device=device,
)
if input_lengths is None:
raise ValueError(
"RTP plugin requires attention_inputs.input_lengths for seq_lens."
)
is_prefill = bool(getattr(attn_inputs, "is_prefill", False))
if is_prefill:
# For chunked prefill, prefix_lengths can remain per-chunk while
# sequence_lengths_plus_1_d tracks the true cumulative context length.
sequence_lengths_plus_1 = RTPForwardContext._non_empty_int32(
getattr(attn_inputs, "sequence_lengths_plus_1_device", None),
device=device,
)
if sequence_lengths_plus_1 is not None:
if int(sequence_lengths_plus_1.numel()) != int(input_lengths.numel()):
raise ValueError(
"RTP plugin sequence_lengths_plus_1_d/input_lengths batch mismatch "
f"(sequence_lengths_plus_1_d={int(sequence_lengths_plus_1.numel())}, "
f"input_lengths={int(input_lengths.numel())})."
)
return sequence_lengths_plus_1.contiguous()
prefix_lengths = RTPForwardContext._non_empty_int32(
getattr(attn_inputs, "prefix_lengths_device", None),
device=device,
)
if prefix_lengths is None:
prefix_lengths = RTPForwardContext._non_empty_int32(
getattr(attn_inputs, "prefix_lengths", None),
device=device,
)
if prefix_lengths is None:
raise ValueError(
"RTP prefill requires attention_inputs.prefix_lengths for seq_lens."
)
if int(prefix_lengths.numel()) != int(input_lengths.numel()):
raise ValueError(
"RTP plugin prefix_lengths/input_lengths batch mismatch "
f"(prefix_lengths={int(prefix_lengths.numel())}, "
f"input_lengths={int(input_lengths.numel())})."
)
return (prefix_lengths + input_lengths).contiguous()
sequence_lengths_plus_1 = RTPForwardContext._non_empty_int32(
getattr(attn_inputs, "sequence_lengths_plus_1_device", None),
device=device,
)
if sequence_lengths_plus_1 is not None:
if int(sequence_lengths_plus_1.numel()) != int(input_lengths.numel()):
raise ValueError(
"RTP plugin sequence_lengths_plus_1_d/input_lengths batch mismatch "
f"(sequence_lengths_plus_1_d={int(sequence_lengths_plus_1.numel())}, "
f"input_lengths={int(input_lengths.numel())})."
)
return sequence_lengths_plus_1.contiguous()
sequence_lengths = RTPForwardContext._non_empty_int32(
getattr(attn_inputs, "sequence_lengths", None),
device=device,
)
if sequence_lengths is not None:
if int(sequence_lengths.numel()) != int(input_lengths.numel()):
raise ValueError(
"RTP plugin sequence_lengths/input_lengths batch mismatch "
f"(sequence_lengths={int(sequence_lengths.numel())}, "
f"input_lengths={int(input_lengths.numel())})."
)
# Keep decode seq_lens semantics aligned with pure RTP/aiter path:
# real context length is sequence_lengths + input_lengths.
return (sequence_lengths + input_lengths).contiguous()
raise ValueError(
"RTP decode requires attention_inputs.sequence_lengths_plus_1_d or "
"sequence_lengths for seq_lens."
)
@staticmethod
def _build_slot_mapping(
*,
positions: torch.Tensor,
query_start_loc: torch.Tensor,
block_table: torch.Tensor,
seq_size_per_block: int,
cg_bufs: dict | None = None,
) -> torch.Tensor:
if positions is None or positions.numel() == 0:
raise ValueError(
"RTP plugin requires non-empty positions for slot_mapping."
)
if query_start_loc is None or query_start_loc.numel() < 2:
raise ValueError(
"RTP plugin requires valid query_start_loc for slot_mapping."
)
if block_table is None or block_table.numel() == 0:
raise ValueError("RTP plugin requires block_table for slot_mapping.")
if block_table.dim() == 1:
block_table = block_table.unsqueeze(0)
if block_table.dim() != 2:
raise ValueError(
f"RTP plugin invalid block_table shape for slot_mapping: {tuple(block_table.shape)}"
)
if seq_size_per_block <= 0:
raise ValueError(
f"RTP plugin got invalid seq_size_per_block={seq_size_per_block}."
)
device = positions.device
dtype = torch.int32
in_capture = torch.cuda.is_current_stream_capturing()
# Capture path must not silently allocate via .to(...)/.contiguous().
if in_capture and cg_bufs is not None:
if positions.device != device or positions.dtype != dtype:
raise RuntimeError(
"RTP plugin capture requires positions to already be int32 on model device."
)
if not positions.is_contiguous():
raise RuntimeError(
"RTP plugin capture requires positions to be contiguous to avoid allocation."
)
if query_start_loc.device != device or query_start_loc.dtype != dtype:
raise RuntimeError(
"RTP plugin capture requires query_start_loc to already be int32 on model device."
)
if not query_start_loc.is_contiguous():
raise RuntimeError(
"RTP plugin capture requires query_start_loc to be contiguous to avoid allocation."
)
if block_table.device != device or block_table.dtype != dtype:
raise RuntimeError(
"RTP plugin capture requires block_table to already be int32 on model device."
)
if not block_table.is_contiguous():
raise RuntimeError(
"RTP plugin capture requires block_table to be contiguous to avoid allocation."
)
pos_i32 = positions
qsl = query_start_loc
bt = block_table
else:
pos_i32 = positions.to(
device=device, dtype=dtype, non_blocking=True
).contiguous()
qsl = query_start_loc.to(
device=device, dtype=dtype, non_blocking=True
).contiguous()
bt = block_table.to(
device=device, dtype=dtype, non_blocking=True
).contiguous()
batch_size = int(qsl.numel()) - 1
num_tokens = int(pos_i32.numel())
if batch_size <= 0:
raise ValueError("RTP plugin query_start_loc produced empty batch.")
if int(bt.shape[0]) != batch_size:
raise ValueError(
"RTP plugin block_table/query_start_loc batch mismatch "
f"(block_table={int(bt.shape[0])}, batch={batch_size})."
)
lengths = qsl[1:] - qsl[:-1]
if in_capture and cg_bufs is not None:
# Zero-alloc path: use pre-allocated buffers so captured GPU ops
# reference stable addresses that stay alive through replay.
# For decode (1 token/seq): seq_id[i] == i, pre-computed as arange.
seq_id = cg_bufs["seq_id"][:num_tokens]
block_col_buf = cg_bufs["block_col"][:num_tokens]
torch.div(
pos_i32,
int(seq_size_per_block),
rounding_mode="floor",
out=block_col_buf,
)
block_col_i64_buf = cg_bufs["block_col_i64"][:num_tokens]
block_col_i64_buf.copy_(block_col_buf)
slot_base_buf = cg_bufs["slot_base"][:num_tokens]
slot_base_buf.copy_(bt[seq_id, block_col_i64_buf])
token_offset_buf = cg_bufs["token_offset"][:num_tokens]
torch.remainder(pos_i32, int(seq_size_per_block), out=token_offset_buf)
slot_mapping_buf = cg_bufs["slot_mapping"][:num_tokens]
torch.add(
slot_base_buf * int(seq_size_per_block),
token_offset_buf,
out=slot_mapping_buf,
)
return slot_mapping_buf
elif in_capture:
# cg_bufs not provided: fall back to searchsorted (capture-safe but
# allocates transient tensors — may cause replay fault if GC'd).
raise RuntimeError(
"RTP plugin capture requires prewarmed cg_bufs; fallback allocation path is disabled."
)
else:
seq_id = torch.repeat_interleave(
torch.arange(batch_size, device=device, dtype=torch.int64),
lengths.to(dtype=torch.int64),
)
block_col = torch.div(
pos_i32,
int(seq_size_per_block),
rounding_mode="floor",
)
slot_base = bt[seq_id, block_col.to(dtype=torch.int64)]
token_offset = torch.remainder(pos_i32, int(seq_size_per_block))
slot_mapping = slot_base * int(seq_size_per_block) + token_offset
return slot_mapping.to(dtype=torch.int64).contiguous()
@staticmethod
def _build_query_start_loc_for_plugin(
*,
attn_inputs: Any,
seq_lens: torch.Tensor,
num_tokens: int,
device: torch.device,
cg_bufs: dict | None = None,
) -> torch.Tensor:
batch_size = int(seq_lens.numel())
if batch_size <= 0:
raise ValueError(
"RTP plugin cannot build query_start_loc with empty seq_lens."
)
in_capture = torch.cuda.is_current_stream_capturing()
# In cuda-graph capture mode, every .tolist()/.item() blocks capture.
# Decode-only capture path (Qwen3.5-MoE) always has num_tokens==batch_size
# (1 token/seq), so query_start_loc == arange(0, bs+1).
if in_capture and cg_bufs is not None:
# Zero-alloc path: return a pre-allocated slice (stable address).
return cg_bufs["query_start_loc"][: batch_size + 1]
if in_capture:
raise ValueError(
"RTP plugin capture requires prewarmed cg_bufs for query_start_loc "
f"(batch={batch_size}, num_tokens={int(num_tokens)})."
)
# Eager-mode validations (host sync allowed): keep prior semantics for
# safety so the eager path catches malformed metadata early.
qsl = RTPForwardContext._query_start_loc(attn_inputs, device=device)
if qsl is not None and qsl.numel() == batch_size + 1:
lengths = qsl[1:] - qsl[:-1]
qsl_stats = torch.stack([qsl[-1], torch.min(lengths)], dim=0).to(
device="cpu"
)
qsl_total_tokens, qsl_min_len = [int(v) for v in qsl_stats.tolist()]
if qsl_total_tokens == int(num_tokens) and qsl_min_len > 0:
return qsl.contiguous()
input_lengths = RTPForwardContext._non_empty_int32(
getattr(attn_inputs, "input_lengths", None),
device=device,
)
if input_lengths is not None and int(input_lengths.numel()) == batch_size:
input_stats = torch.stack(
[torch.min(input_lengths), torch.sum(input_lengths)],
dim=0,
).to(device="cpu")
min_input_len, total_input_len = [int(v) for v in input_stats.tolist()]
if min_input_len > 0 and total_input_len == int(num_tokens):
prefix = torch.zeros((1,), dtype=torch.int32, device=device)
return torch.cat(
[prefix, input_lengths.cumsum(dim=0)], dim=0
).contiguous()
if int(num_tokens) == batch_size:
prefix = torch.arange(0, batch_size + 1, dtype=torch.int32, device=device)
return prefix.contiguous()
if batch_size == 1:
return torch.tensor([0, int(num_tokens)], dtype=torch.int32, device=device)
raise ValueError(
"RTP plugin failed to build valid query_start_loc for plugin attention "
f"(batch={batch_size}, num_tokens={int(num_tokens)})."
)
@staticmethod
def _build_req_id_per_token(
*,
query_start_loc: torch.Tensor,
num_tokens: int,
device: torch.device,
cg_bufs: dict | None = None,
) -> torch.Tensor:
batch_size = int(query_start_loc.numel()) - 1
if batch_size <= 0:
raise ValueError(
"RTP plugin cannot build req_id_per_token for empty batch."
)
in_capture = torch.cuda.is_current_stream_capturing()
if cg_bufs is not None and "seq_id_i32" in cg_bufs:
seq_id_i32 = cg_bufs["seq_id_i32"]
if not isinstance(seq_id_i32, torch.Tensor):
raise RuntimeError(
"RTP plugin capture requires prewarmed seq_id_i32 tensor."
)
if int(seq_id_i32.shape[0]) < int(num_tokens):
raise RuntimeError(
"RTP plugin prewarmed seq_id_i32 buffer is too small "
f"(buffer={int(seq_id_i32.shape[0])}, required={int(num_tokens)})."
)
if seq_id_i32.device != device or seq_id_i32.dtype != torch.int32:
raise RuntimeError(
"RTP plugin capture requires seq_id_i32 to be int32 on model device."
)
if not seq_id_i32.is_contiguous():
raise RuntimeError(
"RTP plugin capture requires seq_id_i32 to be contiguous."
)
return seq_id_i32[:num_tokens]
if in_capture:
raise RuntimeError(
"RTP plugin capture requires prewarmed seq_id_i32 for req_id_per_token."
)
if int(num_tokens) == 0:
return torch.empty((0,), dtype=torch.int32, device=device)
lengths = (query_start_loc[1:] - query_start_loc[:-1]).to(dtype=torch.int64)
if not torch.cuda.is_current_stream_capturing() and int(
lengths.sum().item()
) != int(num_tokens):
raise ValueError(
"RTP plugin query_start_loc/num_tokens mismatch for req_id_per_token "
f"(query_start_loc[-1]={int(query_start_loc[-1].item())}, "
f"num_tokens={int(num_tokens)})."
)
return torch.repeat_interleave(
torch.arange(batch_size, device=device, dtype=torch.int32),
lengths,
).contiguous()
@staticmethod
def _expand_block_table_for_atom_indexer(
block_table: torch.Tensor,
*,
seq_size_per_block: int,
kernel_seq_size_per_block: int,
) -> torch.Tensor:
if (
kernel_seq_size_per_block <= 0
or seq_size_per_block <= 0
or seq_size_per_block == kernel_seq_size_per_block
):
return block_table
if seq_size_per_block % kernel_seq_size_per_block != 0:
raise ValueError(
"RTP plugin cannot expand block_table for ATOM indexer: "
f"seq_size_per_block={seq_size_per_block}, "
f"kernel_seq_size_per_block={kernel_seq_size_per_block}."
)
block_ratio = int(seq_size_per_block // kernel_seq_size_per_block)
offsets = torch.arange(
block_ratio, device=block_table.device, dtype=torch.int32
)
base = block_table.to(dtype=torch.int32)
expanded = base.unsqueeze(-1) * block_ratio + offsets
expanded = torch.where(base.unsqueeze(-1) >= 0, expanded, -1)
return expanded.reshape(base.shape[0], base.shape[1] * block_ratio).contiguous()
@staticmethod
def _expand_block_table_for_atom_indexer_capture(
block_table: torch.Tensor,
*,
seq_size_per_block: int,
kernel_seq_size_per_block: int,
cg_bufs: dict,
) -> torch.Tensor:
if (
kernel_seq_size_per_block <= 0
or seq_size_per_block <= 0
or seq_size_per_block == kernel_seq_size_per_block
):
return block_table
if seq_size_per_block % kernel_seq_size_per_block != 0:
raise ValueError(
"RTP plugin cannot expand block_table for ATOM indexer: "
f"seq_size_per_block={seq_size_per_block}, "
f"kernel_seq_size_per_block={kernel_seq_size_per_block}."
)
if triton is None:
raise RuntimeError(
"RTP plugin cuda-graph capture requires Triton for capture-safe "
"ATOM indexer block_table expansion."
)
out_buf = cg_bufs.get("indexer_block_table_i32")
if not isinstance(out_buf, torch.Tensor):
raise RuntimeError(
"RTP plugin capture requires prewarmed indexer_block_table_i32."