tpu-inference 0.0.1rc1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of tpu-inference might be problematic. Click here for more details.

Files changed (174) hide show
  1. tests/__init__.py +0 -0
  2. tests/core/__init__.py +0 -0
  3. tests/core/test_core_tpu.py +513 -0
  4. tests/core/test_disagg_executor.py +60 -0
  5. tests/core/test_disagg_utils.py +53 -0
  6. tests/core/test_dp_scheduler.py +899 -0
  7. tests/core/test_init.py +49 -0
  8. tests/kernels/__init__.py +0 -0
  9. tests/kernels/fused_moe_v1_test.py +374 -0
  10. tests/kernels/mla_v1_test.py +396 -0
  11. tests/kernels/quantized_matmul_kernel_test.py +191 -0
  12. tests/kernels/ragged_kv_cache_update_v2_test.py +234 -0
  13. tests/kernels/ragged_paged_attention_kernel_v2_test.py +400 -0
  14. tests/kernels/ragged_paged_attention_kernel_v3_hd64_test.py +549 -0
  15. tests/kernels/ragged_paged_attention_kernel_v3_test.py +504 -0
  16. tests/lora/__init__.py +0 -0
  17. tests/lora/conftest.py +32 -0
  18. tests/lora/test_bgmv.py +43 -0
  19. tests/lora/test_layers.py +648 -0
  20. tests/lora/test_lora.py +133 -0
  21. tests/lora/utils.py +88 -0
  22. tests/test_base.py +201 -0
  23. tests/test_envs.py +203 -0
  24. tests/test_quantization.py +836 -0
  25. tests/test_tpu_info.py +120 -0
  26. tests/test_utils.py +235 -0
  27. tpu_inference/__init__.py +53 -0
  28. tpu_inference/core/__init__.py +0 -0
  29. tpu_inference/core/core_tpu.py +786 -0
  30. tpu_inference/core/disagg_executor.py +118 -0
  31. tpu_inference/core/disagg_utils.py +49 -0
  32. tpu_inference/core/sched/__init__.py +0 -0
  33. tpu_inference/core/sched/dp_scheduler.py +523 -0
  34. tpu_inference/distributed/__init__.py +0 -0
  35. tpu_inference/distributed/jax_parallel_state.py +67 -0
  36. tpu_inference/distributed/tpu_connector.py +727 -0
  37. tpu_inference/distributed/utils.py +60 -0
  38. tpu_inference/env_override.py +9 -0
  39. tpu_inference/envs.py +160 -0
  40. tpu_inference/executors/__init__.py +0 -0
  41. tpu_inference/executors/ray_distributed_executor.py +382 -0
  42. tpu_inference/experimental/__init__.py +0 -0
  43. tpu_inference/experimental/llama3_jax_stashed.py +258 -0
  44. tpu_inference/kernels/__init__.py +0 -0
  45. tpu_inference/kernels/collectives/__init__.py +0 -0
  46. tpu_inference/kernels/collectives/all_gather_matmul.py +735 -0
  47. tpu_inference/kernels/collectives/all_gather_matmul_tuned_block_sizes.py +60 -0
  48. tpu_inference/kernels/collectives/util.py +47 -0
  49. tpu_inference/kernels/flash_attention/__init__.py +0 -0
  50. tpu_inference/kernels/flash_attention/kernel.py +772 -0
  51. tpu_inference/kernels/fused_moe/__init__.py +0 -0
  52. tpu_inference/kernels/fused_moe/v1/__init__.py +0 -0
  53. tpu_inference/kernels/fused_moe/v1/kernel.py +1566 -0
  54. tpu_inference/kernels/mla/__init__.py +0 -0
  55. tpu_inference/kernels/mla/v1/__init__.py +0 -0
  56. tpu_inference/kernels/mla/v1/kernel.py +1349 -0
  57. tpu_inference/kernels/quantized_matmul/__init__.py +0 -0
  58. tpu_inference/kernels/quantized_matmul/kernel.py +395 -0
  59. tpu_inference/kernels/quantized_matmul/tuned_block_sizes.py +609 -0
  60. tpu_inference/kernels/quantized_matmul/util.py +58 -0
  61. tpu_inference/kernels/ragged_paged_attention/__init__.py +0 -0
  62. tpu_inference/kernels/ragged_paged_attention/v2/__init__.py +0 -0
  63. tpu_inference/kernels/ragged_paged_attention/v2/kernel.py +875 -0
  64. tpu_inference/kernels/ragged_paged_attention/v2/ragged_kv_cache_update.py +287 -0
  65. tpu_inference/kernels/ragged_paged_attention/v2/tuned_block_sizes.py +1482 -0
  66. tpu_inference/kernels/ragged_paged_attention/v3/__init__.py +0 -0
  67. tpu_inference/kernels/ragged_paged_attention/v3/kernel.py +1501 -0
  68. tpu_inference/kernels/ragged_paged_attention/v3/kernel_hd64.py +1603 -0
  69. tpu_inference/kernels/ragged_paged_attention/v3/tuned_block_sizes.py +4147 -0
  70. tpu_inference/kernels/ragged_paged_attention/v3/tuned_block_sizes_hd64.py +367 -0
  71. tpu_inference/kernels/ragged_paged_attention/v3/util.py +51 -0
  72. tpu_inference/layers/__init__.py +0 -0
  73. tpu_inference/layers/common/__init__.py +0 -0
  74. tpu_inference/layers/common/attention_interface.py +396 -0
  75. tpu_inference/layers/common/attention_metadata.py +34 -0
  76. tpu_inference/layers/common/binary_search.py +295 -0
  77. tpu_inference/layers/common/quant_methods.py +8 -0
  78. tpu_inference/layers/common/sharding.py +582 -0
  79. tpu_inference/layers/jax/__init__.py +0 -0
  80. tpu_inference/layers/jax/attention/__init__.py +0 -0
  81. tpu_inference/layers/jax/attention/attention.py +255 -0
  82. tpu_inference/layers/jax/attention/deepseek_v3_attention.py +354 -0
  83. tpu_inference/layers/jax/attention/gpt_oss_attention.py +262 -0
  84. tpu_inference/layers/jax/attention/llama4_attention.py +153 -0
  85. tpu_inference/layers/jax/base.py +151 -0
  86. tpu_inference/layers/jax/constants.py +88 -0
  87. tpu_inference/layers/jax/layers.py +301 -0
  88. tpu_inference/layers/jax/misc.py +16 -0
  89. tpu_inference/layers/jax/moe/__init__.py +0 -0
  90. tpu_inference/layers/jax/moe/deepseek_v3_moe.py +608 -0
  91. tpu_inference/layers/jax/moe/gpt_oss_moe.py +185 -0
  92. tpu_inference/layers/jax/moe/moe.py +209 -0
  93. tpu_inference/layers/jax/rope.py +280 -0
  94. tpu_inference/layers/jax/rope_interface.py +214 -0
  95. tpu_inference/layers/jax/sample/__init__.py +0 -0
  96. tpu_inference/layers/jax/sample/rejection_sampler.py +515 -0
  97. tpu_inference/layers/jax/sample/sampling.py +96 -0
  98. tpu_inference/layers/jax/sample/sampling_metadata.py +76 -0
  99. tpu_inference/layers/jax/transformer_block.py +107 -0
  100. tpu_inference/layers/vllm/__init__.py +0 -0
  101. tpu_inference/layers/vllm/attention.py +221 -0
  102. tpu_inference/layers/vllm/fused_moe.py +469 -0
  103. tpu_inference/layers/vllm/linear_common.py +186 -0
  104. tpu_inference/layers/vllm/quantization/__init__.py +39 -0
  105. tpu_inference/layers/vllm/quantization/awq.py +207 -0
  106. tpu_inference/layers/vllm/quantization/common.py +110 -0
  107. tpu_inference/layers/vllm/quantization/compressed_tensors/__init__.py +0 -0
  108. tpu_inference/layers/vllm/quantization/compressed_tensors/compressed_tensors.py +120 -0
  109. tpu_inference/layers/vllm/quantization/compressed_tensors/compressed_tensors_moe.py +203 -0
  110. tpu_inference/layers/vllm/quantization/compressed_tensors/schemes/__init__.py +0 -0
  111. tpu_inference/layers/vllm/quantization/compressed_tensors/schemes/compressed_tensors_w8a8_fp8.py +208 -0
  112. tpu_inference/layers/vllm/quantization/compressed_tensors/schemes/compressed_tensors_w8a8_int8.py +136 -0
  113. tpu_inference/layers/vllm/quantization/mxfp4.py +331 -0
  114. tpu_inference/layers/vllm/quantization/unquantized.py +368 -0
  115. tpu_inference/layers/vllm/sharding.py +230 -0
  116. tpu_inference/logger.py +10 -0
  117. tpu_inference/lora/__init__.py +0 -0
  118. tpu_inference/lora/torch_lora_ops.py +103 -0
  119. tpu_inference/lora/torch_punica_tpu.py +310 -0
  120. tpu_inference/models/__init__.py +0 -0
  121. tpu_inference/models/common/__init__.py +0 -0
  122. tpu_inference/models/common/model_loader.py +478 -0
  123. tpu_inference/models/jax/__init__.py +0 -0
  124. tpu_inference/models/jax/deepseek_v3.py +868 -0
  125. tpu_inference/models/jax/gpt_oss.py +492 -0
  126. tpu_inference/models/jax/jax_intermediate_tensor.py +79 -0
  127. tpu_inference/models/jax/llama3.py +376 -0
  128. tpu_inference/models/jax/llama4.py +629 -0
  129. tpu_inference/models/jax/llama_eagle3.py +336 -0
  130. tpu_inference/models/jax/llama_guard_4.py +361 -0
  131. tpu_inference/models/jax/qwen2.py +376 -0
  132. tpu_inference/models/jax/qwen2_5_vl.py +1218 -0
  133. tpu_inference/models/jax/qwen3.py +303 -0
  134. tpu_inference/models/jax/utils/__init__.py +0 -0
  135. tpu_inference/models/jax/utils/file_utils.py +96 -0
  136. tpu_inference/models/jax/utils/multi_modal_utils.py +163 -0
  137. tpu_inference/models/jax/utils/quantization/__init__.py +0 -0
  138. tpu_inference/models/jax/utils/quantization/configs/fp8_all_modules_w_only.yaml +5 -0
  139. tpu_inference/models/jax/utils/quantization/configs/fp8_default.yaml +6 -0
  140. tpu_inference/models/jax/utils/quantization/configs/int8_all_modules_w_only.yaml +5 -0
  141. tpu_inference/models/jax/utils/quantization/configs/int8_default.yaml +6 -0
  142. tpu_inference/models/jax/utils/quantization/mxfp4_utils.py +105 -0
  143. tpu_inference/models/jax/utils/quantization/quantization_utils.py +650 -0
  144. tpu_inference/models/jax/utils/weight_utils.py +584 -0
  145. tpu_inference/models/vllm/__init__.py +0 -0
  146. tpu_inference/models/vllm/vllm_model_wrapper.py +293 -0
  147. tpu_inference/models/vllm/vllm_model_wrapper_context.py +45 -0
  148. tpu_inference/platforms/__init__.py +2 -0
  149. tpu_inference/platforms/tpu_platform.py +275 -0
  150. tpu_inference/runner/__init__.py +0 -0
  151. tpu_inference/runner/block_table.py +122 -0
  152. tpu_inference/runner/compilation_manager.py +865 -0
  153. tpu_inference/runner/input_batch.py +435 -0
  154. tpu_inference/runner/kv_cache.py +132 -0
  155. tpu_inference/runner/kv_cache_manager.py +478 -0
  156. tpu_inference/runner/lora_utils.py +92 -0
  157. tpu_inference/runner/multimodal_manager.py +217 -0
  158. tpu_inference/runner/persistent_batch_manager.py +282 -0
  159. tpu_inference/runner/speculative_decoding_manager.py +248 -0
  160. tpu_inference/runner/structured_decoding_manager.py +87 -0
  161. tpu_inference/runner/tpu_runner.py +1744 -0
  162. tpu_inference/runner/utils.py +426 -0
  163. tpu_inference/spec_decode/__init__.py +0 -0
  164. tpu_inference/spec_decode/jax/__init__.py +0 -0
  165. tpu_inference/spec_decode/jax/eagle3.py +417 -0
  166. tpu_inference/tpu_info.py +78 -0
  167. tpu_inference/utils.py +340 -0
  168. tpu_inference/worker/__init__.py +0 -0
  169. tpu_inference/worker/tpu_worker.py +458 -0
  170. tpu_inference-0.0.1rc1.dist-info/METADATA +108 -0
  171. tpu_inference-0.0.1rc1.dist-info/RECORD +174 -0
  172. tpu_inference-0.0.1rc1.dist-info/WHEEL +5 -0
  173. tpu_inference-0.0.1rc1.dist-info/licenses/LICENSE +201 -0
  174. tpu_inference-0.0.1rc1.dist-info/top_level.txt +2 -0
