optmoe 0.1.0__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.
Files changed (77) hide show
  1. optmoe/__init__.py +80 -0
  2. optmoe/_native.py +25 -0
  3. optmoe/_vendor/__init__.py +2 -0
  4. optmoe/_vendor/sonic_fp8.py +506 -0
  5. optmoe/activation.py +163 -0
  6. optmoe/api.py +626 -0
  7. optmoe/bf16.py +418 -0
  8. optmoe/block_weight_quantization.py +93 -0
  9. optmoe/chunk.py +381 -0
  10. optmoe/column_quantization.py +139 -0
  11. optmoe/combine.py +716 -0
  12. optmoe/dw.py +310 -0
  13. optmoe/env.py +14 -0
  14. optmoe/fixed_dispatch.py +63 -0
  15. optmoe/fp8.py +170 -0
  16. optmoe/fp8_autograd.py +134 -0
  17. optmoe/grouped.py +217 -0
  18. optmoe/hopper_wgrad.py +89 -0
  19. optmoe/include/backward_schedule.cuh +116 -0
  20. optmoe/include/mxfp8_forms_bindings.cpp +17 -0
  21. optmoe/include/mxfp8_forms_launch.cu +692 -0
  22. optmoe/include/nvfp4_requant_args.h +35 -0
  23. optmoe/include/nvfp4_requant_bindings.cpp +67 -0
  24. optmoe/include/nvfp4_requant_launch.cu +634 -0
  25. optmoe/include/owned_backward_bindings.cpp +8 -0
  26. optmoe/include/owned_backward_launch.cu +22 -0
  27. optmoe/include/sm100_backward_tile.cuh +107 -0
  28. optmoe/include/sm100_owned_backward.cuh +105 -0
  29. optmoe/install_kernels.py +141 -0
  30. optmoe/lora.py +656 -0
  31. optmoe/lora_grads.py +477 -0
  32. optmoe/lora_merge.py +68 -0
  33. optmoe/mx_weight_forms.py +316 -0
  34. optmoe/nvfp4_lora.py +799 -0
  35. optmoe/nvfp4_requant/__init__.py +49 -0
  36. optmoe/nvfp4_requant/cuda_nvfp4_requant.py +483 -0
  37. optmoe/nvfp4_requant/nvfp4_requant.py +455 -0
  38. optmoe/nvfp4_requant/nvfp4_requant_cache.py +204 -0
  39. optmoe/nvfp4_requant/sf_layout.py +158 -0
  40. optmoe/nvfp4_requant/triton_nvfp4.py +22 -0
  41. optmoe/nvfp4_requant/triton_nvfp4_requant.py +562 -0
  42. optmoe/ops.py +276 -0
  43. optmoe/optmoe.py +153 -0
  44. optmoe/owned_backward.py +130 -0
  45. optmoe/packing.py +284 -0
  46. optmoe/paired_weight_quantization.py +77 -0
  47. optmoe/peer.py +868 -0
  48. optmoe/peer_backward.py +237 -0
  49. optmoe/peer_dispatch.py +936 -0
  50. optmoe/peer_packing.py +280 -0
  51. optmoe/peer_runtime.py +651 -0
  52. optmoe/peer_scatter.py +80 -0
  53. optmoe/peer_stream.py +454 -0
  54. optmoe/persistent_backward.py +821 -0
  55. optmoe/pipeline.py +294 -0
  56. optmoe/prepare.py +208 -0
  57. optmoe/quantization.py +49 -0
  58. optmoe/recompute.py +52 -0
  59. optmoe/runtime.py +663 -0
  60. optmoe/scheduled.py +453 -0
  61. optmoe/sm90_prep.py +141 -0
  62. optmoe/sm90_weight_forms.py +274 -0
  63. optmoe/sonic.py +96 -0
  64. optmoe/stored_context.py +199 -0
  65. optmoe/synchronization.py +91 -0
  66. optmoe/token_quantization.py +338 -0
  67. optmoe/weight_cache.py +546 -0
  68. optmoe/weight_quantization.py +94 -0
  69. optmoe/wgrad_quantization.py +114 -0
  70. optmoe/workspace_bound.py +214 -0
  71. optmoe-0.1.0.dist-info/METADATA +317 -0
  72. optmoe-0.1.0.dist-info/RECORD +77 -0
  73. optmoe-0.1.0.dist-info/WHEEL +5 -0
  74. optmoe-0.1.0.dist-info/licenses/LICENSE +202 -0
  75. optmoe-0.1.0.dist-info/licenses/vendor/deepgemm/LICENSE +21 -0
  76. optmoe-0.1.0.dist-info/licenses/vendor/sonic-moe/LICENSE +201 -0
  77. optmoe-0.1.0.dist-info/top_level.txt +1 -0
