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,478 @@
1
+ import functools
2
+ from typing import Any, Optional
3
+
4
+ import jax
5
+ import torch
6
+ from flax import nnx
7
+ from jax.sharding import Mesh, NamedSharding, PartitionSpec
8
+ from torchax.ops.mappings import j2t_dtype
9
+ from transformers import PretrainedConfig
10
+ from vllm.config import VllmConfig
11
+ from vllm.model_executor.model_loader import get_model_loader
12
+ from vllm.model_executor.model_loader.runai_streamer_loader import \
13
+ RunaiModelStreamerLoader
14
+ from vllm.utils.func_utils import supports_kw
15
+
16
+ from tpu_inference import envs
17
+ from tpu_inference.layers.common.sharding import ShardingAxisName
18
+ from tpu_inference.logger import init_logger
19
+ from tpu_inference.models.jax.utils.quantization.quantization_utils import (
20
+ apply_qwix_on_abstract_model, apply_qwix_quantization,
21
+ load_random_weights_into_qwix_abstract_model)
22
+
23
+ logger = init_logger(__name__)
24
+
25
+ _MODEL_REGISTRY = {}
26
+
27
+
28
+ class UnsupportedArchitectureError(ValueError):
29
+ """Raised when a model architecture is not supported in the registry."""
30
+ pass
31
+
32
+
33
+ def _get_model_architecture(config: PretrainedConfig) -> nnx.Module:
34
+ # NOTE: Use inline imports here, otherwise the normal imports
35
+ # would cause JAX init failure when using multi hosts with Ray.
36
+
37
+ from tpu_inference.models.jax.deepseek_v3 import DeepSeekV3
38
+ from tpu_inference.models.jax.gpt_oss import GptOss
39
+ from tpu_inference.models.jax.llama3 import LlamaForCausalLM
40
+ from tpu_inference.models.jax.llama4 import Llama4ForCausalLM
41
+ from tpu_inference.models.jax.llama_eagle3 import EagleLlama3ForCausalLM
42
+ from tpu_inference.models.jax.llama_guard_4 import LlamaGuard4ForCausalLM
43
+ from tpu_inference.models.jax.qwen2_5_vl import \
44
+ Qwen2_5_VLForConditionalGeneration
45
+ from tpu_inference.models.jax.qwen3 import Qwen3ForCausalLM
46
+ _MODEL_REGISTRY["Llama4ForCausalLM"] = Llama4ForCausalLM
47
+ _MODEL_REGISTRY["DeepseekV3ForCausalLM"] = DeepSeekV3
48
+ _MODEL_REGISTRY["LlamaForCausalLM"] = LlamaForCausalLM
49
+ _MODEL_REGISTRY["Llama4ForConditionalGeneration"] = LlamaGuard4ForCausalLM
50
+ _MODEL_REGISTRY["Qwen3ForCausalLM"] = Qwen3ForCausalLM
51
+ _MODEL_REGISTRY[
52
+ "Qwen2_5_VLForConditionalGeneration"] = Qwen2_5_VLForConditionalGeneration
53
+ _MODEL_REGISTRY["Eagle3LlamaForCausalLM"] = EagleLlama3ForCausalLM
54
+ _MODEL_REGISTRY["GptOssForCausalLM"] = GptOss
55
+
56
+ architectures = getattr(config, "architectures", [])
57
+ for arch in architectures:
58
+ if arch in _MODEL_REGISTRY:
59
+ return _MODEL_REGISTRY[arch]
60
+ raise UnsupportedArchitectureError(
61
+ f"Model architectures {architectures} not "
62
+ "registered in tpu-inference. Falling back to vLLM-native "
63
+ f"Pytorch definition. JAX-native architectures: {list(_MODEL_REGISTRY.keys())}"
64
+ )
65
+
66
+
67
+ def _get_nnx_model(
68
+ model_class: Any,
69
+ vllm_config: VllmConfig,
70
+ rng: jax.Array,
71
+ mesh: Mesh,
72
+ ) -> nnx.Module:
73
+
74
+ def create_abstract_model() -> nnx.Module:
75
+ """
76
+ Helper class to create an abstract model for `nnx.eval_shape`.
77
+
78
+ Returns:
79
+ An abstract model function.
80
+ """
81
+ return model_class(vllm_config, rng, mesh)
82
+
83
+ @nnx.jit(donate_argnums=(0, ),
84
+ static_argnames=('use_qwix_on_abstract_model', ))
85
+ def create_jit_model(
86
+ model: nnx.Module,
87
+ use_qwix_on_abstract_model: bool = False) -> nnx.Module:
88
+ """
89
+ Create a jit model.
90
+
91
+ Args:
92
+ model: The model to jit.
93
+ use_qwix_on_abstract_model: Whether to apply Qwix on the abstract model.
94
+
95
+ Returns:
96
+ The jitted model.
97
+ """
98
+ state = nnx.state(model)
99
+ nnx.update(model, state)
100
+ if not use_qwix_on_abstract_model:
101
+ # NOTE: if Qwix is not configured, this will be a no-op
102
+ model = apply_qwix_quantization(vllm_config,
103
+ model,
104
+ rng,
105
+ mesh,
106
+ apply_to_abstract_model=False)
107
+ return model
108
+
109
+ if vllm_config.load_config.load_format == "dummy":
110
+ # Create a sharded model with random inited weights.
111
+ # TODO: currently Qwen2ForCausalLM is using legacy model implementation
112
+ # will merge the random init logic when all model are migrated to new model implementation
113
+
114
+ # Handle the case where we want to load in random weights to a Qwix-quantized model. Here, we
115
+ # need to run an abstract pass for Qwix first and then load in the random weights.
116
+ if apply_qwix_on_abstract_model(vllm_config):
117
+ abstract_model_fn = apply_qwix_quantization(
118
+ vllm_config,
119
+ create_abstract_model,
120
+ rng,
121
+ mesh,
122
+ apply_to_abstract_model=True)
123
+
124
+ model = nnx.eval_shape(abstract_model_fn)
125
+ quantization_config = vllm_config.model_config.hf_config.quantization_config if hasattr(
126
+ vllm_config.model_config.hf_config,
127
+ "quantization_config") else {}
128
+ load_random_weights_into_qwix_abstract_model(
129
+ rng, model, mesh, quantization_config)
130
+ with mesh:
131
+ jit_model = create_jit_model(model,
132
+ use_qwix_on_abstract_model=True)
133
+ return jit_model
134
+
135
+ @nnx.jit
136
+ def create_sharded_model():
137
+ model = model_class(vllm_config, rng, mesh)
138
+ state = nnx.state(model)
139
+ pspecs = nnx.get_partition_spec(state)
140
+ sharded_state = jax.lax.with_sharding_constraint(state, pspecs)
141
+ nnx.update(model, sharded_state)
142
+ # NOTE: we don't support quantization for the old Qwen2ForCausalLM implementation
143
+ return model
144
+
145
+ with mesh:
146
+ jit_model = create_sharded_model()
147
+ # In this case, we are applying Qwix quantization to the true, concrete model
148
+ jit_model = apply_qwix_quantization(vllm_config,
149
+ jit_model,
150
+ rng,
151
+ mesh,
152
+ apply_to_abstract_model=False)
153
+ if hasattr(jit_model, 'initialize_cache'):
154
+ jit_model.initialize_cache()
155
+ else:
156
+ # We first create an abstract model without allocating any weights,
157
+ # then fill in its weigths during load_weights from HF.
158
+ # This shows 2 advantages than the normal way:
159
+ # 1. The model weights will only be allocated once. Otherwise the normal way
160
+ # will random-init the model weights first, then load the real weights.
161
+ # The two pass weights allocation causes model loading slow.
162
+ # 2. The model loading won't be OOM. Otherwise the normal way will hold
163
+ # a full model weights after random-init, then duplicate a layer during
164
+ # the load_weights. This would be easy to OOM if the layer is super large.
165
+ abstract_model_fn = create_abstract_model
166
+ # NOTE: only one of the abstract (this) or or concrete Qwix quantization paths should
167
+ # be taken
168
+ if should_apply_qwix_on_abstract_model := apply_qwix_on_abstract_model(
169
+ vllm_config):
170
+ # NOTE: if Qwix is not configured, this will return `create_abstract_model` and
171
+ # thus be a no-op
172
+ abstract_model_fn = apply_qwix_quantization(
173
+ vllm_config,
174
+ create_abstract_model,
175
+ rng,
176
+ mesh,
177
+ apply_to_abstract_model=True)
178
+ model = nnx.eval_shape(abstract_model_fn)
179
+ # Although the created model can already work, we still need to jit
180
+ # the model creation again, otherwise the model forward will have
181
+ # non-trivial overhead in PjitFunction.
182
+ with mesh:
183
+ loader = get_model_loader(vllm_config.load_config)
184
+ if isinstance(loader, RunaiModelStreamerLoader):
185
+ model_weights = vllm_config.model_config.model
186
+ if hasattr(vllm_config.model_config, "model_weights"):
187
+ model_weights = vllm_config.model_config.model_weights
188
+ weights_iterator = loader._get_weights_iterator(
189
+ model_weights, vllm_config.model_config.revision)
190
+ # We set the weights iterator at runtime, to prevent having to change
191
+ # every model's load_weights signature. This also prevents us from hitting
192
+ # a TypeError at runtime if you use the RunaiModelStreamerLoader with any
193
+ # flax_nnx model whose load_weights function does not accept the
194
+ # weights_iterator keyword argument.
195
+ vllm_config.model_config.model_weights_iterator = weights_iterator
196
+ model.load_weights(rng)
197
+ del vllm_config.model_config.model_weights_iterator
198
+ else:
199
+ model.load_weights(rng)
200
+ jit_model = create_jit_model(
201
+ model,
202
+ use_qwix_on_abstract_model=should_apply_qwix_on_abstract_model)
203
+ return jit_model
204
+
205
+
206
+ # TODO(pooyam): We need to refactor this. This is returning a bunch of functions that do not work with all models and this is not very easy to see from the code.
207
+ def get_flax_model(
208
+ vllm_config: VllmConfig,
209
+ rng: jax.Array,
210
+ mesh: Mesh,
211
+ is_draft_model: bool = False,
212
+ ) -> nnx.Module:
213
+ if is_draft_model:
214
+ model_class = _get_model_architecture(
215
+ vllm_config.speculative_config.draft_model_config.hf_config)
216
+ else:
217
+ model_class = _get_model_architecture(
218
+ vllm_config.model_config.hf_config)
219
+ jit_model = _get_nnx_model(model_class, vllm_config, rng, mesh)
220
+ kv_cache_sharding = NamedSharding(
221
+ mesh, PartitionSpec(ShardingAxisName.ATTN_DATA, None, "model"))
222
+ hidden_states_sharding = NamedSharding(mesh,
223
+ PartitionSpec(
224
+ ShardingAxisName.ATTN_DATA,
225
+ None)) # (T, D)
226
+
227
+ # For performance consideration, refer to:
228
+ # https://flax.readthedocs.io/en/latest/guides/performance.html
229
+ graphdef, state = nnx.split(jit_model)
230
+
231
+ @functools.partial(
232
+ jax.jit,
233
+ out_shardings=(
234
+ kv_cache_sharding,
235
+ hidden_states_sharding,
236
+ hidden_states_sharding, # aux hidden states
237
+ ),
238
+ donate_argnums=2, # 0 is graphdef, 1 is state, 2 is kv_cache
239
+ static_argnums=(
240
+ 7, 10, 11
241
+ ), #7 is layer_name_to_kvcache_index, 10 is is_first_rank, 11 is is_last_rank
242
+ )
243
+ def run_model(graphdef, state, *args):
244
+ model = nnx.merge(graphdef, state)
245
+ return model(*args)
246
+
247
+ logits_sharding = NamedSharding(
248
+ mesh, PartitionSpec(ShardingAxisName.ATTN_DATA, "model"))
249
+
250
+ @functools.partial(
251
+ jax.jit,
252
+ out_shardings=(logits_sharding),
253
+ )
254
+ def run_compute_logits(graphdef, state, *args):
255
+ model = nnx.merge(graphdef, state)
256
+ hidden_state, *_ = args
257
+ return model.compute_logits(hidden_state)
258
+
259
+ # Multi-modal support only
260
+ # This function calculates the image token's embeddings by VIT
261
+ def run_get_multimodal_embeddings(graphdef, state, image_grid_thw,
262
+ **kwargs):
263
+ model = nnx.merge(graphdef, state)
264
+ return model.get_multimodal_embeddings(image_grid_thw, **kwargs)
265
+
266
+ embed_sharding = NamedSharding(mesh, PartitionSpec(None))
267
+ # This function will calculates the embeddings of input texts and then merge with the image embeddings
268
+ @functools.partial(
269
+ jax.jit,
270
+ out_shardings=(embed_sharding),
271
+ )
272
+ def run_get_input_embeddings(graphdef, state, *args, **kwargs):
273
+ model = nnx.merge(graphdef, state)
274
+ return model.get_input_embeddings(*args, **kwargs)
275
+
276
+ # For models that want to work with EAGLE-3 speculative decoding
277
+ @functools.partial(
278
+ jax.jit,
279
+ out_shardings=(logits_sharding),
280
+ )
281
+ def combine_hidden_states(graphdef, state, hidden_states):
282
+ model = nnx.merge(graphdef, state)
283
+ return model.combine_hidden_states(hidden_states)
284
+
285
+ model = nnx.merge(graphdef, state)
286
+ precompile_vision_encoder_fn = getattr(model, "precompile_vision_encoder",
287
+ None)
288
+ model_fn = functools.partial(run_model, graphdef)
289
+ compute_logits_fn = functools.partial(run_compute_logits, graphdef)
290
+ get_multimodal_embeddings_fn = functools.partial(
291
+ run_get_multimodal_embeddings, graphdef)
292
+ get_input_embeddings_fn = functools.partial(run_get_input_embeddings,
293
+ graphdef)
294
+ lora_manager, model = None, None
295
+ combine_hidden_states_fn = functools.partial(combine_hidden_states,
296
+ graphdef)
297
+
298
+ get_mrope_input_positions_fn = None if not hasattr(
299
+ jit_model,
300
+ "get_mrope_input_positions") else jit_model.get_mrope_input_positions
301
+
302
+ multimodal_fns = {
303
+ "precompile_vision_encoder_fn": precompile_vision_encoder_fn,
304
+ "get_multimodal_embeddings_fn": get_multimodal_embeddings_fn,
305
+ "get_input_embeddings_fn": get_input_embeddings_fn,
306
+ "get_mrope_input_positions_fn": get_mrope_input_positions_fn,
307
+ }
308
+
309
+ return model_fn, compute_logits_fn, combine_hidden_states_fn, multimodal_fns, state, lora_manager, model
310
+
311
+
312
+ def get_vllm_model(
313
+ vllm_config: VllmConfig,
314
+ rng: jax.Array,
315
+ mesh: Mesh,
316
+ ):
317
+ from tpu_inference.models.vllm.vllm_model_wrapper import VllmModelWrapper
318
+
319
+ model = VllmModelWrapper(
320
+ vllm_config=vllm_config,
321
+ rng=rng,
322
+ mesh=mesh,
323
+ )
324
+ params, lora_manager = model.load_weights()
325
+
326
+ jit_model = model.jit_step_func()
327
+ compute_logits_fn = model.jit_compute_logits_func()
328
+ # the model needs to be returned because lora weights are neither torch.nn.parameter nor torch.nn.buffer. After we load the lora weights and set it to the torch.nn.Module, we can shard it and move it to TPU.
329
+ combine_hidden_states_fn = None
330
+ return jit_model, compute_logits_fn, combine_hidden_states_fn, None, params, lora_manager, model
331
+
332
+
333
+ def get_model(
334
+ vllm_config: VllmConfig,
335
+ rng: jax.Array,
336
+ mesh: Mesh,
337
+ is_draft_model: bool = False,
338
+ ) -> Any:
339
+ impl = envs.MODEL_IMPL_TYPE
340
+ logger.info(f"Loading model with MODEL_IMPL_TYPE={impl}")
341
+
342
+ if impl == "flax_nnx":
343
+ try:
344
+ # Try to load the flax model first
345
+ return get_flax_model(vllm_config, rng, mesh, is_draft_model)
346
+ except UnsupportedArchitectureError as e:
347
+ # Convert the error message to a string to check its contents
348
+ error_msg = str(e)
349
+
350
+ logger.warning(error_msg)
351
+
352
+ # Fall back to the vLLM model and updating the dtype accordingly
353
+ vllm_config.model_config.dtype = j2t_dtype(
354
+ vllm_config.model_config.dtype.dtype)
355
+ return get_vllm_model(vllm_config, rng, mesh)
356
+ elif impl == "vllm":
357
+ return get_vllm_model(vllm_config, rng, mesh)
358
+ else:
359
+ raise NotImplementedError("Unsupported MODEL_IMPL_TYPE")
360
+
361
+
362
+ def _validate_model_interface(model: Any) -> None:
363
+ """Validates that the model class has the required methods and signatures.
364
+
365
+ A valid model must have:
366
+ - An __init__ method that accepts a 'vllm_config' keyword argument.
367
+ - A __call__ method that accepts 'kv_caches', 'input_ids', and
368
+ 'attention_metadata' keyword arguments.
369
+
370
+ Args:
371
+ model: The model class to validate.
372
+
373
+ Raises:
374
+ TypeError: If the model does not meet the interface requirements.
375
+ """
376
+ # Check for __init__ with vllm_config
377
+ model_init = getattr(model, "__init__", None)
378
+ if not callable(model_init):
379
+ raise TypeError(
380
+ f"Model {model.__name__} must have an __init__ method.")
381
+
382
+ if not supports_kw(model_init, "vllm_config"):
383
+ raise TypeError(
384
+ f"Model {model.__name__} __init__ method must accept a "
385
+ "'vllm_config' keyword argument.")
386
+
387
+ # Check for __call__ with required arguments
388
+ model_call = getattr(model, "__call__", None)
389
+ # A class object is always callable (it produces an instance).
390
+ # We need to check if the class _explicitly_ defines a __call__ method for its
391
+ # instance, which is different from `type.__call__`.
392
+ has_defined_call = False
393
+ if isinstance(model, type):
394
+ if any("__call__" in C.__dict__ for C in model.__mro__):
395
+ has_defined_call = True
396
+ elif callable(model_call):
397
+ # For an instance, a simple callable check is sufficient.
398
+ has_defined_call = True
399
+
400
+ if not has_defined_call:
401
+ raise TypeError(f"Model {model.__name__} must have a __call__ method.")
402
+
403
+ required_call_args = ("kv_caches", "input_ids", "attention_metadata")
404
+ missing_args = tuple(arg for arg in required_call_args
405
+ if not supports_kw(model_call, arg))
406
+
407
+ if missing_args:
408
+ raise TypeError(
409
+ f"Model {model.__name__} __call__ method is missing required "
410
+ f"keyword arguments: {missing_args}")
411
+
412
+
413
+ def register_model(arch: str, model: Any) -> None:
414
+ """
415
+ Registers a model class for a given architecture name.
416
+
417
+ This function registers the model with both the tpu_inference registry
418
+ and the vLLM registry. For vLLM, it creates a compatible wrapper
419
+ around the JAX model.
420
+
421
+ Args:
422
+ arch: The name of the architecture (e.g., "LlamaForCausalLM").
423
+ model: The JAX model class to register (e.g., a flax.nnx.Module).
424
+ """
425
+ _validate_model_interface(model)
426
+
427
+ # Register with tpu_inference registry for the JAX backend
428
+ _MODEL_REGISTRY[arch] = model
429
+
430
+ # Create a vLLM-compatible wrapper for the JAX model class.
431
+ # This wrapper inherits from the JAX model and torch.nn.Module
432
+ # to pass vLLM's type checks. It is not meant to be instantiated
433
+ # or executed by vLLM's PyTorch backend.
434
+ def unimplemented_forward(
435
+ self,
436
+ input_ids: "torch.Tensor",
437
+ positions: "torch.Tensor",
438
+ intermediate_tensors: Optional[Any] = None,
439
+ inputs_embeds: Optional["torch.Tensor"] = None,
440
+ ) -> None:
441
+ raise NotImplementedError(
442
+ "This is a JAX model and does not implement the PyTorch forward method."
443
+ )
444
+
445
+ # Same as `forward`, this is a dummy method to satisfy vLLM's type checks.
446
+ def unimplemented_get_input_embeddings(
447
+ self,
448
+ input_ids: "torch.Tensor",
449
+ positions: "torch.Tensor",
450
+ inputs_embeds: Optional["torch.Tensor"] = None,
451
+ ) -> "torch.Tensor":
452
+ raise NotImplementedError(
453
+ "This is a JAX model and does not implement the PyTorch get_input_embeddings method."
454
+ )
455
+
456
+ # We need a custom __init__ that only calls torch.nn.Module's init,
457
+ # to avoid triggering JAX logic when vLLM inspects the class.
458
+ def wrapper_init(self, *args, **kwargs):
459
+ torch.nn.Module.__init__(self)
460
+
461
+ # Dynamically create the wrapper class that is a subclass of both the
462
+ # JAX model and torch.nn.Module.
463
+ VllmCompatibleModel = type(
464
+ f"VllmCompatible{model.__name__}",
465
+ (model, torch.nn.Module),
466
+ {
467
+ "__init__": wrapper_init,
468
+ "forward": unimplemented_forward,
469
+ "get_input_embeddings": unimplemented_get_input_embeddings,
470
+ # Prevent vLLM from trying to load weights into this dummy class.
471
+ "load_weights": lambda self, *args, **kwargs: None,
472
+ })
473
+
474
+ # Register the wrapped model with vLLM's registry.
475
+ from vllm.model_executor.models.registry import ModelRegistry
476
+ ModelRegistry.register_model(arch, VllmCompatibleModel)
477
+ logger.info(
478
+ f"Registered JAX model {arch} with tpu_inference and vLLM registries.")
File without changes