Draft
[WIP]Draft: feat(ops): add runtime-bound grouped linear for MoonEP integration #367
[WIP]Draft: feat(ops): add runtime-bound grouped linear for MoonEP integration #367
Draft
Jia_AustinAdd on 24 days ago
Total: 4 files changed+738-0
@@ -0,0 +1,428 @@
1+"""Host contracts with real op/fuser source and inert tensor/native stubs.
2+ 
3+No CPU/NPU numerical or installation claim is made. Stub tensor math below is
4+only for dtype/shape and call-order observation, never a grouped-GEMM oracle.
5+"""
6+ 
7+import dataclasses
8+import importlib.util
9+from pathlib import Path
10+import sys
11+import types
12+import unittest
13+ 
14+ROOT = Path(__file__).resolve().parents[2] / "transformer_engine/pytorch"
15+ 
16+ 
17+class Tensor:
18+ serial = 1024
19+ 
20+ def __init__(self, shape, dtype="bf16", pointer=None):
21+ self.shape, self.dtype, self.device = tuple(shape), dtype, "npu:0"
22+ self._version, self.requires_grad, self.contiguous = 0, True, True
23+ Tensor.serial += 100000
24+ self.pointer = Tensor.serial if pointer is None else pointer
25+ 
26+ @property
27+ def ndim(self):
28+ return len(self.shape)
29+ 
30+ def numel(self):
31+ result = 1
32+ for n in self.shape:
33+ result *= n
34+ return result
35+ 
36+ def element_size(self):
37+ return 2 if self.dtype == "bf16" else 4
38+ 
39+ def data_ptr(self):
40+ return self.pointer
41+ 
42+ def storage_offset(self):
43+ return 0
44+ 
45+ def stride(self):
46+ values, step = [], 1
47+ for value in reversed(self.shape):
48+ values.append(step)
49+ step *= value
50+ return tuple(reversed(values))
51+ 
52+ def is_contiguous(self):
53+ return self.contiguous
54+ 
55+ def is_neg(self):
56+ return False
57+ 
58+ def is_conj(self):
59+ return False
60+ 
61+ def is_floating_point(self):
62+ return True
63+ 
64+ def requires_grad_(self, value):
65+ self.requires_grad = value
66+ return self
67+ 
68+ def detach(self):
69+ result = Tensor(self.shape, self.dtype, pointer=self.pointer)
70+ result.requires_grad = False
71+ result._version = self._version
72+ return result
73+ 
74+ def float(self):
75+ return Tensor(self.shape, "fp32")
76+ 
77+ def to(self, dtype):
78+ return Tensor(self.shape, dtype)
79+ 
80+ def __getitem__(self, _):
81+ return Tensor((*self.shape, 1), self.dtype)
82+ 
83+ def __mul__(self, other):
84+ return Tensor(self.shape, self.dtype)
85+ 
86+ 
87+class Module:
88+ def __init__(self):
89+ self._parameters = {}
90+ 
91+ def register_parameter(self, name, value):
92+ self._parameters[name] = value
93+ setattr(self, name, value)
94+ 
95+ def parameters(self):
96+ return iter(v for v in self._parameters.values() if v is not None)
97+ 
98+ 
99+def package(name, **attrs):
100+ value = types.ModuleType(name)
101+ value.__path__ = []
102+ value.__dict__.update(attrs)
103+ sys.modules[name] = value
104+ return value
105+ 
106+ 
107+def load(name, relative):
108+ spec = importlib.util.spec_from_file_location(name, ROOT / relative)
109+ module = importlib.util.module_from_spec(spec)
110+ sys.modules[name] = module
111+ spec.loader.exec_module(module)
112+ return module
113+ 
114+ 
115+def fixture():
116+ for name in ("transformer_engine", "transformer_engine.common", "transformer_engine.pytorch",
117+ "transformer_engine.pytorch.ops", "transformer_engine.pytorch.ops.basic"):
118+ package(name)
119+ torch = package("torch", Tensor=Tensor, bfloat16="bf16", float32="fp32", int64="int64",
120+ is_grad_enabled=lambda: False)
121+ torch.nn = types.SimpleNamespace(Module=Module, Parameter=lambda x: x)
122+ torch.empty = lambda shape, **kw: Tensor(shape, kw.get("dtype", "bf16"))
123+ torch.mul = lambda x, y, out: out
124+ torch.no_grad = lambda: lambda function: function
125+ torch.autograd = types.SimpleNamespace(Function=object,
126+ function=types.SimpleNamespace(once_differentiable=lambda f: f))
127+ package("transformer_engine.common.recipe", Recipe=object)
128+ package("transformer_engine.pytorch.quantization", Recipe=object, QuantizerRole=object,
129+ RecipeState=object, autocast=lambda *a, **kw: None,
130+ FP8GlobalStateManager=types.SimpleNamespace(is_first_fp8_module=lambda: False))
131+ package("transformer_engine.pytorch.tensor", Quantizer=object,
132+ Float8CurrentScalingQuantizer=object)
133+ package("transformer_engine.pytorch.quantized_tensor",
134+ prepare_for_saving=lambda *t: (t, None), restore_from_func_ctx=lambda ctx: ctx.saved_tensors)
135+ op = load("transformer_engine.pytorch.ops.op", "ops/op.py")
136+ grouped = load("transformer_engine.pytorch.ops.basic.grouped_linear", "ops/basic/grouped_linear.py")
137+ package("transformer_engine.pytorch.ops.basic.activation", ClampedSwiGLU=object)
138+ package("transformer_engine.pytorch.ops.basic.npu_activation",
139+ swiglu_fwd=lambda x: Tensor((x.shape[0], x.shape[1] // 2)),
140+ swiglu_bwd=lambda x, dy: Tensor(x.shape))
141+ package("transformer_engine.pytorch.cpu_offload", is_cpu_offload_enabled=lambda: False,
142+ mark_activation_offload=lambda *x: None)
143+ package("transformer_engine.pytorch.utils", clear_tensor_data=lambda x: None)
144+ package("transformer_engine.pytorch.ops._common", maybe_dequantize=lambda x, dtype: x)
145+ activation = load("transformer_engine.pytorch.ops.basic.swiglu", "ops/basic/swiglu.py")
146+ fuser = load("transformer_engine.pytorch.ops.fuser", "ops/fuser.py")
147+ return op, grouped, activation, fuser
148+ 
149+ 
150+class Contracts(unittest.TestCase):
151+ def setUp(self):
152+ self.old_modules = dict(sys.modules)
153+ self.op, self.g, self.activation, self.fuser = fixture()
154+ self.trace = []
155+ self.failures = []
156+ def mark_failed(*, error, resources):
157+ self.trace.append("poison")
158+ self.failures.append((error, resources))
159+ self.owner._native_async_failed = True
160+ self.owner._native_async_uncertain += resources
161+ self.owner = types.SimpleNamespace(mark_failed=mark_failed,
162+ _native_async_failed=False, _native_async_uncertain=())
163+ self.node = self.g.GroupedLinear(2, 4, 6)
164+ refs = tuple(Tensor((6, 4)) for _ in range(2))
165+ for i, ref in enumerate(refs):
166+ self.node.register_parameter(f"weight{i}", ref)
167+ self.x, self.dy = Tensor((3, 4)), Tensor((3, 6))
168+ self.spec = self.g.RuntimeLinearSpec((1, 0, 0, 0), 0, Tensor((2,), "int64"),
169+ Tensor((2,), "int64"), Tensor((3,), "bool"), refs, Tensor((3, 6)),
170+ Tensor((3, 4)), Tensor((2, 6, 4), "fp32"), lambda: self.x,
171+ lambda *x: self.trace.append("publish"), self.owner,
172+ lambda *x, **kw: self.trace.append("forward" if kw["transpose_weights"] else "dgrad"),
173+ lambda *x: self.trace.append("producer"))
174+ 
175+ def tearDown(self):
176+ for name in list(sys.modules):
177+ if name not in self.old_modules:
178+ del sys.modules[name]
179+ sys.modules.update(self.old_modules)
180+ 
181+ def forward(self, spec=None):
182+ ctx = self.op.OperationContext()
183+ self.node.op_forward(ctx, self.x, runtime_spec=spec or self.spec)
184+ ctx.saved_tensors = ctx.to_save
185+ return ctx
186+ 
187+ def test_spec_is_immutable_and_fc1_does_not_save_dispatched_x(self):
188+ ctx = self.forward()
189+ self.assertEqual(ctx.saved_tensors, ())
190+ with self.assertRaises(dataclasses.FrozenInstanceError):
191+ self.spec.projection = 1
192+ 
193+ def test_fc2_saves_necessary_input_and_returns_no_runtime_parameter_grads(self):
194+ ctx = self.forward(dataclasses.replace(self.spec, acquire_wgrad_input=None))
195+ self.assertEqual(ctx.saved_tensors, (self.x,))
196+ dx, grads = self.node.op_backward(ctx, self.dy)
197+ self.assertIs(dx, self.spec.grad_input_output)
198+ self.assertEqual(grads, (None, None))
199+ self.assertIsNone(ctx.runtime_spec)
200+ self.assertEqual(ctx.weights, ())
201+ self.assertEqual(self.trace, ["forward", "dgrad", "producer", "publish"])
202+ 
203+ def test_gpu_style_wgrad_store_runs_real_producer_before_gr(self):
204+ def put(tensors, gemm):
205+ gemm(*tensors)
206+ self.trace.append("GR")
207+ self.node.wgrad_store = types.SimpleNamespace(put=put, delay_wgrad_compute=lambda: True)
208+ self.node.op_backward(self.forward(), self.dy)
209+ self.assertEqual(self.trace, ["forward", "dgrad", "producer", "publish", "GR"])
210+ 
211+ def test_missing_or_inactive_wgrad_store_protocol_rejects_before_math(self):
212+ for store in (types.SimpleNamespace(put=lambda *args: None),
213+ types.SimpleNamespace(put=lambda *args: None,
214+ delay_wgrad_compute=lambda: False)):
215+ self.trace.clear()
216+ self.node.wgrad_store = store
217+ with self.assertRaises(ValueError):
218+ self.forward()
219+ self.assertEqual(self.trace, ["poison"])
220+ 
221+ def test_deferred_store_and_double_producer_fail_closed(self):
222+ for put in (lambda tensors, gemm: None,
223+ lambda tensors, gemm: (gemm(*tensors), gemm(*tensors))):
224+ self.node.wgrad_store = types.SimpleNamespace(put=put, delay_wgrad_compute=lambda: True)
225+ with self.assertRaises(RuntimeError):
226+ self.node.op_backward(self.forward(), self.dy)
227+ self.assertEqual(self.trace[-1], "poison")
228+ 
229+ def test_repeated_backward_and_changed_binding_poison(self):
230+ ctx = self.forward()
231+ self.node.op_backward(ctx, self.dy)
232+ with self.assertRaises(RuntimeError):
233+ self.node.op_backward(ctx, self.dy)
234+ ctx = self.forward()
235+ self.spec.weight_refs[0].pointer += 4
236+ with self.assertRaises(RuntimeError):
237+ self.node.op_backward(ctx, self.dy)
238+ 
239+ def test_remote_refill_version_is_not_a_canonical_version(self):
240+ ctx = self.forward()
241+ for ref in self.spec.weight_refs:
242+ ref._version += 1
243+ self.node.op_backward(ctx, self.dy)
244+ self.assertNotIn("poison", self.trace)
245+ 
246+ def test_alias_layout_and_missing_runtime_spec_reject(self):
247+ with self.assertRaises(ValueError):
248+ self.node.op_forward(self.op.OperationContext(), self.x)
249+ for spec in (dataclasses.replace(self.spec, output=Tensor((3, 6), pointer=self.x.pointer)),
250+ dataclasses.replace(self.spec, weight_refs=())):
251+ with self.assertRaises(ValueError):
252+ self.forward(spec)
253+ 
254+ def test_actual_existing_fuser_forward_backward_dispatches_grouped_node(self):
255+ f = self.fuser.OperationFuser([self.node])
256+ f._forward_ops = f._backward_ops = [(self.node, [0])]
257+ ctx = types.SimpleNamespace(save_for_backward=lambda *t: setattr(ctx, "saved_tensors", t))
258+ result = self.fuser._OperationFuserAutogradFunction.forward(
259+ ctx, self.x, f, [{"runtime_spec": self.spec}], False, *f._flat_basic_op_params)
260+ self.assertIs(result, self.spec.output)
261+ gradients = self.fuser._OperationFuserAutogradFunction.backward(ctx, self.dy)
262+ self.assertEqual(gradients[4:], (None, None))
263+ self.assertEqual(self.trace, ["forward", "dgrad", "producer", "publish"])
264+ 
265+ def test_actual_fuser_full_fc1_scaled_swiglu_fc2_chain(self):
266+ fc1, fc2, act = self.g.GroupedLinear(2, 4, 8), self.g.GroupedLinear(2, 4, 4), self.activation.ScaledSwiGLU()
267+ refs1, refs2 = tuple(Tensor((8, 4)) for _ in range(2)), tuple(Tensor((4, 4)) for _ in range(2))
268+ for op, refs in ((fc1, refs1), (fc2, refs2)):
269+ for i, ref in enumerate(refs):
270+ op.register_parameter(f"weight{i}", ref)
271+ linear = lambda *a, **kw: self.trace.append("fwd" if kw["transpose_weights"] else "dx")
272+ s1 = dataclasses.replace(self.spec, weight_refs=refs1, output=Tensor((3, 8)),
273+ wgrad_scratch=Tensor((2, 8, 4), "fp32"), linear_out=linear)
274+ s2 = dataclasses.replace(self.spec, projection=1, weight_refs=refs2,
275+ output=Tensor((3, 4)), wgrad_scratch=Tensor((2, 4, 4), "fp32"),
276+ acquire_wgrad_input=None, linear_out=linear)
277+ sa = self.g.RuntimeActivationSpec(Tensor((3, 4)), Tensor((3,), "fp32"), self.owner,
278+ lambda *a: self.trace.append("dp"))
279+ fc2.wgrad_store = types.SimpleNamespace(
280+ put=lambda tensors, fn: (fn(*tensors), self.trace.append("GR2")),
281+ delay_wgrad_compute=lambda: True)
282+ f = self.fuser.OperationFuser([fc1, act, fc2])
283+ f._forward_ops = f._backward_ops = [(op, [i]) for i, op in enumerate((fc1, act, fc2))]
284+ ctx = types.SimpleNamespace(save_for_backward=lambda *t: setattr(ctx, "saved_tensors", t))
285+ self.fuser._OperationFuserAutogradFunction.forward(ctx, self.x, f,
286+ [{"runtime_spec": s1}, {"runtime_spec": sa}, {"runtime_spec": s2}], False,
287+ *f._flat_basic_op_params, Tensor((3,), "fp32"))
288+ result = self.fuser._OperationFuserAutogradFunction.backward(ctx, Tensor((3, 4)))
289+ self.assertEqual(result[4:8], (None, None, None, None))
290+ self.assertIs(result[8], sa.probability_grad_output)
291+ self.assertEqual(self.trace, ["fwd", "fwd", "dx", "producer", "publish", "GR2", "dp",
292+ "dx", "producer", "publish"])
293+ self.assertTrue(all(c.runtime_spec is None and c.saved_tensors is None
294+ for c in ctx.basic_op_ctxs))
295+ 
296+ def test_fp32_activation_profile_uses_direct_reduce_and_native_backward(self):
297+ node = self.activation.ScaledSwiGLU()
298+ x, p = Tensor((3, 8)), Tensor((3,), "fp32")
299+ out, dp = Tensor((3, 4)), Tensor((3,), "fp32")
300+ spec = self.g.RuntimeActivationSpec(out, dp, self.owner,
301+ lambda owner, product, dest: self.trace.append((product.dtype, dest is dp)))
302+ ctx = self.op.OperationContext()
303+ value, _ = node.fuser_forward([ctx], x, basic_op_extra_inputs=[(p,)],
304+ prev_op_grad_output_quantizer=None, next_op_input_quantizer=None,
305+ basic_op_kwargs=[{"runtime_spec": spec}])
306+ self.assertIs(value, out)
307+ self.assertIs(ctx.to_save[1], p)
308+ ctx.saved_tensors = ctx.to_save
309+ dx, params, extra = node.fuser_backward([ctx], Tensor((3, 4)),
310+ basic_op_grad_extra_outputs=[()])
311+ self.assertEqual(dx.shape, x.shape)
312+ self.assertEqual(params, [()])
313+ self.assertIs(extra[0][0], dp)
314+ self.assertEqual(self.trace, [("fp32", True)])
315+ self.assertIsNone(ctx.runtime_spec)
316+ with self.assertRaises(RuntimeError):
317+ node.fuser_backward([ctx], Tensor((3, 4)), basic_op_grad_extra_outputs=[()])
318+ 
319+ def test_unsupported_constructor_and_bad_gradient_reject(self):
320+ for kwargs in ({"bias": True}, {"single_grouped_weight": True},
321+ {"delay_wgrad_compute": True}, {"device": "npu"}):
322+ with self.assertRaises(ValueError):
323+ self.g.GroupedLinear(2, 4, 6, **kwargs)
324+ ctx = self.forward()
325+ with self.assertRaises(ValueError):
326+ self.node.op_backward(ctx, Tensor((3, 6), "fp32"))
327+ self.assertEqual(self.trace[-1], "poison")
328+ 
329+ def test_legacy_owner_is_rejected_before_any_mathematics(self):
330+ legacy = types.SimpleNamespace(poison_and_retain=lambda: self.trace.append('legacy'))
331+ with self.assertRaisesRegex(TypeError, 'Buffer.mark_failed'):
332+ self.forward(dataclasses.replace(self.spec, operation_owner=legacy))
333+ self.assertEqual(self.trace, [])
334+ 
335+ def test_grouped_forward_failure_keeps_pre_context_inputs_and_actual_error(self):
336+ ctx = self.op.OperationContext()
337+ bad = dataclasses.replace(self.spec, output=Tensor((3, 6), pointer=self.x.pointer))
338+ with self.assertRaises(ValueError) as raised:
339+ self.node.op_forward(ctx, self.x, runtime_spec=bad)
340+ error, resources = self.failures[-1]
341+ self.assertIs(error, raised.exception)
342+ for value in (ctx, bad, self.x, error):
343+ self.assertIn(value, resources)
344+ 
345+ def test_grouped_producer_failure_keeps_exact_r1_source(self):
346+ source = Tensor((3, 4))
347+ error = RuntimeError('producer failed after R1')
348+ def fail(*args):
349+ raise error
350+ spec = dataclasses.replace(self.spec, acquire_wgrad_input=lambda: source,
351+ wgrad_producer=fail)
352+ ctx = self.forward(spec)
353+ with self.assertRaises(RuntimeError) as raised:
354+ self.node.op_backward(ctx, self.dy)
355+ self.assertIs(raised.exception, error)
356+ for value in (ctx, spec, source, self.dy, error):
357+ self.assertIn(value, self.failures[-1][1])
358+ 
359+ def activation_case(self):
360+ node = self.activation.ScaledSwiGLU()
361+ x, p = Tensor((3, 8)), Tensor((3,), 'fp32')
362+ spec = self.g.RuntimeActivationSpec(Tensor((3, 4)), Tensor((3,), 'fp32'),
363+ self.owner, lambda *args: None)
364+ ctx = self.op.OperationContext()
365+ return node, ctx, x, p, spec
366+ 
367+ def test_activation_failure_keeps_unsaved_forward_temporary(self):
368+ node, ctx, x, p, spec = self.activation_case()
369+ error, seen = RuntimeError('probability product failed'), []
370+ def fail(left, right, *, out):
371+ seen.append(left)
372+ raise error
373+ sys.modules['torch'].mul = fail
374+ with self.assertRaises(RuntimeError) as raised:
375+ node._runtime_forward(ctx, x, p, spec, None, None)
376+ self.assertIs(raised.exception, error)
377+ for value in (ctx, spec, x, p, seen[0], error):
378+ self.assertIn(value, self.failures[-1][1])
379+ self.assertEqual(seen[0].dtype, 'fp32')
380+ 
381+ def test_activation_backward_failure_keeps_product_and_da_at_their_boundaries(self):
382+ for phase in ('reduce', 'activation'):
383+ with self.subTest(phase=phase):
384+ node, ctx, x, p, spec = self.activation_case()
385+ error, seen = RuntimeError('injected ' + phase), []
386+ def fail_reduce(owner, product, out):
387+ if phase == 'reduce':
388+ seen.append(product)
389+ raise error
390+ def fail_activation(da, value):
391+ seen.append(da)
392+ raise error
393+ spec = dataclasses.replace(spec, reduce_sum_out=fail_reduce)
394+ node._runtime_forward(ctx, x, p, spec, None, None)
395+ ctx.saved_tensors = ctx.to_save
396+ if phase == 'activation':
397+ node._glu_backward = fail_activation
398+ grad_output = Tensor((3, 4))
399+ with self.assertRaises(RuntimeError) as raised:
400+ node._runtime_backward(ctx, grad_output)
401+ self.assertIs(raised.exception, error)
402+ for value in (ctx, spec, x, p, grad_output, seen[0], error):
403+ self.assertIn(value, self.failures[-1][1])
404+ self.assertEqual(seen[0].dtype, 'fp32' if phase == 'reduce' else 'bf16')
405+ 
406+ def test_higher_order_rejection_preserves_original_runtime_error(self):
407+ ctx = self.forward()
408+ sys.modules['torch'].is_grad_enabled = lambda: True
409+ with self.assertRaisesRegex(RuntimeError, 'higher-order') as raised:
410+ self.node.op_backward(ctx, self.dy)
411+ self.assertIs(self.failures[-1][0], raised.exception)
412+ self.assertNotIsInstance(raised.exception, AttributeError)
413+ 
414+ def test_marker_failure_uses_existing_quarantine_without_losing_old_resources(self):
415+ old, current = object(), object()
416+ self.owner._native_async_uncertain = (old,)
417+ def broken_marker(**kwargs):
418+ raise RuntimeError('marker failed')
419+ self.owner.mark_failed = broken_marker
420+ error = RuntimeError('original failure')
421+ self.g._mark_runtime_failed(self.owner, error, current)
422+ self.assertTrue(self.owner._native_async_failed)
423+ self.assertEqual(self.owner._native_async_uncertain, (old, error, current))
424+ self.assertTrue(any('existing quarantine' in note for note in error.__notes__))
425+ 
426+ 
427+if __name__ == "__main__":
428+ unittest.main()
@@ -18,6 +18,7 @@ from .quantize import Quantize
18from .reduce_scatter import ReduceScatter18from .reduce_scatter import ReduceScatter
19from .reshape import Reshape19from .reshape import Reshape
20from .rmsnorm import RMSNorm20from .rmsnorm import RMSNorm
21+from .grouped_linear import GroupedLinear, RuntimeLinearSpec, RuntimeActivationSpec
21 22 
22from .activation import (23from .activation import (
23 _ActivationOperation,24 _ActivationOperation,
@@ -37,6 +38,9 @@ from .activation import (
37from .swiglu import SwiGLU, ScaledSwiGLU, ScaledClampedQGeGLU38from .swiglu import SwiGLU, ScaledSwiGLU, ScaledClampedQGeGLU
38 39 
39__all__ = [40__all__ = [
41+ "GroupedLinear",
42+ "RuntimeLinearSpec",
43+ "RuntimeActivationSpec",
40 "AddExtraInput",44 "AddExtraInput",
41 "AllGather",45 "AllGather",
42 "AllReduce",46 "AllReduce",
@@ -0,0 +1,226 @@
1+# Copyright (c) 2026, Huawei Technologies Co., Ltd. All rights reserved.
2+# See LICENSE for license information.
3+ 
4+"""BF16 grouped linear node for the existing operation fuser.
5+ 
6+The embedding framework supplies audited compute functions and operation
7+resources. This module owns mathematical context, never transport or native
8+memory completion. Runtime leaves have no canonical DDP hooks.
9+"""
10+ 
11+from __future__ import annotations
12+ 
13+from dataclasses import dataclass
14+from typing import Callable
15+ 
16+import torch
17+ 
18+from ..op import BasicOperation, OperationContext
19+ 
20+ 
21+@dataclass(frozen=True)
22+class RuntimeLinearSpec:
23+ """One call's borrowed operands, destinations and platform functions."""
24+ 
25+ call_identity: tuple
26+ projection: int
27+ counts: torch.Tensor
28+ prefix: torch.Tensor
29+ padding: torch.Tensor
30+ weight_refs: tuple
31+ output: torch.Tensor
32+ grad_input_output: torch.Tensor
33+ wgrad_scratch: torch.Tensor
34+ acquire_wgrad_input: Callable | None
35+ publish_wgrad: Callable
36+ operation_owner: object
37+ linear_out: Callable
38+ wgrad_producer: Callable
39+ 
40+ 
41+@dataclass(frozen=True)
42+class RuntimeActivationSpec:
43+ """Explicit destinations for the FP32-probability activation profile."""
44+ 
45+ output: torch.Tensor
46+ probability_grad_output: torch.Tensor
47+ operation_owner: object
48+ reduce_sum_out: Callable
49+ 
50+ 
51+def _matrix(tensor, shape, dtype, device):
52+ if (not isinstance(tensor, torch.Tensor) or tuple(tensor.shape) != tuple(shape)
53+ or tensor.dtype != dtype or tensor.device != device or not tensor.is_contiguous()
54+ or tensor.is_neg() or tensor.is_conj()):
55+ raise ValueError("runtime grouped linear requires declared contiguous tensor metadata")
56+ 
57+ 
58+def _disjoint(destination, *sources):
59+ begin = destination.data_ptr()
60+ end = begin + destination.numel() * destination.element_size()
61+ for source in sources:
62+ start = source.data_ptr()
63+ stop = start + source.numel() * source.element_size()
64+ if begin < stop and start < end:
65+ raise ValueError("runtime output overlaps an input")
66+ 
67+ 
68+def _binding_identity(tensor):
69+ return (tensor.data_ptr(), tensor.storage_offset(), tuple(tensor.shape),
70+ tuple(tensor.stride()), tensor.dtype, tensor.device)
71+ 
72+ 
73+def _require_failure_owner(owner):
74+ if not callable(getattr(owner, "mark_failed", None)):
75+ raise TypeError("runtime operation owner must expose Buffer.mark_failed")
76+ 
77+ 
78+def _mark_runtime_failed(owner, error, *resources):
79+ """Keep the original exception and uncertain resources in the provider."""
80+ retained = (error, *resources)
81+ combined = (*getattr(owner, "_native_async_uncertain", ()), *retained)
82+ try:
83+ # The exception retains nested Python frames too, including temporaries
84+ # from a mathematical primitive that raised before returning its Tensor.
85+ owner.mark_failed(error=error, resources=retained)
86+ except BaseException as failure:
87+ # PR19's existing Buffer owns these quarantine fields. Reuse the
88+ # prebuilt tuple if its public marker itself fails; never mask error.
89+ try:
90+ owner._native_async_failed = True
91+ owner._native_async_uncertain = combined
92+ note = "Buffer.mark_failed raised; resources retained in its existing quarantine"
93+ except BaseException:
94+ note = "Buffer.mark_failed and quarantine failed; retention is unproven"
95+ annotate = getattr(error, "add_note", None)
96+ if callable(annotate):
97+ try:
98+ annotate(note + ": " + repr(failure))
99+ except BaseException:
100+ pass # Even annotation/OOM failure must preserve the original exception.
101+ 
102+ 
103+class GroupedLinear(BasicOperation):
104+ """Single-token/list-weight/single-out grouped operation, default unusable.
105+ 
106+ Meta parameters are replaced by borrowed runtime leaves before constructing
107+ Sequential's fuser. Every invocation requires an immutable runtime spec.
108+ """
109+ 
110+ def __init__(self, num_gemms, in_features, out_features, *, bias=False,
111+ device="meta", dtype=torch.bfloat16, accumulate_into_main_grad=True,
112+ single_grouped_weight=False, single_grouped_bias=False,
113+ delay_wgrad_compute=False):
114+ super().__init__()
115+ if (type(num_gemms) is not int or not 1 <= num_gemms <= 128
116+ or any(type(v) is not int or v <= 0 for v in (in_features, out_features))
117+ or bias or str(device) != "meta" or dtype != torch.bfloat16
118+ or accumulate_into_main_grad is not True or single_grouped_weight
119+ or single_grouped_bias or delay_wgrad_compute):
120+ raise ValueError("only explicit ordinary BF16 per-expert meta shells are supported")
121+ self.num_gemms, self.in_features, self.out_features = num_gemms, in_features, out_features
122+ self.wgrad_store = None
123+ for index in range(num_gemms):
124+ self.register_parameter(f"weight{index}", torch.nn.Parameter(
125+ torch.empty((out_features, in_features), device="meta", dtype=dtype)))
126+ 
127+ def op_forward(self, ctx: OperationContext, input_, *,
128+ prev_op_grad_output_quantizer=None, next_op_input_quantizer=None,
129+ runtime_spec=None):
130+ if (not isinstance(runtime_spec, RuntimeLinearSpec)
131+ or prev_op_grad_output_quantizer is not None
132+ or next_op_input_quantizer is not None):
133+ raise ValueError("an explicit unquantized runtime grouped spec is required")
134+ spec = runtime_spec
135+ _require_failure_owner(spec.operation_owner)
136+ try:
137+ if self.wgrad_store is not None:
138+ delayed = getattr(self.wgrad_store, "delay_wgrad_compute", None)
139+ if not callable(delayed) or delayed() is not True:
140+ raise ValueError("runtime wgrad store must implement the delayed producer protocol")
141+ weights = tuple(getattr(self, f"weight{i}") for i in range(self.num_gemms))
142+ registered = tuple(self.parameters())
143+ if (len(registered) != len(weights)
144+ or any(a is not b for a, b in zip(registered, weights))
145+ or len(spec.weight_refs) != self.num_gemms):
146+ raise ValueError("runtime leaves must be exactly the registered grouped operands")
147+ _matrix(input_, (spec.output.shape[0], self.in_features), torch.bfloat16, input_.device)
148+ _matrix(spec.output, (input_.shape[0], self.out_features), torch.bfloat16, input_.device)
149+ _matrix(spec.grad_input_output, tuple(input_.shape), torch.bfloat16, input_.device)
150+ _matrix(spec.wgrad_scratch, (self.num_gemms, self.out_features, self.in_features),
151+ torch.float32, input_.device)
152+ for leaf, ref in zip(weights, spec.weight_refs):
153+ _matrix(ref, (self.out_features, self.in_features), torch.bfloat16, input_.device)
154+ if leaf.data_ptr() != ref.data_ptr() or tuple(leaf.shape) != tuple(ref.shape):
155+ raise ValueError("runtime leaf differs from the borrowed weight reference")
156+ for metadata in (spec.counts, spec.prefix):
157+ _matrix(metadata, (self.num_gemms,), torch.int64, input_.device)
158+ _disjoint(spec.output, input_, *spec.weight_refs, spec.counts, spec.prefix)
159+ ctx.runtime_spec, ctx.done = spec, False
160+ ctx.runtime_owner = spec.operation_owner
161+ ctx.weights = weights
162+ ctx.weight_bindings = tuple(map(_binding_identity, weights))
163+ if spec.acquire_wgrad_input is None:
164+ ctx.save_for_backward(input_) # FC2's necessary mathematical input.
165+ else:
166+ ctx.save_for_backward() # FC1 obtains X through exact-plan R1.
167+ # Custom Autograd forward keeps Tensor.requires_grad flags. Native
168+ # primitives borrow detached metadata aliases, while ctx/spec retain
169+ # the original graph owners and caller-visible output identity.
170+ spec.linear_out(spec.operation_owner, input_.detach(),
171+ tuple(ref.detach() for ref in spec.weight_refs), spec.counts,
172+ spec.output.detach(), transpose_weights=True)
173+ return spec.output
174+ except BaseException as error:
175+ _mark_runtime_failed(spec.operation_owner, error, ctx, spec, input_)
176+ raise
177+ 
178+ def op_backward(self, ctx: OperationContext, grad_output):
179+ if ctx.done:
180+ error = RuntimeError("repeated grouped backward is unsupported")
181+ _mark_runtime_failed(ctx.runtime_owner, error, ctx, grad_output)
182+ raise error
183+ spec = ctx.runtime_spec
184+ source = None
185+ try:
186+ if ctx.done or torch.is_grad_enabled():
187+ raise RuntimeError("repeated or higher-order grouped backward is unsupported")
188+ ctx.done = True
189+ registered = tuple(self.parameters())
190+ if (len(registered) != len(ctx.weights)
191+ or any(a is not b for a, b in zip(registered, ctx.weights))
192+ or tuple(map(_binding_identity, ctx.weights)) != ctx.weight_bindings):
193+ raise RuntimeError("runtime weight binding changed while the exact call was live")
194+ # Shared remote payload is deliberately refilled. Canonical version
195+ # admission belongs to the framework before backward PUSH.
196+ _matrix(grad_output, tuple(spec.output.shape), torch.bfloat16, spec.output.device)
197+ _disjoint(spec.grad_input_output, grad_output, *spec.weight_refs)
198+ spec.linear_out(spec.operation_owner, grad_output.detach(),
199+ tuple(ref.detach() for ref in spec.weight_refs), spec.counts,
200+ spec.grad_input_output.detach(), transpose_weights=False)
201+ source = (ctx.saved_tensors[0] if spec.acquire_wgrad_input is None
202+ else spec.acquire_wgrad_input())
203+ produced = False
204+ 
205+ def wgrad_gemm(x, dy):
206+ nonlocal produced
207+ if produced:
208+ raise RuntimeError("grouped wgrad producer cannot run twice")
209+ produced = True
210+ spec.wgrad_producer(spec.operation_owner, x.detach(), dy.detach(), spec.counts,
211+ spec.prefix, spec.wgrad_scratch)
212+ spec.publish_wgrad(spec, spec.wgrad_scratch)
213+ 
214+ if self.wgrad_store is None:
215+ wgrad_gemm(source, grad_output)
216+ else:
217+ self.wgrad_store.put((source, grad_output), wgrad_gemm)
218+ if not produced:
219+ raise RuntimeError("ordinary runtime wgrad store must execute immediately")
220+ # Only the outer original-canonical hook publishes DDP readiness.
221+ result = spec.grad_input_output
222+ ctx.runtime_spec, ctx.weights, ctx.weight_bindings = None, (), ()
223+ return result, (None,) * self.num_gemms
224+ except BaseException as error:
225+ _mark_runtime_failed(spec.operation_owner, error, ctx, spec, grad_output, source)
226+ raise
@@ -21,6 +21,9 @@ from ...cpu_offload import is_cpu_offload_enabled, mark_activation_offload
21from ...tensor import Float8CurrentScalingQuantizer, Quantizer21from ...tensor import Float8CurrentScalingQuantizer, Quantizer
22from ...utils import clear_tensor_data22from ...utils import clear_tensor_data
23from ..op import BasicOperation, OperationContext23from ..op import BasicOperation, OperationContext
24+from .grouped_linear import (
25+ RuntimeActivationSpec, _matrix, _disjoint, _require_failure_owner, _mark_runtime_failed,
26+)
24from .._common import maybe_dequantize27from .._common import maybe_dequantize
25 28 
26__all__ = ["SwiGLU", "ScaledSwiGLU", "ScaledClampedQGeGLU"]29__all__ = ["SwiGLU", "ScaledSwiGLU", "ScaledClampedQGeGLU"]
@@ -248,6 +251,11 @@ class _ScaledGLU(BasicOperation):
248 next_op_input_quantizer: Optional[Quantizer],251 next_op_input_quantizer: Optional[Quantizer],
249 basic_op_kwargs: list[dict[str, Any]],252 basic_op_kwargs: list[dict[str, Any]],
250 ) -> tuple[torch.Tensor, Iterable[Iterable[torch.Tensor]]]:253 ) -> tuple[torch.Tensor, Iterable[Iterable[torch.Tensor]]]:
254+ runtime_spec = basic_op_kwargs[0].get("runtime_spec")
255+ if runtime_spec is not None:
256+ return self._runtime_forward(
257+ basic_op_ctxs[0], input_, basic_op_extra_inputs[0][0], runtime_spec,
258+ prev_op_grad_output_quantizer, next_op_input_quantizer)
251 if self.activation_recompute_in_mlp:259 if self.activation_recompute_in_mlp:
252 raise RuntimeError(260 raise RuntimeError(
253 f"{self.__class__.__name__}(activation_recompute_in_mlp=True) requires the "261 f"{self.__class__.__name__}(activation_recompute_in_mlp=True) requires the "
@@ -294,6 +302,9 @@ class _ScaledGLU(BasicOperation):
294 ]:302 ]:
295 del basic_op_grad_extra_outputs303 del basic_op_grad_extra_outputs
296 304 
305+ if hasattr(basic_op_ctxs[0], "runtime_done"):
306+ return self._runtime_backward(basic_op_ctxs[0], grad_output)
307+ 
297 if self.activation_recompute_in_mlp:308 if self.activation_recompute_in_mlp:
298 raise RuntimeError(309 raise RuntimeError(
299 f"{self.__class__.__name__}(activation_recompute_in_mlp=True) requires the "310 f"{self.__class__.__name__}(activation_recompute_in_mlp=True) requires the "
@@ -320,6 +331,75 @@ class _ScaledGLU(BasicOperation):
320 331 
321 return grad_input, [()], [(grad_extra_input,)]332 return grad_input, [()], [(grad_extra_input,)]
322 333 
334+ def _runtime_forward(self, ctx, x, probabilities, spec, previous_quantizer, next_quantizer):
335+ """Explicit BF16 SwiGLU with preserved FP32 probability operands."""
336+ if not isinstance(spec, RuntimeActivationSpec):
337+ raise ValueError("invalid runtime activation spec")
338+ _require_failure_owner(spec.operation_owner)
339+ activation = activation_fp32 = None
340+ try:
341+ if (type(self).__name__ != "ScaledSwiGLU" or self.activation_recompute_in_mlp
342+ or previous_quantizer is not None or next_quantizer is not None
343+ or x.ndim != 2 or x.shape[1] % 2):
344+ raise ValueError("runtime profile supports ordinary unquantized SwiGLU only")
345+ rows, width = x.shape[0], x.shape[1] // 2
346+ _matrix(x, (rows, 2 * width), torch.bfloat16, x.device)
347+ _matrix(probabilities, (rows,), torch.float32, x.device)
348+ _matrix(spec.output, (rows, width), torch.bfloat16, x.device)
349+ _matrix(spec.probability_grad_output, (rows,), torch.float32, x.device)
350+ _disjoint(spec.output, x, probabilities)
351+ ctx.runtime_spec, ctx.runtime_done = spec, False
352+ ctx.runtime_owner = spec.operation_owner
353+ ctx.save_for_backward(x, probabilities)
354+ activation = self._glu_forward(x)
355+ activation_fp32 = activation.float()
356+ activation = None # Ordinary Torch conversion owns its queued input use.
357+ torch.mul(activation_fp32, probabilities[:, None], out=spec.output)
358+ return spec.output, [()]
359+ except BaseException as error:
360+ _mark_runtime_failed(spec.operation_owner, error, ctx, spec, x, probabilities,
361+ activation, activation_fp32)
362+ raise
363+ 
364+ def _runtime_backward(self, ctx, grad_output):
365+ if ctx.runtime_done:
366+ error = RuntimeError("repeated runtime activation backward")
367+ _mark_runtime_failed(ctx.runtime_owner, error, ctx, grad_output)
368+ raise error
369+ spec = ctx.runtime_spec
370+ x = probabilities = grad = activation = activation_fp32 = None
371+ product = scaled_grad = da = grad_input = None
372+ try:
373+ if ctx.runtime_done or torch.is_grad_enabled():
374+ raise RuntimeError("repeated or higher-order runtime activation backward")
375+ ctx.runtime_done = True
376+ x, probabilities = ctx.saved_tensors
377+ _matrix(grad_output, tuple(spec.output.shape), torch.bfloat16, x.device)
378+ _disjoint(spec.probability_grad_output, grad_output, x, probabilities)
379+ grad = grad_output.float()
380+ activation = self._glu_forward(x)
381+ activation_fp32 = activation.float()
382+ activation = None
383+ product = grad * activation_fp32
384+ activation_fp32 = None
385+ spec.reduce_sum_out(spec.operation_owner, product, spec.probability_grad_output)
386+ product = None # Direct ReduceSum callback guarantees local completion.
387+ # Native activation owns its mathematical result; this is neither a
388+ # GEMM temporary nor a copyback into a promised destination.
389+ scaled_grad = grad * probabilities[:, None]
390+ grad = None
391+ da = scaled_grad.to(torch.bfloat16)
392+ scaled_grad = None
393+ grad_input = self._glu_backward(da, x)
394+ _matrix(grad_input, tuple(x.shape), torch.bfloat16, x.device)
395+ ctx.runtime_spec = None
396+ return grad_input, [()], [(spec.probability_grad_output,)]
397+ except BaseException as error:
398+ _mark_runtime_failed(spec.operation_owner, error, ctx, spec, grad_output,
399+ x, probabilities, grad, activation, activation_fp32,
400+ product, scaled_grad, da, grad_input)
401+ raise
402+ 
323 403 
324class ScaledSwiGLU(_ScaledGLU):404class ScaledSwiGLU(_ScaledGLU):
325 r"""SwiGLU with post-scaling (matches cuDNN grouped GEMM ``act_func="swiglu"``).405 r"""SwiGLU with post-scaling (matches cuDNN grouped GEMM ``act_func="swiglu"``).