optmoe/__init__.py ADDED
@@ -0,0 +1,80 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # Copyright (c) 2026 Axolotl AI
3
+
4
+ """Fused expert-parallel MoE training kernels for Hopper and Blackwell."""
5
+
6
+ __all__ = [
7
+ "DEFAULT_RESERVED_SMS",
8
+ "FP8Experts",
9
+ "PersistentMoE",
10
+ "SonicExperts",
11
+ "OptMoE",
12
+ "OptMoEDispatchRuntime",
13
+ "OptMoERuntime",
14
+ "check_nccl_env",
15
+ "dispatch_unsupported_reason",
16
+ "lora_precision",
17
+ "nccl_env",
18
+ "pipelined_moe",
19
+ "resolve_precision",
20
+ "sonic_experts",
21
+ "sonic_fp8_experts",
22
+ "unsupported_reason",
23
+ ]
24
+
25
+ _API = frozenset(
26
+ {
27
+ "DEFAULT_RESERVED_SMS",
28
+ "OptMoEDispatchRuntime",
29
+ "OptMoERuntime",
30
+ "check_nccl_env",
31
+ "dispatch_unsupported_reason",
32
+ "lora_precision",
33
+ "nccl_env",
34
+ "resolve_precision",
35
+ "unsupported_reason",
36
+ }
37
+ )
38
+
39
+
40
+ def __getattr__(name):
41
+ if name == "__version__":
42
+ from importlib.metadata import PackageNotFoundError, version
43
+
44
+ try:
45
+ return version("optmoe")
46
+ except PackageNotFoundError:
47
+ return "0.0.0"
48
+ if name in _API:
49
+ from . import api
50
+
51
+ return getattr(api, name)
52
+ if name == "OptMoE":
53
+ from .optmoe import OptMoE
54
+
55
+ return OptMoE
56
+ if name == "PersistentMoE":
57
+ from .runtime import PersistentMoE
58
+
59
+ return PersistentMoE
60
+ if name == "FP8Experts":
61
+ from .fp8_autograd import FP8Experts
62
+
63
+ return FP8Experts
64
+ if name == "SonicExperts":
65
+ from .sonic import SonicExperts
66
+
67
+ return SonicExperts
68
+ if name == "pipelined_moe":
69
+ from .pipeline import pipelined_moe
70
+
71
+ return pipelined_moe
72
+ if name == "sonic_experts":
73
+ from .sonic import sonic_experts
74
+
75
+ return sonic_experts
76
+ if name == "sonic_fp8_experts":
77
+ from .sonic import sonic_fp8_experts
78
+
79
+ return sonic_fp8_experts
80
+ raise AttributeError(name)
optmoe/_native.py ADDED
@@ -0,0 +1,25 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # Copyright (c) 2026 Axolotl AI
3
+
4
+ """The compiled kernel extension, ``optmoe_deepgemm``: OPTMoE's DeepGEMM fork, installed
5
+ separately from the pure-Python package (``python -m optmoe.install_kernels``)."""
6
+
7
+ import importlib
8
+
9
+ MISSING = (
10
+ "optmoe needs its compiled kernel extension, optmoe_deepgemm, which is not installed. "
11
+ "Install it with `python -m optmoe.install_kernels` (a prebuilt wheel for this Python, "
12
+ "torch and CUDA version, or a source build)."
13
+ )
14
+
15
+
16
+ def __getattr__(name):
17
+ # resolved on every access, so the extension loads lazily and tests can swap it
18
+ if name != "deep_gemm":
19
+ raise AttributeError(name)
20
+ try:
21
+ return importlib.import_module("optmoe_deepgemm")
22
+ except ModuleNotFoundError as error:
23
+ if error.name != "optmoe_deepgemm":
24
+ raise
25
+ raise ModuleNotFoundError(MISSING, name="optmoe_deepgemm") from None
@@ -0,0 +1,2 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # Copyright (c) 2026 Axolotl AI
@@ -0,0 +1,506 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # Copyright (c) 2025, Wentao Guo, Mayank Mishra, Xinle Cheng, Ion Stoica, Tri Dao
3
+ # Copyright (c) 2026 Axolotl AI
4
+ # Modified by Axolotl AI, 2026: isolated imports, cache-free quantization,
5
+ # and default GEMM configuration. See vendor/sources.json.
6
+
7
+ from functools import partial
8
+
9
+ import cutlass
10
+ import torch
11
+ import torch.nn.functional as F
12
+ from quack.cute_dsl_utils import torch2cute_dtype_map
13
+ from quack.gemm_interface import gemm as _gemm, gemm_dgated as _gemm_dgated, gemm_gated
14
+ from sonicmoe.enums import ActivationType, is_glu
15
+ from sonicmoe.functional.backward import (
16
+ _down_projection_backward_act,
17
+ _token_broadcast_backward,
18
+ _up_projection_backward_act,
19
+ )
20
+ from sonicmoe.functional.forward import _router_forward
21
+ from sonicmoe.functional.triton_kernels import general_routing_router_metadata_triton
22
+
23
+ torch2cute_dtype_map[torch.float8_e4m3fn] = cutlass.Float8E4M3FN
24
+ gemm = partial(_gemm, tuned=False)
25
+ gemm_dgated = partial(_gemm_dgated, tuned=False)
26
+ _FP8_E4M3_MAX = 448.0
27
+
28
+
29
+ def _to_fp8_e4m3_weight(x, perm):
30
+ return _to_fp8_e4m3(x.permute(*perm).contiguous())
31
+
32
+
33
+ def _to_fp8_e4m3(x: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
34
+ scale = x.abs().amax().clamp(min=1e-12) / _FP8_E4M3_MAX
35
+ return (x / scale).to(torch.float8_e4m3fn), scale
36
+
37
+
38
+ def _apply_glu_act(
39
+ h: torch.Tensor, activation_type: ActivationType, concat_layout: bool
40
+ ) -> torch.Tensor:
41
+ if concat_layout:
42
+ gate, up = h.chunk(2, dim=-1)
43
+ else:
44
+ gate, up = h[..., ::2], h[..., 1::2]
45
+ if activation_type == ActivationType.SWIGLU:
46
+ return F.silu(gate) * up
47
+ elif activation_type == ActivationType.GEGLU:
48
+ return F.gelu(gate.float()).to(gate.dtype) * up
49
+ else:
50
+ raise ValueError(f"unsupported activation for fp8 path: {activation_type}")
51
+
52
+
53
+ class _UpProjection(torch.autograd.Function):
54
+ @staticmethod
55
+ def forward(
56
+ ctx,
57
+ x: torch.Tensor,
58
+ w1: torch.Tensor,
59
+ b1: torch.Tensor | None,
60
+ expert_frequency_offset: torch.Tensor,
61
+ total_expert_freq: int,
62
+ K: int,
63
+ x_gather_idx: torch.Tensor,
64
+ s_scatter_idx: torch.Tensor,
65
+ s_reverse_scatter_idx: torch.Tensor,
66
+ num_activated_expert_per_token_offset: torch.Tensor,
67
+ is_each_token_has_variable_activated_experts: bool,
68
+ activation_type: ActivationType,
69
+ is_inference_mode_enabled: bool,
70
+ concat_layout: bool = False,
71
+ use_fp8: bool = False,
72
+ ) -> torch.Tensor:
73
+ T, H = x.shape
74
+ I, H, E = w1.shape
75
+ is_glu_activation = is_glu(activation_type)
76
+ if is_glu_activation:
77
+ I //= 2
78
+ TK = total_expert_freq
79
+
80
+ a = torch.empty(TK, I, dtype=x.dtype, device=x.device)
81
+ h = (
82
+ torch.empty(
83
+ TK, (2 * I if is_glu_activation else I), dtype=x.dtype, device=x.device
84
+ )
85
+ if (not is_inference_mode_enabled)
86
+ else None
87
+ )
88
+
89
+ assert activation_type.value in (
90
+ "swiglu",
91
+ "geglu",
92
+ ), (
93
+ f"QuACK gemm_gated only supports glu activations, got {activation_type.value}"
94
+ )
95
+
96
+ if use_fp8:
97
+ x_fp8, x_sc = _to_fp8_e4m3(x)
98
+ w1_fp8, w1_sc = _to_fp8_e4m3_weight(w1, (2, 1, 0))
99
+ gemm_gated(
100
+ x_fp8,
101
+ w1_fp8,
102
+ activation=activation_type.value,
103
+ alpha=x_sc.float() * w1_sc.float(),
104
+ cu_seqlens_m=expert_frequency_offset,
105
+ A_idx=x_gather_idx,
106
+ preact_out=h,
107
+ postact_out=a,
108
+ store_preact=not is_inference_mode_enabled,
109
+ out_dtype=x.dtype,
110
+ postact_dtype=x.dtype,
111
+ concat_layout=("B",) if concat_layout else None,
112
+ tuned=False,
113
+ )
114
+ if not is_inference_mode_enabled:
115
+ ctx.x_fp8 = x_fp8
116
+ ctx.x_sc = x_sc
117
+ else:
118
+ gemm_gated(
119
+ x,
120
+ w1.permute(2, 1, 0),
121
+ activation=activation_type.value,
122
+ cu_seqlens_m=expert_frequency_offset,
123
+ A_idx=x_gather_idx,
124
+ preact_out=h,
125
+ postact_out=a,
126
+ store_preact=(not is_inference_mode_enabled),
127
+ bias=b1,
128
+ concat_layout=(("B", "bias") if b1 is not None else ("B",))
129
+ if concat_layout
130
+ else None,
131
+ )
132
+
133
+ ctx.T = T
134
+ ctx.TK = TK
135
+ ctx.E = E
136
+ ctx.K = K
137
+ ctx.H = H
138
+ ctx.I = I
139
+ ctx.is_each_token_has_variable_activated_experts = (
140
+ is_each_token_has_variable_activated_experts
141
+ )
142
+ ctx.is_glu_activation = is_glu_activation
143
+ ctx.concat_layout = concat_layout
144
+
145
+ ctx.save_for_backward(
146
+ x,
147
+ w1,
148
+ b1,
149
+ expert_frequency_offset,
150
+ x_gather_idx,
151
+ s_scatter_idx,
152
+ s_reverse_scatter_idx,
153
+ num_activated_expert_per_token_offset,
154
+ )
155
+
156
+ ctx.use_fp8 = use_fp8
157
+ ctx.mark_non_differentiable(a)
158
+ ctx.set_materialize_grads(False)
159
+
160
+ return a, h
161
+
162
+ @staticmethod
163
+ def backward(ctx, _: None, dh: torch.Tensor):
164
+ T = ctx.T
165
+ TK = ctx.TK
166
+ E = ctx.E
167
+ K = ctx.K
168
+ H = ctx.H
169
+ is_glu_activation = ctx.is_glu_activation
170
+ is_each_token_has_variable_activated_experts = (
171
+ ctx.is_each_token_has_variable_activated_experts
172
+ )
173
+ concat_layout = ctx.concat_layout
174
+
175
+ (
176
+ x,
177
+ w1,
178
+ b1,
179
+ expert_frequency_offset,
180
+ x_gather_idx,
181
+ s_scatter_idx,
182
+ s_reverse_scatter_idx,
183
+ num_activated_expert_per_token_offset,
184
+ ) = ctx.saved_tensors
185
+
186
+ dx_expanded = torch.empty(TK, H, dtype=dh.dtype, device=dh.device)
187
+ dw1 = torch.empty_like(w1)
188
+ db1 = None if b1 is None else torch.empty_like(b1)
189
+
190
+ if ctx.use_fp8:
191
+ assert b1 is None, "fp8 path does not support bias"
192
+ w1_fp8, w1_sc = _to_fp8_e4m3_weight(w1, (2, 0, 1))
193
+ dh_fp8, dh_sc = _to_fp8_e4m3(dh)
194
+ x_fp8, x_sc = ctx.x_fp8, ctx.x_sc
195
+ gemm(
196
+ dh_fp8,
197
+ w1_fp8,
198
+ cu_seqlens_m=expert_frequency_offset,
199
+ dynamic_scheduler=False,
200
+ out=dx_expanded,
201
+ alpha=w1_sc.float() * dh_sc.float(),
202
+ concat_layout=(("B",) if concat_layout else None),
203
+ )
204
+ gemm(
205
+ x_fp8.T,
206
+ dh_fp8,
207
+ out=dw1.permute(2, 1, 0),
208
+ alpha=x_sc.float() * dh_sc.float(),
209
+ cu_seqlens_k=expert_frequency_offset,
210
+ A_idx=x_gather_idx,
211
+ batch_idx_permute=None,
212
+ dynamic_scheduler=False,
213
+ concat_layout=(("out",) if concat_layout else None),
214
+ )
215
+ else:
216
+ _up_projection_backward_act(
217
+ w1=w1,
218
+ dx_expanded=dx_expanded,
219
+ dh=dh,
220
+ db1=db1,
221
+ expert_frequency_offset=expert_frequency_offset,
222
+ is_glu_activation=is_glu_activation,
223
+ concat_layout=concat_layout,
224
+ )
225
+ gemm(
226
+ x.T,
227
+ dh,
228
+ out=dw1.permute(2, 1, 0),
229
+ cu_seqlens_k=expert_frequency_offset,
230
+ A_idx=x_gather_idx,
231
+ batch_idx_permute=None,
232
+ dynamic_scheduler=False,
233
+ concat_layout=(("out",) if concat_layout else None),
234
+ )
235
+
236
+ dx_reduced = torch.empty(T, H, dtype=dh.dtype, device=dh.device)
237
+
238
+ _token_broadcast_backward(
239
+ dx_reduced=dx_reduced,
240
+ dx_expanded=dx_expanded,
241
+ s_reverse_scatter_idx=s_reverse_scatter_idx,
242
+ num_activated_expert_per_token_offset=num_activated_expert_per_token_offset,
243
+ varlen_K_max=(E if is_each_token_has_variable_activated_experts else K),
244
+ H=H,
245
+ is_varlen_K=is_each_token_has_variable_activated_experts,
246
+ )
247
+
248
+ return dx_reduced, dw1, db1, *[None] * 13
249
+
250
+
251
+ class _DownProjection(torch.autograd.Function):
252
+ @staticmethod
253
+ def forward(
254
+ ctx,
255
+ a: torch.Tensor,
256
+ h: torch.Tensor,
257
+ w2: torch.Tensor,
258
+ b2: torch.Tensor | None,
259
+ topk_scores: torch.Tensor,
260
+ expert_frequency_offset: torch.Tensor,
261
+ T: int,
262
+ K: int,
263
+ x_gather_idx: torch.Tensor,
264
+ s_scatter_idx: torch.Tensor,
265
+ s_reverse_scatter_idx: torch.Tensor,
266
+ num_activated_expert_per_token_offset: torch.Tensor,
267
+ is_varlen_K: bool,
268
+ activation_type: ActivationType,
269
+ use_fp8: bool = False,
270
+ ) -> torch.Tensor:
271
+ TK = a.size(0)
272
+ H, I, E = w2.shape
273
+
274
+ y = torch.empty(TK, H, dtype=a.dtype, device=a.device)
275
+
276
+ if use_fp8:
277
+ a_fp8, a_sc = _to_fp8_e4m3(a)
278
+ w2_fp8, w2_sc = _to_fp8_e4m3_weight(w2, (2, 1, 0))
279
+ gemm(
280
+ a_fp8,
281
+ w2_fp8,
282
+ out=y,
283
+ cu_seqlens_m=expert_frequency_offset,
284
+ alpha=a_sc.float() * w2_sc.float(),
285
+ )
286
+ else:
287
+ gemm(
288
+ a,
289
+ w2.permute(2, 1, 0),
290
+ out=y,
291
+ cu_seqlens_m=expert_frequency_offset,
292
+ bias=b2,
293
+ )
294
+
295
+ o = torch.empty(T, H, device=a.device, dtype=a.dtype)
296
+ topk_scores = topk_scores.view(-1)
297
+
298
+ _router_forward(
299
+ y=y,
300
+ o=o,
301
+ topk_scores=topk_scores,
302
+ s_reverse_scatter_idx=s_reverse_scatter_idx,
303
+ num_activated_expert_per_token_offset=num_activated_expert_per_token_offset,
304
+ varlen_K_max=(E if is_varlen_K else K),
305
+ H=H,
306
+ is_varlen_K=is_varlen_K,
307
+ )
308
+
309
+ ctx.T = T
310
+ ctx.K = K
311
+ ctx.is_varlen_K = is_varlen_K
312
+ ctx.activation_type = activation_type
313
+ ctx.use_fp8 = use_fp8
314
+
315
+ ctx.save_for_backward(
316
+ h,
317
+ w2,
318
+ b2,
319
+ topk_scores,
320
+ expert_frequency_offset,
321
+ x_gather_idx,
322
+ s_scatter_idx,
323
+ )
324
+
325
+ return o
326
+
327
+ @staticmethod
328
+ def backward(ctx, dout: torch.Tensor):
329
+ T = ctx.T
330
+ K = ctx.K
331
+ is_varlen_K = ctx.is_varlen_K
332
+ activation_type = ctx.activation_type
333
+
334
+ (
335
+ h,
336
+ w2,
337
+ b2,
338
+ topk_scores,
339
+ expert_frequency_offset,
340
+ x_gather_idx,
341
+ s_scatter_idx,
342
+ ) = ctx.saved_tensors
343
+
344
+ dw2 = torch.empty_like(w2)
345
+ db2 = None if b2 is None else torch.empty_like(b2)
346
+ dh = torch.empty_like(h)
347
+
348
+ I = w2.size(1)
349
+ TK = x_gather_idx.size(0)
350
+
351
+ a_prime = torch.empty(TK, I, dtype=h.dtype, device=h.device)
352
+ ds = torch.empty_like(topk_scores)
353
+
354
+ if ctx.use_fp8:
355
+ assert b2 is None, "fp8 path does not support bias"
356
+ dout_fp8, dout_sc = _to_fp8_e4m3(dout)
357
+ w2_fp8, w2_sc = _to_fp8_e4m3_weight(w2, (2, 0, 1))
358
+ s = topk_scores[s_scatter_idx]
359
+ _, _, ds_scattered = gemm_dgated(
360
+ dout_fp8,
361
+ w2_fp8,
362
+ PreAct=h, # must stay bf16: gemm_dgated asserts PreAct.element_size() == 2
363
+ activation=activation_type.value,
364
+ dx_out=dh,
365
+ postact_out=a_prime,
366
+ colvec_scale=s,
367
+ colvec_reduce=True,
368
+ cu_seqlens_m=expert_frequency_offset,
369
+ A_idx=x_gather_idx,
370
+ dynamic_scheduler=False,
371
+ )
372
+ ds[s_scatter_idx] = ds_scattered * (dout_sc * w2_sc)
373
+ dh.mul_(dout_sc * w2_sc)
374
+ a_prime_fp8, ap_sc = _to_fp8_e4m3(a_prime)
375
+ gemm(
376
+ dout_fp8.T,
377
+ a_prime_fp8,
378
+ out=dw2.permute(2, 0, 1),
379
+ alpha=dout_sc.float() * ap_sc.float(),
380
+ cu_seqlens_k=expert_frequency_offset,
381
+ A_idx=x_gather_idx,
382
+ batch_idx_permute=None,
383
+ dynamic_scheduler=False,
384
+ )
385
+ else:
386
+ _down_projection_backward_act(
387
+ dout=dout,
388
+ h=h,
389
+ w2=w2,
390
+ dh=dh,
391
+ ds=ds,
392
+ b2=b2,
393
+ db2=db2,
394
+ a_prime=a_prime,
395
+ topk_scores=topk_scores,
396
+ expert_frequency_offset=expert_frequency_offset,
397
+ x_gather_idx=x_gather_idx,
398
+ s_scatter_idx=s_scatter_idx,
399
+ activation_type=activation_type.value,
400
+ )
401
+ gemm(
402
+ dout.T,
403
+ a_prime,
404
+ out=dw2.permute(2, 0, 1),
405
+ cu_seqlens_k=expert_frequency_offset,
406
+ A_idx=x_gather_idx,
407
+ batch_idx_permute=None,
408
+ dynamic_scheduler=False,
409
+ )
410
+
411
+ # TC top-K routing
412
+ if not is_varlen_K:
413
+ ds = ds.view(T, K)
414
+
415
+ return None, dh, dw2, db2, ds, *[None] * 10
416
+
417
+
418
+ def moe_general_routing_inputs(
419
+ x: torch.Tensor,
420
+ router_scores: torch.Tensor,
421
+ token_indices: torch.Tensor,
422
+ expert_indices: torch.Tensor,
423
+ w1: torch.Tensor,
424
+ b1: torch.Tensor | None,
425
+ w2: torch.Tensor,
426
+ b2: torch.Tensor | None,
427
+ E: int,
428
+ stream_id: int,
429
+ activation_type: ActivationType,
430
+ is_inference_mode_enabled: bool = False,
431
+ concat_layout: bool = False,
432
+ use_fp8: bool = False,
433
+ ) -> tuple[torch.Tensor, torch.Tensor]:
434
+ assert ((b1 is None) and (b2 is None)) or ((b1 is not None) and (b2 is not None)), (
435
+ "b1 and b2 has to be None or not None at the same time!"
436
+ )
437
+
438
+ T = x.size(0)
439
+ TK = router_scores.size(0)
440
+ E = w2.size(-1)
441
+ device = router_scores.device
442
+
443
+ if router_scores.dtype != torch.float32:
444
+ router_scores = router_scores.float()
445
+
446
+ s_scatter_idx = torch.empty(TK, dtype=torch.int32, device=device)
447
+ s_reverse_scatter_idx = torch.empty(TK, dtype=torch.int32, device=device)
448
+ expert_frequency = torch.empty(E, dtype=torch.int32, device=device)
449
+ expert_frequency_offset = torch.empty(E + 1, dtype=torch.int32, device=device)
450
+ x_gather_idx = torch.empty(TK, dtype=torch.int32, device=device)
451
+ num_activated_expert_per_token_offset = torch.empty(
452
+ T + 1, dtype=torch.int32, device=device
453
+ )
454
+
455
+ general_routing_router_metadata_triton(
456
+ token_indices,
457
+ expert_indices,
458
+ T,
459
+ E,
460
+ expert_frequency,
461
+ expert_frequency_offset,
462
+ x_gather_idx,
463
+ s_scatter_idx,
464
+ s_reverse_scatter_idx,
465
+ num_activated_expert_per_token_offset,
466
+ )
467
+
468
+ assert is_glu(activation_type), "QuACK GEMM does not support non GLU activation yet"
469
+
470
+ a, h = _UpProjection.apply(
471
+ x,
472
+ w1,
473
+ b1,
474
+ expert_frequency_offset,
475
+ TK,
476
+ None, # K, not needed
477
+ x_gather_idx,
478
+ s_scatter_idx,
479
+ s_reverse_scatter_idx,
480
+ num_activated_expert_per_token_offset,
481
+ True, # is_each_token_has_variable_activated_expert
482
+ activation_type,
483
+ is_inference_mode_enabled,
484
+ concat_layout,
485
+ use_fp8,
486
+ )
487
+
488
+ o = _DownProjection.apply(
489
+ a,
490
+ h,
491
+ w2,
492
+ b2,
493
+ router_scores,
494
+ expert_frequency_offset,
495
+ T,
496
+ None, # K, not needed
497
+ x_gather_idx,
498
+ s_scatter_idx,
499
+ s_reverse_scatter_idx,
500
+ num_activated_expert_per_token_offset,
501
+ True, # is_each_token_has_variable_activated_expert
502
+ activation_type,
503
+ use_fp8,
504
+ )
505
+
506
+ return o, expert_frequency