Draft
[WIP]fix/moonep-33d7cfb #5
&NewgateAdd on 18 days ago
[WIP]fix/moonep-33d7cfb #5
Draft
Merged fromfix/moonep-33d7cfbintocore_r0.18.0
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.""" | ||
Amindspeed/core/transformer/moe/moonep/moonep.py+131-0File content is under review, please try again later
| @@ -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 | ||
| 40 | from mindspeed.features_manager.moe.tp_extend_ep import MoETpExtendEpFeature | 40 | from mindspeed.features_manager.moe.tp_extend_ep import MoETpExtendEpFeature |
| 41 | from mindspeed.features_manager.moe.gmm import MoEGmmFeature | 41 | from mindspeed.features_manager.moe.gmm import MoEGmmFeature |
| 42 | +from mindspeed.features_manager.moe.moonep import MoonepFeature | ||
| 42 | from mindspeed.features_manager.moe.shared_expert import MoESharedExpertsFeature | 43 | from mindspeed.features_manager.moe.shared_expert import MoESharedExpertsFeature |
| 43 | from mindspeed.features_manager.moe.fb_overlap import MoEFwdBwdOverlapFeature | 44 | from mindspeed.features_manager.moe.fb_overlap import MoEFwdBwdOverlapFeature |
| 44 | from mindspeed.features_manager.moe.balanced_moe import BalancedMoEFeature | 45 | from mindspeed.features_manager.moe.balanced_moe import BalancedMoEFeature |
| @@ -226,6 +227,7 @@ def add_transformer_features(features_list: List[MindSpeedFeature]): | |||
| 226 | def add_moe_features(features_list: List[MindSpeedFeature]): | 227 | def 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 | ||
| 95 | def tenpu_grouped_linear_init_wrapper(fn): | 101 | def 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_args | 107 | 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-NPU | 117 | # 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 and | 13 | // 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 | + | ||
| 295 | PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { | 728 | PYBIND11_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 | } |
Atests_extend/unit_tests/features/moe/test_moonep_activation_zero_copy.py+332-0File content is under review, please try again later
Atests_extend/unit_tests/features/moe/test_moonep_contract.py+795-0File content is under review, please try again later
Atests_extend/unit_tests/features/moe/test_moonep_pr20_autograd.py+663-0File content is under review, please try again later
Atests_extend/unit_tests/features/moe/test_moonep_standard_gmm.py+257-0File content is under review, please try again later
| @@ -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"]) |
| 52 | def test_expert_paths_select_layout_independently_of_fusion( | 53 | def test_expert_paths_select_layout_independently_of_fusion( |
| 53 | - gmm_env, mode, fused, fbo, mcore_forwards_layout, parallel_mode | 54 | + gmm_env, moonep, mode, fused, fbo, mcore_forwards_layout, parallel_mode |
| 54 | ): | 55 | ): |
| 55 | env = gmm_env | 56 | env = gmm_env |
| 56 | env.args.te_gmm_mode = mode | 57 | 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) | ||