tpu-inference 0.11.1.dev202511150811__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 (179) 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 +105 -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 +654 -0
  20. tests/lora/test_lora.py +133 -0
  21. tests/lora/utils.py +96 -0
  22. tests/test_base.py +201 -0
  23. tests/test_envs.py +182 -0
  24. tests/test_quantization.py +836 -0
  25. tests/test_tpu_info.py +120 -0
  26. tests/test_utils.py +236 -0
  27. tpu_inference/__init__.py +34 -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 +51 -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 +728 -0
  37. tpu_inference/distributed/utils.py +59 -0
  38. tpu_inference/env_override.py +9 -0
  39. tpu_inference/envs.py +107 -0
  40. tpu_inference/executors/__init__.py +0 -0
  41. tpu_inference/executors/ray_distributed_executor.py +362 -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 +1035 -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 +1478 -0
  68. tpu_inference/kernels/ragged_paged_attention/v3/kernel_hd64.py +1482 -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 +390 -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 +507 -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 +105 -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 +266 -0
  114. tpu_inference/layers/vllm/quantization/unquantized.py +386 -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 +311 -0
  120. tpu_inference/mock/__init__.py +0 -0
  121. tpu_inference/mock/vllm_config_utils.py +28 -0
  122. tpu_inference/mock/vllm_envs.py +1219 -0
  123. tpu_inference/mock/vllm_logger.py +212 -0
  124. tpu_inference/mock/vllm_logging_utils.py +15 -0
  125. tpu_inference/models/__init__.py +0 -0
  126. tpu_inference/models/common/__init__.py +0 -0
  127. tpu_inference/models/common/model_loader.py +444 -0
  128. tpu_inference/models/jax/__init__.py +0 -0
  129. tpu_inference/models/jax/deepseek_v3.py +868 -0
  130. tpu_inference/models/jax/gpt_oss.py +492 -0
  131. tpu_inference/models/jax/jax_intermediate_tensor.py +79 -0
  132. tpu_inference/models/jax/llama3.py +375 -0
  133. tpu_inference/models/jax/llama4.py +629 -0
  134. tpu_inference/models/jax/llama_eagle3.py +333 -0
  135. tpu_inference/models/jax/phi3.py +376 -0
  136. tpu_inference/models/jax/qwen2.py +375 -0
  137. tpu_inference/models/jax/qwen2_5_vl.py +1103 -0
  138. tpu_inference/models/jax/qwen3.py +302 -0
  139. tpu_inference/models/jax/utils/__init__.py +0 -0
  140. tpu_inference/models/jax/utils/file_utils.py +96 -0
  141. tpu_inference/models/jax/utils/multi_modal_utils.py +163 -0
  142. tpu_inference/models/jax/utils/quantization/__init__.py +0 -0
  143. tpu_inference/models/jax/utils/quantization/configs/fp8_all_modules_w_only.yaml +5 -0
  144. tpu_inference/models/jax/utils/quantization/configs/fp8_default.yaml +6 -0
  145. tpu_inference/models/jax/utils/quantization/configs/int8_all_modules_w_only.yaml +5 -0
  146. tpu_inference/models/jax/utils/quantization/configs/int8_default.yaml +6 -0
  147. tpu_inference/models/jax/utils/quantization/mxfp4_utils.py +105 -0
  148. tpu_inference/models/jax/utils/quantization/quantization_utils.py +653 -0
  149. tpu_inference/models/jax/utils/weight_utils.py +529 -0
  150. tpu_inference/models/vllm/__init__.py +0 -0
  151. tpu_inference/models/vllm/vllm_model_wrapper.py +286 -0
  152. tpu_inference/models/vllm/vllm_model_wrapper_context.py +45 -0
  153. tpu_inference/platforms/__init__.py +2 -0
  154. tpu_inference/platforms/tpu_platform.py +269 -0
  155. tpu_inference/runner/__init__.py +0 -0
  156. tpu_inference/runner/block_table.py +122 -0
  157. tpu_inference/runner/compilation_manager.py +780 -0
  158. tpu_inference/runner/input_batch.py +435 -0
  159. tpu_inference/runner/kv_cache.py +132 -0
  160. tpu_inference/runner/kv_cache_manager.py +479 -0
  161. tpu_inference/runner/lora_utils.py +92 -0
  162. tpu_inference/runner/multimodal_manager.py +217 -0
  163. tpu_inference/runner/persistent_batch_manager.py +244 -0
  164. tpu_inference/runner/speculative_decoding_manager.py +248 -0
  165. tpu_inference/runner/structured_decoding_manager.py +88 -0
  166. tpu_inference/runner/tpu_runner.py +1620 -0
  167. tpu_inference/runner/utils.py +426 -0
  168. tpu_inference/spec_decode/__init__.py +0 -0
  169. tpu_inference/spec_decode/jax/__init__.py +0 -0
  170. tpu_inference/spec_decode/jax/eagle3.py +367 -0
  171. tpu_inference/tpu_info.py +77 -0
  172. tpu_inference/utils.py +317 -0
  173. tpu_inference/worker/__init__.py +0 -0
  174. tpu_inference/worker/tpu_worker.py +321 -0
  175. tpu_inference-0.11.1.dev202511150811.dist-info/METADATA +107 -0
  176. tpu_inference-0.11.1.dev202511150811.dist-info/RECORD +179 -0
  177. tpu_inference-0.11.1.dev202511150811.dist-info/WHEEL +5 -0
  178. tpu_inference-0.11.1.dev202511150811.dist-info/licenses/LICENSE +201 -0
  179. tpu_inference-0.11.1.dev202511150811.dist-info/top_level.txt +2 -0
