-
Notifications
You must be signed in to change notification settings - Fork 2.3k
Expand file tree
/
Copy pathsampler.py
More file actions
4942 lines (4366 loc) · 214 KB
/
sampler.py
File metadata and controls
4942 lines (4366 loc) · 214 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
# Copyright (c) 2025-2026, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import enum
import sys
from abc import ABC, abstractmethod
from collections import defaultdict
from collections.abc import Iterable
from concurrent import futures
from dataclasses import dataclass
from itertools import repeat
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
Generic,
List,
Optional,
Type,
TypeAlias,
TypeVar,
cast,
)
import numpy as np
import torch
from tensorrt_llm._torch.pyexecutor.make_decoding_batch_input_output import (
MakeDecodingBatchInputOutput,
)
from tensorrt_llm._utils import (
maybe_pin_memory,
mpi_disabled,
nvtx_range,
prefer_pinned,
torch_dtype_to_binding,
)
from tensorrt_llm.bindings import (
CudaStream,
DataType,
ModelConfig,
SamplingConfigVector,
WorldConfig,
make_sampling_config,
)
from tensorrt_llm.bindings.executor import DecodingConfig, DecodingMode, FinishReason
from tensorrt_llm.bindings.internal.algorithms import CreateNewDecoderRequests
from tensorrt_llm.bindings.internal.batch_manager import (
DecoderInputBuffers,
add_new_tokens_to_requests,
make_decoding_batch_input,
)
from tensorrt_llm.bindings.internal.runtime import (
BufferManager,
CudaEvent,
DecoderState,
GptDecoderBatched,
)
from tensorrt_llm.executor.result import Logprob
from tensorrt_llm.llmapi.llm_args import KvCacheConfig
from tensorrt_llm.mapping import Mapping
from tensorrt_llm.sampling_params import LogprobMode, SamplingParams
from ..flashinfer_utils import IS_FLASHINFER_AVAILABLE
from ..speculative.interface import get_force_num_accepted_tokens
from ..speculative.spec_tree_manager import SpecTreeManager
from .finish_reason import FinishedState
from .llm_request import LlmRequest, LlmRequestState, get_draft_token_length
from .resource_manager import ResourceManager, ResourceManagerType
from .sampling_utils import (
BEAM_SEARCH_PAD_TOKEN,
GREEDY,
BeamSearchMetadata,
GenericStrategyKeyType,
SimpleGroupedStrategySampler,
Strategy,
StrategyMetadata,
UtilsSamplingParams,
_Fusions,
get_rejected_indices,
resolve_sampling_strategy,
sample,
sample_rejected,
torch_multi_arange,
)
from .scheduler import ScheduledRequests
if sys.version_info[:2] >= (3, 12):
from typing import override
else:
from typing_extensions import override
if TYPE_CHECKING:
from transformers import PretrainedConfig
from tensorrt_llm._torch.models.modeling_utils import DecoderModel, DecoderModelForCausalLM
from .sampling_utils_flashinfer import FlashInferGroupedStrategySampler
_ModelType = TypeVar("_ModelType", bound=DecoderModel)
_ConfigType = TypeVar("_ConfigType", bound=PretrainedConfig)
T = TypeVar("T")
@dataclass(kw_only=True)
class LogProbsState:
sampled_vals: torch.Tensor
sampled_indices: torch.Tensor
sampled_rank: torch.Tensor
topk_vals: torch.Tensor
topk_indices: torch.Tensor
_LogProbsFloatState: TypeAlias = list[list[list[float]]]
_LogProbsIntState: TypeAlias = list[list[list[int]]]
@dataclass(kw_only=True)
class LogProbsStateList:
sampled_vals: _LogProbsFloatState
sampled_indices: _LogProbsIntState
sampled_rank: _LogProbsIntState
topk_vals: _LogProbsFloatState
topk_indices: _LogProbsIntState
@staticmethod
def from_logprobs_state(logprobs_state: LogProbsState) -> "LogProbsStateList":
return LogProbsStateList(
sampled_vals=logprobs_state.sampled_vals.tolist(),
sampled_indices=logprobs_state.sampled_indices.tolist(),
topk_vals=logprobs_state.topk_vals.tolist(),
topk_indices=logprobs_state.topk_indices.tolist(),
sampled_rank=logprobs_state.sampled_rank.tolist(),
)
@dataclass(kw_only=True)
class SampleStateTensors:
new_tokens: torch.Tensor
log_probs: torch.Tensor | None = None
@dataclass(kw_only=True)
class SamplerEvent:
cuda_event: torch.cuda.Event
worker_futures: Optional[list[futures.Future[Any]]] = None
def synchronize(self) -> None:
if self.worker_futures:
futures.wait(self.worker_futures)
self.cuda_event.synchronize()
GenericSampleStateTensorsHost = TypeVar("GenericSampleStateTensorsHost", bound=SampleStateTensors)
GenericSampleStateTensorsDevice = TypeVar(
"GenericSampleStateTensorsDevice", bound=SampleStateTensors
)
@dataclass(kw_only=True)
class SampleState(Generic[GenericSampleStateTensorsHost, GenericSampleStateTensorsDevice]):
requests: list[LlmRequest]
device: Optional[GenericSampleStateTensorsDevice] = None
host: Optional[GenericSampleStateTensorsHost] = None
sampler_event: Optional[SamplerEvent] = None
runtime_draft_len: Optional[int] = None
# Generic bounds not supported, https://github.com/python/typing/issues/548
GenericSampleState = TypeVar("GenericSampleState", bound=SampleState) # type: ignore
class Sampler(ABC, Generic[GenericSampleState]):
def setup_sampler_step(self, scheduled_requests: ScheduledRequests) -> None:
pass
def get_cache_indirection(self) -> torch.Tensor | None:
return None
@abstractmethod
def sample_async(
self,
scheduled_requests: ScheduledRequests,
model_outputs: dict[str, Any],
num_context_logits_prefix_sum: list[int],
resource_manager: Optional[ResourceManager] = None,
) -> GenericSampleState:
raise NotImplementedError
@abstractmethod
def update_requests(
self,
state: GenericSampleState,
resource_manager: Optional[ResourceManager] = None,
) -> None:
raise NotImplementedError
@staticmethod
def beam_width(requests: Iterable[LlmRequest]) -> int:
for req in requests:
return cast(int, req.sampling_config.beam_width)
return 0
@abstractmethod
def is_generation_model(self) -> bool:
raise NotImplementedError
def validate_request(self, request: LlmRequest) -> None:
"""Validate that the request can be processed by the sampler.
If the request is not supported by the sampler, this should raise an
appropriate exception.
Args:
request: The request to validate
Returns:
None if request is valid
Raises:
Appropriate exception if request is not supported by sampler.
"""
def should_provide_draft_probs(self, request: LlmRequest) -> bool:
"""Check if sampler wants to receive draft token probabilities."""
return True # conservative default
class EarlyStopSampler(Sampler[SampleState[SampleStateTensors, SampleStateTensors]]):
"""
Use for skipping decoding step for non generation model,
such as encoder-only model (e.g., BERT) or reward models that only need context phase.
"""
SampleState: TypeAlias = SampleState[SampleStateTensors, SampleStateTensors]
@override
def sample_async(
self,
scheduled_requests: ScheduledRequests,
model_outputs: dict[str, Any],
num_context_logits_prefix_sum: list[int],
resource_manager: Optional[ResourceManager] = None,
) -> SampleState:
host = SampleStateTensors(new_tokens=torch.empty(0))
assert not scheduled_requests.generation_requests
return self.SampleState(requests=scheduled_requests.context_requests, host=host)
@override
def update_requests(
self,
state: SampleState,
resource_manager: Optional[ResourceManager] = None,
) -> None:
assert isinstance(state, SampleState)
requests = state.requests
for idx, request in enumerate(requests):
request.state = LlmRequestState.GENERATION_COMPLETE
# NOTE: This is a hack: set finish reason manually and set the beam 0
request.set_finished_reason(FinishReason.LENGTH, 0)
@override
def is_generation_model(self) -> bool:
return False
@dataclass(kw_only=True)
class MultimodalResult:
mm_embeddings: List[torch.Tensor]
# Can be used to include e.g. `mrope_position_ids`, etc.
extra_data: Optional[Dict[str, Any]] = None
@dataclass(kw_only=True)
class SampleStateWithMMResult(SampleState[SampleStateTensors, SampleStateTensors]):
data: MultimodalResult
@dataclass(kw_only=True, frozen=True, slots=True)
class RequestGroupKey(Generic[GenericStrategyKeyType]): # type: ignore[misc]
strategy_key: GenericStrategyKeyType
needs_probs: bool
@dataclass(kw_only=True, frozen=True)
class RequestGroupValue:
indices: torch.Tensor
strategies: list[Strategy]
speculation_needs_probs_indices: torch.Tensor
need_processed_logprobs: torch.Tensor
need_raw_logprobs: torch.Tensor
@dataclass(kw_only=True, frozen=True)
class RequestGroupValueWithMetadata(RequestGroupValue):
metadata: StrategyMetadata | None
class EarlyStopWithMMResult(Sampler[SampleStateWithMMResult]):
"""
Use for skipping decoding step for non generation model, and return the batch_output (such as mm_embeddings)
"""
SampleState: TypeAlias = SampleStateWithMMResult
@override
def sample_async(
self,
scheduled_requests: ScheduledRequests,
model_outputs: dict[str, Any],
num_context_logits_prefix_sum: list[int],
resource_manager: Optional[ResourceManager] = None,
) -> SampleState:
# from model_outputs to MultimodalResult
data = MultimodalResult(
mm_embeddings=model_outputs.pop("mm_embeddings"),
extra_data={**model_outputs},
)
assert not scheduled_requests.generation_requests
return self.SampleState(requests=scheduled_requests.context_requests, data=data)
@override
def update_requests(
self,
state: SampleState,
resource_manager: Optional[ResourceManager] = None,
) -> None:
# resource_manager will not be used in this function, just for interface consistency.
assert isinstance(state, SampleState)
requests = state.requests
mm_embeddings = state.data.mm_embeddings
extra_data = state.data.extra_data or {}
mrope_position_ids = extra_data.get("mrope_position_ids", None)
mrope_position_deltas = extra_data.get("mrope_position_deltas", None)
for i, (request, mm_embedding) in enumerate(zip(requests, mm_embeddings)):
request.state = LlmRequestState.GENERATION_COMPLETE
# NOTE: This is a hack: set finish reason manually and set the beam 0
request.set_finished_reason(FinishReason.LENGTH, 0)
assert request.multimodal_lengths is not None
if len(mm_embedding) != sum(request.multimodal_lengths):
raise ValueError(
f"mm_embedding shape mismatch: {len(mm_embedding)} != {sum(request.multimodal_lengths)}"
)
request.py_result.append_mm_embeddings(mm_embedding, request.multimodal_lengths)
# Store mrope data if available
if mrope_position_ids is not None and mrope_position_deltas is not None:
request.py_result.set_mrope_position(
mrope_position_ids[i], mrope_position_deltas[i]
)
@override
def is_generation_model(self) -> bool:
return False
# Due to tensorrt_llm::runtime::SamplingConfig using vectors, params
# in LlmRequest.sampling_params are either None or single-element lists.
# This helper method simplifies code using such params.
def _unwrap_singleton(p: Optional[List[T]]) -> Optional[T]:
if p is None:
return None
(t,) = p
return t
def _get_beam_width_in(request: LlmRequest) -> int:
return (
1
if request.is_context_init_state
else request.get_beam_width_by_iter(for_next_iteration=False)
)
def _get_beam_width_out(request: LlmRequest) -> int:
return request.get_beam_width_by_iter(for_next_iteration=True)
def _get_max_beam_width(request: LlmRequest) -> int:
sampling_config = request.sampling_config
max_beam_width = cast(int, sampling_config.beam_width)
if sampling_config.beam_width_array is not None:
max_beam_width = max(
max_beam_width,
cast(
int, torch.tensor(sampling_config.beam_width_array, dtype=torch.int32).max().item()
),
)
return max_beam_width
def _request_get_sampling_params(request: LlmRequest) -> UtilsSamplingParams:
sampling_config = request.sampling_config
temperature = _unwrap_singleton(cast(Optional[list[float]], sampling_config.temperature))
top_p = _unwrap_singleton(cast(Optional[list[float]], sampling_config.top_p))
top_k = _unwrap_singleton(cast(Optional[list[int]], sampling_config.top_k))
beam_width_out = _get_beam_width_out(request)
beam_width_in = _get_beam_width_in(request)
use_beam_search = _get_max_beam_width(request) > 1
return UtilsSamplingParams(
temperature=temperature,
top_p=top_p,
top_k=top_k,
beam_width_in=beam_width_in,
beam_width_out=beam_width_out,
use_beam_search=use_beam_search,
)
def _request_sampling_params_cachable(params: UtilsSamplingParams) -> bool:
return not params.use_beam_search
def _request_strategy(request: LlmRequest, *, vocab_size: int) -> Strategy:
# We try to cache the resolved strategy on the request object, as it's not cheap enough to
# resolve it on every iteration.
cached_sampling_strategy = request.py_sampling_strategy
if cached_sampling_strategy is not None:
return cached_sampling_strategy
params = _request_get_sampling_params(request)
sampling_strategy = resolve_sampling_strategy(params, vocab_size=vocab_size)
if _request_sampling_params_cachable(params):
request.py_sampling_strategy = sampling_strategy
return sampling_strategy
class _CachingRequestGrouper(Generic[GenericStrategyKeyType]):
"""Efficiently groups requests for batched sampling."""
@dataclass(kw_only=True)
class _Store:
"""Auxiliary data structures used for efficiently grouping requests for batched sampling."""
slots_needing_recompute: set[int]
"""Slots where strategy needs (re)computation. Populated in setup_sampler_step."""
non_greedy_slots: set[int]
"""Slots with non-greedy strategies. Used to limit draft-token checks."""
need_processed_logprobs: list[bool]
"""Length: max_num_sequences. True if logprob mode is PROCESSED and return_log_probs is set."""
need_raw_logprobs: list[bool]
"""Length: max_num_sequences. True if logprob mode is RAW and return_log_probs is set."""
speculation_needs_probs: list[bool]
"""Length: max_num_sequences. True if request has draft tokens and non-greedy sampling."""
needs_probs: list[bool]
"""Length: max_num_sequences. True if speculation_needs_probs or need_processed_logprobs."""
strategies: list[Strategy | None]
"""Length: max_num_sequences. Stores cached Strategy tuple for each seq_slot."""
uses_beam_search: list[bool]
"""Length: max_num_sequences. True if max_beam_width > 1 for this slot."""
def __init__(self, max_num_sequences: int):
# Use Python lists instead of tensors to avoid .item() overhead in hot loops
speculation_needs_probs = [False] * max_num_sequences
need_processed_logprobs = [False] * max_num_sequences
need_raw_logprobs = [False] * max_num_sequences
needs_probs = [False] * max_num_sequences
strategies: list[Strategy | None] = [None] * max_num_sequences
uses_beam_search = [False] * max_num_sequences
slots_needing_recompute: set[int] = set()
non_greedy_slots: set[int] = set()
self._store = self._Store(
speculation_needs_probs=speculation_needs_probs,
need_processed_logprobs=need_processed_logprobs,
need_raw_logprobs=need_raw_logprobs,
needs_probs=needs_probs,
strategies=strategies,
uses_beam_search=uses_beam_search,
slots_needing_recompute=slots_needing_recompute,
non_greedy_slots=non_greedy_slots,
)
def prepare_for_new_request(self, request: LlmRequest, slot: int) -> None:
store = self._store
# Initialize cached data for this slot (prevents stale data from previous request)
store.strategies[slot] = None
store.uses_beam_search[slot] = _get_max_beam_width(request) > 1
# Mark slot for strategy recomputation in _group_requests_by_strategy_key
store.slots_needing_recompute.add(slot)
store.non_greedy_slots.discard(slot) # reset until strategy is computed
def group_requests_by_strategy_key(
self,
requests: Iterable[LlmRequest],
*,
strategy_to_key: Callable[[Strategy], GenericStrategyKeyType],
pin_memory: bool = False,
seq_slots: torch.Tensor,
vocab_size: int,
) -> dict[RequestGroupKey[GenericStrategyKeyType], RequestGroupValue]:
"""
Optimized implementation with vectorized boolean operations and efficient grouping.
NB: Client code relies on request indices in returned torch.Tensor being sorted.
"""
store = self._store
# Convert to list for efficient indexing
requests_list = list(requests) if not isinstance(requests, list) else requests
num_requests = len(requests_list)
if num_requests == 0:
return {}
assert not seq_slots.is_cuda, "seq_slots is expected to be a host tensor"
seq_slots_list = seq_slots.tolist()
# Get strategies from cache, only recomputing for slots that need it.
# Recompute is needed for:
# - Uncached slots (strategy is None) — recorded in store.slots_needing_recompute
# - Beam search (beam_width_in changes) — kept in slots_needing_recompute permanently
# - Speculative decoding (draft_tokens can change) — checked for non-greedy slots only
# Build strategies from cache in one shot (C-level list comprehension, ~50ns/elem)
s_strategies = store.strategies
batch_strategies = [s_strategies[slot] for slot in seq_slots_list]
# Build slot→request_index mapping for targeted access
slot_to_idx = {slot: i for i, slot in enumerate(seq_slots_list)}
active_slots = set(slot_to_idx)
# 1) Slots pre-recorded for recompute (context-phase or beam search)
recompute_batch_slots = store.slots_needing_recompute & active_slots
# 2) Non-greedy slots where draft-token status may have changed
# (For greedy: current_has_draft is always False, matching cached, so never stale)
draft_check_slots = (store.non_greedy_slots & active_slots) - recompute_batch_slots
for slot in draft_check_slots:
batch_index = slot_to_idx[slot]
has_draft = bool(requests_list[batch_index].py_draft_tokens)
if store.speculation_needs_probs[slot] != has_draft:
# Draft-token status changed — only update the affected flags.
# The strategy itself doesn't depend on draft tokens (only on sampling params).
store.speculation_needs_probs[slot] = has_draft
store.needs_probs[slot] = has_draft or store.need_processed_logprobs[slot]
# 3) Full recompute for the pre-recorded slots.
# Every slot with a None strategy must already be in slots_needing_recompute
# (populated by setup_sampler_step when a new request arrives).
assert None not in batch_strategies or all(
seq_slots_list[batch_index] in recompute_batch_slots
for batch_index in range(num_requests)
if batch_strategies[batch_index] is None
), (
"Found slots with uncached strategies not registered in slots_needing_recompute. "
"Ensure setup_sampler_step is called before sample_async for new requests."
)
for slot in recompute_batch_slots:
batch_index = slot_to_idx[slot]
request = requests_list[batch_index]
has_draft_tokens = bool(request.py_draft_tokens)
strategy = _request_strategy(request, vocab_size=vocab_size)
store.strategies[slot] = strategy
batch_strategies[batch_index] = strategy
is_greedy = strategy == GREEDY
current_speculation_needs_probs = has_draft_tokens and not is_greedy
store.speculation_needs_probs[slot] = current_speculation_needs_probs
current_need_processed_logprobs = (
request.py_logprobs_mode == LogprobMode.PROCESSED and request.return_log_probs
)
store.need_processed_logprobs[slot] = current_need_processed_logprobs
store.need_raw_logprobs[slot] = (
request.py_logprobs_mode == LogprobMode.RAW and request.return_log_probs
)
store.needs_probs[slot] = (
current_speculation_needs_probs or current_need_processed_logprobs
)
# Track non-greedy slots for future draft-token checks
if is_greedy:
store.non_greedy_slots.discard(slot)
else:
store.non_greedy_slots.add(slot)
# Keep beam-search slots in the recompute set (they always need it);
# remove everything else (strategy is now cached).
if not store.uses_beam_search[slot]:
store.slots_needing_recompute.discard(slot)
# Gather flags using list comprehension (faster than append in loop)
needs_probs = torch.tensor(
[store.needs_probs[slot] for slot in seq_slots_list], dtype=torch.bool, device="cpu"
)
speculation_needs_probs = torch.tensor(
[store.speculation_needs_probs[slot] for slot in seq_slots_list],
dtype=torch.bool,
device="cpu",
)
need_processed_logprobs = torch.tensor(
[store.need_processed_logprobs[slot] for slot in seq_slots_list],
dtype=torch.bool,
device="cpu",
)
need_raw_logprobs = torch.tensor(
[store.need_raw_logprobs[slot] for slot in seq_slots_list],
dtype=torch.bool,
device="cpu",
)
# Build strategy ID mapping for vectorized comparison (all on CPU).
# NB: set() does not preserve insertion order, so we use dict.fromkeys() to deduplicate while preserving order.
unique_strategies = list(dict.fromkeys(batch_strategies))
strategy_to_id = {s: idx for idx, s in enumerate(unique_strategies)}
strategy_ids = torch.tensor(
[strategy_to_id[s] for s in batch_strategies], dtype=torch.int32, device="cpu"
)
# Pre-allocate group_ids array
group_ids = torch.empty(num_requests, dtype=torch.int32, device="cpu")
_next_gid = 0
def _provision_gid() -> int:
nonlocal _next_gid
gid = _next_gid
_next_gid += 1
return gid
unique_keys: defaultdict[tuple[GenericStrategyKeyType, bool], int] = defaultdict(
_provision_gid
)
# Vectorized assignment: loop over unique combinations instead of all requests
for sid, strategy in enumerate(unique_strategies):
strat_mask = strategy_ids == sid
for needs_probs_val in (False, True):
# Vectorized mask for this (strategy, needs_probs) group
mask = strat_mask & (needs_probs if needs_probs_val else ~needs_probs)
if torch.any(mask):
strategy_key = strategy_to_key(strategy) # Called once per group!
key = (strategy_key, needs_probs_val)
group_ids[mask] = unique_keys[key] # Vectorized assignment
# Efficient grouping using sort
sorted_group_ids, sorted_order = torch.sort(group_ids, stable=True)
# Use prepend to detect a "change" at position 0, giving us group_starts directly
group_starts = torch.nonzero(
torch.diff(sorted_group_ids, prepend=torch.tensor([-1], device="cpu")) != 0
).squeeze(1)
group_ends = torch.cat([group_starts[1:], torch.tensor([num_requests], device="cpu")])
# Since groups are assigned in request order, gid → key is just list indexing
id_to_key = list(unique_keys)
# Build result dictionary efficiently
result: dict[RequestGroupKey[GenericStrategyKeyType], RequestGroupValue] = {}
for gid, (start, end) in enumerate(zip(group_starts.tolist(), group_ends.tolist())):
group_sorted_indices = sorted_order[start:end]
strategy_key, needs_probs_bool = id_to_key[gid]
indices_arr = group_sorted_indices.to(torch.int32)
# Convert to list for Python list indexing
group_sorted_indices_list = group_sorted_indices.tolist()
group_strategies = [
batch_strategies[batch_index] for batch_index in group_sorted_indices_list
]
spec_mask = speculation_needs_probs[group_sorted_indices]
spec_indices = indices_arr[spec_mask]
processed_flags = need_processed_logprobs[group_sorted_indices]
raw_flags = need_raw_logprobs[group_sorted_indices]
if pin_memory:
indices_tensor = maybe_pin_memory(indices_arr)
spec_tensor = maybe_pin_memory(spec_indices)
processed_tensor = maybe_pin_memory(processed_flags)
raw_tensor = maybe_pin_memory(raw_flags)
else:
indices_tensor = indices_arr
spec_tensor = spec_indices
processed_tensor = processed_flags
raw_tensor = raw_flags
result[RequestGroupKey(strategy_key=strategy_key, needs_probs=needs_probs_bool)] = (
RequestGroupValue(
indices=indices_tensor,
strategies=group_strategies,
speculation_needs_probs_indices=spec_tensor,
need_processed_logprobs=processed_tensor,
need_raw_logprobs=raw_tensor,
)
)
return result
def add_token(
request: LlmRequest, new_tokens: list[list[list[int]]], *, beam_idx: int, step: int = 0
) -> int:
# NB: Accessing nested lists faster than torch.Tensor or numpy.ndarray
seq_slot = request.py_seq_slot
assert seq_slot is not None
new_token = new_tokens[step][seq_slot][beam_idx]
request.add_new_token(new_token, beam_idx)
return new_token
def int_tensor(shape: tuple[int, ...], device: str = "cuda") -> torch.Tensor:
return torch.empty(shape, dtype=torch.int, device=device)
@dataclass(kw_only=True, frozen=True)
class _BatchedSamplingResult:
# Original request indices for all requests (permuted due to batching by strategy):
batch_req_indices: torch.Tensor
# Next tokens for all requests:
batch_next_tokens_cuda_int: torch.Tensor
# Logits for all requests used for logprobs:
batch_logits_for_logprobs_cuda: torch.Tensor | None = None
# Helper class for _PackedStepIndexer and _UnpackedStepIndexer, facilitating the
# selection of memory locations of tokens associated with given sets of requests.
class _StepIndexTranslator(ABC):
def __init__(
self,
*,
num_steps: torch.Tensor,
req_offsets: Optional[torch.Tensor] = None,
max_steps: Optional[int] = None,
index_dtype: Optional[torch.dtype] = None,
):
"""Build the index.
Arguments:
index_dtype: torch.dtype to use for indices (defaults to torch.int32).
num_steps (index_dtype): Number of steps/tokens for each request
req_offsets (index_dtype): Index offset at which the data for each request starts.
If not provided, it is computed using calculate_request_offsets(),
which assumes dense packing.
max_steps (int): The largest value allowed to occur in num_steps.
If not provided, it is computed from num_steps.
"""
if req_offsets is None:
req_offsets, _ = self.calculate_request_offsets(num_steps)
if max_steps is None:
max_steps = cast(int, num_steps.max().item())
self._index_map, self._index_mask = self._build_index(
req_offsets=req_offsets,
num_steps=num_steps,
max_steps=max_steps,
index_dtype=(index_dtype or torch.int32),
)
@staticmethod
def calculate_request_offsets(
req_num_steps: torch.Tensor,
pin_memory: bool = False,
) -> tuple[torch.Tensor, int]:
if req_num_steps.numel():
req_offsets = torch.cumsum(req_num_steps, 0)
sum_steps = int(req_offsets[-1].item())
req_offsets_rolled = torch.empty_like(req_offsets, pin_memory=pin_memory)
req_offsets_rolled[1:] = req_offsets[:-1]
req_offsets_rolled[0] = 0
req_offsets = req_offsets_rolled
else:
req_offsets = torch.empty_like(req_num_steps, pin_memory=pin_memory)
sum_steps = 0
return req_offsets, sum_steps
def _build_index(
self,
req_offsets: torch.Tensor,
num_steps: torch.Tensor,
max_steps: int,
index_dtype: torch.dtype,
) -> tuple[torch.Tensor, torch.Tensor]:
steps_dim = torch.arange(max_steps, device=num_steps.device, dtype=index_dtype)
valid_mask = steps_dim.unsqueeze(0) < num_steps.unsqueeze(-1)
indices = self._compute_index_map(
index_dtype=index_dtype,
steps_dim=steps_dim,
req_offsets=req_offsets,
)
# NB: steps_dim and req_offsets may have been overwritten by this point.
return indices, valid_mask
@abstractmethod
def _compute_index_map(
self,
index_dtype: torch.dtype,
steps_dim: torch.Tensor,
req_offsets: torch.Tensor,
) -> torch.Tensor:
"""Compute full tensor index map.
Should return a tensor of shape (len(num_steps), max_steps) containing the linear
token index (index_dtype) corresponding to a given request and decoding step.
Each row corresponds to a request (same ordering as 'req_offsets' and 'num_steps'),
and the columns correspond to decoding steps 0, ..., num_steps[i]. Entries corresponding
to decoding steps which are invalid for the given request are masked elsewhere within
_StepIndexTranslator.
This method is allowed to repurpose/overwrite 'steps_dim' and 'req_offsets'.
Arguments:
num_steps (index_dtype): Number of steps/tokens for each request
req_offsets (index_dtype): Index offset at which the data for each request starts.
steps_dim (index_dtype): arange(max_steps)
index_dtype: torch.dtype to use for indices
"""
def __getitem__(self, req_indices: Any) -> torch.Tensor:
"""Gather indices for a given set of requests.
Arguments:
req_indices: Any 1d torch-compatible indexing expression to select requests, corresponds
to the linear indices of the entries in 'num_steps' and 'req_offsets' (cf. __init__).
Returns:
Array of linear indices (index_dtype) selecting the tokens/steps associated
with the requests identified by req_indices, in the same order as
req_indices.
"""
indices = self._index_map[req_indices].view(-1)
mask = self._index_mask[req_indices].view(-1)
# NB: Return value has dynamic shape (depends on mask nnz), which
# implies stream sync if CUDA is used.
return indices[mask]
# Helper class for _PackedStepIndexer and _UnpackedStepIndexer, facilitating the
# selection of memory locations of tokens associated with given sets of requests,
# for memory layouts that can be parametrized via request offsets and step stride.
class _StridedStepIndexTranslator(_StepIndexTranslator):
def __init__(
self,
*,
num_steps: torch.Tensor,
req_offsets: Optional[torch.Tensor] = None,
max_steps: Optional[int] = None,
index_dtype: Optional[torch.dtype] = None,
step_stride: Optional[int] = None,
):
"""Build the index.
Allows to specify a custom stride for steps dimension.
Arguments:
index_dtype: torch.dtype to use for indices (defaults to torch.int32).
num_steps (index_dtype): Number of steps/tokens for each request
req_offsets (index_dtype): Index offset at which the data for each request starts.
If not provided, it is computed using calculate_request_offsets(),
assuming dense packing of tokens (grouped by request). Overriding
this also allows for "request major" indexing into rectangular
tensors.
max_steps (int): The largest value allowed to occur in num_steps.
If not provided, it is computed from 'num_steps'.
step_stride: Additional stride to multiply 'steps_dim' with (defaults to 1). Allows,
e.g., "step major" indexing into rectangular tensors.
"""
self._step_stride = step_stride
super().__init__(
num_steps=num_steps,
req_offsets=req_offsets,
max_steps=max_steps,
index_dtype=index_dtype,
)
@override
def _compute_index_map(
self,
index_dtype: torch.dtype,
steps_dim: torch.Tensor,
req_offsets: torch.Tensor,
) -> torch.Tensor:
if self._step_stride is not None:
steps_dim *= self._step_stride # in-place OK
return req_offsets.unsqueeze(-1) + steps_dim.unsqueeze(0)
# In sample_async(), each request contains a different number of output positions
# (a.k.a. 'steps') and 'logits_cuda' (and other tensors derived from it) packs those
# tokens into a single contiguous array, with the 'step' axis being the rapidly
# changing one.
#
# The class below builds an index to simplify selecting the linear indices of the
# tokens associated with a given set of requests.
#
# NB: Consider switching to torch.nested (cf. https://github.com/pytorch/pytorch/issues/80577)
class _PackedStepIndexer(_StridedStepIndexTranslator):
def __init__(
self,
*,
num_steps: torch.Tensor,
req_offsets: Optional[torch.Tensor] = None,
max_steps: Optional[int] = None,
index_dtype: Optional[torch.dtype] = None,
):
"""Build the index.
Arguments:
index_dtype: torch.dtype to use for indices (defaults to torch.int32).
num_steps (index_dtype): Number of steps/tokens for each request
req_offsets (index_dtype): Index offset at which the data for each request starts.
If not provided, it is computed using calculate_request_offsets().
max_steps (int): The largest value allowed to occur in num_steps.
If not provided, it is computed from 'num_steps'.
"""
super().__init__(
num_steps=num_steps,
req_offsets=req_offsets,
max_steps=max_steps,
index_dtype=index_dtype,
)
# After gathering results with _PackedStepIndexer in TorchSampler._sample_batched_by_strategy,
# they need to be scattered into result buffers in TorchSampler._unbatch_sampling_results.
# This helper class provides the translation from linear packed request + step/token indices
# to unpacked / rectangular-tensor (but still linearized) request + step/token indices.
#
# NB: Consider switching to torch.nested (cf. https://github.com/pytorch/pytorch/issues/80577)
class _UnpackedStepIndexer(_StridedStepIndexTranslator):
class DimOrder(enum.Enum):
SLOT_MAJOR = enum.auto()
STEP_MAJOR = enum.auto()
def __init__(
self,
*,
seq_slots: torch.Tensor,
num_steps: torch.Tensor,
dim_order: DimOrder = DimOrder.SLOT_MAJOR,
steps_dim_size: int,
slots_dim_size: Optional[int] = None,
index_dtype: Optional[torch.dtype] = None,
):
"""Build the index.
Arguments:
index_dtype: torch.dtype to use for indices (defaults to torch.int32).
seq_slots (index_dtype): Request indices in unpacked tensor, enumerated in packed tensor
request order.
num_steps (index_dtype): Number of steps/tokens for each request
dim_order: Memory layout of indexed tensor.
steps_dim_size (int): The extent of the step dimension in the unpacked tensor.
slots_dim_size (int): The extent of the slot dimension in the unpacked tensor.
Required if dim_order is DimOrder.STEP_MAJOR.
"""
if dim_order is self.DimOrder.SLOT_MAJOR:
super().__init__(
num_steps=num_steps,
req_offsets=(steps_dim_size * seq_slots),
max_steps=steps_dim_size,
index_dtype=index_dtype,
)
elif dim_order is self.DimOrder.STEP_MAJOR:
if slots_dim_size is None:
raise ValueError("slots_dim_size required for step-major order")
super().__init__(
num_steps=num_steps,
req_offsets=seq_slots, # no need for stride here
max_steps=steps_dim_size,
index_dtype=index_dtype,
step_stride=slots_dim_size,
)
else:
raise ValueError(f"Invalid dim_order: {dim_order}")
# Beam index to use when no beam search is used but a beam index is required
DEFAULT_BEAM_IDX = 0
# Step index to use when no speculative decoding is used but a step index is required
DEFAULT_STEP_IDX = 0
FinishReasonsList: TypeAlias = list[list[list[int]]]
@dataclass(kw_only=True)
class BeamHistory:
"""
Beam history class for beam search.
This class is used to store the corrected tokens and logprobs for each beam.
It is used to update the beam history for each beam.
"""
tokens: torch.Tensor
logprobs: torch.Tensor | None = None
logprobs_indices: torch.Tensor | None = None
cum_logprobs: torch.Tensor | None = None