@@ -0,0 +1,1744 @@
1
+ import copy
2
+ import functools
3
+ import os
4
+ import random
5
+ from contextlib import nullcontext
6
+ from dataclasses import dataclass
7
+ from typing import Any, Callable, Dict, List, Optional, Tuple, cast
8
+
9
+ import jax
10
+ import jax.numpy as jnp
11
+ import jaxtyping
12
+ import numpy as np
13
+ import vllm.envs as vllm_envs
14
+ from flax import nnx
15
+ from jax.experimental import mesh_utils
16
+ from jax.sharding import NamedSharding, PartitionSpec
17
+ from torchax.ops.mappings import t2j_dtype
18
+ from vllm.config import VllmConfig
19
+ from vllm.distributed import get_pp_group
20
+ from vllm.distributed.kv_transfer import (get_kv_transfer_group,
21
+ has_kv_transfer_group)
22
+ from vllm.forward_context import set_forward_context
23
+ from vllm.tasks import SupportedTask
24
+ from vllm.utils.math_utils import cdiv
25
+ from vllm.v1.core.sched.output import GrammarOutput
26
+ from vllm.v1.core.sched.output import SchedulerOutput as VllmSchedulerOutput
27
+ from vllm.v1.kv_cache_interface import KVCacheConfig
28
+ from vllm.v1.outputs import (EMPTY_MODEL_RUNNER_OUTPUT, AsyncModelRunnerOutput,
29
+ DraftTokenIds, KVConnectorOutput, LogprobsLists,
30
+ ModelRunnerOutput)
31
+ from vllm.v1.request import Request
32
+ from vllm.v1.spec_decode.ngram_proposer import NgramProposer
33
+ from vllm.v1.worker.kv_connector_model_runner_mixin import \
34
+ KVConnectorModelRunnerMixin
35
+ from vllm.v1.worker.lora_model_runner_mixin import LoRAModelRunnerMixin
36
+
37
+ import tpu_inference.envs as envs
38
+ from tpu_inference import utils as common_utils
39
+ from tpu_inference.layers.common.attention_metadata import AttentionMetadata
40
+ from tpu_inference.layers.common.sharding import (MESH_AXIS_NAMES,
41
+ MESH_AXIS_NAMES_2D,
42
+ ShardingAxisName,
43
+ ShardingConfigManager)
44
+ from tpu_inference.layers.jax.sample.rejection_sampler import RejectionSampler
45
+ from tpu_inference.layers.jax.sample.sampling import (compute_logprobs,
46
+ gather_logprobs, sample)
47
+ from tpu_inference.layers.jax.sample.sampling_metadata import \
48
+ TPUSupportedSamplingMetadata
49
+ from tpu_inference.logger import init_logger
50
+ from tpu_inference.models.common.model_loader import get_model
51
+ from tpu_inference.models.jax.jax_intermediate_tensor import \
52
+ JaxIntermediateTensors
53
+ from tpu_inference.models.jax.utils.weight_utils import (
54
+ shard_put, transfer_state_with_mappings)
55
+ from tpu_inference.runner import utils as runner_utils
56
+ from tpu_inference.runner.compilation_manager import CompilationManager
57
+ from tpu_inference.runner.input_batch import CachedRequestState, InputBatch
58
+ from tpu_inference.runner.kv_cache_manager import KVCacheManager
59
+ from tpu_inference.runner.lora_utils import LoraUtils
60
+ from tpu_inference.runner.multimodal_manager import MultiModalManager
61
+ from tpu_inference.runner.persistent_batch_manager import \
62
+ PersistentBatchManager
63
+ from tpu_inference.runner.speculative_decoding_manager import (
64
+ SpecDecodeMetadata, SpeculativeDecodingManager)
65
+ from tpu_inference.runner.structured_decoding_manager import \
66
+ StructuredDecodingManager
67
+ from tpu_inference.spec_decode.jax.eagle3 import Eagle3Proposer
68
+ from tpu_inference.utils import (device_array, make_optimized_mesh,
69
+ time_function, to_torch_dtype)
70
+
71
+ logger = init_logger(__name__)
72
+
73
+ INVALID_TOKEN_ID = -1
74
+ # Smallest output size
75
+ MIN_NUM_SEQS = 8
76
+
77
+ DUMMY_METADATA = AttentionMetadata(
78
+ input_positions=[],
79
+ block_tables=[],
80
+ request_distribution=[0, 0, 0],
81
+ )
82
+
83
+
84
+ class AsyncTPUModelRunnerOutput(AsyncModelRunnerOutput):
85
+ """Holds asynchronous model output specifically from a TPU runner.
86
+
87
+ This class acts as a wrapper around the standard ModelRunnerOutput. Its
88
+ primary purpose is to hold references to data still on the TPU device
89
+ (like the `next_tokens` JAX array) without blocking the main thread.
90
+
91
+ The `get_output()` method is called to resolve these async results,
92
+ triggering the JAX device-to-host (CPU) data transfer and populating
93
+ the final `ModelRunnerOutput` object.
94
+ """
95
+
96
+ def __init__(
97
+ self,
98
+ model_runner_output: ModelRunnerOutput,
99
+ next_tokens: jax.Array,
100
+ num_reqs: int,
101
+ discard_sampled_tokens_req_indices: list[int],
102
+ logits_indices_selector: Optional[List[int]] = None,
103
+ ):
104
+ self._model_runner_output = model_runner_output
105
+ self._next_tokens = next_tokens
106
+ self._num_reqs = num_reqs
107
+ self._discard_sampled_tokens_req_indices = discard_sampled_tokens_req_indices
108
+ self.logits_indices_selector: list[int] = logits_indices_selector
109
+
110
+ def get_output(self) -> ModelRunnerOutput:
111
+ next_tokens_cpu = np.asarray(jax.device_get(self._next_tokens))
112
+ if self.logits_indices_selector is not None:
113
+ next_tokens_cpu = next_tokens_cpu[self.logits_indices_selector]
114
+ selected_token_ids = np.expand_dims(next_tokens_cpu[:self._num_reqs],
115
+ 1)
116
+ valid_sampled_token_ids = selected_token_ids.tolist()
117
+ for i in self._discard_sampled_tokens_req_indices:
118
+ valid_sampled_token_ids[i].clear()
119
+ self._model_runner_output.sampled_token_ids = valid_sampled_token_ids
120
+ return self._model_runner_output
121
+
122
+
123
+ @dataclass
124
+ class AsyncPreResults:
125
+ req_ids: list[str]
126
+ next_tokens: jax.Array
127
+ request_seq_lens: list[tuple[int, CachedRequestState, int]]
128
+ discard_sampled_tokens_req_indices: list[int]
129
+ placeholder_req_id_to_index: dict[str, int]
130
+ logits_indices_selector: Optional[List[int]] = None
131
+
132
+
133
+ @dataclass
134
+ class ExecuteModelState:
135
+ """Ephemeral cached state transferred between execute_model() and
136
+ sample_tokens(), after execute_model() returns None."""
137
+
138
+ scheduler_output: "VllmSchedulerOutput"
139
+ attn_metadata: AttentionMetadata
140
+ input_ids: Optional[jax.Array]
141
+ hidden_states: jax.Array
142
+ logits: jax.Array
143
+ aux_hidden_states: Optional[jax.Array]
144
+ spec_decode_metadata: Optional[SpecDecodeMetadata]
145
+ kv_connector_output: Optional[KVConnectorOutput]
146
+ logits_indices_selector: Optional[List[int]] = None
147
+ padded_num_reqs: Optional[int] = None
148
+
149
+
150
+ @functools.partial(jax.jit, donate_argnums=(0, 1, 2))
151
+ def _substitute_placeholder_token(
152
+ input_ids: jax.Array, token_in_tpu_cur_input_indices: jax.Array,
153
+ token_in_tpu_pre_next_tokens_indices: jax.Array,
154
+ next_tokens: jax.Array, placeholder_num: int):
155
+ """Substitute placeholder tokens from TPU for async scheduler
156
+
157
+ Padding for parallelisation of the substitute_placeholder_token_fn
158
+ [1, 3] => [1, 3, 0, 2, 4, 5, 6, 7, 8]
159
+ The reason for such a special padding instead of padding with -1 is:
160
+ An edge case when the end index needs to be updated and padding is required.
161
+ If we pad the array with -1, the _substitute_placeholder_token_fn will repeatedly update the end element with the original value
162
+ Although such a scenario is unlikely to happen in vLLM, it is best to eliminate any potential risks.
163
+
164
+ Args:
165
+ input_ids: possible input_ids size
166
+ token_in_tpu_cur_input_indices: replace holder idx in input_ids. Length the same to input_ids.
167
+ token_in_tpu_pre_next_tokens_indices: value idx in next_tokens. Length the same to input_ids.
168
+ next_tokens: next tokens on the TPU from previous step.
169
+ placeholder_num: number of placeholders. placeholder_num <= len(token_in_tpu_cur_input_indices)
170
+ Return:
171
+ input_ids after replace placeholder tokens
172
+ """
173
+ assert input_ids.shape == token_in_tpu_cur_input_indices.shape == token_in_tpu_pre_next_tokens_indices.shape, \
174
+ f"Shape mismatch: input_ids and index arrays must have identical shapes due to precompilation assumptions. " \
175
+ f"Got: {input_ids.shape=}, {token_in_tpu_cur_input_indices.shape=}, {token_in_tpu_pre_next_tokens_indices.shape=}"
176
+
177
+ # updates the input_ids for all placeholders.
178
+ mask = jnp.arange(input_ids.shape[0]) < placeholder_num
179
+ new_token_values = next_tokens[token_in_tpu_pre_next_tokens_indices]
180
+ original_values = input_ids[token_in_tpu_cur_input_indices]
181
+ update_values = jnp.where(mask, new_token_values, original_values)
182
+ return input_ids.at[token_in_tpu_cur_input_indices].set(update_values)
183
+
184
+
185
+ def _jax_logprobs_to_lists(logprobs_tensors,
186
+ logits_indices_selector=None,
187
+ cu_num_generated_tokens=None):
188
+ """Convert JAX LogprobsTensors to LogprobsLists by converting JAX arrays to numpy."""
189
+ log_token_ids_list = logprobs_tensors.logprob_token_ids.tolist()
190
+ logprobs_list = logprobs_tensors.logprobs.tolist()
191
+ selected_token_ranks_list = logprobs_tensors.selected_token_ranks.tolist()
192
+
193
+ if logits_indices_selector is not None:
194
+ log_token_ids_list = [
195
+ log_token_ids_list[i] for i in logits_indices_selector
196
+ ]
197
+ logprobs_list = [logprobs_list[i] for i in logits_indices_selector]
198
+ selected_token_ranks_list = [
199
+ selected_token_ranks_list[i] for i in logits_indices_selector
200
+ ]
201
+
202
+ return LogprobsLists(
203
+ logprob_token_ids=np.asarray(log_token_ids_list),
204
+ logprobs=np.asarray(logprobs_list),
205
+ sampled_token_ranks=np.asarray(selected_token_ranks_list),
206
+ cu_num_generated_tokens=cu_num_generated_tokens,
207
+ )
208
+
209
+
210
+ class TPUModelRunner(KVConnectorModelRunnerMixin, LoRAModelRunnerMixin):
211
+
212
+ def __init__(
213
+ self,
214
+ vllm_config: VllmConfig,
215
+ devices: List[Any],
216
+ rank: int = 0,
217
+ is_first_rank: bool = True,
218
+ is_last_rank: bool = True,
219
+ ):
220
+ self.vllm_config = vllm_config
221
+ self.model_config = vllm_config.model_config
222
+ # TODO(jevinjiang): override block size based on RPA v3.
223
+ self.cache_config = vllm_config.cache_config
224
+ self.lora_config = vllm_config.lora_config
225
+ self.load_config = vllm_config.load_config
226
+ self.parallel_config = vllm_config.parallel_config
227
+ self.scheduler_config = vllm_config.scheduler_config
228
+ self.speculative_config = vllm_config.speculative_config
229
+ self.observability_config = vllm_config.observability_config
230
+ self.device_config = vllm_config.device_config
231
+
232
+ self.devices = devices
233
+ self.dtype = self.model_config.dtype
234
+ self.maybe_forbid_compile = runner_utils.ForbidCompile(
235
+ ) if envs.VLLM_XLA_CHECK_RECOMPILATION else nullcontext()
236
+ self.dp_size = self.vllm_config.sharding_config.total_dp_size
237
+ self.rank = rank
238
+ self.is_first_rank = is_first_rank
239
+ self.is_last_rank = is_last_rank
240
+
241
+ self._init_random()
242
+ self._init_mesh()
243
+ self._init_phased_profiling()
244
+ self._init_mm()
245
+ self._init_inputs()
246
+ self._init_speculative_decoding()
247
+
248
+ # Delegate functions to specific manager classes.
249
+ self.compilation_manager = CompilationManager(self)
250
+ if self.is_last_rank:
251
+ self.speculative_decoding_manager = SpeculativeDecodingManager(
252
+ self)
253
+ self.structured_decoding_manager = StructuredDecodingManager(self)
254
+ self.kv_cache_manager = KVCacheManager(self)
255
+ self.mm_manager = MultiModalManager(self)
256
+ self.persistent_batch_manager = PersistentBatchManager(
257
+ self.requests, self.input_batch, self.encoder_cache,
258
+ self.uses_mrope, self.model_config, self.is_last_rank)
259
+ self.lora_utils = LoraUtils(self)
260
+
261
+ cache_dtype = self.cache_config.cache_dtype
262
+ if cache_dtype == "auto":
263
+ cache_dtype = self.dtype
264
+ self.kv_cache_dtype = to_torch_dtype(cache_dtype)
265
+
266
+ self._pre_async_results: AsyncPreResults | None = None
267
+ self._substitute_placeholder_token_fn = _substitute_placeholder_token
268
+ self.execute_model_state: ExecuteModelState | None = None
269
+
270
+ def _init_random(self):
271
+ if self.model_config.seed is None:
272
+ self.model_config.seed = 0
273
+ random.seed(self.model_config.seed)
274
+ np.random.seed(self.model_config.seed)
275
+ self.rng_key = jax.random.key(self.model_config.seed)
276
+
277
+ def _init_mesh(self) -> None:
278
+ if envs.NEW_MODEL_DESIGN:
279
+ self.mesh = self._create_new_model_mesh()
280
+ else:
281
+ # NOTE(wenxindongwork): The new MoE kernel expects a 2D mesh, so we need
282
+ # to create a 2D mesh for now. We should make the new_model_mesh as the default
283
+ # in the future.
284
+ self.mesh = self._create_2d_mesh()
285
+
286
+ logger.info(f"Init mesh | mesh={self.mesh}")
287
+
288
+ def _create_new_model_mesh(self) -> jax.sharding.Mesh:
289
+ num_slices = envs.NUM_SLICES
290
+
291
+ logger.info(f"Creating new model mesh | devices={len(self.devices)}, "
292
+ f"num_slices={num_slices}")
293
+
294
+ if num_slices == 1:
295
+ devices_array = self._create_single_slice_mesh()
296
+ else:
297
+ devices_array = self._create_multi_slice_mesh(num_slices)
298
+
299
+ return jax.sharding.Mesh(devices_array, MESH_AXIS_NAMES)
300
+
301
+ def _create_single_slice_mesh(self) -> jax.Array:
302
+ sharding_strategy: ShardingConfigManager = self.vllm_config.sharding_config
303
+ mesh_shape = (
304
+ sharding_strategy.model_dp_size,
305
+ sharding_strategy.attn_dp_size,
306
+ sharding_strategy.expert_size,
307
+ sharding_strategy.tp_size,
308
+ )
309
+
310
+ return mesh_utils.create_device_mesh(
311
+ mesh_shape,
312
+ self.devices,
313
+ allow_split_physical_axes=True,
314
+ )
315
+
316
+ def _create_multi_slice_mesh(self, num_slices: int) -> jax.Array:
317
+ sharding_strategy: ShardingConfigManager = self.vllm_config.sharding_config
318
+ dp_inner = sharding_strategy.model_dp_size // num_slices
319
+
320
+ # Splits data parallelism across multiple slices.
321
+ ici_mesh_shape = (
322
+ dp_inner,
323
+ sharding_strategy.attn_dp_size,
324
+ sharding_strategy.expert_size,
325
+ sharding_strategy.tp_size,
326
+ )
327
+ dcn_mesh_shape = (num_slices, 1, 1, 1)
328
+
329
+ return mesh_utils.create_hybrid_device_mesh(
330
+ mesh_shape=ici_mesh_shape,
331
+ dcn_mesh_shape=dcn_mesh_shape,
332
+ devices=self.devices,
333
+ allow_split_physical_axes=True,
334
+ )
335
+
336
+ def _create_2d_mesh(self) -> jax.sharding.Mesh:
337
+
338
+ sharding_strategy: ShardingConfigManager = self.vllm_config.sharding_config
339
+ mesh_shape = (
340
+ sharding_strategy.model_dp_size,
341
+ sharding_strategy.tp_size,
342
+ )
343
+
344
+ enforce_device_order = (
345
+ self.vllm_config.sharding_config.device_indexes is not None
346
+ and len(self.vllm_config.sharding_config.device_indexes) > 0)
347
+
348
+ if enforce_device_order:
349
+ return jax.make_mesh(mesh_shape,
350
+ MESH_AXIS_NAMES_2D,
351
+ devices=self.devices)
352
+ else:
353
+ return make_optimized_mesh(mesh_shape,
354
+ MESH_AXIS_NAMES_2D,
355
+ devices=self.devices)
356
+
357
+ def _init_phased_profiling(self) -> None:
358
+ self.phased_profiling_dir = envs.PHASED_PROFILING_DIR
359
+ self.phase_based_profiler = None
360
+ if self.phased_profiling_dir:
361
+ self.phase_based_profiler = runner_utils.PhasedBasedProfiler(
362
+ self.phased_profiling_dir)
363
+
364
+ def _init_mm(self) -> None:
365
+ self.is_multimodal_model = None
366
+ self.uses_mrope = self.model_config.uses_mrope
367
+
368
+ def _init_speculative_decoding(self) -> None:
369
+ self.drafter = None
370
+ if self.speculative_config:
371
+ if self.speculative_config.method == "ngram":
372
+ self.drafter = NgramProposer(self.vllm_config)
373
+ elif self.speculative_config.method == "eagle3":
374
+ self.drafter = Eagle3Proposer(self.vllm_config, self)
375
+ else:
376
+ raise NotImplementedError(
377
+ "Unsupported speculative decoding method: "
378
+ f"{self.speculative_config.method}")
379
+ self.rejection_sampler = RejectionSampler()
380
+
381
+ def _init_inputs(self) -> None:
382
+ model_config = self.model_config
383
+ cache_config = self.cache_config
384
+ scheduler_config = self.scheduler_config
385
+
386
+ self.sliding_window = model_config.get_sliding_window()
387
+ self.block_size = cache_config.block_size
388
+ self.max_model_len = model_config.max_model_len
389
+ self.max_num_blocks_per_req = cdiv(self.max_model_len, self.block_size)
390
+ # InputBatch needs to work with sampling tensors greater than padding
391
+ # to avoid dynamic shapes. Also, avoid suboptimal alignment.
392
+ # The total number of requests is dp_size * max_num_seqs
393
+ self.max_num_reqs = max(self.dp_size * scheduler_config.max_num_seqs,
394
+ MIN_NUM_SEQS)
395
+ # [16, 32, 64, 128, 256, 512, 1024, 2048]
396
+ self.num_tokens_paddings = runner_utils.get_token_paddings(
397
+ min_token_size=max(16, self.dp_size),
398
+ max_token_size=scheduler_config.max_num_batched_tokens *
399
+ self.dp_size,
400
+ padding_gap=vllm_envs.VLLM_TPU_BUCKET_PADDING_GAP)
401
+ self.num_tokens_paddings_per_dp = [
402
+ padding // self.dp_size for padding in self.num_tokens_paddings
403
+ ]
404
+ # In case `max_num_tokens < max(num_tokens_paddings)` use the actual
405
+ # padded max value to pre-allocate data structures and pre-compile.
406
+ self.max_num_tokens = self.num_tokens_paddings[-1]
407
+
408
+ # Request states.
409
+ self.requests: dict[str, CachedRequestState] = {}
410
+ # mm_hash -> encoder_output
411
+ self.encoder_cache: dict[str, jax.Array] = {}
412
+ self.input_batch = InputBatch(
413
+ max_num_reqs=self.max_num_reqs,
414
+ max_model_len=self.max_model_len,
415
+ max_num_batched_tokens=self.max_num_tokens,
416
+ pin_memory=False,
417
+ vocab_size=self.model_config.get_vocab_size(),
418
+ block_sizes=[self.block_size],
419
+ is_spec_decode=bool(self.vllm_config.speculative_config),
420
+ )
421
+
422
+ self.input_ids_cpu = np.zeros(self.max_num_tokens, dtype=np.int32)
423
+ self.positions_cpu = np.zeros(self.max_num_tokens, dtype=np.int32)
424
+ # Note: self.input_batch and self.block_tables_cpu are both initialized
425
+ # with only 1 block_size. For hybrid kv cache, it will be re-init
426
+ # in kv_cache_manager's maybe_reinitialize_input_batch.
427
+ self.block_tables_cpu = [
428
+ np.zeros((self.max_num_reqs, self.max_num_blocks_per_req),
429
+ dtype=np.int32)
430
+ ]
431
+
432
+ self.query_start_loc_cpu = np.zeros(self.max_num_reqs + self.dp_size,
433
+ dtype=np.int32)
434
+ self.seq_lens_cpu = np.zeros(self.max_num_reqs, dtype=np.int32)
435
+ self.logits_indices_cpu = np.zeros(self.max_num_reqs, dtype=np.int32)
436
+ # Range tensor with values [0 .. self.max_num_tokens - 1].
437
+ # Used to initialize positions / context_lens / seq_lens
438
+ # Keep in int64 to avoid overflow with long context
439
+ self.arange_cpu = np.arange(self.max_num_tokens, dtype=np.int64)
440
+ min_num_reqs = max(MIN_NUM_SEQS, self.dp_size)
441
+ self.num_reqs_paddings = runner_utils.get_req_paddings(
442
+ min_req_size=min_num_reqs, max_req_size=self.max_num_reqs)
443
+ self.num_reqs_paddings_per_dp = [
444
+ padding // self.dp_size for padding in self.num_reqs_paddings
445
+ ]
446
+
447
+ # Padding for logits. Without speculative decoding, each request has one position to select from.
448
+ # With speculative decoding, each request has multiple positions to select from.
449
+ max_logits_per_req = 1
450
+ if self.speculative_config:
451
+ max_logits_per_req = self.speculative_config.num_speculative_tokens + 1 # Including bonus token
452
+ self.num_logits_paddings = runner_utils.get_token_paddings(
453
+ min_token_size=MIN_NUM_SEQS,
454
+ max_token_size=self.max_num_reqs * max_logits_per_req,
455
+ padding_gap=0)
456
+ else:
457
+ self.num_logits_paddings = None
458
+
459
+ self.temperatures_cpu = np.zeros(self.max_num_tokens, dtype=np.float32)
460
+ self.top_ps_cpu = np.zeros(self.max_num_tokens, dtype=np.float32)
461
+ self.top_ks_cpu = np.zeros(self.max_num_tokens, dtype=np.int32)
462
+
463
+ # tensors for structured decoding
464
+ self.vocab_size = self.model_config.get_vocab_size()
465
+ self.grammar_bitmask_cpu = np.zeros(
466
+ (self.max_num_reqs, cdiv(self.vocab_size, 32)),
467
+ dtype=np.int32,
468
+ )
469
+ self.require_structured_out_cpu = np.zeros(
470
+ (self.max_num_reqs, 1),
471
+ dtype=np.bool_,
472
+ )
473
+ self.structured_decode_arange = np.arange(0, 32, dtype=np.int32)
474
+
475
+ # multi-modal support
476
+ # Only relevant for models using M-RoPE (e.g, Qwen2-VL)
477
+
478
+ # NOTE: When M-RoPE is enabled, position ids are 3D regardless of
479
+ # the modality of inputs. For text-only inputs, each dimension has
480
+ # identical position IDs, making M-RoPE functionally equivalent to
481
+ # 1D-RoPE.
482
+ # See page 5 of https://arxiv.org/abs/2409.12191
483
+ self.mrope_positions_cpu = np.zeros((3, self.max_num_tokens),
484
+ dtype=np.int64)
485
+
486
+ def load_model(self):
487
+ self.model_fn, self.compute_logits_fn, self.combine_hidden_states_fn, multimodal_fns, self.state, self.lora_manager, self.model = get_model(
488
+ self.vllm_config,
489
+ self.rng_key,
490
+ self.mesh,
491
+ )
492
+
493
+ multimodal_fns = multimodal_fns or {}
494
+ self.precompile_vision_encoder_fn = multimodal_fns.get(
495
+ "precompile_vision_encoder_fn", None)
496
+ self.get_multimodal_embeddings_fn = multimodal_fns.get(
497
+ "get_multimodal_embeddings_fn", None)
498
+ self.get_input_embeddings_fn = multimodal_fns.get(
499
+ "get_input_embeddings_fn", None)
500
+ self.get_mrope_input_positions_fn = multimodal_fns.get(
501
+ "get_mrope_input_positions_fn", None)
502
+
503
+ if self.drafter is not None:
504
+ logger.info("Loading drafter model...")
505
+ self.drafter.load_model(self.state)
506
+
507
+ self.rng_params_for_sampling = nnx.Rngs(
508
+ jax.random.key(self.model_config.seed)).params()
509
+ self.is_multimodal_model = (
510
+ self.model_config.is_multimodal_model
511
+ and self.get_multimodal_embeddings_fn is not None and hasattr(
512
+ self.model_config.hf_config, "architectures"
513
+ ) #TODO: Remove Llama Guard 4 specific condition once the LG4 Vision portion is implemented
514
+ and len(self.model_config.hf_config.architectures) >= 1
515
+ and self.model_config.hf_config.architectures[0]
516
+ != "Llama4ForConditionalGeneration")
517
+
518
+ logger.info(f"Init model | "
519
+ f"hbm={common_utils.hbm_usage_gb(self.devices)}GiB")
520
+
521
+ def get_supported_tasks(self) -> tuple[SupportedTask, ...]:
522
+ return ("generate", )
523
+
524
+ def get_kv_cache_spec(self):
525
+ return self.kv_cache_manager.get_kv_cache_spec()
526
+
527
+ def initialize_kv_cache(self, kv_cache_config: KVCacheConfig) -> None:
528
+ self.kv_cache_config = kv_cache_config
529
+ self.use_hybrid_kvcache = len(kv_cache_config.kv_cache_groups) > 1
530
+ self.kv_caches = []
531
+ self.kv_cache_manager.initialize_kv_cache(kv_cache_config)
532
+ if has_kv_transfer_group():
533
+ get_kv_transfer_group().register_runner(self)
534
+
535
+ def capture_model(self) -> None:
536
+ self.compilation_manager.capture_model()
537
+
538
+ @time_function
539
+ def execute_model(
540
+ self,
541
+ scheduler_output: "VllmSchedulerOutput",
542
+ intermediate_tensors: Optional[JaxIntermediateTensors] = None,
543
+ ) -> ModelRunnerOutput | JaxIntermediateTensors | None:
544
+ if self.execute_model_state is not None:
545
+ raise RuntimeError("State error: sample_tokens() must be called "
546
+ "after execute_model() returns None.")
547
+ _, output = self._execute_model(scheduler_output, intermediate_tensors)
548
+ return output
549
+
550
+ def sample_tokens(
551
+ self,
552
+ grammar_output: "GrammarOutput | None",
553
+ ) -> ModelRunnerOutput | AsyncTPUModelRunnerOutput:
554
+ if self.execute_model_state is None:
555
+ # This can happen in pipeline parallel case.
556
+ return EMPTY_MODEL_RUNNER_OUTPUT
557
+
558
+ (scheduler_output, attn_metadata, input_ids, hidden_states, logits,
559
+ aux_hidden_states, spec_decode_metadata, kv_connector_output,
560
+ logits_indices_selector,
561
+ padded_num_reqs) = (self.execute_model_state.scheduler_output,
562
+ self.execute_model_state.attn_metadata,
563
+ self.execute_model_state.input_ids,
564
+ self.execute_model_state.hidden_states,
565
+ self.execute_model_state.logits,
566
+ self.execute_model_state.aux_hidden_states,
567
+ self.execute_model_state.spec_decode_metadata,
568
+ self.execute_model_state.kv_connector_output,
569
+ self.execute_model_state.logits_indices_selector,
570
+ self.execute_model_state.padded_num_reqs)
571
+ self.execute_model_state = None
572
+
573
+ if grammar_output is not None:
574
+ (
575
+ require_struct_decoding, grammar_bitmask_padded, arange
576
+ ) = self.structured_decoding_manager.prepare_structured_decoding_input(
577
+ logits, grammar_output)
578
+ logits = self.structured_decoding_manager.structured_decode_fn(
579
+ require_struct_decoding,
580
+ grammar_bitmask_padded,
581
+ logits,
582
+ arange,
583
+ )
584
+ return self._sample_from_logits(
585
+ scheduler_output, attn_metadata, input_ids, hidden_states, logits,
586
+ aux_hidden_states, spec_decode_metadata, kv_connector_output,
587
+ logits_indices_selector, padded_num_reqs)
588
+
589
+ def _modify_prev_results(self):
590
+ # If copy to host has not been done, we just wait.
591
+ # device_get should return immediately as we have scheduled it in previous function call.
592
+ assert self._pre_async_results is not None, "When we call _modify_prev_results(), self._pre_async_results should already exist"
593
+ pre_req_ids = self._pre_async_results.req_ids
594
+ pre_next_tokens = self._pre_async_results.next_tokens
595
+ pre_request_seq_lens = self._pre_async_results.request_seq_lens
596
+ pre_discard_sampled_tokens_req_indices = self._pre_async_results.discard_sampled_tokens_req_indices
597
+ pre_logits_indices_selector = self._pre_async_results.logits_indices_selector
598
+
599
+ next_tokens_cpu = np.asarray(jax.device_get(pre_next_tokens))
600
+ if pre_logits_indices_selector is not None:
601
+ next_tokens_cpu = next_tokens_cpu[pre_logits_indices_selector]
602
+ selected_token_ids = np.expand_dims(next_tokens_cpu[:len(pre_req_ids)],
603
+ 1)
604
+ valid_sampled_token_ids = selected_token_ids.tolist()
605
+
606
+ # Mask out the sampled tokens that should not be sampled.
607
+ for i in pre_discard_sampled_tokens_req_indices:
608
+ valid_sampled_token_ids[i].clear()
609
+ # Append sampled tokens
610
+ for pre_req_idx, req_state, _ in pre_request_seq_lens:
611
+ sampled_ids = valid_sampled_token_ids[pre_req_idx]
612
+ if not sampled_ids:
613
+ continue
614
+
615
+ # If request not active in the *current* batch (e.g. finished or evicted), skip it.
616
+ req_id = pre_req_ids[pre_req_idx]
617
+ if req_id not in self.input_batch.req_id_to_index:
618
+ continue
619
+
620
+ req_idx = self.input_batch.req_id_to_index[req_id]
621
+ assert req_state is self.requests[
622
+ req_id], "The req_state should be valid and identical"
623
+
624
+ # Updated on previous execute
625
+ end_idx = self.input_batch.num_tokens_no_spec[req_idx]
626
+ assert len(sampled_ids) == 1, "do not support spec decode yet"
627
+ start_idx = end_idx - 1
628
+ assert end_idx <= self.max_model_len, (
629
+ "Sampled token IDs exceed the max model length. "
630
+ f"Total number of tokens: {end_idx} > max_model_len: "
631
+ f"{self.max_model_len}")
632
+
633
+ self.input_batch.token_ids_cpu[req_idx,
634
+ start_idx:end_idx] = sampled_ids
635
+ # Replace previous placeholder
636
+ req_state.output_token_ids[-1] = sampled_ids[-1]
637
+
638
+ def _update_placeholder(self,
639
+ discard_sampled_tokens_req_indices,
640
+ request_seq_lens,
641
+ logits_indices_selector=None):
642
+ placeholder_req_id_to_index: dict[str, int] = {}
643
+ discard_sampled_tokens_req_indices_set = set(
644
+ discard_sampled_tokens_req_indices)
645
+ for req_idx, req_state, _ in request_seq_lens:
646
+ if req_idx in discard_sampled_tokens_req_indices_set:
647
+ continue
648
+
649
+ start_idx = self.input_batch.num_tokens_no_spec[req_idx]
650
+ # Not supporting spec decode yet, assume only 1 new token
651
+ end_idx = start_idx + 1
652
+ assert end_idx <= self.max_model_len, (
653
+ "Sampled token IDs exceed the max model length. "
654
+ f"Total number of tokens: {end_idx} > max_model_len: "
655
+ f"{self.max_model_len}")
656
+
657
+ # Update cpu tokens at next execute and prepare input from tpu
658
+ self.input_batch.num_tokens_no_spec[req_idx] = end_idx
659
+ self.input_batch.num_tokens[req_idx] = end_idx
660
+
661
+ # For placeholder, should be update on next execute.
662
+ req_state.output_token_ids.extend([0])
663
+ if logits_indices_selector is None:
664
+ placeholder_req_id_to_index[req_state.req_id] = req_idx
665
+ else:
666
+ placeholder_req_id_to_index[
667
+ req_state.req_id] = logits_indices_selector[req_idx]
668
+ return placeholder_req_id_to_index
669
+
670
+ def _execute_model(
671
+ self,
672
+ scheduler_output: "VllmSchedulerOutput",
673
+ intermediate_tensors: Optional[JaxIntermediateTensors] = None,
674
+ ) -> tuple[AttentionMetadata, JaxIntermediateTensors | ModelRunnerOutput
675
+ | None]:
676
+ self.persistent_batch_manager.update_states(
677
+ scheduler_output, self.get_mrope_input_positions_fn)
678
+ if not scheduler_output.total_num_scheduled_tokens:
679
+ if has_kv_transfer_group():
680
+ return DUMMY_METADATA, self.kv_connector_no_forward(
681
+ scheduler_output, self.vllm_config)
682
+
683
+ # Return empty ModelRunnerOutput if there's no work to do.
684
+ # TODO(fhzhang): We rely on empty cycles to remove requests in input batch. Fix it to reduce overhead.
685
+ logger.debug(f"Nothing scheduled: {scheduler_output}!")
686
+ # NOTE(pooyam): There is no guarantee that scheduler is not sending empty output: https://github.com/vllm-project/vllm/blob/7cfea0df390c154c1026f77d3682e2733ca4aca8/vllm/v1/engine/core.py#L275
687
+ # Why they are not preventing that is not clear to me.
688
+ if len(scheduler_output.finished_req_ids) == 0:
689
+ logger.warning(
690
+ "Should not schedule a request that does nothing!")
691
+ # raise Exception(
692
+ # "Should not schedule a request that does nothing!")
693
+ return DUMMY_METADATA, EMPTY_MODEL_RUNNER_OUTPUT
694
+
695
+ # TODO(pooyam): I guess we can remove returning sampling_metadata in `_prepare_inputs` after https://github.com/njhill/vllm/commit/b7433ca1a47732394b1bdea4099d98389515954b
696
+ (
697
+ input_ids,
698
+ input_positions,
699
+ attn_metadata,
700
+ _,
701
+ logits_indices,
702
+ spec_decode_metadata,
703
+ logits_indices_selector,
704
+ padded_num_reqs,
705
+ ) = self._prepare_inputs(scheduler_output)
706
+
707
+ is_llama_guard_4 = (
708
+ hasattr(
709
+ self.model_config.hf_config, "architectures"
710
+ ) #TODO: Remove Llama Guard 4 specific condition once the LG4 Vision portion is implemented
711
+ and len(self.model_config.hf_config.architectures) >= 1
712
+ and self.model_config.hf_config.architectures[0]
713
+ == "Llama4ForConditionalGeneration")
714
+
715
+ # multi-modal support
716
+ if self.is_multimodal_model:
717
+ # Run the multimodal encoder if any.
718
+ # We have the modality embeds at this time.
719
+ self.mm_manager.execute_mm_encoder(scheduler_output)
720
+ mm_embeds = self.mm_manager.gather_mm_embeddings(
721
+ scheduler_output, input_ids.shape[0])
722
+ #TODO: Remove the follow elif statement once Llama Guard 4 Vision portion has been implemented
723
+ elif is_llama_guard_4 and any(
724
+ self.mm_manager.runner.requests[req_id].mm_features
725
+ for req_id in self.mm_manager.runner.input_batch.req_ids):
726
+ raise NotImplementedError(
727
+ "Llama Guard 4 (JAX) currently supports only text inputs. "
728
+ "Multimodal processing not yet implemented.")
729
+ else:
730
+ mm_embeds = []
731
+
732
+ # NOTE(Wenlong): For multi-modal model,
733
+ # it will embed the text tokens and merge with the existing modality embeds
734
+ # Later, the multi-modality model will take the embedding as the input.
735
+ # For text-only model, this does nothing. It will input the input_ids and
736
+ # leave the mebedding job inside the forward pass
737
+ input_ids, inputs_embeds = self._get_input_ids_embeds(
738
+ input_ids, mm_embeds)
739
+
740
+ lora_metadata = self.lora_utils.extract_lora_metadata()
741
+ # TODO: make _get_input_ids_embeds within this context
742
+ # NOTE: right now, mm model will use embeddings as the input,
743
+ # but text-only model will use input_ids
744
+ with self.maybe_forbid_compile:
745
+
746
+ with set_forward_context(
747
+ None,
748
+ self.vllm_config,
749
+ ), self.maybe_get_kv_connector_output(
750
+ scheduler_output) as kv_connector_output:
751
+ # NOTE(Wenlong): It takes both `input_ids` and `inputs_embeds`,
752
+ # but one of them would be `None`
753
+ (self.kv_caches, hidden_states,
754
+ aux_hidden_states) = self.model_fn(
755
+ self.state,
756
+ self.kv_caches,
757
+ input_ids,
758
+ attn_metadata,
759
+ inputs_embeds,
760
+ input_positions,
761
+ tuple(self.layer_name_to_kvcache_index.items()),
762
+ lora_metadata,
763
+ intermediate_tensors,
764
+ self.is_first_rank,
765
+ self.is_last_rank,
766
+ )
767
+ if not get_pp_group().is_last_rank:
768
+ assert isinstance(hidden_states, JaxIntermediateTensors)
769
+ hidden_states.kv_connector_output = kv_connector_output
770
+ return attn_metadata, hidden_states
771
+ hidden_states = self._select_from_array_fn(hidden_states,
772
+ logits_indices)
773
+ logits = self.compute_logits_fn(
774
+ self.state,
775
+ hidden_states,
776
+ lora_metadata,
777
+ )
778
+
779
+ self.execute_model_state = ExecuteModelState(
780
+ scheduler_output=scheduler_output,
781
+ attn_metadata=attn_metadata,
782
+ input_ids=input_ids,
783
+ hidden_states=hidden_states,
784
+ logits=logits,
785
+ aux_hidden_states=aux_hidden_states,
786
+ spec_decode_metadata=spec_decode_metadata,
787
+ kv_connector_output=kv_connector_output,
788
+ logits_indices_selector=logits_indices_selector,
789
+ padded_num_reqs=padded_num_reqs)
790
+ return attn_metadata, None
791
+
792
+ def _sample_from_logits(
793
+ self,
794
+ scheduler_output: "VllmSchedulerOutput",
795
+ attn_metadata: AttentionMetadata,
796
+ input_ids: Optional[jax.Array],
797
+ hidden_states: jax.Array,
798
+ logits: jax.Array,
799
+ aux_hidden_states: Optional[jax.Array],
800
+ spec_decode_metadata: Optional[SpecDecodeMetadata],
801
+ kv_connector_output: Optional[KVConnectorOutput],
802
+ logits_indices_selector: Optional[List[int]] = None,
803
+ padded_num_reqs: Optional[int] = None,
804
+ ) -> ModelRunnerOutput | AsyncTPUModelRunnerOutput:
805
+ if padded_num_reqs is None:
806
+ padded_num_reqs = runner_utils.get_padded_num_reqs_with_upper_limit(
807
+ self.input_batch.num_reqs, self.max_num_reqs)
808
+
809
+ sharding = None
810
+ if self.dp_size > 1:
811
+ sharding = NamedSharding(self.mesh,
812
+ PartitionSpec(ShardingAxisName.ATTN_DATA))
813
+
814
+ tpu_sampling_metadata = TPUSupportedSamplingMetadata.from_input_batch(
815
+ self.mesh, self.input_batch, padded_num_reqs, sharding=sharding)
816
+
817
+ # TODO(pooyam): Should we move this to `_prepare_inputs`?
818
+ if tpu_sampling_metadata.do_sampling:
819
+ self.rng_params_for_sampling, step_rng = jax.random.split(
820
+ self.rng_params_for_sampling)
821
+ else:
822
+ step_rng = self.rng_params_for_sampling
823
+
824
+ if spec_decode_metadata is None:
825
+ next_tokens = sample(
826
+ step_rng,
827
+ self.mesh,
828
+ logits,
829
+ tpu_sampling_metadata,
830
+ )
831
+ else:
832
+ if tpu_sampling_metadata.do_sampling:
833
+ bonus_rng, rejection_rng = jax.random.split(step_rng)
834
+ else:
835
+ bonus_rng = step_rng
836
+ rejection_rng = step_rng
837
+ bonus_logits = self._select_from_array_fn(
838
+ logits, spec_decode_metadata.bonus_logits_indices)
839
+ bonus_token_ids = sample(
840
+ bonus_rng,
841
+ self.mesh,
842
+ bonus_logits,
843
+ tpu_sampling_metadata,
844
+ )
845
+ target_logits = self._select_from_array_fn(
846
+ logits, spec_decode_metadata.target_logits_indices)
847
+ next_tokens = self.rejection_sampler(
848
+ draft_token_ids=spec_decode_metadata.draft_token_ids,
849
+ num_draft_tokens=spec_decode_metadata.draft_lengths,
850
+ draft_probs=None,
851
+ target_logits=target_logits,
852
+ bonus_token_ids=bonus_token_ids,
853
+ sampling_metadata=tpu_sampling_metadata,
854
+ key=rejection_rng,
855
+ )
856
+
857
+ if tpu_sampling_metadata.logprobs:
858
+ logprobs = self._compute_and_gather_logprobs(
859
+ logits, next_tokens, self.model_config.max_logprobs)
860
+ else:
861
+ logprobs = None
862
+
863
+ num_reqs = self.input_batch.num_reqs
864
+
865
+ # Update the cache state concurrently. Code above will not block until
866
+ # We use `selected_token_ids`. Add mark_step if post-processing changes
867
+ request_seq_lens: list[tuple[int, CachedRequestState, int]] = []
868
+ discard_sampled_tokens_req_indices = []
869
+ for i, req_id in zip(range(num_reqs), self.input_batch.req_ids):
870
+ assert req_id is not None
871
+ req_state = self.requests[req_id]
872
+ seq_len = (req_state.num_computed_tokens +
873
+ scheduler_output.num_scheduled_tokens[req_id])
874
+ if seq_len >= req_state.num_tokens:
875
+ request_seq_lens.append((i, req_state, seq_len))
876
+ else:
877
+ # Ignore the sampled token from the partial request.
878
+ # Rewind the generator state as if the token was not sampled.
879
+ generator = self.input_batch.generators.get(i)
880
+ if generator is not None:
881
+ # This relies on cuda-specific torch-internal impl details
882
+ generator.set_offset(generator.get_offset() - 4)
883
+
884
+ # Record the index of the request that should not be sampled,
885
+ # so that we could clear the sampled tokens before returning.
886
+ discard_sampled_tokens_req_indices.append(i)
887
+
888
+ assert all(
889
+ req_id is not None for req_id in
890
+ self.input_batch.req_ids[:num_reqs]), "req_ids contains None"
891
+ req_ids = cast(list[str], self.input_batch.req_ids[:num_reqs])
892
+
893
+ prompt_logprobs_dict = {}
894
+ for req_id in self.input_batch.req_ids[:num_reqs]:
895
+ prompt_logprobs_dict[req_id] = None
896
+
897
+ # If async scheduler enabled
898
+ if self.scheduler_config.async_scheduling:
899
+ # Get previous results from TPU and replace the placeholder.
900
+ if self._pre_async_results is not None:
901
+ assert not self.speculative_config and spec_decode_metadata is None, "Async scheduler does not support speculative decoding yet."
902
+ self._modify_prev_results()
903
+
904
+ # Set placeholder for next tokens that is not yet generated
905
+ placeholder_req_id_to_index: dict[
906
+ str, int] = self._update_placeholder(
907
+ discard_sampled_tokens_req_indices, request_seq_lens,
908
+ logits_indices_selector)
909
+
910
+ if logprobs is not None:
911
+ # Map logprobs back to the pre-dp shuffling order
912
+ logprobs_lists = _jax_logprobs_to_lists(
913
+ logprobs, logits_indices_selector)
914
+
915
+ else:
916
+ logprobs_lists = None
917
+
918
+ # Save the previous results
919
+ next_tokens = jax.copy_to_host_async(next_tokens)
920
+ self._pre_async_results = AsyncPreResults(
921
+ req_ids=req_ids,
922
+ next_tokens=next_tokens,
923
+ request_seq_lens=request_seq_lens,
924
+ discard_sampled_tokens_req_indices=
925
+ discard_sampled_tokens_req_indices,
926
+ placeholder_req_id_to_index=placeholder_req_id_to_index,
927
+ logits_indices_selector=logits_indices_selector)
928
+
929
+ # Return Model output to executor
930
+ model_runner_output = ModelRunnerOutput(
931
+ req_ids=req_ids,
932
+ req_id_to_index=copy.deepcopy(
933
+ self.input_batch.req_id_to_index),
934
+ sampled_token_ids=[], # Fill in async get
935
+ logprobs=logprobs_lists,
936
+ prompt_logprobs_dict=prompt_logprobs_dict,
937
+ pooler_output=[],
938
+ kv_connector_output=kv_connector_output,
939
+ )
940
+ # Return async_model_runner_output
941
+ async_model_runner_output = AsyncTPUModelRunnerOutput(
942
+ model_runner_output, next_tokens, num_reqs,
943
+ discard_sampled_tokens_req_indices, logits_indices_selector)
944
+ return async_model_runner_output
945
+
946
+ if spec_decode_metadata is None:
947
+ next_tokens = np.asarray(jax.device_get(next_tokens))
948
+ # Map tokens back to the pre-dp shuffling order
949
+ if logits_indices_selector is not None:
950
+ next_tokens = next_tokens[logits_indices_selector]
951
+ selected_token_ids = np.expand_dims(next_tokens[:num_reqs], 1)
952
+ valid_sampled_token_ids = selected_token_ids.tolist()
953
+ else:
954
+ valid_sampled_token_ids = self.rejection_sampler.parse_output(
955
+ next_tokens, self.input_batch.vocab_size,
956
+ spec_decode_metadata.draft_lengths_cpu, num_reqs,
957
+ spec_decode_metadata.draft_token_ids.shape[0])
958
+
959
+ # Mask out the sampled tokens that should not be sampled.
960
+ for i in discard_sampled_tokens_req_indices:
961
+ valid_sampled_token_ids[i].clear()
962
+ # Append sampled tokens
963
+ for req_idx, req_state, _ in request_seq_lens:
964
+ sampled_ids = valid_sampled_token_ids[req_idx]
965
+ if not sampled_ids:
966
+ continue
967
+
968
+ start_idx = self.input_batch.num_tokens_no_spec[req_idx]
969
+ end_idx = start_idx + len(sampled_ids)
970
+ assert end_idx <= self.max_model_len, (
971
+ "Sampled token IDs exceed the max model length. "
972
+ f"Total number of tokens: {end_idx} > max_model_len: "
973
+ f"{self.max_model_len}")
974
+
975
+ self.input_batch.token_ids_cpu[req_idx,
976
+ start_idx:end_idx] = sampled_ids
977
+ self.input_batch.num_tokens_no_spec[req_idx] = end_idx
978
+ self.input_batch.num_tokens[req_idx] = end_idx
979
+ req_state.output_token_ids.extend(sampled_ids)
980
+
981
+ if logprobs is not None:
982
+ # Map logprobs back to the pre-dp shuffling order
983
+ logprobs_lists = _jax_logprobs_to_lists(logprobs,
984
+ logits_indices_selector)
985
+ else:
986
+ logprobs_lists = None
987
+
988
+ if self.speculative_config:
989
+ with self.maybe_forbid_compile:
990
+ self.speculative_decoding_manager.propose_draft_token_ids(
991
+ valid_sampled_token_ids,
992
+ aux_hidden_states,
993
+ attn_metadata,
994
+ spec_decode_metadata,
995
+ scheduler_output,
996
+ input_ids,
997
+ )
998
+
999
+ model_runner_output = ModelRunnerOutput(
1000
+ req_ids=req_ids,
1001
+ req_id_to_index=self.input_batch.req_id_to_index,
1002
+ sampled_token_ids=valid_sampled_token_ids,
1003
+ logprobs=logprobs_lists,
1004
+ prompt_logprobs_dict=prompt_logprobs_dict,
1005
+ pooler_output=[],
1006
+ kv_connector_output=kv_connector_output,
1007
+ )
1008
+ return model_runner_output
1009
+
1010
+ @functools.partial(jax.jit, static_argnums=(0, ))
1011
+ def _select_from_array_fn(self, array, indices_to_select):
1012
+
1013
+ def select_local_fn(local_array, local_indices):
1014
+ return local_array[local_indices]
1015
+
1016
+ ret = jax.shard_map(
1017
+ select_local_fn,
1018
+ mesh=self.mesh,
1019
+ in_specs=(PartitionSpec(ShardingAxisName.ATTN_DATA),
1020
+ PartitionSpec(ShardingAxisName.ATTN_DATA)),
1021
+ out_specs=PartitionSpec(ShardingAxisName.ATTN_DATA))(
1022
+ array, indices_to_select)
1023
+
1024
+ return ret
1025
+
1026
+ @staticmethod
1027
+ @functools.partial(jax.jit, static_argnames=("max_logprobs", ))
1028
+ def _compute_and_gather_logprobs(logits, next_tokens, max_logprobs):
1029
+ logprobs = compute_logprobs(logits)
1030
+ return gather_logprobs(logprobs, next_tokens, max_logprobs)
1031
+
1032
+ def _prepare_dp_input_metadata(self,
1033
+ scheduler_output: "VllmSchedulerOutput"):
1034
+
1035
+ dp_size = self.dp_size
1036
+ num_reqs = self.input_batch.num_reqs
1037
+ max_num_reqs_per_dp_rank = self.max_num_reqs // dp_size
1038
+ req_ids_dp = {dp_rank: [] for dp_rank in range(dp_size)}
1039
+ req_indices_dp = {dp_rank: [] for dp_rank in range(dp_size)}
1040
+ num_scheduled_tokens_per_dp_rank = {
1041
+ dp_rank: 0
1042
+ for dp_rank in range(dp_size)
1043
+ }
1044
+ scheduled_tokens_per_dp_rank = {
1045
+ dp_rank: []
1046
+ for dp_rank in range(dp_size)
1047
+ }
1048
+ num_req_per_dp_rank = {dp_rank: 0 for dp_rank in range(dp_size)}
1049
+
1050
+ for req_id in self.input_batch.req_ids[:num_reqs]:
1051
+ dp_rank = scheduler_output.assigned_dp_rank[req_id]
1052
+ req_ids_dp[dp_rank].append(req_id)
1053
+ req_indices_dp[dp_rank].append(
1054
+ self.input_batch.req_id_to_index[req_id])
1055
+ num_scheduled_tokens_per_dp_rank[
1056
+ dp_rank] += scheduler_output.num_scheduled_tokens[req_id]
1057
+ scheduled_tokens_per_dp_rank[dp_rank].append(
1058
+ scheduler_output.num_scheduled_tokens[req_id])
1059
+ num_req_per_dp_rank[dp_rank] += 1
1060
+
1061
+ # Find maximum number of scheduled tokens across DP ranks
1062
+ max_num_scheduled_tokens_across_dp = max(
1063
+ num_scheduled_tokens_per_dp_rank.values())
1064
+
1065
+ padded_num_scheduled_tokens_per_dp_rank = runner_utils.get_padded_token_len(
1066
+ self.num_tokens_paddings_per_dp,
1067
+ max_num_scheduled_tokens_across_dp)
1068
+
1069
+ padded_total_num_scheduled_tokens = (
1070
+ padded_num_scheduled_tokens_per_dp_rank * dp_size)
1071
+
1072
+ assert max_num_scheduled_tokens_across_dp > 0
1073
+
1074
+ # Find maximum number of requests across DP ranks
1075
+ max_num_reqs_across_dp = max(
1076
+ len(req_ids) for req_ids in req_ids_dp.values())
1077
+ padded_num_reqs_per_dp_rank = runner_utils.get_padded_token_len(
1078
+ self.num_reqs_paddings_per_dp, max_num_reqs_across_dp)
1079
+ padded_num_reqs = padded_num_reqs_per_dp_rank * dp_size
1080
+
1081
+ all_req_indices = np.concatenate(
1082
+ [req_indices_dp[dp_rank] for dp_rank in range(dp_size)])
1083
+ all_positions = np.concatenate([
1084
+ np.arange(len(req_indices_dp[dp_rank])) +
1085
+ padded_num_reqs_per_dp_rank * dp_rank for dp_rank in range(dp_size)
1086
+ ])
1087
+
1088
+ # Sort positions by request indices
1089
+ sorted_indices = np.argsort(all_req_indices)
1090
+ logits_indices_selector = all_positions[sorted_indices]
1091
+
1092
+ return (req_ids_dp, req_indices_dp, num_scheduled_tokens_per_dp_rank,
1093
+ scheduled_tokens_per_dp_rank, num_req_per_dp_rank,
1094
+ padded_num_scheduled_tokens_per_dp_rank, padded_num_reqs,
1095
+ padded_total_num_scheduled_tokens, padded_num_reqs_per_dp_rank,
1096
+ logits_indices_selector, max_num_reqs_per_dp_rank)
1097
+
1098
+ def _prepare_async_token_substitution_indices_dp(
1099
+ self, req_ids_dp, scheduled_tokens_per_dp_rank,
1100
+ padded_num_scheduled_tokens_per_dp_rank, dp_size):
1101
+ """Prepare token substitution indices for async scheduling in DP mode."""
1102
+ token_in_tpu_cur_input_indices_dp = {}
1103
+ token_in_tpu_pre_next_tokens_indices_dp = {}
1104
+
1105
+ for dp_rank in range(dp_size):
1106
+ token_in_tpu_cur_input_indices_dp[dp_rank] = []
1107
+ token_in_tpu_pre_next_tokens_indices_dp[dp_rank] = []
1108
+
1109
+ token_offset = padded_num_scheduled_tokens_per_dp_rank * dp_rank
1110
+ acc_cur_len = token_offset
1111
+
1112
+ for i, req_id in enumerate(req_ids_dp[dp_rank]):
1113
+ acc_cur_len += scheduled_tokens_per_dp_rank[dp_rank][i]
1114
+ if req_id not in self._pre_async_results.placeholder_req_id_to_index:
1115
+ continue
1116
+
1117
+ token_in_tpu_cur_input_indices_dp[dp_rank].append(acc_cur_len -
1118
+ 1)
1119
+ token_in_tpu_pre_next_tokens_indices_dp[dp_rank].append(
1120
+ self._pre_async_results.placeholder_req_id_to_index[req_id]
1121
+ )
1122
+
1123
+ return token_in_tpu_cur_input_indices_dp, token_in_tpu_pre_next_tokens_indices_dp
1124
+
1125
+ def _prepare_async_token_substitution_indices_non_dp(
1126
+ self, num_reqs, num_scheduled_tokens_per_req):
1127
+ """Prepare token substitution indices for async scheduling in non-DP mode."""
1128
+ token_in_tpu_cur_input_indices_list = []
1129
+ token_in_tpu_pre_next_tokens_indices_list = []
1130
+ acc_cur_len = 0
1131
+
1132
+ for i, req_id in enumerate(self.input_batch.req_ids[:num_reqs]):
1133
+ acc_cur_len += num_scheduled_tokens_per_req[i]
1134
+ assert req_id is not None
1135
+ if req_id not in self._pre_async_results.placeholder_req_id_to_index:
1136
+ continue
1137
+
1138
+ token_in_tpu_cur_input_indices_list.append(acc_cur_len - 1)
1139
+ token_in_tpu_pre_next_tokens_indices_list.append(
1140
+ self._pre_async_results.placeholder_req_id_to_index[req_id])
1141
+
1142
+ if len(token_in_tpu_cur_input_indices_list) > 0:
1143
+ return (np.array(token_in_tpu_cur_input_indices_list),
1144
+ np.array(token_in_tpu_pre_next_tokens_indices_list))
1145
+ else:
1146
+ return np.array([]), np.array([])
1147
+
1148
+ def _apply_async_token_substitution(self, input_ids,
1149
+ token_in_tpu_cur_input_indices,
1150
+ token_in_tpu_pre_next_tokens_indices):
1151
+ """Apply async token substitution if needed."""
1152
+ if len(token_in_tpu_cur_input_indices) == 0:
1153
+ return input_ids
1154
+
1155
+ idx_pad_len = len(input_ids) - len(token_in_tpu_cur_input_indices)
1156
+
1157
+ # Pad according to the instructions written inside self._substitute_placeholder_token_fn
1158
+ full_range = np.arange(0, len(input_ids))
1159
+ missing_values = np.setdiff1d(full_range,
1160
+ token_in_tpu_cur_input_indices)
1161
+ padded_token_in_tpu_cur_input_indices = np.concatenate(
1162
+ (token_in_tpu_cur_input_indices, missing_values))
1163
+
1164
+ padded_token_in_tpu_pre_next_tokens_indices = np.pad(
1165
+ token_in_tpu_pre_next_tokens_indices, (0, idx_pad_len),
1166
+ mode='constant',
1167
+ constant_values=-1)
1168
+
1169
+ (padded_token_in_tpu_cur_input_indices,
1170
+ padded_token_in_tpu_pre_next_tokens_indices) = device_array(
1171
+ self.mesh, (padded_token_in_tpu_cur_input_indices,
1172
+ padded_token_in_tpu_pre_next_tokens_indices))
1173
+
1174
+ with self.maybe_forbid_compile:
1175
+ input_ids = self._substitute_placeholder_token_fn(
1176
+ input_ids, padded_token_in_tpu_cur_input_indices,
1177
+ padded_token_in_tpu_pre_next_tokens_indices,
1178
+ self._pre_async_results.next_tokens,
1179
+ len(token_in_tpu_cur_input_indices))
1180
+
1181
+ return input_ids
1182
+
1183
+ def _prepare_inputs(self, scheduler_output: "VllmSchedulerOutput"):
1184
+ if self.dp_size > 1:
1185
+ return self._prepare_inputs_dp(scheduler_output)
1186
+ else:
1187
+ return self._prepare_inputs_non_dp(scheduler_output)
1188
+
1189
+ def _prepare_inputs_dp(self, scheduler_output: "VllmSchedulerOutput"):
1190
+ total_num_scheduled_tokens = scheduler_output.total_num_scheduled_tokens
1191
+ assert total_num_scheduled_tokens > 0
1192
+ num_reqs = self.input_batch.num_reqs
1193
+ assert num_reqs > 0
1194
+
1195
+ dp_size = self.dp_size
1196
+ data_parallel_attn_sharding = NamedSharding(
1197
+ self.mesh, PartitionSpec(ShardingAxisName.ATTN_DATA))
1198
+
1199
+ (req_ids_dp, req_indices_dp, num_scheduled_tokens_per_dp_rank,
1200
+ scheduled_tokens_per_dp_rank, num_req_per_dp_rank,
1201
+ padded_num_scheduled_tokens_per_dp_rank, padded_num_reqs,
1202
+ padded_total_num_scheduled_tokens, padded_num_reqs_per_dp_rank,
1203
+ logits_indices_selector, max_num_reqs_per_dp_rank
1204
+ ) = self._prepare_dp_input_metadata(scheduler_output)
1205
+ # Multi-modal support
1206
+ # Calculate M-RoPE positions.
1207
+ # Only relevant for models using M-RoPE (e.g, Qwen2-VL)
1208
+ if self.uses_mrope:
1209
+ self.mm_manager.calc_mrope_positions(scheduler_output)
1210
+
1211
+ # Async scheduling: prepare token substitution indices for DP
1212
+ token_in_tpu_cur_input_indices_dp = {}
1213
+ token_in_tpu_pre_next_tokens_indices_dp = {}
1214
+ if self.scheduler_config.async_scheduling and self._pre_async_results is not None:
1215
+ # If async previous results exists, we will prepare for the token substitution here
1216
+ # The actual substitution will be performed in tpu during later parts of this function.
1217
+ (token_in_tpu_cur_input_indices_dp,
1218
+ token_in_tpu_pre_next_tokens_indices_dp
1219
+ ) = self._prepare_async_token_substitution_indices_dp(
1220
+ req_ids_dp, scheduled_tokens_per_dp_rank,
1221
+ padded_num_scheduled_tokens_per_dp_rank, dp_size)
1222
+
1223
+ # Populates input_ids and positions
1224
+ for dp_rank in range(dp_size):
1225
+ if num_req_per_dp_rank[dp_rank] == 0:
1226
+ continue
1227
+ token_offset = padded_num_scheduled_tokens_per_dp_rank * dp_rank
1228
+ num_scheduled_tokens_per_req = scheduled_tokens_per_dp_rank[
1229
+ dp_rank]
1230
+ total_num_scheduled_tokens = num_scheduled_tokens_per_dp_rank[
1231
+ dp_rank]
1232
+ input_ids_cpu = self.input_ids_cpu[
1233
+ token_offset:token_offset +
1234
+ padded_num_scheduled_tokens_per_dp_rank]
1235
+ positions_cpu = self.positions_cpu[
1236
+ token_offset:token_offset +
1237
+ padded_num_scheduled_tokens_per_dp_rank]
1238
+ # Get request indices.
1239
+ # E.g., [2, 5, 3] -> [0, 0, 1, 1, 1, 1, 1, 2, 2, 2]
1240
+ # For each scheduled token, what are the corresponding req index.
1241
+ req_indices = np.repeat(req_indices_dp[dp_rank],
1242
+ num_scheduled_tokens_per_req)
1243
+ # Get batched arange.
1244
+ # E.g., [2, 5, 3] -> [0, 1, 0, 1, 2, 3, 4, 0, 1, 2]
1245
+ # For each scheduled token, what is its position in corresponding req.
1246
+ arange = np.concatenate(
1247
+ [self.arange_cpu[:n] for n in num_scheduled_tokens_per_req])
1248
+ # Get positions.
1249
+ positions_np = positions_cpu[:total_num_scheduled_tokens]
1250
+ np.add(
1251
+ self.input_batch.num_computed_tokens_cpu[req_indices],
1252
+ arange,
1253
+ out=positions_np,
1254
+ )
1255
+ # Get token indices.
1256
+ # E.g., [0, 1, 0, 1, 2, 3, 4, 0, 1, 2]
1257
+ # -> [0, 1, M, M + 1, M + 2, M + 3, M + 4, 2 * M, 2 * M + 1, 2 * M + 2]
1258
+ # where M is the max_model_len.
1259
+ token_indices = (
1260
+ positions_np +
1261
+ req_indices * self.input_batch.token_ids_cpu.shape[1])
1262
+ # NOTE(woosuk): We use torch.index_select instead of np.take here
1263
+ # because torch.index_select is much faster than np.take for large
1264
+ # tensors.
1265
+ np.take(
1266
+ self.input_batch.token_ids_cpu.ravel(),
1267
+ token_indices,
1268
+ out=input_ids_cpu[:total_num_scheduled_tokens],
1269
+ )
1270
+
1271
+ input_ids_cpu[total_num_scheduled_tokens:] = 0
1272
+
1273
+ # Prepare the attention metadata (query_start_loc_cpu, seq_lens_cpu)
1274
+ for dp_rank in range(dp_size):
1275
+ req_offset = dp_rank * max_num_reqs_per_dp_rank
1276
+ query_start_loc_cpu = self.query_start_loc_cpu[
1277
+ req_offset + dp_rank:req_offset + max_num_reqs_per_dp_rank +
1278
+ dp_rank + 1]
1279
+ seq_lens_cpu = self.seq_lens_cpu[req_offset:req_offset +
1280
+ max_num_reqs_per_dp_rank]
1281
+ _num_reqs = num_req_per_dp_rank[dp_rank]
1282
+ req_indices = req_indices_dp[dp_rank]
1283
+ num_scheduled_tokens_per_req = scheduled_tokens_per_dp_rank[
1284
+ dp_rank]
1285
+
1286
+ if _num_reqs == 0:
1287
+ query_start_loc_cpu[:] = 0
1288
+ seq_lens_cpu[:] = 0
1289
+ continue
1290
+
1291
+ np.cumsum(
1292
+ num_scheduled_tokens_per_req,
1293
+ out=query_start_loc_cpu[1:_num_reqs + 1],
1294
+ )
1295
+ query_start_loc_cpu[_num_reqs + 1:] = 1
1296
+
1297
+ seq_lens_cpu[:_num_reqs] = (
1298
+ self.input_batch.num_computed_tokens_cpu[req_indices] +
1299
+ num_scheduled_tokens_per_req)
1300
+ seq_lens_cpu[_num_reqs:] = 0
1301
+
1302
+ # populate logits_indices
1303
+ for dp_rank in range(dp_size):
1304
+ req_offset = dp_rank * padded_num_reqs_per_dp_rank
1305
+ query_loc_req_offset = dp_rank * (max_num_reqs_per_dp_rank + 1)
1306
+ _num_reqs = num_req_per_dp_rank[dp_rank]
1307
+
1308
+ logits_indices_cpu = self.logits_indices_cpu[
1309
+ req_offset:req_offset + padded_num_reqs_per_dp_rank]
1310
+ logits_indices_cpu[:_num_reqs] = (
1311
+ self.query_start_loc_cpu[query_loc_req_offset +
1312
+ 1:query_loc_req_offset + _num_reqs +
1313
+ 1] - 1)
1314
+ logits_indices_cpu[_num_reqs:] = -1
1315
+
1316
+ logits_indices = self.logits_indices_cpu[:padded_num_reqs]
1317
+
1318
+ # Please see runner_utils.PhasedBasedProfiler for details
1319
+ if self.phase_based_profiler:
1320
+ batch_composition_stats = runner_utils.get_batch_composition_stats(
1321
+ self.input_batch, total_num_scheduled_tokens, num_reqs,
1322
+ padded_total_num_scheduled_tokens, scheduler_output)
1323
+
1324
+ self.phase_based_profiler.step(batch_composition_stats)
1325
+
1326
+ # Inputs
1327
+ input_ids = self.input_ids_cpu[:padded_total_num_scheduled_tokens]
1328
+ positions = self.positions_cpu[:padded_total_num_scheduled_tokens]
1329
+ mrope_positions = self.mrope_positions_cpu[:, :
1330
+ padded_total_num_scheduled_tokens]
1331
+
1332
+ query_start_loc = self.query_start_loc_cpu[:self.max_num_reqs +
1333
+ dp_size]
1334
+ seq_lens = self.seq_lens_cpu[:self.max_num_reqs]
1335
+
1336
+ _request_distribution = []
1337
+ for dp_rank in range(dp_size):
1338
+ _num_reqs = num_req_per_dp_rank[dp_rank]
1339
+ _request_distribution.append([0, 0, _num_reqs])
1340
+ request_distribution = np.array(_request_distribution).ravel()
1341
+
1342
+ use_spec_decode = len(
1343
+ scheduler_output.scheduled_spec_decode_tokens) > 0
1344
+ if not use_spec_decode:
1345
+ spec_decode_metadata = None
1346
+ else:
1347
+ num_draft_tokens = np.zeros(num_reqs, dtype=np.int32)
1348
+ for (
1349
+ req_id,
1350
+ draft_token_ids,
1351
+ ) in scheduler_output.scheduled_spec_decode_tokens.items():
1352
+ req_idx = self.input_batch.req_id_to_index[req_id]
1353
+ num_draft_tokens[req_idx] = len(draft_token_ids)
1354
+
1355
+ spec_decode_metadata = (
1356
+ self.speculative_decoding_manager.get_spec_decode_metadata(
1357
+ num_draft_tokens,
1358
+ self.query_start_loc_cpu[1:num_reqs + 1],
1359
+ padded_num_reqs,
1360
+ ))
1361
+ logits_indices = spec_decode_metadata.final_logits_indices
1362
+
1363
+ # Put to device
1364
+ sampling_metadata = TPUSupportedSamplingMetadata.from_input_batch(
1365
+ self.mesh,
1366
+ self.input_batch,
1367
+ padded_num_reqs,
1368
+ sharding=data_parallel_attn_sharding,
1369
+ )
1370
+ if self.uses_mrope:
1371
+ positions = mrope_positions
1372
+
1373
+ query_start_loc_cpu = query_start_loc
1374
+ logits_indices_cpu = logits_indices
1375
+ seq_lens_cpu = seq_lens
1376
+
1377
+ (input_ids, positions, query_start_loc, seq_lens, logits_indices,
1378
+ request_distribution) = device_array(
1379
+ self.mesh,
1380
+ (input_ids, positions, query_start_loc, seq_lens, logits_indices,
1381
+ request_distribution),
1382
+ sharding=data_parallel_attn_sharding,
1383
+ )
1384
+
1385
+ attention_metadata_per_layer: Dict[str, AttentionMetadata] = {}
1386
+ uniform_attention_metadata: AttentionMetadata = None
1387
+ for kv_cache_gid, kv_cache_group in enumerate(
1388
+ self.kv_cache_config.kv_cache_groups):
1389
+ block_tables = self.block_tables_cpu[kv_cache_gid][:self.
1390
+ max_num_reqs]
1391
+ for dp_rank in range(dp_size):
1392
+ req_offset = dp_rank * max_num_reqs_per_dp_rank
1393
+ _num_reqs = num_req_per_dp_rank[dp_rank]
1394
+
1395
+ block_tables[
1396
+ req_offset:req_offset + _num_reqs, :self.
1397
+ max_num_blocks_per_req] = self.input_batch.block_table[
1398
+ 0].get_cpu_tensor()[req_indices_dp[dp_rank]]
1399
+ # Convert block_tables to 1D on cpu.
1400
+ block_tables = block_tables.reshape(-1)
1401
+ block_tables = device_array(
1402
+ self.mesh,
1403
+ (block_tables),
1404
+ sharding=data_parallel_attn_sharding,
1405
+ )
1406
+
1407
+ attention_metadata_gid = AttentionMetadata(
1408
+ input_positions=positions,
1409
+ block_tables=block_tables,
1410
+ seq_lens=seq_lens,
1411
+ query_start_loc=query_start_loc,
1412
+ request_distribution=request_distribution,
1413
+ )
1414
+
1415
+ # This is for making these cpu buffers hidden during tracing
1416
+ attention_metadata_gid.query_start_loc_cpu = query_start_loc_cpu
1417
+ attention_metadata_gid.seq_lens_cpu = seq_lens_cpu
1418
+
1419
+ if not self.use_hybrid_kvcache:
1420
+ uniform_attention_metadata = attention_metadata_gid
1421
+ else:
1422
+ for layer_name in kv_cache_group.layer_names:
1423
+ attention_metadata_per_layer[
1424
+ layer_name] = attention_metadata_gid
1425
+
1426
+ # Async scheduling: substitute placeholder tokens for DP
1427
+ if self.scheduler_config.async_scheduling and self._pre_async_results is not None:
1428
+ # Collect all token indices that need substitution across all DP ranks
1429
+ all_token_indices_to_substitute = []
1430
+ all_pre_next_tokens_indices = []
1431
+
1432
+ for dp_rank in range(dp_size):
1433
+ cur_indices = token_in_tpu_cur_input_indices_dp[dp_rank]
1434
+ pre_indices = token_in_tpu_pre_next_tokens_indices_dp[dp_rank]
1435
+ all_token_indices_to_substitute.extend(cur_indices)
1436
+ all_pre_next_tokens_indices.extend(pre_indices)
1437
+
1438
+ if len(all_token_indices_to_substitute) > 0:
1439
+ token_in_tpu_cur_input_indices = np.array(
1440
+ all_token_indices_to_substitute)
1441
+ token_in_tpu_pre_next_tokens_indices = np.array(
1442
+ all_pre_next_tokens_indices)
1443
+ input_ids = self._apply_async_token_substitution(
1444
+ input_ids, token_in_tpu_cur_input_indices,
1445
+ token_in_tpu_pre_next_tokens_indices)
1446
+
1447
+ if self.lora_config is not None:
1448
+ self.lora_utils.set_active_loras(
1449
+ num_scheduled_tokens_per_req,
1450
+ total_num_scheduled_tokens,
1451
+ padded_total_num_scheduled_tokens,
1452
+ )
1453
+
1454
+ if self.use_hybrid_kvcache:
1455
+ attention_metadata = attention_metadata_per_layer
1456
+ else:
1457
+ attention_metadata = uniform_attention_metadata
1458
+ return (
1459
+ input_ids,
1460
+ positions,
1461
+ attention_metadata,
1462
+ sampling_metadata,
1463
+ logits_indices,
1464
+ spec_decode_metadata,
1465
+ logits_indices_selector,
1466
+ padded_num_reqs,
1467
+ )
1468
+
1469
+ def _prepare_inputs_non_dp(self, scheduler_output: "VllmSchedulerOutput"):
1470
+ total_num_scheduled_tokens = scheduler_output.total_num_scheduled_tokens
1471
+ assert total_num_scheduled_tokens > 0
1472
+ num_reqs = self.input_batch.num_reqs
1473
+ assert num_reqs > 0
1474
+
1475
+ # Get the number of scheduled tokens for each request.
1476
+ num_scheduled_tokens_per_req = []
1477
+ max_num_scheduled_tokens_all_reqs = 0
1478
+ for req_id in self.input_batch.req_ids[:num_reqs]:
1479
+ assert req_id is not None
1480
+ num_tokens = scheduler_output.num_scheduled_tokens[req_id]
1481
+ num_scheduled_tokens_per_req.append(num_tokens)
1482
+ max_num_scheduled_tokens_all_reqs = max(
1483
+ max_num_scheduled_tokens_all_reqs, num_tokens)
1484
+ num_scheduled_tokens_per_req = np.array(num_scheduled_tokens_per_req,
1485
+ dtype=np.int32)
1486
+ assert max_num_scheduled_tokens_all_reqs > 0
1487
+ padded_num_reqs = runner_utils.get_padded_num_reqs_with_upper_limit(
1488
+ num_reqs, self.max_num_reqs)
1489
+
1490
+ # Get request indices.
1491
+ # E.g., [2, 5, 3] -> [0, 0, 1, 1, 1, 1, 1, 2, 2, 2]
1492
+ # For each scheduled token, what are the corresponding req index.
1493
+ req_indices = np.repeat(self.arange_cpu[:num_reqs],
1494
+ num_scheduled_tokens_per_req)
1495
+ token_in_tpu_cur_input_indices = np.array([])
1496
+ token_in_tpu_pre_next_tokens_indices = np.array([])
1497
+ if self.scheduler_config.async_scheduling and self._pre_async_results is not None:
1498
+ # If async previous results exists, we will prepare for the token substitution here
1499
+ # The actual substitution will be performed in tpu during later parts of this function.
1500
+ (token_in_tpu_cur_input_indices,
1501
+ token_in_tpu_pre_next_tokens_indices
1502
+ ) = self._prepare_async_token_substitution_indices_non_dp(
1503
+ num_reqs, num_scheduled_tokens_per_req)
1504
+
1505
+ # Get batched arange.
1506
+ # E.g., [2, 5, 3] -> [0, 1, 0, 1, 2, 3, 4, 0, 1, 2]
1507
+ # For each scheduled token, what is its position in corresponding req.
1508
+ arange = np.concatenate(
1509
+ [self.arange_cpu[:n] for n in num_scheduled_tokens_per_req])
1510
+
1511
+ # Get positions.
1512
+ positions_np = self.positions_cpu[:total_num_scheduled_tokens]
1513
+ np.add(self.input_batch.num_computed_tokens_cpu[req_indices],
1514
+ arange,
1515
+ out=positions_np)
1516
+
1517
+ # Multi-modal support
1518
+ # Calculate M-RoPE positions.
1519
+ # Only relevant for models using M-RoPE (e.g, Qwen2-VL)
1520
+ if self.uses_mrope:
1521
+ self.mm_manager.calc_mrope_positions(scheduler_output)
1522
+
1523
+ # Get token indices.
1524
+ # E.g., [0, 1, 0, 1, 2, 3, 4, 0, 1, 2]
1525
+ # -> [0, 1, M, M + 1, M + 2, M + 3, M + 4, 2 * M, 2 * M + 1, 2 * M + 2]
1526
+ # where M is the max_model_len.
1527
+ token_indices = (positions_np +
1528
+ req_indices * self.input_batch.token_ids_cpu.shape[1])
1529
+
1530
+ # NOTE(woosuk): We use torch.index_select instead of np.take here
1531
+ # because torch.index_select is much faster than np.take for large
1532
+ # tensors.
1533
+ np.take(self.input_batch.token_ids_cpu.ravel(),
1534
+ token_indices,
1535
+ out=self.input_ids_cpu[:total_num_scheduled_tokens])
1536
+
1537
+ # Prepare the attention metadata.
1538
+ self.query_start_loc_cpu[0] = 0
1539
+ np.cumsum(num_scheduled_tokens_per_req,
1540
+ out=self.query_start_loc_cpu[1:num_reqs + 1])
1541
+ self.query_start_loc_cpu[num_reqs + 1:] = 1
1542
+
1543
+ self.seq_lens_cpu[:num_reqs] = (
1544
+ self.input_batch.num_computed_tokens_cpu[:num_reqs] +
1545
+ num_scheduled_tokens_per_req)
1546
+
1547
+ # Do the padding and copy the tensors to the TPU.
1548
+ padded_total_num_scheduled_tokens = runner_utils.get_padded_token_len(
1549
+ self.num_tokens_paddings, total_num_scheduled_tokens)
1550
+ # Zero out to avoid spurious values from prev iteration (last cp chunk)
1551
+ self.input_ids_cpu[
1552
+ total_num_scheduled_tokens:padded_total_num_scheduled_tokens] = 0
1553
+
1554
+ # Please see runner_utils.PhasedBasedProfiler for details
1555
+ if self.phase_based_profiler:
1556
+ batch_composition_stats = runner_utils.get_batch_composition_stats(
1557
+ self.input_batch, total_num_scheduled_tokens, num_reqs,
1558
+ padded_total_num_scheduled_tokens, scheduler_output)
1559
+
1560
+ self.phase_based_profiler.step(batch_composition_stats)
1561
+
1562
+ # Inputs
1563
+ input_ids = self.input_ids_cpu[:padded_total_num_scheduled_tokens]
1564
+ positions = self.positions_cpu[:padded_total_num_scheduled_tokens]
1565
+ mrope_positions = self.mrope_positions_cpu[:, :
1566
+ padded_total_num_scheduled_tokens]
1567
+
1568
+ # TODO(pooyam): Some paddings are up to `num_reqs_paddings` (spec decoding, select hidden states, etc) and some other are to `max_num_reqs` (block table, seq_lens). We should stick to one of them maybe?
1569
+ query_start_loc = self.query_start_loc_cpu[:self.max_num_reqs + 1]
1570
+ seq_lens = self.seq_lens_cpu[:self.max_num_reqs]
1571
+ request_distribution = np.array(self.input_batch.request_distribution)
1572
+ use_spec_decode = len(
1573
+ scheduler_output.scheduled_spec_decode_tokens) > 0
1574
+ if not use_spec_decode:
1575
+ logits_indices = self.query_start_loc_cpu[1:padded_num_reqs +
1576
+ 1] - 1
1577
+ spec_decode_metadata = None
1578
+ else:
1579
+ num_draft_tokens = np.zeros(num_reqs, dtype=np.int32)
1580
+ for req_id, draft_token_ids in (
1581
+ scheduler_output.scheduled_spec_decode_tokens.items()):
1582
+ req_idx = self.input_batch.req_id_to_index[req_id]
1583
+ num_draft_tokens[req_idx] = len(draft_token_ids)
1584
+
1585
+ spec_decode_metadata = self.speculative_decoding_manager.get_spec_decode_metadata(
1586
+ num_draft_tokens, self.query_start_loc_cpu[1:num_reqs + 1],
1587
+ padded_num_reqs)
1588
+ logits_indices = spec_decode_metadata.final_logits_indices
1589
+
1590
+ # Put to device
1591
+ sampling_metadata = TPUSupportedSamplingMetadata.from_input_batch(
1592
+ self.mesh, self.input_batch, padded_num_reqs)
1593
+ if self.uses_mrope:
1594
+ positions = mrope_positions
1595
+ query_start_loc_cpu = query_start_loc
1596
+ seq_lens_cpu = seq_lens
1597
+
1598
+ (input_ids, positions, query_start_loc, seq_lens,
1599
+ logits_indices, request_distribution) = device_array(
1600
+ self.mesh, (input_ids, positions, query_start_loc, seq_lens,
1601
+ logits_indices, request_distribution))
1602
+
1603
+ attention_metadata_per_layer: Dict[str, AttentionMetadata] = {}
1604
+ uniform_attention_metadata: AttentionMetadata = None
1605
+ for kv_cache_gid, kv_cache_group in enumerate(
1606
+ self.kv_cache_config.kv_cache_groups):
1607
+ block_tables = self.block_tables_cpu[kv_cache_gid][:self.
1608
+ max_num_reqs]
1609
+ block_tables[:num_reqs] = (
1610
+ self.input_batch.block_table[kv_cache_gid].get_cpu_tensor()
1611
+ [:num_reqs])
1612
+ # Convert block_tables to 1D on cpu.
1613
+ block_tables = block_tables.reshape(-1)
1614
+ block_tables = device_array(self.mesh, (block_tables))
1615
+
1616
+ attention_metadata_gid = AttentionMetadata(
1617
+ input_positions=positions,
1618
+ block_tables=block_tables,
1619
+ seq_lens=seq_lens,
1620
+ query_start_loc=query_start_loc,
1621
+ request_distribution=request_distribution)
1622
+ # This is for making these cpu buffers hidden during tracing
1623
+ attention_metadata_gid.query_start_loc_cpu = query_start_loc_cpu
1624
+ attention_metadata_gid.seq_lens_cpu = seq_lens_cpu
1625
+
1626
+ if not self.use_hybrid_kvcache:
1627
+ # all layers share the same attention metadata
1628
+ uniform_attention_metadata = attention_metadata_gid
1629
+ else:
1630
+ for layer_name in kv_cache_group.layer_names:
1631
+ attention_metadata_per_layer[
1632
+ layer_name] = attention_metadata_gid
1633
+
1634
+ if self.scheduler_config.async_scheduling and len(
1635
+ token_in_tpu_cur_input_indices) > 0:
1636
+ assert self._pre_async_results is not None
1637
+ input_ids = self._apply_async_token_substitution(
1638
+ input_ids, token_in_tpu_cur_input_indices,
1639
+ token_in_tpu_pre_next_tokens_indices)
1640
+
1641
+ if self.lora_config is not None:
1642
+ self.lora_utils.set_active_loras(
1643
+ num_scheduled_tokens_per_req, total_num_scheduled_tokens,
1644
+ padded_total_num_scheduled_tokens)
1645
+ logits_indices_selector = None
1646
+
1647
+ if self.use_hybrid_kvcache:
1648
+ attention_metadata = attention_metadata_per_layer
1649
+ else:
1650
+ attention_metadata = uniform_attention_metadata
1651
+ return (input_ids, positions, attention_metadata, sampling_metadata,
1652
+ logits_indices, spec_decode_metadata, logits_indices_selector,
1653
+ padded_num_reqs)
1654
+
1655
+ def _get_input_ids_embeds(self, input_ids: jax.Array,
1656
+ mm_embeds: list[jax.Array]):
1657
+ if self.is_multimodal_model:
1658
+ inputs_embeds = self.get_input_embeddings_fn(
1659
+ self.state,
1660
+ input_ids,
1661
+ mm_embeds,
1662
+ )
1663
+ return None, inputs_embeds
1664
+ else:
1665
+ return input_ids, None
1666
+
1667
+ def take_draft_token_ids(self) -> Optional[DraftTokenIds]:
1668
+ return self.speculative_decoding_manager.take_draft_token_ids()
1669
+
1670
+ ###### Local disagg utilities ######
1671
+
1672
+ def get_kv_cache_for_block_ids(
1673
+ self,
1674
+ block_ids: List[int],
1675
+ ) -> List[jax.Array]:
1676
+ return self.kv_cache_manager.get_kv_cache_for_block_ids(block_ids)
1677
+
1678
+ def transfer_kv_cache(self,
1679
+ kv_cache_slices: List[jax.Array]) -> List[jax.Array]:
1680
+ return self.kv_cache_manager.transfer_kv_cache(kv_cache_slices)
1681
+
1682
+ def insert_request_with_kv_cache(
1683
+ self,
1684
+ request: "Request",
1685
+ kv_cache_slices: List[jax.Array],
1686
+ block_ids: List[List[int]],
1687
+ ):
1688
+ return self.kv_cache_manager.insert_request_with_kv_cache(
1689
+ request, kv_cache_slices, block_ids)
1690
+
1691
+ ###### RL framework integration ######
1692
+
1693
+ def _sync_weights(
1694
+ self,
1695
+ updated_weights: jaxtyping.PyTree,
1696
+ mappings: Dict[str, Tuple[str, Tuple[str]]],
1697
+ transpose_keys: Dict[str, Tuple[int]],
1698
+ reshard_fn: Callable[[jaxtyping.PyTree, jaxtyping.PyTree],
1699
+ jaxtyping.PyTree] = None
1700
+ ) -> None:
1701
+ """For RL framework integration."""
1702
+ if reshard_fn is not None:
1703
+ updated_weights = reshard_fn(updated_weights, self.state)
1704
+ shard = None
1705
+ else:
1706
+ shard = functools.partial(shard_put, mesh=self.mesh)
1707
+ self.state = transfer_state_with_mappings(
1708
+ src_state=updated_weights,
1709
+ tgt_state=self.state,
1710
+ mappings=mappings,
1711
+ transpose_keys=transpose_keys,
1712
+ shard=shard)
1713
+
1714
+ def get_intermediate_tensor_spec(self, num_tokens: int):
1715
+ impl = os.getenv("MODEL_IMPL_TYPE", "flax_nnx").lower()
1716
+ jax_dtype = t2j_dtype(self.dtype) if impl == "vllm" else self.dtype
1717
+ num_padded_tokens = runner_utils.get_padded_token_len(
1718
+ self.num_tokens_paddings, num_tokens)
1719
+ sharding = NamedSharding(self.mesh, PartitionSpec())
1720
+ hidden_size = self.model_config.get_hidden_size()
1721
+ spec = jax.ShapeDtypeStruct(shape=(num_padded_tokens, hidden_size),
1722
+ dtype=jax_dtype,
1723
+ sharding=sharding)
1724
+ tensor_spec = {"hidden_states": spec, "residual": spec}
1725
+ return tensor_spec
1726
+
1727
+ def get_uuid_for_jax_transfer(self,
1728
+ scheduler_output: "VllmSchedulerOutput",
1729
+ rank: int, step: int) -> int:
1730
+ '''
1731
+ Get a uuid for jax.transfer, here we use the hash of
1732
+ scheduler_output + counter_step + sender's rank
1733
+ '''
1734
+ scheduler_output_str = ""
1735
+ if not scheduler_output.num_scheduled_tokens:
1736
+ scheduler_output_str = "empty_batch"
1737
+ else:
1738
+ scheduler_output_str = str(
1739
+ sorted(scheduler_output.num_scheduled_tokens.items()))
1740
+ unique_str = f'{scheduler_output_str} {step} {rank}'
1741
+ import hashlib
1742
+ hasher = hashlib.sha1()
1743
+ hasher.update(unique_str.encode('utf-8'))
1744
+ return int.from_bytes(hasher.digest()[:8], 'big')