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,248 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+ from typing import TYPE_CHECKING, Optional
5
+
6
+ import jax.numpy as jnp
7
+ import numpy as np
8
+ from vllm.v1.core.sched.output import SchedulerOutput as VllmSchedulerOutput
9
+ from vllm.v1.outputs import DraftTokenIds
10
+ from vllm.v1.spec_decode.ngram_proposer import NgramProposer
11
+
12
+ from tpu_inference.runner import utils as runner_utils
13
+ from tpu_inference.spec_decode.jax.eagle3 import Eagle3Proposer
14
+ from tpu_inference.utils import device_array
15
+
16
+ if TYPE_CHECKING:
17
+ from tpu_inference.layers.common.attention_metadata import \
18
+ AttentionMetadata
19
+ from tpu_inference.runner.tpu_runner import TPUModelRunner
20
+
21
+
22
+ @dataclass
23
+ class SpecDecodeMetadata:
24
+ """Metadata for speculative decoding on JAX/TPU, containing all necessary indices."""
25
+ draft_token_ids: jnp.ndarray
26
+ draft_lengths: jnp.ndarray
27
+ draft_lengths_cpu: np.ndarray
28
+ target_logits_indices: jnp.ndarray
29
+ bonus_logits_indices: jnp.ndarray
30
+ final_logits_indices: jnp.ndarray
31
+
32
+
33
+ class SpeculativeDecodingManager:
34
+
35
+ def __init__(self, runner: TPUModelRunner):
36
+ self.runner = runner
37
+ # Cached draft tokens.
38
+ self._draft_token_ids: Optional[list[list[int]]] = None
39
+
40
+ def take_draft_token_ids(self) -> Optional[DraftTokenIds]:
41
+ if self._draft_token_ids is None:
42
+ return None
43
+ req_ids = self.runner.input_batch.req_ids
44
+ draft_token_ids = self._draft_token_ids
45
+ self._draft_token_ids = None
46
+ return DraftTokenIds(req_ids, draft_token_ids)
47
+
48
+ def propose_draft_token_ids(
49
+ self,
50
+ sampled_token_ids: list[list[int]],
51
+ aux_hidden_states: Optional[tuple[jnp.ndarray, ...]],
52
+ attn_metadata: AttentionMetadata,
53
+ spec_decode_metadata: Optional[SpecDecodeMetadata],
54
+ scheduler_output: Optional[VllmSchedulerOutput] = None,
55
+ input_ids: Optional[jnp.ndarray] = None,
56
+ ) -> None:
57
+ if self.runner.speculative_config.method == "ngram":
58
+ assert isinstance(self.runner.drafter, NgramProposer)
59
+ self._draft_token_ids = self.runner.drafter.propose(
60
+ sampled_token_ids[:self.runner.input_batch.num_reqs],
61
+ self.runner.input_batch.req_ids,
62
+ self.runner.input_batch.num_tokens_no_spec,
63
+ self.runner.input_batch.token_ids_cpu,
64
+ self.runner.input_batch.spec_decode_unsupported_reqs)
65
+ elif self.runner.speculative_config.method == "eagle3":
66
+ self._draft_token_ids = self.propose_eagle3_draft_token_ids(
67
+ sampled_token_ids,
68
+ aux_hidden_states,
69
+ attn_metadata,
70
+ spec_decode_metadata,
71
+ scheduler_output,
72
+ input_ids,
73
+ )
74
+ else:
75
+ raise NotImplementedError(
76
+ f"Speculative decoding method "
77
+ f"'{self.runner.speculative_config.method}' is not supported.")
78
+
79
+ def propose_eagle3_draft_token_ids(
80
+ self,
81
+ sampled_token_ids: list[list[int]],
82
+ aux_hidden_states: Optional[tuple[jnp.ndarray, ...]],
83
+ attn_metadata: AttentionMetadata,
84
+ spec_decode_metadata: Optional[SpecDecodeMetadata],
85
+ scheduler_output: VllmSchedulerOutput,
86
+ input_ids: jnp.ndarray,
87
+ ) -> list[list[int]]:
88
+ assert isinstance(self.runner.drafter, Eagle3Proposer)
89
+
90
+ # TODO(woosuk): Refactor the loop.
91
+ req_ids = self.runner.input_batch.req_ids
92
+ next_token_ids: list[int] = []
93
+ for i, token_ids in enumerate(sampled_token_ids):
94
+ if token_ids:
95
+ # Common case.
96
+ next_token_id = token_ids[-1]
97
+ else:
98
+ # Partial prefill (rare case).
99
+ # Get the next token id from the request state.
100
+ req_id = req_ids[i]
101
+ req_state = self.runner.requests[req_id]
102
+ seq_len = (req_state.num_computed_tokens +
103
+ scheduler_output.num_scheduled_tokens[req_id])
104
+ next_token_id = req_state.get_token_id(seq_len)
105
+ next_token_ids.append(next_token_id)
106
+
107
+ # Pad the batch size to match with existing padding for target model
108
+ pad_len = attn_metadata.seq_lens.shape[0] - len(next_token_ids)
109
+ assert pad_len >= 0
110
+ next_token_ids += [0] * pad_len
111
+
112
+ next_token_ids = device_array(
113
+ self.runner.mesh, np.array(next_token_ids, dtype=jnp.int32))
114
+
115
+ if spec_decode_metadata is None:
116
+ num_rejected_tokens = None
117
+ else:
118
+ num_draft_tokens = spec_decode_metadata.draft_lengths_cpu
119
+ num_rejected_tokens = [
120
+ int(n) + 1 - len(sampled_token_ids[i]) if n > 0 else 0
121
+ for i, n in enumerate(num_draft_tokens)
122
+ ]
123
+
124
+ pad_len = self.runner.max_num_reqs - len(num_rejected_tokens)
125
+ num_rejected_tokens += [0] * pad_len
126
+ num_rejected_tokens = device_array(
127
+ self.runner.mesh, np.array(num_rejected_tokens,
128
+ dtype=jnp.int32))
129
+
130
+ target_hidden_states, input_ids, last_token_indices, attn_metadata = self.runner.drafter.prepare_inputs(
131
+ attn_metadata,
132
+ input_ids,
133
+ aux_hidden_states,
134
+ next_token_ids,
135
+ num_rejected_tokens,
136
+ )
137
+
138
+ self.runner.kv_caches, draft_token_ids = self.runner.drafter.propose(
139
+ kv_caches=self.runner.kv_caches,
140
+ input_ids=input_ids,
141
+ attn_metadata=attn_metadata,
142
+ last_token_indices=last_token_indices,
143
+ target_hidden_states=target_hidden_states,
144
+ )
145
+ draft_token_ids = np.array(draft_token_ids)
146
+ if draft_token_ids.ndim == 1:
147
+ draft_token_ids = np.expand_dims(draft_token_ids, axis=-1)
148
+ return draft_token_ids.tolist()
149
+
150
+ def get_spec_decode_metadata(
151
+ self,
152
+ num_draft_tokens: np.ndarray,
153
+ cu_num_scheduled_tokens: np.ndarray,
154
+ padded_num_reqs: int,
155
+ ) -> SpecDecodeMetadata:
156
+ # Inputs:
157
+ # cu_num_scheduled_tokens: [ 4, 104, 107, 207, 209]
158
+ # num_draft_tokens: [ 3, 0, 2, 0, 1]
159
+ # Outputs:
160
+ # cu_num_draft_tokens: [ 3, 3, 5, 5, 6]
161
+ # logits_indices: [ 0, 1, 2, 3, 103, 104, 105, 106,
162
+ # 206, 207, 208]
163
+ # target_logits_indices: [ 0, 1, 2, 5, 6, 9]
164
+ # bonus_logits_indices: [ 3, 4, 7, 8, 10]
165
+
166
+ # Compute the logits indices.
167
+ # [4, 1, 3, 1, 2]
168
+ num_sampled_tokens = num_draft_tokens + 1
169
+
170
+ # Step 1. cu_num_sampled_tokens: [4, 5, 8, 9, 11]
171
+ # arange: [0, 1, 2, 3, 0, 0, 1, 2, 0, 0, 1]
172
+ cu_num_sampled_tokens = np.cumsum(num_sampled_tokens)
173
+ arange = np.concatenate(
174
+ [self.runner.arange_cpu[:n] for n in num_sampled_tokens])
175
+ # Step 2. [0, 0, 0, 0, 103, 104, 104, 104, 206, 207, 207]
176
+ logits_indices = np.repeat(
177
+ cu_num_scheduled_tokens - num_sampled_tokens, num_sampled_tokens)
178
+ # Step 3. [0, 1, 2, 3, 103, 104, 105, 106, 206, 207, 208]
179
+ logits_indices += arange
180
+ # Compute the bonus logits indices.
181
+ bonus_logits_indices = cu_num_sampled_tokens - 1
182
+
183
+ # Compute the draft logits indices.
184
+ # arange: [0, 1, 2, 0, 1, 0]
185
+ arange = np.concatenate(
186
+ [self.runner.arange_cpu[:n] for n in num_draft_tokens])
187
+ # [0, 0, 0, 5, 5, 9]
188
+ target_logits_indices = np.repeat(
189
+ cu_num_sampled_tokens - num_sampled_tokens, num_draft_tokens)
190
+ # [0, 1, 2, 5, 6, 9]
191
+ target_logits_indices += arange
192
+
193
+ # Compute the draft token ids.
194
+ # draft_token_indices: [ 1, 2, 3, 105, 106, 208]
195
+ draft_token_ids = self.runner.input_ids_cpu[logits_indices]
196
+ draft_token_ids = draft_token_ids[target_logits_indices + 1]
197
+ padded_logits_length = runner_utils.get_padded_token_len(
198
+ self.runner.num_logits_paddings, logits_indices.shape[0])
199
+ padded_logits_indices = np.concatenate([
200
+ logits_indices,
201
+ np.zeros(padded_logits_length - logits_indices.shape[0],
202
+ dtype=np.int32)
203
+ ])
204
+
205
+ assert bonus_logits_indices.shape[0] <= padded_num_reqs, (
206
+ f"bonus_logits_indices.shape[0]={bonus_logits_indices.shape[0]} "
207
+ f"padded_num_reqs={padded_num_reqs}")
208
+
209
+ padded_bonus_logits_indices = np.concatenate([
210
+ bonus_logits_indices,
211
+ np.zeros(padded_num_reqs - bonus_logits_indices.shape[0],
212
+ dtype=np.int32)
213
+ ])
214
+ padded_num_draft_tokens = np.concatenate([
215
+ num_draft_tokens,
216
+ np.zeros(padded_num_reqs - num_draft_tokens.shape[0],
217
+ dtype=np.int32)
218
+ ])
219
+ padded_draft_token_ids = np.concatenate([
220
+ draft_token_ids,
221
+ np.zeros(padded_logits_length - draft_token_ids.shape[0],
222
+ dtype=np.int32)
223
+ ])
224
+ padded_target_logits_indices = np.concatenate([
225
+ target_logits_indices,
226
+ np.zeros(padded_logits_length - target_logits_indices.shape[0],
227
+ dtype=np.int32)
228
+ ])
229
+
230
+ padded_num_draft_tokens_cpu = padded_num_draft_tokens
231
+ # CPU -> TPU copy.
232
+ (padded_num_draft_tokens, padded_draft_token_ids,
233
+ padded_logits_indices, padded_target_logits_indices,
234
+ padded_bonus_logits_indices) = device_array(
235
+ self.runner.mesh,
236
+ (padded_num_draft_tokens, padded_draft_token_ids,
237
+ padded_logits_indices, padded_target_logits_indices,
238
+ padded_bonus_logits_indices))
239
+
240
+ metadata = SpecDecodeMetadata(
241
+ draft_token_ids=padded_draft_token_ids,
242
+ draft_lengths=padded_num_draft_tokens,
243
+ draft_lengths_cpu=padded_num_draft_tokens_cpu,
244
+ target_logits_indices=padded_target_logits_indices,
245
+ bonus_logits_indices=padded_bonus_logits_indices,
246
+ final_logits_indices=padded_logits_indices,
247
+ )
248
+ return metadata
@@ -0,0 +1,87 @@
1
+ import functools
2
+ from typing import TYPE_CHECKING, Tuple
3
+
4
+ import jax
5
+ import jax.numpy as jnp
6
+
7
+ from tpu_inference.utils import device_array
8
+
9
+ if TYPE_CHECKING:
10
+ from vllm.v1.core.sched.output import GrammarOutput
11
+
12
+ from tpu_inference.runner.tpu_runner import TPUModelRunner
13
+
14
+
15
+ class StructuredDecodingManager:
16
+
17
+ def __init__(self, runner: "TPUModelRunner"):
18
+ self.runner = runner
19
+
20
+ @functools.partial(jax.jit, static_argnums=(0, ))
21
+ def structured_decode_fn(self, require_struct_decoding: jax.Array,
22
+ grammar_bitmask: jax.Array, logits: jax.Array,
23
+ arange: jax.Array) -> jax.Array:
24
+ return jax.lax.cond(
25
+ jnp.any(require_struct_decoding),
26
+ lambda: self._apply_grammar_bitmask_kernel(
27
+ logits, grammar_bitmask, require_struct_decoding, arange),
28
+ lambda: logits)
29
+
30
+ @functools.partial(jax.jit, static_argnums=(0, ))
31
+ def _apply_grammar_bitmask_kernel(self, logits: jax.Array,
32
+ grammar_bitmask: jax.Array,
33
+ require_struct_decoding: jax.Array,
34
+ arange: jax.Array) -> jax.Array:
35
+
36
+ # Unpack the bitmask for the entire batch at once.
37
+ # grammar_bitmask: (B, N) where B=num_reqs, N=cdiv(vocab_size, 32)
38
+ # arange: (32,)
39
+ # (B, N, 1) and (1, 1, 32) broadcast to (B, N, 32)
40
+ unpacked_bitmask = jnp.right_shift(grammar_bitmask[:, :, None],
41
+ arange[None, None, :]) & 1 == 0
42
+
43
+ # Reshape to (B, vocab_size) and apply to logits.
44
+ # (B, N * 32) -> (B, vocab_size)
45
+ unpacked_bitmask = unpacked_bitmask.reshape(
46
+ logits.shape[0], -1)[:, :self.runner.vocab_size]
47
+
48
+ masked_logits = jnp.where(unpacked_bitmask, -jnp.inf, logits)
49
+
50
+ return jnp.where(require_struct_decoding, masked_logits, logits)
51
+
52
+ def prepare_structured_decoding_input(
53
+ self, logits: jax.Array, grammar_output: "GrammarOutput"
54
+ ) -> Tuple[jax.Array, jax.Array, jax.Array]:
55
+ grammar_bitmask = grammar_output.grammar_bitmask
56
+ assert grammar_bitmask is not None
57
+ num_reqs, _ = logits.shape
58
+
59
+ # Reset pre-allocated tensors
60
+ self.runner.grammar_bitmask_cpu.fill(0)
61
+ self.runner.require_structured_out_cpu.fill(0)
62
+
63
+ sorted_struct_requests = sorted(
64
+ grammar_output.structured_output_request_ids)
65
+
66
+ cumulative_mask_idx = 0
67
+ for req_id in sorted_struct_requests:
68
+ if req_id not in self.runner.input_batch.req_id_to_index:
69
+ continue
70
+ batch_index = self.runner.input_batch.req_id_to_index[req_id]
71
+ self.runner.grammar_bitmask_cpu[batch_index] = grammar_bitmask[
72
+ cumulative_mask_idx]
73
+ # It's not guaranteed that all requests in this batch require
74
+ # structured output, so create a bool tensor to represent
75
+ # the requests that need structured output.
76
+ self.runner.require_structured_out_cpu[batch_index] = True
77
+ cumulative_mask_idx += 1
78
+
79
+ (require_structured_out_cpu,
80
+ grammar_bitmask_cpu, structured_decode_arange) = device_array(
81
+ self.runner.mesh,
82
+ (self.runner.require_structured_out_cpu[:num_reqs],
83
+ self.runner.grammar_bitmask_cpu[:num_reqs],
84
+ self.runner.structured_decode_arange))
85
+
86
+ return (require_structured_out_cpu, grammar_bitmask_cpu,
87
+ structured_decode_arange)