marcsun13 HF Staff commited on
Commit
567c8ad
·
verified ·
1 Parent(s): fe6ac89

Upload folder using huggingface_hub

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. README.md +7 -0
  2. build.toml +3 -0
  3. flake.nix +17 -0
  4. tests/__init__.py +0 -0
  5. tests/__pycache__/__init__.cpython-310.pyc +0 -0
  6. tests/__pycache__/conftest.cpython-310-pytest-8.3.4.pyc +0 -0
  7. tests/__pycache__/test_mxfp.cpython-310-pytest-8.3.4.pyc +0 -0
  8. tests/conftest.py +20 -0
  9. tests/test_compaction.py +28 -0
  10. tests/test_matmul.py +569 -0
  11. tests/test_mxfp.py +113 -0
  12. tests/test_routing.py +97 -0
  13. tests/test_specialize.py +84 -0
  14. tests/test_swiglu.py +42 -0
  15. tests/test_tensor.py +1 -0
  16. tests/test_tensor_details/test_layout_blackwell.py +24 -0
  17. tests/test_tensor_details/test_layout_hopper.py +99 -0
  18. torch-ext/triton_kernels/__init__.py +0 -0
  19. torch-ext/triton_kernels/__pycache__/__init__.cpython-310.pyc +0 -0
  20. torch-ext/triton_kernels/__pycache__/compaction.cpython-310.pyc +0 -0
  21. torch-ext/triton_kernels/__pycache__/datastruct.cpython-310.pyc +0 -0
  22. torch-ext/triton_kernels/__pycache__/matmul_ogs.cpython-310.pyc +0 -0
  23. torch-ext/triton_kernels/__pycache__/numerics.cpython-310.pyc +0 -0
  24. torch-ext/triton_kernels/__pycache__/routing.cpython-310.pyc +0 -0
  25. torch-ext/triton_kernels/__pycache__/specialize.cpython-310.pyc +0 -0
  26. torch-ext/triton_kernels/__pycache__/swiglu.cpython-310.pyc +0 -0
  27. torch-ext/triton_kernels/__pycache__/target_info.cpython-310.pyc +0 -0
  28. torch-ext/triton_kernels/__pycache__/topk.cpython-310.pyc +0 -0
  29. torch-ext/triton_kernels/compaction.py +69 -0
  30. torch-ext/triton_kernels/compaction_details/__pycache__/_masked_compaction.cpython-310.pyc +0 -0
  31. torch-ext/triton_kernels/compaction_details/_masked_compaction.py +20 -0
  32. torch-ext/triton_kernels/matmul_ogs.py +662 -0
  33. torch-ext/triton_kernels/matmul_ogs_details/__pycache__/_common.cpython-310.pyc +0 -0
  34. torch-ext/triton_kernels/matmul_ogs_details/__pycache__/_finalize_matmul.cpython-310.pyc +0 -0
  35. torch-ext/triton_kernels/matmul_ogs_details/__pycache__/_matmul_ogs.cpython-310.pyc +0 -0
  36. torch-ext/triton_kernels/matmul_ogs_details/__pycache__/_p_matmul_ogs.cpython-310.pyc +0 -0
  37. torch-ext/triton_kernels/matmul_ogs_details/__pycache__/_weight_transpose.cpython-310.pyc +0 -0
  38. torch-ext/triton_kernels/matmul_ogs_details/__pycache__/fast_contiguous.cpython-310.pyc +0 -0
  39. torch-ext/triton_kernels/matmul_ogs_details/__pycache__/opt_flags.cpython-310.pyc +0 -0
  40. torch-ext/triton_kernels/matmul_ogs_details/__pycache__/opt_flags_amd.cpython-310.pyc +0 -0
  41. torch-ext/triton_kernels/matmul_ogs_details/__pycache__/opt_flags_nvidia.cpython-310.pyc +0 -0
  42. torch-ext/triton_kernels/matmul_ogs_details/_common.py +165 -0
  43. torch-ext/triton_kernels/matmul_ogs_details/_finalize_matmul.py +377 -0
  44. torch-ext/triton_kernels/matmul_ogs_details/_matmul_ogs.py +464 -0
  45. torch-ext/triton_kernels/matmul_ogs_details/_p_matmul_ogs.py +505 -0
  46. torch-ext/triton_kernels/matmul_ogs_details/opt_flags.py +298 -0
  47. torch-ext/triton_kernels/matmul_ogs_details/opt_flags_details/opt_flags_amd.py +33 -0
  48. torch-ext/triton_kernels/matmul_ogs_details/opt_flags_details/opt_flags_nvidia.py +111 -0
  49. torch-ext/triton_kernels/numerics.py +42 -0
  50. torch-ext/triton_kernels/numerics_details/__init__.py +0 -0
README.md ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ # triton-kernels
2
+
3
+ triton-kernels is a set of kernels that enable fast moe on different architecture. These kernels are compatible with different precision (e.g bf16, mxfp4)
4
+
5
+
6
+ Original code here https://github.com/triton-lang/triton/tree/main/python/triton_kernels
7
+ The current version is the following commit 7d0efaa7231661299284a603512fce4fa255e62c
build.toml ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ [general]
2
+ name = "triton_kernels"
3
+ universal = true
flake.nix ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ description = "Flake for triton-kernels kernels";
3
+
4
+ inputs = {
5
+ kernel-builder.url = "github:huggingface/kernel-builder";
6
+ };
7
+
8
+ outputs =
9
+ {
10
+ self,
11
+ kernel-builder,
12
+ }:
13
+ kernel-builder.lib.genFlakeOutputs {
14
+ path = ./.;
15
+ rev = self.shortRev or self.dirtyShortRev or self.lastModifiedDate;
16
+ };
17
+ }
tests/__init__.py ADDED
File without changes
tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (156 Bytes). View file
 
tests/__pycache__/conftest.cpython-310-pytest-8.3.4.pyc ADDED
Binary file (618 Bytes). View file
 
tests/__pycache__/test_mxfp.cpython-310-pytest-8.3.4.pyc ADDED
Binary file (8.73 kB). View file
 
