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,469 @@
1
+ import functools
2
+
3
+ import jax
4
+ from jax import numpy as jnp
5
+ from jax import shard_map
6
+ from jax.experimental.pallas.ops.tpu.megablox.gmm import gmm
7
+ from jax.sharding import Mesh
8
+ from jax.sharding import PartitionSpec as P
9
+
10
+ from tpu_inference.layers.vllm.linear_common import \
11
+ slice_sharded_tensor_for_concatenation
12
+
13
+
14
+ def activation_fn(activation: str, x1: jax.Array, x2: jax.Array) -> jax.Array:
15
+ match activation:
16
+ case "silu":
17
+ return jax.nn.silu(x1) * x2
18
+ case "swigluoai":
19
+ return _swigluoai(x1, x2)
20
+ case _:
21
+ raise NotImplementedError(
22
+ f"FusedMoE does not support {activation} activation")
23
+
24
+
25
+ def _swigluoai(x1: jax.Array,
26
+ x2: jax.Array,
27
+ alpha=1.702,
28
+ limit=7.0) -> jax.Array:
29
+ x1 = jnp.clip(x1, a_max=limit)
30
+ x2 = jnp.clip(x2, a_min=-limit, a_max=limit)
31
+
32
+ gated_activation = x1 * jax.nn.sigmoid(alpha * x1)
33
+
34
+ return gated_activation * (x2 + 1)
35
+
36
+
37
+ def _round_up_to_multiple_of_128_within_limit(x: int, limit: int) -> int:
38
+ """
39
+ Rounds the given integer `x` up to the nearest multiple of 128, without
40
+ exceeding the specified `limit`.
41
+
42
+ If `x` is less than or equal to 128, returns 128.
43
+ If `x` is less than `limit`, returns the smallest multiple of 128 greater
44
+ than or equal to `x`.
45
+ If `x` is greater than or equal to `limit`, searches for the largest
46
+ multiple of 128 less than or equal to `limit` (down to 512) that divides `x`
47
+ evenly, and returns it.
48
+ If no such candidate is found, returns `limit`.
49
+
50
+ Args:
51
+ x (int): The integer to round up.
52
+ limit (int): The upper bound (must be a multiple of 128).
53
+
54
+ Returns:
55
+ int: The rounded value according to the rules above.
56
+
57
+ Raises:
58
+ AssertionError: If `limit` is less than 128 or not a multiple of 128.
59
+ """
60
+ assert limit >= 128 and limit % 128 == 0
61
+ if x <= 128:
62
+ return 128
63
+ if x < limit:
64
+ return (x + 127) // 128 * 128
65
+ for candidate in range(limit, 511, -128):
66
+ if x % candidate == 0:
67
+ return candidate
68
+ return limit
69
+
70
+
71
+ def _get_tiling_size_for_gmm_kernel(m: int, k: int, n: int,
72
+ g: int) -> tuple[int, int, int]:
73
+ """
74
+ Calculate optimal tiling sizes for a GMM kernel in a Mixture of Experts
75
+ (MoE) setting.
76
+
77
+ Args:
78
+ m (int): The total number of tokens.
79
+ n (int): The output feature dimension.
80
+ k (int): The input feature dimension.
81
+ g (int): The number of experts.
82
+
83
+ Returns:
84
+ tuple[int, int, int]: A tuple (tm, tk, tn)
85
+ """
86
+
87
+ # TODO(Chengji): increase the upper limit tiling size of m when we can set
88
+ # the vmem size to be used for gmm kernel.
89
+ # NOTE: In average each expert has m // g tokens, but as it might be
90
+ # unbalanced, here we doubled the token size when choosing tiling size of m.
91
+ # 2m//g can be either greater or less than 512. If there are 32 tokens and
92
+ # topk=2, m=topk * num_tokens=64, in this case, 2*m//g will be less than
93
+ # 512.
94
+ tm = _round_up_to_multiple_of_128_within_limit(2 * m // g, 512)
95
+ tm = min(tm, m) # there's a requirement that m % tm == 0
96
+ # k/n correspond to n_input_features/n_output_features in the matmul so they
97
+ # are normally greater than 2048, unless the num shards is large.
98
+ tk = _round_up_to_multiple_of_128_within_limit(k, 2048)
99
+ tn = _round_up_to_multiple_of_128_within_limit(n, 2048)
100
+ return tm, tk, tn
101
+
102
+
103
+ def tensor_sharded_gmm_merged_column_parallel(
104
+ lhs: jax.Array,
105
+ rhs: jax.Array,
106
+ rhs_bias: jax.Array | None,
107
+ group_sizes: jax.Array,
108
+ mesh: Mesh,
109
+ ) -> tuple[jax.Array, jax.Array]:
110
+
111
+ def _gmm(lhs, rhs, group_sizes):
112
+ m, g, n, k = lhs.shape[0], *rhs.shape
113
+ tm, tk, tn = _get_tiling_size_for_gmm_kernel(m, k, n, g)
114
+ return gmm(
115
+ lhs,
116
+ rhs,
117
+ group_sizes,
118
+ preferred_element_type=lhs.dtype,
119
+ tiling=(tm, tk, tn),
120
+ transpose_rhs=True,
121
+ group_offset=jnp.array(0),
122
+ )
123
+
124
+ gmm_result = shard_map(
125
+ _gmm,
126
+ mesh=mesh,
127
+ in_specs=(P("data", None), P(None, "model", None), P("data")),
128
+ out_specs=(P("data", "model")),
129
+ check_vma=False,
130
+ )(lhs, rhs, group_sizes)
131
+
132
+ if rhs_bias is not None:
133
+
134
+ def _add_bias(gmm_result_local, rhs_bias_local, group_sizes_global):
135
+ rhs_bias = jnp.repeat(
136
+ rhs_bias_local,
137
+ group_sizes_global,
138
+ 0,
139
+ total_repeat_length=gmm_result_local.shape[0])
140
+ return gmm_result_local + rhs_bias
141
+
142
+ gmm_result = shard_map(
143
+ _add_bias,
144
+ mesh=mesh,
145
+ in_specs=(P("data", "model"), P(None, "model"), P("data")),
146
+ out_specs=(P("data", "model")),
147
+ )(gmm_result, rhs_bias, group_sizes)
148
+ gmm_result = gmm_result.astype(lhs.dtype)
149
+
150
+ tp_size = mesh.shape["model"]
151
+ intermediate_size = gmm_result.shape[-1] // 2
152
+ output_sizes = [intermediate_size, intermediate_size]
153
+ return slice_sharded_tensor_for_concatenation(gmm_result, output_sizes,
154
+ tp_size)
155
+
156
+
157
+ def tensor_sharded_gmm_row_parallel(
158
+ lhs: jax.Array,
159
+ rhs: jax.Array,
160
+ rhs_bias: jax.Array | None,
161
+ group_sizes: jax.Array,
162
+ mesh: Mesh,
163
+ ) -> jax.Array:
164
+
165
+ def _gmm_all_reduce(lhs, rhs, group_sizes):
166
+ m, g, n, k = lhs.shape[0], *rhs.shape
167
+ tm, tk, tn = _get_tiling_size_for_gmm_kernel(m, k, n, g)
168
+ out = gmm(
169
+ lhs,
170
+ rhs,
171
+ group_sizes,
172
+ preferred_element_type=lhs.dtype,
173
+ tiling=(tm, tk, tn),
174
+ transpose_rhs=True,
175
+ group_offset=jnp.array(0),
176
+ )
177
+ return jax.lax.psum(out, axis_name="model")
178
+
179
+ gmm_result = shard_map(
180
+ _gmm_all_reduce,
181
+ mesh=mesh,
182
+ in_specs=(P("data", "model"), P(None, None, "model"), P("data")),
183
+ out_specs=(P("data")),
184
+ check_vma=False,
185
+ )(lhs, rhs, group_sizes)
186
+
187
+ if rhs_bias is not None:
188
+
189
+ def _add_bias(gmm_result_local, rhs_bias_local, group_sizes_global):
190
+ rhs_bias = jnp.repeat(
191
+ rhs_bias_local,
192
+ group_sizes_global,
193
+ 0,
194
+ total_repeat_length=gmm_result_local.shape[0])
195
+ return gmm_result_local + rhs_bias
196
+
197
+ gmm_result = shard_map(
198
+ _add_bias,
199
+ mesh=mesh,
200
+ in_specs=(P("data"), P(), P("data")),
201
+ out_specs=(P("data")),
202
+ )(gmm_result, rhs_bias, group_sizes)
203
+
204
+ return gmm_result.astype(lhs.dtype)
205
+
206
+
207
+ def expert_sharded_gmm(
208
+ lhs: jax.Array,
209
+ rhs: jax.Array,
210
+ group_sizes: jax.Array,
211
+ mesh: Mesh,
212
+ ) -> jax.Array:
213
+ ep_size = mesh.shape["model"]
214
+
215
+ num_experts = rhs.shape[0]
216
+ num_experts_per_shard = num_experts // ep_size
217
+ group_offset = jnp.arange(0, num_experts, num_experts_per_shard)
218
+
219
+ def _gmm(lhs, rhs, group_sizes, group_offset):
220
+ m, g, n, k = lhs.shape[0], *rhs.shape
221
+ tm, tk, tn = _get_tiling_size_for_gmm_kernel(m, k, n, g)
222
+
223
+ gmm_res = gmm(
224
+ lhs=lhs,
225
+ rhs=rhs,
226
+ group_sizes=group_sizes,
227
+ preferred_element_type=lhs.dtype,
228
+ tiling=(tm, tk, tn),
229
+ transpose_rhs=True,
230
+ group_offset=group_offset[0],
231
+ )
232
+ return gmm_res
233
+
234
+ # The result from gmm on each shard has the same shape, but only the rows
235
+ # for this shard has non-zero values. Taking below as an working example:
236
+ # A, A, A, A 0, 0, 0, 0 0, 0, 0, 0 0, 0, 0, 0
237
+ # A, A, A, A 0, 0, 0, 0 0, 0, 0, 0 0, 0, 0, 0
238
+ # A, A, A, A 0, 0, 0, 0 0, 0, 0, 0 0, 0, 0, 0
239
+ # 0, 0, 0, 0 B, B, B, B 0, 0, 0, 0 0, 0, 0, 0
240
+ # 0, 0, 0, 0 B, B, B, B 0, 0, 0, 0 0, 0, 0, 0
241
+ # 0, 0, 0, 0 0, 0, 0, 0 C, C, C, C 0, 0, 0, 0
242
+ # 0, 0, 0, 0 0, 0, 0, 0 C, C, C, C 0, 0, 0, 0
243
+ # 0, 0, 0, 0 0, 0, 0, 0 C, C, C, C 0, 0, 0, 0
244
+ # 0, 0, 0, 0 0, 0, 0, 0 C, C, C, C 0, 0, 0, 0
245
+ # 0, 0, 0, 0 0, 0, 0, 0 C, C, C, C 0, 0, 0, 0
246
+ # 0, 0, 0, 0 0, 0, 0, 0 0, 0, 0, 0 D, D, D, D
247
+ # 0, 0, 0, 0 0, 0, 0, 0 0, 0, 0, 0 D, D, D, D
248
+ # 0, 0, 0, 0 0, 0, 0, 0 0, 0, 0, 0 D, D, D, D
249
+ # 0, 0, 0, 0 0, 0, 0, 0 0, 0, 0, 0 D, D, D, D
250
+ # shard-0 shard-1 shard-2 shard-3
251
+ # Each shards has 3 (row A), 2 (row B), 5 (row C) and 4 (row D).
252
+ gmm_res = shard_map(
253
+ _gmm,
254
+ mesh=mesh,
255
+ in_specs=(P(), P("model", None, None), P(), P("model")),
256
+ out_specs=(P("model", None)),
257
+ check_vma=False,
258
+ )(lhs, rhs, group_sizes, group_offset)
259
+
260
+ # For i-th shard, it is responsible groups (AKA experts) from
261
+ # i*num_experts_per_shard to (i+1)*num_experts_per_shard We sum them up to
262
+ # get total rows in that shard, and that is the size for shard to send to
263
+ # its peers. This is also the number of non-zero rows from the gmm results.
264
+ # In the working example, send_sizes would be [3, 2, 5, 4].
265
+
266
+ # group_sizes has shape of [num_tokens_per_shard * num_experts_per_shard].
267
+ # So reshaping to [num_tokens_per_shard, num_experts_per_shard] and applying
268
+ # sum(axis=1) will get desired send_sizes shaped [num_tokens_per_shard].
269
+ send_sizes = group_sizes.reshape(-1, num_experts_per_shard).sum(axis=1)
270
+ # In the working example, input_offsets would be [0, 3, 5, 10]
271
+ input_offsets = jnp.concatenate((jnp.array([0]), send_sizes.cumsum()[:-1]))
272
+ output_offsets = input_offsets
273
+ recv_sizes = send_sizes
274
+
275
+ def _ragged_all_to_all(operand, input_offsets, send_sizes, output_offsets,
276
+ recv_sizes):
277
+ output = jnp.zeros_like(operand)
278
+
279
+ # input_offsets, send_sizes and output_offsets are sharded and there is
280
+ # only 1 elemnt in each shard, we are taking the 0-th element from them
281
+ # just so that jnp.repeat generates the arrays with correct shape.
282
+ input_offsets_of_shard = jnp.repeat(input_offsets[0], ep_size)
283
+ send_sizes_of_shard = jnp.repeat(send_sizes[0], ep_size)
284
+ output_offsets_of_shard = jnp.repeat(output_offsets[0], ep_size)
285
+
286
+ # recv_sizes is replicated across shards, because all the shards receive
287
+ # the same data and write to the output in the same way (same
288
+ # output_offsets and same recv_sizes) and thus generates replicated
289
+ # output.
290
+ recv_sizes_of_shard = recv_sizes
291
+
292
+ # In the working example, for each shard, the values of the offsets and
293
+ # sizes would be:
294
+ # shard-0 shard-1 shard-2 shard-3
295
+ # input_offsets_of_shard [0, 0, 0, 0] [3, 3, 3, 3] [5, 5, 5, 5] [10,10,10,10]
296
+ # send_sizes_of_shard [3, 3, 3, 3] [2, 2, 2, 2] [5, 5, 5, 5] [4, 4, 4, 4 ]
297
+ # output_offsets_of_shard [0, 0, 0, 0] [0, 0, 0, 0] [0, 0, 0, 0] [10,10,10,10]
298
+ # recv_sizes_of_shard [3, 2, 5, 4] [3, 2, 5, 4] [3, 2, 5, 4] [3, 2, 5, 4]
299
+ return jax.lax.ragged_all_to_all(operand,
300
+ output,
301
+ input_offsets_of_shard,
302
+ send_sizes_of_shard,
303
+ output_offsets_of_shard,
304
+ recv_sizes_of_shard,
305
+ axis_name="model")
306
+
307
+ # Use ragged_all_to_all to send the result from gmm for each expert to all
308
+ # the shards. In the working example, the result would be:
309
+ # A, A, A, A A, A, A, A A, A, A, A A, A, A, A
310
+ # A, A, A, A A, A, A, A A, A, A, A A, A, A, A
311
+ # A, A, A, A A, A, A, A A, A, A, A A, A, A, A
312
+ # B, B, B, B B, B, B, B B, B, B, B B, B, B, B
313
+ # B, B, B, B B, B, B, B B, B, B, B B, B, B, B
314
+ # C, C, C, C C, C, C, C C, C, C, C C, C, C, C
315
+ # C, C, C, C C, C, C, C C, C, C, C C, C, C, C
316
+ # C, C, C, C C, C, C, C C, C, C, C C, C, C, C
317
+ # C, C, C, C C, C, C, C C, C, C, C C, C, C, C
318
+ # C, C, C, C C, C, C, C C, C, C, C C, C, C, C
319
+ # D, D, D, D D, D, D, D D, D, D, D D, D, D, D
320
+ # D, D, D, D D, D, D, D D, D, D, D D, D, D, D
321
+ # D, D, D, D D, D, D, D D, D, D, D D, D, D, D
322
+ # D, D, D, D D, D, D, D D, D, D, D D, D, D, D
323
+ # shard-0 shard-1 shard-2 shard-3
324
+ return shard_map(
325
+ _ragged_all_to_all,
326
+ mesh=mesh,
327
+ in_specs=(P("model", None), P("model"), P("model"), P("model"), P()),
328
+ out_specs=(P()),
329
+ check_vma=False,
330
+ )(gmm_res, input_offsets, send_sizes, output_offsets, recv_sizes)
331
+
332
+
333
+ @functools.partial(
334
+ jax.jit,
335
+ static_argnames=(
336
+ "topk",
337
+ "renormalize",
338
+ "mesh",
339
+ "use_ep",
340
+ "activation",
341
+ ),
342
+ )
343
+ def fused_moe_func(
344
+ hidden_states: jax.Array,
345
+ w1: jax.Array,
346
+ w2: jax.Array,
347
+ w1_bias: jax.Array | None,
348
+ w2_bias: jax.Array | None,
349
+ gating_output: jax.Array,
350
+ topk: int,
351
+ renormalize: bool,
352
+ mesh: Mesh,
353
+ use_ep: bool,
354
+ activation: str,
355
+ ) -> jax.Array:
356
+ """
357
+ Route tokens in hidden_states into each experts based on routing
358
+ information in gating_out and performs moe with w1 and w2 weights.
359
+
360
+ Args:
361
+ hidden_states: [num_tokens, hidden_size]
362
+ w1: first moe weights [num_experts, intermediate_size * 2, hidden_size]
363
+ w2: second moe weights [num_experts, hidden_size, intermediate_size]
364
+ w1_bias: optional bias of w1 [num_experts, intermediate_size * 2]
365
+ w2_bias: optional bias of w2 [num_experts, hidden_size]
366
+ gating_output: routing information of tokens [num_tokens, num_experts]
367
+ topk: number of experts to choose per token.
368
+ renormalize: normalize gating_output.
369
+ mesh: mesh to perform moe.
370
+ use_ep: use expert parallelism.
371
+ activation: activation function to perform on the output of w1.
372
+
373
+ Returns:
374
+ Output of moe operation [num_tokens, hidden_size]
375
+ """
376
+ if use_ep and (w1_bias is not None or w2_bias is not None):
377
+ raise NotImplementedError(
378
+ "Bias is not supported when using expert parallelism.")
379
+
380
+ num_tokens = hidden_states.shape[0]
381
+ global_num_experts, hidden_size, intermediate_size = w2.shape
382
+ dtype = hidden_states.dtype
383
+
384
+ assert (num_tokens * topk) % 16 == 0, (
385
+ "The kernel requires num_tokens * topk to be a multiple of "
386
+ f"16 but got {num_tokens}*{topk}={num_tokens*topk}")
387
+ assert hidden_states.shape == (num_tokens, hidden_size)
388
+ assert gating_output.shape == (num_tokens, global_num_experts)
389
+ assert w1.shape == (global_num_experts, intermediate_size * 2, hidden_size)
390
+
391
+ topk_weights = jax.nn.softmax(gating_output.astype(jnp.float32), axis=-1)
392
+ topk_weights, topk_indices = jax.lax.top_k(topk_weights, k=topk)
393
+ if renormalize:
394
+ topk_weights = topk_weights / topk_weights.sum(axis=-1, keepdims=True)
395
+ topk_weights = topk_weights.astype(dtype)
396
+
397
+ def _process_tokens_locally(hidden_states_local, topk_indices_local):
398
+ num_tokens_local = hidden_states_local.shape[0]
399
+ topk_indices_flat = topk_indices_local.flatten()
400
+ topk_argsort_indices = jnp.argsort(topk_indices_flat)
401
+ topk_argsort_revert_indices = jnp.argsort(topk_argsort_indices)
402
+ token_indices = jnp.arange(num_tokens_local,
403
+ dtype=jnp.int32).repeat(topk)
404
+ token_indices_sorted = token_indices[topk_argsort_indices]
405
+ group_sizes_local = jnp.bincount(topk_indices_flat,
406
+ length=global_num_experts)
407
+
408
+ x = hidden_states_local[token_indices_sorted]
409
+ return x, group_sizes_local, topk_argsort_revert_indices
410
+
411
+ x, group_sizes, topk_argsort_revert_indices = shard_map(
412
+ _process_tokens_locally,
413
+ mesh=mesh,
414
+ in_specs=(P("data", None), P("data", None)),
415
+ out_specs=(P("data", None), P("data"), P("data")),
416
+ )(hidden_states, topk_indices)
417
+
418
+ if use_ep:
419
+ x = expert_sharded_gmm(
420
+ x,
421
+ w1,
422
+ group_sizes,
423
+ mesh=mesh,
424
+ )
425
+ x1, x2 = jnp.split(x, 2, -1)
426
+
427
+ x = activation_fn(activation, x1, x2)
428
+
429
+ x = expert_sharded_gmm(
430
+ x,
431
+ w2,
432
+ group_sizes,
433
+ mesh=mesh,
434
+ )
435
+ else:
436
+ x1, x2 = tensor_sharded_gmm_merged_column_parallel(
437
+ x,
438
+ w1,
439
+ w1_bias,
440
+ group_sizes,
441
+ mesh=mesh,
442
+ )
443
+
444
+ x = activation_fn(activation, x1, x2)
445
+
446
+ x = tensor_sharded_gmm_row_parallel(
447
+ x,
448
+ w2,
449
+ w2_bias,
450
+ group_sizes,
451
+ mesh=mesh,
452
+ )
453
+
454
+ def _finalize_output(x_local, topk_argsort_revert_indices_local,
455
+ topk_weights_local):
456
+ x_local = x_local[topk_argsort_revert_indices_local].reshape(
457
+ -1, topk, hidden_size)
458
+ x_local = x_local * jnp.expand_dims(topk_weights_local, axis=-1)
459
+ x_local = x_local.sum(axis=-2)
460
+ return x_local
461
+
462
+ x = shard_map(
463
+ _finalize_output,
464
+ mesh=mesh,
465
+ in_specs=(P("data", None), P("data"), P("data", None)),
466
+ out_specs=(P("data", None)),
467
+ )(x, topk_argsort_revert_indices, topk_weights)
468
+
469
+ return x[:num_tokens, :hidden_size]
@@ -0,0 +1,186 @@
1
+ from typing import Optional, Union
2
+
3
+ import jax
4
+ import jax.numpy as jnp
5
+ import torch
6
+ from jax.experimental.shard_map import shard_map
7
+ from jax.sharding import Mesh, NamedSharding
8
+ from jax.sharding import PartitionSpec as P
9
+ from torchax.interop import torch_view
10
+ from torchax.ops.mappings import t2j
11
+
12
+ from tpu_inference.kernels.quantized_matmul.kernel import \
13
+ quantized_matmul_kernel
14
+
15
+
16
+ def sharded_quantized_matmul(x: jax.Array, w_q: jax.Array, w_s: jax.Array,
17
+ mesh: Mesh, weight_sharding: P):
18
+ out_axis, in_axis = weight_sharding
19
+ x_sharding = P(None, in_axis)
20
+ scale_sharding = P(out_axis, )
21
+ out_sharding = P(None, out_axis)
22
+
23
+ x = jax.lax.with_sharding_constraint(x, NamedSharding(mesh, x_sharding))
24
+
25
+ def wrapper(x, w_q, w_s):
26
+ output = quantized_matmul_kernel(x, w_q, w_s, x_q_dtype=w_q.dtype)
27
+ if in_axis:
28
+ output = jax.lax.psum(output, axis_name=in_axis)
29
+ return output
30
+
31
+ return shard_map(wrapper,
32
+ mesh=mesh,
33
+ in_specs=(x_sharding, weight_sharding, scale_sharding),
34
+ out_specs=(out_sharding),
35
+ check_rep=False)(x, w_q, w_s)
36
+
37
+
38
+ def reorder_concatenated_tensor_for_sharding(concatenated_tensor: jax.Array,
39
+ split_sizes: list[int],
40
+ n_shards: int, dim: int):
41
+ """
42
+ Reorder a replicated concatenated tensor such that when sharded on multiple chips, each shard is a concatenation of the shards of the individual tensors.
43
+ For example, let the concatenated_tensor be:
44
+ AAAAAAAAAAAABBBBBBBBCCCC
45
+ 12 As 8 Bs 4 Cs
46
+ and let the split_sizes = [12, 8, 4] and n_shards = 4.
47
+ The output is:
48
+ AAABBCAAABBCAAABBCAAABBC
49
+ In other words, it reorders the input tensor into 4 segements, with each segment corresponding to a shard and being AAABBC.
50
+ Args:
51
+ concatenated_tensor: the tensor, concatenated on the dimension specified by `dim`.
52
+ split_sizes: each individual tensor's size on the dimension specified by `dim`.
53
+ n_shards: num of shards.
54
+ dim: the dimension on which the concatenated_tensor is concatenated.
55
+ """
56
+ # Split the concatenated tensor into individual tensors.
57
+ split_tensors = []
58
+ start_offset = 0
59
+ old_shape = concatenated_tensor.shape
60
+ # New shape ensures each split_tensor[i] maps to a tensor in ith shards
61
+ new_shape = old_shape[:dim] + (n_shards, -1) + old_shape[dim + 1:]
62
+ for split_size in split_sizes:
63
+ split_tensor = jax.lax.slice_in_dim(concatenated_tensor,
64
+ start_offset,
65
+ start_offset + split_size,
66
+ axis=dim)
67
+ split_tensors.append(split_tensor.reshape(new_shape))
68
+ start_offset += split_size
69
+ # While maintaining 0th dim as a shard dim, we concatenate along 1th dim to
70
+ # to create concatenated tnensor where 0th dim maps to shard dim.
71
+ reordered_tensor = jnp.concatenate(split_tensors, axis=dim + 1)
72
+ return reordered_tensor.reshape(old_shape)
73
+
74
+
75
+ def slice_sharded_tensor_for_concatenation(sharded_tensor: jax.Array,
76
+ split_sizes: list[int],
77
+ n_shards: int):
78
+ """
79
+ Slice the input tensor which is sharded on multiple chips (on the last dim) into individual tensors with the same sharding.
80
+ For example, let the sharded_tensor be:
81
+ AAABBC | AAABBC | AAABBC | AAABBC
82
+ Shard0 Shard1 Shard2 Shard3
83
+ and let the split_sizes = [12, 8, 4] and n_shards = 4.
84
+ The output is a list of 3 tensors:
85
+ AAA | AAA | AAA | AAA
86
+ BB | BB | BB | BB
87
+ C | C | C | C
88
+ Shard0 Shard1 Shard2 Shard3
89
+ In other words, each individual tensor is a slice of the input tensor with the same sharding.
90
+ Args:
91
+ sharded_tensor: the input tensor, sharded on the last dim.
92
+ split_sizes: each individual tensor's size on the last dim.
93
+ n_shards: num of shards.
94
+ """
95
+ new_shape = sharded_tensor.shape[:-1] + (n_shards, -1)
96
+ # New shape ensures each sharded_tensor[:, i] maps to a tensor in ith shards
97
+ sharded_tensor = sharded_tensor.reshape(new_shape)
98
+
99
+ split_tensors = []
100
+ start_offset = 0
101
+ for split_size in split_sizes:
102
+ assert split_size % n_shards == 0
103
+ sz = split_size // n_shards # size of this split tensor per shard
104
+ end_offset = start_offset + sz
105
+ # Because we are slicing over last dim, sharding dim remains intact.
106
+ # Therefore, splitting happens locally.
107
+ split_tensor = sharded_tensor[..., start_offset:end_offset]
108
+ split_tensors.append(split_tensor.reshape(new_shape[:-2] + (-1, )))
109
+ start_offset = end_offset
110
+
111
+ return split_tensors
112
+
113
+
114
+ def torch_to_jax_param(
115
+ tensor: torch.Tensor,
116
+ sharding: NamedSharding,
117
+ output_sizes: Optional[int],
118
+ n_shards: int,
119
+ fused: bool,
120
+ dim: int = 0,
121
+ jax_dtype: Optional[jnp.dtype] = None,
122
+ ) -> Union[torch.nn.Parameter, torch.nn.ParameterList]:
123
+ if output_sizes is None:
124
+ output_sizes = [tensor.shape[0]]
125
+
126
+ tensor = t2j(tensor, use_dlpack=False)
127
+ if jax_dtype:
128
+ tensor = tensor.astype(jax_dtype)
129
+
130
+ if fused:
131
+ tensor = reorder_concatenated_tensor_for_sharding(
132
+ tensor, output_sizes, n_shards, dim)
133
+ tensor = jax.device_put(tensor, sharding)
134
+ param = torch.nn.Parameter(torch_view(tensor), requires_grad=False)
135
+ else:
136
+ tensors = []
137
+ start_offset = 0
138
+ for size in output_sizes:
139
+ end_offset = start_offset + size
140
+
141
+ tensor_split = jax.lax.slice_in_dim(tensor,
142
+ start_offset,
143
+ end_offset,
144
+ axis=dim)
145
+ tensor_split = jax.device_put(tensor_split, sharding)
146
+ tensor_split = torch.nn.Parameter(torch_view(tensor_split),
147
+ requires_grad=False)
148
+ tensors.append(tensor_split)
149
+
150
+ start_offset = end_offset
151
+ param = torch.nn.ParameterList(tensors)
152
+ return param
153
+
154
+
155
+ MODEL_MATMUL_FUSION_TRUTH_TABLE = {
156
+ ("Qwen/Qwen2.5-7B-Instruct", 1024, 1, "QKVParallelLinear"):
157
+ True,
158
+ ("Qwen/Qwen2.5-7B-Instruct", 1024, 1, "MergedColumnParallelLinear"):
159
+ False,
160
+ ("Qwen/Qwen2.5-7B-Instruct", 2048, 1, "QKVParallelLinear"):
161
+ False,
162
+ ("Qwen/Qwen2.5-7B-Instruct", 2048, 1, "MergedColumnParallelLinear"):
163
+ False,
164
+ ("meta-llama/Llama-3.1-8B-Instruct", 1024, 1, "QKVParallelLinear"):
165
+ False,
166
+ ("meta-llama/Llama-3.1-8B-Instruct", 1024, 1, "MergedColumnParallelLinear"):
167
+ False,
168
+ ("meta-llama/Llama-3.1-8B-Instruct", 2048, 1, "QKVParallelLinear"):
169
+ False,
170
+ ("meta-llama/Llama-3.1-8B-Instruct", 2048, 1, "MergedColumnParallelLinear"):
171
+ False,
172
+ ("RedHatAI/Meta-Llama-3.1-8B-Instruct-quantized.w8a8", 1024, 1, "QKVParallelLinear"):
173
+ False,
174
+ ("RedHatAI/Meta-Llama-3.1-8B-Instruct-quantized.w8a8", 1024, 1, "MergedColumnParallelLinear"):
175
+ False,
176
+ ("RedHatAI/Meta-Llama-3.1-8B-Instruct-quantized.w8a8", 2048, 1, "QKVParallelLinear"):
177
+ False,
178
+ ("RedHatAI/Meta-Llama-3.1-8B-Instruct-quantized.w8a8", 2048, 1, "MergedColumnParallelLinear"):
179
+ False,
180
+ }
181
+
182
+
183
+ def get_model_matmul_fusion_assignment(model_name: str, batch_size: int,
184
+ tp_size: int, layer_name: str):
185
+ key = (model_name, batch_size, tp_size, layer_name)
186
+ return MODEL_MATMUL_FUSION_TRUTH_TABLE.get(key, True)
@@ -0,0 +1,39 @@
1
+ import copy
2
+
3
+ from jax.sharding import Mesh
4
+ from vllm.config import VllmConfig
5
+ from vllm.model_executor.layers.quantization.base_config import \
6
+ QuantizationConfig
7
+
8
+ from tpu_inference.layers.common import quant_methods
9
+ from tpu_inference.layers.vllm.quantization.awq import VllmAWQConfig
10
+ from tpu_inference.layers.vllm.quantization.common import JaxCommonConfig
11
+ from tpu_inference.layers.vllm.quantization.compressed_tensors.compressed_tensors import \
12
+ VllmCompressedTensorsConfig # noqa: E501
13
+ from tpu_inference.layers.vllm.quantization.mxfp4 import VllmMxfp4Config
14
+ from tpu_inference.layers.vllm.quantization.unquantized import \
15
+ VllmUnquantizedConfig
16
+
17
+
18
+ def get_tpu_quantization_config(vllm_config: VllmConfig,
19
+ mesh: Mesh) -> QuantizationConfig:
20
+ model_config = copy.deepcopy(vllm_config.model_config)
21
+ # TODO(kyuyeunk): Add support for "tpu_int8".
22
+ method_to_config: dict[str, str] = {
23
+ None: VllmUnquantizedConfig,
24
+ quant_methods.COMPRESSED_TENSORS: VllmCompressedTensorsConfig,
25
+ quant_methods.AWQ: VllmAWQConfig,
26
+ quant_methods.MXFP4: VllmMxfp4Config,
27
+ }
28
+ if model_config.quantization not in method_to_config:
29
+ raise NotImplementedError(
30
+ f"{model_config.quantization} quantization method not supported."
31
+ f" Supported methods are {method_to_config.keys()}")
32
+ quant_config = method_to_config[model_config.quantization]
33
+ assert issubclass(quant_config, JaxCommonConfig)
34
+ quant_config.set_configs(vllm_config, mesh)
35
+
36
+ model_config.quantization = quant_methods.get_tpu_quant_method(
37
+ quant_config.get_name())
38
+ return VllmConfig.get_quantization_config(model_config,
39
+ vllm_config.load_config)