@@ -0,0 +1,507 @@
1
+ import functools
2
+
3
+ import jax
4
+ from jax import numpy as jnp
5
+ from jax.experimental.pallas.ops.tpu.megablox.gmm import gmm
6
+ from jax.experimental.shard_map import shard_map
7
+ from jax.sharding import Mesh, NamedSharding, PartitionSpec
8
+
9
+ from tpu_inference.layers.vllm.linear_common import \
10
+ slice_sharded_tensor_for_concatenation
11
+
12
+ P = PartitionSpec
13
+
14
+
15
+ def activation_fn(activation: str, x1, x2):
16
+ match activation:
17
+ case "silu":
18
+ return jax.nn.silu(x1) * x2
19
+ case "swigluoai":
20
+ return _swigluoai(x1, x2)
21
+ case _:
22
+ raise NotImplementedError(
23
+ f"FusedMoE does not support {activation} activation")
24
+
25
+
26
+ def _swigluoai(x1, x2, alpha=1.702, limit=7.0):
27
+ x1 = jnp.clip(x1, a_max=limit)
28
+ x2 = jnp.clip(x2, a_min=-limit, a_max=limit)
29
+
30
+ gated_activation = x1 * jax.nn.sigmoid(alpha * x1)
31
+
32
+ return gated_activation * (x2 + 1)
33
+
34
+
35
+ def _round_up_to_multiple_of_128_within_limit(x: int, limit: int) -> int:
36
+ """
37
+ Rounds the given integer `x` up to the nearest multiple of 128, without
38
+ exceeding the specified `limit`.
39
+
40
+ If `x` is less than or equal to 128, returns 128.
41
+ If `x` is less than `limit`, returns the smallest multiple of 128 greater
42
+ than or equal to `x`.
43
+ If `x` is greater than or equal to `limit`, searches for the largest
44
+ multiple of 128 less than or equal to `limit` (down to 512) that divides `x`
45
+ evenly, and returns it.
46
+ If no such candidate is found, returns `limit`.
47
+
48
+ Args:
49
+ x (int): The integer to round up.
50
+ limit (int): The upper bound (must be a multiple of 128).
51
+
52
+ Returns:
53
+ int: The rounded value according to the rules above.
54
+
55
+ Raises:
56
+ AssertionError: If `limit` is less than 128 or not a multiple of 128.
57
+ """
58
+ assert limit >= 128 and limit % 128 == 0
59
+ if x <= 128:
60
+ return 128
61
+ if x < limit:
62
+ return (x + 127) // 128 * 128
63
+ for candidate in range(limit, 511, -128):
64
+ if x % candidate == 0:
65
+ return candidate
66
+ return limit
67
+
68
+
69
+ def _get_tiling_size_for_gmm_kernel(m: int, k: int, n: int,
70
+ g: int) -> tuple[int, int, int]:
71
+ """
72
+ Calculate optimal tiling sizes for a GMM kernel in a Mixture of Experts
73
+ (MoE) setting.
74
+
75
+ Args:
76
+ m (int): The total number of tokens.
77
+ n (int): The output feature dimension.
78
+ k (int): The input feature dimension.
79
+ g (int): The number of experts.
80
+
81
+ Returns:
82
+ tuple[int, int, int]: A tuple (tm, tk, tn)
83
+ """
84
+
85
+ # TODO(Chengji): increase the upper limit tiling size of m when we can set
86
+ # the vmem size to be used for gmm kernel.
87
+ # NOTE: In average each expert has m // g tokens, but as it might be
88
+ # unbalanced, here we doubled the token size when choosing tiling size of m.
89
+ # 2m//g can be either greater or less than 512. If there are 32 tokens and
90
+ # topk=2, m=topk * num_tokens=64, in this case, 2*m//g will be less than
91
+ # 512.
92
+ tm = _round_up_to_multiple_of_128_within_limit(2 * m // g, 512)
93
+ tm = min(tm, m) # there's a requirement that m % tm == 0
94
+ # k/n correspond to n_input_features/n_output_features in the matmul so they
95
+ # are normally greater than 2048, unless the num shards is large.
96
+ tk = _round_up_to_multiple_of_128_within_limit(k, 2048)
97
+ tn = _round_up_to_multiple_of_128_within_limit(n, 2048)
98
+ return tm, tk, tn
99
+
100
+
101
+ def tensor_sharded_gmm_merged_column_parallel(
102
+ lhs: jax.Array,
103
+ rhs: jax.Array,
104
+ rhs_bias: jax.Array | None,
105
+ group_sizes: jax.Array,
106
+ transpose_rhs: bool,
107
+ mesh: Mesh,
108
+ intermediate_size: int,
109
+ ) -> jax.Array:
110
+ # adapted from https://github.com/pytorch/xla/blob/1d409399474197c484894be90b75d9855393dda5/torch_xla/experimental/custom_kernel.py#L1401
111
+ m, k, g = lhs.shape[0], lhs.shape[1], rhs.shape[0]
112
+ n = rhs.shape[1] if transpose_rhs else rhs.shape[2]
113
+ tm, tk, tn = _get_tiling_size_for_gmm_kernel(m, k, n, g)
114
+
115
+ _gmm = functools.partial(
116
+ gmm,
117
+ preferred_element_type=lhs.dtype,
118
+ tiling=(tm, tk, tn),
119
+ transpose_rhs=transpose_rhs,
120
+ group_offset=jnp.array(0),
121
+ )
122
+
123
+ gmm_result = shard_map(
124
+ _gmm,
125
+ mesh=mesh,
126
+ in_specs=(P(), P(None, "model", None), P()),
127
+ out_specs=(P(None, "model")),
128
+ check_rep=False,
129
+ )(lhs, rhs, group_sizes)
130
+
131
+ if rhs_bias is not None:
132
+ rhs_bis = jnp.repeat(rhs_bias, group_sizes, 0, total_repeat_length=m)
133
+ gmm_result = (gmm_result + rhs_bis).astype(gmm_result.dtype)
134
+
135
+ n_shards = mesh.shape["model"]
136
+ output_sizes = [intermediate_size, intermediate_size]
137
+
138
+ return slice_sharded_tensor_for_concatenation(gmm_result, output_sizes,
139
+ n_shards)
140
+
141
+
142
+ def tensor_sharded_gmm_row_parallel(
143
+ lhs: jax.Array,
144
+ rhs: jax.Array,
145
+ rhs_bias: jax.Array | None,
146
+ group_sizes: jax.Array,
147
+ transpose_rhs: bool,
148
+ mesh: Mesh,
149
+ ) -> jax.Array:
150
+ # adapted from https://github.com/pytorch/xla/blob/1d409399474197c484894be90b75d9855393dda5/torch_xla/experimental/custom_kernel.py#L1401
151
+ m, k, g = lhs.shape[0], lhs.shape[1], rhs.shape[0]
152
+ n = rhs.shape[1] if transpose_rhs else rhs.shape[2]
153
+ tm, tk, tn = _get_tiling_size_for_gmm_kernel(m, k, n, g)
154
+
155
+ _gmm = functools.partial(
156
+ gmm,
157
+ preferred_element_type=lhs.dtype,
158
+ tiling=(tm, tk, tn),
159
+ transpose_rhs=transpose_rhs,
160
+ group_offset=jnp.array(0),
161
+ )
162
+
163
+ def _gmm_all_reduce(lhs, rhs, group_sizes):
164
+ r = _gmm(lhs, rhs, group_sizes)
165
+ return jax.lax.psum(r, axis_name="model")
166
+
167
+ gmm_result = shard_map(
168
+ _gmm_all_reduce,
169
+ mesh=mesh,
170
+ in_specs=(P(None, "model"), P(None, None, "model"), P()),
171
+ out_specs=(P()),
172
+ check_rep=False,
173
+ )(lhs, rhs, group_sizes)
174
+
175
+ if rhs_bias is not None:
176
+ rhs_bias = jnp.repeat(rhs_bias, group_sizes, 0, total_repeat_length=m)
177
+ gmm_result = (gmm_result + rhs_bias).astype(gmm_result.dtype)
178
+
179
+ return gmm_result
180
+
181
+
182
+ def expert_sharded_gmm(
183
+ lhs: jax.Array,
184
+ rhs: jax.Array,
185
+ group_sizes: jax.Array,
186
+ transpose_rhs: bool,
187
+ mesh: Mesh,
188
+ num_experts: int,
189
+ ep_size: int,
190
+ ) -> jax.Array:
191
+ # adapted from https://github.com/pytorch/xla/blob/1d409399474197c484894be90b75d9855393dda5/torch_xla/experimental/custom_kernel.py#L1401
192
+ m, k, g = lhs.shape[0], lhs.shape[1], rhs.shape[0]
193
+ n = rhs.shape[1] if transpose_rhs else rhs.shape[2]
194
+ tm, tk, tn = _get_tiling_size_for_gmm_kernel(m, k, n, g)
195
+
196
+ num_experts_per_shard = num_experts // ep_size
197
+ group_offset = jnp.arange(0, num_experts, num_experts_per_shard)
198
+ group_offset = jax.lax.with_sharding_constraint(
199
+ group_offset, NamedSharding(mesh, P("model")))
200
+
201
+ def _gmm(lhs, rhs, group_sizes, group_offset):
202
+ # Group offset for this shard. `group_offset` is sharded, and in this
203
+ # sharded function, it has only 1 element and `group_offset.shape` is
204
+ # (1,) but gmm kernel requires the group_offset to be a ()-shaped array,
205
+ # so we group_offset[0].
206
+ group_offset_of_shard = group_offset[0]
207
+ gmm_res = gmm(
208
+ lhs=lhs,
209
+ rhs=rhs,
210
+ group_sizes=group_sizes,
211
+ preferred_element_type=lhs.dtype,
212
+ tiling=(tm, tk, tn),
213
+ transpose_rhs=transpose_rhs,
214
+ group_offset=group_offset_of_shard,
215
+ )
216
+ return gmm_res
217
+
218
+ # The result from gmm on each shard has the same shape, but only the rows
219
+ # for this shard has non-zero values. Taking below as an working example:
220
+ # A, A, A, A 0, 0, 0, 0 0, 0, 0, 0 0, 0, 0, 0
221
+ # A, A, A, A 0, 0, 0, 0 0, 0, 0, 0 0, 0, 0, 0
222
+ # A, A, A, A 0, 0, 0, 0 0, 0, 0, 0 0, 0, 0, 0
223
+ # 0, 0, 0, 0 B, B, B, B 0, 0, 0, 0 0, 0, 0, 0
224
+ # 0, 0, 0, 0 B, B, B, B 0, 0, 0, 0 0, 0, 0, 0
225
+ # 0, 0, 0, 0 0, 0, 0, 0 C, C, C, C 0, 0, 0, 0
226
+ # 0, 0, 0, 0 0, 0, 0, 0 C, C, C, C 0, 0, 0, 0
227
+ # 0, 0, 0, 0 0, 0, 0, 0 C, C, C, C 0, 0, 0, 0
228
+ # 0, 0, 0, 0 0, 0, 0, 0 C, C, C, C 0, 0, 0, 0
229
+ # 0, 0, 0, 0 0, 0, 0, 0 C, C, C, C 0, 0, 0, 0
230
+ # 0, 0, 0, 0 0, 0, 0, 0 0, 0, 0, 0 D, D, D, D
231
+ # 0, 0, 0, 0 0, 0, 0, 0 0, 0, 0, 0 D, D, D, D
232
+ # 0, 0, 0, 0 0, 0, 0, 0 0, 0, 0, 0 D, D, D, D
233
+ # 0, 0, 0, 0 0, 0, 0, 0 0, 0, 0, 0 D, D, D, D
234
+ # shard-0 shard-1 shard-2 shard-3
235
+ # Each shards has 3 (row A), 2 (row B), 5 (row C) and 4 (row D).
236
+ gmm_res = shard_map(
237
+ _gmm,
238
+ mesh=mesh,
239
+ in_specs=(P(), P("model", None, None), P(), P("model")),
240
+ out_specs=(P("model", None)),
241
+ check_rep=False,
242
+ )(lhs, rhs, group_sizes, group_offset)
243
+
244
+ # For i-th shard, it is responsible groups (AKA experts) from
245
+ # i*num_experts_per_shard to (i+1)*num_experts_per_shard We sum them up to
246
+ # get total rows in that shard, and that is the size for shard to send to
247
+ # its peers. This is also the number of non-zero rows from the gmm results.
248
+ # In the working example, send_sizes would be [3, 2, 5, 4]
249
+ send_sizes = jnp.array([
250
+ group_sizes[i * num_experts_per_shard:(i + 1) *
251
+ num_experts_per_shard].sum() for i in range(ep_size)
252
+ ])
253
+ # In the working example, input_offsets would be [0, 3, 5, 10]
254
+ input_offsets = jnp.concatenate((jnp.array([0]), send_sizes.cumsum()[:-1]))
255
+ output_offsets = input_offsets
256
+ recv_sizes = send_sizes
257
+
258
+ input_offsets = jax.lax.with_sharding_constraint(
259
+ input_offsets, NamedSharding(mesh, P("model")))
260
+ send_sizes = jax.lax.with_sharding_constraint(
261
+ send_sizes, NamedSharding(mesh, P("model")))
262
+ output_offsets = jax.lax.with_sharding_constraint(
263
+ output_offsets, NamedSharding(mesh, P("model")))
264
+
265
+ def _ragged_all_to_all(operand, input_offsets, send_sizes, output_offsets,
266
+ recv_sizes):
267
+ output = jnp.zeros_like(operand)
268
+
269
+ # input_offsets, send_sizes and output_offsets are sharded and there is
270
+ # only 1 elemnt in each shard, we are taking the 0-th element from them
271
+ # just so that jnp.repeat generates the arrays with correct shape.
272
+ input_offsets_of_shard = jnp.repeat(input_offsets[0], ep_size)
273
+ send_sizes_of_shard = jnp.repeat(send_sizes[0], ep_size)
274
+ output_offsets_of_shard = jnp.repeat(output_offsets[0], ep_size)
275
+
276
+ # recv_sizes is replicated across shards, because all the shards receive
277
+ # the same data and write to the output in the same way (same
278
+ # output_offsets and same recv_sizes) and thus generates replicated
279
+ # output.
280
+ recv_sizes_of_shard = recv_sizes
281
+
282
+ # In the working example, for each shard, the values of the offsets and
283
+ # sizes would be:
284
+ # shard-0 shard-1 shard-2 shard-3
285
+ # input_offsets_of_shard [0, 0, 0, 0] [3, 3, 3, 3] [5, 5, 5, 5] [10,10,10,10]
286
+ # send_sizes_of_shard [3, 3, 3, 3] [2, 2, 2, 2] [5, 5, 5, 5] [4, 4, 4, 4 ]
287
+ # output_offsets_of_shard [0, 0, 0, 0] [0, 0, 0, 0] [0, 0, 0, 0] [10,10,10,10]
288
+ # recv_sizes_of_shard [3, 2, 5, 4] [3, 2, 5, 4] [3, 2, 5, 4] [3, 2, 5, 4]
289
+ return jax.lax.ragged_all_to_all(operand,
290
+ output,
291
+ input_offsets_of_shard,
292
+ send_sizes_of_shard,
293
+ output_offsets_of_shard,
294
+ recv_sizes_of_shard,
295
+ axis_name="model")
296
+
297
+ # Use ragged_all_to_all to send the result from gmm for each expert to all
298
+ # the shards. In the working example, the result would be:
299
+ # A, A, A, A A, A, A, A A, A, A, A A, A, A, A
300
+ # A, A, A, A A, A, A, A A, A, A, A A, A, A, A
301
+ # A, A, A, A A, A, A, A A, A, A, A A, A, A, A
302
+ # B, B, B, B B, B, B, B B, B, B, B B, B, B, B
303
+ # B, B, B, B B, B, B, B B, B, B, B B, B, B, B
304
+ # C, C, C, C C, C, C, C C, C, C, C C, C, C, C
305
+ # C, C, C, C C, C, C, C C, C, C, C C, C, C, C
306
+ # C, C, C, C C, C, C, C C, C, C, C C, C, C, C
307
+ # C, C, C, C C, C, C, C C, C, C, C C, C, C, C
308
+ # C, C, C, C C, C, C, C C, C, C, C C, C, C, C
309
+ # D, D, D, D D, D, D, D D, D, D, D D, D, D, D
310
+ # D, D, D, D D, D, D, D D, D, D, D D, D, D, D
311
+ # D, D, D, D D, D, D, D D, D, D, D D, D, D, D
312
+ # D, D, D, D D, D, D, D D, D, D, D D, D, D, D
313
+ # shard-0 shard-1 shard-2 shard-3
314
+ return shard_map(
315
+ _ragged_all_to_all,
316
+ mesh=mesh,
317
+ in_specs=(P("model", None), P("model"), P("model"), P("model"), P()),
318
+ out_specs=(P()),
319
+ check_rep=False,
320
+ )(gmm_res, input_offsets, send_sizes, output_offsets, recv_sizes)
321
+
322
+
323
+ def fused_moe_func(
324
+ hidden_states: jax.Array,
325
+ w1: jax.Array,
326
+ w2: jax.Array,
327
+ w1_bias: jax.Array | None,
328
+ w2_bias: jax.Array | None,
329
+ gating_output: jax.Array,
330
+ topk: int,
331
+ global_num_experts: int,
332
+ renormalize: bool,
333
+ reduce_results: bool,
334
+ mesh: Mesh,
335
+ use_ep: bool,
336
+ activation: str,
337
+ ):
338
+ """
339
+ Args:
340
+ hidden_states: [*, hidden_size]
341
+ w1: [num_experts, intermediate_size * 2, hidden_size]
342
+ w2: [num_experts, hidden_size, intermediate_size]
343
+ gating_output: [*, num_experts]
344
+ """
345
+ # adapted from https://github.com/vllm-project/vllm/blob/29fa5cac1cd731026f59084d93a822921507573c/vllm/model_executor/layers/fused_moe/moe_pallas.py#L26
346
+ if use_ep and (w1_bias is not None or w2_bias is not None):
347
+ raise NotImplementedError(
348
+ "Bias is not supported when using expert parallelism.")
349
+ orig_shape = hidden_states.shape
350
+ hidden_size = hidden_states.shape[-1]
351
+ num_tokens = hidden_states.size // hidden_size
352
+ assert global_num_experts == w1.shape[0]
353
+ ep_size = mesh.shape["model"] # only used if use_ep is True.
354
+ intermediate_size = w2.shape[-1]
355
+ dtype = hidden_states.dtype
356
+ assert (num_tokens * topk) % 16 == 0, (
357
+ "The kernel requires num_tokens * topk to be a multiple of "
358
+ f"16 but got {num_tokens}*{topk}={num_tokens*topk}")
359
+
360
+ hidden_states = hidden_states.reshape(num_tokens, hidden_size)
361
+ gating_output = gating_output.reshape(num_tokens, global_num_experts)
362
+
363
+ topk_weights = jax.nn.softmax(gating_output.astype(jnp.float32), axis=-1)
364
+ topk_weights, topk_indices = jax.lax.top_k(topk_weights, k=topk)
365
+ if renormalize:
366
+ topk_weights = topk_weights / topk_weights.sum(axis=-1, keepdims=True)
367
+ topk_weights = topk_weights.astype(dtype)
368
+
369
+ topk_indices_flat = topk_indices.flatten()
370
+ topk_argsort_indices = jnp.argsort(topk_indices_flat)
371
+ topk_argsort_revert_indices = jnp.argsort(topk_argsort_indices)
372
+ token_indices = jnp.arange(num_tokens, dtype=jnp.int32).repeat(topk)
373
+ token_indices_sorted = token_indices[topk_argsort_indices]
374
+ group_sizes = jnp.bincount(topk_indices_flat, length=global_num_experts)
375
+
376
+ x = hidden_states[token_indices_sorted]
377
+
378
+ if use_ep:
379
+ x = expert_sharded_gmm(
380
+ x,
381
+ w1,
382
+ group_sizes,
383
+ transpose_rhs=True,
384
+ mesh=mesh,
385
+ num_experts=global_num_experts,
386
+ ep_size=ep_size,
387
+ )
388
+ x1, x2 = x[..., :intermediate_size], x[..., intermediate_size:]
389
+ else:
390
+ x1, x2 = tensor_sharded_gmm_merged_column_parallel(
391
+ x,
392
+ w1,
393
+ w1_bias,
394
+ group_sizes,
395
+ transpose_rhs=True,
396
+ mesh=mesh,
397
+ intermediate_size=intermediate_size,
398
+ )
399
+
400
+ x = activation_fn(activation, x1, x2)
401
+
402
+ if use_ep:
403
+ x = expert_sharded_gmm(
404
+ x,
405
+ w2,
406
+ group_sizes,
407
+ transpose_rhs=True,
408
+ mesh=mesh,
409
+ num_experts=global_num_experts,
410
+ ep_size=ep_size,
411
+ )
412
+ else:
413
+ x = jax.lax.with_sharding_constraint(
414
+ x, NamedSharding(mesh, P(None, "model")))
415
+ x = tensor_sharded_gmm_row_parallel(
416
+ x,
417
+ w2,
418
+ w2_bias,
419
+ group_sizes,
420
+ transpose_rhs=True,
421
+ mesh=mesh,
422
+ )
423
+
424
+ x = x[topk_argsort_revert_indices].reshape(-1, topk, hidden_size)
425
+ x = x * jnp.expand_dims(topk_weights, axis=-1)
426
+ x = x.sum(axis=-2)
427
+ x = x.reshape(orig_shape)
428
+
429
+ if reduce_results:
430
+ x = jax.lax.with_sharding_constraint(x, NamedSharding(mesh, P()))
431
+ return x
432
+
433
+
434
+ @functools.partial(
435
+ jax.jit,
436
+ static_argnames=(
437
+ "topk",
438
+ "global_num_experts",
439
+ "renormalize",
440
+ "reduce_results",
441
+ "mesh",
442
+ "use_ep",
443
+ "activation",
444
+ ),
445
+ )
446
+ def fused_moe_func_padded(
447
+ hidden_states: jax.Array,
448
+ w1: jax.Array,
449
+ w2: jax.Array,
450
+ w1_bias: jax.Array | None,
451
+ w2_bias: jax.Array | None,
452
+ gating_output: jax.Array,
453
+ topk: int,
454
+ global_num_experts: int,
455
+ renormalize: bool,
456
+ reduce_results: bool,
457
+ mesh: Mesh,
458
+ use_ep: bool,
459
+ activation: str,
460
+ ):
461
+ # TODO(fanhongmin@google.com): Once the jax runner pads the input, we no longer need this.
462
+ hidden_size = hidden_states.shape[-1]
463
+ num_tokens = hidden_states.size // hidden_size
464
+ if num_tokens * topk < 16:
465
+ assert 16 % (num_tokens *
466
+ topk) == 0, f"Cannot pad to 16: {num_tokens=}, {topk=}"
467
+ n_repeats = 16 // (num_tokens * topk)
468
+
469
+ reps = (n_repeats, ) + (1, ) * (hidden_states.ndim - 1)
470
+ expanded_hidden_states = jnp.tile(hidden_states, reps)
471
+
472
+ reps = (n_repeats, ) + (1, ) * (gating_output.ndim - 1)
473
+ expanded_gating_output = jnp.tile(gating_output, reps)
474
+
475
+ expanded_x = fused_moe_func(
476
+ expanded_hidden_states,
477
+ w1,
478
+ w2,
479
+ w1_bias,
480
+ w2_bias,
481
+ expanded_gating_output,
482
+ topk,
483
+ global_num_experts,
484
+ renormalize,
485
+ reduce_results,
486
+ mesh,
487
+ use_ep,
488
+ activation,
489
+ )
490
+ x = expanded_x[:hidden_states.shape[0]]
491
+ return x
492
+ else:
493
+ return fused_moe_func(
494
+ hidden_states,
495
+ w1,
496
+ w2,
497
+ w1_bias,
498
+ w2_bias,
499
+ gating_output,
500
+ topk,
501
+ global_num_experts,
502
+ renormalize,
503
+ reduce_results,
504
+ mesh,
505
+ use_ep,
506
+ activation,
507
+ )
@@ -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)