tests/conftest.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+
4
+ def pytest_addoption(parser):
5
+ parser.addoption("--device", action="store", default="cuda")
6
+
7
+
8
+ @pytest.fixture
9
+ def device(request):
10
+ return request.config.getoption("--device")
11
+
12
+
13
+ @pytest.fixture
14
+ def fresh_knobs(monkeypatch):
15
+ from triton._internal_testing import _fresh_knobs_impl
16
+ fresh_function, reset_function = _fresh_knobs_impl(monkeypatch)
17
+ try:
18
+ yield fresh_function()
19
+ finally:
20
+ reset_function()
tests/test_compaction.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+ import torch
3
+ from triton_kernels.compaction import compaction, compaction_torch
4
+
5
+
6
+ @pytest.mark.parametrize("n_tokens, n_cols, k, p", [
7
+ (8192, 64, 4, 0.5),
8
+ (8192, 64, 4, 1.0),
9
+ (131, 128, 16, 0.6),
10
+ (496, 128, 16, 0.),
11
+ ])
12
+ def test_compaction(n_tokens, n_cols, k, p, device):
13
+ yi = torch.rand((n_tokens, n_cols), device=device).argsort(dim=-1)
14
+ yi = yi[:, :k].to(torch.int32)
15
+ yv = torch.randn((n_tokens, k), dtype=torch.bfloat16, device=device)
16
+ # "drop" indices from yi with probability `p`
17
+ mask = torch.zeros((n_tokens, n_cols), dtype=torch.int32, device=device)
18
+ keep = (torch.rand(yi.shape, device=device) < p)
19
+ if keep.any():
20
+ rows = torch.arange(yi.size(0), device=device).unsqueeze(1).expand_as(yi)
21
+ mask[rows[keep], yi[keep]] = 1
22
+ chunks = mask.view(*mask.shape[:-1], -1, 32)
23
+ weights = (1 << torch.arange(32, dtype=torch.int32, device=device))
24
+ bitmask = (chunks.int() * weights).sum(dim=-1)
25
+ yv_ref, yi_ref = compaction_torch(yv, yi, bitmask)
26
+ yv_tri, yi_tri = compaction(yv, yi, bitmask)
27
+ assert torch.all(yi_ref == yi_tri)
28
+ assert torch.all(yv_ref == yv_tri)
tests/test_matmul.py ADDED
@@ -0,0 +1,569 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # isort: off
2
+ # fmt: off
3
+ from dataclasses import dataclass, fields, replace
4
+ import pytest
5
+ import torch
6
+ from typing import Union
7
+ import triton
8
+ # routing utilities
9
+ from triton_kernels.routing import routing
10
+ # matmul utilities
11
+ import triton_kernels.matmul_ogs_details.opt_flags as opt_flags
12
+ from triton_kernels.matmul_ogs import FlexCtx, PrecisionConfig, FusedActivation, FnSpecs, FnName, Epilogue
13
+ from triton_kernels.matmul_ogs import matmul_ogs_set_idle_sms, matmul_ogs, matmul_ogs_torch
14
+ from triton_kernels.swiglu import swiglu, swiglu_fn, PrecisionConfig as SwiGLUPrecisionConfig
15
+ from triton_kernels.tensor import convert_layout, wrap_torch_tensor, FP4
16
+ from triton_kernels.tensor_details import layout
17
+ # numerics utilities
18
+ from triton_kernels.numerics import InFlexData, OutFlexData
19
+ from triton_kernels.numerics_details.mxfp import downcast_to_mxfp, upcast_from_mxfp, dequantize_mxfp8_fn, downcast_to_mxfp_torch, upcast_from_mxfp_torch, MXFP_BLOCK_SIZE
20
+ # testing utilities
21
+ from triton_kernels.testing import assert_close, compute_actual_scale
22
+ # target-specific utilities
23
+ from triton_kernels.target_info import is_hip, is_hip_cdna3, is_cuda, is_hip_cdna4
24
+
25
+ # ---------------
26
+ # initialize data
27
+ # ---------------
28
+
29
+
30
+ def alloc_rand(shape, device, dtype, requires_grad=True):
31
+ if dtype.itemsize == 1:
32
+ tmp = 2**-(torch.randint(4, 8, shape, device=device, dtype=torch.float16))
33
+ return tmp.to(dtype).requires_grad_(requires_grad)
34
+ return torch.randn(shape, device=device, dtype=dtype, requires_grad=requires_grad)
35
+
36
+
37
+ def alloc_rand_like(x):
38
+ return alloc_rand(x.shape, x.device, x.dtype, x.requires_grad)
39
+
40
+
41
+ def mask_indx(idx, n_expts_act):
42
+ idx.src_indx[idx.dst_indx[-n_expts_act:]] = -1
43
+ idx.dst_indx[-n_expts_act:] = -1
44
+ return idx
45
+
46
+
47
+ def init_routing_data(m, n_expts_tot, n_expts_act, n_expt_shards, do_gather, do_scatter, device="cuda"):
48
+ logits = torch.randn((m, n_expts_tot), dtype=torch.float16, device=device, requires_grad=True)
49
+ routing_data, gather_idx, scatter_idx = routing(logits, n_expts_act, simulated_ep=n_expt_shards)
50
+ routing_data.gate_scal = None
51
+ gather_idx = gather_idx if do_gather else None
52
+ scatter_idx = scatter_idx if do_scatter else None
53
+ return m, routing_data, gather_idx, scatter_idx
54
+
55
+
56
+ def init_compute_data(m, n, k, gindx, sindx, n_expts_tot, n_expts_act, n_expt_shards, mode, act_dtype, weight_dtype,
57
+ has_y_gammas, requires_grad=True, device="cuda"):
58
+ torch.manual_seed(0)
59
+ assert mode in {'batched', "plain", 'ragged'}
60
+ in_m = m * (n_expts_act if gindx is None else 1)
61
+ shape_x = (n_expts_tot, in_m, k) if mode == 'batched' else (in_m, k)
62
+ shape_batch = tuple() if mode == "plain" else (n_expts_tot // n_expt_shards, )
63
+ x = alloc_rand(shape_x, device=device, dtype=act_dtype, requires_grad=requires_grad)
64
+ w = alloc_rand(shape_batch + (k, n), device=device, dtype=weight_dtype, requires_grad=requires_grad)
65
+ bias = alloc_rand(shape_batch + (n, ), device=device, dtype=torch.float32, requires_grad=requires_grad)
66
+ gs0 = 2**torch.randint(-5, 0, (m * n_expts_act, ), device=device, dtype=torch.float32, requires_grad=requires_grad)
67
+ gs1 = 2**torch.randint(-5, 0, (m * n_expts_act, ), device=device, dtype=torch.float32, requires_grad=requires_grad)
68
+ gs0 = gs0.detach().requires_grad_(requires_grad)
69
+ gs1 = gs1.detach().requires_grad_(requires_grad)
70
+ if mode == 'batched' or (not has_y_gammas) or (has_y_gammas and (gindx is not None) and act_dtype.itemsize >= 2):
71
+ gs0 = None
72
+ gs1 = None
73
+ if "float8" in str(weight_dtype) and torch.cuda.get_device_capability()[0] < 10:
74
+ w = w.transpose(-1, -2).contiguous().transpose(-1, -2)
75
+ return x, w, bias, gs0, gs1
76
+
77
+
78
+ # ---------------
79
+ # numerics stuff
80
+ # ---------------
81
+
82
+
83
+ def init_precision(out_dtype, act_use_flexpoint, weight_dtype, weight_mxfp, n_expts_tot=1, device="cuda"):
84
+ weight_use_flexpoint = weight_dtype.itemsize == 1 and not weight_mxfp
85
+ # flexpoint
86
+ make_tensor = lambda val0, val1: torch.tensor([val0, val1] * (n_expts_tot // 2) +
87
+ ([val0]
88
+ if n_expts_tot % 2 else []), dtype=torch.float32, device=device)
89
+ make_scalar = lambda val: torch.tensor([val], dtype=torch.float32, device=device)
90
+ in_flex_data = lambda scale, use_flex: InFlexData(dtype=out_dtype, scale=make_scalar(scale)
91
+ ) if use_flex else InFlexData()
92
+ in_flex_edata = lambda scale0, scale1, use_flex: InFlexData(dtype=weight_dtype, scale=make_tensor(scale0, scale1)
93
+ ) if use_flex else InFlexData()
94
+ out_flex_data = lambda scale, use_flex: OutFlexData(dtype=out_dtype, expected_scale=make_scalar(
95
+ scale), actual_scale=make_scalar(0), checksum_scale=make_scalar(0)) if use_flex else OutFlexData()
96
+ flex_ctx = FlexCtx(
97
+ lhs_data=in_flex_data(1.25, act_use_flexpoint),
98
+ rhs_data=in_flex_edata(1.50, 1.25, weight_use_flexpoint),
99
+ out_data=out_flex_data(4.00, act_use_flexpoint),
100
+ )
101
+ return PrecisionConfig(flex_ctx=flex_ctx, acc_scale=2.0 if act_use_flexpoint or weight_use_flexpoint else 1.0,
102
+ out_dtype=out_dtype)
103
+
104
+
105
+ def apply_precision(x_tri, w_tri, bias_tri, gs0_tri, gs1_tri, precision_config):
106
+ flex_ctx = precision_config.flex_ctx
107
+
108
+ def apply(x, scale):
109
+ if scale is None:
110
+ x = x.clone()
111
+ elif scale.numel() == 1:
112
+ x = x.float() * scale
113
+ else:
114
+ assert x.ndim == 3
115
+ assert scale.numel() == x.shape[0]
116
+ x = x.float() * scale[:, None, None]
117
+ return x.detach().requires_grad_()
118
+
119
+ return (
120
+ apply(x_tri, flex_ctx.lhs_data.scale),
121
+ apply(w_tri, flex_ctx.rhs_data.scale),
122
+ apply(bias_tri, None),
123
+ None if gs0_tri is None else apply(gs0_tri, None),
124
+ None if gs1_tri is None else apply(gs1_tri, None),
125
+ )
126
+
127
+
128
+ def dtype_str_to_torch(dtype_str: str) -> torch.dtype:
129
+ return torch.uint8 if dtype_str == "float4_e2m1" else getattr(torch, dtype_str)
130
+
131
+
132
+ # Scope to ensure that the opt_flags_constraints are reset after the test
133
+ @pytest.fixture
134
+ def opt_flags_scope(request):
135
+ yield
136
+ opt_flags.reset_opt_flags_constraints()
137
+
138
+
139
+ # ---------------
140
+ # unit tests
141
+ # ---------------
142
+
143
+
144
+ @dataclass
145
+ class Case:
146
+ m: int
147
+ n: int
148
+ k: int
149
+ mode: str
150
+ act_dtype_str: str
151
+ weight_dtype_str: str
152
+ n_expts_tot: int = 1
153
+ n_expts_act: int = 1
154
+ n_expt_shards: int = 1
155
+ split_k: int = 1
156
+ hbm_swizzling: bool = False
157
+ epilogue_subtile: Union[int, None] = None
158
+
159
+
160
+ @pytest.mark.parametrize(
161
+ ", ".join(f.name for f in fields(Case)),
162
+ [
163
+ tuple(getattr(case, f.name) for f in fields(Case)) for case in [
164
+ # Non-mx types:
165
+ Case(16, 256, 256, "ragged", "float16", "float16", 128, 4),
166
+ Case(16, 256, 256, "ragged", "float16", "float16", 128, 4, n_expt_shards=2),
167
+ Case(16, 256, 256, "ragged", "float16", "float16", 128, 4, n_expt_shards=4),
168
+ Case(16, 256, 256, "ragged", "float16", "float16", 4, 1, n_expt_shards=2),
169
+ Case(16, 256, 256, "ragged", "float16", "float16", 128, 4, split_k=3),
170
+ Case(16, 256, 256, "ragged", "float16", "float16", 128, 4, split_k=3),
171
+ Case(300, 400, 400, "batched", "float8_e5m2", "float8_e5m2", 5, 1),
172
+ Case(16, 256, 256, "batched", "float16", "float16", 5, 1),
173
+ Case(16, 256, 256, "ragged", "float16", "float16", 3, 1),
174
+ Case(256, 256, 256, "ragged", "float16", "float16", 4, 1),
175
+ Case(256, 256, 256, "ragged", "float16", "float16", 4, 1, split_k=3),
176
+ Case(300, 400, 400, "batched", "float16", "float16", 5, 1),
177
+ Case(300, 400, 400, "ragged", "float16", "float16"),
178
+ Case(300, 400, 400, "ragged", "float8_e5m2", "float8_e5m2"),
179
+ Case(1000, 400, 400, "ragged", "float8_e5m2", "float8_e5m2", 3, 1),
180
+ Case(600, 400, 400, "ragged", "float8_e5m2", "float8_e5m2", 4, 2, epilogue_subtile=1),
181
+ Case(600, 400, 400, "ragged", "float8_e5m2", "float8_e5m2", 4, 2, epilogue_subtile=2),
182
+ Case(600, 400, 400, "ragged", "float8_e5m2", "float8_e5m2", 4, 2, epilogue_subtile=4),
183
+ Case(600, 400, 400, "ragged", "float8_e5m2", "float8_e5m2", 4, 2),
184
+ Case(600, 400, 400, "ragged", "float8_e5m2", "float8_e5m2", 4, 2, n_expt_shards=2),
185
+ Case(600, 400, 400, "ragged", "float8_e5m2", "float8_e5m2", 4, 1, n_expt_shards=2),
186
+ Case(600, 400, 400, "ragged", "float8_e5m2", "float8_e5m2", 4, 2, split_k=2),
187
+ Case(1000, 400, 400, "ragged", "float16", "float16", 3, 1),
188
+ Case(1000, 700, 700, "ragged", "float16", "float16", 8, 2),
189
+ Case(1000, 700, 700, "ragged", "float16", "float16", 8, 2, split_k=9),
190
+ # mx types:
191
+ Case(16, 256, 256, "plain", "bfloat16", "mxfloat4_e2m1", 1, 1),
192
+ Case(16, 256, 256, "plain", "bfloat16", "mxfloat4_e2m1", 1, 1, hbm_swizzling=True),
193
+ Case(16, 256, 256, "ragged", "bfloat16", "mxfloat4_e2m1", 1, 1),
194
+ Case(16, 256, 256, "ragged", "bfloat16", "mxfloat4_e2m1", 1, 1, hbm_swizzling=True),
195
+ Case(1000, 700, 700, "batched", "bfloat16", "mxfloat4_e2m1", 8, 2),
196
+ Case(1000, 700, 700, "batched", "bfloat16", "mxfloat4_e2m1", 8, 2, hbm_swizzling=True),
197
+ Case(1000, 700, 700, "ragged", "bfloat16", "mxfloat4_e2m1", 8, 2, split_k=9),
198
+ Case(1000, 512, 256, "ragged", "bfloat16", "mxfloat4_e2m1", 8, 2, split_k=9, hbm_swizzling=True),
199
+ Case(300, 400, 400, "ragged", "bfloat16", "mxfloat8_e4m3fn", 8, 4),
200
+ Case(300, 400, 400, "ragged", "bfloat16", "mxfloat8_e4m3fn", 8, 4, hbm_swizzling=True),
201
+ Case(300, 400, 400, "batched", "bfloat16", "mxfloat8_e5m2", 32, 4),
202
+ Case(1000, 700, 2, "batched", "bfloat16", "mxfloat4_e2m1", 8, 2),
203
+ Case(1, 2880, 2880, "ragged", "bfloat16", "mxfloat4_e2m1", 128, 4),
204
+ Case(16, 256, 256, "ragged", "float8_e5m2", "mxfloat4_e2m1", 128, 4, hbm_swizzling=True),
205
+ Case(1000, 704, 832, "batched", "float8_e5m2", "mxfloat4_e2m1", 3, 1, hbm_swizzling=True),
206
+ Case(1000, 704, 832, "batched", "float8_e5m2", "mxfloat4_e2m1", 3, 1, hbm_swizzling=True),
207
+ Case(1000, 704, 832, "batched", "float8_e5m2", "mxfloat4_e2m1", 3, 1),
208
+ Case(1000, 704, 800, "ragged", "float8_e5m2", "mxfloat4_e2m1", 8, 2, split_k=9),
209
+ Case(1000, 704, 800, "ragged", "float8_e5m2", "mxfloat4_e2m1", 8, 2, split_k=9, hbm_swizzling=True),
210
+ Case(1000, 704, 800, "ragged", "float8_e5m2", "mxfloat4_e2m1", 8, 2),
211
+ Case(1000, 704, 800, "ragged", "float8_e5m2", "mxfloat4_e2m1", 8, 2, hbm_swizzling=True),
212
+ Case(300, 400, 400, "ragged", "float8_e5m2", "mxfloat8_e4m3fn", 8, 4),
213
+ Case(300, 400, 400, "ragged", "float8_e5m2", "mxfloat8_e4m3fn", 8, 4, hbm_swizzling=True),
214
+ Case(300, 400, 832, "ragged", "float8_e5m2", "mxfloat4_e2m1", 8, 4),
215
+ Case(300, 400, 832, "ragged", "float8_e5m2", "mxfloat4_e2m1", 8, 4, hbm_swizzling=True),
216
+ Case(300, 400, 400, "batched", "float8_e5m2", "mxfloat8_e4m3fn", 32, 4),
217
+ Case(300, 400, 400, "batched", "float8_e5m2", "mxfloat8_e4m3fn", 32, 4, hbm_swizzling=True),
218
+ Case(256, 256, 256, "ragged", "float8_e5m2", "mxfloat4_e2m1", 128, 4, hbm_swizzling=True),
219
+ Case(256, 256, 256, "ragged", "float8_e5m2", "mxfloat4_e2m1", 128, 4, hbm_swizzling=False),
220
+ Case(16, 256, 256, "ragged", "mxfloat8_e4m3fn", "mxfloat4_e2m1", 128, 4, hbm_swizzling=True),
221
+ Case(1000, 704, 800, "batched", "mxfloat8_e4m3fn", "mxfloat4_e2m1", 3, 1, hbm_swizzling=True),
222
+ Case(1000, 704, 800, "batched", "mxfloat8_e4m3fn", "mxfloat4_e2m1", 2, 1),
223
+ Case(1000, 704, 800, "ragged", "mxfloat8_e4m3fn", "mxfloat4_e2m1", 8, 2, split_k=9),
224
+ Case(1000, 704, 800, "ragged", "mxfloat8_e4m3fn", "mxfloat4_e2m1", 8, 2, split_k=9, hbm_swizzling=True),
225
+ Case(1000, 704, 800, "ragged", "mxfloat8_e4m3fn", "mxfloat4_e2m1", 8, 2),
226
+ Case(1000, 704, 800, "ragged", "mxfloat8_e4m3fn", "mxfloat4_e2m1", 8, 2, hbm_swizzling=True),
227
+ Case(300, 400, 400, "ragged", "mxfloat8_e4m3fn", "mxfloat8_e4m3fn", 8, 4),
228
+ Case(300, 400, 400, "ragged", "mxfloat8_e4m3fn", "mxfloat8_e4m3fn", 8, 4, hbm_swizzling=True),
229
+ Case(300, 400, 800, "ragged", "mxfloat8_e4m3fn", "mxfloat4_e2m1", 8, 4),
230
+ Case(300, 400, 800, "ragged", "mxfloat8_e4m3fn", "mxfloat4_e2m1", 8, 4, hbm_swizzling=True),
231
+ Case(300, 400, 400, "batched", "mxfloat8_e4m3fn", "mxfloat8_e4m3fn", 32, 4),
232
+ Case(300, 400, 400, "batched", "mxfloat8_e4m3fn", "mxfloat8_e4m3fn", 32, 4, hbm_swizzling=True),
233
+ # AMD
234
+ Case(300, 400, 400, "ragged", "float8_e4m3fnuz", "float8_e4m3fnuz"),
235
+ Case(1000, 400, 400, "ragged", "float8_e4m3fnuz", "float8_e4m3fnuz", 3, 1),
236
+ Case(600, 400, 400, "ragged", "float8_e4m3fnuz", "float8_e4m3fnuz", 4, 2),
237
+ Case(600, 400, 400, "ragged", "float8_e4m3fnuz", "float8_e4m3fnuz", 4, 2, n_expt_shards=2),
238
+ Case(600, 400, 400, "ragged", "float8_e4m3fnuz", "float8_e4m3fnuz", 4, 2, split_k=2),
239
+ Case(300, 400, 400, "ragged", "float8_e4m3fn", "float8_e4m3fn"),
240
+ Case(1000, 400, 400, "ragged", "float8_e4m3fn", "float8_e4m3fn", 3, 1),
241
+ Case(600, 400, 400, "ragged", "float8_e4m3fn", "float8_e4m3fn", 4, 2),
242
+ Case(600, 400, 400, "ragged", "float8_e4m3fn", "float8_e4m3fn", 4, 2, n_expt_shards=2),
243
+ ]
244
+ ],
245
+ )
246
+ @pytest.mark.parametrize("block_m", [16, 128])
247
+ @pytest.mark.parametrize("do_gather, do_scatter, fused_scatter", [
248
+ (False, False, False),
249
+ (True, False, False),
250
+ (False, True, False),
251
+ (True, True, False),
252
+ (True, True, True),
253
+ ])
254
+ @pytest.mark.parametrize("has_y_gammas", [False, True])
255
+ @pytest.mark.parametrize("is_persistent", [False, True])
256
+ def test_op(m, n, k, split_k, do_gather, do_scatter, fused_scatter, has_y_gammas, is_persistent, n_expts_tot,
257
+ n_expts_act, n_expt_shards, mode, act_dtype_str, weight_dtype_str, block_m, hbm_swizzling, epilogue_subtile,
258
+ device, opt_flags_scope, fresh_knobs):
259
+ # TODO: remove when Triton FP8 supports proper RTNE
260
+ if is_cuda():
261
+ if "float8" in weight_dtype_str and torch.cuda.get_device_capability()[0] < 9:
262
+ pytest.skip("Float8 not tested on A100")
263
+ if "float16" in act_dtype_str and "mx" in weight_dtype_str and torch.cuda.get_device_capability()[0] >= 10:
264
+ pytest.skip("float16 x mx not supported with cuda capability >= 10")
265
+ if weight_dtype_str.startswith("mx"):
266
+ if "float8" in act_dtype_str and torch.cuda.get_device_capability()[0] < 10:
267
+ pytest.skip("float8 x mx not supported with cuda capability < 10")
268
+ if act_dtype_str == "mxfloat8_e4m3fn":
269
+ if is_persistent:
270
+ pytest.skip("mx x mx not supported with persistent kernel")
271
+ if n == 2880 and k == 2880 and torch.cuda.get_device_capability()[0] < 9:
272
+ pytest.skip("Not enough memory on A100")
273
+
274
+ elif is_hip():
275
+ if "float8" in act_dtype_str and "mx" in weight_dtype_str and not is_hip_cdna4():
276
+ pytest.skip("float8 x mx only supported on CDNA4")
277
+ if "float8" in act_dtype_str and "mxfloat8" in weight_dtype_str:
278
+ pytest.skip("NYI: float8 x mxfloat8 not tested on AMD GPU")
279
+ if act_dtype_str.startswith("mx") and weight_dtype_str.startswith("mx"):
280
+ pytest.skip("NYI: mx x mx not tested on AMD GPU")
281
+ if is_persistent:
282
+ pytest.skip("NYI: Persistent kernel not supported on AMD GPU")
283
+ if split_k > 1:
284
+ pytest.skip("splitK hasn't been fully tested on AMD GPU.")
285
+
286
+ if "float8_e4m3fnuz" in (weight_dtype_str, act_dtype_str) and not is_hip_cdna3():
287
+ pytest.skip("float8_e4m3fnuz only tested on AMD CDNA3 Platform")
288
+
289
+ if fused_scatter and split_k > 1:
290
+ pytest.skip("fused scatter scratchpad not supported with split_k")
291
+ if hbm_swizzling:
292
+ if is_hip():
293
+ pytest.skip("NYI. HBM swizzling just implemented for CUDA.")
294
+ if torch.cuda.get_device_capability()[0] < 9:
295
+ pytest.skip("NYI. Ampere swizzling.")
296
+ if torch.cuda.get_device_capability()[0] < 10:
297
+ if "mxfloat4" not in weight_dtype_str:
298
+ pytest.skip("NYI. Hopper swizzling just implemented for mxfp4.")
299
+ if k % 64 != 0 or n % 64 != 0:
300
+ # Automatic padding not implemented for Hopper swizzle
301
+ pytest.skip("Hopper swizzling acts on a 64x64 tile (4x1 mma tiles).")
302
+
303
+ # launch metadata for batched / mx types may not work yet.
304
+ test_launch_metadata = (mode == "ragged") and ("mx" not in weight_dtype_str)
305
+
306
+ torch.manual_seed(0)
307
+
308
+ block_k = None
309
+ if is_persistent and weight_dtype_str.startswith("mx") and torch.cuda.get_device_capability()[0] < 10:
310
+ # Override block_k for testing correctness. The default is temporarily 128 for
311
+ # performance reasons which doesn't work with persistent matmul.
312
+ # TODO: revisit when Triton is better for H100 + MXFP4
313
+ block_k = 256
314
+
315
+ constraints = {
316
+ "block_m": block_m,
317
+ "block_k": block_k,
318
+ "split_k": split_k,
319
+ "fused_scatter": fused_scatter,
320
+ "is_persistent": is_persistent,
321
+ "epilogue_subtile": epilogue_subtile,
322
+ }
323
+ opt_flags.update_opt_flags_constraints(constraints)
324
+
325
+ weight_mxfp = weight_dtype_str.startswith("mx")
326
+ if weight_mxfp:
327
+ weight_dtype_str = weight_dtype_str[2:]
328
+ act_mxfp8 = act_dtype_str.startswith("mx")
329
+ act_is_float8 = act_dtype_str.startswith("float8")
330
+ if act_mxfp8:
331
+ act_dtype_str = act_dtype_str[2:]
332
+ dequantize_mxfp8_spec = FnSpecs(
333
+ FnName.DEQUANTIZE_MXFP8.name, dequantize_mxfp8_fn, (), ()
334
+ )
335
+
336
+ test_bwd = False
337
+ weight_dtype = dtype_str_to_torch(weight_dtype_str)
338
+ act_dtype = dtype_str_to_torch(act_dtype_str)
339
+ precision_opt = init_precision(act_dtype, act_is_float8, weight_dtype, weight_mxfp, n_expts_tot // n_expt_shards, device=device)
340
+ # precision_opt.x_pad_trans_requires_flexpoint = False
341
+ if mode == "ragged":
342
+ m, rdata, gindx, sindx = init_routing_data(m, n_expts_tot, n_expts_act, n_expt_shards, do_gather, do_scatter,
343
+ device=device)
344
+ else:
345
+ rdata = gindx = sindx = None
346
+ x_tri, w_tri, bias_tri, gs0_tri, gs1_tri = init_compute_data(m, n, k, gindx, sindx, n_expts_tot, n_expts_act,
347
+ n_expt_shards, mode, torch.bfloat16 if act_mxfp8 else act_dtype, #
348
+ torch.bfloat16 if weight_mxfp else weight_dtype,
349
+ has_y_gammas, requires_grad=test_bwd, device=device)
350
+ x_ref, w_ref, bias_ref, gs0_ref, gs1_ref = apply_precision(x_tri, w_tri, bias_tri, gs0_tri, gs1_tri, precision_opt)
351
+
352
+ if w_tri.shape[0] == 1:
353
+ # Test the case when weight has dim 2, i.e., shape (K, N).
354
+ w_tri = w_tri.squeeze(0).detach().requires_grad_(test_bwd)
355
+ w_ref = w_ref.squeeze(0).detach().requires_grad_(test_bwd)
356
+
357
+ if weight_mxfp:
358
+ mx_axis = w_tri.ndim - 2
359
+ # compute layouts
360
+ w_layout, w_layout_opts = layout.StridedLayout, dict()
361
+ w_scale_layout, w_scale_layout_opts = layout.StridedLayout, dict()
362
+ if hbm_swizzling and "float4" in weight_dtype_str:
363
+ w_layout, w_layout_opts = layout.make_default_matmul_mxfp4_w_layout(mx_axis=mx_axis)
364
+ w_scale_layout, w_scale_layout_opts = layout.make_default_matmul_mxfp4_w_scale_layout(
365
+ mx_axis=mx_axis, num_warps=8)
366
+ # downcast to mxfp
367
+ w_tri, w_scale_tri = downcast_to_mxfp(w_tri, weight_dtype, axis=mx_axis)
368
+ w_ref = upcast_from_mxfp(w_tri, w_scale_tri, torch.bfloat16, axis=mx_axis)
369
+ w_tri_dtype = FP4 if "float4" in weight_dtype_str else weight_dtype
370
+ w_tri = wrap_torch_tensor(w_tri, w_tri_dtype)
371
+ w_scale_tri = wrap_torch_tensor(w_scale_tri)
372
+ # convert layouts
373
+ w_tri = convert_layout(w_tri, w_layout, **w_layout_opts)
374
+ w_scale_tri = convert_layout(w_scale_tri, w_scale_layout, **w_scale_layout_opts)
375
+ precision_opt.weight_scale = w_scale_tri
376
+ epilogue = None
377
+ if act_mxfp8:
378
+ x_tri, x_mx_scales_tri = downcast_to_mxfp(x_tri, act_dtype, axis=-1)
379
+ x_ref = upcast_from_mxfp(x_tri, x_mx_scales_tri, torch.bfloat16, axis=-1)
380
+ is_input_batched = x_tri.ndim == 3
381
+ y_shape = x_tri.shape if is_input_batched else (1,) + x_tri.shape
382
+ n_rows = y_shape[1] if gindx is None or mode == "batched" else gindx.dst_indx.shape[0]
383
+ y_shape = (y_shape[0], n_rows, w_tri.shape[-1])
384
+ if sindx is None or mode == "batched":
385
+ if not is_input_batched:
386
+ y_shape = (y_shape[1], y_shape[2])
387
+ else:
388
+ y_shape = (n_rows // rdata.n_expts_act, y_shape[-1])
389
+ y_scale_shape = y_shape[:-1] + (triton.cdiv(y_shape[-1], MXFP_BLOCK_SIZE),)
390
+ y_scale = torch.empty(y_scale_shape, dtype=torch.uint8, device=x_tri.device)
391
+ precision_opt = replace(precision_opt, act_scale=x_mx_scales_tri, out_scale=y_scale)
392
+ epilogue = Epilogue(dequantize_mxfp8_spec, tuple(), tuple(), effective_itemsize=6.0)
393
+ else:
394
+ y_scale = None
395
+
396
+ if test_launch_metadata:
397
+
398
+ def _clobber(t, used_mask):
399
+ # Fill the unread part of the tensor with garbage, to be sure that
400
+ # we don't actually read from the part.
401
+ if len(used_mask) == 1:
402
+ return
403
+ elif t.element_size() == 1:
404
+ t.view(torch.int8)[~used_mask] = 127
405
+ else:
406
+ t[~used_mask] = torch.inf
407
+
408
+ if rdata is not None:
409
+ n_tokens = rdata.expt_hist.sum().item()
410
+ used_expts = (rdata.expt_hist > 0)
411
+ _clobber(w_tri, used_expts)
412
+ n_w_bytes = used_expts.sum().item() * n * k * w_tri.element_size()
413
+ else:
414
+ n_tokens = m
415
+ n_w_bytes = w_tri.numel() * w_tri.element_size()
416
+
417
+ if gindx is not None:
418
+ used_x_rows = (gindx.dst_indx.view(-1, n_expts_act) != -1).any(dim=1)
419
+ _clobber(x_tri, used_x_rows)
420
+ n_x_bytes = used_x_rows.sum().item() * k * x_tri.element_size()
421
+ elif rdata is not None:
422
+ n_x_bytes = n_tokens * k * x_tri.element_size()
423
+ else:
424
+ n_x_bytes = x_tri.numel() * x_tri.element_size()
425
+
426
+ nbytes = None
427
+
428
+ def _hook(launch_metadata):
429
+ nonlocal nbytes
430
+ metadata = launch_metadata.get()
431
+ if "matmul_ogs" in metadata["name"]:
432
+ nbytes = metadata["bytes"]
433
+
434
+ triton.knobs.runtime.launch_enter_hook = _hook
435
+
436
+ if mode == "batched":
437
+ rdata, gindx, sindx = None, None, None
438
+ flex = precision_opt.flex_ctx
439
+
440
+ # triton
441
+ try:
442
+ tri_y = matmul_ogs(x_tri, w_tri, bias_tri, rdata, gindx, sindx, precision_opt, gammas=gs1_ref, epilogue=epilogue)
443
+ except (opt_flags.InapplicableConstraint, NotImplementedError):
444
+ pytest.skip("inapplicable opt_flags constraint")
445
+ # If split_k > 1, then the intermediate tensor is fp32.
446
+ sep_gather = mode == "ragged" and do_gather and n_expts_act > 1 and split_k == 1
447
+ sep_scatter = mode == "ragged" and do_scatter and n_expts_act > 1 and split_k == 1
448
+ y_scale = flex.out_data.expected_scale if act_is_float8 else 1
449
+
450
+ if test_launch_metadata:
451
+ if gindx is not None:
452
+ n_y_bytes = (gindx.src_indx != -1).sum().item() * n * tri_y.element_size()
453
+ elif rdata is not None:
454
+ n_y_bytes = n_tokens * n * tri_y.element_size()
455
+ else:
456
+ n_y_bytes = tri_y.numel() * tri_y.element_size()
457
+ assert nbytes == n_x_bytes + n_y_bytes + n_w_bytes
458
+ triton.knobs.runtime.launch_enter_hook = None
459
+
460
+ def round_x(x, idx):
461
+ return x.to(act_dtype).to(torch.float32) if sep_gather else x
462
+
463
+ round_y = lambda y: (y / y_scale).to(act_dtype).to(torch.float32) * y_scale if sep_scatter else y
464
+ ref_y = matmul_ogs_torch(x_ref, w_ref, bias_ref, #
465
+ rdata, gindx, sindx, round_x=round_x, round_y=round_y, gammas=gs1_ref)
466
+ scale = lambda val, scal: val if scal is None else val / scal
467
+ if n_expt_shards > 1:
468
+ if do_scatter:
469
+ indx = sindx.dst_indx[sindx.dst_indx != -1]
470
+ ref_y = ref_y[indx // n_expts_act, :]
471
+ if act_is_float8:
472
+ tri_y = tri_y.view(torch.int8)
473
+ tri_y = tri_y[indx // n_expts_act, :]
474
+ if act_is_float8:
475
+ tri_y = tri_y.view(act_dtype)
476
+ else:
477
+ n_rows = rdata.expt_hist.sum()
478
+ assert n_rows > 0
479
+ ref_y = ref_y[:n_rows]
480
+ tri_y = tri_y[:n_rows]
481
+ if act_mxfp8:
482
+ tri_y = upcast_from_mxfp(tri_y, precision_opt.out_scale, dtype=torch.bfloat16, axis=-1).to(ref_y.dtype)
483
+ ref_y_quant, ref_y_scale = downcast_to_mxfp_torch(ref_y, act_dtype, axis=-1)
484
+ ref_y = upcast_from_mxfp_torch(ref_y_quant, ref_y_scale, target_dtype=ref_y.dtype, axis=-1)
485
+ maxtol = 4e-1
486
+ rmstol = 4e-2
487
+ else:
488
+ maxtol = None
489
+ rmstol = None
490
+ assert_close(scale(ref_y, flex.out_data.expected_scale), tri_y, maxtol=maxtol, rmstol=rmstol)
491
+
492
+ if act_is_float8:
493
+ tri_y_scale = flex.out_data.actual_scale.clone()
494
+ ref_y_scale = compute_actual_scale(ref_y, tri_y.dtype)
495
+ assert (ref_y_scale -
496
+ tri_y_scale).abs() < 1e-10, f"ref_y_scale: {ref_y_scale}, tri_y_scale: {tri_y_scale.item()}"
497
+
498
+
499
+ def test_set_idle_sms():
500
+ if not is_cuda():
501
+ pytest.skip("Only supported on CUDA")
502
+ from triton_kernels.matmul_ogs_details.opt_flags import make_opt_flags
503
+ num_idle_sms = 24
504
+ matmul_ogs_set_idle_sms(num_idle_sms)
505
+ flags = make_opt_flags(torch.float32, torch.float32, torch.float32, PrecisionConfig(), \
506
+ 1024, 1024, 1024, None, True, False, 1)
507
+ assert flags.idle_sms == num_idle_sms
508
+
509
+
510
+ @pytest.mark.parametrize("m, n, k, mode", [
511
+ (1200, 704, 608, "ragged"),
512
+ (800, 800, 400, "batched"),
513
+ ])
514
+ @pytest.mark.parametrize("split_k", [1, 2])
515
+ @pytest.mark.parametrize("do_gather, do_scatter, fused_scatter", [
516
+ (False, False, False),
517
+ (True, False, False),
518
+ (False, True, False),
519
+ (True, True, False),
520
+ (True, True, True),
521
+ ])
522
+ @pytest.mark.parametrize("is_persistent, epilogue_subtile", [
523
+ (False, None),
524
+ (True, 1),
525
+ (True, 4),
526
+ ])
527
+ @pytest.mark.parametrize("swiglu_alpha, swiglu_limit", [
528
+ (1.1, 1.4),
529
+ (1.0, 1.2),
530
+ (0.7, 1.0),
531
+ ])
532
+ def test_fused_act(m, n, k, mode, split_k, do_gather, do_scatter, fused_scatter, is_persistent, epilogue_subtile,
533
+ swiglu_alpha, swiglu_limit, device, opt_flags_scope):
534
+ if fused_scatter and split_k > 1:
535
+ pytest.skip("fused scatter scratchpad not supported with split_k")
536
+ torch.manual_seed(0)
537
+ constraints = {
538
+ "is_persistent": is_persistent,
539
+ "epilogue_subtile": epilogue_subtile,
540
+ "fused_scatter": fused_scatter,
541
+ "split_k": split_k,
542
+ }
543
+ n_expts_tot, n_expts_act, n_expt_shards = 1, 1, 1
544
+ opt_flags.update_opt_flags_constraints(constraints)
545
+
546
+ weight_dtype, act_dtype = torch.float16, torch.float16
547
+ if mode == "ragged":
548
+ m, rdata, gindx, sindx = init_routing_data(m, n_expts_tot, n_expts_act, n_expt_shards, do_gather, do_scatter,
549
+ device=device)
550
+ else:
551
+ rdata = gindx = sindx = None
552
+
553
+ precision_opt = init_precision(act_dtype, str(act_dtype).startswith("torch.float8"), weight_dtype, False, n_expts_tot // n_expt_shards, device=device)
554
+ x, w, bias, _, _ = init_compute_data(m, n, k, gindx, sindx, n_expts_tot, n_expts_act, n_expt_shards, mode,
555
+ act_dtype, weight_dtype, False, requires_grad=False, device=device)
556
+
557
+ if mode == "batched":
558
+ rdata, gindx, sindx = None, None, None
559
+
560
+ try:
561
+ a = swiglu(matmul_ogs(x, w, bias, rdata, gindx, sindx, precision_opt), swiglu_alpha,
562
+ precision_config=SwiGLUPrecisionConfig(swiglu_limit))
563
+ b = matmul_ogs(
564
+ x, w, bias, rdata, gindx, sindx, precision_opt,
565
+ fused_activation=FusedActivation(FnSpecs("swiglu", swiglu_fn, ("alpha", "limit")),
566
+ (swiglu_alpha, swiglu_limit), 2))
567
+ except opt_flags.InapplicableConstraint:
568
+ pytest.skip("inapplicable constraint")
569
+ assert_close(a, b)
tests/test_mxfp.py ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+ import torch
3
+
4
+ from triton_kernels.numerics_details.mxfp import (
5
+ DequantScaleRoundingMode,
6
+ downcast_to_mxfp,
7
+ downcast_to_mxfp_torch,
8
+ get_max_quant_val,
9
+ upcast_from_mxfp,
10
+ upcast_from_mxfp_torch,
11
+ )
12
+ from triton_kernels.testing import assert_close, assert_equal
13
+
14
+
15
+ def dtype_str_to_torch(dtype_str: str) -> torch.dtype:
16
+ return torch.uint8 if dtype_str == "float4_e2m1" else getattr(torch, dtype_str)
17
+
18
+
19
+ @pytest.mark.parametrize("dst_dtype", ["float16", "bfloat16"])
20
+ def test_mxfp4_rounding_cases(dst_dtype):
21
+ dst_dtype = dtype_str_to_torch(dst_dtype)
22
+ x = torch.tensor([6, 0, 0.24, 0.25, 0.75, 0.99, 1.2, 1.3]).cuda().bfloat16().view(1, -1, 1)
23
+ quant, scale = downcast_to_mxfp(x, torch.uint8, axis=1)
24
+ dequant = upcast_from_mxfp(quant, scale, dst_dtype, axis=1)
25
+ assert dequant.flatten().tolist() == [6, 0, 0, 0.5, 1.0, 1.0, 1.0, 1.5], f"{dequant=}"
26
+
27
+ quant_torch, scale_torch = downcast_to_mxfp_torch(x, torch.uint8, axis=1)
28
+ assert_equal(quant_torch, quant)
29
+ assert_equal(scale_torch, scale)
30
+
31
+ dequant_torch = upcast_from_mxfp_torch(quant_torch, scale_torch, dst_dtype, axis=1)
32
+ assert_equal(dequant_torch, dequant)
33
+
34
+
35
+ @pytest.mark.parametrize("src_dtype", ["float4_e2m1", "float8_e5m2", "float8_e4m3fn"])
36
+ @pytest.mark.parametrize("dst_dtype", ["float16", "bfloat16"])
37
+ def test_mxfp_quant_dequant(src_dtype, dst_dtype):
38
+ if "float8" in src_dtype and torch.cuda.get_device_capability()[0] < 9:
39
+ pytest.skip("Float8 not tested on A100")
40
+ limit_range = src_dtype == "float8_e5m2" and dst_dtype == "float16"
41
+
42
+ # This test checks that quantization and dequantization kernels produce the exact values for some inputs
43
+ # that can be represented exactly in the quantized format.
44
+ src_dtype = dtype_str_to_torch(src_dtype)
45
+ dst_dtype = dtype_str_to_torch(dst_dtype)
46
+ max_val = get_max_quant_val(src_dtype)
47
+ if limit_range:
48
+ # FP16 can't represent the full range of MXFP8, so we limit the max value here
49
+ max_val = 128
50
+
51
+ # These are all the valid mxfp4 positive values.
52
+ pos_vals = torch.tensor([0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, max_val], device="cuda", dtype=dst_dtype)
53
+ neg_vals = -pos_vals
54
+ k_dim = torch.cat([pos_vals, neg_vals])
55
+ k_dim = k_dim.reshape([k_dim.shape[0], 1])
56
+
57
+ # We pick power of 2 scales since both the scales and their inverse only require exponent bits to be exactly
58
+ # represented. This means we can store the scales exactly in the e8m0 format.
59
+ powers = torch.arange(-8, 8, device="cuda", dtype=dst_dtype)
60
+ scales = 2**powers
61
+ scales = scales.reshape([1, powers.shape[0]])
62
+ weight = k_dim * scales
63
+ weight = weight.repeat((9, 32)) # Repeat the dimensions to test multi block launches.
64
+ weight = weight.reshape([1, weight.shape[0], weight.shape[1]])
65
+ weight = weight.mT.contiguous().mT
66
+ quant, scale = downcast_to_mxfp(weight, src_dtype, axis=1)
67
+ dequant = upcast_from_mxfp(quant, scale, dst_dtype, axis=1)
68
+ assert_equal(weight, dequant)
69
+
70
+
71
+ # fmt: off
72
+ @pytest.mark.parametrize(
73
+ "shape, axis, quant_dtype, rounding_mode",
74
+ [
75
+ ((3, 4096, 1024), 1, "float4_e2m1", DequantScaleRoundingMode.ROUND_UP),
76
+ ((10, 254, 60), 0, "float4_e2m1", DequantScaleRoundingMode.ROUND_DOWN),
77
+ ((1, 320, 160), 2, "float8_e5m2", DequantScaleRoundingMode.ROUND_UP),
78
+ ((2, 16, 512), -1, "float8_e4m3fn", DequantScaleRoundingMode.ROUND_DOWN),
79
+ ],
80
+ )
81
+ # fmt: on
82
+ @pytest.mark.parametrize("dequant_dtype", ["float16", "bfloat16"])
83
+ def test_mxfp_casting(
84
+ shape: tuple[int, ...],
85
+ axis: int,
86
+ quant_dtype: str,
87
+ dequant_dtype: str,
88
+ rounding_mode: DequantScaleRoundingMode,
89
+ ):
90
+ if "float8" in quant_dtype and torch.cuda.get_device_capability()[0] < 9:
91
+ pytest.skip("Float8 not tested on A100")
92
+ quant_torch_type = dtype_str_to_torch(quant_dtype)
93
+ dequant_torch_type = dtype_str_to_torch(dequant_dtype)
94
+ # Generate random input tensor that is contiguous once axis is the last dimension
95
+ x = torch.randn(shape, device="cuda", dtype=dequant_torch_type)
96
+
97
+ # Quantize and check equivalence
98
+ quant, scale = downcast_to_mxfp(x, quant_torch_type, axis, DEQUANT_SCALE_ROUNDING_MODE=rounding_mode)
99
+ quant_torch, scale_torch = downcast_to_mxfp_torch(x, quant_torch_type, axis,
100
+ DEQUANT_SCALE_ROUNDING_MODE=rounding_mode)
101
+
102
+ assert_equal(quant_torch, quant)
103
+ assert_equal(scale_torch, scale)
104
+ assert_equal(1, quant.stride(axis))
105
+ assert_equal(1, quant_torch.stride(axis))
106
+
107
+ # Dequantize and check equivalence
108
+ dequant = upcast_from_mxfp(quant, scale, dequant_torch_type, axis)
109
+ dequant_torch = upcast_from_mxfp_torch(quant_torch, scale_torch, dequant_torch_type, axis)
110
+ assert_equal(dequant, dequant_torch)
111
+
112
+ # Dequantized result should be close to the original, though tolerance is large due to the precision loss.
113
+ assert_close(x, dequant, maxtol=0.5, rmstol=0.15)
tests/test_routing.py ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+ import torch
3
+ from triton_kernels.routing import routing, routing_torch
4
+ from triton_kernels.testing import assert_close
5
+ from triton_kernels.testing import assert_equal
6
+
7
+
8
+ def init_data(n_tokens, n_expts_tot, dtype=torch.float16, device="cuda"):
9
+ logits = torch.randn((n_tokens, n_expts_tot), dtype=dtype, device=device, requires_grad=True)
10
+ return logits
11
+
12
+
13
+ n_tokens = [(x, None) for x in [371, 255, 256, 4096, 1023, 1024]]
14
+ n_tokens += [(1152, 911)]
15
+
16
+
17
+ @pytest.mark.parametrize("n_tokens_pad, n_tokens_raw", n_tokens)
18
+ @pytest.mark.parametrize("n_expts_tot, n_expts_act", [(128, 32), (1500, 8)])
19
+ @pytest.mark.parametrize("use_expt_indx", [False, True])
20
+ @pytest.mark.parametrize("sm_first", [True, False])
21
+ def test_op(n_tokens_pad, n_tokens_raw, n_expts_tot, n_expts_act, sm_first, use_expt_indx, device):
22
+ torch.manual_seed(2)
23
+ if n_tokens_raw is None:
24
+ n_tokens_raw = n_tokens_pad
25
+ n_routing_rows = None
26
+ else:
27
+ n_routing_rows = torch.tensor([n_tokens_raw], dtype=torch.int32, device=device)
28
+ n_gates_raw = n_tokens_raw * n_expts_act
29
+ tri_logits = init_data(n_tokens_pad, n_expts_tot, device=device, dtype=torch.float32).detach()
30
+ tri_logits[n_tokens_raw:, :] = float("inf") # should not be used
31
+ tri_logits = tri_logits.requires_grad_(True)
32
+ ref_logits = tri_logits.clone().detach().requires_grad_(True)
33
+
34
+ if use_expt_indx:
35
+ rand_idx = lambda: torch.randperm(n_expts_tot, device="cuda", dtype=torch.int64)
36
+ tri_expt_indx = torch.stack([rand_idx()[:n_expts_act] for _ in range(n_tokens_pad)])
37
+ tri_expt_indx, _ = torch.sort(tri_expt_indx, dim=1)
38
+ tri_expt_indx[n_tokens_raw:] = -99999 # should not be used
39
+ ref_expt_indx = tri_expt_indx[:n_tokens_raw]
40
+ else:
41
+ tri_expt_indx = ref_expt_indx = None
42
+ ref_routing_data, ref_gather, ref_scatter = routing_torch(ref_logits, n_expts_act, sm_first, ref_expt_indx,
43
+ n_rows=n_routing_rows)
44
+ tri_routing_data, tri_gather, tri_scatter = routing(tri_logits, n_expts_act, sm_first, tri_expt_indx,
45
+ n_rows=n_routing_rows)
46
+
47
+ def _assert_indx_equal(ref, tri):
48
+ assert_equal(ref, tri[:len(ref)])
49
+ assert torch.all(tri[len(ref):] == -1)
50
+
51
+ assert_close(ref_routing_data.gate_scal, tri_routing_data.gate_scal[:n_gates_raw], 2e-2, 4e-3)
52
+ assert_equal(ref_routing_data.expt_hist, tri_routing_data.expt_hist)
53
+
54
+ ref_expt_data = ref_routing_data.expt_data
55
+ tri_expt_data = tri_routing_data.expt_data
56
+ assert_equal(ref_expt_data.hist, tri_expt_data.hist)
57
+ assert_equal(ref_expt_data.token_offs_raw, tri_expt_data.token_offs_raw)
58
+ assert len(ref_expt_data.token_offs_pad) == len(tri_expt_data.token_offs_pad)
59
+ assert len(ref_expt_data.block_pid_map) == len(tri_expt_data.block_pid_map)
60
+ for block_m in ref_expt_data.token_offs_pad.keys():
61
+ assert_equal(ref_expt_data.token_offs_pad[block_m], tri_expt_data.token_offs_pad[block_m])
62
+ assert_equal(ref_expt_data.block_pid_map[block_m], tri_expt_data.block_pid_map[block_m])
63
+
64
+ assert ref_routing_data.n_expts_tot == ref_routing_data.n_expts_tot
65
+ assert ref_routing_data.n_expts_act == ref_routing_data.n_expts_act
66
+
67
+ _assert_indx_equal(ref_gather.src_indx, tri_gather.src_indx)
68
+ _assert_indx_equal(ref_gather.dst_indx, tri_gather.dst_indx)
69
+ _assert_indx_equal(ref_scatter.src_indx, tri_scatter.src_indx)
70
+ _assert_indx_equal(ref_scatter.dst_indx, tri_scatter.dst_indx)
71
+
72
+ scales_grad = torch.randn_like(tri_routing_data.gate_scal)
73
+ ref_routing_data.gate_scal.backward(scales_grad[:n_gates_raw])
74
+ tri_routing_data.gate_scal.backward(scales_grad)
75
+
76
+ assert_close(ref_logits.grad[:n_tokens_raw], tri_logits.grad[:n_tokens_raw])
77
+
78
+
79
+ def bench_routing():
80
+ import triton.profiler as proton
81
+ n_tokens = 8192
82
+ n_expts_tot, n_expts_act = 128, 4
83
+ tri_logits = init_data(n_tokens, n_expts_tot)
84
+ proton.start("routing")
85
+ proton.activate()
86
+ for i in range(100):
87
+ tri_routing_data, tri_gather, tri_scatter = routing(tri_logits, n_expts_act)
88
+ proton.finalize()
89
+ try:
90
+ import os
91
+ os.system("proton-viewer -m time/ms routing.hatchet")
92
+ except Exception:
93
+ pass
94
+
95
+
96
+ if __name__ == "__main__":
97
+ bench_routing()
tests/test_specialize.py ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import importlib
3
+ from triton_kernels.specialize import cacheable, specialize
4
+ import triton
5
+ import triton.language as tl
6
+
7
+
8
+ @triton.jit
9
+ def template_kernel(o):
10
+ cst = 1.0
11
+ tl.store(o, cst)
12
+
13
+
14
+ def retrieve_fn(module, name):
15
+ module = importlib.import_module(module)
16
+ fn = getattr(module, name)
17
+ return fn
18
+
19
+
20
+ _specialized_kernel = None
21
+
22
+
23
+ def get_specialized_kernel():
24
+ global _specialized_kernel
25
+ if _specialized_kernel is not None:
26
+ return _specialized_kernel
27
+ import types
28
+ spec_constants = {}
29
+ spec_tuples = {}
30
+ module = types.ModuleType("specialized_kernel")
31
+ module.specialized = specialize(template_kernel, module, spec_constants, spec_tuples)
32
+ _specialized_kernel = module.specialized
33
+ return _specialized_kernel
34
+
35
+
36
+ @cacheable
37
+ def cacheable_kernel():
38
+ return get_specialized_kernel()
39
+
40
+
41
+ def test_cacheable(device, fresh_knobs):
42
+ specialized_kernel = get_specialized_kernel()
43
+
44
+ specialization_data = None
45
+ fn_name = None
46
+ module_name = None
47
+
48
+ def cache_hook(*args, **kwargs):
49
+ nonlocal specialization_data
50
+ nonlocal fn_name
51
+ nonlocal module_name
52
+ specialization_data = kwargs["compile"]["specialization_data"]
53
+ fn_name = kwargs["fn"].name
54
+ module_name = kwargs["fn"].module
55
+
56
+ triton.knobs.runtime.jit_cache_hook = cache_hook
57
+ o = torch.empty((1, ), dtype=torch.float32, device=device)
58
+ k = specialized_kernel[(1, )](o, )
59
+ hash = k.hash
60
+ assert o.item() == 1.0
61
+ assert module_name == "tests.test_specialize"
62
+ assert fn_name == "cacheable_kernel"
63
+
64
+ compile_count = 0
65
+
66
+ def count_hook(*args, **kwargs):
67
+ nonlocal compile_count
68
+ compile_count += 1
69
+
70
+ triton.knobs.runtime.jit_cache_hook = count_hook
71
+ # clear the cache
72
+ specialized_kernel.device_caches.clear()
73
+
74
+ # retrieve the kernel from name and preload it.
75
+ fn = retrieve_fn(module_name, fn_name)
76
+ assert fn == specialized_kernel
77
+ preload = fn.preload(specialization_data)
78
+ assert compile_count == 1
79
+ assert preload.hash == hash
80
+
81
+ # verify that we hit the cache.
82
+ compile_count = 0
83
+ specialized_kernel[(1, )](o, )
84
+ assert compile_count == 0
tests/test_swiglu.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from triton_kernels.routing import routing_torch
2
+ from triton_kernels.swiglu import swiglu, swiglu_torch, PrecisionConfig
3
+ from triton_kernels.testing import assert_close
4
+ import torch
5
+ import pytest
6
+
7
+ from .test_routing import init_data as init_routing_data
8
+
9
+ # ---------------
10
+ # initialize data
11
+ # ---------------
12
+
13
+
14
+ def alloc_rand(shape, device, dtype, requires_grad=True):
15
+ if dtype.itemsize == 1:
16
+ tmp = 2**-(torch.randint(4, 8, shape, device=device, dtype=torch.float16))
17
+ return tmp.to(dtype).requires_grad_(requires_grad)
18
+ return torch.randn(shape, device=device, dtype=dtype, requires_grad=requires_grad)
19
+
20
+
21
+ # ---------------
22
+ # unit tests
23
+ # ---------------
24
+
25
+
26
+ @pytest.mark.parametrize("M, N", [(1311, 4352)])
27
+ @pytest.mark.parametrize("limit", [1e-2, 10])
28
+ def test_op(M, N, limit, device, alpha=0.5):
29
+ torch.manual_seed(2)
30
+ # initialize expert data
31
+ n_expts_tot = 6
32
+ n_expts_act = 2
33
+ logits = init_routing_data(M, n_expts_tot).detach()
34
+ routing_data, _, _ = routing_torch(logits, n_expts_act)
35
+ n_tokens = routing_data.expt_hist.sum()
36
+
37
+ # initialize data
38
+ x = alloc_rand([n_tokens, N], device=device, dtype=torch.bfloat16)
39
+ precision_config = PrecisionConfig(limit=limit)
40
+ tri_y = swiglu(x, alpha, precision_config, routing_data)
41
+ ref_y = swiglu_torch(x, alpha, precision_config)
42
+ assert_close(tri_y, ref_y)
tests/test_tensor.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # TODO: add tests for non-layout parts of tensor class
tests/test_tensor_details/test_layout_blackwell.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+ import torch
3
+ from triton_kernels.tensor_details.layout import BlackwellMXScaleLayout
4
+
5
+ # ------------------------------------------------------------
6
+ # Torch tests
7
+ # ------------------------------------------------------------
8
+
9
+
10
+ @pytest.mark.parametrize(
11
+ "shape",
12
+ [
13
+ (3, 4096, 1024),
14
+ (10, 254, 60),
15
+ (1, 320, 160),
16
+ (2, 16, 512),
17
+ (3, 2, 36),
18
+ ],
19
+ )
20
+ def test_mxfp4_scale_roundtrip(shape):
21
+ x = torch.randint(0, 256, shape, dtype=torch.uint8, device="cuda")
22
+ layout = BlackwellMXScaleLayout(x.shape)
23
+ res = layout.unswizzle_data(layout.swizzle_data(x))
24
+ assert (res == x).all()
tests/test_tensor_details/test_layout_hopper.py ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+ from triton._internal_testing import is_cuda
3
+ from triton_kernels.tensor import wrap_torch_tensor, convert_layout, FP4
4
+ from triton_kernels.tensor_details.layout import HopperMXScaleLayout, HopperMXValueLayout
5
+ from triton_kernels.numerics_details.mxfp import downcast_to_mxfp, upcast_from_mxfp
6
+ from triton_kernels.tensor_details.layout_details.hopper_value import mxfp4_to_bf16_triton
7
+ from triton_kernels.tensor_details.layout_details.hopper_scale import unswizzle_mxfp4_scale_hopper
8
+ from triton_kernels.target_info import cuda_capability_geq
9
+ import triton.language as tl
10
+ import triton
11
+ import torch
12
+
13
+ # ------------------------------------------------------------
14
+ # Torch tests
15
+ # ------------------------------------------------------------
16
+
17
+
18
+ @pytest.mark.parametrize("shape", [(16, 32), (16, 64), (32, 32), (32, 64), (64, 128), (128, 128)])
19
+ @pytest.mark.parametrize("trans", [False, True])
20
+ @pytest.mark.parametrize("mx_axis", [0, 1])
21
+ @pytest.mark.parametrize("mma_version", [2, 3])
22
+ def test_mxfp4_value_roundtrip(shape, trans, mx_axis, mma_version):
23
+ x = torch.randint(0, 256, shape, dtype=torch.uint8, device="cuda")
24
+ if trans:
25
+ x = x.mT
26
+ if x.shape[1 - mx_axis] < 32:
27
+ pytest.skip("Not enough elements along non-mx axis")
28
+ layout = HopperMXValueLayout(x.shape, mx_axis, mma_version)
29
+ res = layout.unswizzle_data(layout.swizzle_data(x))
30
+ assert (res == x).all()
31
+
32
+
33
+ @pytest.mark.parametrize("mx_axis", [0, 1])
34
+ @pytest.mark.parametrize("num_warps", [4, 8])
35
+ @pytest.mark.parametrize("shape", [(256, 64), (256, 128), (256, 256)])
36
+ def test_mxfp4_scale_roundtrip(shape, mx_axis, num_warps):
37
+ x = torch.randint(0, 256, shape, dtype=torch.uint8, device="cuda")
38
+ layout = HopperMXScaleLayout(x.shape, mx_axis=mx_axis, num_warps=num_warps)
39
+ res = layout.unswizzle_data(layout.swizzle_data(x))
40
+ assert (res[:shape[0], :shape[1]] == x).all()
41
+
42
+
43
+ # ------------------------------------------------------------
44
+ # Triton tests
45
+ # ------------------------------------------------------------
46
+
47
+ # ------------------ upcast mxfp4 to bf16 --------------------
48
+
49
+
50
+ @triton.jit
51
+ def _upcast_mxfp4_to_bf16(Y, X, XScale, x_stride_m, x_stride_n, x_scale_stride_m, x_scale_stride_n, y_stride_m,
52
+ y_stride_n, X_BLOCK_M: tl.constexpr, X_BLOCK_N: tl.constexpr, Y_BLOCK_M: tl.constexpr,
53
+ Y_BLOCK_N: tl.constexpr, SCALE_BLOCK_M: tl.constexpr, SCALE_BLOCK_N: tl.constexpr,
54
+ mx_axis: tl.constexpr):
55
+ offs_m_val = tl.arange(0, X_BLOCK_M)
56
+ offs_n_val = tl.arange(0, X_BLOCK_N)
57
+ offs_m_scale = tl.arange(0, SCALE_BLOCK_M)
58
+ offs_n_scale = tl.arange(0, SCALE_BLOCK_N)
59
+ # load values
60
+ offs_x = offs_m_val[:, None] * x_stride_m + offs_n_val[None, :] * x_stride_n
61
+ x = tl.load(X + offs_x)
62
+ # load scales
63
+ offs_x_scale = offs_m_scale[:, None] * x_scale_stride_m + offs_n_scale[None, :] * x_scale_stride_n
64
+ x_scale = tl.load(XScale + offs_x_scale)
65
+ x_scale = unswizzle_mxfp4_scale_hopper(x_scale, mx_axis=mx_axis, num_warps=tl.extra.cuda.num_warps())
66
+ y = mxfp4_to_bf16_triton(x, x_scale, mx_axis=mx_axis)
67
+ # write back output
68
+ offs_m_val = tl.arange(0, Y_BLOCK_M)
69
+ offs_n_val = tl.arange(0, Y_BLOCK_N)
70
+ offs_y = offs_m_val[:, None] * y_stride_m + offs_n_val[None, :] * y_stride_n
71
+ tl.store(Y + offs_y, y)
72
+
73
+
74
+ @pytest.mark.skipif(not is_cuda(), reason="Only supported on cuda")
75
+ @pytest.mark.skipif(not cuda_capability_geq(9), reason="Only supported for capability >= 9")
76
+ def test_upcast_mxfp4_to_bf16():
77
+ mx_axis = 0
78
+ num_warps = 4
79
+ torch.manual_seed(0)
80
+ torch.cuda.manual_seed(0)
81
+ shape = (256, 128)
82
+ x = torch.randn(shape, dtype=torch.bfloat16, device="cuda")
83
+ x_fp4_val, x_fp4_scale = downcast_to_mxfp(x, torch.uint8, axis=mx_axis)
84
+ x_bf16 = upcast_from_mxfp(x_fp4_val, x_fp4_scale, x.dtype, axis=mx_axis)
85
+ x_fp4_val = wrap_torch_tensor(x_fp4_val, dtype=FP4)
86
+ x_fp4_scale = wrap_torch_tensor(x_fp4_scale)
87
+ x_fp4_val = convert_layout(x_fp4_val, HopperMXValueLayout, mx_axis=mx_axis)
88
+ x_fp4_scale = convert_layout(x_fp4_scale, HopperMXScaleLayout, mx_axis=mx_axis, num_warps=num_warps)
89
+ y = torch.empty_like(x_bf16)
90
+ _upcast_mxfp4_to_bf16[(1, )](
91
+ y, x_fp4_val.storage.data, x_fp4_scale.storage.data, #
92
+ x_fp4_val.storage.data.stride(0), x_fp4_val.storage.data.stride(1), #
93
+ x_fp4_scale.storage.data.stride(0), x_fp4_scale.storage.data.stride(1), #
94
+ y.stride(0), y.stride(1), #
95
+ x_fp4_val.storage.data.shape[0], x_fp4_val.storage.data.shape[1], #
96
+ shape[0], shape[1], #
97
+ x_fp4_scale.storage.data.shape[0], x_fp4_scale.storage.data.shape[1], #
98
+ mx_axis=mx_axis, num_warps=num_warps)
99
+ assert (y == x_bf16).all()
torch-ext/triton_kernels/__init__.py ADDED
File without changes
torch-ext/triton_kernels/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (165 Bytes). View file
 
torch-ext/triton_kernels/__pycache__/compaction.cpython-310.pyc ADDED
Binary file (2.2 kB). View file
 
torch-ext/triton_kernels/__pycache__/datastruct.cpython-310.pyc ADDED
Binary file (2.1 kB). View file
 
torch-ext/triton_kernels/__pycache__/matmul_ogs.cpython-310.pyc ADDED
Binary file (25.4 kB). View file
 
torch-ext/triton_kernels/__pycache__/numerics.cpython-310.pyc ADDED
Binary file (1.77 kB). View file
 
torch-ext/triton_kernels/__pycache__/routing.cpython-310.pyc ADDED
Binary file (8.44 kB). View file
 
torch-ext/triton_kernels/__pycache__/specialize.cpython-310.pyc ADDED
Binary file (4.12 kB). View file
 
torch-ext/triton_kernels/__pycache__/swiglu.cpython-310.pyc ADDED
Binary file (2.9 kB). View file
 
torch-ext/triton_kernels/__pycache__/target_info.cpython-310.pyc ADDED
Binary file (2.11 kB). View file
 
torch-ext/triton_kernels/__pycache__/topk.cpython-310.pyc ADDED
Binary file (2.89 kB). View file
 
torch-ext/triton_kernels/compaction.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from .compaction_details._masked_compaction import _masked_compaction
3
+ from .tensor import Bitmatrix
4
+
5
+
6
+ def compaction(yv, yi, bitmask, sentinel=-1):
7
+ """
8
+ Return compacted copies of *yv* and *yi* based on a per-row bitmask.
9
+
10
+ Only the elements whose index appears among the active bits of *bitmask*
11
+ are kept; the rest are replaced by *sentinel*. Kept elements preserve
12
+ their original left-to-right order.
13
+
14
+ Parameters
15
+ ----------
16
+ yv : torch.Tensor, shape (B, K)
17
+ Values tensor.
18
+ yi : torch.Tensor, shape (B, K), dtype torch.long
19
+ Integer indices (0 ≤ index < 32) associated with *yv*.
20
+ bitmask : torch.Tensor, shape (B,) **or** (B, 32)
21
+ Per-row mask of active indices. See the in-place version for details.
22
+ sentinel : int, default -1
23
+ Value written into dropped positions of the returned tensors.
24
+
25
+ Returns
26
+ -------
27
+ (yv_out, yi_out) : Tuple[torch.Tensor, torch.Tensor], each shape (B, K)
28
+ New tensors with the same dtype/device as the inputs.
29
+
30
+ """
31
+
32
+ n_rows, n_cols = yi.shape
33
+ ret_yv = torch.empty_like(yv)
34
+ ret_yi = torch.empty_like(yi)
35
+ if isinstance(bitmask, Bitmatrix):
36
+ bitmask = bitmask.storage.data
37
+
38
+ _masked_compaction[(n_rows, )](
39
+ yv, yi, bitmask, bitmask.stride(0), bitmask.stride(1), # inputs
40
+ ret_yv, ret_yi, # outputs
41
+ sentinel, # sentinel
42
+ K=n_cols # constants
43
+ )
44
+ return ret_yv, ret_yi
45
+
46
+
47
+ def compaction_torch(yv: torch.Tensor, yi: torch.Tensor, bitmask: torch.Tensor, sentinel=-1):
48
+ """
49
+ reference implementation of `masked_compact`
50
+ """
51
+ B, K = yi.shape
52
+ device = yi.device
53
+ # Expand bitmask to a boolean matrix of active bits (B, 32)
54
+ w = (1 << torch.arange(32, device=device, dtype=bitmask.dtype))
55
+ bits = (bitmask.unsqueeze(-1) & w) != 0
56
+ mask = bits.flatten(start_dim=-2) # or bits.reshape(B, -1)
57
+ # For every yi element decide whether it should be kept
58
+ keep = mask.gather(1, yi.long())
59
+ # Build a stable permutation that brings all "keep" items forward
60
+ # False→0, True→1 ==> invert so kept==0, dropped==1, then argsort
61
+ order = (~keep).to(torch.int).argsort(dim=1, stable=True)
62
+ # Re‑order tensors according to above permutation
63
+ yi_sorted = yi.gather(1, order)
64
+ yv_sorted = yv.gather(1, order)
65
+ # fill relevant positions with sentinel
66
+ keep_sorted = keep.gather(1, order)
67
+ yi_sorted[~keep_sorted] = sentinel
68
+ yv_sorted[~keep_sorted] = sentinel
69
+ return yv_sorted, yi_sorted
torch-ext/triton_kernels/compaction_details/__pycache__/_masked_compaction.cpython-310.pyc ADDED
Binary file (883 Bytes). View file
 
torch-ext/triton_kernels/compaction_details/_masked_compaction.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import triton
2
+ import triton.language as tl
3
+
4
+
5
+ @triton.jit
6
+ def _masked_compaction(Yv, Yi, BitMask, stride_bm, stride_bn, RetYv, RetYi, sentinel, K: tl.constexpr):
7
+ pid_m = tl.program_id(0)
8
+ yv = tl.load(Yv + pid_m * K + tl.arange(0, K))
9
+ yi = tl.load(Yi + pid_m * K + tl.arange(0, K))
10
+ div = yi // 32
11
+ rem = yi % 32
12
+ active_bits = (tl.load(BitMask + pid_m * stride_bm + div * stride_bn) >> rem) & 1
13
+ exc_cumsum = tl.cumsum(active_bits, 0) - active_bits
14
+ active_flags = active_bits.to(tl.int1)
15
+ rev_arange = tl.where(active_flags, 0, K - 1 - tl.arange(0, K))
16
+ write_indx = exc_cumsum + rev_arange
17
+ yv = tl.where(active_flags, yv, sentinel)
18
+ yi = tl.where(active_flags, yi, sentinel)
19
+ tl.store(RetYv + pid_m * K + write_indx, yv)
20
+ tl.store(RetYi + pid_m * K + write_indx, yi)
torch-ext/triton_kernels/matmul_ogs.py ADDED
@@ -0,0 +1,662 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # isort: off
2
+ # fmt: off
3
+ from dataclasses import dataclass
4
+ import itertools
5
+ import sys
6
+ import torch
7
+ import triton
8
+ from enum import Enum, auto
9
+ # utilities
10
+ from triton_kernels import target_info
11
+ from triton_kernels.numerics import InFlexData, OutFlexData
12
+ from triton_kernels.routing import GatherIndx, RoutingData, ScatterIndx
13
+ from triton_kernels.target_info import is_cuda
14
+ # details
15
+ from .matmul_ogs_details._matmul_ogs import _compute_writeback_idx
16
+ from .matmul_ogs_details._matmul_ogs import _matmul_ogs
17
+ from .matmul_ogs_details._p_matmul_ogs import _p_matmul_ogs, get_per_device_per_stream_alloc_fn
18
+ from .matmul_ogs_details._finalize_matmul import _finalize_matmul
19
+ from .matmul_ogs_details.opt_flags import make_opt_flags, update_opt_flags_constraints
20
+ from .numerics_details.mxfp import MXFP_BLOCK_SIZE
21
+ from .specialize import specialize
22
+ from .tensor import Storage, Tensor, FP4, bitwidth, wrap_torch_tensor
23
+
24
+
25
+ @dataclass(frozen=True)
26
+ class FnSpecs:
27
+ name: str
28
+ fn: "triton.runtime.jit.JITFunction"
29
+ fn_arg_names: tuple[str]
30
+ fn_arg_do_not_specialize: tuple[str] = tuple()
31
+
32
+ @staticmethod
33
+ def default():
34
+ return FnSpecs("dflt", None, tuple())
35
+
36
+
37
+ @dataclass(frozen=True)
38
+ class FusedActivation:
39
+ specs: FnSpecs = FnSpecs.default()
40
+ fn_args: tuple[object] = tuple()
41
+ reduction_n: int = 1
42
+
43
+
44
+ @dataclass(frozen=True)
45
+ class Epilogue:
46
+ specs: FnSpecs = FnSpecs.default()
47
+ fn_arg_values_matmul: tuple[object] = tuple()
48
+ fn_arg_values_finalize: tuple[object] = tuple()
49
+ effective_itemsize: float = None
50
+
51
+ class FnName(Enum):
52
+ DEQUANTIZE_MXFP8 = auto()
53
+
54
+
55
+ EpilogueSpecs = FnSpecs # TODO: remove this alias when callers are updated
56
+
57
+ _kernels = dict()
58
+
59
+
60
+ def get_kernels(epilogue: FnSpecs = FnSpecs.default(), fused_activation: FnSpecs = FnSpecs.default()):
61
+ global _kernels
62
+ key = (fused_activation.name, epilogue.name)
63
+ if key in _kernels:
64
+ return _kernels[key]
65
+ spec_constants = {
66
+ "ACTIVATION_FN": fused_activation.fn,
67
+ "EPILOGUE_FN": epilogue.fn,
68
+ }
69
+ spec_tuples = {
70
+ "activation_fn_args": fused_activation.fn_arg_names,
71
+ "epilogue_fn_args": epilogue.fn_arg_names,
72
+ }
73
+ do_not_specialize = fused_activation.fn_arg_do_not_specialize + epilogue.fn_arg_do_not_specialize
74
+ import types
75
+
76
+ module = types.ModuleType(f"matmul_ogs_{'_'.join(key)}")
77
+ sys.modules[module.__name__] = module
78
+ module._finalize_matmul = specialize(_finalize_matmul, module, spec_constants, spec_tuples,
79
+ do_not_specialize=do_not_specialize)
80
+ module._matmul_ogs = specialize(_matmul_ogs, module, spec_constants, spec_tuples,
81
+ do_not_specialize=do_not_specialize)
82
+ module._p_matmul_ogs = specialize(_p_matmul_ogs, module, spec_constants, spec_tuples,
83
+ do_not_specialize=do_not_specialize)
84
+ _kernels[key] = module
85
+ return module
86
+
87
+
88
+ # -----------------------------------------------------------------------------
89
+ # Matrix Multiplication + Outer Gather/Scatter
90
+ # -----------------------------------------------------------------------------
91
+
92
+
93
+ def can_overflow_int32(tensor: torch.Tensor):
94
+ max_int32 = (1 << 31) - 1
95
+ offset = 0
96
+ for i in range(tensor.ndim):
97
+ offset += (tensor.shape[i] - 1) * tensor.stride(i)
98
+ return offset > max_int32
99
+
100
+
101
+ def should_upcast_indices(*args):
102
+ return any(tensor is not None and can_overflow_int32(tensor) for tensor in args)
103
+
104
+
105
+ # ---------------------
106
+ # Numerics
107
+ # ---------------------
108
+
109
+ # fmt: off
110
+
111
+ @dataclass(frozen=True)
112
+ class FlexCtx:
113
+ lhs_data: InFlexData = InFlexData()
114
+ rhs_data: InFlexData = InFlexData()
115
+ out_data: OutFlexData = OutFlexData()
116
+
117
+ @dataclass
118
+ class PrecisionConfig:
119
+ max_num_imprecise_acc: int = None
120
+ allow_tf32: bool = True
121
+ flex_ctx: FlexCtx = FlexCtx()
122
+ acc_scale: int = 1.0
123
+ flexpoint_saturate_inf: bool = False
124
+ report_quantization_err_fn: callable = None
125
+ act_scale: Tensor | None = None
126
+ weight_scale: Tensor| None = None
127
+ out_scale: Tensor | None = None
128
+ out_dtype: torch.dtype = None
129
+ enforce_bitwise_invariance: bool = False
130
+
131
+ # ---------------------
132
+ # Preprocessing
133
+ # ---------------------
134
+
135
+ @dataclass(frozen=True)
136
+ class PreprocessingFeatures:
137
+ swap_xw: bool
138
+
139
+
140
+ def init_preprocessing_features(w, precision_config, opt_flags):
141
+ swap_xw = False # Whether or not to swap X and W operands to the tl.dot
142
+ if target_info.cuda_capability_geq(10, 0):
143
+ swap_xw = precision_config.weight_scale is not None and opt_flags.block_m <= 64 and opt_flags.is_persistent
144
+ return PreprocessingFeatures(swap_xw)
145
+
146
+ def apply_preprocessing_features(x, w, gather_indx, scatter_indx, routing_data, opt_flags, preprocessing_features):
147
+ has_fused_scatter_scratchpad = opt_flags.fused_scatter and routing_data.n_expts_act > 1
148
+ if has_fused_scatter_scratchpad:
149
+ M = scatter_indx.src_indx.shape[0]
150
+ writeback_idxs = torch.zeros((M,), dtype=torch.int32, device=x.device)
151
+ writeback_size = writeback_idxs.shape[0]
152
+ finalize_scatter_idxs = torch.zeros((M // routing_data.n_expts_act + M + 1,), dtype=torch.int32, device=x.device)
153
+ BLOCK_M=256
154
+ _compute_writeback_idx[(triton.cdiv(M, BLOCK_M),)](
155
+ writeback_idxs,
156
+ finalize_scatter_idxs,
157
+ scatter_indx.dst_indx,
158
+ scatter_indx.src_indx,
159
+ M // routing_data.n_expts_act,
160
+ M,
161
+ BLOCK_M=BLOCK_M,
162
+ N_EXPTS_ACT=routing_data.n_expts_act,
163
+ )
164
+ elif scatter_indx is not None and routing_data.n_expts_act == 1:
165
+ writeback_idxs = scatter_indx.dst_indx
166
+ writeback_size = scatter_indx.dst_indx.shape[0]
167
+ finalize_scatter_idxs = None
168
+ else:
169
+ writeback_idxs, writeback_size, finalize_scatter_idxs = None, None, None
170
+ # preprocess routing information and ptr lookup table
171
+ M = x.shape[1] if gather_indx is None else gather_indx.src_indx.shape[0]
172
+ return x, w, writeback_idxs, writeback_size, finalize_scatter_idxs
173
+
174
+
175
+ # ---------------------
176
+ # Postprocessing
177
+ # ---------------------
178
+
179
+
180
+ @dataclass(frozen=True)
181
+ class PostprocessingFeatures:
182
+ finalize: bool
183
+
184
+ def init_postprocessing_features(routing_data, scatter_indx, opt_flags):
185
+ finalize = (scatter_indx is not None and routing_data.n_expts_act > 1) or opt_flags.split_k > 1
186
+ return PostprocessingFeatures(finalize)
187
+
188
+ def apply_postprocessing_features(scatter_indx, finalize_scatter_idxs, opt_flags, expt_offs, num_indx, precision_config, routing_data,
189
+ postprocess_features, memory, fused_activation, epilogue):
190
+ out = memory["output"]
191
+ flex_ctx = precision_config.flex_ctx
192
+ if postprocess_features.finalize:
193
+ has_fused_scatter_scratchpad = opt_flags.fused_scatter and routing_data.n_expts_act > 1
194
+ if has_fused_scatter_scratchpad:
195
+ inp = memory["output"]
196
+ else:
197
+ inp = memory["scratchpad"]["matmul"]
198
+ if scatter_indx is not None:
199
+ assert inp.shape[1] == 1, "batched finalize scatter not supported"
200
+ n_final_rows = scatter_indx.src_indx.shape[0] // routing_data.n_expts_act
201
+ scatter_src_indx = scatter_indx.src_indx
202
+ EXPT_PER_TOK = routing_data.n_expts_act
203
+ num_rows = None
204
+ else:
205
+ n_final_rows = inp.shape[1] * inp.shape[2]
206
+ scatter_src_indx = None
207
+ EXPT_PER_TOK = 1
208
+ num_rows = num_indx or (None if expt_offs is None else expt_offs[-1])
209
+
210
+ if inp.dtype == torch.float32:
211
+ inp_flex = OutFlexData()
212
+ else:
213
+ inp_flex = precision_config.flex_ctx.out_data
214
+
215
+ out_scatter = memory["output"]
216
+ out_scatter_flex = precision_config.flex_ctx.out_data
217
+
218
+ N = inp.shape[3]
219
+ M = n_final_rows
220
+ warps_per_sm = 32 if target_info.is_hip() else 128
221
+
222
+ def compute_grid(BLOCK_N, num_warps):
223
+ num_pid = target_info.num_sms() * (warps_per_sm // num_warps)
224
+ if M < num_pid or target_info.is_hip():
225
+ grid_n = triton.cdiv(N, BLOCK_N)
226
+ grid_m = min(M, max(1, triton.cdiv(num_pid, grid_n)))
227
+ else:
228
+ grid_m = min(M, num_pid)
229
+ grid_n = 1
230
+ return (grid_m, grid_n)
231
+
232
+ if inp.dtype.itemsize == 1:
233
+ candidates = [(1024, 1)]
234
+ else:
235
+ if target_info.is_hip():
236
+ candidates = [(4096 // inp.dtype.itemsize, 2)]
237
+ else:
238
+ if inp.dtype.itemsize == 2:
239
+ candidates = [
240
+ (4096 // inp.dtype.itemsize, 4),
241
+ (1024 // inp.dtype.itemsize, 1),
242
+ ]
243
+ else:
244
+ candidates = [
245
+ (2048 // inp.dtype.itemsize, 4),
246
+ (1024 // inp.dtype.itemsize, 1),
247
+ ]
248
+ if precision_config.enforce_bitwise_invariance:
249
+ candidates = [candidates[0]]
250
+
251
+ # sort by smallest grid_n so we share compute across a row
252
+ grid, (BLOCK_N, num_warps) = sorted([(compute_grid(*c), c) for c in candidates], key=lambda x: x[0][1])[0]
253
+ STAGES = 1 if num_warps == 1 else min(triton.cdiv(triton.cdiv(N, BLOCK_N), grid[1]), 5)
254
+
255
+ out_scale = precision_config.out_scale
256
+ out_has_mx = out_scale is not None
257
+ out_scale_strides = (None, None) if out_scale is None else out_scale.stride()[-2:]
258
+ mx_a_scale = memory["scratchpad"].get("mx_out_scale", None)
259
+ if mx_a_scale is not None:
260
+ mx_a_scale_stride_k, mx_a_scale_stride_m = [mx_a_scale.stride(i) for i in (0, 2)]
261
+ else:
262
+ mx_a_scale_stride_k, mx_a_scale_stride_m = None, None
263
+
264
+ kernels = get_kernels(epilogue.specs, fused_activation.specs)
265
+ kernels._finalize_matmul[grid](
266
+ flex_ctx.out_data.reinterpret(out_scatter),
267
+ *((None, out_scale, None) if out_has_mx else out_scatter_flex),
268
+ *out_scale_strides,
269
+ flex_ctx.out_data.reinterpret(inp), inp.stride(0), inp.stride(2),
270
+ inp_flex.expected_scale if mx_a_scale is None else mx_a_scale,
271
+ mx_a_scale_stride_k, mx_a_scale_stride_m,
272
+ scatter_src_indx, finalize_scatter_idxs,
273
+ inp.shape[0], M, N, num_rows,
274
+ *fused_activation.fn_args, fused_activation.reduction_n,
275
+ *epilogue.fn_arg_values_finalize,
276
+ EXPT_PER_TOK=EXPT_PER_TOK,
277
+ BLOCK_N=BLOCK_N,
278
+ STAGES=STAGES,
279
+ num_warps=num_warps,
280
+ flexpoint_saturate_inf=precision_config.flexpoint_saturate_inf,
281
+ HAS_FUSED_SCRATCHPAD=has_fused_scatter_scratchpad,
282
+ )
283
+ out = out_scatter
284
+ # trim unnecessary part of output
285
+ if has_fused_scatter_scratchpad:
286
+ # Discard scratchpad part.
287
+ # This still gives a contiguous tensor, because shape[0] > 1 only when
288
+ # batch mode is enabled, in which case this is a no-op (there's no scratchpad).
289
+ out = out[:, :, :n_final_rows, :]
290
+ return out
291
+
292
+
293
+ # ---------------------
294
+ # Allocation
295
+ # ---------------------
296
+
297
+ @dataclass
298
+ class MatmulAllocation:
299
+ device: str
300
+ output: tuple[tuple[int], torch.dtype]
301
+ scratchpads: dict[str, tuple]
302
+
303
+ def init_allocation(x, w, precision_config, fused_activation, routing_data, gather_indx, scatter_indx, opt_flags,
304
+ preprocessing_features, postprocessing_features):
305
+ # ---- output ------
306
+ N = w.shape[-1]
307
+ # by default - M is number of rows in the activations
308
+ M = x.shape[-2]
309
+ # if the activations are gathered, then M is number of gather indices
310
+ if gather_indx is not None:
311
+ M = gather_indx.src_indx.shape[0]
312
+ # final output
313
+ if routing_data.n_expts_act == 1 or scatter_indx is None:
314
+ y_rows = M
315
+ elif opt_flags.fused_scatter:
316
+ # we need the scratchpad and the output to be contiguous in memory
317
+ Mc = scatter_indx.src_indx.shape[0] // routing_data.n_expts_act # compressed number of rows
318
+ y_rows = M + Mc
319
+ else:
320
+ Mc = scatter_indx.src_indx.shape[0] // routing_data.n_expts_act # compressed number of rows
321
+ y_rows = Mc
322
+ batch_dim = x.shape[0] if x.ndim == 3 else 1
323
+ y_shape = (batch_dim, y_rows, N // fused_activation.reduction_n)
324
+ out_dtype = precision_config.out_dtype or x.dtype
325
+ output = (y_shape, out_dtype)
326
+ # ---- scratchpad -----#
327
+ scratchpad = dict()
328
+ # if we need either standalone scatter or split-k, the matmul output will need post-processing
329
+ if postprocessing_features.finalize:
330
+ if opt_flags.split_k > 1 or not opt_flags.fused_scatter:
331
+ dtype = torch.float32 if opt_flags.split_k > 1 else out_dtype
332
+ scratchpad["matmul"] = ((opt_flags.split_k, 1, M, N), dtype)
333
+ if precision_config.out_scale is not None and not (scratchpad.get("matmul", None) is not None and scratchpad["matmul"][1].itemsize > 1):
334
+ scratchpad["mx_out_scale"] = ((opt_flags.split_k, 1, M, triton.cdiv(N, MXFP_BLOCK_SIZE)), torch.uint8)
335
+ return MatmulAllocation(x.device, output, scratchpad)
336
+
337
+ def apply_allocation(allocation: MatmulAllocation, output):
338
+ ret = dict()
339
+ if output is None:
340
+ output = torch.empty(allocation.output[0], device=allocation.device, dtype=allocation.output[1])
341
+ else:
342
+ assert output.shape == allocation.output[0]
343
+ ret["output"] = output[None, :, :]
344
+ ret["scratchpad"] = {
345
+ k: torch.empty(v[0], device=allocation.device, dtype=v[1])
346
+ for k, v in allocation.scratchpads.items()
347
+ }
348
+ return ret
349
+
350
+ # -----------------------------------------------------------------------------
351
+ # Canonicalize
352
+ # -----------------------------------------------------------------------------
353
+ # the `matmul_ogs` kernel can operate on 2D or 3D inputs depending on the mode being used
354
+ # we can canonicalize storages to make the implementation more uniform
355
+
356
+ def _canonicalize_storage(storage, out_ndim, flex_data):
357
+ assert out_ndim >= storage.data.ndim
358
+ new_storage_shape = [1] * (out_ndim - storage.data.ndim) + list(storage.data.shape)
359
+ new_storage_data = storage.data.view(new_storage_shape)
360
+ if flex_data is not None:
361
+ new_storage_data = flex_data.reinterpret(new_storage_data)
362
+ return Storage(new_storage_data, storage.layout)
363
+
364
+
365
+ # -----------------------------------------------------------------------------
366
+ # Triton Implementation
367
+ # -----------------------------------------------------------------------------
368
+
369
+ def matmul_ogs_set_idle_sms(num_idle_sms):
370
+ """
371
+ persistent kernels will leave `num_idle_sms` idle
372
+ """
373
+ update_opt_flags_constraints({"idle_sms": num_idle_sms})
374
+
375
+ def matmul_ogs(x, w, bias,
376
+ routing_data: RoutingData | None = None,
377
+ gather_indx: GatherIndx | None = None,
378
+ scatter_indx: ScatterIndx | None = None,
379
+ precision_config: PrecisionConfig | None = None,
380
+ betas: torch.Tensor | None = None,
381
+ gammas: torch.Tensor | None = None,
382
+ out_alpha: float | None = None,
383
+ y: torch.Tensor | None = None,
384
+ fused_activation: FusedActivation | None = None,
385
+ epilogue: Epilogue | None = None,
386
+ ):
387
+ """
388
+ Y[:, :] = 0.
389
+ for e in num_experts:
390
+ Y[idxs_y_m(e), :] += matmul(X[idxs_x_m(e), :], W[e, :, :])
391
+ """
392
+ is_input_batched = x.ndim == 3
393
+ if is_input_batched:
394
+ assert gather_indx is None, "gather not supported in batched mode"
395
+ assert scatter_indx is None, "scatter not supported in batched mode"
396
+ assert routing_data is None, "routing not supported in batched mode"
397
+ assert w.ndim == 3 and w.shape[0] == x.shape[0]
398
+ # canonicalize inputs
399
+ if precision_config is None:
400
+ precision_config = PrecisionConfig()
401
+ if fused_activation is None:
402
+ fused_activation = FusedActivation(FnSpecs.default(), tuple(), 1)
403
+ if epilogue is None:
404
+ epilogue = Epilogue(FnSpecs.default(), tuple(), tuple(), False)
405
+ if routing_data is None:
406
+ routing_data = RoutingData(None, None, max(1, w.shape[0]), 1)
407
+ # unpack scales
408
+ w_scale = precision_config.weight_scale
409
+ w_has_mx = w_scale is not None
410
+ is_hopper_fp8 = is_cuda() and not target_info.cuda_capability_geq(10, 0) and bitwidth(w.dtype) == 8
411
+ if w_has_mx: assert w.stride(-2) == 1, "`w` must be column-major when it has data-type mxfp"
412
+ if is_hopper_fp8: assert w.stride(-2) == 1, "`w` must be column-major when it has data-type FP8 on capability < 10"
413
+ if not isinstance(w, Tensor):
414
+ # TODO: remove this code path; using uint8 for mxfp4 weight will bite us when we want to support uint8 for real
415
+ dtype = FP4 if w.dtype == torch.uint8 else w.dtype
416
+ w = wrap_torch_tensor(w, dtype=dtype)
417
+ if w_scale is not None and not isinstance(w_scale, Tensor):
418
+ w_scale = Tensor(w_scale)
419
+ if w_scale is not None:
420
+ w_scale.storage.data = w_scale.data.view(torch.uint8)
421
+ w_scale.dtype = torch.uint8
422
+ x_scale = precision_config.act_scale
423
+ x_has_mx = x_scale is not None
424
+ if x_has_mx: assert x.stride(-1) == 1, "'x' must be row-major when it has data-type mxfp"
425
+ if x_scale is not None and not isinstance(x_scale, Tensor):
426
+ x_scale = Tensor(x_scale)
427
+ if not isinstance(x, Tensor):
428
+ x = Tensor(x, dtype=x.dtype)
429
+ # determine shapes
430
+ M = x.shape[-2] if gather_indx is None else gather_indx.src_indx.shape[0]
431
+ batch_size = w.shape[0] if routing_data.expt_hist is None and w.ndim == 3 else 1
432
+ K, N = w.shape[-2:]
433
+ assert K == x.shape[-1]
434
+ if x.ndim == 3 and w.ndim == 3:
435
+ assert x.shape[0] == w.shape[0]
436
+ # compute optimization flags
437
+ out_dtype = precision_config.out_dtype or x.dtype
438
+ can_use_tma = x.storage.is_tma_compliant() and \
439
+ w.storage.is_tma_compliant() and \
440
+ (w_scale is None or w_scale.storage.is_tma_compliant())
441
+ # hopper w/ mxfp4 doesn't support TMA
442
+ can_use_tma = can_use_tma and (torch.cuda.get_device_capability()[0] > 9 or bitwidth(w.dtype) != 4)
443
+ can_use_fused_scatter = scatter_indx is not None and fused_activation.specs.fn is None
444
+ opt_flags = make_opt_flags(out_dtype, x.dtype, w.dtype, precision_config,
445
+ M, N, K, routing_data, can_use_tma, can_use_fused_scatter, epilogue.effective_itemsize,
446
+ )
447
+ if w_scale is not None and opt_flags.is_persistent and not target_info.has_native_mxfp():
448
+ raise NotImplementedError("Must use non-persistent kernel for simulated MXFP")
449
+ if w_scale is not None and w_scale.storage.layout.name is not None and not opt_flags.is_persistent and target_info.has_native_mxfp():
450
+ raise NotImplementedError("Must use persistent kernel and be TMA-compliant for native MXFP")
451
+ # determine necessary pre/post processing
452
+ preprocessing_features = init_preprocessing_features(w, precision_config, opt_flags)
453
+ postprocessing_features = init_postprocessing_features(routing_data, scatter_indx, opt_flags)
454
+ # allocate output/scratchpad memory
455
+ allocation = init_allocation(x, w, precision_config, fused_activation,
456
+ routing_data, gather_indx, scatter_indx,
457
+ opt_flags, preprocessing_features, postprocessing_features
458
+ )
459
+ memory = apply_allocation(allocation, y)
460
+ # TMA descriptors require a global memory allocation
461
+ if opt_flags.is_persistent:
462
+ triton.set_allocator(get_per_device_per_stream_alloc_fn(x.device))
463
+ # Intermediate tensors and postprocess kernels for each situation
464
+ out0, out0_flex = memory["output"], precision_config.flex_ctx.out_data
465
+ fused_postprocess_activation = FusedActivation(FnSpecs.default(), tuple(), 1)
466
+ out_scale = None if precision_config.out_scale is None else precision_config.out_scale.data.view(torch.uint8)
467
+ if postprocessing_features.finalize:
468
+ if opt_flags.fused_scatter:
469
+ out0 = memory["output"]
470
+ else:
471
+ out0 = memory["scratchpad"]["matmul"]
472
+ if "mx_out_scale" in memory["scratchpad"]:
473
+ assert out_scale is not None
474
+ out_scale = memory["scratchpad"]["mx_out_scale"]
475
+ out0_flex = OutFlexData() if out0.dtype == torch.float32 else precision_config.flex_ctx.out_data
476
+
477
+ fused_activation, fused_postprocess_activation = fused_postprocess_activation, fused_activation
478
+ out_has_mx = out_scale is not None and out0.element_size() == 1
479
+ if out_has_mx:
480
+ if isinstance(out_scale, Tensor):
481
+ out_scale = Tensor(out_scale)
482
+ else:
483
+ out_scale = None
484
+ # pre-processing
485
+ x, w, writeback_idxs, writeback_size, finalize_scatter_idxs = apply_preprocessing_features(
486
+ x, w, gather_indx, scatter_indx, routing_data, opt_flags, preprocessing_features
487
+ )
488
+ # matrix multiplication
489
+ flex = precision_config.flex_ctx
490
+ bias_stride = None if bias is None else bias.stride(0)
491
+ num_indx = None if scatter_indx is None else scatter_indx.src_indx.shape[0]
492
+ # moe metadata
493
+ expt_data = routing_data.expt_data
494
+ block_m = opt_flags.block_m
495
+ expt_hist = None if expt_data is None else expt_data.hist
496
+ expt_hist_sum = None if expt_data is None else expt_data.token_offs_pad[block_m][-1]
497
+ expt_token_offs_raw = None if expt_data is None else expt_data.token_offs_raw
498
+ expt_block_pid_map = None if expt_data is None else expt_data.block_pid_map[block_m]
499
+ # spmd grid
500
+ grid_m = triton.cdiv(M, opt_flags.block_m)
501
+ if expt_block_pid_map is not None:
502
+ grid_m = routing_data.n_blocks(M, opt_flags.block_m)
503
+ grid_n = triton.cdiv(N, opt_flags.block_n)
504
+ max_grid = batch_size * grid_m * grid_n * opt_flags.split_k
505
+ grid = min(target_info.num_sms() - opt_flags.idle_sms, max_grid) if opt_flags.is_persistent else max_grid
506
+ # canonicalize storage
507
+ has_gather = gather_indx is not None
508
+ x_storage = _canonicalize_storage(x.storage, 2 if has_gather else 3, flex.lhs_data)
509
+ w_storage = _canonicalize_storage(w.storage, 3, flex.rhs_data)
510
+ # create tma descriptor for x
511
+ x_has_tma = ((not has_gather) or (has_gather and target_info.has_tma_gather())) and opt_flags.is_persistent
512
+ x_block_tma = ([1] if has_gather else [1, opt_flags.block_m]) + [opt_flags.block_k]
513
+ x_tensor_or_tma = x_storage.make_tma(x_block_tma) if x_has_tma else x_storage.data
514
+ # create tma descriptor for w
515
+ w_has_tma = opt_flags.is_persistent
516
+ w_tensor_or_tma = w_storage.make_tma([1, opt_flags.block_k, opt_flags.block_n]) if w_has_tma else w_storage.data
517
+ # create tma descriptor for w_scale
518
+ w_scale_tensor_or_tma = w_scale
519
+ w_scale_has_tma = opt_flags.is_persistent and w_scale is not None
520
+ w_scale_tensor_or_tma = w_scale.storage.make_tma([opt_flags.block_n, opt_flags.block_k]) if w_scale_has_tma else w_scale
521
+ # canonicalize strides
522
+ x_strides = [0]*(3 - x_storage.data.ndim) + list(x_storage.data.stride())
523
+ x_scale_strides = x_scale.stride() if x_has_mx else (None, None, None)
524
+ x_scale_strides = (0, ) * (3 - len(x_scale_strides)) + x_scale_strides
525
+ w_scale_strides = w_scale.stride() if w_has_mx and not w_scale_has_tma else (None, None, None)
526
+ w_scale_strides = (0, ) * (3 - len(w_scale_strides)) + w_scale_strides
527
+ out_scale_strides = out_scale.stride() if out_has_mx else (None, None, None, None)
528
+ out_scale_strides = (0, ) * (3 - len(out_scale_strides)) + out_scale_strides
529
+ # launch kernel
530
+ kernels = get_kernels(epilogue.specs, fused_activation.specs)
531
+ (kernels._p_matmul_ogs if opt_flags.is_persistent else kernels._matmul_ogs)[(grid,)](
532
+ flex.out_data.reinterpret(memory["output"]),
533
+ flex.out_data.reinterpret(out0), *out0.stride(),
534
+ *((None, out_scale, None) if out_has_mx else out0_flex),
535
+ *out_scale_strides[-3:],
536
+ x_tensor_or_tma, x_storage.data, *x_strides,
537
+ flex.lhs_data.scale,
538
+ None if x_scale is None else x_scale.data.view(torch.uint8), *x_scale_strides,
539
+ w_tensor_or_tma, *w_storage.data.stride(), w_storage.data.stride()[-1] != 1,
540
+ flex.rhs_data.scale,
541
+ w_scale_tensor_or_tma, *w_scale_strides,
542
+ bias, bias_stride,
543
+ x.shape[-2],
544
+ x.shape[-2] if routing_data.expt_hist is None else None,
545
+ N, K,
546
+ betas, gammas,
547
+ None if gather_indx is None else gather_indx.src_indx,
548
+ None if scatter_indx is None else scatter_indx.src_indx,
549
+ num_indx,
550
+ writeback_idxs, writeback_size,
551
+ expt_hist, expt_token_offs_raw, expt_hist_sum, expt_block_pid_map,
552
+ batch_size, grid_m, grid_n,
553
+ out_alpha,
554
+ *fused_activation.fn_args, fused_activation.reduction_n,
555
+ *epilogue.fn_arg_values_matmul,
556
+ routing_data.n_expts_tot, routing_data.n_expts_act,
557
+ precision_config.max_num_imprecise_acc,
558
+ precision_config.allow_tf32,
559
+ precision_config.flexpoint_saturate_inf,
560
+ flex.rhs_data.is_per_batch,
561
+ opt_flags.block_m,
562
+ opt_flags.block_n,
563
+ opt_flags.block_k,
564
+ opt_flags.group_m,
565
+ XCD_SWIZZLE=opt_flags.xcd_swizzle,
566
+ SWIZZLE_MX_VALUE=w.storage.layout.name,
567
+ SWIZZLE_MX_SCALE=None if w_scale is None else w_scale.storage.layout.name,
568
+ EPILOGUE_SUBTILE=opt_flags.epilogue_subtile,
569
+ SPLIT_K=opt_flags.split_k,
570
+ EVEN_K=K % opt_flags.block_k == 0,
571
+ W_CACHE_MODIFIER=opt_flags.w_cache_modifier,
572
+ TOKENS_PER_EXPT_FOR_ANNOTATION=routing_data.expected_tokens_per_expt,
573
+ num_warps=opt_flags.num_warps,
574
+ num_stages=opt_flags.num_stages,
575
+ arch=opt_flags.arch,
576
+ UPCAST_INDICES=should_upcast_indices(x, w, out0),
577
+ DISABLE_Y_TMA=out0.stride(-2) * out0.dtype.itemsize % 16 != 0,
578
+ SWAP_XW=preprocessing_features.swap_xw,
579
+ IS_EPILOGUE_DEQUANT_MXFP8=epilogue.specs.name == FnName.DEQUANTIZE_MXFP8.name,
580
+ NUM_SMS = grid if opt_flags.is_persistent else 0,
581
+ **opt_flags.target_kernel_kwargs)
582
+ # post-processing
583
+ out = apply_postprocessing_features(scatter_indx, finalize_scatter_idxs, opt_flags, expt_token_offs_raw,
584
+ num_indx, precision_config, routing_data,
585
+ postprocessing_features, memory, fused_postprocess_activation, epilogue)
586
+ # remove split-k
587
+ out = out.squeeze(0)
588
+ if not is_input_batched:
589
+ out = out.view(out.shape[-2], out.shape[-1])
590
+ return out
591
+
592
+
593
+ # -----------------------------------------------------------------------------
594
+ # Reference Implementation
595
+ # -----------------------------------------------------------------------------
596
+
597
+ def matmul_ogs_torch(x, w, bias,
598
+ routing_data: RoutingData = None,
599
+ gather_indx: GatherIndx = None,
600
+ scatter_indx: ScatterIndx = None,
601
+ precision_config: PrecisionConfig = None,
602
+ betas = None,
603
+ gammas = None,
604
+ round_x = None, round_y = None,
605
+ ):
606
+ is_input_batched = x.ndim == 3
607
+ assert x.dtype.itemsize > 1
608
+ assert w.dtype.itemsize > 1
609
+ if is_input_batched:
610
+ assert gather_indx is None, "gather not supported in batched mode"
611
+ assert scatter_indx is None, "scatter not supported in batched mode"
612
+ assert routing_data is None, "routing not supported in batched mode"
613
+ assert w.ndim == 3 and w.shape[0] == x.shape[0]
614
+ if round_x is None:
615
+ round_x = lambda x: x
616
+ if round_y is None:
617
+ round_y = lambda x: x
618
+ if bias.ndim == 1:
619
+ bias = bias.view(1, *bias.shape)
620
+ if w.ndim == 2:
621
+ w = w.view(1, *w.shape)
622
+ if x.ndim == 2:
623
+ x = x.view(1, *x.shape)
624
+ if routing_data is None:
625
+ routing_data = RoutingData(None, None, w.shape[0], 1)
626
+ n_expts_act = routing_data.n_expts_act
627
+ # memory offsets
628
+ if routing_data.n_expts_tot > 1 and not is_input_batched:
629
+ sizes = routing_data.expt_hist
630
+ off = torch.zeros(sizes.shape[0] + 1, dtype=torch.int32)
631
+ off[1:] = torch.cumsum(sizes, 0)
632
+ offs = list(itertools.pairwise(off))
633
+ else:
634
+ offs = [[0, x.shape[1]] for _ in range(w.shape[0])]
635
+ # compute
636
+ n_rows = x.shape[1] if gather_indx is None else gather_indx.dst_indx.shape[0]
637
+ y = torch.zeros((x.shape[0], n_rows, w.shape[-1]), device=x.device, dtype=x.dtype)
638
+ for i, (lo, hi) in enumerate(offs):
639
+ if gather_indx is None:
640
+ idx = torch.arange(lo, hi, device=x.device)
641
+ else:
642
+ idx = gather_indx.src_indx[lo:hi] // n_expts_act
643
+ batch = i if is_input_batched else 0
644
+ out = torch.matmul(round_x(x[batch, idx, :], torch.arange(lo, hi, device="cuda")).float(),
645
+ w[i].float())
646
+ if bias is not None:
647
+ out += bias[i, :] if betas is None else bias[i, :] * betas[lo:hi, None]
648
+ if gammas is not None:
649
+ out *= gammas[lo:hi, None]
650
+ y[batch, lo:hi, :] = round_y(out)
651
+ if not is_input_batched:
652
+ y = y.view(y.shape[1], y.shape[2])
653
+ if scatter_indx is None:
654
+ return y
655
+ # accumulate output from all experts
656
+ n_rows = y.shape[0] // n_expts_act
657
+ out = torch.zeros((n_rows, y.shape[-1]), dtype=torch.float32, device=x.device)
658
+ for i, (lo, hi) in enumerate(offs):
659
+ dst_idx = scatter_indx.dst_indx[lo:hi] // n_expts_act
660
+ msk = dst_idx != -1
661
+ out[dst_idx[msk], :] += y[lo:hi, :][msk, :].float()
662
+ return out
torch-ext/triton_kernels/matmul_ogs_details/__pycache__/_common.cpython-310.pyc ADDED
Binary file (5.09 kB). View file
 
torch-ext/triton_kernels/matmul_ogs_details/__pycache__/_finalize_matmul.cpython-310.pyc ADDED
Binary file (8.89 kB). View file
 
torch-ext/triton_kernels/matmul_ogs_details/__pycache__/_matmul_ogs.cpython-310.pyc ADDED
Binary file (9.11 kB). View file
 
torch-ext/triton_kernels/matmul_ogs_details/__pycache__/_p_matmul_ogs.cpython-310.pyc ADDED
Binary file (12.4 kB). View file
 
torch-ext/triton_kernels/matmul_ogs_details/__pycache__/_weight_transpose.cpython-310.pyc ADDED
Binary file (1.25 kB). View file
 
torch-ext/triton_kernels/matmul_ogs_details/__pycache__/fast_contiguous.cpython-310.pyc ADDED
Binary file (1.2 kB). View file
 
torch-ext/triton_kernels/matmul_ogs_details/__pycache__/opt_flags.cpython-310.pyc ADDED
Binary file (6.38 kB). View file
 
torch-ext/triton_kernels/matmul_ogs_details/__pycache__/opt_flags_amd.cpython-310.pyc ADDED
Binary file (921 Bytes). View file
 
torch-ext/triton_kernels/matmul_ogs_details/__pycache__/opt_flags_nvidia.cpython-310.pyc ADDED
Binary file (2.63 kB). View file
 
torch-ext/triton_kernels/matmul_ogs_details/_common.py ADDED
@@ -0,0 +1,165 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+
3
+ import triton
4
+ import triton.language as tl
5
+ from triton.tools.tensor_descriptor import TensorDescriptor
6
+
7
+ # -----------------------------------------------------------------------------
8
+ # Utilities
9
+ # -----------------------------------------------------------------------------
10
+
11
+
12
+ @tl.constexpr_function
13
+ def get_scaled_dot_format_string(dtype: tl.dtype):
14
+ mapping = {
15
+ tl.float16: "fp16",
16
+ tl.bfloat16: "bf16",
17
+ tl.uint8: "e2m1",
18
+ tl.float8e4nv: "e4m3",
19
+ tl.float8e5: "e5m2",
20
+ }
21
+ return mapping[dtype]
22
+
23
+
24
+ @triton.jit
25
+ def xcd_swizzle(pid, domain_size, XCD_SWIZZLE: tl.constexpr):
26
+ """
27
+ Swizzle the program id based on integer XCD_SWIZZLE.
28
+ This is useful for reording how blocks are ordered. A scheduler may, for example,
29
+ assign sequential blocks 0, 1, 2, 3, ..., 8, 9, 10.. to its 8 hardware units 0, 1, 2, 3, ..., 0, 1, 2.
30
+ This pattern may not be ideal for memory access, and it may be better to swizzle so the assignment
31
+ becomes 0, 0, 0, 0, ..., 1, 1, 1, ... In the swizzled arrangement, sequential blocks are assigned to
32
+ the same hardware unit.
33
+ """
34
+ # Number of pids per group in the new arrangement
35
+ pids_per_group = domain_size // XCD_SWIZZLE
36
+ extra_pid_groups = domain_size % XCD_SWIZZLE
37
+
38
+ # Compute current current and local pid within the group
39
+ group = pid % XCD_SWIZZLE
40
+ local_pid = pid // XCD_SWIZZLE
41
+
42
+ # Calculate new pid based on the new grouping
43
+ new_pid = group * pids_per_group + min(group, extra_pid_groups) + local_pid
44
+ return new_pid
45
+
46
+
47
+ @triton.jit
48
+ def swizzle2d(pid, grid_m, grid_n, GROUP_M: tl.constexpr):
49
+ width = GROUP_M * grid_n
50
+ group_id = pid // width
51
+ group_size = min(grid_m - group_id * GROUP_M, GROUP_M)
52
+ pid_m = group_id * GROUP_M + (pid % group_size)
53
+ pid_n = (pid % width) // (group_size)
54
+ return pid_m, pid_n
55
+
56
+
57
+ def make_matmul_repr(base_name, order):
58
+
59
+ def matmul_repr(specialization):
60
+ signature = specialization.signature
61
+ constants = specialization.constants
62
+ reorder = lambda L: [L[i] for i in order]
63
+ layout = lambda stride: "N" if stride in constants else "T"
64
+
65
+ def convert_dtype(dtype):
66
+ if "tensordesc" in dtype:
67
+ ret = convert_dtype(dtype.split("<")[1].split("[")[0])
68
+ return ret
69
+ elif "u8" in dtype:
70
+ return "mxfp4"
71
+ elif dtype[0] == "*":
72
+ return dtype[1:]
73
+ else:
74
+ return dtype
75
+
76
+ dtypes = "x".join([convert_dtype(f"{signature[i]}") for i in reorder(["Y", "X", "W"])])
77
+ layouts = "".join([f"{layout(i)}" for i in reorder(["stride_y_n", "stride_x_k", "stride_w_n"])])
78
+ blocks = "x".join([f"{constants[i]}" for i in ["BLOCK_M", "BLOCK_N", "BLOCK_K", "SPLIT_K"]])
79
+ # mode = []
80
+ # if "GatherIndx" not in constants:
81
+ # mode += ['g']
82
+ # if "ScatterSrcIndx" not in constants:
83
+ # mode += ['s']
84
+ # suffix = "" if not mode else "_o" + (''.join(mode))
85
+ # if base_name.startswith("_p"):
86
+ # suffix += "_ptma"
87
+ return f"{base_name}_{layouts}_{dtypes}_{blocks}"
88
+
89
+ return matmul_repr
90
+
91
+
92
+ def matmul_launch_metadata(grid, kernel, args):
93
+ from ..proton_opts import launch_metadata_allow_sync
94
+
95
+ ret = dict()
96
+ M, N, K = args["M"], args["N"], args["K"]
97
+ Y, X, W = [t.base if isinstance(t, TensorDescriptor) else t for t in [args["Y"], args["X"], args["W"]]]
98
+ tokens_per_expt = args.get("TOKENS_PER_EXPT_FOR_ANNOTATION")
99
+ hist = args["ExptHist"]
100
+ if hist is not None:
101
+ # If annotation is given, use that to generate name for profiling.
102
+ if tokens_per_expt is not None:
103
+ n_rows = f"{tokens_per_expt}*"
104
+ elif launch_metadata_allow_sync():
105
+ n_rows = int(hist.float().mean())
106
+ else:
107
+ n_rows = "unknown"
108
+
109
+ if launch_metadata_allow_sync():
110
+ n_tokens = float(hist.sum())
111
+ n_w_bytes = (W.numel() * W.element_size() // hist.numel()) * (hist > 0).sum()
112
+ elif tokens_per_expt is not None:
113
+ n_tokens = tokens_per_expt * args["N_EXPTS_TOT"]
114
+ # This may not be totally correct (e.g., we might not be using all experts)
115
+ # but it's better than nothing.
116
+ n_w_bytes = W.numel() * W.element_size()
117
+ else:
118
+ n_tokens = None
119
+ n_w_bytes = 0
120
+
121
+ # If annotation is given, use that to generate name for profiling.
122
+ tokens_per_expt = args.get("TOKENS_PER_EXPT_FOR_ANNOTATION")
123
+ n_rows = f"{tokens_per_expt}*" if tokens_per_expt is not None else n_rows
124
+ else:
125
+ n_tokens = None
126
+ n_w_bytes = W.numel() * W.element_size()
127
+ repr = lambda s, x: f"{s} = {x}" if x is not None else f"E_{len(hist)}({s}) = {n_rows}"
128
+ nbits = X.dtype.itemsize * 8
129
+ batch_repr = ""
130
+ if "batch_size" in args and args["batch_size"] > 1:
131
+ batch_repr = repr("B", args["batch_size"]) + ", "
132
+ ret["name"] = f"{kernel.name} [{batch_repr}{repr('M', M)}, {repr('N', N)}, {repr('K', K)}] stg{kernel.num_stages}"
133
+ ep_subtile = args["EPILOGUE_SUBTILE"]
134
+ if ep_subtile is not None and ep_subtile > 1:
135
+ ret["name"] += f" ep/{ep_subtile}"
136
+
137
+ if hist is not None and n_tokens is None:
138
+ return ret # Don't fill metadata because we can't compute them properly.
139
+
140
+ fM = M if M is not None else n_tokens
141
+ fK = K if K is not None else n_tokens
142
+ ret[f"flops{nbits}"] = 2.0 * fM * N * fK
143
+
144
+ gindx = args.get("GatherIndx", None)
145
+ # sindx = args.get("WriteBackIndx", None)
146
+ n_x_bytes = X.numel() * X.element_size()
147
+ n_y_bytes = Y.numel() * Y.element_size()
148
+ if hist is not None:
149
+ assert n_tokens is not None
150
+ n_expts_act = args["N_EXPTS_ACT"]
151
+
152
+ if (gindx is not None) and launch_metadata_allow_sync():
153
+ # recreate inverse GatherIndx.
154
+ dst = torch.full_like(gindx, -1)
155
+ idx = torch.arange(len(gindx), device=gindx.device, dtype=torch.int32)
156
+ mask = (gindx != -1)
157
+ dst[gindx[mask]] = idx[mask]
158
+ n_read_rows = (dst.view((-1, n_expts_act)) != -1).any(dim=1).sum()
159
+ else:
160
+ n_read_rows = n_tokens
161
+ n_x_bytes = n_read_rows * X.shape[-1] * X.element_size()
162
+ n_y_bytes = n_tokens * Y.shape[-1] * Y.element_size()
163
+ ret["bytes"] = int(n_x_bytes + n_y_bytes + n_w_bytes)
164
+
165
+ return ret
torch-ext/triton_kernels/matmul_ogs_details/_finalize_matmul.py ADDED
@@ -0,0 +1,377 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import triton
2
+ import triton.language as tl
3
+ from triton_kernels.numerics_details.flexpoint import float_to_flex, load_scale, update_scale
4
+ from triton_kernels.numerics_details.mxfp_details._downcast_to_mxfp import MXFP_BLOCK_SIZE
5
+ from triton_kernels.target_info import cuda_capability_geq as _cuda_capability_geq
6
+ from triton_kernels.target_info import is_hip as _is_hip
7
+
8
+
9
+ # fmt: off
10
+ @tl.constexpr_function
11
+ def is_hip():
12
+ return _is_hip()
13
+
14
+
15
+ @tl.constexpr_function
16
+ def cuda_capability_geq(x, y):
17
+ return _cuda_capability_geq(x, y)
18
+
19
+
20
+ @tl.constexpr_function
21
+ def log2(n):
22
+ return len(bin(n)) - 3
23
+
24
+
25
+ @tl.constexpr_function
26
+ def _permute_to_end_order(n: int, axis: int):
27
+ """
28
+ Returns the order of the axes of a tensor to permute `axis` to the end.
29
+ """
30
+ order = tuple(range(n))
31
+ return order[:axis] + order[(axis + 1):] + (axis, )
32
+
33
+
34
+ @triton.jit
35
+ def permute_to_end(x, axis: tl.constexpr):
36
+ """
37
+ Permutes `x` so that `axis` is the last axis.
38
+ """
39
+ N: tl.constexpr = len(x.shape)
40
+ return tl.permute(x, _permute_to_end_order(N, axis).value)
41
+
42
+
43
+ @triton.jit
44
+ def split_n(x, N: tl.constexpr):
45
+ """
46
+ Given `x`, a tensor of shape AxB...x2x2...x2, split it N times.
47
+ Return a tuple of the results.
48
+ """
49
+ xs = (x, )
50
+ for i in tl.static_range(N):
51
+ next = tl.split(xs[0])
52
+ for j in tl.static_range(2**i - 1):
53
+ next = next + tl.split(xs[j + 1])
54
+ xs = next
55
+ return xs
56
+
57
+
58
+ @triton.jit
59
+ def thread_local_absmax(x, BLOCK_SIZE: tl.constexpr = None, NUM_THREADS: tl.constexpr = None):
60
+ N: tl.constexpr = tl.extra.cuda.num_threads() if NUM_THREADS is None else NUM_THREADS
61
+ BS: tl.constexpr = x.numel if BLOCK_SIZE is None else BLOCK_SIZE
62
+ tl.static_assert(BS % N == 0, "BLOCK_SIZE must be divisible by NUM_THREADS")
63
+ return tl.max(tl.reshape(tl.abs(x), [N, BS // N], can_reorder=True), axis=1)
64
+
65
+
66
+ def _finalize_matmul_launch_metadata(grid, kernel, args):
67
+ ret = dict()
68
+ Out, A, ScatterSrcIndx, FinalizeScatterIdxs, K, M, N, EXPT_PER_TOK, NumRows = [
69
+ args[name]
70
+ for name in ["Out", "A", "ScatterSrcIndx", "FinalizeScatterIdxs", "K", "M", "N", "EXPT_PER_TOK", "NumRows"]
71
+ ]
72
+ ret["name"] = f"{kernel.name} [M={M}x{EXPT_PER_TOK} {N=} {K=}]"
73
+
74
+ if FinalizeScatterIdxs is not None:
75
+ M = FinalizeScatterIdxs[-1].item()
76
+
77
+ if ScatterSrcIndx is not None:
78
+ is_active = (ScatterSrcIndx != -1).view((-1, EXPT_PER_TOK))
79
+ n_active = is_active.sum(dim=1)
80
+ need_accum = n_active >= (1 if K > 1 else 2)
81
+ is_active &= need_accum[:, None]
82
+ active_input_rows = is_active.sum()
83
+ active_output_rows = need_accum.sum()
84
+ if EXPT_PER_TOK > 1:
85
+ # Masked rows are set to zero.
86
+ active_output_rows += (n_active == 0).sum()
87
+ else:
88
+ if NumRows is not None:
89
+ if isinstance(NumRows, int):
90
+ active_input_rows = NumRows
91
+ else:
92
+ active_input_rows = NumRows.item()
93
+ else:
94
+ active_input_rows = M
95
+ active_output_rows = M
96
+
97
+ ret["bytes"] = (active_input_rows * K * A.shape[-1] * A.element_size() +
98
+ active_output_rows * Out.shape[-1] * Out.element_size())
99
+ if FinalizeScatterIdxs is not None:
100
+ ret["bytes"] += FinalizeScatterIdxs.numel() * FinalizeScatterIdxs.element_size()
101
+ elif ScatterSrcIndx is not None and EXPT_PER_TOK > 1:
102
+ ret["bytes"] += ScatterSrcIndx.numel() * ScatterSrcIndx.element_size()
103
+ nbits = Out.dtype.itemsize * 8
104
+ ret[f"flops{nbits}"] = active_input_rows * K * A.shape[-1]
105
+ return ret
106
+
107
+
108
+ @tl.constexpr_function
109
+ def _accumulate_f16_into_f32_and_track_absmax_ptx(n_inputs: int, src_type: str, absmax_reg_name: str | None):
110
+ """
111
+ Generate PTX code to take fp16 inputs and sum them into an f32 accumulator using mixed-precision
112
+ adds. If `absmax_reg_name` is provided, the absolute maximum value seen so far is tracked inside
113
+ that register.
114
+
115
+ Generates code something like:
116
+
117
+ add.f32.f16 $0, $2, $1;
118
+ add.f32.f16 $0, $3, $0;
119
+ add.f32.f16 $0, $4, $0;
120
+ add.f32.f16 $0, $5, $0;
121
+
122
+ .reg .f32 b;
123
+ abs.f32 b, $0;
124
+ max.f32 my_abs_max, my_abs_max, b;
125
+ """
126
+ # Add the first f16 value to the input $1, store into the output $0.
127
+ ptx = f"\nadd.f32.{src_type} $0, $2, $1;"
128
+ # Accumulate the rest of the inputs into the output $0.
129
+ for i in range(1, n_inputs):
130
+ ptx += f"\nadd.f32.{src_type} $0, ${2 + i}, $0;"
131
+ if absmax_reg_name is not None:
132
+ # Update `absmax_reg_name` with the absolute maximum value seen so far.
133
+ ptx += f"""
134
+ .reg .f32 b;
135
+ abs.f32 b, $0;
136
+ max.f32 {absmax_reg_name}, {absmax_reg_name}, b;
137
+ """
138
+ # Return the PTX snippet, brace-enclosed so we don't pollute the global namespace.
139
+ return f"{{{ptx}}}"
140
+
141
+
142
+ @triton.jit
143
+ def _mixed_precision_accumulate_and_track_absmax(acc, x, axis: tl.constexpr, absmax_reg_name: tl.constexpr = None):
144
+ """Given an fp8/bf16/fp16 tensor, accumulate into `acc` along `axis`.
145
+ Values are first converted to bf16/fp16, packed into 32-bit registers, and then accumulated using
146
+ mixed-precision adds.
147
+
148
+ If `absmax_reg_name` is provided, the absolute maximum value seen so far is tracked inside that
149
+ register.
150
+ """
151
+ REDUCTION_SIZE: tl.constexpr = x.shape[axis]
152
+ tl.static_assert(2**log2(REDUCTION_SIZE) == REDUCTION_SIZE,
153
+ f"Reduction size must be a power of 2, was {REDUCTION_SIZE}")
154
+ # move `axis` to the last axis and reshape for iterative splitting.
155
+ x = permute_to_end(x, axis)
156
+ x = tl.reshape(x, x.shape[:-1] + (2, ) * log2(REDUCTION_SIZE))
157
+ # Split into a tuple of AxB tensors.
158
+ xs = split_n(x, log2(REDUCTION_SIZE))
159
+ if (tl.constexpr(x.dtype == tl.float8e4nv) or tl.constexpr(x.dtype == tl.float8e5)):
160
+ # Convert fp8 to fp16.
161
+ fp16_xs = ()
162
+ for i in tl.static_range(len(xs)):
163
+ fp16_xs += (xs[i].to(tl.float16), )
164
+ xs = fp16_xs
165
+ src_type: tl.constexpr = "f16"
166
+ elif x.dtype == tl.float16:
167
+ src_type: tl.constexpr = "f16"
168
+ elif x.dtype == tl.bfloat16:
169
+ src_type: tl.constexpr = "bf16"
170
+ else:
171
+ tl.static_assert(False, f"Unsupported dtype: {x.dtype}")
172
+ return tl.inline_asm_elementwise(
173
+ _accumulate_f16_into_f32_and_track_absmax_ptx(REDUCTION_SIZE, src_type, absmax_reg_name),
174
+ "=r,r" + (",h" * len(xs)),
175
+ (acc, ) + xs,
176
+ dtype=tl.float32,
177
+ is_pure=True,
178
+ pack=1,
179
+ )
180
+
181
+
182
+ def _finalize_matmul_repr(specialization):
183
+ signature = specialization.signature
184
+ suffix = "" if "ScatterSrcIndx" in specialization.constants else "_scatter"
185
+ return f"_finalize_matmul{suffix}_{signature['A'][1:]}"
186
+
187
+
188
+ @triton.jit(repr=_finalize_matmul_repr, launch_metadata=_finalize_matmul_launch_metadata)
189
+ def _finalize_matmul(
190
+ Out,
191
+ OutExpectedScale,
192
+ OutActualScale,
193
+ OutChecksumScale,
194
+ stride_out_mx_m, stride_out_mx_n,
195
+ A,
196
+ stride_a_k,
197
+ stride_a_m,
198
+ AScale,
199
+ stride_a_mx_k,
200
+ stride_a_mx_m,
201
+ ScatterSrcIndx,
202
+ FinalizeScatterIdxs,
203
+ K: tl.constexpr,
204
+ M,
205
+ N,
206
+ NumRows,
207
+ # fused activation function
208
+ ACTIVATION_FN: tl.constexpr,
209
+ activation_fn_args,
210
+ ACTIVATION_REDUCTION_N: tl.constexpr,
211
+ # epilogue transform
212
+ EPILOGUE_FN: tl.constexpr,
213
+ epilogue_fn_args,
214
+ EXPT_PER_TOK: tl.constexpr,
215
+ flexpoint_saturate_inf: tl.constexpr,
216
+ BLOCK_N: tl.constexpr,
217
+ STAGES: tl.constexpr,
218
+ HAS_FUSED_SCRATCHPAD: tl.constexpr,
219
+ ):
220
+ IN_MXFP8: tl.constexpr = stride_a_mx_k is not None
221
+ OUT_MXFP8: tl.constexpr = stride_out_mx_m is not None
222
+ if HAS_FUSED_SCRATCHPAD:
223
+ # Bump A to the scratchpad region.
224
+ A += tl.cast(M, tl.int64) * stride_a_m
225
+
226
+ USE_FUSED_MIXED_PREC_ACC: tl.constexpr = (cuda_capability_geq(10, 0)
227
+ and tl.constexpr(A.dtype.element_ty != tl.float32))
228
+ USE_FUSED_ABSMAX: tl.constexpr = (USE_FUSED_MIXED_PREC_ACC and OutActualScale is not None) and ACTIVATION_FN is None
229
+
230
+ THREADS_PER_BLOCK: tl.constexpr = tl.extra.cuda.num_threads()
231
+ local_max = tl.full([THREADS_PER_BLOCK], 0.0, tl.float32)
232
+ if USE_FUSED_ABSMAX:
233
+ local_max = tl.inline_asm_elementwise(
234
+ """
235
+ .reg .f32 my_abs_max;
236
+ mov.b32 my_abs_max, 0;
237
+ mov.b32 $0, 0;
238
+ """, "=r,r", [local_max], dtype=tl.float32, is_pure=False, pack=1)
239
+
240
+ out_scale = load_scale(OutExpectedScale)
241
+ a_scale = load_scale(AScale)
242
+
243
+ if FinalizeScatterIdxs is not None:
244
+ MBound = tl.load(FinalizeScatterIdxs + M + M * EXPT_PER_TOK)
245
+ if tl.program_id(0) >= MBound:
246
+ return
247
+ else:
248
+ MBound = M
249
+
250
+ if NumRows is not None:
251
+ NumRows = NumRows # remove constexpr
252
+ if NumRows.dtype.is_ptr():
253
+ NumRows = tl.load(NumRows)
254
+
255
+ if FinalizeScatterIdxs is not None or (ScatterSrcIndx is not None and EXPT_PER_TOK > 1):
256
+ n_active_experts = 0
257
+ else:
258
+ n_active_experts: tl.constexpr = EXPT_PER_TOK
259
+
260
+ OUT_BLOCK_N: tl.constexpr = BLOCK_N // ACTIVATION_REDUCTION_N
261
+ outN = N // ACTIVATION_REDUCTION_N
262
+
263
+ for pid_m in tl.range(tl.program_id(0), MBound, tl.num_programs(0)):
264
+ src_offs = pid_m * EXPT_PER_TOK + tl.arange(0, EXPT_PER_TOK)
265
+ if FinalizeScatterIdxs is not None:
266
+ row = tl.load(FinalizeScatterIdxs + pid_m)
267
+ src_idxs = tl.load(FinalizeScatterIdxs + M + src_offs)
268
+ n_active_experts = tl.sum((src_idxs != -1).to(tl.int32))
269
+ elif ScatterSrcIndx is not None and EXPT_PER_TOK > 1:
270
+ row = pid_m
271
+ src_idxs = tl.load(ScatterSrcIndx + src_offs)
272
+ n_active_experts = tl.sum((src_idxs != -1).to(tl.int32))
273
+ else:
274
+ row = pid_m
275
+ src_idxs = src_offs
276
+ if NumRows is not None:
277
+ src_idxs = tl.where(src_idxs < NumRows, src_idxs, -1)
278
+
279
+ if n_active_experts == 0:
280
+ for off_n in tl.range(tl.program_id(1) * OUT_BLOCK_N, outN, tl.num_programs(1) * OUT_BLOCK_N):
281
+ offs_n = off_n + tl.arange(0, OUT_BLOCK_N)
282
+ n_mask = offs_n < outN
283
+ tl.store(Out + row * outN + offs_n, tl.zeros([OUT_BLOCK_N], dtype=Out.dtype.element_ty), mask=n_mask)
284
+ else:
285
+ for off_n in tl.range(tl.program_id(1) * BLOCK_N, N, tl.num_programs(1) * BLOCK_N, num_stages=STAGES):
286
+ offs_n = off_n + tl.arange(0, BLOCK_N)
287
+ n_mask = offs_n < N
288
+ if IN_MXFP8:
289
+ MX_SCALE_BLOCK_N: tl.constexpr = BLOCK_N // MXFP_BLOCK_SIZE
290
+ N_MX_BLOCK: tl.constexpr = tl.cdiv(N, MXFP_BLOCK_SIZE)
291
+ offs_n_scale = off_n // BLOCK_N * MX_SCALE_BLOCK_N + tl.arange(0, MX_SCALE_BLOCK_N)[None, :]
292
+ n_mask_scale = offs_n_scale < N_MX_BLOCK
293
+
294
+ acc = tl.zeros([BLOCK_N], dtype=tl.float32)
295
+ if is_hip():
296
+ if EXPT_PER_TOK > 1:
297
+ src_idxs_tup = split_n(tl.reshape(src_idxs, (2, ) * log2(EXPT_PER_TOK)), log2(EXPT_PER_TOK))
298
+ else:
299
+ # Convert 1D tensor to 1D tuple.
300
+ src_idxs_tup = tl.split(tl.reshape(tl.join(src_idxs, src_idxs), (2, )))[:1]
301
+ for i in tl.static_range(0, EXPT_PER_TOK, 1):
302
+ src_idx = src_idxs_tup[i]
303
+ if src_idx != -1:
304
+ As = A + src_idx.to(tl.int64) * stride_a_m + offs_n
305
+ for ki in tl.static_range(K):
306
+ acc += tl.load(As, mask=n_mask, other=0.0)
307
+ As += stride_a_k
308
+ else:
309
+ As = A + src_idxs.to(tl.int64)[:, None] * stride_a_m + offs_n[None, :]
310
+ if IN_MXFP8:
311
+ AScales = AScale + src_idxs.to(tl.int64)[:, None] * stride_a_mx_m + offs_n_scale[None, :]
312
+ for ki in tl.static_range(K):
313
+ a = tl.load(As, mask=(src_idxs != -1)[:, None] & n_mask[None, :], other=0.0)
314
+ As += stride_a_k
315
+ if IN_MXFP8:
316
+ a_mx_scale = tl.load(AScales, mask=(src_idxs != -1)[:, None] & n_mask_scale[None, :])
317
+ AScales += stride_a_mx_k
318
+ a_mx_scale = (a_mx_scale.to(tl.uint32) << 23).to(tl.float32, bitcast=True)
319
+ a_mx_scale = a_mx_scale.reshape([EXPT_PER_TOK, MX_SCALE_BLOCK_N, 1])
320
+ a = a.to(tl.float32).reshape([EXPT_PER_TOK, MX_SCALE_BLOCK_N, MXFP_BLOCK_SIZE])
321
+ a = (a_mx_scale * a).reshape([EXPT_PER_TOK, BLOCK_N])
322
+ acc += tl.sum(a, dtype=tl.float32, axis=0)
323
+ elif USE_FUSED_MIXED_PREC_ACC:
324
+ acc = _mixed_precision_accumulate_and_track_absmax(
325
+ acc, a, axis=0,
326
+ absmax_reg_name="my_abs_max" if USE_FUSED_ABSMAX and ki == K - 1 else None)
327
+ else:
328
+ acc += tl.sum(a, dtype=tl.float32, axis=0)
329
+ if not IN_MXFP8:
330
+ acc = acc * a_scale
331
+ if ACTIVATION_FN is not None:
332
+ out = ACTIVATION_FN(tl.reshape(acc, (1, BLOCK_N)), *activation_fn_args)
333
+ out = tl.reshape(out, (OUT_BLOCK_N, ))
334
+ else:
335
+ tl.static_assert(ACTIVATION_REDUCTION_N == 1,
336
+ "Activation reduction must be 1 if no activation fn is provided")
337
+ out = acc
338
+ if not USE_FUSED_ABSMAX and OutActualScale is not None:
339
+ local_max = tl.maximum(local_max, thread_local_absmax(out))
340
+ if OUT_MXFP8:
341
+ OUT_MX_SCALE_BLOCK_N: tl.constexpr = OUT_BLOCK_N // MXFP_BLOCK_SIZE
342
+ OUT_N_MX_BLOCK: tl.constexpr = (outN + MXFP_BLOCK_SIZE - 1) // MXFP_BLOCK_SIZE
343
+ offs_n_scale = off_n // BLOCK_N * OUT_MX_SCALE_BLOCK_N + tl.arange(0, OUT_MX_SCALE_BLOCK_N)[None, :]
344
+ n_mask_scale = offs_n_scale < OUT_N_MX_BLOCK
345
+ acc, acc_scale = EPILOGUE_FN(acc[None, :], n_mask[None, :], *epilogue_fn_args,
346
+ pid=row * tl.num_programs(1) + tl.program_id(1))
347
+ tl.static_assert(OUT_BLOCK_N % OUT_MX_SCALE_BLOCK_N == 0, "")
348
+ tl.store(OutActualScale + row * stride_out_mx_m + offs_n_scale * stride_out_mx_n, acc_scale, mask=n_mask_scale)
349
+ tl.store(Out + row * outN + offs_n[None, :], acc, mask=n_mask[None, :])
350
+ else:
351
+ out = float_to_flex(out, out_scale if OutExpectedScale is not None else None, None, OutChecksumScale,
352
+ None, Out, flexpoint_saturate_inf)
353
+ if EPILOGUE_FN is not None:
354
+ out = EPILOGUE_FN(out, *epilogue_fn_args, target_dtype=Out.dtype.element_ty,
355
+ pid=row * tl.num_programs(1) + tl.program_id(1))
356
+ offs_n = off_n // ACTIVATION_REDUCTION_N + tl.arange(0, OUT_BLOCK_N)
357
+ n_mask = offs_n < outN
358
+ tl.store(Out + row * outN + offs_n, out, mask=n_mask)
359
+
360
+ persisent_m = tl.num_programs(0) < MBound
361
+ if not persisent_m and n_active_experts == 0:
362
+ # Skip updating the scale if there were no active experts and this is a non-persistent launch.
363
+ # The loop ran only once, and inside it we only stored zeros.
364
+ return
365
+
366
+ if USE_FUSED_ABSMAX:
367
+ local_max = tl.inline_asm_elementwise(
368
+ "mov.b32 $0, my_abs_max;",
369
+ "=r,r",
370
+ [local_max],
371
+ dtype=tl.float32,
372
+ is_pure=True,
373
+ pack=1,
374
+ )
375
+ local_max *= a_scale
376
+ if not OUT_MXFP8:
377
+ update_scale(local_max, OutActualScale, Out)
torch-ext/triton_kernels/matmul_ogs_details/_matmul_ogs.py ADDED
@@ -0,0 +1,464 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # isort: off
2
+ # fmt: off
3
+ import triton
4
+ import triton.language as tl
5
+ from triton_kernels.tensor_details.layout_details.blackwell_scale import unswizzle_mx_scale_bw
6
+ from triton_kernels.tensor_details.layout_details.hopper_scale import unswizzle_mxfp4_scale_hopper
7
+ from triton_kernels.tensor_details.layout_details.hopper_value import mxfp4_to_bf16_triton
8
+ from triton_kernels.numerics_details.flexpoint import float_to_flex, load_scale
9
+ from triton_kernels.numerics_details.mxfp_details._downcast_to_mxfp import MXFP_BLOCK_SIZE
10
+ from ._common import make_matmul_repr, matmul_launch_metadata, swizzle2d, xcd_swizzle, get_scaled_dot_format_string
11
+
12
+
13
+ @triton.jit
14
+ def _zero_masked_rows(
15
+ pid_m, pid_n,
16
+ Y, stride_y_m, stride_y_n,
17
+ N,
18
+ ScatterSrcIndx, num_idxs,
19
+ BLOCK_M: tl.constexpr, BLOCK_N: tl.constexpr):
20
+ offs_m = BLOCK_M * pid_m.to(tl.int64) + tl.arange(0, BLOCK_M)
21
+ offs_n = BLOCK_N * pid_n + tl.arange(0, BLOCK_N)
22
+ src_idx = tl.load(ScatterSrcIndx + offs_m, mask=offs_m < num_idxs, other=0)
23
+ YPtrs = Y + offs_m[:, None] * stride_y_m + offs_n[None, :] * stride_y_n
24
+ mask_n = offs_n < N
25
+ mask = (src_idx == -1)[:, None] & mask_n[None, :]
26
+ tl.store(YPtrs, tl.zeros([BLOCK_M, BLOCK_N], dtype=tl.float32), mask=mask)
27
+
28
+
29
+ _matmul_ogs_repr = make_matmul_repr("_matmul_ogs", [0, 1, 2])
30
+ @triton.jit(do_not_specialize=["TOKENS_PER_EXPT_FOR_ANNOTATION"],
31
+ repr=_matmul_ogs_repr, launch_metadata=matmul_launch_metadata)
32
+ def _matmul_ogs(
33
+ Y, Out, stride_y_k, stride_y_z, stride_y_m, stride_y_n,
34
+ YExpectedScale, YActualScale, YChecksumScale,
35
+ stride_y_mx_z, stride_y_mx_m, stride_y_mx_n,
36
+ X, XPtr, stride_x_z, stride_x_m, stride_x_k,
37
+ XScale,
38
+ XMxScale, stride_x_mx_z, stride_x_mx_m, stride_x_mx_k,
39
+ W, stride_w_e, stride_w_k, stride_w_n, W_TRANSPOSE: tl.constexpr,
40
+ WScale,
41
+ WMxScale, stride_w_mx_e, stride_w_mx_k, stride_w_mx_n,
42
+ B, stride_b_e, # Bias
43
+ NRows, M, N, K, # shapes
44
+ # expt data
45
+ Betas, Gammas,
46
+ GatherIndx,
47
+ ScatterSrcIndx, num_idxs,
48
+ WriteBackIndx, writeback_size,
49
+ ExptHist, ExptOffs, ExptOffsSum, ExptData,
50
+ # true grid size
51
+ batch_size, grid_m, grid_n,
52
+ # Out scale
53
+ out_alpha,
54
+ # fused activation function
55
+ ACTIVATION_FN: tl.constexpr, activation_fn_args, ACTIVATION_REDUCTION_N: tl.constexpr,
56
+ # epilogue transform
57
+ EPILOGUE_FN: tl.constexpr, epilogue_fn_args,
58
+ # MoE config
59
+ N_EXPTS_TOT: tl.constexpr, N_EXPTS_ACT: tl.constexpr,
60
+ # precision config
61
+ MAX_NUM_IMPRECISE_ACC: tl.constexpr, ALLOW_TF32: tl.constexpr,
62
+ FLEXPOINT_SATURATE_INF: tl.constexpr,
63
+ PER_BATCH_SCALE: tl.constexpr,
64
+ # optimization config
65
+ BLOCK_M: tl.constexpr, BLOCK_N: tl.constexpr, BLOCK_K: tl.constexpr,
66
+ GROUP_M: tl.constexpr, XCD_SWIZZLE: tl.constexpr,
67
+ # One of ["HOPPER", "BLACKWELL", None]
68
+ SWIZZLE_MX_VALUE: tl.constexpr,
69
+ # One of ["HOPPER", "BLACKWELL", None]
70
+ SWIZZLE_MX_SCALE: tl.constexpr,
71
+ EPILOGUE_SUBTILE: tl.constexpr,
72
+ EVEN_K: tl.constexpr, SPLIT_K: tl.constexpr,
73
+ W_CACHE_MODIFIER: tl.constexpr,
74
+ NUM_SMS: tl.constexpr,
75
+ TOKENS_PER_EXPT_FOR_ANNOTATION=None,
76
+ UPCAST_INDICES: tl.constexpr = False,
77
+ DISABLE_Y_TMA: tl.constexpr = True,
78
+ SWAP_XW: tl.constexpr = False,
79
+ IS_EPILOGUE_DEQUANT_MXFP8: tl.constexpr = False):
80
+
81
+ Y = Out # Y is passed for the purposes of annotation; replace it with Out
82
+ is_w_microscaled: tl.constexpr = WMxScale is not None
83
+ MX_PACK_DIVISOR: tl.constexpr = MXFP_BLOCK_SIZE
84
+ if is_w_microscaled:
85
+ w_type: tl.constexpr = W.dtype.element_ty
86
+ is_mxfp4: tl.constexpr = w_type == tl.uint8
87
+ tl.static_assert(w_type == tl.uint8 or (w_type == tl.float8e4nv or w_type == tl.float8e5),
88
+ "mx_weight_ptr must be uint8 or fp8")
89
+ tl.static_assert(WMxScale.dtype.element_ty == tl.uint8, "mx_scale_ptr must be uint8")
90
+ tl.static_assert(BLOCK_K % MX_PACK_DIVISOR == 0, "BLOCK_K must be a multiple of MX_PACK_DIVISOR")
91
+ tl.static_assert(SWIZZLE_MX_VALUE == "HOPPER_VALUE" or SWIZZLE_MX_VALUE is None, "Only Hopper swizzling is supported for values")
92
+ else:
93
+ tl.static_assert(SWIZZLE_MX_VALUE is None)
94
+ tl.static_assert(SWIZZLE_MX_SCALE is None)
95
+ is_x_microscaled: tl.constexpr = XMxScale is not None
96
+ if is_x_microscaled:
97
+ x_type: tl.constexpr = X.dtype.element_ty
98
+ tl.static_assert(is_w_microscaled)
99
+ tl.static_assert(x_type == tl.float8e4nv, "mx_act_ptr must be float8e4nv")
100
+ tl.static_assert(XMxScale.dtype.element_ty == tl.uint8, "mx_scale_ptr must be uint8")
101
+ tl.static_assert(BLOCK_K % MX_PACK_DIVISOR == 0, "BLOCK_K must be a multiple of MX_PACK_DIVISOR")
102
+ is_out_microscaled: tl.constexpr = stride_y_mx_z is not None
103
+
104
+ OUT_BLOCK_N: tl.constexpr = BLOCK_N // ACTIVATION_REDUCTION_N
105
+ yN = N // ACTIVATION_REDUCTION_N
106
+
107
+ pid = tl.program_id(0)
108
+ if ExptOffsSum is not None and XCD_SWIZZLE > 1:
109
+ # Determine how much padding there is on the expert data. This allows us to
110
+ # know the true grid size and avoid processing padding tiles.
111
+ padding_m = grid_m - tl.load(ExptOffsSum)
112
+ else:
113
+ padding_m: tl.constexpr = 0
114
+
115
+ HAS_FUSED_SCATTER: tl.constexpr = WriteBackIndx is not None
116
+ index_type: tl.constexpr = tl.int64 if UPCAST_INDICES else tl.int32
117
+
118
+ total_actual_tiles = batch_size * (grid_m - padding_m) * grid_n * SPLIT_K
119
+ if padding_m > 0 and pid >= total_actual_tiles:
120
+ tl.device_assert(batch_size == 0)
121
+ pid_mn = pid - total_actual_tiles
122
+ if pid_mn < padding_m * grid_n:
123
+ pid_m, pid_n = swizzle2d(pid_mn, padding_m, grid_n, GROUP_M)
124
+
125
+ # set masked out rows to 0
126
+ if HAS_FUSED_SCATTER and N_EXPTS_ACT == 1:
127
+ _zero_masked_rows(pid_m, pid_n, Y, stride_y_m, stride_y_n, yN, ScatterSrcIndx, num_idxs, BLOCK_M, OUT_BLOCK_N)
128
+ return
129
+
130
+ # swizzle program ids
131
+ pid_emnk = pid
132
+ if XCD_SWIZZLE != 1:
133
+ pid_emnk = xcd_swizzle(pid_emnk, total_actual_tiles, XCD_SWIZZLE)
134
+ pid_e = pid_emnk // ((grid_m - padding_m) * grid_n * SPLIT_K)
135
+ pid_mnk = pid_emnk % ((grid_m - padding_m) * grid_n * SPLIT_K)
136
+ pid_k = pid_mnk % SPLIT_K
137
+ pid_mn = pid_mnk // SPLIT_K
138
+ pid_m, pid_n = swizzle2d(pid_mn, (grid_m - padding_m), grid_n, GROUP_M)
139
+ # For split-k, advance to the output k slice
140
+ if SPLIT_K > 1:
141
+ Y += pid_k.to( index_type) * stride_y_k
142
+ if is_out_microscaled:
143
+ YActualScale += pid_k.to(index_type) * stride_x_mx_k
144
+ # set masked out rows to 0
145
+ if HAS_FUSED_SCATTER and N_EXPTS_ACT == 1:
146
+ _zero_masked_rows(pid_m, pid_n, Y, stride_y_m, stride_y_n, yN, ScatterSrcIndx, num_idxs, BLOCK_M, OUT_BLOCK_N)
147
+ # unpack expert data
148
+ if ExptData is None:
149
+ tl.static_assert(M is not None)
150
+ expt_id, start_z, start_m, block_id = pid_e, pid_e, 0, pid_m
151
+ else:
152
+ tl.static_assert(M is None)
153
+ expt_data = tl.load(ExptData + pid_m)
154
+ if expt_data == -1:
155
+ return
156
+ expt_id = expt_data & 0x0000FFFF
157
+ block_id = expt_data >> 16
158
+ M = tl.load(ExptHist + expt_id)
159
+ start_m = tl.load(ExptOffs + expt_id)
160
+ start_z = 0
161
+ expt_id, block_id = expt_id.to(index_type), block_id.to(index_type)
162
+ start_m, start_z = start_m.to(index_type), start_z.to(index_type)
163
+ pid_n, pid_k = pid_n.to(index_type), pid_k.to(index_type)
164
+ # A pointers
165
+ offs_x_m = BLOCK_M * block_id + tl.arange(0, BLOCK_M)
166
+ offs_x_m = tl.max_contiguous(tl.multiple_of(offs_x_m % M, BLOCK_M), BLOCK_M)
167
+ X += start_z * stride_x_z
168
+ if GatherIndx is None:
169
+ X += start_m * stride_x_m
170
+ else:
171
+ GatherIndx += start_m
172
+ # no needs to bounds-check here because `offs_x_m` wraps around M dim
173
+ offs_x_m = tl.load(GatherIndx + offs_x_m) // N_EXPTS_ACT
174
+ offs_k = BLOCK_K * pid_k + tl.arange(0, BLOCK_K)
175
+ XPtrs = X + offs_x_m.to(index_type)[:, None] * stride_x_m + offs_k.to(index_type)[None, :] * stride_x_k
176
+
177
+ # TODO: refactor if/else when triton front end improves
178
+ if is_w_microscaled:
179
+ if SWIZZLE_MX_VALUE == "HOPPER_VALUE":
180
+ tl.static_assert(is_mxfp4, "Only mxfp4 is supported for HOPPER swizzling")
181
+ tl.static_assert(not is_x_microscaled)
182
+ # We have pack 2 fp4 values in a byte but we divide the dimension by 2
183
+ # when swizzling
184
+ W_K_DIVISOR: tl.constexpr = 1
185
+ W_K_MULTIPLIER: tl.constexpr = 2
186
+ W_N_DIVISOR: tl.constexpr = 4
187
+ else:
188
+ # We have pack 2 fp4 values in a byte
189
+ W_K_DIVISOR: tl.constexpr = 2 if is_mxfp4 else 1
190
+ W_K_MULTIPLIER: tl.constexpr = 1
191
+ W_N_DIVISOR: tl.constexpr = 1
192
+
193
+ PACKED_BLOCK_K_W: tl.constexpr = (BLOCK_K // W_K_DIVISOR) * W_K_MULTIPLIER
194
+ PACKED_BLOCK_N_W: tl.constexpr = BLOCK_N // W_N_DIVISOR
195
+ MX_SCALE_BLOCK_K: tl.constexpr = BLOCK_K // MX_PACK_DIVISOR
196
+
197
+ WMxScale += expt_id * stride_w_mx_e
198
+
199
+ if SWIZZLE_MX_SCALE == "BLACKWELL_SCALE":
200
+ tl.static_assert(BLOCK_N % 128 == 0)
201
+ tl.static_assert(MX_SCALE_BLOCK_K % 4 == 0)
202
+ PACKED_MX_BLOCK: tl.constexpr = (MX_SCALE_BLOCK_K // 4) * 32 * 4 * 4
203
+ SCALE_BLOCK_N: tl.constexpr = BLOCK_N // 128
204
+ stride_scale_k: tl.constexpr = 1
205
+ elif SWIZZLE_MX_SCALE == "HOPPER_SCALE":
206
+ n_warps: tl.constexpr = tl.extra.cuda.num_warps()
207
+ tl.static_assert(BLOCK_N % (2 * n_warps * 2 * 8) == 0)
208
+ tl.static_assert(MX_SCALE_BLOCK_K % 2 == 0)
209
+ PACKED_MX_BLOCK: tl.constexpr = MX_SCALE_BLOCK_K * 32
210
+ SCALE_BLOCK_N: tl.constexpr = BLOCK_N // 32
211
+ stride_scale_k = stride_w_mx_k
212
+ else:
213
+ PACKED_MX_BLOCK: tl.constexpr = MX_SCALE_BLOCK_K
214
+ SCALE_BLOCK_N: tl.constexpr = BLOCK_N
215
+ stride_scale_k = stride_w_mx_k
216
+ offs_n_scale = (pid_n * SCALE_BLOCK_N + tl.arange(0, SCALE_BLOCK_N)) % N
217
+ offs_n_scale = tl.max_contiguous(tl.multiple_of(offs_n_scale, SCALE_BLOCK_N), SCALE_BLOCK_N)
218
+ # K dimension must be the last dimension for the scales
219
+ offs_k_scale = PACKED_MX_BLOCK * pid_k + tl.arange(0, PACKED_MX_BLOCK)
220
+ WMxScalePtrs = WMxScale + offs_k_scale.to(index_type)[None, :] * stride_scale_k + offs_n_scale.to(index_type)[:, None] * stride_w_mx_n
221
+ else:
222
+ WMxScalePtrs = None
223
+ offs_k_scale = None
224
+ W_K_DIVISOR: tl.constexpr = 1
225
+ W_K_MULTIPLIER: tl.constexpr = 1
226
+ W_N_DIVISOR: tl.constexpr = 1
227
+ PACKED_BLOCK_K_W: tl.constexpr = BLOCK_K
228
+ PACKED_BLOCK_N_W: tl.constexpr = BLOCK_N
229
+
230
+ # B pointers
231
+ offs_w_n = pid_n * PACKED_BLOCK_N_W + tl.arange(0, PACKED_BLOCK_N_W)
232
+ offs_w_n = tl.max_contiguous(tl.multiple_of(offs_w_n % (N // W_N_DIVISOR), PACKED_BLOCK_N_W), PACKED_BLOCK_N_W)
233
+
234
+ if is_x_microscaled:
235
+ XMxScale += start_z.to(index_type) * stride_x_mx_z
236
+ if GatherIndx is None:
237
+ XMxScale += start_m * stride_x_mx_m
238
+ offs_x_k_scale = MX_SCALE_BLOCK_K * pid_k + tl.arange(0, MX_SCALE_BLOCK_K)
239
+ XMxScalePtrs = XMxScale + offs_x_m.to(index_type)[:, None] * stride_x_mx_m + offs_x_k_scale.to(index_type)[None, :] * stride_x_mx_k
240
+ else:
241
+ XMxScalePtrs = None
242
+
243
+ offs_w_k = PACKED_BLOCK_K_W * pid_k + tl.arange(0, PACKED_BLOCK_K_W)
244
+ W += expt_id * stride_w_e
245
+ WPtrs = W + (offs_w_k.to(index_type)[:, None] * stride_w_k + offs_w_n.to(index_type)[None, :] * stride_w_n)
246
+ # compute output
247
+ acc = tl.zeros((BLOCK_M, BLOCK_N), dtype=tl.float32)
248
+ for k in range(K, BLOCK_K * pid_k, -(BLOCK_K * SPLIT_K)):
249
+ if EVEN_K:
250
+ mask_k = tl.full([BLOCK_K], True, dtype=tl.int1)
251
+ mask_k_w = tl.full([PACKED_BLOCK_K_W], True, dtype=tl.int1)
252
+ if is_w_microscaled and SWIZZLE_MX_SCALE is None:
253
+ mask_k_scale = tl.full([PACKED_MX_BLOCK], True, dtype=tl.int1)
254
+ if is_x_microscaled:
255
+ mask_x_k_scale = tl.full([MX_SCALE_BLOCK_K], True, dtype=tl.int1)
256
+ else:
257
+ mask_k = offs_k < k
258
+ mask_k_w = offs_w_k < ((k // W_K_DIVISOR) * W_K_MULTIPLIER)
259
+ if is_w_microscaled and SWIZZLE_MX_SCALE is None:
260
+ mask_k_scale = offs_k_scale * MX_PACK_DIVISOR < k
261
+ if is_x_microscaled:
262
+ mask_x_k_scale = offs_x_k_scale * MX_PACK_DIVISOR < k
263
+
264
+ x = tl.load(XPtrs, mask=mask_k[None, :], other=0.0)
265
+ w = tl.load(WPtrs, mask=mask_k_w[:, None], other=0.0, cache_modifier=W_CACHE_MODIFIER)
266
+ if is_w_microscaled:
267
+ x_format: tl.constexpr = get_scaled_dot_format_string(x.dtype)
268
+ w_format: tl.constexpr = get_scaled_dot_format_string(w.dtype)
269
+
270
+ if is_x_microscaled:
271
+ x_scales = tl.load(XMxScalePtrs, mask=mask_x_k_scale[None, :])
272
+ elif x_format == "fp16" or x_format == "bf16":
273
+ x_scales: tl.constexpr = None
274
+ else:
275
+ # Scale of 1 in E8M0 format
276
+ x_scales = tl.full((BLOCK_M, MX_SCALE_BLOCK_K), 127, dtype=tl.uint8)
277
+
278
+ if SWIZZLE_MX_SCALE == "BLACKWELL_SCALE":
279
+ w_scales = unswizzle_mx_scale_bw(tl.load(WMxScalePtrs))
280
+ elif SWIZZLE_MX_SCALE == "HOPPER_SCALE":
281
+ # Handshake with the swizzling code
282
+ num_warps: tl.constexpr = tl.extra.cuda.num_warps()
283
+ w_scales = unswizzle_mxfp4_scale_hopper(tl.load(WMxScalePtrs), mx_axis=1, num_warps=num_warps)
284
+ else:
285
+ w_scales = tl.load(WMxScalePtrs, mask=mask_k_scale[None, :])
286
+
287
+ if SWIZZLE_MX_VALUE == "HOPPER_VALUE":
288
+ # Handshake with the swizzling code
289
+ tl.static_assert(x_format == "bf16")
290
+ tl.static_assert(w_format == "e2m1")
291
+ w = mxfp4_to_bf16_triton(w.trans(), w_scales, 1)
292
+ tl.static_assert(w.dtype == tl.bfloat16)
293
+ acc = acc.trans()
294
+ x = x.trans()
295
+ # w = w.trans()
296
+ acc = tl.dot(w, x, acc, max_num_imprecise_acc=MAX_NUM_IMPRECISE_ACC, allow_tf32=ALLOW_TF32)
297
+ acc = acc.trans()
298
+ else:
299
+ acc = tl.dot_scaled(x, x_scales, x_format, w, w_scales, w_format, acc=acc, fast_math=True)
300
+ if SWIZZLE_MX_SCALE == "BLACKWELL_SCALE":
301
+ WMxScalePtrs += (MX_SCALE_BLOCK_K // 4 * SPLIT_K) * stride_w_mx_k
302
+ else:
303
+ WMxScalePtrs += (PACKED_MX_BLOCK * SPLIT_K) * stride_w_mx_k
304
+ if is_x_microscaled:
305
+ XMxScalePtrs += (MX_SCALE_BLOCK_K * SPLIT_K) * stride_x_mx_k
306
+ else:
307
+ acc = tl.dot(x, w, acc, max_num_imprecise_acc=MAX_NUM_IMPRECISE_ACC, allow_tf32=ALLOW_TF32)
308
+ XPtrs += (BLOCK_K * SPLIT_K) * stride_x_k
309
+ WPtrs += (PACKED_BLOCK_K_W * SPLIT_K) * stride_w_k
310
+ # bias + scale
311
+ offs_m = BLOCK_M * block_id + tl.arange(0, BLOCK_M)
312
+ offs_y_n = BLOCK_N * pid_n + tl.arange(0, BLOCK_N)
313
+ mask_m = offs_m < M
314
+ mask_n = offs_y_n < N
315
+ if B is not None:
316
+ BPtrs = B + expt_id * stride_b_e + offs_y_n
317
+ if pid_k == 0:
318
+ bias = tl.load(BPtrs, mask=mask_n, other=0)
319
+ else:
320
+ bias = tl.full([BLOCK_N], 0, dtype=tl.float32)
321
+ else:
322
+ bias = tl.full([BLOCK_N], 0, dtype=tl.float32)
323
+ if Betas is not None:
324
+ betas = tl.load(Betas + start_m + offs_m, mask=mask_m, other=0.0)
325
+ else:
326
+ betas = tl.full([BLOCK_M], 1, dtype=tl.float32)
327
+ if Gammas is not None:
328
+ gammas = tl.load(Gammas + start_m + offs_m, mask=mask_m, other=0.0)
329
+ else:
330
+ gammas = tl.full([BLOCK_M], 1, dtype=tl.float32)
331
+ # flexpoint
332
+ x_scale = load_scale(XScale)
333
+ if PER_BATCH_SCALE:
334
+ w_scale = load_scale(WScale + expt_id)
335
+ else:
336
+ w_scale = load_scale(WScale)
337
+ acc *= x_scale * w_scale
338
+ acc = acc + bias[None, :] * betas[:, None]
339
+ if out_alpha is not None:
340
+ acc *= out_alpha
341
+ if ACTIVATION_FN is not None:
342
+ out = ACTIVATION_FN(acc, *activation_fn_args)
343
+ tl.static_assert(out.shape[1] == OUT_BLOCK_N, f"Activation fn out.shape[1] ({out.shape[1]}) doesn't match computed OUT_BLOCK_N ({OUT_BLOCK_N})")
344
+ offs_y_n = OUT_BLOCK_N * pid_n + tl.arange(0, OUT_BLOCK_N)
345
+ mask_n = offs_y_n < yN
346
+ else:
347
+ tl.static_assert(ACTIVATION_REDUCTION_N == 1, "Activation reduction must be 1 if no activation fn is provided")
348
+ out = acc
349
+ out *= gammas[:, None]
350
+ # write-back
351
+ Y += start_z.to(index_type) * stride_y_z
352
+ if WriteBackIndx is not None:
353
+ WriteBackIndx += start_m
354
+ dst_idx = tl.load(WriteBackIndx + offs_m, mask=start_m + offs_m < writeback_size, other=-1)
355
+ mask_m = mask_m & (dst_idx != -1)
356
+ offs_y_m = dst_idx
357
+ else:
358
+ Y += start_m * stride_y_m
359
+ offs_y_m = offs_m
360
+
361
+ YPtrs = Y + offs_y_m.to(index_type)[:, None] * stride_y_m + offs_y_n.to(index_type)[None, :] * stride_y_n
362
+ mask = mask_m[:, None] & mask_n[None, :]
363
+ if is_out_microscaled:
364
+ MX_SCALE_BLOCK_N: tl.constexpr = BLOCK_N // MXFP_BLOCK_SIZE
365
+ N_MX_BLOCK: tl.constexpr = tl.cdiv(N, MXFP_BLOCK_SIZE)
366
+ tl.static_assert(EPILOGUE_FN is not None)
367
+ out, out_scale = EPILOGUE_FN(out, mask, *epilogue_fn_args)
368
+ tl.static_assert(BLOCK_N % MX_SCALE_BLOCK_N == 0, "")
369
+ offs_y_n_scale = MX_SCALE_BLOCK_N * pid_n + tl.arange(0, MX_SCALE_BLOCK_N)
370
+ mask_n_scale = offs_y_n_scale < N_MX_BLOCK
371
+ YActualScale += start_z.to(index_type) * stride_y_mx_z
372
+ if WriteBackIndx is None:
373
+ YActualScale += start_m * stride_y_mx_m
374
+ YActualScalePtrs = YActualScale + offs_y_m.to(index_type)[:, None] * stride_y_mx_m + offs_y_n_scale.to(index_type)[None, :] * stride_y_mx_n
375
+ else:
376
+ YActualScalePtrs = YActualScale + (offs_y_m - NRows).to(index_type)[:, None] * stride_y_mx_m + offs_y_n_scale.to(index_type)[None, :] * stride_y_mx_n
377
+ tl.store(YActualScalePtrs, out_scale, mask=mask_m[:, None] & mask_n_scale[None, :])
378
+ else:
379
+ out = float_to_flex(out, YExpectedScale, YActualScale, YChecksumScale, mask, Y, FLEXPOINT_SATURATE_INF)
380
+ if EPILOGUE_FN is not None and not IS_EPILOGUE_DEQUANT_MXFP8:
381
+ out = EPILOGUE_FN(out, *epilogue_fn_args, target_dtype=YPtrs.dtype.element_ty)
382
+ tl.store(YPtrs, out, mask=mask)
383
+
384
+
385
+ # Imagine N_EXPTS_ACT = 4, n_final_rows = 5, and n_scratchpad_rows = 8.
386
+ # Also imagine scatter_indx.src_indx is:
387
+ # (number of active experts per final row)
388
+ # -1 -1 0 -1 1
389
+ # -1 2 -1 -1 1
390
+ # 1 3 -1 -1 2
391
+ # -1 4 5 6 3
392
+ # -1 -1 -1 -1 0 (this row is unused)
393
+ #
394
+ # Then, row 0 and 1 can be written directly to the final tensor.
395
+ # In this case, WriteBackIndx looks like:
396
+ # [0] = 0 : intermediate row 0 is written directly to final row 0
397
+ # [1] = 5+1=6 : scratchpad starts at offset 5
398
+ # [2] = 1 : intermediate row 2 is written directly to final row 1
399
+ # [3] = 5+3=8
400
+ # [4] = 5+4=9
401
+ # [5] = 5+5=10
402
+ # [6] = 5+6=11
403
+ # [7] = -1 : unused (there are only seven intermediate rows)
404
+ @triton.jit
405
+ def _compute_writeback_idx(
406
+ WriteBackIndx,
407
+ FinalizeScatterIdxs,
408
+ ScatterDstIndx, ScatterSrcIndx,
409
+ n_final_rows, n_scratchpad_rows,
410
+ BLOCK_M: tl.constexpr,
411
+ N_EXPTS_ACT: tl.constexpr,
412
+ ):
413
+ tl.static_assert(N_EXPTS_ACT > 1)
414
+
415
+ pid_m = tl.program_id(0)
416
+ offs_m = pid_m * BLOCK_M + tl.arange(0, BLOCK_M)
417
+ mask_m = offs_m < n_scratchpad_rows
418
+ dst_idxs = tl.load(ScatterDstIndx + offs_m, mask=mask_m, other=-1)
419
+ # Load corresponding rows in ScatterSrcIndx.
420
+ mask = dst_idxs != -1
421
+ src_offs = (dst_idxs // N_EXPTS_ACT) * N_EXPTS_ACT
422
+ src_offs = src_offs[:, None] + tl.arange(0, N_EXPTS_ACT)[None, :]
423
+ src_idxs = tl.load(ScatterSrcIndx + src_offs, mask=mask[:, None], other=-1)
424
+ # Compute the number of actually active experts.
425
+ is_src_active = (src_idxs != -1).to(tl.int32)
426
+ has_one_active = tl.sum(is_src_active, axis=1) == 1
427
+ # Compute the writeback index.
428
+ wb_idx = tl.where(has_one_active, dst_idxs // N_EXPTS_ACT, n_final_rows + offs_m)
429
+ wb_idx = tl.where(mask, wb_idx, -1)
430
+ tl.store(WriteBackIndx + offs_m, wb_idx, mask=mask_m)
431
+
432
+ if pid_m >= ((n_final_rows + BLOCK_M - 1) // BLOCK_M):
433
+ return
434
+
435
+ mask_m = offs_m < n_final_rows
436
+ src_offs = offs_m[:, None] * N_EXPTS_ACT + tl.arange(0, N_EXPTS_ACT)[None, :]
437
+ src_idxs = tl.load(ScatterSrcIndx + src_offs, mask=mask_m[:, None], other=-1)
438
+ is_src_active = (src_idxs != -1).to(tl.int32)
439
+ num_src_active = tl.sum(is_src_active, axis=1)
440
+
441
+ need_finalize_scatter = mask_m & (num_src_active != 1)
442
+ finalize_scatter_count = tl.sum(need_finalize_scatter.to(tl.int32))
443
+ if finalize_scatter_count == 0:
444
+ return
445
+ pp_off = tl.atomic_add(FinalizeScatterIdxs + n_final_rows + n_scratchpad_rows, finalize_scatter_count)
446
+
447
+ # need_finalize_scatter = [1, 0, 0, 1, 1, 0, 1, 0, 1]
448
+ # arange = [0, 1, 2, 3, 4, 5, 6, 7, 8]
449
+ arange = tl.arange(0, BLOCK_M)
450
+ # idxs = [0, _, _, 3, 4, _, 6, _, 8]
451
+ last = BLOCK_M - 1
452
+ idxs = tl.where(need_finalize_scatter, arange, last)
453
+ # idxs = [0, 3, 4, 6, 8, _, _, _, _]
454
+ idxs = tl.sort(idxs)
455
+ # r = offs_m
456
+ # d = [r[0], r[3], r[4], r[6], r[8], r[-1], r[-1], r[-1], r[-1]]
457
+ d = tl.gather(offs_m, idxs, axis=0)
458
+ s = tl.gather(src_idxs, idxs.expand_dims(1).broadcast_to(src_idxs.shape), axis=0)
459
+ # store destination indices
460
+ Ptr = FinalizeScatterIdxs + pp_off
461
+ tl.store(Ptr + arange, d, mask=arange < finalize_scatter_count)
462
+ # store src indices
463
+ Ptr = FinalizeScatterIdxs + n_final_rows + pp_off * N_EXPTS_ACT
464
+ tl.store(Ptr + N_EXPTS_ACT * arange[:, None] + tl.arange(0, N_EXPTS_ACT)[None, :], s, mask=(arange < finalize_scatter_count)[:, None])
torch-ext/triton_kernels/matmul_ogs_details/_p_matmul_ogs.py ADDED
@@ -0,0 +1,505 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # isort: off
2
+ # fmt: off
3
+ import torch
4
+ import triton
5
+ import triton.language as tl
6
+ from triton_kernels import target_info
7
+ from triton_kernels.tensor_details.layout_details.blackwell_scale import unswizzle_mx_scale_bw
8
+ from triton_kernels.numerics_details.flexpoint import (
9
+ float_to_flex,
10
+ load_scale,
11
+ nan_propagating_absmax_reduce,
12
+ compute_scale,
13
+ )
14
+ from triton_kernels.numerics_details.mxfp_details._downcast_to_mxfp import MXFP_BLOCK_SIZE
15
+ from ._common import make_matmul_repr, matmul_launch_metadata, swizzle2d, xcd_swizzle, get_scaled_dot_format_string
16
+
17
+
18
+ @tl.constexpr_function
19
+ def cuda_capability_geq(major, minor):
20
+ return target_info.cuda_capability_geq(major, minor)
21
+
22
+ @tl.constexpr_function
23
+ def get_dtype(tensor_or_desc: tl.tensor | tl.tensor_descriptor) -> tl.dtype:
24
+ if isinstance(tensor_or_desc, tl.tensor):
25
+ return tensor_or_desc.dtype.element_ty
26
+ elif isinstance(tensor_or_desc, tl.tensor_descriptor):
27
+ return tensor_or_desc.dtype
28
+ else:
29
+ raise ValueError(f"Invalid type: {type(tensor_or_desc)}")
30
+
31
+
32
+ @triton.jit
33
+ def _tma_load_2d(desc, offs, transpose: tl.constexpr = False):
34
+ if len(desc.shape) == 2 and len(offs) == 3:
35
+ tl.device_assert(offs[0] == 0, "2D TMA load requires Z offset to be 0")
36
+ offs = offs[1:]
37
+ if transpose:
38
+ offs = offs[:-2] + [offs[-1], offs[-2]]
39
+ res = desc.load(offs)
40
+ res = tl.reshape(res, desc.block_shape[-2:])
41
+ if transpose:
42
+ res = tl.trans(res)
43
+ return res
44
+
45
+
46
+ # Helper function to recreate a TMA desc with the same fields, but with a new pointer and optional new shape.
47
+ @triton.jit
48
+ def _update_tensor_desc(desc, ptr, shape=None):
49
+ return tl.make_tensor_descriptor(
50
+ ptr,
51
+ shape=shape or desc.shape,
52
+ # last dim must be constexpr 1; reflecting the old descriptor drops the constexpr
53
+ strides=desc.strides[:-1] + [tl.constexpr(1)],
54
+ block_shape=desc.block_shape,
55
+ )
56
+
57
+
58
+ @triton.jit
59
+ def _load_tile_attrs(
60
+ tile_id, num_tiles, grid_m, grid_n, padding_m,
61
+ M, ExptData, ExptHist, ExptOffs,
62
+ BLOCK_M: tl.constexpr, BLOCK_N: tl.constexpr, SPLIT_K: tl.constexpr,
63
+ GROUP_M: tl.constexpr, XCD_SWIZZLE: tl.constexpr):
64
+ # unpack and swizzle program ids
65
+ pid_emnk = tile_id
66
+ if XCD_SWIZZLE != 1:
67
+ pid_emnk = xcd_swizzle(pid_emnk, num_tiles // SPLIT_K, XCD_SWIZZLE)
68
+ pid_e = pid_emnk // ((grid_m - padding_m) * grid_n * SPLIT_K)
69
+ pid_mnk = pid_emnk % ((grid_m - padding_m) * grid_n * SPLIT_K)
70
+ if SPLIT_K > 1:
71
+ pid_k = pid_mnk % SPLIT_K
72
+ pid_mn = pid_mnk // SPLIT_K
73
+ else:
74
+ pid_k: tl.constexpr = 0
75
+ pid_mn = pid_mnk
76
+ pid_m, pid_n = swizzle2d(pid_mn, (grid_m - padding_m), grid_n, GROUP_M)
77
+
78
+ # unpack expert data
79
+ if ExptData is None:
80
+ tl.static_assert(M is not None)
81
+ expt_id, start_z, start_m, block_id, eM = pid_e, pid_e, 0, pid_m, -1
82
+ else:
83
+ tl.static_assert(M is None)
84
+ expt_data = tl.load(ExptData + pid_m)
85
+ expt_id = expt_data & 0x0000FFFF
86
+ block_id = expt_data >> 16
87
+ eM = tl.load(ExptHist + expt_id)
88
+ start_m = tl.load(ExptOffs + expt_id)
89
+ start_z = 0
90
+
91
+ off_m = BLOCK_M * block_id
92
+ off_n = BLOCK_N * pid_n
93
+
94
+ return expt_id, start_z, start_m, eM, off_m, off_n, pid_k
95
+
96
+
97
+ @triton.jit
98
+ def _load_writeback_idx_and_mask(WriteBackIndx, writeback_size, offs, mask):
99
+ mask = mask & (offs < writeback_size)
100
+ offs = tl.load(WriteBackIndx + offs, mask=mask, other=-1)
101
+ mask = offs != -1
102
+ return (offs, mask)
103
+
104
+
105
+ _matmul_ogs_repr = make_matmul_repr("_p_matmul_ogs", [0, 1, 2])
106
+ @triton.jit(do_not_specialize=["TOKENS_PER_EXPT_FOR_ANNOTATION"],
107
+ repr=_matmul_ogs_repr, launch_metadata=matmul_launch_metadata)
108
+ def _p_matmul_ogs(
109
+ Y, Out, stride_y_k, stride_y_z, stride_y_m, stride_y_n,
110
+ YExpectedScale, YActualScale, YChecksumScale,
111
+ stride_y_mx_z, stride_y_mx_m, stride_y_mx_n,
112
+ X, XPtr, stride_x_z, stride_x_m, stride_x_k,
113
+ XScale,
114
+ XMxScale, stride_x_mx_z, stride_x_mx_m, stride_x_mx_k,
115
+ W, stride_w_e, stride_w_k, stride_w_n, W_TRANSPOSE: tl.constexpr,
116
+ WScale,
117
+ MxScale, stride_mx_e, stride_mx_k, stride_mx_n,
118
+ B, stride_b_e, # Bias
119
+ NRows, M, N, K, # shapes
120
+ # expt data
121
+ Betas, Gammas,
122
+ GatherIndx,
123
+ ScatterSrcIndx, num_idxs,
124
+ WriteBackIndx, writeback_size,
125
+ ExptHist, ExptOffs, ExptOffsSum, ExptData,
126
+ # true grid size
127
+ batch_size, grid_m, grid_n,
128
+ # Out scale
129
+ out_alpha,
130
+ # fused activation function
131
+ ACTIVATION_FN: tl.constexpr, activation_fn_args, ACTIVATION_REDUCTION_N: tl.constexpr,
132
+ # epilogue transform
133
+ EPILOGUE_FN: tl.constexpr, epilogue_fn_args,
134
+ # MoE config
135
+ N_EXPTS_TOT: tl.constexpr, N_EXPTS_ACT: tl.constexpr,
136
+ # precision config
137
+ MAX_NUM_IMPRECISE_ACC: tl.constexpr, ALLOW_TF32: tl.constexpr,
138
+ FLEXPOINT_SATURATE_INF: tl.constexpr,
139
+ PER_BATCH_SCALE: tl.constexpr,
140
+ # optimization config
141
+ BLOCK_M: tl.constexpr, BLOCK_N: tl.constexpr, BLOCK_K: tl.constexpr,
142
+ GROUP_M: tl.constexpr, XCD_SWIZZLE: tl.constexpr,
143
+ # NYI: Must be None
144
+ SWIZZLE_MX_VALUE: tl.constexpr,
145
+ # One of ["BLACKWELL", None]
146
+ SWIZZLE_MX_SCALE: tl.constexpr,
147
+ EPILOGUE_SUBTILE: tl.constexpr,
148
+ EVEN_K: tl.constexpr, SPLIT_K: tl.constexpr,
149
+ W_CACHE_MODIFIER: tl.constexpr,
150
+ NUM_SMS: tl.constexpr,
151
+ TOKENS_PER_EXPT_FOR_ANNOTATION=None,
152
+ UPCAST_INDICES:tl.constexpr=False,
153
+ DISABLE_Y_TMA: tl.constexpr=False,
154
+ SWAP_XW: tl.constexpr = False,
155
+ IS_EPILOGUE_DEQUANT_MXFP8: tl.constexpr = False):
156
+ tl.static_assert(SWIZZLE_MX_VALUE is None, "NYI. Value swizzling")
157
+ Y = Out # Y is passed for the purposes of annotation; replace it with Out
158
+
159
+ is_microscaled_format: tl.constexpr = MxScale is not None
160
+ MX_PACK_DIVISOR: tl.constexpr = MXFP_BLOCK_SIZE
161
+ if is_microscaled_format:
162
+ w_type: tl.constexpr = get_dtype(W)
163
+ tl.static_assert(w_type == tl.uint8 or (w_type == tl.float8e4nv or w_type == tl.float8e5),
164
+ "mx_weight_ptr must be uint8")
165
+ tl.static_assert(get_dtype(MxScale) == tl.uint8, "mx_scale_ptr must be uint8")
166
+ tl.static_assert(BLOCK_K % MX_PACK_DIVISOR == 0, "BLOCK_K must be a multiple of MX_PACK_DIVISOR")
167
+ tl.static_assert(SWIZZLE_MX_SCALE == "BLACKWELL_SCALE" or SWIZZLE_MX_SCALE is None, "Only Blackwell swizzling is supported for scales")
168
+
169
+ # We have pack 2 fp4 values in a byte
170
+ W_PACK_DIVISOR: tl.constexpr = 2 if w_type == tl.uint8 else 1
171
+ PACKED_BLOCK_K_W: tl.constexpr = BLOCK_K // W_PACK_DIVISOR
172
+ MX_SCALE_BLOCK_K: tl.constexpr = BLOCK_K // MX_PACK_DIVISOR
173
+ else:
174
+ W_PACK_DIVISOR: tl.constexpr = 1
175
+ MX_SCALE_BLOCK_K: tl.constexpr = 1
176
+ PACKED_BLOCK_K_W: tl.constexpr = BLOCK_K
177
+ tl.static_assert(SWIZZLE_MX_SCALE is None)
178
+
179
+ if ExptOffsSum is not None:
180
+ # Determine how much padding there is on the expert data. This allows us to
181
+ # know the true grid size and avoid processing padding tiles.
182
+ padding_m = grid_m - tl.load(ExptOffsSum)
183
+ else:
184
+ padding_m: tl.constexpr = 0
185
+
186
+ HAS_FUSED_SCATTER: tl.constexpr = WriteBackIndx is not None
187
+ index_type: tl.constexpr = tl.int64
188
+
189
+ if EPILOGUE_SUBTILE is None:
190
+ SUBTILE_FACTOR: tl.constexpr = 1
191
+ else:
192
+ SUBTILE_FACTOR: tl.constexpr = EPILOGUE_SUBTILE
193
+ EPILOGUE_BLOCK_N: tl.constexpr = BLOCK_N // SUBTILE_FACTOR
194
+ OUT_BLOCK_N: tl.constexpr = EPILOGUE_BLOCK_N // ACTIVATION_REDUCTION_N
195
+ yN = N // ACTIVATION_REDUCTION_N
196
+
197
+ # set masked out rows to 0
198
+ if HAS_FUSED_SCATTER and N_EXPTS_ACT == 1:
199
+ # Iterate with reversed pids so that later pids will get more tiles if the number of
200
+ # tiles isn't evenly divisible by the number of SMs.
201
+ # The main loop after this iterates in the forward direction such that earlier
202
+ # pids get more tiles if the number of tiles isn't evenly divisible.
203
+ # This helps balance the work across the SMs.
204
+ for pid_mnk in range(NUM_SMS - tl.program_id(0) - 1, batch_size * grid_m * grid_n * SPLIT_K, NUM_SMS):
205
+ pid_k = pid_mnk % SPLIT_K
206
+ pid_mn = pid_mnk // SPLIT_K
207
+ pid_m, pid_n = swizzle2d(pid_mn, grid_m, grid_n, GROUP_M)
208
+
209
+ z = tl.zeros([BLOCK_M, BLOCK_N // ACTIVATION_REDUCTION_N], dtype=tl.float32)
210
+ offs_m = z.shape[0] * pid_m + tl.arange(0, z.shape[0])
211
+ offs_n = z.shape[1] * pid_n + tl.arange(0, z.shape[1])
212
+ src_idx = tl.load(ScatterSrcIndx + offs_m, mask=offs_m < num_idxs, other=0)
213
+ YPtrs = Y + offs_m.to(index_type)[:, None] * stride_y_m + offs_n[None, :] * stride_y_n
214
+ mask_n = offs_n < yN
215
+ mask = (src_idx == -1)[:, None] & mask_n[None, :]
216
+ tl.store(YPtrs + pid_k * stride_y_k, z, mask=mask)
217
+
218
+ USE_FLEXPOINT_SCALE: tl.constexpr = YActualScale is not None or YChecksumScale is not None
219
+
220
+ USE_GATHER_TMA: tl.constexpr = GatherIndx is not None and cuda_capability_geq(10, 0)
221
+ X_USE_LOAD_TMA: tl.constexpr = GatherIndx is None and isinstance(X, tl.tensor_descriptor)
222
+ USE_SCATTER_TMA: tl.constexpr = (cuda_capability_geq(10, 0) and HAS_FUSED_SCATTER) and not DISABLE_Y_TMA
223
+ INT_MAX: tl.constexpr = 2147483647
224
+
225
+ if USE_SCATTER_TMA:
226
+ y_desc = tl.make_tensor_descriptor(
227
+ Y,
228
+ # No masking on the M dimension because we manually mask by setting indices to INT_MAX
229
+ shape=[INT_MAX - 1, yN],
230
+ strides=[stride_y_m, stride_y_n],
231
+ block_shape=[1, OUT_BLOCK_N],
232
+ )
233
+
234
+ k_tiles = tl.cdiv(K, BLOCK_K * SPLIT_K)
235
+ num_tiles = batch_size * (grid_m - padding_m) * grid_n * SPLIT_K
236
+
237
+ # If true, do not share loop-carried variables between the prologue and the
238
+ # epilogue to enable better pipelining with mmav5
239
+ INDEPENDENT_EPILOGUE: tl.constexpr = cuda_capability_geq(10, 0)
240
+
241
+ # start negative; will be incremented at the top of the loop
242
+ if INDEPENDENT_EPILOGUE:
243
+ tile_id1 = tl.program_id(0) - NUM_SMS
244
+
245
+ # Keep track of local max for updating flexpoint scales.
246
+ THREADS_PER_BLOCK: tl.constexpr = tl.extra.cuda.num_threads()
247
+ local_absmax = tl.full([THREADS_PER_BLOCK], 0.0, tl.uint32)
248
+
249
+ DISALLOW_ACC_MULTI_BUFFER: tl.constexpr = is_microscaled_format and BLOCK_M * BLOCK_N >= 128 * 256
250
+ # Enable warp specialization when all loads are TMA loads.
251
+ WARP_SPECIALIZE: tl.constexpr = (USE_GATHER_TMA or X_USE_LOAD_TMA)
252
+
253
+ for tile_id in tl.range(tl.program_id(0), num_tiles, NUM_SMS, flatten=True, disallow_acc_multi_buffer=DISALLOW_ACC_MULTI_BUFFER, warp_specialize=WARP_SPECIALIZE):
254
+ expt_id, start_z, start_m, eM, off_m, off_n, pid_k = _load_tile_attrs(
255
+ tile_id, num_tiles, grid_m, grid_n, padding_m,
256
+ M, ExptData, ExptHist, ExptOffs,
257
+ BLOCK_M, BLOCK_N, SPLIT_K,
258
+ GROUP_M, XCD_SWIZZLE)
259
+
260
+ # Base pointers and offsets.
261
+ if not USE_GATHER_TMA and not X_USE_LOAD_TMA:
262
+ XBase = X + start_z.to(index_type) * stride_x_z
263
+ offs_x_k = tl.arange(0, BLOCK_K)[None, :] * stride_x_k
264
+ if SPLIT_K > 1:
265
+ offs_x_k += pid_k.to(index_type) * BLOCK_K * stride_x_k
266
+
267
+ if not X_USE_LOAD_TMA:
268
+ offs_m = off_m + tl.arange(0, BLOCK_M)
269
+ mask_m = offs_m < (M if M is not None else eM)
270
+ if USE_GATHER_TMA:
271
+ # Mask the gather indices and load -1 instead. TMA will handle OOB accesses.
272
+ if ExptData is None:
273
+ offs_x_m = tl.load(GatherIndx + start_m.to(index_type) + offs_m, mask=mask_m)
274
+ # Bump rows to account for the Z offset.
275
+ offs_x_m += start_z * (stride_x_z // stride_x_m)
276
+ offs_x_m = tl.where(mask_m, offs_x_m, -1)
277
+ else:
278
+ offs_x_m = tl.load(GatherIndx + start_m.to(index_type) + offs_m,
279
+ mask=mask_m, other=-N_EXPTS_ACT) // N_EXPTS_ACT
280
+ else:
281
+ if M is not None:
282
+ offs_m = tl.max_contiguous(tl.multiple_of(offs_m % M, BLOCK_M), BLOCK_M)
283
+ else:
284
+ offs_m = tl.max_contiguous(tl.multiple_of(offs_m % eM, BLOCK_M), BLOCK_M)
285
+ # no needs to bounds-check here because `offs_m` wraps around M dim
286
+ offs_m = tl.load(GatherIndx + start_m.to(index_type) + offs_m) // N_EXPTS_ACT
287
+ offs_x_m = offs_m.to(index_type)[:, None] * stride_x_m
288
+
289
+ acc = tl.zeros((BLOCK_N, BLOCK_M) if SWAP_XW else (BLOCK_M, BLOCK_N), dtype=tl.float32)
290
+ for ki in tl.range(k_tiles, disallow_acc_multi_buffer=DISALLOW_ACC_MULTI_BUFFER):
291
+ off_k = pid_k * BLOCK_K + ki * BLOCK_K * SPLIT_K
292
+ off_k_w = pid_k * PACKED_BLOCK_K_W + ki * PACKED_BLOCK_K_W * SPLIT_K
293
+ off_k_mx = pid_k * MX_SCALE_BLOCK_K + ki * MX_SCALE_BLOCK_K * SPLIT_K
294
+
295
+ if USE_GATHER_TMA:
296
+ x = X.gather(offs_x_m, off_k)
297
+ elif X_USE_LOAD_TMA:
298
+ x = _tma_load_2d(X, [start_z, start_m + off_m, off_k])
299
+ else:
300
+ XPtrs = XBase + offs_x_m + offs_x_k
301
+ XBase += BLOCK_K * SPLIT_K * stride_x_k
302
+ mask_k = tl.arange(0, BLOCK_K) < K - off_k
303
+ if EVEN_K:
304
+ if SPLIT_K > 1:
305
+ x = tl.load(XPtrs, mask=mask_k[None, :], other=0.0)
306
+ else:
307
+ x = tl.load(XPtrs)
308
+ else:
309
+ x = tl.load(XPtrs, mask=mask_k[None, :], other=0.0)
310
+
311
+ w = _tma_load_2d(W, [expt_id, off_k_w, off_n], transpose=W_TRANSPOSE)
312
+
313
+ if is_microscaled_format:
314
+ x_format: tl.constexpr = get_scaled_dot_format_string(x.dtype)
315
+ mx_format: tl.constexpr = get_scaled_dot_format_string(w.dtype)
316
+ if x_format == "fp16" or x_format == "bf16":
317
+ x_scales: tl.constexpr = None
318
+ else:
319
+ x_scales = tl.full((BLOCK_M, BLOCK_K // MX_PACK_DIVISOR), 127, dtype=tl.uint8)
320
+ if SWIZZLE_MX_SCALE == "BLACKWELL_SCALE":
321
+ flattened_expt_n_idx = expt_id * ((N + 127) // 128) + (off_n // 128)
322
+ w_scales = MxScale.load([0, flattened_expt_n_idx, pid_k * MX_SCALE_BLOCK_K // 4 + ki * (MX_SCALE_BLOCK_K // 4 * SPLIT_K), 0, 0])
323
+ w_scales = w_scales.reshape((w_scales.shape[1], w_scales.shape[2] * w_scales.shape[-2] * w_scales.shape[-1]))
324
+ w_scales = unswizzle_mx_scale_bw(w_scales)
325
+ else:
326
+ w_scales = _tma_load_2d(MxScale, [expt_id, off_k_mx, off_n]).T
327
+ if SWAP_XW:
328
+ acc = tl.dot_scaled(w.T, w_scales, mx_format, x.T, x_scales, x_format, acc=acc, fast_math=True)
329
+ else:
330
+ acc = tl.dot_scaled(x, x_scales, x_format, w, w_scales, mx_format, acc=acc, fast_math=True)
331
+ else:
332
+ if SWAP_XW:
333
+ acc = tl.dot(w.T, x.T, acc, max_num_imprecise_acc=MAX_NUM_IMPRECISE_ACC, allow_tf32=ALLOW_TF32)
334
+ else:
335
+ acc = tl.dot(x, w, acc, max_num_imprecise_acc=MAX_NUM_IMPRECISE_ACC, allow_tf32=ALLOW_TF32)
336
+
337
+ if INDEPENDENT_EPILOGUE:
338
+ tile_id1 += NUM_SMS
339
+ expt_id1, start_z1, start_m1, eM1, off_m1, off_n1, pid_k1 = _load_tile_attrs(
340
+ tile_id1, num_tiles, grid_m, grid_n, padding_m,
341
+ M, ExptData, ExptHist, ExptOffs,
342
+ BLOCK_M, BLOCK_N, SPLIT_K,
343
+ GROUP_M, XCD_SWIZZLE)
344
+ else:
345
+ tile_id1, expt_id1, start_z1, start_m1, eM1 = tile_id, expt_id, start_z, start_m, eM
346
+ off_m1, off_n1, pid_k1 = off_m, off_n, pid_k
347
+
348
+ # Determine output row offsets and mask
349
+ offs_m = off_m1 + tl.arange(0, BLOCK_M)
350
+ mask_m = offs_m < M if M is not None else offs_m < eM1
351
+ if HAS_FUSED_SCATTER:
352
+ offs_y_m, mask_m = _load_writeback_idx_and_mask(
353
+ WriteBackIndx, writeback_size, start_m1 + offs_m, mask_m)
354
+ # Later, mask out the acc for computing flexpoint scales.
355
+ MASK_ACC: tl.constexpr = USE_FLEXPOINT_SCALE
356
+
357
+ if USE_SCATTER_TMA and SPLIT_K > 1:
358
+ # Compute the split k offset in number of rows, and add it to offs_y_m.
359
+ # This allows us to write to the correct slice in the output tensor while using
360
+ # a 2D TMA scatter.
361
+ tl.device_assert(stride_y_k // stride_y_m == tl.cdiv(stride_y_k, stride_y_m))
362
+ split_k_row_offs = pid_k1 * (stride_y_k // stride_y_m)
363
+ offs_y_m = tl.where(mask_m, offs_y_m + split_k_row_offs, offs_y_m)
364
+ else:
365
+ offs_y_m = start_m1 + offs_m
366
+
367
+ if USE_GATHER_TMA:
368
+ MASK_ACC: tl.constexpr = False
369
+ else:
370
+ # Later, mask out the acc for computing flexpoint scales.
371
+ MASK_ACC: tl.constexpr = USE_FLEXPOINT_SCALE
372
+
373
+ # TMA is faster on Blackwell if a SWAP_XW transpose is not needed, or when we need registers to mask out the acc.
374
+ # Contrary to the SWAP_XW case, having a fused activation function tends to make TMA faster again.
375
+ # For the ideal optimization, this would depend on what the activation function is doing.
376
+ Y_USE_TMA: tl.constexpr = (MASK_ACC or cuda_capability_geq(10, 0)) and not (
377
+ DISABLE_Y_TMA or (SWAP_XW and ACTIVATION_FN is None))
378
+
379
+ YBase = Y + start_z1.to(index_type) * stride_y_z + start_m1.to(index_type) * stride_y_m
380
+ if USE_SCATTER_TMA:
381
+ if ExptData is None: # start_z1 may change; update the descriptor
382
+ y_desc = _update_tensor_desc(y_desc, YBase)
383
+ elif not HAS_FUSED_SCATTER and Y_USE_TMA:
384
+ y_desc = tl.make_tensor_descriptor(
385
+ YBase + pid_k1.to(index_type) * stride_y_k,
386
+ shape=[M if M is not None else eM1, yN],
387
+ strides=[stride_y_m, stride_y_n],
388
+ block_shape=[BLOCK_M, OUT_BLOCK_N],
389
+ )
390
+
391
+ # bias + scale
392
+ offs_y_n = off_n1 + tl.arange(0, BLOCK_N)
393
+ mask_n = offs_y_n < N
394
+ if B is not None:
395
+ BPtrs = B + expt_id1 * stride_b_e + offs_y_n
396
+ if pid_k1 == 0:
397
+ bias = tl.load(BPtrs, mask=mask_n, other=0)
398
+ else:
399
+ bias = tl.full([BLOCK_N], 0, dtype=tl.float32)
400
+ else:
401
+ bias = tl.full([BLOCK_N], 0, dtype=tl.float32)
402
+ if Betas is not None:
403
+ betas = tl.load(Betas + start_m1 + offs_m, mask=mask_m, other=0.0)
404
+ else:
405
+ betas = tl.full([BLOCK_M], 1, dtype=tl.float32)
406
+ if Gammas is not None:
407
+ gammas = tl.load(Gammas + start_m1 + offs_m, mask=mask_m, other=0.0)
408
+ else:
409
+ gammas = tl.full([BLOCK_M], 1, dtype=tl.float32)
410
+ x_scale = load_scale(XScale)
411
+ if PER_BATCH_SCALE:
412
+ w_scale = load_scale(WScale + expt_id1)
413
+ else:
414
+ w_scale = load_scale(WScale)
415
+
416
+ accs = (acc,)
417
+ biases = (bias,)
418
+
419
+ if SUBTILE_FACTOR >= 2:
420
+ acc0, acc1 = acc.reshape(BLOCK_M, 2, BLOCK_N // 2).permute(0, 2, 1).split()
421
+ accs = (acc0, acc1)
422
+ bias0, bias1 = bias.reshape(2, BLOCK_N // 2).permute(1, 0).split()
423
+ biases = (bias0, bias1)
424
+
425
+ if SUBTILE_FACTOR >= 4:
426
+ acc00, acc01 = acc0.reshape(BLOCK_M, 2, BLOCK_N // 4).permute(0, 2, 1).split()
427
+ acc10, acc11 = acc1.reshape(BLOCK_M, 2, BLOCK_N // 4).permute(0, 2, 1).split()
428
+ accs = (acc00, acc01, acc10, acc11)
429
+ bias00, bias01 = bias0.reshape(2, BLOCK_N // 4).permute(1, 0).split()
430
+ bias10, bias11 = bias1.reshape(2, BLOCK_N // 4).permute(1, 0).split()
431
+ biases = (bias00, bias01, bias10, bias11)
432
+
433
+ tl.static_assert(EPILOGUE_BLOCK_N == BLOCK_N // SUBTILE_FACTOR)
434
+ tl.static_assert(len(accs) == SUBTILE_FACTOR)
435
+
436
+ for a_i in tl.static_range(len(accs)):
437
+ acc_tile = accs[a_i]
438
+ acc_tile *= x_scale * w_scale
439
+
440
+ if SWAP_XW:
441
+ acc_tile = acc_tile.T
442
+
443
+ acc_tile = acc_tile + biases[a_i][None, :] * betas[:, None]
444
+ if out_alpha is not None:
445
+ acc_tile *= out_alpha
446
+
447
+ if ACTIVATION_FN is not None:
448
+ out = ACTIVATION_FN(acc_tile, *activation_fn_args)
449
+ tl.static_assert(out.shape[1] == OUT_BLOCK_N, f"Activation fn out.shape[1] ({out.shape[1]}) doesn't match computed OUT_BLOCK_N ({OUT_BLOCK_N})")
450
+ else:
451
+ tl.static_assert(ACTIVATION_REDUCTION_N == 1, "Activation reduction must be 1 if no activation fn is provided")
452
+ out = acc_tile
453
+
454
+ out *= gammas[:, None]
455
+
456
+ if MASK_ACC:
457
+ out = tl.where(mask_m[:, None], out, 0.0)
458
+ # Flexpoint
459
+ out_view = tl.reshape(
460
+ out, [out.numel // THREADS_PER_BLOCK, THREADS_PER_BLOCK], can_reorder=True)
461
+ local_absmax = tl.maximum(local_absmax, nan_propagating_absmax_reduce(out_view, axis=0))
462
+ out = float_to_flex(
463
+ out, YExpectedScale,
464
+ None, # ActualScale: local absmax is tracked and updated after the loop
465
+ YChecksumScale,
466
+ None, # mask: out is manually masked to 0
467
+ Y, FLEXPOINT_SATURATE_INF)
468
+ if EPILOGUE_FN is not None:
469
+ out = EPILOGUE_FN(out, *epilogue_fn_args, target_dtype=Y.dtype.element_ty, pid=len(accs)*tile_id1 + a_i)
470
+
471
+ out_off_n = off_n1 // ACTIVATION_REDUCTION_N + a_i * OUT_BLOCK_N
472
+ if USE_SCATTER_TMA:
473
+ # Convert -1 offsets to INT_MAX. We do this by clearing the leading bit. Note that
474
+ # there shouldn't be any other negative values.
475
+ offs_y_m = (offs_y_m.to(tl.uint32, bitcast=True) & 0x7FFFFFFF).to(tl.int32, bitcast=True)
476
+ y_desc.scatter(out.to(Y.dtype.element_ty), offs_y_m, out_off_n)
477
+ elif not HAS_FUSED_SCATTER and Y_USE_TMA:
478
+ y_desc.store([off_m1, out_off_n], out.to(Y.dtype.element_ty))
479
+ else:
480
+ offs_y_n = out_off_n + tl.arange(0, OUT_BLOCK_N)
481
+ mask_n = offs_y_n < yN
482
+
483
+ YPtrs = Y + pid_k1.to(index_type) * stride_y_k + start_z1.to(index_type) * stride_y_z + offs_y_m.to(index_type)[:, None] * stride_y_m + offs_y_n[None, :] * stride_y_n
484
+ mask = mask_m[:, None] & mask_n[None, :]
485
+ tl.store(YPtrs, out, mask=mask)
486
+
487
+
488
+ # Update the flexpoint scales
489
+ if YActualScale is not None:
490
+ tl.atomic_max(YActualScale, compute_scale(local_absmax.to(tl.float32, bitcast=True), Y), sem="relaxed")
491
+
492
+
493
+ _per_device_alloc_fns = {}
494
+ def get_per_device_per_stream_alloc_fn(device):
495
+ if device not in _per_device_alloc_fns:
496
+ _per_stream_tensors = {}
497
+ def alloc_fn(size: int, alignment: int, stream):
498
+ assert alignment == 128
499
+ if stream not in _per_stream_tensors or _per_stream_tensors[stream].numel() < size:
500
+ _per_stream_tensors[stream] = torch.empty(size, device=device, dtype=torch.int8)
501
+ _per_stream_tensors[stream].__hibernate__ = {"type": "ignore"}
502
+ return _per_stream_tensors[stream]
503
+
504
+ _per_device_alloc_fns[device] = alloc_fn
505
+ return _per_device_alloc_fns[device]
torch-ext/triton_kernels/matmul_ogs_details/opt_flags.py ADDED
@@ -0,0 +1,298 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # isort: off
2
+ # fmt: off
3
+ from dataclasses import dataclass
4
+ import triton
5
+ from triton_kernels.target_info import get_cdna_version
6
+ import torch
7
+ from .opt_flags_details import opt_flags_amd, opt_flags_nvidia
8
+
9
+
10
+ @dataclass
11
+ class OptFlags:
12
+ block_m: int
13
+ block_n: int
14
+ block_k: int
15
+ num_warps: int
16
+ num_stages: int
17
+ group_m: int
18
+ xcd_swizzle: int
19
+ w_cache_modifier: str
20
+ split_k: int
21
+ fused_scatter: bool
22
+ is_persistent: bool
23
+ idle_sms: int
24
+ epilogue_subtile: int | None
25
+ arch: str
26
+ target_kernel_kwargs: dict
27
+
28
+ def __post_init__(self):
29
+ if self.fused_scatter and self.split_k != 1:
30
+ raise ValueError("Not supported")
31
+
32
+
33
+
34
+ def make_default_opt_flags_amd(
35
+ out_dtype,
36
+ lhs_dtype,
37
+ rhs_dtype,
38
+ precision_config,
39
+ m,
40
+ n,
41
+ k,
42
+ routing_data,
43
+ can_use_persistent_tma,
44
+ can_use_fused_scatter,
45
+ enforce_bitwise_invariance,
46
+ epilogue_effective_itemsize,
47
+ constraints,
48
+ ):
49
+ constraints_supported = ["block_m", "block_k", "split_k", "fused_scatter", "is_persistent", "epilogue_subtile"]
50
+ assert not any([c not in constraints_supported for c in constraints]), constraints.keys()
51
+ # tokens per expert
52
+ if routing_data is None:
53
+ tokens_per_expt = m
54
+ elif routing_data.expected_tokens_per_expt is None:
55
+ tokens_per_expt = max(1, m // routing_data.n_expts_tot)
56
+ else:
57
+ tokens_per_expt = routing_data.expected_tokens_per_expt
58
+
59
+ is_cdna4 = get_cdna_version() == 4
60
+ # block_m
61
+ if constraints.get("block_m", None):
62
+ block_m = constraints["block_m"]
63
+ elif enforce_bitwise_invariance:
64
+ block_m = 256 if is_cdna4 else 128
65
+ elif tokens_per_expt >= 512 and n >= 2048:
66
+ block_m = 256 if is_cdna4 else 128
67
+ elif is_cdna4 and m >= 512:
68
+ block_m = 128
69
+ else:
70
+ block_m = max(32, min(triton.next_power_of_2(tokens_per_expt), 64))
71
+
72
+ if routing_data is not None:
73
+ grid_m = routing_data.n_blocks(m, block_m)
74
+ else:
75
+ grid_m = triton.cdiv(m, block_m)
76
+ # group_m:
77
+ group_m = 4
78
+ # number of xcds
79
+ num_xcds = 8
80
+ xcd_swizzle = num_xcds
81
+ # block_nk:
82
+ block_n, block_k = opt_flags_amd.compute_block_nk(
83
+ n, block_m, grid_m, num_xcds, lhs_dtype, rhs_dtype, precision_config
84
+ )
85
+ # Replace block_k if provided in constraints.
86
+ # TODO: Does opt_flags_amd.compute_block_nk need to be refactored?
87
+ if constraints.get("block_k", None) is not None:
88
+ block_k = constraints["block_k"]
89
+ is_persistent = constraints.get("is_persistent", False)
90
+ # split_k:
91
+ if constraints.get("split_k", None) is not None:
92
+ split_k = constraints["split_k"]
93
+ elif is_persistent or enforce_bitwise_invariance:
94
+ split_k = 1
95
+ else:
96
+ grid_size = grid_m * ((n + block_n - 1) // block_n)
97
+ n_cu = torch.cuda.get_device_properties(0).multi_processor_count
98
+ split_k = max(1, n_cu // grid_size)
99
+ # w_cache_modifier:
100
+ w_cache_modifier = ".cg" if block_m <= 32 else None
101
+ # num_warps, num_stages
102
+ num_warps = 2 if (m is not None and m <= 16) else 8
103
+ num_stages = 2
104
+ # AMD-specific
105
+ target_kernel_kwargs = {"waves_per_eu": 0, "matrix_instr_nonkdim": 16, "kpack": 1}
106
+ ret = OptFlags(
107
+ block_m=block_m,
108
+ block_n=block_n,
109
+ block_k=block_k,
110
+ num_warps=num_warps,
111
+ num_stages=num_stages,
112
+ group_m=group_m,
113
+ xcd_swizzle=xcd_swizzle,
114
+ w_cache_modifier=w_cache_modifier,
115
+ split_k=split_k,
116
+ fused_scatter=constraints.get('fused_scatter', False),
117
+ is_persistent=is_persistent,
118
+ idle_sms=0,
119
+ epilogue_subtile=constraints.get('epilogue_subtile', None),
120
+ arch=None,
121
+ target_kernel_kwargs=target_kernel_kwargs,
122
+ )
123
+ # check constraints
124
+ assert all(getattr(ret, ck) == cv for ck, cv in constraints.items() if cv is not None), f"{ret} != {constraints}"
125
+ return ret
126
+
127
+ def make_default_opt_flags_nvidia(
128
+ out_dtype,
129
+ lhs_dtype,
130
+ rhs_dtype,
131
+ precision_config,
132
+ m,
133
+ n,
134
+ k,
135
+ routing_data,
136
+ can_use_persistent_tma,
137
+ can_use_fused_scatter,
138
+ enforce_bitwise_invariance,
139
+ epilogue_effective_itemsize,
140
+ constraints,
141
+ ):
142
+ constraints_supported = ["block_m", "block_k", "split_k", "fused_scatter", "is_persistent", "epilogue_subtile", "num_stages", "idle_sms"]
143
+ assert not any([c not in constraints_supported for c in constraints]), constraints.keys()
144
+ # tokens per expert
145
+ if routing_data is None:
146
+ tokens_per_expt = m
147
+ elif routing_data.expected_tokens_per_expt is None:
148
+ tokens_per_expt = max(1, m // routing_data.n_expts_tot)
149
+ else:
150
+ tokens_per_expt = routing_data.expected_tokens_per_expt
151
+ # pid swizzling
152
+ group_m = 8
153
+ xcd_swizzle = 1
154
+ # block_m
155
+ if constraints.get("block_m", None):
156
+ block_m = constraints["block_m"]
157
+ elif enforce_bitwise_invariance:
158
+ block_m = 128
159
+ else:
160
+ min_block_m = 64 if torch.cuda.get_device_capability()[0] == 10 else 16
161
+ block_m = max(min_block_m, min(triton.next_power_of_2(tokens_per_expt), 128))
162
+ # block n
163
+ arch = None
164
+ block_n = opt_flags_nvidia.compute_block_n(n, arch, precision_config)
165
+ # is_persistent
166
+ grid_size = opt_flags_nvidia.compute_grid_size(routing_data, m, n, block_m, block_n)
167
+ n_sms = torch.cuda.get_device_properties(0).multi_processor_count
168
+ tiles_per_sm = grid_size / n_sms
169
+ supports_persistent = can_use_persistent_tma and (arch is None or int(arch[2:-1]) >= 9)
170
+ if constraints.get("is_persistent", None) is not None:
171
+ is_persistent = constraints["is_persistent"]
172
+ else:
173
+ has_simple_epilogue = precision_config.max_num_imprecise_acc is None
174
+ is_persistent = supports_persistent and has_simple_epilogue and (tiles_per_sm >= 2.0 or lhs_dtype.itemsize <= 1) and out_dtype.itemsize < 4
175
+ # TEMP CHANGE
176
+ if precision_config.act_scale is not None or precision_config.out_scale is not None:
177
+ is_persistent = False
178
+ # block k
179
+ if constraints.get("block_k", None) is not None:
180
+ block_k = constraints["block_k"]
181
+ else:
182
+ block_k = opt_flags_nvidia.compute_block_k(m, k, is_persistent, lhs_dtype, rhs_dtype, precision_config)
183
+ # split_k
184
+ if constraints.get("split_k", None) is not None:
185
+ split_k = constraints["split_k"]
186
+ elif is_persistent or enforce_bitwise_invariance or precision_config.act_scale is not None or precision_config.out_scale is not None:
187
+ split_k = 1
188
+ else:
189
+ estimated_actual_grid_size = opt_flags_nvidia.compute_grid_size(None, m, n, block_m, block_n)
190
+ split_k = opt_flags_nvidia.compute_split_k(block_k, k, estimated_actual_grid_size)
191
+ if split_k > 1:
192
+ # With split_k, results are written in f32. Use that for the following computations.
193
+ out_dtype = torch.float32
194
+ compute_num_stages_args = (
195
+ precision_config,
196
+ is_persistent,
197
+ block_m,
198
+ block_n,
199
+ block_k,
200
+ out_dtype,
201
+ lhs_dtype,
202
+ rhs_dtype,
203
+ )
204
+
205
+ if constraints.get("epilogue_subtile", None) is not None:
206
+ subtiles_to_check = [constraints["epilogue_subtile"]]
207
+ else:
208
+ subtiles_to_check = [1, 2, 4]
209
+ num_stages = -1
210
+ for ep in subtiles_to_check:
211
+ ns = opt_flags_nvidia.compute_num_stages(*compute_num_stages_args, ep, epilogue_effective_itemsize)
212
+ if ns > num_stages:
213
+ epilogue_subtile, num_stages = ep, ns
214
+ assert num_stages >= 1
215
+ if constraints.get("num_stages", None):
216
+ num_stages = constraints["num_stages"]
217
+
218
+ # fused scatter scratchpad
219
+ if constraints.get("fused_scatter", None) is not None:
220
+ fused_scatter = constraints["fused_scatter"]
221
+ else:
222
+ fused_scatter = can_use_fused_scatter and split_k == 1
223
+ # Handshake with the HBM swizzling
224
+ num_warps = opt_flags_nvidia.compute_num_warps(block_m, block_n, precision_config)
225
+ ret = OptFlags(
226
+ block_m=block_m,
227
+ block_n=block_n,
228
+ block_k=block_k,
229
+ num_warps=num_warps,
230
+ num_stages=num_stages,
231
+ group_m=group_m,
232
+ xcd_swizzle=xcd_swizzle,
233
+ w_cache_modifier=None,
234
+ split_k=split_k,
235
+ fused_scatter=fused_scatter,
236
+ is_persistent=is_persistent,
237
+ epilogue_subtile=epilogue_subtile,
238
+ arch=arch,
239
+ target_kernel_kwargs=dict(),
240
+ idle_sms=constraints.get("idle_sms", 0),
241
+ )
242
+ # check constraints
243
+ assert all(getattr(ret, ck) == cv for ck, cv in constraints.items() if cv is not None), f"{ret} != {constraints}"
244
+ return ret
245
+
246
+ # --------------
247
+ # User Interface
248
+ # --------------
249
+
250
+ _opt_flags_constraints: dict = dict()
251
+ _opt_flags: OptFlags | None = None
252
+
253
+ def update_opt_flags_constraints(constraints: dict[str, int]):
254
+ global _opt_flags_constraints
255
+ _opt_flags_constraints.update(constraints)
256
+
257
+ def reset_opt_flags_constraints():
258
+ global _opt_flags_constraints
259
+ _opt_flags_constraints = dict()
260
+
261
+ def set_opt_flags(opt_flags: OptFlags):
262
+ global _opt_flags
263
+ assert not _opt_flags_constraints, "setting constraints is incompatible with manual flags override"
264
+ assert not _opt_flags, "opt_flags already set; please reset to None first"
265
+ _opt_flags = opt_flags
266
+
267
+ class InapplicableConstraint(Exception):
268
+ pass
269
+
270
+ def make_opt_flags(
271
+ out_dtype,
272
+ lhs_dtype,
273
+ rhs_dtype,
274
+ precision_config,
275
+ m,
276
+ n,
277
+ k,
278
+ routing_data,
279
+ can_use_persistent_tma,
280
+ can_use_fused_scatter,
281
+ epilogue_effective_itemsize,
282
+ ):
283
+ if _opt_flags_constraints.get("is_persistent", False) and not can_use_persistent_tma:
284
+ raise InapplicableConstraint("cannot enforce `is_persistent=True` constraint")
285
+ enforce_bitwise_invariance = precision_config.enforce_bitwise_invariance
286
+ if _opt_flags is not None:
287
+ assert not _opt_flags_constraints
288
+ return _opt_flags
289
+ args = [out_dtype, lhs_dtype, rhs_dtype, precision_config, m, n, k,
290
+ routing_data, can_use_persistent_tma, can_use_fused_scatter,
291
+ enforce_bitwise_invariance, epilogue_effective_itemsize,
292
+ _opt_flags_constraints]
293
+ backend = triton.runtime.driver.active.get_current_target().backend
294
+ if backend == "hip":
295
+ return make_default_opt_flags_amd(*args)
296
+ if backend == "cuda":
297
+ return make_default_opt_flags_nvidia(*args)
298
+ assert False
torch-ext/triton_kernels/matmul_ogs_details/opt_flags_details/opt_flags_amd.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import triton
3
+ from triton_kernels.target_info import get_cdna_version
4
+ from triton_kernels.tensor import bitwidth
5
+
6
+
7
+ def compute_block_nk(n, block_m, grid_m, num_xcds, lhs_dtype, rhs_dtype, precision_config):
8
+ lhs_width = bitwidth(lhs_dtype) / 8
9
+ rhs_width = bitwidth(rhs_dtype) / 8
10
+
11
+ # block_n:
12
+ n_cu = torch.cuda.get_device_properties(0).multi_processor_count
13
+ if n is not None:
14
+ if n <= 128 and (n & (n - 1)) == 0:
15
+ block_n = n
16
+ else:
17
+ block_n = max(32, min(256, triton.next_power_of_2(grid_m * n * num_xcds // n_cu)))
18
+ elif block_m > 64:
19
+ block_n = 256
20
+ else:
21
+ block_n = 128
22
+
23
+ if get_cdna_version() == 4 and block_m == 128:
24
+ block_n = 512
25
+
26
+ # block_k needs to match the cacheline size (128B)
27
+ block_k = int(128 // min(lhs_width, rhs_width))
28
+
29
+ # TODO: block_k = 128 seems to work better for now.
30
+ # perhaps due to increased number of k loops to pipeline
31
+ if precision_config.weight_scale is not None and get_cdna_version() != 4:
32
+ block_k = 128
33
+ return block_n, block_k
torch-ext/triton_kernels/matmul_ogs_details/opt_flags_details/opt_flags_nvidia.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import triton
3
+ from triton_kernels import target_info
4
+ from triton_kernels.tensor import get_layout, bitwidth, FP4
5
+ from triton_kernels.tensor_details.layout import HopperMXScaleLayout
6
+ from triton_kernels.numerics_details.mxfp_details._downcast_to_mxfp import MXFP_BLOCK_SIZE
7
+
8
+
9
+ def compute_grid_size(routing_data, m, n, block_m, block_n):
10
+ if routing_data is not None:
11
+ grid_m = routing_data.n_blocks(m, block_m)
12
+ else:
13
+ grid_m = triton.cdiv(m, block_m)
14
+ grid_n = (n + block_n - 1) // block_n
15
+ return grid_m * grid_n
16
+
17
+
18
+ def compute_block_n(n: int, arch, precision_config):
19
+ # block_n:
20
+ layout = get_layout(precision_config.weight_scale)
21
+ if isinstance(layout, HopperMXScaleLayout) and layout.num_warps == 4:
22
+ return 128
23
+ elif precision_config.max_num_imprecise_acc is None and n > 128:
24
+ return 256
25
+ else:
26
+ return max(16, min(128, triton.next_power_of_2(n)))
27
+
28
+
29
+ def compute_block_k(m: int, k: int | None, is_persistent: bool, lhs_dtype, rhs_dtype, precision_config):
30
+ lhs_width = bitwidth(lhs_dtype)
31
+ rhs_width = bitwidth(rhs_dtype)
32
+ # block_k needs to match the cacheline size (1024 bits)
33
+ block_k = int(1024 // min(lhs_width, rhs_width))
34
+ has_native_mxfp = target_info.cuda_capability_geq(10, 0)
35
+ if rhs_width == 4 and not has_native_mxfp:
36
+ block_k = 128
37
+ elif k is not None:
38
+ block_k = max(32, min(triton.next_power_of_2(k), block_k))
39
+ has_mx_weight_scale = precision_config is not None and precision_config.weight_scale is not None
40
+ if has_native_mxfp and is_persistent and has_mx_weight_scale:
41
+ block_k = min(block_k, 128)
42
+ return block_k
43
+
44
+
45
+ def compute_split_k(block_k: int, k: int | None, grid_size: int) -> int:
46
+ device_props = torch.cuda.get_device_properties(0)
47
+ n_sms = device_props.multi_processor_count
48
+ split_k = n_sms // grid_size
49
+ if k is not None:
50
+ # avoid split_k for small k
51
+ num_block_k = triton.cdiv(k, block_k)
52
+ split_k = min(split_k, num_block_k // 4)
53
+ split_k = max(split_k, 1)
54
+ return split_k
55
+
56
+
57
+ def compute_num_warps(block_m, block_n, precision_config):
58
+ layout = get_layout(precision_config.weight_scale)
59
+ if isinstance(layout, HopperMXScaleLayout):
60
+ return layout.num_warps
61
+ return max(block_m * block_n // 4096, 4)
62
+
63
+
64
+ def compute_num_stages(
65
+ precision_config,
66
+ is_persistent,
67
+ block_m,
68
+ block_n,
69
+ block_k,
70
+ out_dtype,
71
+ lhs_dtype,
72
+ rhs_dtype,
73
+ epilogue_subtile,
74
+ epilogue_effective_itemsize,
75
+ ):
76
+ if precision_config.max_num_imprecise_acc is not None:
77
+ return 3
78
+ weight_size = bitwidth(rhs_dtype) / 8
79
+ stage_size = block_m * block_k * lhs_dtype.itemsize + block_k * block_n * weight_size
80
+ device_props = torch.cuda.get_device_properties(0)
81
+ smem_capacity = device_props.shared_memory_per_block_optin
82
+ has_native_mxfp = target_info.cuda_capability_geq(10, 0)
83
+ if has_native_mxfp and getattr(precision_config, "weight_scale", None) is not None:
84
+ if rhs_dtype == FP4:
85
+ # 4-bit e2m1 weights are padded 2x
86
+ # https://docs.nvidia.com/cuda/parallel-thread-execution/#packing-format-used-for-matrix-a-and-b-by-kind-mxf8f6f4-in-shared-memory
87
+ stage_size += block_k * block_n * weight_size
88
+
89
+ if is_persistent:
90
+ # Per-stage wait barrier
91
+ stage_size += 8
92
+ if target_info.cuda_capability_geq(10, 0):
93
+ acc_size = epilogue_effective_itemsize or out_dtype.itemsize
94
+ else:
95
+ acc_size = out_dtype.itemsize
96
+ if target_info.cuda_capability_geq(10, 0) and epilogue_subtile is not None:
97
+ acc_block_n = block_n // epilogue_subtile
98
+ else:
99
+ acc_block_n = block_n
100
+ # pipelined TMA store local to global, or
101
+ # pipelined layout conversion before store of the accumulator
102
+ # note: layout conversion has some padding
103
+ smem_capacity -= int((block_m + 4) * acc_block_n * acc_size)
104
+ if precision_config.weight_scale is not None:
105
+ # mx scales
106
+ stage_size += block_n * (block_k // int(MXFP_BLOCK_SIZE))
107
+ elif has_native_mxfp:
108
+ # mx scales
109
+ stage_size += block_n * (block_k // int(MXFP_BLOCK_SIZE))
110
+ num_stages = min(4, smem_capacity // int(stage_size))
111
+ return num_stages
torch-ext/triton_kernels/numerics.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from dataclasses import dataclass
3
+
4
+ MAX_FINITE_FLOAT8E5 = 57344.0
5
+ MAX_FINITE_FLOAT8E4NV = 448.0
6
+ MAX_FINITE_FLOAT8E4B8 = 240.0
7
+
8
+
9
+ @dataclass(frozen=True)
10
+ class BaseFlexData:
11
+ dtype: torch.dtype | None = None
12
+
13
+ def view(self, x: torch.Tensor):
14
+ if self.dtype is None:
15
+ return x
16
+ return x.view(self.dtype)
17
+
18
+ def reinterpret(self, x):
19
+ if self.dtype is None or x.dtype.itemsize > 1:
20
+ return x
21
+ return x.view(self.dtype)
22
+
23
+
24
+ @dataclass(frozen=True)
25
+ class InFlexData(BaseFlexData):
26
+ scale: torch.Tensor | None = None
27
+
28
+ @property
29
+ def is_per_batch(self):
30
+ return False if self.scale is None else len(self.scale) > 1
31
+
32
+
33
+ @dataclass(frozen=True)
34
+ class OutFlexData(BaseFlexData):
35
+ expected_scale: torch.Tensor | None = None
36
+ actual_scale: torch.Tensor | None = None
37
+ checksum_scale: torch.Tensor | None = None
38
+
39
+ def __iter__(self):
40
+ yield self.expected_scale
41
+ yield self.actual_scale
42
+ yield self.checksum_scale
torch-ext/triton_kernels/numerics_details/__init__.py ADDED
File without changes