Draft
[WIP]fix/moonep-33d7cfb #5
&NewgateAdd on 18 days ago
[WIP]fix/moonep-33d7cfb #5
Draft
&NewgateAdd on 18 days ago
Total: 17 files changed+5099-7
@@ -0,0 +1 @@
1+mindspeed/ops/gmm.py -text whitespace=blank-at-eol,blank-at-eof,space-before-tab,cr-at-eol
@@ -0,0 +1 @@
1+"""MoonEP integration modules; importing this package has no runtime side effects."""
@@ -0,0 +1,131 @@
1+"""Flex dispatcher wiring for synchronous Ascend MoonEP."""
2+ 
3+from __future__ import annotations
4+ 
5+from functools import wraps
6+ 
7+from .moonep_runtime import close_moonep, initialize_moonep
8+from .virtual_expert_load_balancer import VirtualExpertLoadBalancer
9+ 
10+ 
11+def build_moonep_flex_token_dispatcher():
12+ """Return a Flex subclass that changes only manager construction."""
13+ from megatron.core.transformer.moe.token_dispatcher import (
14+ MoEFlexTokenDispatcher,
15+ MoETokenDispatcher,
16+ _DispatchManager,
17+ )
18+ 
19+ class _VirtualExpertMoonEPManager(VirtualExpertLoadBalancer, _DispatchManager):
20+ def __init__(self, group, num_local_experts, num_experts, config):
21+ VirtualExpertLoadBalancer.__init__(
22+ self,
23+ group=group,
24+ num_local_experts=num_local_experts,
25+ num_experts=num_experts,
26+ config=config,
27+ )
28+ 
29+ class MoonEPFlexTokenDispatcher(MoEFlexTokenDispatcher):
30+ def __init__(self, num_local_experts, local_expert_indices, config, pg_collection=None):
31+ # Upstream Flex rejects the private "moonep" backend. Reuse all six
32+ # public stages but construct only the NPU manager here.
33+ MoETokenDispatcher.__init__(self, config=config, pg_collection=pg_collection)
34+ if self.tp_size != 1:
35+ raise ValueError("synchronous MoonEP requires expert tensor parallel size 1")
36+ self.num_local_experts = int(num_local_experts)
37+ self.local_expert_indices = tuple(local_expert_indices)
38+ self._comm_manager = _VirtualExpertMoonEPManager(
39+ group=self.tp_ep_group,
40+ num_local_experts=self.num_local_experts,
41+ num_experts=int(config.num_moe_experts),
42+ config=config,
43+ )
44+ self.cudagraph_attrs = []
45+ 
46+ def get_expert_zero_copy_buffers(self):
47+ # The private Experts Autograd boundary supplies Z2/Z4 directly;
48+ # the generic TE op-fuser must not allocate or bind another buffer.
49+ return None, None
50+ 
51+ def wrap_layer_input(self, hidden_states):
52+ """Expose the dispatcher boundary on older Megatron Core."""
53+ return self._comm_manager.wrap_layer_input(hidden_states)
54+ 
55+ def finalize_layer_output(self, output):
56+ """Attach the exact plan after model-specific layer postprocessing."""
57+ return self._comm_manager.finalize_output(output)
58+ 
59+ _VirtualExpertMoonEPManager.__name__ = "_VirtualExpertMoonEPManager"
60+ MoonEPFlexTokenDispatcher.__name__ = "MoonEPFlexTokenDispatcher"
61+ return MoonEPFlexTokenDispatcher
62+ 
63+ 
64+def moonep_moe_layer_init_wrapper(fn):
65+ @wraps(fn)
66+ def wrapper(layer, *args, **kwargs):
67+ result = fn(layer, *args, **kwargs)
68+ dispatcher = getattr(layer, "token_dispatcher", None)
69+ manager = getattr(dispatcher, "_comm_manager", None)
70+ if isinstance(manager, VirtualExpertLoadBalancer):
71+ manager.bind_experts(layer.experts)
72+ return result
73+ 
74+ return wrapper
75+ 
76+ 
77+def moonep_moe_layer_route_wrapper(fn):
78+ """Expose a layer-input hook without changing upstream Megatron."""
79+ @wraps(fn)
80+ def wrapper(layer, hidden_states, *args, **kwargs):
81+ dispatcher = getattr(layer, "token_dispatcher", None)
82+ manager = getattr(dispatcher, "_comm_manager", None)
83+ if isinstance(manager, VirtualExpertLoadBalancer):
84+ hidden_states = dispatcher.wrap_layer_input(hidden_states)
85+ return fn(layer, hidden_states, *args, **kwargs)
86+ 
87+ return wrapper
88+ 
89+ 
90+def moonep_moe_layer_postprocess_wrapper(fn):
91+ """Expose the final layer-output boundary on older Megatron Core."""
92+ @wraps(fn)
93+ def wrapper(layer, *args, **kwargs):
94+ output = fn(layer, *args, **kwargs)
95+ dispatcher = getattr(layer, "token_dispatcher", None)
96+ manager = getattr(dispatcher, "_comm_manager", None)
97+ if isinstance(manager, VirtualExpertLoadBalancer):
98+ output = dispatcher.finalize_layer_output(output)
99+ return output
100+ 
101+ return wrapper
102+ 
103+ 
104+def setup_wrapper(fn):
105+ @wraps(fn)
106+ def wrapper(*args, **kwargs):
107+ result = fn(*args, **kwargs)
108+ initialize_moonep()
109+ return result
110+ 
111+ return wrapper
112+ 
113+ 
114+def save_checkpoint_wrapper(fn):
115+ @wraps(fn)
116+ def wrapper(*args, **kwargs):
117+ from .moonep_runtime import checkpoint_drain
118+ 
119+ checkpoint_drain()
120+ return fn(*args, **kwargs)
121+ 
122+ return wrapper
123+ 
124+ 
125+def destroy_model_parallel_wrapper(fn):
126+ @wraps(fn)
127+ def wrapper(*args, **kwargs):
128+ close_moonep()
129+ return fn(*args, **kwargs)
130+ 
131+ return wrapper
@@ -0,0 +1,103 @@
1+"""Configuration checks for the synchronous MoonEP integration."""
2+ 
3+from __future__ import annotations
4+ 
5+def moonep_enabled(args) -> bool:
6+ return (
7+ getattr(args, "moe_token_dispatcher_type", None) == "flex"
8+ and getattr(args, "moe_flex_dispatcher_backend", None) == "moonep"
9+ )
10+ 
11+ 
12+def _enabled(args, name, default=False):
13+ value = getattr(args, name, default)
14+ if isinstance(value, str):
15+ disabled_values = {"", "disable", "disabled", "false", "none", "off"}
16+ return value.strip().lower() not in disabled_values
17+ return bool(value)
18+ 
19+ 
20+def validate_moonep_args(args) -> None:
21+ if not moonep_enabled(args):
22+ return
23+ errors = []
24+ ep = int(getattr(args, "expert_model_parallel_size", 1))
25+ # Raw Core args own num_experts; TransformerConfig owns num_moe_experts.
26+ # Original MA may carry both, so never silently prefer a conflicting value.
27+ counts = [getattr(args, name, None) for name in ("num_experts", "num_moe_experts")]
28+ counts = [value for value in counts if value is not None]
29+ experts = 0
30+ if any(type(value) is not int for value in counts):
31+ errors.append("num_experts/num_moe_experts must be integers (not bool, float, or string)")
32+ elif len(counts) == 2 and counts[0] != counts[1]:
33+ errors.append("conflicting num_experts and num_moe_experts")
34+ elif counts:
35+ experts = counts[0]
36+ if ep <= 1 or experts <= 0 or experts % ep:
37+ errors.append("EP must be >1 and num_moe_experts must be positive and divisible by EP")
38+ if int(getattr(args, "expert_tensor_parallel_size", 1)) != 1:
39+ errors.append("expert tensor parallel size must be 1")
40+ if not _enabled(args, "bf16") or _enabled(args, "fp16"):
41+ errors.append("activation and expert weights must use BF16")
42+ # Feature validation sees raw args and original MA's TransformerConfig
43+ # post-init; runtime initialization sees get_full_args(). A config does not
44+ # itself own the optimizer setting, so validate it only when propagated.
45+ use_distributed_optimizer = getattr(args, "use_distributed_optimizer", None)
46+ if use_distributed_optimizer is not None and not bool(use_distributed_optimizer):
47+ errors.append("distributed optimizer is required")
48+ if not _enabled(args, "moe_grouped_gemm"):
49+ errors.append("moe_grouped_gemm must be enabled")
50+ if _enabled(args, "moe_single_grouped_weight"):
51+ errors.append("moe_single_grouped_weight must be false (per-expert checkpoint schema)")
52+ if _enabled(args, "add_bias_linear"):
53+ errors.append("grouped expert bias is unsupported")
54+ # This expert-only MS flag is propagated by original MA into configs.
55+ # It is not an alias for Core's global gradient_accumulation_fusion flag.
56+ if not _enabled(args, "gemm_gradient_accumulation_fusion"):
57+ errors.append("gemm_gradient_accumulation_fusion must be enabled")
58+ if _enabled(args, "moe_shared_expert_overlap"):
59+ errors.append("shared expert overlap must be disabled")
60+ for name in (
61+ "overlap_moe_expert_parallel_comm",
62+ "overlap_param_gather",
63+ "overlap_param_gather_with_optimizer_step",
64+ "moe_fb_overlap",
65+ "moe_enable_fb_overlap",
66+ "moe_zero_memory",
67+ "use_cuda_graphs",
68+ "fp8",
69+ "fp4",
70+ ):
71+ if _enabled(args, name):
72+ errors.append(f"{name} is unsupported by synchronous MoonEP v1")
73+ for name in (
74+ "moe_permute_fusion",
75+ "moe_token_dispatcher_fused_permute",
76+ "use_fused_moe_token_permute_and_unpermute",
77+ ):
78+ if _enabled(args, name):
79+ errors.append(f"{name} must be disabled")
80+ recompute_modules = tuple(getattr(args, "recompute_modules", ()) or ())
81+ # Full-layer and selective MoE recompute are not adapted for the current
82+ # exact-plan lifetime; both configurations remain explicitly rejected.
83+ if "moe_act" in recompute_modules:
84+ errors.append(
85+ "selective moe_act recompute is unsupported"
86+ )
87+ if _enabled(args, "moe_enable_moonep"):
88+ errors.append("legacy moe_enable_moonep is removed; use flex + moonep")
89+ if getattr(args, "recompute_granularity", None):
90+ errors.append("recompute is not yet adapted for the PR20 exact-plan lifetime")
91+ for name in ("use_te_activation", "use_te_activation_func"):
92+ if _enabled(args, name):
93+ errors.append(f"{name} is not adapted for the plain SwiGLU profile")
94+ if getattr(args, "moe_mlp_glu_interleave_size", None) is not None:
95+ errors.append("moe_mlp_glu_interleave_size is not adapted")
96+ if hasattr(args, "gated_linear_unit") and not args.gated_linear_unit:
97+ errors.append("gated_linear_unit is required")
98+ if getattr(args, "activation_func_clamp_value", None) is not None:
99+ errors.append("activation_func_clamp_value is not adapted")
100+ if float(getattr(args, "glu_linear_offset", 0) or 0) != 0:
101+ errors.append("glu_linear_offset is not adapted")
102+ if errors:
103+ raise ValueError("invalid MoonEP L+B configuration: " + "; ".join(errors))
@@ -0,0 +1,466 @@
1+"""Flow-free exact-plan Autograd boundaries for synchronous Ascend MoonEP."""
2+ 
3+from __future__ import annotations
4+ 
5+from functools import wraps
6+import weakref
7+ 
8+from .virtual_expert_load_balancer import (
9+ _VirtualExperts,
10+ VirtualExpertPlan,
11+ build_physical_counts,
12+ plan_metadata,
13+ tensor_identity,
14+)
15+ 
16+ 
17+def _backward_expectations(hidden, probs, virtual_experts):
18+ """Classify checkpoint original/recompute before Function.apply."""
19+ import torch
20+ 
21+ grad_enabled = torch.is_grad_enabled()
22+ dispatch_backward_expected = grad_enabled and (
23+ bool(getattr(hidden, "requires_grad", False))
24+ or bool(getattr(probs, "requires_grad", False))
25+ )
26+ expert_backward_expected = grad_enabled and (
27+ dispatch_backward_expected
28+ or any(
29+ bool(getattr(parameter, "requires_grad", False))
30+ for parameter in virtual_experts.source_parameters
31+ )
32+ )
33+ return dispatch_backward_expected, expert_backward_expected
34+ 
35+ 
36+def _prepare_dummy_gradients(weights, owners, specs):
37+ """Prepare private return values without publishing Parameter/DDP readiness.
38+ 
39+ Append each allocation immediately: the active segment roots ``owners``
40+ through its final drain, including a partial preparation or drain failure.
41+ Nothing here changes Parameter.grad or grad_added_to_main_grad.
42+ """
43+ import torch
44+ 
45+ for parameter in weights:
46+ added = hasattr(parameter, "grad_added_to_main_grad")
47+ zero_out = bool(getattr(parameter, "zero_out_wgrad", False))
48+ specs.append((tuple(parameter.shape), parameter.dtype, parameter.device,
49+ added, zero_out))
50+ owners.append(
51+ torch.empty_like(parameter)
52+ if added and not zero_out
53+ else torch.zeros_like(parameter)
54+ )
55+ 
56+ 
57+def _validate_dummy_gradients(weights, owners, specs):
58+ """Recheck the consumer contract after completion, before any ready flag."""
59+ if len(owners) != len(weights) or len(specs) != len(weights):
60+ raise RuntimeError("incomplete canonical gradient dummies")
61+ for parameter, value, spec in zip(weights, owners, specs):
62+ shape, dtype, device, added, zero_out = spec
63+ if (tuple(parameter.shape) != shape or parameter.dtype != dtype
64+ or parameter.device != device
65+ or hasattr(parameter, "grad_added_to_main_grad") != added
66+ or bool(getattr(parameter, "zero_out_wgrad", False)) != zero_out
67+ or tuple(value.shape) != shape or value.dtype != dtype
68+ or value.device != device):
69+ raise RuntimeError("canonical gradient dummy contract changed")
70+ 
71+ 
72+def _types():
73+ import torch
74+ from mindspeed.ops.gmm import npu_gmm_v5_out
75+ from . import moonep_runtime
76+ 
77+ class Dispatch(torch.autograd.Function):
78+ @staticmethod
79+ def forward(
80+ ctx,
81+ hidden,
82+ probs,
83+ indices,
84+ counts,
85+ manager,
86+ dispatch_backward_expected,
87+ expert_backward_expected,
88+ ):
89+ route_invalid = getattr(manager, "_pending_route_invalid", None)
90+ route_identity = getattr(manager, "_pending_route_invalid_identity", ())
91+ # The mutable list is rooted by the boundary before preparation.
92+ # Each newly returned Tensor/plan is appended before later enqueue.
93+ metadata_owners = []
94+ plan = None
95+ try:
96+ z1, dispatched_probs, cu_seqlens, provider_plan = (
97+ moonep_runtime.get_moonep_buffer().dispatch(
98+ hidden,
99+ route_weights_sk=probs,
100+ topk_experts_sk=indices,
101+ tokens_per_expert=counts,
102+ zero_copy=moonep_runtime.strict_zero_copy_enabled(),
103+ )
104+ )
105+ def check_route_validation():
106+ # Reuse the original peer gate, before entering the counts
107+ # collective. A foreign/rebound local bit cannot strand its
108+ # peers in that later collective.
109+ if (getattr(manager, "_pending_route_invalid", None) is not route_invalid
110+ or getattr(manager, "_pending_route_invalid_identity", ()) != route_identity):
111+ raise RuntimeError("MoonEP deferred route validation was rebound")
112+ if route_invalid is None:
113+ if route_identity:
114+ raise RuntimeError("MoonEP deferred route validation is missing")
115+ elif (route_invalid.dtype != torch.bool or route_invalid.ndim != 0
116+ or route_invalid.device != cu_seqlens.device
117+ or tensor_identity(route_invalid) != route_identity):
118+ raise RuntimeError("MoonEP deferred route validation storage/layout changed")
119+ 
120+ def prepare_metadata():
121+ nonlocal z1, plan
122+ z1 = moonep_runtime.independent_activation_alias(z1)
123+ metadata_owners.append(z1)
124+ validation = {"route_invalid": route_invalid} if route_invalid is not None else {}
125+ physical_counts = build_physical_counts(
126+ cu_seqlens,
127+ rank=int(torch.distributed.get_rank(group=manager.group)),
128+ local_experts=manager.num_local_experts,
129+ global_experts=manager.num_experts,
130+ slots=manager.num_local_experts,
131+ carrier_rows=int(z1.shape[0]),
132+ **validation,
133+ )
134+ metadata_owners.append(physical_counts)
135+ plan = VirtualExpertPlan(
136+ provider_plan=provider_plan,
137+ group_counts_2l=physical_counts,
138+ manager_cookie=manager._cookie,
139+ dispatch_backward_expected=bool(dispatch_backward_expected),
140+ expert_backward_expected=bool(expert_backward_expected),
141+ cu_seqlens=cu_seqlens,
142+ )
143+ metadata_owners.append(plan)
144+ plan.prefix = physical_counts.cumsum(0)
145+ plan.source_pins = (manager._forward_source, probs.detach())
146+ plan.source_versions = tuple(tensor_identity(t) for t in plan.source_pins)
147+ plan.weight_versions = tuple(int(w._version) for w in manager.virtual_experts.source_parameters)
148+ # Same-Q0 consumers follow the original publication
149+ # barrier; they need no earlier physical Host completion.
150+ padding = torch.arange(z1.shape[0], device=z1.device) >= cu_seqlens[-1]
151+ plan.padding_mask = padding
152+ z1.masked_fill_(padding.unsqueeze(-1), 0)
153+ dispatched_probs.masked_fill_(padding, 0)
154+ plan.metadata = plan_metadata(plan)
155+ 
156+ pins = (manager, ctx, hidden, probs, indices, counts, route_invalid,
157+ z1, dispatched_probs, cu_seqlens, provider_plan, metadata_owners)
158+ moonep_runtime.complete_boundary(
159+ "Dispatch.forward", *pins,
160+ check=check_route_validation, prepare=prepare_metadata,
161+ )
162+ # Admission/publication and Autograd visibility follow the
163+ # original drain, including all newly queued metadata work.
164+ _VirtualExperts.admit(plan)
165+ manager.accept_forward_plan(plan)
166+ ctx.plan = plan
167+ ctx.manager_ref = weakref.ref(manager)
168+ return z1, dispatched_probs
169+ except Exception as exc:
170+ manager.fail_stop(plan, exc, tuple(locals().values()))
171+ raise
172+ 
173+ @staticmethod
174+ @torch.autograd.function.once_differentiable
175+ def backward(ctx, grad_hidden, grad_probs):
176+ manager = ctx.manager_ref()
177+ if manager is None:
178+ raise RuntimeError("MoonEP manager disappeared before dispatch backward")
179+ plan = ctx.plan
180+ manager.require_backward_plan(plan)
181+ try:
182+ route_for_combine = grad_probs
183+ if moonep_runtime.strict_zero_copy_enabled() and grad_probs is not None:
184+ route_for_combine = moonep_runtime.stage_route_grad(grad_probs)
185+ grad_input, grad_route, _ = moonep_runtime.get_moonep_buffer().combine(
186+ plan=plan.provider_plan,
187+ hidden_nvsh=grad_hidden,
188+ route_weights_nvs=route_for_combine,
189+ zero_copy=moonep_runtime.strict_zero_copy_enabled(),
190+ )
191+ moonep_runtime.complete_boundary(
192+ "Dispatch.backward", manager, ctx, plan, grad_hidden, grad_probs,
193+ route_for_combine, grad_input, grad_route,
194+ )
195+ manager.retire(plan)
196+ except Exception as exc:
197+ manager.fail_stop(plan, exc, tuple(locals().values()))
198+ raise
199+ return grad_input, grad_route, None, None, None, None, None
200+ 
201+ class Combine(torch.autograd.Function):
202+ @staticmethod
203+ def forward(ctx, expert_output, plan, manager):
204+ try:
205+ output, _, _ = moonep_runtime.get_moonep_buffer().combine(
206+ plan=plan.provider_plan,
207+ hidden_nvsh=expert_output,
208+ zero_copy=moonep_runtime.strict_zero_copy_enabled(),
209+ )
210+ moonep_runtime.complete_boundary(
211+ "Combine.forward", manager, ctx, plan, expert_output, output,
212+ )
213+ except Exception as exc:
214+ manager.fail_stop(plan, exc, tuple(locals().values()))
215+ raise
216+ ctx.plan = plan
217+ ctx.manager_ref = weakref.ref(manager)
218+ return output
219+ 
220+ @staticmethod
221+ @torch.autograd.function.once_differentiable
222+ def backward(ctx, grad_output):
223+ manager = ctx.manager_ref()
224+ if manager is None:
225+ raise RuntimeError("MoonEP manager disappeared before combine backward")
226+ plan = ctx.plan
227+ manager.require_backward_plan(plan)
228+ try:
229+ dispatch_source = grad_output
230+ if not dispatch_source.is_contiguous():
231+ raise RuntimeError("MoonEP combine backward requires contiguous dY")
232+ z3, _, _, _ = moonep_runtime.get_moonep_buffer().dispatch(
233+ dispatch_source,
234+ plan=plan.provider_plan,
235+ zero_copy=moonep_runtime.strict_zero_copy_enabled(),
236+ )
237+ moonep_runtime.complete_boundary(
238+ "Combine.backward", manager, ctx, plan, grad_output, dispatch_source, z3,
239+ )
240+ z3 = moonep_runtime.independent_activation_alias(z3)
241+ z3.masked_fill_(plan.padding_mask.unsqueeze(-1), 0)
242+ moonep_runtime.activation_edge("Z3", z3)
243+ return z3, None, None
244+ except Exception as exc:
245+ manager.fail_stop(plan, exc, tuple(locals().values()))
246+ raise
247+ 
248+ class Experts(torch.autograd.Function):
249+ @staticmethod
250+ def forward(ctx, hidden, probs, original_hidden, plan, manager, *weights):
251+ virtual_experts = manager.virtual_experts
252+ count = virtual_experts.num_local_experts
253+ if probs.ndim != 1:
254+ raise RuntimeError("MoonEP expert-order probabilities must be one-dimensional")
255+ if len(weights) != 2 * count:
256+ raise RuntimeError("MoonEP expert boundary received an invalid weight set")
257+ try:
258+ buffer = moonep_runtime.get_moonep_buffer()
259+ moonep_runtime.begin_submission_segment(
260+ plan, manager, hidden, probs, original_hidden, weights,
261+ )
262+ # moe_zero_memory is disabled for this integration: retain the
263+ # FC1 input, as ordinary alltoall training does. Strict ZC's
264+ # carrier will be overwritten by Z2 and subsequent plans.
265+ saved_input = None
266+ def prepare_input():
267+ nonlocal saved_input
268+ if plan.saved_input is not None or plan.saved_input_identity:
269+ raise RuntimeError("MoonEP saved Z1 was already bound to this exact plan")
270+ if plan.expert_backward_expected:
271+ saved_input = moonep_runtime.save_expert_input(hidden)
272+ plan.saved_input = saved_input
273+ plan.saved_input_identity = tensor_identity(saved_input)
274+ # Reuse the existing peer gate: a local snapshot allocation or
275+ # enqueue failure must be agreed before any peer starts PUSH.
276+ virtual_experts.prefetch(buffer, "fc1", plan, prepare=prepare_input)
277+ virtual_experts.prefetch(buffer, "fc2", plan)
278+ 
279+ fc1_refs = virtual_experts.gmm_weight_refs("fc1", transpose=True)
280+ fc1_out = hidden.new_empty((hidden.shape[0], weights[0].shape[0]))
281+ npu_gmm_v5_out(hidden.detach(), fc1_refs, fc1_out, plan.group_counts_2l)
282+ 
283+ with torch.enable_grad():
284+ fc1_leaf = fc1_out.detach().requires_grad_(True)
285+ activated = virtual_experts.activation(fc1_leaf)
286+ probability = probs.unsqueeze(-1)
287+ weighted = (activated.detach() * probability).to(activated.dtype)
288+ 
289+ fc2_refs = virtual_experts.gmm_weight_refs("fc2", transpose=True)
290+ strict = moonep_runtime.strict_zero_copy_enabled()
291+ z2 = hidden if strict else hidden.new_empty(hidden.shape)
292+ npu_gmm_v5_out(weighted, fc2_refs, z2.detach(), plan.group_counts_2l)
293+ moonep_runtime.activation_edge("Z2", z2)
294+ if strict:
295+ ctx.mark_dirty(hidden)
296+ saved_probs = moonep_runtime.snapshot_route_probs(probs) if strict else probs
297+ ctx.plan = plan
298+ ctx.manager_ref = weakref.ref(manager)
299+ ctx.save_for_backward(
300+ saved_input, fc1_leaf, activated, weighted, saved_probs, *weights
301+ )
302+ moonep_runtime.end_submission_segment()
303+ return z2
304+ except Exception as exc:
305+ moonep_runtime.abort_submission_segment(exc)
306+ manager.fail_stop(plan, exc, tuple(locals().values()))
307+ raise
308+ 
309+ @staticmethod
310+ @torch.autograd.function.once_differentiable
311+ def backward(ctx, grad_output):
312+ manager = ctx.manager_ref()
313+ if manager is None:
314+ raise RuntimeError("MoonEP manager disappeared before expert backward")
315+ plan = ctx.plan
316+ dummy, dummy_specs = [], []
317+ try:
318+ manager.require_backward_plan(plan)
319+ virtual_experts = manager.virtual_experts
320+ saved = ctx.saved_tensors
321+ saved_input, fc1_leaf, activated, weighted, probs = saved[:5]
322+ weights = saved[5:]
323+ if saved_input is None:
324+ raise RuntimeError("MoonEP expert backward requires its saved Z1 input")
325+ # Full Z1/source/weight checks ran at the coordinated backward
326+ # entry; saved_tensors retains PyTorch's own version checks.
327+ if saved_input is not plan.saved_input:
328+ raise RuntimeError("MoonEP expert backward received a foreign saved Z1")
329+ buffer = moonep_runtime.get_moonep_buffer()
330+ moonep_runtime.begin_submission_segment(plan, manager, saved, grad_output, dummy)
331+ counts = plan.group_counts_2l
332+ 
333+ fc2_dgrad_refs = virtual_experts.gmm_weight_refs("fc2", transpose=False)
334+ grad_weighted = weighted.new_empty(weighted.shape)
335+ npu_gmm_v5_out(grad_output, fc2_dgrad_refs, grad_weighted, counts)
336+ virtual_experts.produce_and_publish(
337+ buffer, "fc2", plan, grad_output, weighted,
338+ )
339+ virtual_experts.reduce(buffer, "fc2", plan)
340+ 
341+ probability = probs.unsqueeze(-1)
342+ with torch.enable_grad():
343+ grad_fc1 = torch.autograd.grad(
344+ activated,
345+ fc1_leaf,
346+ (grad_weighted * probability).to(activated.dtype),
347+ retain_graph=False,
348+ create_graph=False,
349+ )[0]
350+ grad_probs = (
351+ grad_weighted.float() * activated.detach().float()
352+ ).sum(dim=-1).to(probs.dtype)
353+ 
354+ virtual_experts.produce_and_publish(
355+ buffer, "fc1", plan, grad_fc1, saved_input,
356+ )
357+ virtual_experts.reduce(buffer, "fc1", plan)
358+ 
359+ z4 = None
360+ if plan.dispatch_backward_expected:
361+ fc1_dgrad_refs = virtual_experts.gmm_weight_refs(
362+ "fc1", transpose=False
363+ )
364+ # Saved input is owned storage; Z4 must still target the
365+ # symmetric carrier, after all same-Q0 Z3 consumers finish.
366+ z4 = (
367+ moonep_runtime.independent_activation_alias(
368+ buffer._ctx["hidden_buf_local"]
369+ ) if moonep_runtime.strict_zero_copy_enabled()
370+ else saved_input.new_empty(saved_input.shape)
371+ )
372+ npu_gmm_v5_out(grad_fc1, fc1_dgrad_refs, z4, counts)
373+ moonep_runtime.activation_edge("Z4", z4)
374+ 
375+ # GR's fused WORLD completes peer readers; same-Q0 clear/Z4
376+ # and the retained segment drain precede DDP-ready/retirement.
377+ # Prepare in the existing peer gate while GMM/GR is in flight:
378+ # partial allocation failures must be agreed before any rank
379+ # advances. Zero-filled fallbacks join this segment's drain.
380+ moonep_runtime.complete(
381+ peer=True, native_fence=False,
382+ check=lambda: _prepare_dummy_gradients(weights, dummy, dummy_specs),
383+ )
384+ moonep_runtime.end_submission_segment()
385+ virtual_experts.finalize_grads()
386+ # Every allocation is private until completion AND validation.
387+ _validate_dummy_gradients(weights, dummy, dummy_specs)
388+ if not plan.dispatch_backward_expected:
389+ manager.retire(plan)
390+ for parameter in weights:
391+ if hasattr(parameter, "grad_added_to_main_grad"):
392+ parameter.grad_added_to_main_grad = True
393+ return (z4, grad_probs, None, None, None, *dummy)
394+ except Exception as exc:
395+ moonep_runtime.abort_submission_segment(exc)
396+ manager.fail_stop(plan, exc, tuple(locals().values()))
397+ raise
398+ 
399+ return Dispatch, Combine, Experts
400+ 
401+ 
402+_AUTOGRAD_TYPES = None
403+ 
404+ 
405+def _autograd_types():
406+ global _AUTOGRAD_TYPES
407+ if _AUTOGRAD_TYPES is None:
408+ _AUTOGRAD_TYPES = _types()
409+ return _AUTOGRAD_TYPES
410+ 
411+ 
412+def dispatch_apply(hidden, probs, indices, counts, manager):
413+ from . import moonep_runtime
414+ 
415+ dispatch_backward_expected, expert_backward_expected = _backward_expectations(
416+ hidden, probs, manager.virtual_experts
417+ )
418+ try:
419+ z1, dispatched_probs = _autograd_types()[0].apply(
420+ hidden,
421+ probs,
422+ indices,
423+ counts,
424+ manager,
425+ dispatch_backward_expected,
426+ expert_backward_expected,
427+ )
428+ plan = manager.forward_plan()
429+ moonep_runtime.activation_edge("Z1", z1)
430+ return z1, dispatched_probs, plan
431+ except Exception as exc:
432+ manager.fail_stop(None, exc, tuple(locals().values()))
433+ raise
434+ 
435+ 
436+def combine_apply(expert_output, manager, plan):
437+ return _autograd_types()[1].apply(expert_output, plan, manager)
438+ 
439+ 
440+def moonep_grouped_mlp_forward_wrapper(forward):
441+ @wraps(forward)
442+ def wrapper(experts, hidden, tokens_per_expert, probs, *args, **kwargs):
443+ manager_ref = getattr(experts, "_mindspeed_moonep_manager_ref", None)
444+ if manager_ref is None:
445+ return forward(experts, hidden, tokens_per_expert, probs, *args, **kwargs)
446+ if args or kwargs:
447+ raise RuntimeError("MoonEP routed experts do not accept extra forward arguments")
448+ manager = manager_ref()
449+ if manager is None:
450+ raise RuntimeError("MoonEP manager disappeared before expert forward")
451+ plan = manager.forward_plan()
452+ if tokens_per_expert is not plan.group_counts_2l:
453+ raise RuntimeError("MoonEP counts are not the original plan Tensor")
454+ if (
455+ tuple(tokens_per_expert.shape) != tuple(plan.group_counts_2l.shape)
456+ or tokens_per_expert.data_ptr() != plan.group_counts_2l.data_ptr()
457+ ):
458+ raise RuntimeError("MoonEP expert counts do not belong to the exact dispatch plan")
459+ original = manager.consume_forward_source(plan)
460+ weights = manager.virtual_experts.source_parameters
461+ output = _autograd_types()[2].apply(
462+ hidden, probs, original, plan, manager, *weights
463+ )
464+ return output, None
465+ 
466+ return wrapper
@@ -39,6 +39,7 @@ from mindspeed.features_manager.tensor_parallel.locl_coc import CoCFeature
39 39 
40from mindspeed.features_manager.moe.tp_extend_ep import MoETpExtendEpFeature40from mindspeed.features_manager.moe.tp_extend_ep import MoETpExtendEpFeature
41from mindspeed.features_manager.moe.gmm import MoEGmmFeature41from mindspeed.features_manager.moe.gmm import MoEGmmFeature
42+from mindspeed.features_manager.moe.moonep import MoonepFeature
42from mindspeed.features_manager.moe.shared_expert import MoESharedExpertsFeature43from mindspeed.features_manager.moe.shared_expert import MoESharedExpertsFeature
43from mindspeed.features_manager.moe.fb_overlap import MoEFwdBwdOverlapFeature44from mindspeed.features_manager.moe.fb_overlap import MoEFwdBwdOverlapFeature
44from mindspeed.features_manager.moe.balanced_moe import BalancedMoEFeature45from mindspeed.features_manager.moe.balanced_moe import BalancedMoEFeature
@@ -226,6 +227,7 @@ def add_transformer_features(features_list: List[MindSpeedFeature]):
226def add_moe_features(features_list: List[MindSpeedFeature]):227def add_moe_features(features_list: List[MindSpeedFeature]):
227 features_list.extend(228 features_list.extend(
228 [229 [
230+ MoonepFeature(),
229 MoEGmmFeature(),231 MoEGmmFeature(),
230 MoETpExtendEpFeature(),232 MoETpExtendEpFeature(),
231 MoESharedExpertsFeature(),233 MoESharedExpertsFeature(),
@@ -79,7 +79,13 @@ def te_grouped_linear_init_wrapper(fn):
79 parallel_mode = bound_args.arguments.get('parallel_mode')79 parallel_mode = bound_args.arguments.get('parallel_mode')
80 config = bound_args.arguments.get('config')80 config = bound_args.arguments.get('config')
81 mindspeed_args = get_full_args()81 mindspeed_args = get_full_args()
82- config.moe_single_grouped_weight = getattr(mindspeed_args, 'te_gmm_mode', 'compatible') == 'performance'82+ moon_ep = (
83+ getattr(mindspeed_args, 'moe_token_dispatcher_type', None) == 'flex'
84+ and getattr(mindspeed_args, 'moe_flex_dispatcher_backend', None) == 'moonep'
85+ )
86+ config.moe_single_grouped_weight = (
87+ not moon_ep and getattr(mindspeed_args, 'te_gmm_mode', 'compatible') == 'performance'
88+ )
83 89 
84 fn(self, *args, **kwargs)90 fn(self, *args, **kwargs)
85 91 
@@ -93,7 +99,7 @@ def te_grouped_linear_init_wrapper(fn):
93 99 
94 100 
95def tenpu_grouped_linear_init_wrapper(fn):101def tenpu_grouped_linear_init_wrapper(fn):
96- """Preserve explicit layout, or supply TE-GMM mode when MCore omits it."""102+ """Preserve explicit layout and require per-expert Parameters for MoonEP."""
97 fn_signature = signature(fn)103 fn_signature = signature(fn)
98 104 
99 @wraps(fn)105 @wraps(fn)
@@ -101,11 +107,18 @@ def tenpu_grouped_linear_init_wrapper(fn):
101 from mindspeed.args_utils import get_full_args107 from mindspeed.args_utils import get_full_args
102 108 
103 bound_args = fn_signature.bind(self, *args, **kwargs)109 bound_args = fn_signature.bind(self, *args, **kwargs)
110+ mindspeed_args = get_full_args()
111+ moon_ep = (
112+ getattr(mindspeed_args, 'moe_token_dispatcher_type', None) == 'flex'
113+ and getattr(mindspeed_args, 'moe_flex_dispatcher_backend', None) == 'moonep'
114+ )
115+ if moon_ep:
116+ bound_args.arguments['single_grouped_weight'] = False
104 # MCore only forwards this argument for TE >= 2.14, whereas TE-NPU117 # MCore only forwards this argument for TE >= 2.14, whereas TE-NPU
105 # already supports it at 2.13. Keep performance mode working there.118 # already supports it at 2.13. Keep performance mode working there.
106- if 'single_grouped_weight' not in bound_args.arguments:119+ elif 'single_grouped_weight' not in bound_args.arguments:
107 bound_args.arguments['single_grouped_weight'] = (120 bound_args.arguments['single_grouped_weight'] = (
108- getattr(get_full_args(), 'te_gmm_mode', 'compatible') == 'performance'121+ getattr(mindspeed_args, 'te_gmm_mode', 'compatible') == 'performance'
109 )122 )
110 return fn(*bound_args.args, **bound_args.kwargs)123 return fn(*bound_args.args, **bound_args.kwargs)
111 124 
@@ -0,0 +1,88 @@
1+"""Feature gate for the private synchronous Ascend MoonEP adapter."""
2+ 
3+from argparse import ArgumentParser
4+from importlib.util import find_spec
5+from mindspeed.core.transformer.moe.moonep.moonep_contract import moonep_enabled, validate_moonep_args
6+from mindspeed.features_manager.feature import MindSpeedFeature
7+ 
8+ 
9+class MoonepFeature(MindSpeedFeature):
10+ def __init__(self):
11+ super().__init__("moonep", 2)
12+ 
13+ def is_need_apply(self, args):
14+ return moonep_enabled(args)
15+ 
16+ def register_args(self, parser: ArgumentParser):
17+ self.add_parser_argument_choices_value(parser, "--moe-flex-dispatcher-backend", "moonep")
18+ group = parser.add_argument_group(title="Ascend MoonEP")
19+ group.add_argument(
20+ "--moonep-activation-zero-copy",
21+ action="store_true",
22+ help="Require strict caller-owned Z1-Z4/R1 activation buffers (default: COPY-SYNC).",
23+ )
24+ 
25+ def validate_args(self, args):
26+ validate_moonep_args(args)
27+ 
28+ def register_patches(self, patch_manager, args):
29+ if not moonep_enabled(args):
30+ return
31+ # Missing optional Bridge is valid for Core-only training. A present
32+ # package still follows normal patch resolution: do not hide its errors.
33+ bridge_available = find_spec("megatron.bridge") is not None
34+ from mindspeed.core.transformer.moe.moonep.moonep import (
35+ build_moonep_flex_token_dispatcher,
36+ destroy_model_parallel_wrapper,
37+ moonep_moe_layer_init_wrapper,
38+ moonep_moe_layer_postprocess_wrapper,
39+ moonep_moe_layer_route_wrapper,
40+ save_checkpoint_wrapper,
41+ setup_wrapper,
42+ )
43+ from mindspeed.core.transformer.moe.moonep.moonep_executor import (
44+ moonep_grouped_mlp_forward_wrapper,
45+ )
46+ 
47+ dispatcher = build_moonep_flex_token_dispatcher()
48+ for target in (
49+ "megatron.core.transformer.moe.token_dispatcher.MoEFlexTokenDispatcher",
50+ "megatron.core.transformer.moe.moe_layer.MoEFlexTokenDispatcher",
51+ ):
52+ patch_manager.register_patch(target, dispatcher, force_patch=True)
53+ patch_manager.register_patch(
54+ "megatron.core.transformer.moe.moe_layer.MoELayer.__init__",
55+ moonep_moe_layer_init_wrapper,
56+ )
57+ patch_manager.register_patch(
58+ "megatron.core.transformer.moe.moe_layer.MoELayer.route",
59+ moonep_moe_layer_route_wrapper,
60+ )
61+ patch_manager.register_patch(
62+ "megatron.core.transformer.moe.moe_layer.MoELayer.postprocess",
63+ moonep_moe_layer_postprocess_wrapper,
64+ )
65+ patch_manager.register_patch(
66+ "megatron.core.transformer.moe.experts.TEGroupedMLP.forward",
67+ moonep_grouped_mlp_forward_wrapper,
68+ )
69+ setup_targets = (
70+ "megatron.training.training.setup_model_and_optimizer",
71+ "mindspeed.training.setup_model_and_optimizer",
72+ )
73+ checkpoint_targets = (
74+ "megatron.training.training.save_checkpoint",
75+ "megatron.training.checkpointing.save_checkpoint",
76+ "mindspeed.training.save_checkpoint",
77+ )
78+ if bridge_available:
79+ setup_targets += ("megatron.bridge.training.setup.setup",)
80+ checkpoint_targets += ("megatron.bridge.training.checkpointing.save_checkpoint",)
81+ for target in setup_targets:
82+ patch_manager.register_patch(target, setup_wrapper)
83+ for target in checkpoint_targets:
84+ patch_manager.register_patch(target, save_checkpoint_wrapper)
85+ patch_manager.register_patch(
86+ "megatron.core.parallel_state.destroy_model_parallel",
87+ destroy_model_parallel_wrapper,
88+ )
@@ -13,6 +13,16 @@
13// See the License for the specific language governing permissions and13// See the License for the specific language governing permissions and
14// limitations under the License.14// limitations under the License.
15#include <torch/extension.h>15#include <torch/extension.h>
16+#include <cstdint>
17+#include <cstdlib>
18+#include <limits.h>
19+#include <memory>
20+#include <mutex>
21+#include <map>
22+#include <set>
23+#include <sstream>
24+#include <sys/stat.h>
25+#include <thread>
16#include <torch_npu/csrc/framework/utils/RandomOpAdapter.h>26#include <torch_npu/csrc/framework/utils/RandomOpAdapter.h>
17#include <torch_npu/csrc/framework/utils/OpAdapter.h>27#include <torch_npu/csrc/framework/utils/OpAdapter.h>
18#include <torch_npu/csrc/core/npu/NPUFormat.h>28#include <torch_npu/csrc/core/npu/NPUFormat.h>
@@ -292,6 +302,429 @@ std::tuple<std::vector<at::Tensor>, std::vector<at::Tensor>, std::vector<at::Ten
292 return std::make_tuple(dx, dw_output, dbias);302 return std::make_tuple(dx, dw_output, dbias);
293}303}
294 304 
305+namespace moonep_standard {
306+// Only these two MoonEP entry points use this owner. An explicitly opened
307+// segment retains device storage until one checked caller-stream completion.
308+// The generic GMM paths above and calls outside a segment are unchanged.
309+using Run = int (*)(void*, uint64_t, aclOpExecutor*, aclrtStream);
310+using V5Query = int (*)(const aclTensorList*, const aclTensorList*, const aclTensorList*,
311+ const aclTensorList*, const aclTensorList*, const aclTensorList*, const aclTensorList*,
312+ const aclTensorList*, const aclTensor*, const aclTensorList*, const aclTensorList*,
313+ const aclTensorList*, int64_t, int64_t, int64_t, int64_t, aclIntArray*, aclTensorList*,
314+ aclTensorList*, aclTensorList*, uint64_t*, aclOpExecutor**);
315+using AddQuery = int (*)(const aclTensor*, const aclTensor*, const aclTensor*, aclTensor*,
316+ bool, bool, int64_t, int64_t, uint64_t*, aclOpExecutor**);
317+ 
318+std::string canonical(const char* value)
319+{
320+ TORCH_CHECK(value && value[0] == '/', "MoonEP requires an absolute standard library path");
321+ char resolved[PATH_MAX];
322+ TORCH_CHECK(realpath(value, resolved), "cannot resolve standard library: ", value);
323+ struct stat st;
324+ TORCH_CHECK(stat(resolved, &st) == 0 && S_ISREG(st.st_mode), "standard library is not a regular file");
325+ const std::string path(resolved);
326+ TORCH_CHECK(path.find("cust") == std::string::npos, "custom opapi libraries are forbidden");
327+ return path;
328+}
329+ 
330+struct Library {
331+ std::string selection;
332+ std::string path;
333+ std::string dependencies;
334+ std::set<std::string> allowed;
335+ std::vector<void*> handles;
336+ std::map<std::string, std::string> owners;
337+ V5Query v5_query = nullptr;
338+ Run v5_run = nullptr;
339+ AddQuery add_query = nullptr;
340+ Run add_run = nullptr;
341+ _aclCreateTensor create_tensor = nullptr;
342+ _aclDestroyTensor destroy_tensor = nullptr;
343+ _aclCreateTensorList create_list = nullptr;
344+ _aclDestroyTensorList destroy_list = nullptr;
345+ InitHugeMemThreadLocal init_memory = nullptr;
346+ UnInitHugeMemThreadLocal uninit_memory = nullptr;
347+ ReleaseHugeMem release_memory = nullptr;
348+ 
349+ Library()
350+ {
351+ const char* selected = std::getenv("MINDSPEED_MOONEP_OPAPI");
352+ selection = selected ? selected : "";
353+ path = canonical(selection.c_str());
354+ TORCH_CHECK(path.substr(path.find_last_of('/') + 1) == "libopapi.so", "select standard libopapi.so");
355+ const char* raw = std::getenv("MINDSPEED_MOONEP_OPAPI_DEPENDENCIES");
356+ dependencies = raw ? raw : "";
357+ allowed.insert(path);
358+ std::stringstream parts(dependencies);
359+ std::string item;
360+ while (std::getline(parts, item, ':')) {
361+ TORCH_CHECK(!item.empty(), "empty standard dependency path");
362+ const auto dependency = canonical(item.c_str());
363+ TORCH_CHECK(allowed.insert(dependency).second, "duplicate standard dependency");
364+ void* handle = dlopen(dependency.c_str(), RTLD_NOW | RTLD_LOCAL);
365+ TORCH_CHECK(handle, "cannot load declared standard dependency: ", dependency);
366+ handles.push_back(handle);
367+ }
368+ TORCH_CHECK(dependencies.empty() || dependencies.back() != ':', "empty standard dependency path");
369+ void* handle = dlopen(path.c_str(), RTLD_NOW | RTLD_LOCAL);
370+ TORCH_CHECK(handle, "cannot load selected standard libopapi.so");
371+ handles.insert(handles.begin(), handle);
372+ // Publish this process-lifetime owner only after the entire fixed ABI
373+ // has been resolved and each symbol's actual provider has been checked.
374+ v5_query = symbol<V5Query>("aclnnGroupedMatmulV5GetWorkspaceSize", true);
375+ v5_run = symbol<Run>("aclnnGroupedMatmulV5", true);
376+ add_query = symbol<AddQuery>("aclnnGroupedMatmulAddV2GetWorkspaceSize", true);
377+ add_run = symbol<Run>("aclnnGroupedMatmulAddV2", true);
378+ create_tensor = symbol<_aclCreateTensor>("aclCreateTensor");
379+ destroy_tensor = symbol<_aclDestroyTensor>("aclDestroyTensor");
380+ create_list = symbol<_aclCreateTensorList>("aclCreateTensorList");
381+ destroy_list = symbol<_aclDestroyTensorList>("aclDestroyTensorList");
382+ init_memory = symbol<InitHugeMemThreadLocal>("InitHugeMemThreadLocal");
383+ uninit_memory = symbol<UnInitHugeMemThreadLocal>("UnInitHugeMemThreadLocal");
384+ release_memory = symbol<ReleaseHugeMem>("ReleaseHugeMem");
385+ }
386+ 
387+ void unchanged() const
388+ {
389+ const char* selected = std::getenv("MINDSPEED_MOONEP_OPAPI");
390+ const char* raw = std::getenv("MINDSPEED_MOONEP_OPAPI_DEPENDENCIES");
391+ TORCH_CHECK(selection == (selected ? selected : "") &&
392+ dependencies == (raw ? raw : ""), "MoonEP standard library selection changed");
393+ }
394+ 
395+ template<class F> F symbol(const char* name, bool operation = false)
396+ {
397+ void* address = nullptr;
398+ for (auto handle : handles) {
399+ address = dlsym(handle, name);
400+ if (address) break;
401+ }
402+ TORCH_CHECK(address, "missing standard symbol: ", name);
403+ Dl_info info{};
404+ TORCH_CHECK(dladdr(address, &info) && info.dli_fname, "missing symbol owner: ", name);
405+ const auto owner = canonical(info.dli_fname);
406+ TORCH_CHECK(operation ? owner == path : allowed.count(owner) == 1,
407+ "undeclared standard symbol owner: ", name, " at ", owner);
408+ owners[name] = owner;
409+ return reinterpret_cast<F>(address);
410+ }
411+};
412+ 
413+Library& library()
414+{
415+ // Library handles deliberately remain loaded while any failed call may own
416+ // an executor or device-visible descriptor from that library.
417+ static auto* value = new Library();
418+ value->unchanged();
419+ return *value;
420+}
421+ 
422+std::map<std::string, std::string> backend_info()
423+{
424+ return library().owners;
425+}
426+ 
427+struct Call {
428+ Library* owner = nullptr; // Library and its validated handles outlive every Call.
429+ std::vector<at::Tensor> tensors;
430+ at::Tensor workspace;
431+ std::vector<aclTensor*> descriptors;
432+ std::vector<aclTensorList*> lists;
433+ aclOpExecutor* executor = nullptr;
434+ bool tls = false;
435+ 
436+ aclTensor* tensor(const at::Tensor& value)
437+ {
438+ TORCH_CHECK(!value.unsafeGetTensorImpl()->is_wrapped_number(), "wrapped scalars are forbidden");
439+ TORCH_CHECK(at_npu::native::get_npu_format(value) == ACL_FORMAT_ND, "MoonEP tensors must be ND");
440+ tensors.push_back(value);
441+ const int64_t storage_size = value.storage().nbytes() / value.element_size();
442+ auto descriptor = owner->create_tensor(
443+ value.sizes().data(), value.dim(), kATenScalarTypeToAclDataTypeTable[static_cast<int64_t>(value.scalar_type())],
444+ value.strides().data(), value.storage_offset(), ACL_FORMAT_ND, &storage_size, 1,
445+ const_cast<void*>(value.storage().data()));
446+ TORCH_CHECK(descriptor, "aclCreateTensor failed");
447+ descriptors.push_back(descriptor);
448+ return descriptor;
449+ }
450+ 
451+ aclTensorList* list(const std::vector<at::Tensor>& values)
452+ {
453+ std::vector<const aclTensor*> items;
454+ for (const auto& value : values) items.push_back(tensor(value));
455+ auto result = owner->create_list(items.data(), items.size());
456+ TORCH_CHECK(result, "aclCreateTensorList failed");
457+ lists.push_back(result);
458+ // Fixed opbase aclDestroyTensorList destroys its element descriptors.
459+ // Transfer only after successful list creation; failed construction
460+ // leaves the individual descriptors owned by this Call.
461+ descriptors.resize(descriptors.size() - items.size());
462+ return result;
463+ }
464+ 
465+ void release()
466+ {
467+ auto& lib = *owner;
468+ while (!lists.empty()) {
469+ TORCH_CHECK(lib.destroy_list(lists.back()) == 0,
470+ "aclDestroyTensorList failed");
471+ lists.pop_back();
472+ }
473+ while (!descriptors.empty()) {
474+ TORCH_CHECK(lib.destroy_tensor(descriptors.back()) == 0,
475+ "aclDestroyTensor failed");
476+ descriptors.pop_back();
477+ }
478+ lib.release_memory(nullptr, false);
479+ lib.uninit_memory(nullptr, false);
480+ tls = false;
481+ }
482+};
483+ 
484+bool failed = false;
485+struct Segment {
486+ bool active = false;
487+ std::thread::id thread;
488+ int device = -1;
489+ aclrtStream stream = nullptr;
490+ // Experts.forward uses two calls; backward uses at most four. Reserve
491+ // roots before submitting anything, and reject accidental scope growth.
492+ std::vector<std::shared_ptr<Call>> calls;
493+};
494+ 
495+Segment& segment()
496+{
497+ // Never run Tensor destructors during extension/runtime static teardown.
498+ static auto* value = new Segment();
499+ return *value;
500+}
501+ 
502+std::mutex& owner_mutex()
503+{
504+ static auto* value = new std::mutex();
505+ return *value;
506+}
507+ 
508+void check_segment(c10_npu::NPUStream current, aclrtStream stream)
509+{
510+ auto& value = segment();
511+ TORCH_CHECK(value.active && value.thread == std::this_thread::get_id(),
512+ "MoonEP segment belongs to another host thread or is not active");
513+ TORCH_CHECK(value.device == current.device_index() && value.stream == stream,
514+ "MoonEP segment device/caller stream changed");
515+}
516+ 
517+void begin_segment()
518+{
519+ std::lock_guard<std::mutex> lock(owner_mutex());
520+ TORCH_CHECK(!failed, "MoonEP standard compute owner is failed; process restart required");
521+ auto& value = segment();
522+ TORCH_CHECK(!value.active && value.calls.empty(), "MoonEP nested or unfinished segment");
523+ value.calls.reserve(4);
524+ auto current = c10_npu::getCurrentNPUStream();
525+ auto stream = current.stream(); // drain Q1; do not wait for device work
526+ TORCH_CHECK(stream, "MoonEP segment caller stream is null");
527+ value.thread = std::this_thread::get_id();
528+ value.device = current.device_index();
529+ value.stream = stream;
530+ value.active = true;
531+}
532+ 
533+uint64_t flush_segment()
534+{
535+ std::lock_guard<std::mutex> lock(owner_mutex());
536+ TORCH_CHECK(!failed, "MoonEP standard compute owner is failed; process restart required");
537+ try {
538+ auto current = c10_npu::getCurrentNPUStream();
539+ auto stream = current.stream(); // producer Q1 commands precede raw ACL barriers
540+ check_segment(current, stream);
541+ return reinterpret_cast<uintptr_t>(stream);
542+ } catch (...) {
543+ failed = true;
544+ throw;
545+ }
546+}
547+ 
548+void end_segment()
549+{
550+ std::lock_guard<std::mutex> lock(owner_mutex());
551+ TORCH_CHECK(!failed, "MoonEP standard compute owner is failed; process restart required");
552+ try {
553+ auto current = c10_npu::getCurrentNPUStream();
554+ auto stream = current.stream();
555+ check_segment(current, stream);
556+ current.synchronize(); // the single physical completion before storage retirement
557+ segment().calls.clear();
558+ segment().active = false;
559+ } catch (...) {
560+ failed = true; // retain every call, not just the last submitted operation
561+ throw;
562+ }
563+}
564+ 
565+void abort_segment()
566+{
567+ std::lock_guard<std::mutex> lock(owner_mutex());
568+ failed = true; // intentionally retain roots, even if completion is unknown
569+}
570+ 
571+std::map<std::string, uint64_t> segment_info()
572+{
573+ std::lock_guard<std::mutex> lock(owner_mutex());
574+ uint64_t workspace = 0;
575+ for (const auto& call : segment().calls) {
576+ if (call->workspace.defined()) workspace += call->workspace.numel();
577+ }
578+ return {{"active", segment().active}, {"failed", failed},
579+ {"pending_calls", segment().calls.size()}, {"max_calls", 4},
580+ {"pending_workspace_bytes", workspace}};
581+}
582+ 
583+std::shared_ptr<Call>& quarantine()
584+{
585+ static auto* retained = new std::shared_ptr<Call>();
586+ return *retained;
587+}
588+ 
589+template<class Query> void execute(const at::Tensor& input, const char* operation, Run Library::*run, Query query)
590+{
591+ std::lock_guard<std::mutex> lock(owner_mutex());
592+ TORCH_CHECK(!failed, "MoonEP standard compute owner is failed; process restart required");
593+ auto& retained = quarantine(); // allocate the strong root before submission
594+ auto call = std::make_shared<Call>();
595+ try {
596+ auto& lib = library();
597+ call->owner = &lib;
598+ auto current = c10_npu::getCurrentNPUStream();
599+ TORCH_CHECK(input.device().index() == current.device_index(), "wrong current NPU device");
600+ auto stream = current.stream(); // public accessor drains the caller's Q1
601+ TORCH_CHECK(stream, "current NPU stream is null after Q1 drain");
602+ check_segment(current, stream);
603+ TORCH_CHECK(segment().calls.size() < 4, "MoonEP segment exceeds four GMM calls");
604+ segment().calls.push_back(call); // strong root precedes query/launch
605+ TORCH_CHECK(lib.init_memory(nullptr, false) == 0,
606+ "InitHugeMemThreadLocal failed");
607+ call->tls = true;
608+ uint64_t bytes = 0;
609+ query(*call, bytes);
610+ TORCH_CHECK(call->executor, "standard workspace query returned a null executor");
611+ TORCH_CHECK(bytes <= static_cast<uint64_t>(INT64_MAX), "workspace size overflow");
612+ if (bytes) call->workspace = at::empty({static_cast<int64_t>(bytes)}, input.options().dtype(at::kByte));
613+ TORCH_CHECK((lib.*run)(
614+ bytes ? call->workspace.data_ptr() : nullptr, bytes, call->executor, stream) == 0,
615+ "standard operator launch failed: ", operation);
616+ // ACLNN host submission has returned. Match descriptor/TLS cleanup on
617+ // this same thread (as in the standard TorchNPU asynchronous adapter).
618+ // Segment roots keep workspace and Tensor storage alive independently.
619+ call->release();
620+ } catch (...) {
621+ failed = true;
622+ retained = call; // shared_ptr assignment allocates nothing while unwinding
623+ throw; // never mask the first query/launch/completion/cleanup error
624+ }
625+}
626+ 
627+void metadata(const at::Tensor& value, const at::Tensor& reference)
628+{
629+ TORCH_CHECK(value.device() == reference.device() && value.device().type() == c10::DeviceType::PrivateUse1,
630+ "MoonEP tensors must use one NPU device");
631+ TORCH_CHECK(!value.requires_grad(), "MoonEP standard compute requires detached aliases");
632+ TORCH_CHECK(!value.is_neg() && !value.is_conj(), "lazy negative/conjugate views are forbidden");
633+ TORCH_CHECK(value.storage_offset() >= 0, "negative storage offset");
634+ int64_t last = value.storage_offset();
635+ for (int64_t dim = 0; dim < value.dim(); ++dim) {
636+ TORCH_CHECK(value.stride(dim) >= 0, "negative strides are forbidden");
637+ if (value.size(dim)) last += (value.size(dim) - 1) * value.stride(dim);
638+ }
639+ TORCH_CHECK(!value.numel() || static_cast<uint64_t>(last + 1) <= value.storage().nbytes() / value.element_size(),
640+ "Tensor view exceeds its backing");
641+}
642+ 
643+void disjoint(const at::Tensor& out, const at::Tensor& input)
644+{
645+ if (!out.numel() || !input.numel()) return;
646+ const auto begin = reinterpret_cast<uintptr_t>(out.data_ptr());
647+ const auto other = reinterpret_cast<uintptr_t>(input.data_ptr());
648+ TORCH_CHECK(begin + out.numel() * out.element_size() <= other ||
649+ other + input.numel() * input.element_size() <= begin, "MoonEP output aliases an input");
650+}
651+}
652+ 
653+at::Tensor npu_gmm_v5_out(const at::Tensor& x,
654+ const std::vector<at::Tensor>& weight,
655+ const at::Tensor& out,
656+ const at::Tensor& group_list)
657+{
658+ TORCH_CHECK(x.scalar_type() == at::kBFloat16, "npu_gmm_v5_out requires BF16 x");
659+ TORCH_CHECK(out.scalar_type() == at::kBFloat16, "npu_gmm_v5_out requires BF16 out");
660+ TORCH_CHECK(group_list.scalar_type() == at::kLong && group_list.dim() == 1,
661+ "npu_gmm_v5_out requires a 1-D INT64 group count tensor");
662+ TORCH_CHECK(!weight.empty() && weight.size() == static_cast<size_t>(group_list.size(0)),
663+ "weight refs and group counts must have the same non-zero length");
664+ TORCH_CHECK(x.is_contiguous() && out.is_contiguous() && group_list.is_contiguous(),
665+ "npu_gmm_v5_out forbids implicit contiguous/copy fallbacks");
666+ for (size_t index = 0; index < weight.size(); ++index) {
667+ TORCH_CHECK(weight[index].scalar_type() == at::kBFloat16,
668+ "every weight ref must be BF16");
669+ TORCH_CHECK(weight[index].is_contiguous() ||
670+ (weight[index].dim() == 2 && weight[index].stride(0) == 1 &&
671+ weight[index].stride(1) == weight[index].size(0)),
672+ "every weight ref must be contiguous or a zero-copy 2-D transpose view");
673+ }
674+ 
675+ TORCH_CHECK(x.dim() == 2 && out.dim() == 2 && x.size(0) == out.size(0), "V5 requires matching token matrices");
676+ moonep_standard::metadata(x, x);
677+ moonep_standard::metadata(out, x);
678+ moonep_standard::metadata(group_list, x);
679+ moonep_standard::disjoint(out, x);
680+ moonep_standard::disjoint(out, group_list);
681+ for (const auto& item : weight) {
682+ moonep_standard::metadata(item, x);
683+ TORCH_CHECK(item.dim() == 2 && item.size(0) == x.size(1) && item.size(1) == out.size(1),
684+ "V5 weight ref shape mismatch");
685+ moonep_standard::disjoint(out, item);
686+ }
687+ moonep_standard::execute(x, "aclnnGroupedMatmulV5", &moonep_standard::Library::v5_run,
688+ [&](moonep_standard::Call& call, uint64_t& bytes) {
689+ auto inputs = call.list({x});
690+ auto weights = call.list(weight);
691+ auto outputs = call.list({out});
692+ auto groups = call.tensor(group_list);
693+ TORCH_CHECK(call.owner->v5_query(inputs, weights, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr,
694+ groups, nullptr, nullptr, nullptr, 3, 0, 1, 0, nullptr, outputs, nullptr, nullptr,
695+ &bytes, &call.executor) == 0, "GroupedMatmulV5 workspace query failed");
696+ });
697+ return out;
698+}
699+ 
700+at::Tensor npu_grouped_matmul_add_fp32_out(const at::Tensor& dy, const at::Tensor& x,
701+ const at::Tensor& scratch, const at::Tensor& prefix)
702+{
703+ TORCH_CHECK(x.scalar_type() == at::kBFloat16 && dy.scalar_type() == at::kBFloat16,
704+ "AddV2 requires BF16 x and dy");
705+ TORCH_CHECK(x.dim() == 2 && dy.dim() == 2 && x.size(0) == dy.size(0), "AddV2 token matrix mismatch");
706+ TORCH_CHECK(prefix.scalar_type() == at::kLong && prefix.dim() == 1 && prefix.numel() > 0,
707+ "AddV2 requires an INT64 prefix vector");
708+ TORCH_CHECK(scratch.scalar_type() == at::kFloat && scratch.dim() == 3 &&
709+ scratch.size(0) == prefix.numel() && scratch.size(1) == dy.size(1) && scratch.size(2) == x.size(1),
710+ "AddV2 requires FP32 scratch[G,O,I]");
711+ for (const auto& item : {x, dy, scratch, prefix}) {
712+ moonep_standard::metadata(item, x);
713+ TORCH_CHECK(item.is_contiguous(), "AddV2 forbids implicit copies");
714+ }
715+ for (const auto& item : {x, dy, prefix}) moonep_standard::disjoint(scratch, item);
716+ moonep_standard::execute(x, "aclnnGroupedMatmulAddV2", &moonep_standard::Library::add_run,
717+ [&](moonep_standard::Call& call, uint64_t& bytes) {
718+ auto grad = call.tensor(dy);
719+ auto input = call.tensor(x);
720+ auto groups = call.tensor(prefix);
721+ auto output = call.tensor(scratch);
722+ TORCH_CHECK(call.owner->add_query(grad, input, groups, output, true, false, 2, 0, &bytes, &call.executor) == 0,
723+ "GroupedMatmulAddV2 workspace query failed");
724+ });
725+ return scratch;
726+}
727+ 
295PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {728PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
296 using gmmv1 = std::vector<at::Tensor>(*)(const std::vector<at::Tensor>&, const std::vector<at::Tensor>&, const std::vector<at::Tensor>&, c10::optional<std::vector<int64_t>>, c10::optional<int64_t>, c10::optional<int64_t>);729 using gmmv1 = std::vector<at::Tensor>(*)(const std::vector<at::Tensor>&, const std::vector<at::Tensor>&, const std::vector<at::Tensor>&, c10::optional<std::vector<int64_t>>, c10::optional<int64_t>, c10::optional<int64_t>);
297 using gmmv2 = std::vector<at::Tensor>(*)(const std::vector<at::Tensor>&, const std::vector<at::Tensor>&, const std::vector<at::Tensor>&, const c10::optional<at::Tensor>&, c10::optional<int64_t>, c10::optional<int64_t>);730 using gmmv2 = std::vector<at::Tensor>(*)(const std::vector<at::Tensor>&, const std::vector<at::Tensor>&, const std::vector<at::Tensor>&, const c10::optional<at::Tensor>&, c10::optional<int64_t>, c10::optional<int64_t>);
@@ -306,4 +739,13 @@ PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
306 m.def("npu_gmm", (gmmv2)&npu_gmm, "grouped matmul forward with group_list type Tensor");739 m.def("npu_gmm", (gmmv2)&npu_gmm, "grouped matmul forward with group_list type Tensor");
307 m.def("npu_gmm_backward", (gmmv2_backward)&npu_gmm_backward, "grouped matmul backward with group_list type Tensor");740 m.def("npu_gmm_backward", (gmmv2_backward)&npu_gmm_backward, "grouped matmul backward with group_list type Tensor");
308 m.def("npu_gmm_backward_fusion", (gmmv2_backward_fusion)&npu_gmm_backward_fusion, "grouped matmul backward with group_list type Tensor");741 m.def("npu_gmm_backward_fusion", (gmmv2_backward_fusion)&npu_gmm_backward_fusion, "grouped matmul backward with group_list type Tensor");
742+ m.def("npu_gmm_v5_out", &npu_gmm_v5_out, "GroupedMatmulV5 with caller-owned output");
743+ m.def("npu_grouped_matmul_add_fp32_out", &npu_grouped_matmul_add_fp32_out,
744+ "BF16 grouped producer into caller-owned FP32 full-G scratch");
745+ m.def("moonep_standard_backend_info", &moonep_standard::backend_info);
746+ m.def("moonep_standard_begin_segment", &moonep_standard::begin_segment);
747+ m.def("moonep_standard_flush_segment", &moonep_standard::flush_segment);
748+ m.def("moonep_standard_end_segment", &moonep_standard::end_segment);
749+ m.def("moonep_standard_abort_segment", &moonep_standard::abort_segment);
750+ m.def("moonep_standard_segment_info", &moonep_standard::segment_info);
309}751}
@@ -1,3 +1,7 @@
1+import os
2+from pathlib import Path
3+from threading import Lock
4+ 
1import torch5import torch
2from torch.library import impl6from torch.library import impl
3from mindspeed.op_builder import GMMOpBuilder, GMMV2OpBuilder7from mindspeed.op_builder import GMMOpBuilder, GMMV2OpBuilder
@@ -5,7 +9,129 @@ from mindspeed.op_builder.builder import AS_LIBRARY
5from mindspeed.ops.npu_groupmatmul_add import npu_groupmatmul_add_fp329from mindspeed.ops.npu_groupmatmul_add import npu_groupmatmul_add_fp32
6 10 
7 11 
8-__all__ = ["npu_gmm", "npu_gmm_v2"]12+__all__ = ["npu_gmm", "npu_gmm_v2", "npu_gmm_v5_out", "npu_grouped_matmul_add_fp32_out"]
13+ 
14+ 
15+def _require_contiguous(tensor, name):
16+ if not isinstance(tensor, torch.Tensor):
17+ raise TypeError(f"{name} must be a torch.Tensor, got {type(tensor)}.")
18+ if not tensor.is_contiguous():
19+ raise ValueError(f"{name} must be contiguous; MoonEP does not permit a copy fallback.")
20+ if tensor.is_neg() or tensor.is_conj():
21+ raise ValueError(f"{name} cannot be a lazy negative/conjugate view.")
22+ 
23+ 
24+def npu_gmm_v5_out(x, weight_refs, out, group_counts_2l):
25+ """Run the fixed MoonEP V5 single-x/multi-weight/single-out contract."""
26+ _require_contiguous(x, "x")
27+ _require_contiguous(out, "out")
28+ _require_contiguous(group_counts_2l, "group_counts_2l")
29+ if x.dtype != torch.bfloat16 or out.dtype != torch.bfloat16:
30+ raise TypeError("npu_gmm_v5_out requires BF16 x and out.")
31+ if group_counts_2l.dtype != torch.int64 or group_counts_2l.dim() != 1:
32+ raise TypeError("group_counts_2l must be a one-dimensional INT64 tensor.")
33+ if not isinstance(weight_refs, (list, tuple)) or len(weight_refs) != group_counts_2l.numel():
34+ raise ValueError("weight_refs length must equal group_counts_2l length.")
35+ for index, weight in enumerate(weight_refs):
36+ if not isinstance(weight, torch.Tensor):
37+ raise TypeError(f"weight_refs[{index}] must be a Tensor.")
38+ transpose_view = (
39+ weight.dim() == 2
40+ and weight.stride(0) == 1
41+ and weight.stride(1) == weight.shape[0]
42+ )
43+ if not weight.is_contiguous() and not transpose_view:
44+ raise ValueError(
45+ f"weight_refs[{index}] must be contiguous or a zero-copy 2-D transpose view."
46+ )
47+ if weight.is_neg() or weight.is_conj():
48+ raise ValueError("Weight refs cannot use lazy negative/conjugate views.")
49+ if weight.dtype != torch.bfloat16 or weight.device != x.device:
50+ raise TypeError(f"weight_refs[{index}] must be BF16 on {x.device}.")
51+ if out.device != x.device or group_counts_2l.device != x.device:
52+ raise RuntimeError("x, out, group_counts_2l and all weight refs must be on one device.")
53+ 
54+ if x.dim() != 2 or out.dim() != 2 or x.shape[0] != out.shape[0] or not weight_refs:
55+ raise ValueError("V5 requires matching token matrices and nonempty refs.")
56+ if any(value.requires_grad for value in (x, out, group_counts_2l, *weight_refs)):
57+ raise RuntimeError("MoonEP native inputs must be detached aliases.")
58+ if any(tuple(weight.shape) != (x.shape[1], out.shape[1]) for weight in weight_refs):
59+ raise ValueError("V5 weight refs must match [input width, output width].")
60+ result = _standard_binding().npu_gmm_v5_out(x, list(weight_refs), out, group_counts_2l)
61+ _same_out(result, out)
62+ torch.autograd.graph.increment_version(out)
63+ return result
64+ 
65+ 
66+def npu_grouped_matmul_add_fp32_out(dy, x, scratch, prefix):
67+ """Standard AddV2 producer; the caller zeroes independent full-G scratch."""
68+ for value, name in ((dy, "dy"), (x, "x"), (scratch, "scratch"), (prefix, "prefix")):
69+ _require_contiguous(value, name)
70+ if value.requires_grad:
71+ raise RuntimeError("MoonEP native inputs must be detached aliases.")
72+ if x.dtype != torch.bfloat16 or dy.dtype != torch.bfloat16:
73+ raise TypeError("AddV2 requires two BF16 token tensors.")
74+ if x.dim() != 2 or dy.dim() != 2 or x.shape[0] != dy.shape[0]:
75+ raise ValueError("AddV2 requires token matrices with matching row counts.")
76+ if prefix.dtype != torch.int64 or prefix.dim() != 1 or not prefix.numel():
77+ raise TypeError("AddV2 requires a nonempty INT64 prefix vector.")
78+ if scratch.dtype != torch.float32 or tuple(scratch.shape) != (prefix.numel(), dy.shape[1], x.shape[1]):
79+ raise ValueError("AddV2 requires independent FP32 scratch[G,O,I].")
80+ if any(value.device != x.device for value in (dy, scratch, prefix)):
81+ raise ValueError("AddV2 tensors must share one device.")
82+ result = _standard_binding().npu_grouped_matmul_add_fp32_out(dy, x, scratch, prefix)
83+ _same_out(result, scratch)
84+ torch.autograd.graph.increment_version(scratch)
85+ return result
86+ 
87+ 
88+_standard_selection = None
89+_standard_module = None
90+_standard_lock = Lock()
91+ 
92+ 
93+def _standard_binding():
94+ global _standard_selection, _standard_module
95+ selection = (os.environ.get("MINDSPEED_MOONEP_OPAPI", ""),
96+ os.environ.get("MINDSPEED_MOONEP_OPAPI_DEPENDENCIES", ""))
97+ if _standard_selection is not None:
98+ if _standard_selection != selection:
99+ raise RuntimeError("MoonEP standard library selection changed.")
100+ return _standard_module
101+ with _standard_lock:
102+ if _standard_selection is not None:
103+ if _standard_selection != selection:
104+ raise RuntimeError("MoonEP standard library selection changed.")
105+ return _standard_module
106+ main, dependencies = selection
107+ entries = [main] + (dependencies.split(":") if dependencies else [])
108+ paths = []
109+ for entry in entries:
110+ path = Path(entry)
111+ if not path.is_absolute() or not path.is_file():
112+ raise RuntimeError("MoonEP requires absolute regular standard library files.")
113+ path = path.resolve(strict=True)
114+ if "cust" in str(path).lower():
115+ raise RuntimeError("Custom opapi providers are forbidden.")
116+ paths.append(str(path))
117+ if Path(paths[0]).name != "libopapi.so" or len(set(paths)) != len(paths):
118+ raise RuntimeError("Select one standard libopapi.so and unique explicit dependencies.")
119+ module = GMMFunction.builder2.load()
120+ if selection != (os.environ.get("MINDSPEED_MOONEP_OPAPI", ""),
121+ os.environ.get("MINDSPEED_MOONEP_OPAPI_DEPENDENCIES", "")):
122+ raise RuntimeError("MoonEP standard library selection changed during loading.")
123+ # These libraries must remain immutable for this process. Provenance is
124+ # audited at admission; warm calls still reject any selection change.
125+ _standard_module = module
126+ _standard_selection = selection
127+ return module
128+ 
129+ 
130+def _same_out(result, out):
131+ if (not isinstance(result, torch.Tensor) or result.data_ptr() != out.data_ptr()
132+ or result.storage_offset() != out.storage_offset() or result.shape != out.shape
133+ or result.stride() != out.stride() or result.dtype != out.dtype or result.device != out.device):
134+ raise RuntimeError("Standard grouped matmul violated caller-owned output identity.")
9 135 
10 136 
11def check_optional_tensor(tensor, device, name):137def check_optional_tensor(tensor, device, name):
@@ -0,0 +1,332 @@
1+"""Production zero-copy Autograd; persistent-bank CPU transport/native oracles.
2+ 
3+The framework wrapper and GMM Python guards execute unchanged. Only pointer
4+construction, transport, native math and DDP rules are CPU models, not NPU or
5+SHMEM evidence. Both persistent root banks and view banks are exercised.
6+"""
7+from types import SimpleNamespace
8+import gc
9+import weakref
10+import pytest,torch
11+from test_moonep_pr20_autograd import chain,_inputs,_reference,_DDPRuleFixture
12+from test_moonep_pr20_autograd import (
13+ test_uninitialized_dispatch_tails_are_cleared_on_all_three_edges as check_padding,
14+ test_two_microbatch_no_sync_preserves_old_main_grad_exactly_once as check_no_sync,
15+ test_backward_host_check_preserves_plan_and_version_rejections_before_push as check_versions,
16+ test_gr_failure_preserves_original_error_resources_and_closes_admission as check_gr_failure,
17+)
18+from mindspeed.core.transformer.moe.moonep import moonep_runtime as runtime
19+from mindspeed.core.transformer.moe.moonep import moonep_executor as executor
20+from mindspeed.core.transformer.moe.moonep import virtual_expert_load_balancer as ve
21+ 
22+def independent(tensor):
23+ header=torch.empty(0,dtype=tensor.dtype).set_(tensor.untyped_storage(),tensor.storage_offset(),tuple(tensor.shape),tuple(tensor.stride()))
24+ assert header._base is None and header.data_ptr()==tensor.data_ptr()
25+ assert header is not tensor
26+ return header
27+ 
28+def _strict_chain(chain,monkeypatch,view_bank):
29+ b=chain.buffer;backing=torch.empty(4,2,dtype=torch.bfloat16)
30+ b._ctx['hidden_buf_local']=backing[:] if view_bank else backing
31+ b._ctx['weights_buf_local']=torch.empty(4,dtype=torch.int32)
32+ b._ctx['NvS']=4
33+ original=b.dispatch;seen=[]
34+ def dispatch(hidden,**kwargs):
35+ assert kwargs.get('zero_copy') is True
36+ data,probs,cu,plan=original(hidden,**kwargs)
37+ with torch.no_grad():b._ctx['hidden_buf_local'].copy_(data)
38+ return b._ctx['hidden_buf_local'],probs,cu,plan
39+ def combine(*,plan,hidden_nvsh,route_weights_nvs=None,**kwargs):
40+ assert kwargs.get('zero_copy') is True
41+ assert hidden_nvsh.data_ptr()==b._ctx['hidden_buf_local'].data_ptr()
42+ b.events.append(('combine',id(plan)))
43+ return hidden_nvsh.detach().clone(),None if route_weights_nvs is None else route_weights_nvs.reshape(4,1).clone(),None
44+ monkeypatch.setattr(b,'dispatch',dispatch);monkeypatch.setattr(b,'combine',combine)
45+ def from_pointer(tensor):
46+ alias=independent(tensor);seen.append(alias);return alias
47+ monkeypatch.setattr(runtime,'_activation_tensor_from_pointer',from_pointer)
48+ monkeypatch.setattr(runtime,'_STRICT_ZERO_COPY',True)
49+ return SimpleNamespace(**vars(chain),headers=seen,provider_bank=b._ctx['hidden_buf_local'],copy_before=runtime.copy_ledger())
50+ 
51+@pytest.fixture(params=[False,True],ids=["root-bank","view-bank"])
52+def strict_chain(chain,monkeypatch,request):
53+ return _strict_chain(chain,monkeypatch,request.param)
54+ 
55+ 
56+@pytest.fixture
57+def zero_copy(strict_chain):
58+ return strict_chain
59+ 
60+@pytest.mark.parametrize('xg,pg',[(False,False),(False,True),(True,False),(True,True)])
61+def test_zero_copy_real_boundaries_and_gradients(zero_copy,xg,pg):
62+ x,p,dy=_inputs(xg,pg);expected=_reference(x,p,dy,zero_copy.parameters)
63+ old=[v.main_grad.clone() for v in zero_copy.parameters]
64+ ddp=_DDPRuleFixture(zero_copy.parameters,zero_out=True,overlap=True)
65+ y=zero_copy.run(x,p);torch.testing.assert_close(y,expected['y'],rtol=0,atol=0)
66+ y.backward(dy)
67+ for w,b,d in zip(zero_copy.parameters,old,expected['dw']):torch.testing.assert_close(w.main_grad,b+d,rtol=0,atol=1e-7)
68+ assert x.grad is None if not xg else torch.equal(x.grad,expected['dx'])
69+ assert p.grad is None if not pg else torch.equal(p.grad,expected['dp'])
70+ assert len(ddp.seen)==2 and all(not torch.count_nonzero(g) for _,g in ddp.seen)
71+ assert ve._VirtualExperts.active_exact_plan_count==0
72+ assert runtime._FATAL_ERROR is None
73+ assert not zero_copy.provider_bank.requires_grad and zero_copy.provider_bank.grad_fn is None
74+ assert runtime.copy_ledger()==zero_copy.copy_before
75+ assert len({h.data_ptr() for h in zero_copy.headers})==1
76+ 
77+@pytest.mark.parametrize('microbatches',[2,8])
78+def test_zero_copy_pending_forwards_reverse_backward(zero_copy,microbatches):
79+ before=[p.main_grad.clone() for p in zero_copy.parameters];xs=[];ps=[];refs=[];ys=[];dys=[]
80+ for i in range(microbatches):
81+ x,p,dy=_inputs(True,True,scale=i+1)
82+ refs.append(_reference(x,p,dy,zero_copy.parameters));xs.append(x);ps.append(p);dys.append(dy)
83+ ys.append(zero_copy.run(x,p))
84+ assert ve._VirtualExperts.active_exact_plan_count==microbatches
85+ for i in reversed(range(microbatches)):
86+ torch.testing.assert_close(ys[i],refs[i]['y'],rtol=0,atol=0)
87+ ys[i].backward(dys[i]);assert torch.equal(xs[i].grad,refs[i]['dx']) and torch.equal(ps[i].grad,refs[i]['dp'])
88+ for j,w in enumerate(zero_copy.parameters):
89+ expected=before[j]
90+ for i in reversed(range(microbatches)):expected=expected+refs[i]['dw'][j]
91+ torch.testing.assert_close(w.main_grad,expected,rtol=0,atol=1e-7)
92+ assert ve._VirtualExperts.active_exact_plan_count==0 and runtime._FATAL_ERROR is None
93+ 
94+def test_zero_copy_two_layers_shared_carrier(zero_copy):
95+ first=zero_copy
96+ model=torch.nn.Module();model.activation_func=first.model.activation_func
97+ for name in ('linear_fc1','linear_fc2'):
98+ layer=torch.nn.Module();w=getattr(first.model,name).weight0
99+ layer.register_parameter('weight0',torch.nn.Parameter((w.detach()*1.5).clone()))
100+ layer.weight0.main_grad=torch.full_like(w,.375,dtype=torch.float32);model.add_module(name,layer)
101+ manager=ve.VirtualExpertLoadBalancer(group=first.buffer._ctx['group'],num_local_experts=1,num_experts=2,config=SimpleNamespace(moe_router_topk=1))
102+ manager.bind_experts(model);manager.virtual_experts.prepare_bindings(first.buffer)
103+ wrapper=executor.moonep_grouped_mlp_forward_wrapper(lambda *a:pytest.fail('fallback'))
104+ def run2(x,p):
105+ manager.setup_metadata(torch.zeros(4,1,dtype=torch.int32),p)
106+ z=manager.dispatch(x);out,_=wrapper(model,z,manager.tokens_per_expert,manager.dispatched_probs)
107+ return manager.finalize_output(manager.combine(out))
108+ x,p,dy=_inputs(True,True);_,p2,_=_inputs(True,True)
109+ initial1=[w.main_grad.clone() for w in first.parameters];initial2=[w.main_grad.clone() for w in manager.virtual_experts.source_parameters]
110+ dummy=_reference(x,p,dy,first.parameters);ref2=_reference(dummy['y'],p2,dy,manager.virtual_experts.source_parameters)
111+ ref1=_reference(x,p,ref2['dx'],first.parameters)
112+ y1=first.run(x,p);y2=run2(y1,p2)
113+ torch.testing.assert_close(y2,ref2['y'],rtol=0,atol=0);y2.backward(dy)
114+ assert torch.equal(x.grad,ref1['dx']) and torch.equal(p.grad,ref1['dp']) and torch.equal(p2.grad,ref2['dp'])
115+ for weights,old,ref in ((first.parameters,initial1,ref1),(manager.virtual_experts.source_parameters,initial2,ref2)):
116+ for w,b,d in zip(weights,old,ref['dw']):torch.testing.assert_close(w.main_grad,b+d,rtol=0,atol=1e-7)
117+ assert ve._VirtualExperts.active_exact_plan_count==0 and runtime._FATAL_ERROR is None
118+ 
119+def test_independent_header_version_counter():
120+ carrier=torch.zeros(4,2,dtype=torch.bfloat16);h=independent(carrier);version=h._version
121+ carrier.fill_(42);assert h._version==version and torch.equal(h,carrier)
122+ h2=independent(carrier);v2=h2._version
123+ h.zero_();assert h2._version==v2 and not torch.count_nonzero(h2)
124+ 
125+def test_zero_copy_nan_suffix_on_z1_z3_r1(zero_copy,monkeypatch):
126+ check_padding(zero_copy,monkeypatch)
127+ 
128+@pytest.mark.parametrize('zero_out,overlap',[(False,False),(False,True),(True,False),(True,True)])
129+def test_zero_copy_ddp_rule_and_no_sync(zero_copy,zero_out,overlap):
130+ check_no_sync(zero_copy,zero_out,overlap)
131+ 
132+@pytest.mark.parametrize('mutation',['foreign','metadata','counts','mask','source','weight'])
133+def test_zero_copy_preserves_fail_closed_before_push(zero_copy,monkeypatch,mutation):
134+ check_versions(zero_copy,monkeypatch,mutation)
135+ 
136+def test_zero_copy_gr_failure_still_quarantines(zero_copy):
137+ check_gr_failure(zero_copy)
138+ 
139+ 
140+ 
141+@pytest.mark.parametrize('invalid',['same','view','copy','attached'])
142+def test_zero_copy_rejects_bad_wrapper_metadata(strict_chain,monkeypatch,invalid):
143+ bank=strict_chain.provider_bank
144+ def invalid_wrapper(tensor):
145+ if invalid=='same':return tensor
146+ if invalid=='view':return tensor[:]
147+ if invalid=='copy':return tensor.clone()
148+ return independent(tensor).requires_grad_(True)
149+ monkeypatch.setattr(runtime,'_activation_tensor_from_pointer',invalid_wrapper)
150+ with pytest.raises(RuntimeError,match='independent metadata'):
151+ runtime.independent_activation_alias(bank)
152+ 
153+def test_copy_sync_keeps_tensor_and_does_not_construct_pointer(chain,monkeypatch):
154+ monkeypatch.setattr(runtime,'_activation_tensor_from_pointer',lambda value:pytest.fail('COPY_SYNC pointer construction'))
155+ value=chain.buffer._ctx['hidden_buf_local']
156+ assert runtime.independent_activation_alias(value) is value
157+ 
158+ 
159+def test_framework_stages_route_grad_without_provider_private_helper(zero_copy):
160+ buffer=zero_copy.buffer
161+ assert not hasattr(buffer,'_stage_route_weights_for_combine')
162+ before=runtime.metadata_copy_ledger()['dispatch_backward_route_grad'].copy()
163+ values=torch.tensor([.25,-2.,0.,7.],dtype=torch.float32)
164+ staged=runtime.stage_route_grad(values)
165+ assert staged.data_ptr()==buffer._ctx['weights_buf_local'].data_ptr()
166+ assert torch.equal(staged,values) and staged.data_ptr()!=values.data_ptr()
167+ after=runtime.metadata_copy_ledger()['dispatch_backward_route_grad']
168+ assert after['calls']==before['calls']+1 and after['bytes']==before['bytes']+16
169+ 
170+ 
171+@pytest.mark.parametrize('fault',['dtype','shape','noncontiguous'])
172+def test_route_grad_rejects_invalid_metadata_before_copy(zero_copy,fault):
173+ carrier=zero_copy.buffer._ctx['weights_buf_local']
174+ carrier.zero_();before=runtime.metadata_copy_ledger()
175+ value=torch.arange(4,dtype=torch.float32)
176+ if fault=='dtype':value=value.to(torch.bfloat16)
177+ elif fault=='shape':value=value.reshape(2,2)
178+ else:value=torch.arange(8,dtype=torch.float32)[::2]
179+ with pytest.raises((ValueError,TypeError)):
180+ runtime.stage_route_grad(value)
181+ assert not torch.count_nonzero(carrier)
182+ assert runtime.metadata_copy_ledger()==before
183+ 
184+ 
185+@pytest.mark.parametrize('activation_mode', ['copy', 'zero-copy-root', 'zero-copy-view'])
186+@pytest.mark.parametrize('x_grad,p_grad', [(False,False),(False,True),(True,False),(True,True)])
187+def test_continuous_real_chain_saved_input_and_ready_after_completion(chain, monkeypatch, x_grad, p_grad,
188+ activation_mode):
189+ c = chain if activation_mode == 'copy' else _strict_chain(
190+ chain, monkeypatch, activation_mode == 'zero-copy-view')
191+ if activation_mode == 'copy':
192+ monkeypatch.setattr(runtime, '_activation_tensor_from_pointer',
193+ lambda value: pytest.fail('COPY must not construct a carrier alias'))
194+ backend = c.backend
195+ ready = []
196+ def consume(grad):
197+ assert runtime._SUBMISSION_SEGMENT is None and not backend.active
198+ ready.append(True)
199+ return grad
200+ for parameter in c.parameters:
201+ parameter.grad_added_to_main_grad = False
202+ parameter.register_hook(consume)
203+ x, p, dy = _inputs(x_grad, p_grad)
204+ expected = _reference(x, p, dy, c.parameters)
205+ y = c.run(x, p)
206+ plan = y.grad_fn.callback_args[0]
207+ snapshot = plan.saved_input
208+ assert snapshot is not None
209+ assert snapshot.data_ptr() != c.buffer._ctx['hidden_buf_local'].data_ptr()
210+ torch.testing.assert_close(snapshot, x.detach(), rtol=0, atol=0)
211+ saved_copies = runtime.saved_activation_copy_ledger()['expert_input_z1']['calls']
212+ assert saved_copies == (0 if activation_mode == 'copy' else 1)
213+ y.backward(dy)
214+ torch.testing.assert_close(y, expected['y'], rtol=0, atol=0)
215+ if x_grad:
216+ torch.testing.assert_close(x.grad, expected['dx'], rtol=0, atol=0)
217+ if p_grad:
218+ torch.testing.assert_close(p.grad, expected['dp'], rtol=0, atol=0)
219+ for parameter, dw in zip(c.parameters, expected['dw']):
220+ torch.testing.assert_close(parameter.main_grad, dw+.375, rtol=0, atol=0)
221+ assert parameter.grad_added_to_main_grad
222+ assert len(ready) == len(c.parameters)
223+ assert plan.retired and plan.saved_input is None
224+ assert runtime._SUBMISSION_SEGMENT is None and not backend.active
225+ assert backend.ends == (7 if x_grad or p_grad else 6)
226+ assert sum(event[0] == 'dispatch' for event in c.buffer.events) == 2
227+ 
228+ 
229+def test_failed_continuous_completion_quarantines_owner_and_closes_admission(strict_chain, monkeypatch):
230+ c = strict_chain
231+ backend = c.backend
232+ plan, pin = SimpleNamespace(retired=False), object()
233+ runtime.begin_submission_segment(plan, pin)
234+ backend.error = RuntimeError('original completion error')
235+ with pytest.raises(RuntimeError) as caught:
236+ runtime.end_submission_segment()
237+ assert caught.value is backend.error
238+ segment = runtime._SUBMISSION_SEGMENT
239+ assert segment['plan'] is plan and segment['pins'][0] is pin
240+ assert backend.failed and runtime._FATAL_ERROR is not None and runtime._QUARANTINE
241+ with pytest.raises(RuntimeError):
242+ runtime.begin_submission_segment(SimpleNamespace(retired=False))
243+ assert runtime._SUBMISSION_SEGMENT is segment
244+ 
245+ 
246+@pytest.mark.parametrize('zero_out,overlap', [(False,False),(False,True),(True,False),(True,True)])
247+def test_continuous_copy_no_sync_accumulates_exactly_once(chain, monkeypatch, zero_out, overlap):
248+ backend = chain.backend
249+ check_no_sync(chain, zero_out, overlap)
250+ assert runtime._SUBMISSION_SEGMENT is None and not backend.active
251+ assert runtime.saved_activation_copy_ledger()['expert_input_z1']['calls'] == 0
252+ 
253+ 
254+@pytest.mark.parametrize('microbatches', [2, 4])
255+def test_continuous_copy_pending_forwards_keep_independent_saved_inputs(chain, monkeypatch, microbatches):
256+ backend = chain.backend
257+ expected = [parameter.main_grad.clone() for parameter in chain.parameters]
258+ pending = []
259+ for index in range(microbatches):
260+ x, p, dy = _inputs(scale=index + 1)
261+ reference = _reference(x, p, dy, chain.parameters)
262+ y = chain.run(x, p)
263+ plan = y.grad_fn.callback_args[0]
264+ assert plan.saved_input.data_ptr() != chain.buffer._ctx['hidden_buf_local'].data_ptr()
265+ pending.append((x, p, dy, y, plan, reference))
266+ expected = [old + delta for old, delta in zip(expected, reference['dw'])]
267+ assert len({plan.saved_input.data_ptr() for _, _, _, _, plan, _ in pending}) == microbatches
268+ for x, p, dy, y, plan, reference in reversed(pending):
269+ torch.testing.assert_close(plan.saved_input, x.detach(), rtol=0, atol=0)
270+ torch.testing.assert_close(y, reference['y'], rtol=0, atol=0)
271+ y.backward(dy)
272+ torch.testing.assert_close(x.grad, reference['dx'], rtol=0, atol=0)
273+ torch.testing.assert_close(p.grad, reference['dp'], rtol=0, atol=0)
274+ assert plan.retired and plan.saved_input is None
275+ for parameter, total in zip(chain.parameters, expected):
276+ torch.testing.assert_close(parameter.main_grad, total, rtol=0, atol=1e-7)
277+ assert runtime._SUBMISSION_SEGMENT is None and not backend.active
278+ assert ve._VirtualExperts.active_exact_plan_count == 0
279+ assert runtime.saved_activation_copy_ledger()['expert_input_z1']['calls'] == 0
280+ 
281+ 
282+def test_continuous_copy_gr_failure_retains_segment_and_closes_admission(chain, monkeypatch):
283+ backend = chain.backend
284+ check_gr_failure(chain)
285+ assert backend.failed and runtime._SUBMISSION_SEGMENT is not None
286+ assert runtime._SUBMISSION_SEGMENT['plan'] is chain.manager._plan
287+ 
288+ 
289+def test_continuous_copy_completion_failure_pins_returned_tensors(chain, monkeypatch):
290+ backend = chain.backend
291+ original_dispatch = chain.buffer.dispatch
292+ returned_refs = []
293+ 
294+ def dispatch(*args, **kwargs):
295+ result = original_dispatch(*args, **kwargs)
296+ returned_refs.extend(weakref.ref(tensor) for tensor in result[:3])
297+ return result
298+ 
299+ monkeypatch.setattr(chain.buffer, 'dispatch', dispatch)
300+ error = RuntimeError('COPY dispatch completion failed')
301+ backend.error = error
302+ x, p, _ = _inputs()
303+ with pytest.raises(RuntimeError, match='COPY dispatch completion failed') as caught:
304+ chain.run(x, p)
305+ assert caught.value is error and runtime._FATAL_ERROR is error and backend.failed
306+ assert chain.manager._plan is None and ve._VirtualExperts.active_exact_plan_count == 0
307+ assert runtime._SUBMISSION_SEGMENT is not None
308+ assert [event[0] for event in chain.buffer.events] == ['dispatch']
309+ del caught
310+ error.__traceback__ = error.__context__ = error.__cause__ = None
311+ gc.collect()
312+ assert len(returned_refs) == 3 and all(reference() is not None for reference in returned_refs)
313+ with pytest.raises(RuntimeError, match='admission is closed'):
314+ runtime.ensure_admission()
315+ 
316+ 
317+@pytest.mark.parametrize('activation_mode', ['copy', 'zero-copy-root', 'zero-copy-view'])
318+def test_default_submission_no_grad_completes_and_retires_plan(chain, monkeypatch, activation_mode):
319+ c = chain if activation_mode == 'copy' else _strict_chain(
320+ chain, monkeypatch, activation_mode == 'zero-copy-view')
321+ x, p, dy = _inputs(False, False)
322+ reference = _reference(x, p, dy, c.parameters)
323+ initial = [weight.main_grad.clone() for weight in c.parameters]
324+ with torch.no_grad():
325+ output = c.run(x, p)
326+ torch.testing.assert_close(output, reference['y'], rtol=0, atol=0)
327+ assert not output.requires_grad and output.grad_fn is None
328+ for weight, value in zip(c.parameters, initial):
329+ torch.testing.assert_close(weight.main_grad, value, rtol=0, atol=0)
330+ assert c.backend.ends == 3 and not c.backend.active
331+ assert runtime._SUBMISSION_SEGMENT is None and c.manager._plan is None
332+ assert ve._VirtualExperts.active_exact_plan_count == 0
@@ -0,0 +1,663 @@
1+"""CPU Autograd behavior; native GMM/PUSH/GR below are explicit test oracles.
2+ 
3+The real Dispatch/Combine/Experts, manager, plan and _VirtualExperts run here.
4+The tiny identity-routing Buffer and DDP-rule fixture are not native/collective
5+or real Core DDP evidence. No SHMEM, TENPU, torch_npu or builder is imported.
6+The explicit external-worker CPU8 case exercises real CPU Gloo only.
7+"""
8+ 
9+from contextlib import contextmanager
10+import gc
11+import importlib.util
12+from itertools import count
13+from pathlib import Path
14+from types import ModuleType, SimpleNamespace
15+import sys
16+import weakref
17+ 
18+import pytest
19+import torch
20+import torch.nn.functional as F
21+ 
22+from mindspeed.core.transformer.moe.moonep import moonep_executor as executor
23+from mindspeed.core.transformer.moe.moonep import moonep_runtime as runtime
24+from mindspeed.core.transformer.moe.moonep import virtual_expert_load_balancer as ve
25+ 
26+ 
27+_LIBRARY_IDS = count()
28+ 
29+ 
30+def _load_real_gmm_wrappers(monkeypatch, tmp_path):
31+ """Execute real gmm.py, stubbing only builder/native and unrelated old ATB.
32+ 
33+ Real torch.library decorators remain active in a private CPU-test namespace.
34+ The placeholder .so is only input to Python path validation: never dlopened.
35+ """
36+ native = SimpleNamespace(npu_gmm_v5_out=_grouped_oracle,
37+ npu_grouped_matmul_add_fp32_out=_producer_oracle)
38+ class Builder:
39+ def load(self):
40+ return native
41+ builders = ModuleType('mindspeed.op_builder')
42+ builders.GMMOpBuilder = builders.GMMV2OpBuilder = Builder
43+ base = ModuleType('mindspeed.op_builder.builder')
44+ library = torch.library.Library(f'pr20_host_oracle_{next(_LIBRARY_IDS)}', 'DEF')
45+ for name, groups in [('npu_gmm.Tensor', 'Tensor?'), ('npu_gmm.List', 'int[]?'),
46+ ('npu_gmm_v2.Tensor', 'Tensor?')]:
47+ library.define(f'{name}(Tensor original_weight, Tensor x, Tensor weight, *, '
48+ f'Tensor? bias=None, {groups} group_list=None, int? group_type=0, '
49+ 'bool? gemm_fusion=False) -> Tensor')
50+ base.AS_LIBRARY = library
51+ old_atb = ModuleType('mindspeed.ops.npu_groupmatmul_add')
52+ old_atb.npu_groupmatmul_add_fp32 = lambda *args: pytest.fail('old ATB/wrapper fallback')
53+ for name, module in [('mindspeed.op_builder', builders),
54+ ('mindspeed.op_builder.builder', base),
55+ ('mindspeed.ops.npu_groupmatmul_add', old_atb)]:
56+ monkeypatch.setitem(sys.modules, name, module)
57+ path = Path(__file__).resolve().parents[4]/'mindspeed/ops/gmm.py'
58+ spec = importlib.util.spec_from_file_location('mindspeed.ops.gmm', path)
59+ module = importlib.util.module_from_spec(spec)
60+ monkeypatch.setitem(sys.modules, 'mindspeed.ops.gmm', module)
61+ spec.loader.exec_module(module)
62+ selected = tmp_path/'libopapi.so'
63+ selected.write_bytes(b'CPU oracle path-validation placeholder; never loaded')
64+ monkeypatch.setenv('MINDSPEED_MOONEP_OPAPI', str(selected))
65+ monkeypatch.setenv('MINDSPEED_MOONEP_OPAPI_DEPENDENCIES', '')
66+ assert Path(module.npu_gmm_v5_out.__code__.co_filename).resolve() == path
67+ return module
68+ 
69+ 
70+def _grouped_oracle(x, refs, out, counts):
71+ """Per-group CPU matmul is an oracle, never the production grouped call."""
72+ runtime._submission_context() # Every real graph call must own an active segment.
73+ assert not any(value.requires_grad for value in (x, out, counts, *refs))
74+ begin = 0
75+ with torch.no_grad():
76+ for count, weight in zip(counts.tolist(), refs):
77+ end = begin + count
78+ out[begin:end].copy_(x[begin:end] @ weight)
79+ begin = end
80+ assert begin == len(x)
81+ return out
82+ 
83+ 
84+def _producer_oracle(dy, x, scratch, prefix):
85+ """Emulate one independent FP32 full-G native producer, not publication."""
86+ runtime._submission_context()
87+ assert dy.dtype == x.dtype == torch.bfloat16
88+ assert not any(value.requires_grad for value in (dy, x, scratch, prefix))
89+ assert scratch.dtype == torch.float32 and not torch.count_nonzero(scratch)
90+ assert scratch.untyped_storage()._cdata not in (
91+ dy.untyped_storage()._cdata, x.untyped_storage()._cdata)
92+ begin = 0
93+ with torch.no_grad():
94+ for index, end in enumerate(prefix.tolist()):
95+ scratch[index].add_(dy[begin:end].float().t() @ x[begin:end].float())
96+ begin = end
97+ return scratch
98+ 
99+ 
100+class _BufferOracle:
@@ -0,0 +1,257 @@
1+"""Python-level contracts for the MoonEP standard GMM / AddV2 entry points.
2+ 
3+Pure CPU: the wrapper module is loaded with inert builders, no NPU dispatcher is
4+registered, and no native math is executed. Checks operand guards, caller-owned
5+output identity, and the frozen standard-library selection cache.
6+"""
7+ 
8+import importlib.util
9+from pathlib import Path
10+import sys
11+from types import ModuleType, SimpleNamespace
12+import pytest
13+import torch
14+ 
15+ROOT = Path(__file__).resolve().parents[4]
16+ 
17+@pytest.fixture
18+def wrapper(monkeypatch):
19+ builders = ModuleType('mindspeed.op_builder')
20+ builders.GMMOpBuilder = builders.GMMV2OpBuilder = lambda: SimpleNamespace(load=lambda: None)
21+ common = ModuleType('mindspeed.op_builder.builder')
22+ common.AS_LIBRARY = object()
23+ old_add = ModuleType('mindspeed.ops.npu_groupmatmul_add')
24+ old_add.npu_groupmatmul_add_fp32 = lambda *args: pytest.fail('unrelated old wrapper invoked')
25+ for name, module in ((builders.__name__, builders), (common.__name__, common), (old_add.__name__, old_add)):
26+ monkeypatch.setitem(sys.modules, name, module)
27+ monkeypatch.setattr(torch.library, 'impl', lambda *args: lambda function: function)
28+ spec = importlib.util.spec_from_file_location('minimal_gmm_wrapper', ROOT/'mindspeed/ops/gmm.py')
29+ result = importlib.util.module_from_spec(spec)
30+ spec.loader.exec_module(result)
31+ return result
32+ 
33+def values():
34+ return (torch.zeros(3, 4, dtype=torch.bfloat16),
35+ torch.zeros(3, 2, dtype=torch.bfloat16),
36+ torch.zeros(2, 4, 2), torch.tensor([2, 3], dtype=torch.int64))
37+ 
38+def test_add_actual_wrapper_preserves_four_arg_identity_and_raw_version(wrapper, monkeypatch):
39+ dy, x, scratch, prefix = values()
40+ seen = []
41+ def call(*args):
42+ seen.append(args)
43+ return scratch
44+ monkeypatch.setattr(wrapper, '_standard_binding', lambda: SimpleNamespace(npu_grouped_matmul_add_fp32_out=call))
45+ before = scratch._version
46+ assert wrapper.npu_grouped_matmul_add_fp32_out(dy, x, scratch, prefix) is scratch
47+ assert all(actual is expected for actual, expected in zip(seen[0], (dy, x, scratch, prefix)))
48+ assert scratch._version == before + 1
49+ 
50+@pytest.mark.parametrize('fault', ['dtype', 'shape', 'prefix', 'stride', 'grad', 'negative'])
51+def test_add_invalid_metadata_never_calls_binding(wrapper, monkeypatch, fault):
52+ dy, x, scratch, prefix = values()
53+ if fault == 'dtype': dy = dy.float()
54+ elif fault == 'shape': scratch = scratch[:, :3]
55+ elif fault == 'prefix': prefix = prefix.int()
56+ elif fault == 'stride': x = torch.zeros(2, 3, dtype=torch.bfloat16).t()
57+ elif fault == 'grad': x.requires_grad_(True)
58+ elif fault == 'negative': x = torch._neg_view(x)
59+ monkeypatch.setattr(wrapper, '_standard_binding', lambda: pytest.fail('invalid metadata reached loader'))
60+ with pytest.raises((TypeError, ValueError, RuntimeError)):
61+ wrapper.npu_grouped_matmul_add_fp32_out(dy, x, scratch, prefix)
62+ 
63+def test_add_return_copy_rejected_without_version_handoff(wrapper, monkeypatch):
64+ dy, x, scratch, prefix = values()
65+ monkeypatch.setattr(wrapper, '_standard_binding', lambda: SimpleNamespace(
66+ npu_grouped_matmul_add_fp32_out=lambda *args: scratch.clone()))
67+ before = scratch._version
68+ with pytest.raises(RuntimeError, match='output identity'):
69+ wrapper.npu_grouped_matmul_add_fp32_out(dy, x, scratch, prefix)
70+ assert scratch._version == before
71+ 
72+def test_v5_actual_wrapper_keeps_zero_copy_transpose_ref(wrapper, monkeypatch):
73+ x = torch.zeros(3, 2, dtype=torch.bfloat16)
74+ weight = torch.zeros(4, 2, dtype=torch.bfloat16).t()
75+ out = torch.empty(3, 4, dtype=torch.bfloat16)
76+ counts = torch.tensor([3])
77+ def call(actual_x, refs, actual_out, actual_counts):
78+ assert actual_x is x and refs[0] is weight and actual_out is out and actual_counts is counts
79+ return out
80+ monkeypatch.setattr(wrapper, '_standard_binding', lambda: SimpleNamespace(npu_gmm_v5_out=call))
81+ before = out._version
82+ assert wrapper.npu_gmm_v5_out(x, [weight], out, counts) is out
83+ assert out._version == before + 1
84+ 
85+def test_standard_selector_explicit_files_immutable_and_no_builder_on_error(wrapper, tmp_path, monkeypatch):
86+ main = tmp_path/'libopapi.so'
87+ main.write_bytes(b'inert host file, never loaded')
88+ monkeypatch.setenv('MINDSPEED_MOONEP_OPAPI', str(main))
89+ monkeypatch.setenv('MINDSPEED_MOONEP_OPAPI_DEPENDENCIES', '')
90+ binding = object()
91+ monkeypatch.setattr(wrapper.GMMFunction.builder2, 'load', lambda: binding)
92+ assert wrapper._standard_binding() is binding
93+ other = tmp_path/'other'
94+ other.mkdir()
95+ (other/'libopapi.so').write_bytes(b'other inert selected file')
96+ monkeypatch.setenv('MINDSPEED_MOONEP_OPAPI', str(other/'libopapi.so'))
97+ with pytest.raises(RuntimeError, match='selection changed'):
98+ wrapper._standard_binding()
99+ 
100+@pytest.mark.parametrize('entry', ['', 'libopapi.so', 'libcust_opapi.so', 'missing/libopapi.so'])
101+def test_selector_invalid_path_rejects_before_builder(wrapper, tmp_path, monkeypatch, entry):
102+ path = tmp_path/entry if entry.startswith('libcust') else Path(entry)
103+ if entry.startswith('libcust'): path.write_bytes(b'not loaded')
104+ monkeypatch.setenv('MINDSPEED_MOONEP_OPAPI', str(path) if entry else '')
105+ monkeypatch.delenv('MINDSPEED_MOONEP_OPAPI_DEPENDENCIES', raising=False)
106+ with pytest.raises(RuntimeError):
107+ wrapper._standard_binding()
108+ 
109+def test_selector_warm_call_uses_frozen_module_without_filesystem(wrapper, tmp_path, monkeypatch):
110+ main = tmp_path/'libopapi.so'
111+ main.write_bytes(b'inert host selection, never loaded')
112+ monkeypatch.setenv('MINDSPEED_MOONEP_OPAPI', str(main))
113+ monkeypatch.setenv('MINDSPEED_MOONEP_OPAPI_DEPENDENCIES', '')
114+ binding, loads = object(), []
115+ monkeypatch.setattr(wrapper.GMMFunction.builder2, 'load', lambda: loads.append('load') or binding)
116+ assert wrapper._standard_binding() is binding
117+ for method in ('is_absolute', 'is_file', 'resolve'):
118+ monkeypatch.setattr(Path, method, lambda *args, **kwargs: pytest.fail('warm filesystem query'))
119+ for _ in range(8):
120+ assert wrapper._standard_binding() is binding
121+ assert loads == ['load']
122+ # A changed raw path or dependency string is rejected before any lookup.
123+ for key, value in (('MINDSPEED_MOONEP_OPAPI', str(main)+'/alias'),
124+ ('MINDSPEED_MOONEP_OPAPI_DEPENDENCIES', '/changed/dependency.so')):
125+ with monkeypatch.context() as changed:
126+ changed.setenv(key, value)
127+ with pytest.raises(RuntimeError, match='selection changed'):
128+ wrapper._standard_binding()
129+ 
130+@pytest.mark.parametrize('error', ['missing standard symbol', 'wrong symbol provider', 'inert load failed'])
131+def test_selector_failed_cold_load_never_publishes_cache(wrapper, tmp_path, monkeypatch, error):
132+ main = tmp_path/'libopapi.so'
133+ main.write_bytes(b'inert host selection, never loaded')
134+ monkeypatch.setenv('MINDSPEED_MOONEP_OPAPI', str(main))
135+ monkeypatch.setenv('MINDSPEED_MOONEP_OPAPI_DEPENDENCIES', '')
136+ loads = []
137+ def reject():
138+ loads.append('load')
139+ raise RuntimeError(error)
140+ monkeypatch.setattr(wrapper.GMMFunction.builder2, 'load', reject)
141+ with pytest.raises(RuntimeError, match=error):
142+ wrapper._standard_binding()
143+ assert loads == ['load']
144+ assert wrapper._standard_selection is None and wrapper._standard_module is None
145+ 
146+@pytest.mark.parametrize('key', ['MINDSPEED_MOONEP_OPAPI', 'MINDSPEED_MOONEP_OPAPI_DEPENDENCIES'])
147+def test_selector_environment_changed_during_load_never_publishes(wrapper, tmp_path, monkeypatch, key):
148+ main = tmp_path/'libopapi.so'
149+ main.write_bytes(b'inert host selection, never loaded')
150+ monkeypatch.setenv('MINDSPEED_MOONEP_OPAPI', str(main))
151+ monkeypatch.setenv('MINDSPEED_MOONEP_OPAPI_DEPENDENCIES', '')
152+ def load():
153+ monkeypatch.setenv(key, 'changed during cold load')
154+ return object()
155+ monkeypatch.setattr(wrapper.GMMFunction.builder2, 'load', load)
156+ with pytest.raises(RuntimeError, match='selection changed'):
157+ wrapper._standard_binding()
158+ assert wrapper._standard_selection is None and wrapper._standard_module is None
159+ 
160+def test_selector_concurrent_first_calls_publish_one_complete_module(wrapper, tmp_path, monkeypatch):
161+ from concurrent.futures import ThreadPoolExecutor
162+ from threading import Event
163+ 
164+ main = tmp_path/'libopapi.so'
165+ main.write_bytes(b'inert host selection, never loaded')
166+ monkeypatch.setenv('MINDSPEED_MOONEP_OPAPI', str(main))
167+ monkeypatch.setenv('MINDSPEED_MOONEP_OPAPI_DEPENDENCIES', '')
168+ entered, release, second_started = Event(), Event(), Event()
169+ binding, loads = object(), []
170+ def load():
171+ loads.append('load')
172+ entered.set()
173+ assert release.wait(5), 'test did not release inert loader'
174+ return binding
175+ def second():
176+ second_started.set()
177+ return wrapper._standard_binding()
178+ monkeypatch.setattr(wrapper.GMMFunction.builder2, 'load', load)
179+ with ThreadPoolExecutor(max_workers=2) as pool:
180+ first = pool.submit(wrapper._standard_binding)
181+ try:
182+ assert entered.wait(5)
183+ assert wrapper._standard_selection is None and wrapper._standard_module is None
184+ other = pool.submit(second)
185+ assert second_started.wait(5)
186+ finally:
187+ release.set()
188+ assert first.result(timeout=5) is binding
189+ assert other.result(timeout=5) is binding
190+ assert loads == ['load']
191+ 
192+def test_selector_warm_cache_does_not_skip_operand_guards(wrapper, tmp_path, monkeypatch):
193+ main = tmp_path/'libopapi.so'
194+ main.write_bytes(b'inert host selection, never loaded')
195+ monkeypatch.setenv('MINDSPEED_MOONEP_OPAPI', str(main))
196+ monkeypatch.setenv('MINDSPEED_MOONEP_OPAPI_DEPENDENCIES', '')
197+ binding = SimpleNamespace(npu_gmm_v5_out=lambda *args: pytest.fail('invalid operand reached native'))
198+ monkeypatch.setattr(wrapper.GMMFunction.builder2, 'load', lambda: binding)
199+ assert wrapper._standard_binding() is binding
200+ x = torch.zeros(3, 2, dtype=torch.bfloat16)
201+ out = torch.empty(3, 4, dtype=torch.bfloat16)
202+ with pytest.raises(ValueError, match='weight refs must match'):
203+ wrapper.npu_gmm_v5_out(x, [torch.zeros(2, 5, dtype=torch.bfloat16)], out,
204+ torch.tensor([3], dtype=torch.int64))
205+ 
206+def test_native_source_retains_owner_and_uses_only_standard_phase_pair():
207+ source = (ROOT/'mindspeed/ops/csrc/cann/gmm.cpp').read_text()
208+ moon = source[source.index('namespace moonep_standard'):]
209+ assert 'aclnnPointerGroupedMatmulAdd' not in source
210+ assert 'ACLNN_CMD(' not in moon
211+ assert 'current.stream()' in moon and 'current.stream(false)' not in moon
212+ execute = moon[moon.index('template<class Query> void execute'):moon.index('void metadata(')]
213+ end_segment = moon[moon.index('void end_segment()'):moon.index('void abort_segment()')]
214+ assert 'current.synchronize()' not in execute
215+ assert execute.index('check_segment(current, stream)') < execute.index('query(*call, bytes)')
216+ assert execute.index('segment().calls.push_back(call)') < execute.index('query(*call, bytes)')
217+ assert end_segment.index('current.synchronize()') < end_segment.index('segment().calls.clear()')
218+ assert 'retained = call' in moon and 'process restart required' in moon
219+ assert 'ACL_FORMAT_ND' in moon and 'ACL_FORMAT_NCL' not in moon
220+ assert 'true, false, 2, 0, &bytes' in moon
221+ assert 'groups, nullptr, nullptr, nullptr, 3, 0, 1, 0' in moon
222+ assert 'descriptors.resize(descriptors.size() - items.size())' in moon
223+ assert 'TORCH_CHECK(call->executor' in moon
224+ assert '!value.is_neg() && !value.is_conj()' in moon
225+ 
226+def test_python_source_compiles_without_importing_native():
227+ package = ROOT/'mindspeed/core/transformer/moe/moonep'
228+ modules = {'moonep.py', 'moonep_contract.py', 'moonep_executor.py',
229+ 'moonep_runtime.py', 'virtual_expert_load_balancer.py'}
230+ assert {path.name for path in package.glob('*.py')} == modules | {'__init__.py'}
231+ for name in modules | {'__init__.py'}:
232+ path = package/name
233+ compile(path.read_bytes(), str(path), 'exec')
234+ compile((ROOT/'mindspeed/ops/gmm.py').read_bytes(), 'gmm.py', 'exec')
235+ 
236+def test_moonep_package_keeps_one_runtime_and_no_eager_imports():
237+ import ast
238+ import importlib
239+ import sys
240+ 
241+ prefix = 'mindspeed.core.transformer.moe.moonep'
242+ package = importlib.import_module(prefix)
243+ body = ast.parse(Path(package.__file__).read_bytes()).body
244+ assert len(body) == 1 and isinstance(body[0], ast.Expr)
245+ assert isinstance(body[0].value, ast.Constant) and isinstance(body[0].value.value, str)
246+ runtime = importlib.import_module(prefix+'.moonep_runtime')
247+ executor = importlib.import_module(prefix+'.moonep_executor')
248+ experts = importlib.import_module(prefix+'.virtual_expert_load_balancer')
249+ assert executor._VirtualExperts is experts._VirtualExperts
250+ assert sys.modules[prefix+'.moonep_runtime'] is runtime
251+ for name in ('moonep_contract', 'moonep_executor', 'moonep_runtime',
252+ 'virtual_expert_load_balancer'):
253+ assert 'mindspeed.core.transformer.moe.'+name not in sys.modules
254+ assert not (Path(package.__file__).parent.parent/(name+'.py')).exists()
255+ aliases = [module for module in list(sys.modules.values())
256+ if isinstance(module, ModuleType) and vars(module).get('__file__') == runtime.__file__]
257+ assert len(aliases) == 1
@@ -44,17 +44,20 @@ def gmm_env(monkeypatch):
44 return SimpleNamespace(gmm=gmm, args=args, build_fbo=build_fbo)44 return SimpleNamespace(gmm=gmm, args=args, build_fbo=build_fbo)
45 45 
46 46 
47+@pytest.mark.parametrize("moonep", [False, True])
47@pytest.mark.parametrize("mode", ["compatible", "performance"])48@pytest.mark.parametrize("mode", ["compatible", "performance"])
48@pytest.mark.parametrize("fused", [False, True])49@pytest.mark.parametrize("fused", [False, True])
49@pytest.mark.parametrize("fbo", [False, True])50@pytest.mark.parametrize("fbo", [False, True])
50@pytest.mark.parametrize("mcore_forwards_layout", [False, True], ids=["te213", "te214"])51@pytest.mark.parametrize("mcore_forwards_layout", [False, True], ids=["te213", "te214"])
51@pytest.mark.parametrize("parallel_mode", ["column", "row"])52@pytest.mark.parametrize("parallel_mode", ["column", "row"])
52def test_expert_paths_select_layout_independently_of_fusion(53def test_expert_paths_select_layout_independently_of_fusion(
53- gmm_env, mode, fused, fbo, mcore_forwards_layout, parallel_mode54+ gmm_env, moonep, mode, fused, fbo, mcore_forwards_layout, parallel_mode
54):55):
55 env = gmm_env56 env = gmm_env
56 env.args.te_gmm_mode = mode57 env.args.te_gmm_mode = mode
57- packed = mode == "performance"58+ env.args.moe_token_dispatcher_type = "flex"
59+ env.args.moe_flex_dispatcher_backend = "moonep" if moonep else "deepep"
60+ packed = not moonep and mode == "performance"
58 config = SimpleNamespace(61 config = SimpleNamespace(
59 gemm_gradient_accumulation_fusion=fused,62 gemm_gradient_accumulation_fusion=fused,
60 gradient_accumulation_fusion=not fused,63 gradient_accumulation_fusion=not fused,
@@ -138,3 +141,25 @@ def test_missing_mode_defaults_to_compatible_even_with_fusion(gmm_env):
138 141 
139 wrapped = gmm_env.gmm.tenpu_grouped_linear_init_wrapper(init)142 wrapped = gmm_env.gmm.tenpu_grouped_linear_init_wrapper(init)
140 assert wrapped(object(), fuse_wgrad_accumulation=True) == (True, False)143 assert wrapped(object(), fuse_wgrad_accumulation=True) == (True, False)
144+ 
145+ 
146+@pytest.mark.parametrize("mode", ["compatible", "performance"])
147+@pytest.mark.parametrize("fused", [False, True])
148+@pytest.mark.parametrize("explicit_layout", [None, False, True])
149+@pytest.mark.parametrize("positional", [False, True])
150+def test_moonep_requires_per_expert_weights(gmm_env, mode, fused, explicit_layout, positional):
151+ gmm_env.args.te_gmm_mode = mode
152+ gmm_env.args.moe_token_dispatcher_type = "flex"
153+ gmm_env.args.moe_flex_dispatcher_backend = "moonep"
154+ 
155+ def init(self, fuse_wgrad_accumulation=False, single_grouped_weight=False):
156+ return fuse_wgrad_accumulation, single_grouped_weight
157+ 
158+ wrapped = gmm_env.gmm.tenpu_grouped_linear_init_wrapper(init)
159+ if explicit_layout is None:
160+ result = wrapped(object(), fuse_wgrad_accumulation=fused)
161+ elif positional:
162+ result = wrapped(object(), fused, explicit_layout)
163+ else:
164+ result = wrapped(object(), fuse_wgrad_accumulation=fused, single_grouped_weight=explicit_layout)
165+ assert result == (fused, False)