Draft
[WIP]sync/pr-4146 #4
&NewgateAdd on 22 days ago
[WIP]sync/pr-4146 #4
Draft
Merged fromsync/pr-4146intodev_npu_async
Total: 29 files changed+11442-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,107 @@ | |||
| 1 | +# MoonEP PR20:标准 grouped GEMM 与独立 FP32 wgrad | ||
| 2 | + | ||
| 3 | +本功能默认关闭。它从 PR3990 保留 Dispatch / Experts / Combine 及专家级 | ||
| 4 | +Autograd,原样依赖 MoonEP PR20,不依赖 PR12033 或 pointer-target wgrad。 | ||
| 5 | +当前源码/host 证据不代表设备、真实 Core/DDP 训练或性能验收通过。 | ||
| 6 | + | ||
| 7 | +## 固定依赖与范围 | ||
| 8 | + | ||
| 9 | +- MindSpeed 起点:`4723bb74298d8d899474e7ee5d203eca6e52a28b`。 | ||
| 10 | +- MoonEP PR20:`f5914caa23a826a56309f3b981f05d804f166d75`,包名 `npu_patch`。 | ||
| 11 | +- SHMEM:`431c3c43232917f663b7a7022f321802ff23a5c1`。 | ||
| 12 | +- CATLASS:`4fab1d0953b846f4876aa04cf07d1ecbd1110fad`。 | ||
| 13 | +- TENPU/Core/adaptor 不包含本功能源码修改。 | ||
| 14 | + | ||
| 15 | +首期 profile 为 BF16、无 bias、默认 SwiGLU、expert TP=1、B=L、同步 | ||
| 16 | +COPY-SYNC;原 FP32 概率数学及 Torch sum 保留。recompute、strict activation | ||
| 17 | +zero-copy、MoE overlap、参数 gather overlap、其他激活变体明确拒绝。 | ||
| 18 | +参与 setup 的每个 rank 必须已绑定至少一个本地 MoE 层,同进程各层共享几何。 | ||
| 19 | +PP/VPP/CP/model TP 的其他组合需要分别验证,不继承小拓扑结果。 | ||
| 20 | + | ||
| 21 | +## 标准计算 | ||
| 22 | + | ||
| 23 | +`npu_gmm_v5_out(x, weight_refs, out, counts)` 保留四个参数,调用方准备方向: | ||
| 24 | + | ||
| 25 | +- forward/dgrad:单 BF16 token Tensor、G 个二维 BF16 weight refs、单 caller-owned out。 | ||
| 26 | +- V5 参数固定为 `splitItem=3, groupType=0, groupListType=1, actType=0`。 | ||
| 27 | +- wgrad:两个 BF16 Tensor,标准 AddV2 作用于清零的独立 FP32 `[G,O,I]` scratch。 | ||
| 28 | +- AddV2 使用 INT64 device prefix;V5 使用 INT64 device counts,二者不能混用。 | ||
| 29 | +- scratch 的 local/remote 分组分别对真实目标 `add_` 一次;PR20 GR 追加远端贡献后 | ||
| 30 | + 不再 canonical add。canonical Parameter/main_grad、优化器和 checkpoint 身份不变。 | ||
| 31 | + | ||
| 32 | +薄绑定在原 `mindspeed/ops/csrc/cann/gmm.cpp` 中。它只使用显式选择的标准库, | ||
| 33 | +排空当前 Q1、在同一调用线程执行两阶段 API,检查完成后才释放 descriptor/workspace。 | ||
| 34 | +完成不明或释放失败会保留资源并关闭后续调用,需要进程重启。 | ||
| 35 | + | ||
| 36 | +构建或调用前显式设置实际核验的绝对路径,例如: | ||
| 37 | + | ||
| 38 | +```bash | ||
| 39 | +export MINDSPEED_MOONEP_OPAPI=/actual/cann/aarch64-linux/lib64/libopapi.so | ||
| 40 | +export MINDSPEED_MOONEP_OPAPI_DEPENDENCIES=/actual/cann/aarch64-linux/lib64/libnnopbase.so | ||
| 41 | +export TORCH_EXTENSIONS_DIR=/task/private/cache/torch_extensions | ||
| 42 | +``` | ||
| 43 | + | ||
| 44 | +依赖列表用冒号分隔;首次选择后不可改变。operator 四符号必须归属于所选 | ||
| 45 | +libopapi,descriptor/TLS 工具只能归属于该库或显式依赖。路径相符不证明内部 | ||
| 46 | +没有 staging:实际库哈希、headers、SOC、loaded maps、direct-out 和数学须分项核验。 | ||
| 47 | +禁止使用 devlib stub 或 custom OPP 代替实际标准运行库。 | ||
| 48 | + | ||
| 49 | +## 资源与失败边界 | ||
| 50 | + | ||
| 51 | +模型/DDP 创建真实 main_grad 后,枚举唯一 Buffer chunks、全部非零 native | ||
| 52 | +workspace、FC1/FC2 的 weight/grad sources。按真实 allocation 物理大小和登记顺序 | ||
| 53 | +核对,仅初始化一次 SHMEM,再为各层准备四份 pointer binding。 | ||
| 54 | + | ||
| 55 | +原 X/P0 使用独立 Tensor header pin 原 backing,R1 使用同一原 plan。 | ||
| 56 | +不保存 dispatched-X 副本;dP 在 R1 前生成,FC1 wgrad 最后读取 R1 后再算独立 dX。 | ||
| 57 | +slot 清零、PUSH、producer、target add、GR、raw-write 版本记账均有明确顺序。 | ||
| 58 | +GR/peer 完成后才返回 canonical dummy;Dispatch.backward 最终通信后退休 plan。 | ||
| 59 | + | ||
| 60 | +失败保留首异常和实际可达资源,禁止重放、checkpoint 或不确定的 teardown。 | ||
| 61 | +正常关闭要求没有活跃 plan,完成 peer fence 后 finalize,再销毁唯一 backing。 | ||
| 62 | +关闭后不在同一进程重建 session。 | ||
| 63 | + | ||
| 64 | +所有权按层区分:PR20 Buffer/SHMEM 管内部通信资源、登记和 native 执行; | ||
| 65 | +`_VirtualExperts` 持有外部 VMM allocation 引用与共享 scratch,负责有序销毁; | ||
| 66 | +MindSpeed runtime 保留 integration 首异常、拒绝重放和进程强引用;标准 C++ | ||
| 67 | +Call 保留其 Tensor、descriptor、workspace、TLS 生命周期及失败事实。 | ||
| 68 | +这些关联不复制 payload,也不形成第二套 native-ready 状态。 | ||
| 69 | +参数 AccumulateGrad 与 Dispatch.backward 在 Experts 返回后分别由 Autograd 调度, | ||
| 70 | +不假定两者先后;此前两投影 GR 必须完成,整个 backward 完成后才能更新参数。 | ||
| 71 | +当前仅 COPY-SYNC 可达;strict getter 固定 False,strict 专属 metadata 字段为零, | ||
| 72 | +COPY ledger 继续计量。GTP 和 full/selective recompute 仍明确拒绝;未测拓扑不继承组件结果。 | ||
| 73 | + | ||
| 74 | +## 验证入口 | ||
| 75 | + | ||
| 76 | +纯 host 入口(私有 CPU torch/pytest 依赖,不加载 NPU 扩展或初始化 SHMEM): | ||
| 77 | + | ||
| 78 | +```bash | ||
| 79 | +python tests_extend/host/moonep_minimal_host.py --cpu-deps /absolute/private/cpu-deps | ||
| 80 | +``` | ||
| 81 | + | ||
| 82 | +CPU Gloo 八进程检查可加 `--cpu8-output /absolute/fresh/private/output`;父进程仅 | ||
| 83 | +启动八个独立受审 worker,使用私有 FileStore,不替代实际 TorchNPU/HCCL 组件准入。 | ||
| 84 | +MoonEP 的主机错误协调组由原 runtime 一次创建、原 Buffer 上下文持有。 | ||
| 85 | +backward 输入 hook 的纯元数据检查也使用该 CPU EP 组;不新增组或 native ready 状态。 | ||
| 86 | +它不证明设备完成,随后两次 PUSH 的 stream/device 检查与完整完成边仍保留。 | ||
| 87 | +默认完整完成路径保留。仅两次 wgrad producer 前使用受限本地完成:保留全 EP | ||
| 88 | +错误协调、stream 检查和 checked local sync,省去该处额外 peer fence 及第二次 sync; | ||
| 89 | +PUSH、GR、quiet 和前后完成边均不变。新旧控制协议在初始化前一致拒绝, | ||
| 90 | +不能将此模式用于并发、外来 stream 或任意调用方。要求可用 Gloo、未绑定设备的默认进程组及匹配的安装源码/API; | ||
| 91 | +实际 adaptor bootstrap 的官方 TorchNPU tag 包装须匹配固定源码、闭包及原函数; | ||
| 92 | +继续执行公开 new_group,不绕过包装。不支持的包装或 `--disable-gloo-group` | ||
| 93 | +会拒绝,不静默退回其它控制后端。 | ||
| 94 | + | ||
| 95 | +组件入口为 `tests_extend/system_tests/moonep/validate_lplusb_gmm_contract.py` | ||
| 96 | +和 `validate_lplusb_autograd_4rank.py`。后者保留历史文件名,当前目标是八进程、 | ||
| 97 | +真实 Core PP2/EP2 分组、L=B=2 的通信/Autograd 组件;它不执行流水 schedule, | ||
| 98 | +**不是**真实 Core/DDP 训练。oracle 不替代 native grouped 调用。 | ||
| 99 | + | ||
| 100 | +`validate_core_ddp_train.py` 使用原 Core 模型、PP2 schedule、DDP 和 optimizer; | ||
| 101 | +`compare_core_ddp_abba.py` 离线比较八 rank 的 OFF/ON/ON/OFF 收据。 | ||
| 102 | +其纯 host 合同通过 `moonep_minimal_host.py --core-training-only` 运行;host | ||
| 103 | +结果不生成设备或训练资格。真实训练必须先闭合组件与独审,并冻结输入 manifest。 | ||
| 104 | +实际主 loss 只来自末流水 stage,首 stage 记录 None,不能为观测新增热区广播; | ||
| 105 | +主计时采用原 Core 日志打印的逐步 iteration ms(最后全局 rank 的 interval timer, | ||
| 106 | +0.1ms 精度),比较器必须通过 `--logs` 绑定四份原始日志;observer 的八 rank | ||
| 107 | +最大值仅作辅助,不充当该主指标。生产默认关闭,工具存在不代表训练或性能通过。 | ||
| @@ -0,0 +1 @@ | |||
| 1 | +"""MoonEP integration modules; importing this package has no runtime side effects.""" | ||
| @@ -0,0 +1,133 @@ | |||
| 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 | + result[0] if isinstance(result, tuple) else getattr(result, "model", None) | ||
| 110 | + ) | ||
| 111 | + return result | ||
| 112 | + | ||
| 113 | + return wrapper | ||
| 114 | + | ||
| 115 | + | ||
| 116 | +def save_checkpoint_wrapper(fn): | ||
| 117 | + @wraps(fn) | ||
| 118 | + def wrapper(*args, **kwargs): | ||
| 119 | + from .moonep_runtime import checkpoint_drain | ||
| 120 | + | ||
| 121 | + checkpoint_drain() | ||
| 122 | + return fn(*args, **kwargs) | ||
| 123 | + | ||
| 124 | + return wrapper | ||
| 125 | + | ||
| 126 | + | ||
| 127 | +def destroy_model_parallel_wrapper(fn): | ||
| 128 | + @wraps(fn) | ||
| 129 | + def wrapper(*args, **kwargs): | ||
| 130 | + close_moonep() | ||
| 131 | + return fn(*args, **kwargs) | ||
| 132 | + | ||
| 133 | + return wrapper | ||
| @@ -0,0 +1,238 @@ | |||
| 1 | +"""Fail-closed configuration and side-effect-free capability checks for MoonEP.""" | ||
| 2 | + | ||
| 3 | +from __future__ import annotations | ||
| 4 | + | ||
| 5 | +import hashlib | ||
| 6 | +import importlib.machinery | ||
| 7 | +import importlib.metadata | ||
| 8 | +import json | ||
| 9 | +from pathlib import Path | ||
| 10 | +from urllib.parse import unquote, urlparse | ||
| 11 | +from urllib.request import url2pathname | ||
| 12 | + | ||
| 13 | + | ||
| 14 | +_CAPABILITY_RESOURCE = "npu_patch/_integration_capabilities.json" | ||
| 15 | +_CAPABILITY_BASENAME = "_integration_capabilities.json" | ||
| 16 | +_REQUIRED_EDGES = ("Z1", "Z2", "Z3", "Z4", "R1") | ||
| 17 | + | ||
| 18 | + | ||
| 19 | +def moonep_enabled(args) -> bool: | ||
| 20 | + return ( | ||
| 21 | + getattr(args, "moe_token_dispatcher_type", None) == "flex" | ||
| 22 | + and getattr(args, "moe_flex_dispatcher_backend", None) == "moonep" | ||
| 23 | + ) | ||
| 24 | + | ||
| 25 | + | ||
| 26 | +def _enabled(args, name, default=False): | ||
| 27 | + value = getattr(args, name, default) | ||
| 28 | + if isinstance(value, str): | ||
| 29 | + disabled_values = {"", "disable", "disabled", "false", "none", "off"} | ||
| 30 | + return value.strip().lower() not in disabled_values | ||
| 31 | + return bool(value) | ||
| 32 | + | ||
| 33 | + | ||
| 34 | +def validate_moonep_args(args) -> None: | ||
| 35 | + if not moonep_enabled(args): | ||
| 36 | + return | ||
| 37 | + errors = [] | ||
| 38 | + ep = int(getattr(args, "expert_model_parallel_size", 1)) | ||
| 39 | + # Raw Core args own num_experts; TransformerConfig owns num_moe_experts. | ||
| 40 | + # Original MA may carry both, so never silently prefer a conflicting value. | ||
| 41 | + counts = [getattr(args, name, None) for name in ("num_experts", "num_moe_experts")] | ||
| 42 | + counts = [value for value in counts if value is not None] | ||
| 43 | + experts = 0 | ||
| 44 | + if any(type(value) is not int for value in counts): | ||
| 45 | + errors.append("num_experts/num_moe_experts must be integers (not bool, float, or string)") | ||
| 46 | + elif len(counts) == 2 and counts[0] != counts[1]: | ||
| 47 | + errors.append("conflicting num_experts and num_moe_experts") | ||
| 48 | + elif counts: | ||
| 49 | + experts = counts[0] | ||
| 50 | + if ep <= 1 or experts <= 0 or experts % ep: | ||
| 51 | + errors.append("EP must be >1 and num_moe_experts must be positive and divisible by EP") | ||
| 52 | + if int(getattr(args, "expert_tensor_parallel_size", 1)) != 1: | ||
| 53 | + errors.append("expert tensor parallel size must be 1") | ||
| 54 | + if not _enabled(args, "bf16") or _enabled(args, "fp16"): | ||
| 55 | + errors.append("activation and expert weights must use BF16") | ||
| 56 | + # Feature validation sees raw args and original MA's TransformerConfig | ||
| 57 | + # post-init; runtime initialization sees get_full_args(). A config does not | ||
| 58 | + # itself own the optimizer setting, so validate it only when propagated. | ||
| 59 | + use_distributed_optimizer = getattr(args, "use_distributed_optimizer", None) | ||
| 60 | + if use_distributed_optimizer is not None and not bool(use_distributed_optimizer): | ||
| 61 | + errors.append("distributed optimizer is required") | ||
| 62 | + if not _enabled(args, "moe_grouped_gemm"): | ||
| 63 | + errors.append("moe_grouped_gemm must be enabled") | ||
| 64 | + if _enabled(args, "moe_single_grouped_weight"): | ||
| 65 | + errors.append("moe_single_grouped_weight must be false (per-expert checkpoint schema)") | ||
| 66 | + if _enabled(args, "add_bias_linear"): | ||
| 67 | + errors.append("grouped expert bias is unsupported") | ||
| 68 | + # This expert-only MS flag is propagated by original MA into configs. | ||
| 69 | + # It is not an alias for Core's global gradient_accumulation_fusion flag. | ||
| 70 | + if not _enabled(args, "gemm_gradient_accumulation_fusion"): | ||
| 71 | + errors.append("gemm_gradient_accumulation_fusion must be enabled") | ||
| 72 | + if _enabled(args, "moe_shared_expert_overlap"): | ||
| 73 | + errors.append("shared expert overlap must be disabled") | ||
| 74 | + for name in ( | ||
| 75 | + "overlap_moe_expert_parallel_comm", | ||
| 76 | + "overlap_param_gather", | ||
| 77 | + "overlap_param_gather_with_optimizer_step", | ||
| 78 | + "moe_fb_overlap", | ||
| 79 | + "moe_enable_fb_overlap", | ||
| 80 | + "moe_zero_memory", | ||
| 81 | + "use_cuda_graphs", | ||
| 82 | + "fp8", | ||
| 83 | + "fp4", | ||
| 84 | + ): | ||
| 85 | + if _enabled(args, name): | ||
| 86 | + errors.append(f"{name} is unsupported by synchronous MoonEP v1") | ||
| 87 | + for name in ( | ||
| 88 | + "moe_permute_fusion", | ||
| 89 | + "moe_token_dispatcher_fused_permute", | ||
| 90 | + "use_fused_moe_token_permute_and_unpermute", | ||
| 91 | + ): | ||
| 92 | + if _enabled(args, name): | ||
| 93 | + errors.append(f"{name} must be disabled") | ||
| 94 | + recompute_modules = tuple(getattr(args, "recompute_modules", ()) or ()) | ||
| 95 | + # Full-layer and selective MoE recompute are not adapted for the current | ||
| 96 | + # exact-plan lifetime; both configurations remain explicitly rejected. | ||
| 97 | + if "moe_act" in recompute_modules: | ||
| 98 | + errors.append( | ||
| 99 | + "selective moe_act recompute is unsupported" | ||
| 100 | + ) | ||
| 101 | + if _enabled(args, "moe_enable_moonep"): | ||
| 102 | + errors.append("legacy moe_enable_moonep is removed; use flex + moonep") | ||
| 103 | + if _enabled(args, "moonep_activation_zero_copy"): | ||
| 104 | + errors.append("strict activation zero-copy is not adapted for the PR20 copy-counted profile") | ||
| 105 | + if getattr(args, "recompute_granularity", None): | ||
| 106 | + errors.append("recompute is not yet adapted for the PR20 exact-plan lifetime") | ||
| 107 | + for name in ("use_te_activation", "use_te_activation_func"): | ||
| 108 | + if _enabled(args, name): | ||
| 109 | + errors.append(f"{name} is not adapted for the plain SwiGLU profile") | ||
| 110 | + if getattr(args, "moe_mlp_glu_interleave_size", None) is not None: | ||
| 111 | + errors.append("moe_mlp_glu_interleave_size is not adapted") | ||
| 112 | + if hasattr(args, "gated_linear_unit") and not args.gated_linear_unit: | ||
| 113 | + errors.append("gated_linear_unit is required") | ||
| 114 | + if getattr(args, "activation_func_clamp_value", None) is not None: | ||
| 115 | + errors.append("activation_func_clamp_value is not adapted") | ||
| 116 | + if float(getattr(args, "glu_linear_offset", 0) or 0) != 0: | ||
| 117 | + errors.append("glu_linear_offset is not adapted") | ||
| 118 | + if errors: | ||
| 119 | + raise ValueError("invalid MoonEP L+B configuration: " + "; ".join(errors)) | ||
| 120 | + | ||
| 121 | + | ||
| 122 | +def _import_selected_capability_path(distribution_name): | ||
| 123 | + """Resolve a normal PYTHONPATH package without executing its __init__.py.""" | ||
| 124 | + package_name = distribution_name.replace("-", "_") | ||
| 125 | + spec = importlib.machinery.PathFinder.find_spec(package_name) | ||
| 126 | + if spec is None: | ||
| 127 | + return None | ||
| 128 | + locations = tuple(spec.submodule_search_locations or ()) | ||
| 129 | + if len(locations) != 1: | ||
| 130 | + raise RuntimeError( | ||
| 131 | + f"MoonEP provider {package_name} must resolve to one regular package" | ||
| 132 | + ) | ||
| 133 | + path = (Path(locations[0]).resolve() / _CAPABILITY_BASENAME).resolve() | ||
| 134 | + if not path.is_file(): | ||
| 135 | + raise RuntimeError( | ||
| 136 | + "ascend-moonep capability resource is missing beside the " | ||
| 137 | + f"import-selected provider: {path}" | ||
| 138 | + ) | ||
| 139 | + return path | ||
| 140 | + | ||
| 141 | + | ||
| 142 | +def read_provider_capabilities(distribution_name="npu_patch") -> dict[str, object]: | ||
| 143 | + """Read provider data without importing provider Python or native DSOs.""" | ||
| 144 | + path = _import_selected_capability_path(distribution_name) | ||
| 145 | + if path is not None: | ||
| 146 | + return _load_provider_capabilities(path) | ||
| 147 | + | ||
| 148 | + # PEP 660 editable installs may be exposed by a generated MetaPathFinder | ||
| 149 | + # instead of a normal sys.path package. Distribution metadata remains the | ||
| 150 | + # side-effect-free fallback for that layout and for installed wheels. | ||
| 151 | + try: | ||
| 152 | + distribution = importlib.metadata.distribution(distribution_name) | ||
| 153 | + except importlib.metadata.PackageNotFoundError as exc: | ||
| 154 | + raise RuntimeError( | ||
| 155 | + "MoonEP backend requires an importable ascend_moonep checkout or " | ||
| 156 | + "an installed ascend-moonep distribution" | ||
| 157 | + ) from exc | ||
| 158 | + path = Path(distribution.locate_file(_CAPABILITY_RESOURCE)).resolve() | ||
| 159 | + if not path.is_file(): | ||
| 160 | + # PEP 660 editable installs keep package files in the source checkout, | ||
| 161 | + # while locate_file() remains rooted at site-packages. PEP 610's | ||
| 162 | + # direct_url.json is distribution metadata and can be read without | ||
| 163 | + # importing ascend_moonep or loading its native extension. | ||
| 164 | + direct_url = distribution.read_text("direct_url.json") | ||
| 165 | + if direct_url: | ||
| 166 | + metadata = json.loads(direct_url) | ||
| 167 | + parsed = urlparse(metadata.get("url", "")) | ||
| 168 | + if parsed.scheme == "file" and metadata.get("dir_info", {}).get("editable"): | ||
| 169 | + source_root = Path(url2pathname(unquote(parsed.path))).resolve() | ||
| 170 | + path = (source_root / _CAPABILITY_RESOURCE).resolve() | ||
| 171 | + if not path.is_file(): | ||
| 172 | + raise RuntimeError(f"ascend-moonep capability resource is missing: {_CAPABILITY_RESOURCE}") | ||
| 173 | + return _load_provider_capabilities(path) | ||
| 174 | + | ||
| 175 | + | ||
| 176 | +def _load_provider_capabilities(path) -> dict[str, object]: | ||
| 177 | + with path.open("r", encoding="utf-8") as stream: | ||
| 178 | + manifest = json.load(stream) | ||
| 179 | + required = { | ||
| 180 | + "schema": 2, | ||
| 181 | + "provider_abi": "expert-pointer-buffer-v8", | ||
| 182 | + "layout": "LOCAL_EXPERTS_AND_SLOTS", | ||
| 183 | + "ordinary_source_owner_push": True, | ||
| 184 | + "direct_owner_reduce": True, | ||
| 185 | + "vmm_granularity_query": True, | ||
| 186 | + "explicit_comm_buffers": True, | ||
| 187 | + } | ||
| 188 | + mismatches = [key for key, value in required.items() if manifest.get(key) != value] | ||
| 189 | + if mismatches: | ||
| 190 | + raise RuntimeError("ascend-moonep capability mismatch: " + ", ".join(mismatches)) | ||
| 191 | + if manifest.get("completion_model", {}).get("synchronous") != "current_stream": | ||
| 192 | + raise RuntimeError("provider must declare current-stream submission") | ||
| 193 | + required_abis = {"GRAD_REDUCE_POINTER_ABI": 1, | ||
| 194 | + "GRAD_REDUCE_POINTER_UDMA_ABI": 3, "PREFETCH_PUSH_POINTER_ABI": 3} | ||
| 195 | + if manifest.get("native_abis") != required_abis: | ||
| 196 | + raise RuntimeError("PR20 native pointer ABI declaration mismatch") | ||
| 197 | + return manifest | ||
| 198 | + | ||
| 199 | + | ||
| 200 | +def capability_digest(manifest: dict[str, object]) -> str: | ||
| 201 | + payload = json.dumps(manifest, sort_keys=True, separators=(",", ":")).encode("utf-8") | ||
| 202 | + return hashlib.sha256(payload).hexdigest() | ||
| 203 | + | ||
| 204 | + | ||
| 205 | +def coordinated_capability_preflight(group=None) -> tuple[dict[str, object], str]: | ||
| 206 | + """Make every WORLD rank fail before provider import if any local read fails.""" | ||
| 207 | + import torch | ||
| 208 | + | ||
| 209 | + local_error = None | ||
| 210 | + try: | ||
| 211 | + manifest = read_provider_capabilities() | ||
| 212 | + digest = capability_digest(manifest) | ||
| 213 | + except Exception as exc: | ||
| 214 | + local_error = exc | ||
| 215 | + manifest = {} | ||
| 216 | + digest = "0" * 64 | ||
| 217 | + if torch.distributed.is_available() and torch.distributed.is_initialized(): | ||
| 218 | + device = torch.device("npu", torch.npu.current_device()) | ||
| 219 | + ok = torch.tensor([0 if local_error else 1], dtype=torch.int32, device=device) | ||
| 220 | + torch.distributed.all_reduce(ok, op=torch.distributed.ReduceOp.MIN, group=group) | ||
| 221 | + if int(ok.item()) != 1: | ||
| 222 | + if local_error is not None: | ||
| 223 | + raise RuntimeError( | ||
| 224 | + "MoonEP capability preflight failed before provider import: " | ||
| 225 | + f"{type(local_error).__name__}: {local_error}" | ||
| 226 | + ) from local_error | ||
| 227 | + raise RuntimeError("MoonEP capability preflight failed on another WORLD rank") | ||
| 228 | + raw = torch.tensor(list(bytes.fromhex(digest)), dtype=torch.uint8, device=device) | ||
| 229 | + peers = [torch.empty_like(raw) for _ in range(torch.distributed.get_world_size(group=group))] | ||
| 230 | + torch.distributed.all_gather(peers, raw, group=group) | ||
| 231 | + if any(bytes(peer.cpu().tolist()).hex() != digest for peer in peers): | ||
| 232 | + raise RuntimeError("ascend-moonep capability manifest differs across WORLD ranks") | ||
| 233 | + elif local_error is not None: | ||
| 234 | + raise RuntimeError( | ||
| 235 | + "MoonEP capability preflight failed before provider import: " | ||
| 236 | + f"{type(local_error).__name__}: {local_error}" | ||
| 237 | + ) from local_error | ||
| 238 | + return manifest, digest | ||
| @@ -0,0 +1,349 @@ | |||
| 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 _types(): | ||
| 37 | + import torch | ||
| 38 | + from mindspeed.ops.gmm import npu_gmm_v5_out | ||
| 39 | + from . import moonep_runtime | ||
| 40 | + | ||
| 41 | + class Dispatch(torch.autograd.Function): | ||
| 42 | + @staticmethod | ||
| 43 | + def forward( | ||
| 44 | + ctx, | ||
| 45 | + hidden, | ||
| 46 | + probs, | ||
| 47 | + indices, | ||
| 48 | + counts, | ||
| 49 | + manager, | ||
| 50 | + dispatch_backward_expected, | ||
| 51 | + expert_backward_expected, | ||
| 52 | + ): | ||
| 53 | + try: | ||
| 54 | + z1, dispatched_probs, cu_seqlens, provider_plan = ( | ||
| 55 | + moonep_runtime.get_moonep_buffer().dispatch( | ||
| 56 | + hidden, | ||
| 57 | + route_weights_sk=probs, | ||
| 58 | + topk_experts_sk=indices, | ||
| 59 | + tokens_per_expert=counts, | ||
| 60 | + zero_copy=moonep_runtime.strict_zero_copy_enabled(), | ||
| 61 | + ) | ||
| 62 | + ) | ||
| 63 | + moonep_runtime.complete(peer=True) | ||
| 64 | + import torch | ||
| 65 | + | ||
| 66 | + physical_counts = build_physical_counts( | ||
| 67 | + cu_seqlens, | ||
| 68 | + rank=int(torch.distributed.get_rank(group=manager.group)), | ||
| 69 | + local_experts=manager.num_local_experts, | ||
| 70 | + global_experts=manager.num_experts, | ||
| 71 | + slots=manager.num_local_experts, | ||
| 72 | + carrier_rows=int(z1.shape[0]), | ||
| 73 | + ) | ||
| 74 | + plan = VirtualExpertPlan( | ||
| 75 | + provider_plan=provider_plan, | ||
| 76 | + group_counts_2l=physical_counts, | ||
| 77 | + manager_cookie=manager._cookie, | ||
| 78 | + dispatch_backward_expected=bool(dispatch_backward_expected), | ||
| 79 | + expert_backward_expected=bool(expert_backward_expected), | ||
| 80 | + ) | ||
| 81 | + plan.prefix = physical_counts.cumsum(0) | ||
| 82 | + plan.source_pins = (manager._forward_source, probs.detach()) | ||
| 83 | + plan.source_versions = tuple(tensor_identity(t) for t in plan.source_pins) | ||
| 84 | + plan.weight_versions = tuple(int(w._version) for w in manager.virtual_experts.source_parameters) | ||
| 85 | + # Explicit zero suffix: every GMM still partitions the full carrier. | ||
| 86 | + padding = torch.arange(z1.shape[0], device=z1.device) >= cu_seqlens[-1] | ||
| 87 | + z1.masked_fill_(padding.unsqueeze(-1), 0) | ||
| 88 | + dispatched_probs.masked_fill_(padding, 0) | ||
| 89 | + plan.metadata = plan_metadata(plan) | ||
| 90 | + _VirtualExperts.admit(plan) | ||
| 91 | + manager.accept_forward_plan(plan) | ||
| 92 | + ctx.plan = plan | ||
| 93 | + ctx.manager_ref = weakref.ref(manager) | ||
| 94 | + return z1, dispatched_probs | ||
| 95 | + except Exception as exc: | ||
| 96 | + manager.fail_stop(None, exc, tuple(locals().values())) | ||
| 97 | + raise | ||
| 98 | + | ||
| 99 | + @staticmethod | ||
| 100 | + @torch.autograd.function.once_differentiable | ||
| 101 | + def backward(ctx, grad_hidden, grad_probs): | ||
| 102 | + manager = ctx.manager_ref() | ||
| 103 | + if manager is None: | ||
| 104 | + raise RuntimeError("MoonEP manager disappeared before dispatch backward") | ||
| 105 | + plan = ctx.plan | ||
| 106 | + manager.require_backward_plan(plan) | ||
| 107 | + try: | ||
| 108 | + grad_input, grad_route, _ = moonep_runtime.get_moonep_buffer().combine( | ||
| 109 | + plan=plan.provider_plan, | ||
| 110 | + hidden_nvsh=grad_hidden, | ||
| 111 | + route_weights_nvs=grad_probs, | ||
| 112 | + zero_copy=moonep_runtime.strict_zero_copy_enabled(), | ||
| 113 | + ) | ||
| 114 | + moonep_runtime.complete(peer=True) | ||
| 115 | + manager.retire(plan) | ||
| 116 | + except Exception as exc: | ||
| 117 | + manager.fail_stop(plan, exc, tuple(locals().values())) | ||
| 118 | + raise | ||
| 119 | + return grad_input, grad_route, None, None, None, None, None | ||
| 120 | + | ||
| 121 | + class Combine(torch.autograd.Function): | ||
| 122 | + @staticmethod | ||
| 123 | + def forward(ctx, expert_output, plan, manager): | ||
| 124 | + try: | ||
| 125 | + output, _, _ = moonep_runtime.get_moonep_buffer().combine( | ||
| 126 | + plan=plan.provider_plan, | ||
| 127 | + hidden_nvsh=expert_output, | ||
| 128 | + zero_copy=moonep_runtime.strict_zero_copy_enabled(), | ||
| 129 | + ) | ||
| 130 | + moonep_runtime.complete(peer=True) | ||
| 131 | + except Exception as exc: | ||
| 132 | + manager.fail_stop(plan, exc, tuple(locals().values())) | ||
| 133 | + raise | ||
| 134 | + ctx.plan = plan | ||
| 135 | + ctx.manager_ref = weakref.ref(manager) | ||
| 136 | + return output | ||
| 137 | + | ||
| 138 | + @staticmethod | ||
| 139 | + @torch.autograd.function.once_differentiable | ||
| 140 | + def backward(ctx, grad_output): | ||
| 141 | + manager = ctx.manager_ref() | ||
| 142 | + if manager is None: | ||
| 143 | + raise RuntimeError("MoonEP manager disappeared before combine backward") | ||
| 144 | + plan = ctx.plan | ||
| 145 | + manager.require_backward_plan(plan) | ||
| 146 | + try: | ||
| 147 | + dispatch_source = grad_output | ||
| 148 | + if not dispatch_source.is_contiguous(): | ||
| 149 | + raise RuntimeError("MoonEP combine backward requires contiguous dY") | ||
| 150 | + z3, _, _, _ = moonep_runtime.get_moonep_buffer().dispatch( | ||
| 151 | + dispatch_source, | ||
| 152 | + plan=plan.provider_plan, | ||
| 153 | + zero_copy=moonep_runtime.strict_zero_copy_enabled(), | ||
| 154 | + ) | ||
| 155 | + moonep_runtime.complete(peer=True) | ||
| 156 | + padding = torch.arange(z3.shape[0], device=z3.device) >= plan.provider_plan.cu_seqlens[-1] | ||
| 157 | + z3.masked_fill_(padding.unsqueeze(-1), 0) | ||
| 158 | + moonep_runtime.activation_edge("Z3", z3) | ||
| 159 | + return z3, None, None | ||
| 160 | + except Exception as exc: | ||
| 161 | + manager.fail_stop(plan, exc, tuple(locals().values())) | ||
| 162 | + raise | ||
| 163 | + | ||
| 164 | + class Experts(torch.autograd.Function): | ||
| 165 | + @staticmethod | ||
| 166 | + def forward(ctx, hidden, probs, original_hidden, plan, manager, *weights): | ||
| 167 | + virtual_experts = manager.virtual_experts | ||
| 168 | + count = virtual_experts.num_local_experts | ||
| 169 | + if probs.ndim != 1: | ||
| 170 | + raise RuntimeError("MoonEP expert-order probabilities must be one-dimensional") | ||
| 171 | + if len(weights) != 2 * count: | ||
| 172 | + raise RuntimeError("MoonEP expert boundary received an invalid weight set") | ||
| 173 | + try: | ||
| 174 | + buffer = moonep_runtime.get_moonep_buffer() | ||
| 175 | + virtual_experts.prefetch(buffer, "fc1", plan) | ||
| 176 | + virtual_experts.prefetch(buffer, "fc2", plan) | ||
| 177 | + | ||
| 178 | + fc1_refs = virtual_experts.gmm_weight_refs("fc1", transpose=True) | ||
| 179 | + fc1_out = hidden.new_empty((hidden.shape[0], weights[0].shape[0])) | ||
| 180 | + npu_gmm_v5_out(hidden.detach(), fc1_refs, fc1_out, plan.group_counts_2l) | ||
| 181 | + | ||
| 182 | + with torch.enable_grad(): | ||
| 183 | + fc1_leaf = fc1_out.detach().requires_grad_(True) | ||
| 184 | + activated = virtual_experts.activation(fc1_leaf) | ||
| 185 | + probability = probs.unsqueeze(-1) | ||
| 186 | + weighted = (activated.detach() * probability).to(activated.dtype) | ||
| 187 | + | ||
| 188 | + fc2_refs = virtual_experts.gmm_weight_refs("fc2", transpose=True) | ||
| 189 | + z2 = hidden.new_empty(hidden.shape) | ||
| 190 | + npu_gmm_v5_out(weighted, fc2_refs, z2, plan.group_counts_2l) | ||
| 191 | + moonep_runtime.activation_edge("Z2", z2) | ||
| 192 | + ctx.plan = plan | ||
| 193 | + ctx.manager_ref = weakref.ref(manager) | ||
| 194 | + ctx.weight_versions = tuple(int(weight._version) for weight in weights) | ||
| 195 | + ctx.save_for_backward( | ||
| 196 | + original_hidden, fc1_leaf, activated, weighted, probs, *weights | ||
| 197 | + ) | ||
| 198 | + return z2 | ||
| 199 | + except Exception as exc: | ||
| 200 | + manager.fail_stop(plan, exc, tuple(locals().values())) | ||
| 201 | + raise | ||
| 202 | + | ||
| 203 | + @staticmethod | ||
| 204 | + @torch.autograd.function.once_differentiable | ||
| 205 | + def backward(ctx, grad_output): | ||
| 206 | + manager = ctx.manager_ref() | ||
| 207 | + if manager is None: | ||
| 208 | + raise RuntimeError("MoonEP manager disappeared before expert backward") | ||
| 209 | + plan = ctx.plan | ||
| 210 | + try: | ||
| 211 | + manager.require_backward_plan(plan) | ||
| 212 | + virtual_experts = manager.virtual_experts | ||
| 213 | + saved = ctx.saved_tensors | ||
| 214 | + original_hidden, fc1_leaf, activated, weighted, probs = saved[:5] | ||
| 215 | + weights = saved[5:] | ||
| 216 | + if tuple(int(weight._version) for weight in weights) != ctx.weight_versions: | ||
| 217 | + raise RuntimeError("expert Parameter changed between exact forward and backward") | ||
| 218 | + buffer = moonep_runtime.get_moonep_buffer() | ||
| 219 | + counts = plan.group_counts_2l | ||
| 220 | + | ||
| 221 | + fc2_dgrad_refs = virtual_experts.gmm_weight_refs("fc2", transpose=False) | ||
| 222 | + grad_weighted = weighted.new_empty(weighted.shape) | ||
| 223 | + npu_gmm_v5_out(grad_output, fc2_dgrad_refs, grad_weighted, counts) | ||
| 224 | + virtual_experts.produce_and_publish( | ||
| 225 | + buffer, "fc2", plan, grad_output, weighted, | ||
| 226 | + ) | ||
| 227 | + virtual_experts.reduce(buffer, "fc2", plan) | ||
| 228 | + | ||
| 229 | + probability = probs.unsqueeze(-1) | ||
| 230 | + with torch.enable_grad(): | ||
| 231 | + grad_fc1 = torch.autograd.grad( | ||
| 232 | + activated, | ||
| 233 | + fc1_leaf, | ||
| 234 | + (grad_weighted * probability).to(activated.dtype), | ||
| 235 | + retain_graph=False, | ||
| 236 | + create_graph=False, | ||
| 237 | + )[0] | ||
| 238 | + grad_probs = ( | ||
| 239 | + grad_weighted.float() * activated.detach().float() | ||
| 240 | + ).sum(dim=-1).to(probs.dtype) | ||
| 241 | + | ||
| 242 | + r1, _, _, _ = buffer.dispatch( | ||
| 243 | + original_hidden, | ||
| 244 | + plan=plan.provider_plan, | ||
| 245 | + zero_copy=moonep_runtime.strict_zero_copy_enabled(), | ||
| 246 | + ) | ||
| 247 | + moonep_runtime.complete(peer=True) | ||
| 248 | + padding = torch.arange(r1.shape[0], device=r1.device) >= plan.provider_plan.cu_seqlens[-1] | ||
| 249 | + r1.masked_fill_(padding.unsqueeze(-1), 0) | ||
| 250 | + moonep_runtime.activation_edge("R1", r1) | ||
| 251 | + virtual_experts.produce_and_publish( | ||
| 252 | + buffer, "fc1", plan, grad_fc1, r1, | ||
| 253 | + ) | ||
| 254 | + virtual_experts.reduce(buffer, "fc1", plan) | ||
| 255 | + | ||
| 256 | + z4 = None | ||
| 257 | + if plan.dispatch_backward_expected: | ||
| 258 | + fc1_dgrad_refs = virtual_experts.gmm_weight_refs( | ||
| 259 | + "fc1", transpose=False | ||
| 260 | + ) | ||
| 261 | + z4 = r1.new_empty(r1.shape) | ||
| 262 | + npu_gmm_v5_out(grad_fc1, fc1_dgrad_refs, z4, counts) | ||
| 263 | + moonep_runtime.activation_edge("Z4", z4) | ||
| 264 | + | ||
| 265 | + moonep_runtime.complete(peer=True) | ||
| 266 | + virtual_experts.finalize_grads() | ||
| 267 | + # Prepare every dummy before publishing any DDP-ready flag. | ||
| 268 | + dummy = tuple(torch.zeros_like(parameter) for parameter in weights) | ||
| 269 | + for parameter, value in zip(weights, dummy): | ||
| 270 | + if value.shape != parameter.shape or value.dtype != parameter.dtype or value.device != parameter.device: | ||
| 271 | + raise RuntimeError("invalid canonical gradient dummy") | ||
| 272 | + if not plan.dispatch_backward_expected: | ||
| 273 | + manager.retire(plan) | ||
| 274 | + for parameter in weights: | ||
| 275 | + if hasattr(parameter, "grad_added_to_main_grad"): | ||
| 276 | + parameter.grad_added_to_main_grad = True | ||
| 277 | + return (z4, grad_probs, None, None, None, *dummy) | ||
| 278 | + except Exception as exc: | ||
| 279 | + manager.fail_stop(plan, exc, tuple(locals().values())) | ||
| 280 | + raise | ||
| 281 | + | ||
| 282 | + return Dispatch, Combine, Experts | ||
| 283 | + | ||
| 284 | + | ||
| 285 | +_AUTOGRAD_TYPES = None | ||
| 286 | + | ||
| 287 | + | ||
| 288 | +def _autograd_types(): | ||
| 289 | + global _AUTOGRAD_TYPES | ||
| 290 | + if _AUTOGRAD_TYPES is None: | ||
| 291 | + _AUTOGRAD_TYPES = _types() | ||
| 292 | + return _AUTOGRAD_TYPES | ||
| 293 | + | ||
| 294 | + | ||
| 295 | +def dispatch_apply(hidden, probs, indices, counts, manager): | ||
| 296 | + from . import moonep_runtime | ||
| 297 | + | ||
| 298 | + dispatch_backward_expected, expert_backward_expected = _backward_expectations( | ||
| 299 | + hidden, probs, manager.virtual_experts | ||
| 300 | + ) | ||
| 301 | + try: | ||
| 302 | + z1, dispatched_probs = _autograd_types()[0].apply( | ||
| 303 | + hidden, | ||
| 304 | + probs, | ||
| 305 | + indices, | ||
| 306 | + counts, | ||
| 307 | + manager, | ||
| 308 | + dispatch_backward_expected, | ||
| 309 | + expert_backward_expected, | ||
| 310 | + ) | ||
| 311 | + plan = manager.forward_plan() | ||
| 312 | + moonep_runtime.activation_edge("Z1", z1) | ||
| 313 | + return z1, dispatched_probs, plan | ||
| 314 | + except Exception as exc: | ||
| 315 | + manager.fail_stop(None, exc, tuple(locals().values())) | ||
| 316 | + raise | ||
| 317 | + | ||
| 318 | + | ||
| 319 | +def combine_apply(expert_output, manager, plan): | ||
| 320 | + return _autograd_types()[1].apply(expert_output, plan, manager) | ||
| 321 | + | ||
| 322 | + | ||
| 323 | +def moonep_grouped_mlp_forward_wrapper(forward): | ||
| 324 | + @wraps(forward) | ||
| 325 | + def wrapper(experts, hidden, tokens_per_expert, probs, *args, **kwargs): | ||
| 326 | + manager_ref = getattr(experts, "_mindspeed_moonep_manager_ref", None) | ||
| 327 | + if manager_ref is None: | ||
| 328 | + return forward(experts, hidden, tokens_per_expert, probs, *args, **kwargs) | ||
| 329 | + if args or kwargs: | ||
| 330 | + raise RuntimeError("MoonEP routed experts do not accept extra forward arguments") | ||
| 331 | + manager = manager_ref() | ||
| 332 | + if manager is None: | ||
| 333 | + raise RuntimeError("MoonEP manager disappeared before expert forward") | ||
| 334 | + plan = manager.forward_plan() | ||
| 335 | + if tokens_per_expert is not plan.group_counts_2l: | ||
| 336 | + raise RuntimeError("MoonEP counts are not the original plan Tensor") | ||
| 337 | + if ( | ||
| 338 | + tuple(tokens_per_expert.shape) != tuple(plan.group_counts_2l.shape) | ||
| 339 | + or tokens_per_expert.data_ptr() != plan.group_counts_2l.data_ptr() | ||
| 340 | + ): | ||
| 341 | + raise RuntimeError("MoonEP expert counts do not belong to the exact dispatch plan") | ||
| 342 | + original = manager.consume_forward_source(plan) | ||
| 343 | + weights = manager.virtual_experts.source_parameters | ||
| 344 | + output = _autograd_types()[2].apply( | ||
| 345 | + hidden, probs, original, plan, manager, *weights | ||
| 346 | + ) | ||
| 347 | + return output, None | ||
| 348 | + | ||
| 349 | + return wrapper | ||
| @@ -0,0 +1,644 @@ | |||
| 1 | +"""Control objects for synchronous Ascend MoonEP virtual experts.""" | ||
| 2 | + | ||
| 3 | +from __future__ import annotations | ||
| 4 | + | ||
| 5 | +from dataclasses import dataclass | ||
| 6 | +import weakref | ||
| 7 | + | ||
| 8 | + | ||
| 9 | +@dataclass(slots=True) | ||
| 10 | +class VirtualExpertPlan: | ||
| 11 | + """One exact forward/recompute pass, owned by its Autograd graph.""" | ||
| 12 | + | ||
| 13 | + provider_plan: object | ||
| 14 | + group_counts_2l: object | ||
| 15 | + manager_cookie: object | ||
| 16 | + dispatch_backward_expected: bool | ||
| 17 | + expert_backward_expected: bool | ||
| 18 | + admitted: bool = False | ||
| 19 | + retired: bool = False | ||
| 20 | + backward_started: bool = False | ||
| 21 | + prefix: object = None | ||
| 22 | + metadata: tuple = () | ||
| 23 | + published: tuple = () | ||
| 24 | + reduced: tuple = () | ||
| 25 | + source_pins: tuple = () | ||
| 26 | + source_versions: tuple = () | ||
| 27 | + weight_versions: tuple = () | ||
| 28 | + | ||
| 29 | + | ||
| 30 | +def build_physical_counts( | ||
| 31 | + global_cu_seqlens, | ||
| 32 | + *, | ||
| 33 | + rank: int, | ||
| 34 | + local_experts: int, | ||
| 35 | + global_experts: int, | ||
| 36 | + slots: int, | ||
| 37 | + carrier_rows: int | None = None, | ||
| 38 | +): | ||
| 39 | + """Return device counts ordered as this rank's L natives followed by B slots. | ||
| 40 | + | ||
| 41 | + MoonEP uses a fixed-capacity carrier. A rank may receive fewer routed rows | ||
| 42 | + than that capacity, but grouped GMM must still partition every carrier row. | ||
| 43 | + Assign the producer-zeroed suffix to the final slot without a device-to-host | ||
| 44 | + synchronization. Zero activation rows make this padding mathematically | ||
| 45 | + inert in forward, dgrad, and pointer-target wgrad. | ||
| 46 | + """ | ||
| 47 | + import torch | ||
| 48 | + | ||
| 49 | + if global_cu_seqlens.dtype != torch.int32 or global_cu_seqlens.ndim != 1: | ||
| 50 | + raise TypeError("global_cu_seqlens must be a one-dimensional INT32 tensor") | ||
| 51 | + if not global_cu_seqlens.is_contiguous(): | ||
| 52 | + raise ValueError("global_cu_seqlens must be contiguous") | ||
| 53 | + if slots != local_experts: | ||
| 54 | + raise ValueError("synchronous MoonEP requires B == L") | ||
| 55 | + if global_cu_seqlens.numel() != global_experts + slots: | ||
| 56 | + raise ValueError("global_cu_seqlens must describe E native groups followed by B slots") | ||
| 57 | + prefix = torch.zeros( | ||
| 58 | + 1, dtype=global_cu_seqlens.dtype, device=global_cu_seqlens.device | ||
| 59 | + ) | ||
| 60 | + global_counts = torch.diff(torch.cat((prefix, global_cu_seqlens))).to(torch.int64) | ||
| 61 | + begin = int(rank) * int(local_experts) | ||
| 62 | + end = begin + int(local_experts) | ||
| 63 | + if begin < 0 or end > int(global_experts): | ||
| 64 | + raise ValueError("rank/local expert range is outside the global expert axis") | ||
| 65 | + physical_counts = torch.cat( | ||
| 66 | + (global_counts[begin:end], global_counts[global_experts:]) | ||
| 67 | + ).contiguous() | ||
| 68 | + foreign = global_counts.clone() | ||
| 69 | + foreign[begin:end].zero_() | ||
| 70 | + foreign[global_experts:].zero_() | ||
| 71 | + invalid = (global_counts < 0).any() | foreign.any() | ||
| 72 | + if carrier_rows is not None: | ||
| 73 | + carrier_rows = int(carrier_rows) | ||
| 74 | + if carrier_rows <= 0: | ||
| 75 | + raise ValueError("carrier_rows must be positive") | ||
| 76 | + invalid = invalid | (global_cu_seqlens[-1] > carrier_rows) | ||
| 77 | + # Only a scalar validation bit crosses the host boundary, never counts. | ||
| 78 | + _validate_device_bit(invalid, "nonmonotone/foreign/overflow MoonEP groups") | ||
| 79 | + if carrier_rows is not None: | ||
| 80 | + physical_counts[-1].add_(carrier_rows - physical_counts.sum()) | ||
| 81 | + return physical_counts | ||
| 82 | + | ||
| 83 | + | ||
| 84 | +def _validate_device_bit(invalid, message): | ||
| 85 | + import torch | ||
| 86 | + if invalid.device.type == "npu" and torch.distributed.is_initialized(): | ||
| 87 | + from .moonep_runtime import get_moonep_buffer | ||
| 88 | + group = get_moonep_buffer()._ctx['group'] | ||
| 89 | + invalid = invalid.to(torch.int32) | ||
| 90 | + torch.distributed.all_reduce(invalid, op=torch.distributed.ReduceOp.MAX, group=group) | ||
| 91 | + if bool(invalid.item()): | ||
| 92 | + raise ValueError(message) | ||
| 93 | + | ||
| 94 | + | ||
| 95 | +def tensor_identity(tensor, *, version=True): | ||
| 96 | + return (id(tensor), tensor.untyped_storage()._cdata, tensor.untyped_storage().nbytes(), | ||
| 97 | + tensor.data_ptr(), tensor.storage_offset(), tuple(tensor.shape), | ||
| 98 | + tuple(tensor.stride()), tensor.dtype, tensor.device, | ||
| 99 | + int(tensor._version) if version else None) | ||
| 100 | + | ||
| @@ -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,14 @@ | |||
| 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 <map> | ||
| 21 | +#include <set> | ||
| 22 | +#include <sstream> | ||
| 23 | +#include <sys/stat.h> | ||
| 16 | #include <torch_npu/csrc/framework/utils/RandomOpAdapter.h> | 24 | #include <torch_npu/csrc/framework/utils/RandomOpAdapter.h> |
| 17 | #include <torch_npu/csrc/framework/utils/OpAdapter.h> | 25 | #include <torch_npu/csrc/framework/utils/OpAdapter.h> |
| 18 | #include <torch_npu/csrc/core/npu/NPUFormat.h> | 26 | #include <torch_npu/csrc/core/npu/NPUFormat.h> |
| @@ -292,6 +300,322 @@ std::tuple<std::vector<at::Tensor>, std::vector<at::Tensor>, std::vector<at::Ten | |||
| 292 | return std::make_tuple(dx, dw_output, dbias); | 300 | return std::make_tuple(dx, dw_output, dbias); |
| 293 | } | 301 | } |
| 294 | 302 | ||
| 303 | +namespace moonep_standard { | ||
| 304 | +// Only these two MoonEP entry points use this synchronous owner. The existing | ||
| 305 | +// generic GMM paths above retain their original implementation. | ||
| 306 | +using Run = int (*)(void*, uint64_t, aclOpExecutor*, aclrtStream); | ||
| 307 | +using V5Query = int (*)(const aclTensorList*, const aclTensorList*, const aclTensorList*, | ||
| 308 | + const aclTensorList*, const aclTensorList*, const aclTensorList*, const aclTensorList*, | ||
| 309 | + const aclTensorList*, const aclTensor*, const aclTensorList*, const aclTensorList*, | ||
| 310 | + const aclTensorList*, int64_t, int64_t, int64_t, int64_t, aclIntArray*, aclTensorList*, | ||
| 311 | + aclTensorList*, aclTensorList*, uint64_t*, aclOpExecutor**); | ||
| 312 | +using AddQuery = int (*)(const aclTensor*, const aclTensor*, const aclTensor*, aclTensor*, | ||
| 313 | + bool, bool, int64_t, int64_t, uint64_t*, aclOpExecutor**); | ||
| 314 | + | ||
| 315 | +std::string canonical(const char* value) | ||
| 316 | +{ | ||
| 317 | + TORCH_CHECK(value && value[0] == '/', "MoonEP requires an absolute standard library path"); | ||
| 318 | + char resolved[PATH_MAX]; | ||
| 319 | + TORCH_CHECK(realpath(value, resolved), "cannot resolve standard library: ", value); | ||
| 320 | + struct stat st; | ||
| 321 | + TORCH_CHECK(stat(resolved, &st) == 0 && S_ISREG(st.st_mode), "standard library is not a regular file"); | ||
| 322 | + const std::string path(resolved); | ||
| 323 | + TORCH_CHECK(path.find("cust") == std::string::npos, "custom opapi libraries are forbidden"); | ||
| 324 | + return path; | ||
| 325 | +} | ||
| 326 | + | ||
| 327 | +struct Library { | ||
| 328 | + std::string selection; | ||
| 329 | + std::string path; | ||
| 330 | + std::string dependencies; | ||
| 331 | + std::set<std::string> allowed; | ||
| 332 | + std::vector<void*> handles; | ||
| 333 | + std::map<std::string, std::string> owners; | ||
| 334 | + V5Query v5_query = nullptr; | ||
| 335 | + Run v5_run = nullptr; | ||
| 336 | + AddQuery add_query = nullptr; | ||
| 337 | + Run add_run = nullptr; | ||
| 338 | + _aclCreateTensor create_tensor = nullptr; | ||
| 339 | + _aclDestroyTensor destroy_tensor = nullptr; | ||
| 340 | + _aclCreateTensorList create_list = nullptr; | ||
| 341 | + _aclDestroyTensorList destroy_list = nullptr; | ||
| 342 | + InitHugeMemThreadLocal init_memory = nullptr; | ||
| 343 | + UnInitHugeMemThreadLocal uninit_memory = nullptr; | ||
| 344 | + ReleaseHugeMem release_memory = nullptr; | ||
| 345 | + | ||
| 346 | + Library() | ||
| 347 | + { | ||
| 348 | + const char* selected = std::getenv("MINDSPEED_MOONEP_OPAPI"); | ||
| 349 | + selection = selected ? selected : ""; | ||
| 350 | + path = canonical(selection.c_str()); | ||
| 351 | + TORCH_CHECK(path.substr(path.find_last_of('/') + 1) == "libopapi.so", "select standard libopapi.so"); | ||
| 352 | + const char* raw = std::getenv("MINDSPEED_MOONEP_OPAPI_DEPENDENCIES"); | ||
| 353 | + dependencies = raw ? raw : ""; | ||
| 354 | + allowed.insert(path); | ||
| 355 | + std::stringstream parts(dependencies); | ||
| 356 | + std::string item; | ||
| 357 | + while (std::getline(parts, item, ':')) { | ||
| 358 | + TORCH_CHECK(!item.empty(), "empty standard dependency path"); | ||
| 359 | + const auto dependency = canonical(item.c_str()); | ||
| 360 | + TORCH_CHECK(allowed.insert(dependency).second, "duplicate standard dependency"); | ||
| 361 | + void* handle = dlopen(dependency.c_str(), RTLD_NOW | RTLD_LOCAL); | ||
| 362 | + TORCH_CHECK(handle, "cannot load declared standard dependency: ", dependency); | ||
| 363 | + handles.push_back(handle); | ||
| 364 | + } | ||
| 365 | + TORCH_CHECK(dependencies.empty() || dependencies.back() != ':', "empty standard dependency path"); | ||
| 366 | + void* handle = dlopen(path.c_str(), RTLD_NOW | RTLD_LOCAL); | ||
| 367 | + TORCH_CHECK(handle, "cannot load selected standard libopapi.so"); | ||
| 368 | + handles.insert(handles.begin(), handle); | ||
| 369 | + // Publish this process-lifetime owner only after the entire fixed ABI | ||
| 370 | + // has been resolved and each symbol's actual provider has been checked. | ||
| 371 | + v5_query = symbol<V5Query>("aclnnGroupedMatmulV5GetWorkspaceSize", true); | ||
| 372 | + v5_run = symbol<Run>("aclnnGroupedMatmulV5", true); | ||
| 373 | + add_query = symbol<AddQuery>("aclnnGroupedMatmulAddV2GetWorkspaceSize", true); | ||
| 374 | + add_run = symbol<Run>("aclnnGroupedMatmulAddV2", true); | ||
| 375 | + create_tensor = symbol<_aclCreateTensor>("aclCreateTensor"); | ||
| 376 | + destroy_tensor = symbol<_aclDestroyTensor>("aclDestroyTensor"); | ||
| 377 | + create_list = symbol<_aclCreateTensorList>("aclCreateTensorList"); | ||
| 378 | + destroy_list = symbol<_aclDestroyTensorList>("aclDestroyTensorList"); | ||
| 379 | + init_memory = symbol<InitHugeMemThreadLocal>("InitHugeMemThreadLocal"); | ||
| 380 | + uninit_memory = symbol<UnInitHugeMemThreadLocal>("UnInitHugeMemThreadLocal"); | ||
| 381 | + release_memory = symbol<ReleaseHugeMem>("ReleaseHugeMem"); | ||
| 382 | + } | ||
| 383 | + | ||
| 384 | + void unchanged() const | ||
| 385 | + { | ||
| 386 | + const char* selected = std::getenv("MINDSPEED_MOONEP_OPAPI"); | ||
| 387 | + const char* raw = std::getenv("MINDSPEED_MOONEP_OPAPI_DEPENDENCIES"); | ||
| 388 | + TORCH_CHECK(selection == (selected ? selected : "") && | ||
| 389 | + dependencies == (raw ? raw : ""), "MoonEP standard library selection changed"); | ||
| 390 | + } | ||
| 391 | + | ||
| 392 | + template<class F> F symbol(const char* name, bool operation = false) | ||
| 393 | + { | ||
| 394 | + void* address = nullptr; | ||
| 395 | + for (auto handle : handles) { | ||
| 396 | + address = dlsym(handle, name); | ||
| 397 | + if (address) break; | ||
| 398 | + } | ||
| 399 | + TORCH_CHECK(address, "missing standard symbol: ", name); | ||
| 400 | + Dl_info info{}; | ||
| 401 | + TORCH_CHECK(dladdr(address, &info) && info.dli_fname, "missing symbol owner: ", name); | ||
| 402 | + const auto owner = canonical(info.dli_fname); | ||
| 403 | + TORCH_CHECK(operation ? owner == path : allowed.count(owner) == 1, | ||
| 404 | + "undeclared standard symbol owner: ", name, " at ", owner); | ||
| 405 | + owners[name] = owner; | ||
| 406 | + return reinterpret_cast<F>(address); | ||
| 407 | + } | ||
| 408 | +}; | ||
| 409 | + | ||
| 410 | +Library& library() | ||
| 411 | +{ | ||
| 412 | + // Library handles deliberately remain loaded while any failed call may own | ||
| 413 | + // an executor or device-visible descriptor from that library. | ||
| 414 | + static auto* value = new Library(); | ||
| 415 | + value->unchanged(); | ||
| 416 | + return *value; | ||
| 417 | +} | ||
| 418 | + | ||
| 419 | +std::map<std::string, std::string> backend_info() | ||
| 420 | +{ | ||
| 421 | + return library().owners; | ||
| 422 | +} | ||
| 423 | + | ||
| 424 | +struct Call { | ||
| 425 | + Library* owner = nullptr; // Library and its validated handles outlive every Call. | ||
| 426 | + std::vector<at::Tensor> tensors; | ||
| 427 | + at::Tensor workspace; | ||
| 428 | + std::vector<aclTensor*> descriptors; | ||
| 429 | + std::vector<aclTensorList*> lists; | ||
| 430 | + aclOpExecutor* executor = nullptr; | ||
| 431 | + | ||
| 432 | + aclTensor* tensor(const at::Tensor& value) | ||
| 433 | + { | ||
| 434 | + TORCH_CHECK(!value.unsafeGetTensorImpl()->is_wrapped_number(), "wrapped scalars are forbidden"); | ||
| 435 | + TORCH_CHECK(at_npu::native::get_npu_format(value) == ACL_FORMAT_ND, "MoonEP tensors must be ND"); | ||
| 436 | + tensors.push_back(value); | ||
| 437 | + const int64_t storage_size = value.storage().nbytes() / value.element_size(); | ||
| 438 | + auto descriptor = owner->create_tensor( | ||
| 439 | + value.sizes().data(), value.dim(), kATenScalarTypeToAclDataTypeTable[static_cast<int64_t>(value.scalar_type())], | ||
| 440 | + value.strides().data(), value.storage_offset(), ACL_FORMAT_ND, &storage_size, 1, | ||
| 441 | + const_cast<void*>(value.storage().data())); | ||
| 442 | + TORCH_CHECK(descriptor, "aclCreateTensor failed"); | ||
| 443 | + descriptors.push_back(descriptor); | ||
| 444 | + return descriptor; | ||
| 445 | + } | ||
| 446 | + | ||
| 447 | + aclTensorList* list(const std::vector<at::Tensor>& values) | ||
| 448 | + { | ||
| 449 | + std::vector<const aclTensor*> items; | ||
| 450 | + for (const auto& value : values) items.push_back(tensor(value)); | ||
| 451 | + auto result = owner->create_list(items.data(), items.size()); | ||
| 452 | + TORCH_CHECK(result, "aclCreateTensorList failed"); | ||
| 453 | + lists.push_back(result); | ||
| 454 | + // Fixed opbase aclDestroyTensorList destroys its element descriptors. | ||
| 455 | + // Transfer only after successful list creation; failed construction | ||
| 456 | + // leaves the individual descriptors owned by this Call. | ||
| 457 | + descriptors.resize(descriptors.size() - items.size()); | ||
| 458 | + return result; | ||
| 459 | + } | ||
| 460 | + | ||
| 461 | + void release() | ||
| 462 | + { | ||
| 463 | + auto& lib = *owner; | ||
| 464 | + while (!lists.empty()) { | ||
| 465 | + TORCH_CHECK(lib.destroy_list(lists.back()) == 0, | ||
| 466 | + "aclDestroyTensorList failed"); | ||
| 467 | + lists.pop_back(); | ||
| 468 | + } | ||
| 469 | + while (!descriptors.empty()) { | ||
| 470 | + TORCH_CHECK(lib.destroy_tensor(descriptors.back()) == 0, | ||
| 471 | + "aclDestroyTensor failed"); | ||
| 472 | + descriptors.pop_back(); | ||
| 473 | + } | ||
| 474 | + lib.release_memory(nullptr, false); | ||
| 475 | + lib.uninit_memory(nullptr, false); | ||
| 476 | + } | ||
| 477 | +}; | ||
| 478 | + | ||
| 479 | +bool failed = false; | ||
| 480 | +std::shared_ptr<Call>& quarantine() | ||
| 481 | +{ | ||
| 482 | + static auto* retained = new std::shared_ptr<Call>(); | ||
| 483 | + return *retained; | ||
| 484 | +} | ||
| 485 | + | ||
| 486 | +template<class Query> void execute(const at::Tensor& input, const char* operation, Run Library::*run, Query query) | ||
| 487 | +{ | ||
| 488 | + TORCH_CHECK(!failed, "MoonEP standard compute owner is failed; process restart required"); | ||
| 489 | + auto& retained = quarantine(); // allocate the strong root before submission | ||
| 490 | + auto call = std::make_shared<Call>(); | ||
| 491 | + try { | ||
| 492 | + auto& lib = library(); | ||
| 493 | + call->owner = &lib; | ||
| 494 | + auto current = c10_npu::getCurrentNPUStream(); | ||
| 495 | + TORCH_CHECK(input.device().index() == current.device_index(), "wrong current NPU device"); | ||
| 496 | + auto stream = current.stream(); // public accessor drains the caller's Q1 | ||
| 497 | + TORCH_CHECK(stream, "current NPU stream is null after Q1 drain"); | ||
| 498 | + current.synchronize(); | ||
| 499 | + TORCH_CHECK(lib.init_memory(nullptr, false) == 0, | ||
| 500 | + "InitHugeMemThreadLocal failed"); | ||
| 501 | + uint64_t bytes = 0; | ||
| 502 | + query(*call, bytes); | ||
| 503 | + TORCH_CHECK(call->executor, "standard workspace query returned a null executor"); | ||
| 504 | + TORCH_CHECK(bytes <= static_cast<uint64_t>(INT64_MAX), "workspace size overflow"); | ||
| 505 | + if (bytes) call->workspace = at::empty({static_cast<int64_t>(bytes)}, input.options().dtype(at::kByte)); | ||
| 506 | + TORCH_CHECK((lib.*run)( | ||
| 507 | + bytes ? call->workspace.data_ptr() : nullptr, bytes, call->executor, stream) == 0, | ||
| 508 | + "standard operator launch failed: ", operation); | ||
| 509 | + current.synchronize(); // checked completion precedes every resource release | ||
| 510 | + call->release(); | ||
| 511 | + } catch (...) { | ||
| 512 | + failed = true; | ||
| 513 | + retained = call; // shared_ptr assignment allocates nothing while unwinding | ||
| 514 | + throw; // never mask the first query/launch/completion/cleanup error | ||
| 515 | + } | ||
| 516 | +} | ||
| 517 | + | ||
| 518 | +void metadata(const at::Tensor& value, const at::Tensor& reference) | ||
| 519 | +{ | ||
| 520 | + TORCH_CHECK(value.device() == reference.device() && value.device().type() == c10::DeviceType::PrivateUse1, | ||
| 521 | + "MoonEP tensors must use one NPU device"); | ||
| 522 | + TORCH_CHECK(!value.requires_grad(), "MoonEP standard compute requires detached aliases"); | ||
| 523 | + TORCH_CHECK(!value.is_neg() && !value.is_conj(), "lazy negative/conjugate views are forbidden"); | ||
| 524 | + TORCH_CHECK(value.storage_offset() >= 0, "negative storage offset"); | ||
| 525 | + int64_t last = value.storage_offset(); | ||
| 526 | + for (int64_t dim = 0; dim < value.dim(); ++dim) { | ||
| 527 | + TORCH_CHECK(value.stride(dim) >= 0, "negative strides are forbidden"); | ||
| 528 | + if (value.size(dim)) last += (value.size(dim) - 1) * value.stride(dim); | ||
| 529 | + } | ||
| 530 | + TORCH_CHECK(!value.numel() || static_cast<uint64_t>(last + 1) <= value.storage().nbytes() / value.element_size(), | ||
| 531 | + "Tensor view exceeds its backing"); | ||
| 532 | +} | ||
| 533 | + | ||
| 534 | +void disjoint(const at::Tensor& out, const at::Tensor& input) | ||
| 535 | +{ | ||
| 536 | + if (!out.numel() || !input.numel()) return; | ||
| 537 | + const auto begin = reinterpret_cast<uintptr_t>(out.data_ptr()); | ||
| 538 | + const auto other = reinterpret_cast<uintptr_t>(input.data_ptr()); | ||
| 539 | + TORCH_CHECK(begin + out.numel() * out.element_size() <= other || | ||
| 540 | + other + input.numel() * input.element_size() <= begin, "MoonEP output aliases an input"); | ||
| 541 | +} | ||
| 542 | +} | ||
| 543 | + | ||
| 544 | +at::Tensor npu_gmm_v5_out(const at::Tensor& x, | ||
| 545 | + const std::vector<at::Tensor>& weight, | ||
| 546 | + const at::Tensor& out, | ||
| 547 | + const at::Tensor& group_list) | ||
| 548 | +{ | ||
| 549 | + TORCH_CHECK(x.scalar_type() == at::kBFloat16, "npu_gmm_v5_out requires BF16 x"); | ||
| 550 | + TORCH_CHECK(out.scalar_type() == at::kBFloat16, "npu_gmm_v5_out requires BF16 out"); | ||
| 551 | + TORCH_CHECK(group_list.scalar_type() == at::kLong && group_list.dim() == 1, | ||
| 552 | + "npu_gmm_v5_out requires a 1-D INT64 group count tensor"); | ||
| 553 | + TORCH_CHECK(!weight.empty() && weight.size() == static_cast<size_t>(group_list.size(0)), | ||
| 554 | + "weight refs and group counts must have the same non-zero length"); | ||
| 555 | + TORCH_CHECK(x.is_contiguous() && out.is_contiguous() && group_list.is_contiguous(), | ||
| 556 | + "npu_gmm_v5_out forbids implicit contiguous/copy fallbacks"); | ||
| 557 | + for (size_t index = 0; index < weight.size(); ++index) { | ||
| 558 | + TORCH_CHECK(weight[index].scalar_type() == at::kBFloat16, | ||
| 559 | + "every weight ref must be BF16"); | ||
| 560 | + TORCH_CHECK(weight[index].is_contiguous() || | ||
| 561 | + (weight[index].dim() == 2 && weight[index].stride(0) == 1 && | ||
| 562 | + weight[index].stride(1) == weight[index].size(0)), | ||
| 563 | + "every weight ref must be contiguous or a zero-copy 2-D transpose view"); | ||
| 564 | + } | ||
| 565 | + | ||
| 566 | + TORCH_CHECK(x.dim() == 2 && out.dim() == 2 && x.size(0) == out.size(0), "V5 requires matching token matrices"); | ||
| 567 | + moonep_standard::metadata(x, x); | ||
| 568 | + moonep_standard::metadata(out, x); | ||
| 569 | + moonep_standard::metadata(group_list, x); | ||
| 570 | + moonep_standard::disjoint(out, x); | ||
| 571 | + moonep_standard::disjoint(out, group_list); | ||
| 572 | + for (const auto& item : weight) { | ||
| 573 | + moonep_standard::metadata(item, x); | ||
| 574 | + TORCH_CHECK(item.dim() == 2 && item.size(0) == x.size(1) && item.size(1) == out.size(1), | ||
| 575 | + "V5 weight ref shape mismatch"); | ||
| 576 | + moonep_standard::disjoint(out, item); | ||
| 577 | + } | ||
| 578 | + moonep_standard::execute(x, "aclnnGroupedMatmulV5", &moonep_standard::Library::v5_run, | ||
| 579 | + [&](moonep_standard::Call& call, uint64_t& bytes) { | ||
| 580 | + auto inputs = call.list({x}); | ||
| 581 | + auto weights = call.list(weight); | ||
| 582 | + auto outputs = call.list({out}); | ||
| 583 | + auto groups = call.tensor(group_list); | ||
| 584 | + TORCH_CHECK(call.owner->v5_query(inputs, weights, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, | ||
| 585 | + groups, nullptr, nullptr, nullptr, 3, 0, 1, 0, nullptr, outputs, nullptr, nullptr, | ||
| 586 | + &bytes, &call.executor) == 0, "GroupedMatmulV5 workspace query failed"); | ||
| 587 | + }); | ||
| 588 | + return out; | ||
| 589 | +} | ||
| 590 | + | ||
| 591 | +at::Tensor npu_grouped_matmul_add_fp32_out(const at::Tensor& dy, const at::Tensor& x, | ||
| 592 | + const at::Tensor& scratch, const at::Tensor& prefix) | ||
| 593 | +{ | ||
| 594 | + TORCH_CHECK(x.scalar_type() == at::kBFloat16 && dy.scalar_type() == at::kBFloat16, | ||
| 595 | + "AddV2 requires BF16 x and dy"); | ||
| 596 | + TORCH_CHECK(x.dim() == 2 && dy.dim() == 2 && x.size(0) == dy.size(0), "AddV2 token matrix mismatch"); | ||
| 597 | + TORCH_CHECK(prefix.scalar_type() == at::kLong && prefix.dim() == 1 && prefix.numel() > 0, | ||
| 598 | + "AddV2 requires an INT64 prefix vector"); | ||
| 599 | + TORCH_CHECK(scratch.scalar_type() == at::kFloat && scratch.dim() == 3 && | ||
| 600 | + scratch.size(0) == prefix.numel() && scratch.size(1) == dy.size(1) && scratch.size(2) == x.size(1), | ||
| 601 | + "AddV2 requires FP32 scratch[G,O,I]"); | ||
| 602 | + for (const auto& item : {x, dy, scratch, prefix}) { | ||
| 603 | + moonep_standard::metadata(item, x); | ||
| 604 | + TORCH_CHECK(item.is_contiguous(), "AddV2 forbids implicit copies"); | ||
| 605 | + } | ||
| 606 | + for (const auto& item : {x, dy, prefix}) moonep_standard::disjoint(scratch, item); | ||
| 607 | + moonep_standard::execute(x, "aclnnGroupedMatmulAddV2", &moonep_standard::Library::add_run, | ||
| 608 | + [&](moonep_standard::Call& call, uint64_t& bytes) { | ||
| 609 | + auto grad = call.tensor(dy); | ||
| 610 | + auto input = call.tensor(x); | ||
| 611 | + auto groups = call.tensor(prefix); | ||
| 612 | + auto output = call.tensor(scratch); | ||
| 613 | + TORCH_CHECK(call.owner->add_query(grad, input, groups, output, true, false, 2, 0, &bytes, &call.executor) == 0, | ||
| 614 | + "GroupedMatmulAddV2 workspace query failed"); | ||
| 615 | + }); | ||
| 616 | + return scratch; | ||
| 617 | +} | ||
| 618 | + | ||
| 295 | PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { | 619 | 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>); | 620 | 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>); | 621 | 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 +630,8 @@ PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { | |||
| 306 | m.def("npu_gmm", (gmmv2)&npu_gmm, "grouped matmul forward with group_list type Tensor"); | 630 | 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"); | 631 | 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"); | 632 | m.def("npu_gmm_backward_fusion", (gmmv2_backward_fusion)&npu_gmm_backward_fusion, "grouped matmul backward with group_list type Tensor"); |
| 633 | + m.def("npu_gmm_v5_out", &npu_gmm_v5_out, "GroupedMatmulV5 with caller-owned output"); | ||
| 634 | + m.def("npu_grouped_matmul_add_fp32_out", &npu_grouped_matmul_add_fp32_out, | ||
| 635 | + "BF16 grouped producer into caller-owned FP32 full-G scratch"); | ||
| 636 | + m.def("moonep_standard_backend_info", &moonep_standard::backend_info); | ||
| 309 | } | 637 | } |
| @@ -1,3 +1,7 @@ | |||
| 1 | +import os | ||
| 2 | +from pathlib import Path | ||
| 3 | +from threading import Lock | ||
| 4 | + | ||
| 1 | import torch | 5 | import torch |
| 2 | from torch.library import impl | 6 | from torch.library import impl |
| 3 | from mindspeed.op_builder import GMMOpBuilder, GMMV2OpBuilder | 7 | from mindspeed.op_builder import GMMOpBuilder, GMMV2OpBuilder |
| @@ -5,7 +9,129 @@ from mindspeed.op_builder.builder import AS_LIBRARY | |||
| 5 | from mindspeed.ops.npu_groupmatmul_add import npu_groupmatmul_add_fp32 | 9 | from 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 | ||
| 11 | def check_optional_tensor(tensor, device, name): | 137 | def check_optional_tensor(tensor, device, name): |
| @@ -0,0 +1,120 @@ | |||
| 1 | +"""Read-only physical-line budget; writes only JSON to stdout.""" | ||
| 2 | +import argparse | ||
| 3 | +import hashlib | ||
| 4 | +import json | ||
| 5 | +import os | ||
| 6 | +from pathlib import Path | ||
| 7 | +import stat | ||
| 8 | +import subprocess | ||
| 9 | + | ||
| 10 | +BASES = {'donor': '4723bb74298d8d899474e7ee5d203eca6e52a28b', | ||
| 11 | + 'target': 'c1c5e11c168e6009dff7af5d8fc285895048d0a9', | ||
| 12 | + 'starting_merge': 'fbd40ed0e5e39de2c172900ac4db6b772dae0718'} | ||
| 13 | + | ||
| 14 | + | ||
| 15 | +def windows_io_name(value): | ||
| 16 | + if value.startswith('\\\\?\\'): | ||
| 17 | + return value | ||
| 18 | + return '\\\\?\\UNC\\'+value[2:] if value.startswith('\\\\') else '\\\\?\\'+value | ||
| 19 | + | ||
| 20 | + | ||
| 21 | +def io_path(path): | ||
| 22 | + value = os.path.abspath(os.fspath(path)) | ||
| 23 | + return Path(windows_io_name(value) if os.name == 'nt' else value) | ||
| 24 | + | ||
| 25 | + | ||
| 26 | +def display_path(path): | ||
| 27 | + value = os.fspath(path) | ||
| 28 | + if value.startswith('\\\\?\\UNC\\'): | ||
| 29 | + value = '\\\\'+value[8:] | ||
| 30 | + elif value.startswith('\\\\?\\'): | ||
| 31 | + value = value[4:] | ||
| 32 | + return Path(value) | ||
| 33 | + | ||
| 34 | + | ||
| 35 | +def checked_stat(path): | ||
| 36 | + info = io_path(path).lstat() | ||
| 37 | + if stat.S_ISLNK(info.st_mode) or getattr(info, 'st_reparse_tag', 0) == getattr(stat, 'IO_REPARSE_TAG_MOUNT_POINT', -1): | ||
| 38 | + raise ValueError('explicitly account for symlink/junction separately: '+str(display_path(path))) | ||
| 39 | + return info | ||
| 40 | + | ||
| 41 | + | ||
| 42 | +def regular_file(path): | ||
| 43 | + try: | ||
| 44 | + return stat.S_ISREG(checked_stat(path).st_mode) | ||
| 45 | + except FileNotFoundError: | ||
| 46 | + return False # Tracked deletions remain absent; no other IO error is suppressed. | ||
| 47 | + | ||
| 48 | + | ||
| 49 | +def canonical_path(path): | ||
| 50 | + selected = display_path(io_path(path)) | ||
| 51 | + for ancestor in (*reversed(selected.parents), selected): | ||
| 52 | + checked_stat(ancestor) | ||
| 53 | + return display_path(io_path(selected).resolve(strict=True)) | ||
| 54 | + | ||
| 55 | + | ||
| 56 | +def support_files(selected): | ||
| 57 | + info = checked_stat(selected) | ||
| 58 | + if stat.S_ISREG(info.st_mode): | ||
| 59 | + yield selected | ||
| 60 | + elif stat.S_ISDIR(info.st_mode): | ||
| 61 | + with os.scandir(io_path(selected)) as entries: | ||
| 62 | + children = [display_path(entry.path) for entry in entries] | ||
| 63 | + for child in children: | ||
| 64 | + yield from support_files(child) | ||
| 65 | + | ||
| 66 | + | ||
| 67 | +ROOT = canonical_path(__file__).parents[2] | ||
| 68 | + | ||
| 69 | + | ||
| 70 | +def git(*arguments): | ||
| 71 | + return subprocess.check_output(['git', '--no-optional-locks', '-C', str(ROOT), *arguments]) | ||
| 72 | + | ||
| 73 | + | ||
| 74 | +def record(path): | ||
| 75 | + checked_stat(path) | ||
| 76 | + data = io_path(path).read_bytes() | ||
| 77 | + return dict(bytes=len(data), sha256=hashlib.sha256(data).hexdigest(), | ||
| 78 | + physical_lines=None if b'\0' in data else len(data.splitlines())) | ||
| 79 | + | ||
| 80 | + | ||
| 81 | +def main(): | ||
| 82 | + parser = argparse.ArgumentParser(description=__doc__) | ||
| 83 | + parser.add_argument('--support', action='append', type=Path, default=[], | ||
| 84 | + help='Explicit additional dedicated documentation/tool directory or file') | ||
| 85 | + args = parser.parse_args() | ||
| 86 | + extra = [p for p in git('ls-files', '--others', '--exclude-standard', '-z').decode().split('\0') if p] | ||
| 87 | + comparisons = {} | ||
| 88 | + complete = set(extra) | ||
| 89 | + for name, base in BASES.items(): | ||
| 90 | + rows = [line.split('\t', 2) for line in git('diff', '--numstat', '--no-renames', base).decode().splitlines()] | ||
| 91 | + comparisons[name] = dict(base=base, files=rows, | ||
| 92 | + tracked_added=sum(int(a) for a, d, p in rows if a.isdigit()), | ||
| 93 | + tracked_deleted_not_credited=sum(int(d) for a, d, p in rows if d.isdigit()), | ||
| 94 | + binary_unknown=[p for a, d, p in rows if not a.isdigit()]) | ||
| 95 | + if name == 'target': | ||
| 96 | + complete.update(p for p in git('diff', '--name-only', '--no-renames', '-z', base).decode().split('\0') if p) | ||
| 97 | + files = {name: record(ROOT/name) for name in sorted(complete) if regular_file(ROOT/name)} | ||
| 98 | + untracked = {name: record(ROOT/name) for name in extra if regular_file(ROOT/name)} | ||
| 99 | + support = {} | ||
| 100 | + already = {canonical_path(ROOT/name) for name in files} | ||
| 101 | + for selected in args.support: | ||
| 102 | + selected = canonical_path(selected) | ||
| 103 | + for path in support_files(selected): | ||
| 104 | + if canonical_path(path) not in already: | ||
| 105 | + support[str(path)] = record(path) | ||
| 106 | + result = dict(head=git('rev-parse', 'HEAD').decode().strip(), comparisons=comparisons, | ||
| 107 | + untracked=untracked, complete_target_comparison=files, additional_support=support, | ||
| 108 | + deleted_lines_subtracted=False, | ||
| 109 | + complete_file_lines=(sum(item['physical_lines'] for item in files.values()) | ||
| 110 | + if all(item['physical_lines'] is not None for item in files.values()) else None), | ||
| 111 | + additional_support_lines=(sum(item['physical_lines'] for item in support.values()) | ||
| 112 | + if all(item['physical_lines'] is not None for item in support.values()) else None), | ||
| 113 | + binary_lines='UNKNOWN; bytes and hashes reported, not silently counted as zero source', | ||
| 114 | + history='Previous candidates/evidence remain separate; include explicitly, never credit deletions.', | ||
| 115 | + dependency_scope='Original third-party CPU wheels are dependencies, not task source; report separately.') | ||
| 116 | + print(json.dumps(result, indent=2)) | ||
| 117 | + | ||
| 118 | + | ||
| 119 | +if __name__ == '__main__': | ||
| 120 | + main() | ||
| @@ -0,0 +1,179 @@ | |||
| 1 | +"""Run only PR3990 host contracts with explicit private CPU dependencies.""" | ||
| 2 | +import argparse | ||
| 3 | +import importlib.abc | ||
| 4 | +import json | ||
| 5 | +import os | ||
| 6 | +from pathlib import Path | ||
| 7 | +import sys | ||
| 8 | + | ||
| 9 | + | ||
| 10 | +def _cpu8_workers(output, deps): | ||
| 11 | + """Launch fresh guarded CPU workers; this parent never imports Torch.""" | ||
| 12 | + import subprocess | ||
| 13 | + import time | ||
| 14 | + | ||
| 15 | + if (not output.is_absolute() or output != output.resolve() | ||
| 16 | + or output.exists() or output.is_symlink()): | ||
| 17 | + raise ValueError('CPU8 requires a fresh absolute task-private output directory') | ||
| 18 | + if any(name in os.environ for name in ('RANK', 'LOCAL_RANK', 'WORLD_SIZE')): | ||
| 19 | + raise RuntimeError('CPU8 parent must not run inside another distributed launcher') | ||
| 20 | + output.parent.resolve(strict=True) | ||
| 21 | + output.mkdir() | ||
| 22 | + receipts = output/'receipts' | ||
| 23 | + receipts.mkdir() | ||
| 24 | + workers, logs = [], [] | ||
| 25 | + failure = None | ||
| 26 | + deadline = time.monotonic()+120 | ||
| 27 | + journal = (output/'processes.jsonl').open('x', encoding='utf-8') | ||
| 28 | + try: | ||
| 29 | + for rank in range(8): | ||
| 30 | + env = dict(os.environ, RANK=str(rank), LOCAL_RANK=str(rank), WORLD_SIZE='8', | ||
| 31 | + TORCH_DEVICE_BACKEND_AUTOLOAD='0', PYTEST_DISABLE_PLUGIN_AUTOLOAD='1', | ||
| 32 | + MOONEP_HOST_CONTROL_CPU8='1', MOONEP_HOST_CONTROL_CPU8_STORE=str(output/'store'), | ||
| 33 | + MOONEP_HOST_CONTROL_CPU8_OUTPUT=str(receipts), OMP_NUM_THREADS='1') | ||
| 34 | + command = [sys.executable, '-E', '-X', 'utf8', str(Path(__file__).resolve()), | ||
| 35 | + '--cpu-deps', str(deps), '-k', 'cpu8_real_gloo'] | ||
| 36 | + log = (output/f'rank{rank}.log').open('x', encoding='utf-8') | ||
| 37 | + logs.append(log) | ||
| 38 | + process = subprocess.Popen(command, env=env, stdin=subprocess.DEVNULL, | ||
| 39 | + stdout=log, stderr=subprocess.STDOUT, | ||
| 40 | + creationflags=subprocess.CREATE_NO_WINDOW if os.name == 'nt' else 0) | ||
| 41 | + workers.append((rank, process, command)) | ||
| 42 | + journal.write(json.dumps(dict(rank=rank, pid=process.pid, command=command))+'\n') | ||
| 43 | + journal.flush() | ||
| 44 | + for _, process, _ in workers: | ||
| 45 | + process.wait(timeout=max(0.1, deadline-time.monotonic())) | ||
| 46 | + except Exception as error: | ||
| 47 | + failure = f'{type(error).__name__}: {error}' | ||
| 48 | + finally: | ||
| 49 | + cleanup_deadline = time.monotonic()+10 | ||
| 50 | + for _, process, _ in workers: | ||
| 51 | + if process.poll() is None: | ||
| 52 | + process.terminate() | ||
| 53 | + for _, process, _ in workers: | ||
| 54 | + try: | ||
| 55 | + process.wait(timeout=max(0.1, min(5, cleanup_deadline-time.monotonic()))) | ||
| 56 | + except subprocess.TimeoutExpired: | ||
| 57 | + process.kill() | ||
| 58 | + try: | ||
| 59 | + process.wait(timeout=max(0.1, min(5, cleanup_deadline-time.monotonic()))) | ||
| 60 | + except subprocess.TimeoutExpired: | ||
| 61 | + failure = f'owned CPU worker {process.pid} remains live after kill; inspect before retry' | ||
| 62 | + for log in logs: | ||
| 63 | + log.close() | ||
| 64 | + journal.close() | ||
| 65 | + results = [] | ||
| 66 | + for rank, process, command in workers: | ||
| 67 | + lines = (output/f'rank{rank}.log').read_text(encoding='utf-8').splitlines() | ||
| 68 | + guards = [json.loads(line) for line in lines if line.startswith('{"denied"')] | ||
| 69 | + path = receipts/f'rank{rank}.json' | ||
| 70 | + row = json.loads(path.read_text(encoding='utf-8')) if path.is_file() else None | ||
| 71 | + passed = (process.returncode == 0 and len(guards) == 1 | ||
| 72 | + and guards[0]['exit_code'] == 0 and guards[0]['denied'] == [] | ||
| 73 | + and guards[0]['scope'] == 'HOST_CPU_AND_STUB_ONLY' | ||
| 74 | + and guards[0]['native_npu_shmem'] == 'NOT_RUN' | ||
| 75 | + and guards[0]['training_qualifying'] is False | ||
| 76 | + and row is not None and row['rank'] == rank and row['status'] == 'PASS' | ||
| 77 | + and row['cpu_only'] is True | ||
| 78 | + and tuple(row['members']) == ((0, 1), (2, 3), (4, 5), (6, 7))[rank//2]) | ||
| 79 | + results.append(dict(rank=rank, pid=process.pid, command=command, | ||
| 80 | + exit_code=process.returncode, passed=passed, guard=guards, receipt=row)) | ||
| 81 | + passed = failure is None and len(results) == 8 and all(row['passed'] for row in results) | ||
| 82 | + result = dict(scope='PARENT_LAUNCH_ONLY_EIGHT_CPU_GLOO_WORKERS_EACH_GUARDED_NOT_CORE_HCCL', | ||
| 83 | + passed=passed, failure=failure, workers=results, native_npu_shmem='NOT_RUN', | ||
| 84 | + training_qualifying=False, wait_timeout_seconds=120, cleanup_wait_budget_seconds=10) | ||
| 85 | + with (output/'RESULT.json').open('x', encoding='utf-8') as handle: | ||
| 86 | + json.dump(result, handle, indent=2) | ||
| 87 | + print(json.dumps(result)) | ||
| 88 | + return 0 if passed else 1 | ||
| 89 | + | ||
| 90 | + | ||
| 91 | +def main(): | ||
| 92 | + parser = argparse.ArgumentParser(description=__doc__) | ||
| 93 | + parser.add_argument('--cpu-deps', type=Path, required=True) | ||
| 94 | + parser.add_argument('-k', dest='selection', default=None) | ||
| 95 | + parser.add_argument('--cpu8-output', type=Path, | ||
| 96 | + help='Run eight fresh guarded CPU workers with a private FileStore') | ||
| 97 | + selection = parser.add_mutually_exclusive_group() | ||
| 98 | + selection.add_argument('--configuration-only', action='store_true', | ||
| 99 | + help='Run the existing weight-mode configuration tests under the same guard') | ||
| 100 | + selection.add_argument('--core-training-only', action='store_true', | ||
| 101 | + help='Run the pure-host Core training driver contracts under the same guard') | ||
| 102 | + args = parser.parse_args() | ||
| 103 | + deps = args.cpu_deps.resolve(strict=True) | ||
| 104 | + root = Path(__file__).resolve().parents[2] | ||
| 105 | + if not args.cpu_deps.is_absolute() or not (deps/'torch/__init__.py').is_file(): | ||
| 106 | + raise ValueError('explicit absolute private CPU Torch dependency directory required') | ||
| 107 | + forbidden = ('torch_npu', 'torchair', 'npu_patch', 'ascend_moonep', 'shmem', 'transformer_engine') | ||
| 108 | + if any(name.split('.')[0] in forbidden or name == 'torch' for name in sys.modules): | ||
| 109 | + raise RuntimeError('fresh host interpreter required') | ||
| 110 | + if args.cpu8_output is not None: | ||
| 111 | + if args.selection or args.configuration_only or args.core_training_only: | ||
| 112 | + raise ValueError('CPU8 parent selects only its dedicated worker test') | ||
| 113 | + raise SystemExit(_cpu8_workers(args.cpu8_output, deps)) | ||
| 114 | + sys.dont_write_bytecode = True | ||
| 115 | + os.environ['TORCH_DEVICE_BACKEND_AUTOLOAD'] = '0' | ||
| 116 | + os.environ['PYTEST_DISABLE_PLUGIN_AUTOLOAD'] = '1' | ||
| 117 | + denied = [] | ||
| 118 | + | ||
| 119 | + def reject(name): | ||
| 120 | + denied.append(name) | ||
| 121 | + raise RuntimeError('pure host guard rejected '+name) | ||
| 122 | + | ||
| 123 | + class Imports(importlib.abc.MetaPathFinder): | ||
| 124 | + def find_spec(self, fullname, path=None, target=None): | ||
| 125 | + if fullname.split('.')[0] in forbidden or fullname == 'torch.utils.cpp_extension': | ||
| 126 | + reject(fullname) | ||
| 127 | + | ||
| 128 | + def audit(event, values): | ||
| 129 | + if event in ('subprocess.Popen', '_winapi.CreateProcess'): | ||
| 130 | + reject('subprocess/compiler') | ||
| 131 | + if event == 'import' and values[0].split('.')[0] in forbidden: | ||
| 132 | + reject('native import '+values[0]) | ||
| 133 | + if event == 'import' and values[1]: | ||
| 134 | + origin = Path(str(values[1])).resolve() | ||
| 135 | + if origin.suffix in ('.pyd', '.so') and not ( | ||
| 136 | + origin.is_relative_to(deps) or origin.parent == Path(sys.base_prefix)/'DLLs'): | ||
| 137 | + reject('extension outside CPU dependencies/stdlib '+origin.name) | ||
| 138 | + if event == 'ctypes.dlopen': | ||
| 139 | + if values[0] is None: | ||
| 140 | + return | ||
| 141 | + library = Path(str(values[0])) | ||
| 142 | + cpu = library.is_absolute() and library.resolve().is_relative_to(deps) | ||
| 143 | + windows = os.name == 'nt' and library.name.lower().removesuffix('.dll') in ( | ||
| 144 | + 'kernel32', 'msvcrt', 'msvcp140', 'vcruntime140', 'vcruntime140_1') | ||
| 145 | + if not (cpu or windows): | ||
| 146 | + reject('dlopen '+library.name) | ||
| 147 | + | ||
| 148 | + sys.meta_path.insert(0, Imports()) | ||
| 149 | + sys.addaudithook(audit) | ||
| 150 | + sys.path[:0] = [str(deps), str(root)] | ||
| 151 | + import torch | ||
| 152 | + import pytest | ||
| 153 | + if (torch.__version__ != '2.5.1+cpu' or torch.version.cuda is not None | ||
| 154 | + or not Path(torch.__file__).resolve().is_relative_to(deps) | ||
| 155 | + or pytest.__version__ != '8.4.2' or not Path(pytest.__file__).resolve().is_relative_to(deps)): | ||
| 156 | + raise RuntimeError('private official CPU dependency identity mismatch') | ||
| 157 | + torch.set_num_threads(1) | ||
| 158 | + command = ['-q', '--noconftest', '-p', 'no:cacheprovider', | ||
| 159 | + str(root/'tests_extend/unit_tests/features/moe/test_moonep_lplusb_contract.py'), | ||
| 160 | + str(root/'tests_extend/unit_tests/features/moe/test_moonep_pr20_autograd.py'), | ||
| 161 | + str(root/'tests_extend/host/test_moonep_standard_gmm.py'), | ||
| 162 | + str(root/'tests_extend/host/test_moonep_mechanism_probe.py')] | ||
| 163 | + if args.configuration_only: | ||
| 164 | + command = ['-q', '--noconftest', '-p', 'no:cacheprovider', | ||
| 165 | + str(root/'tests_extend/unit_tests/mindspeed/test_gmm_weight_mode.py')] | ||
| 166 | + if args.core_training_only: | ||
| 167 | + command = ['-q', '--noconftest', '-p', 'no:cacheprovider', | ||
| 168 | + str(root/'tests_extend/host/test_moonep_core_training_contract.py')] | ||
| 169 | + if args.selection: | ||
| 170 | + command += ['-k', args.selection] | ||
| 171 | + status = pytest.main(command) | ||
| 172 | + print(json.dumps(dict(scope='HOST_CPU_AND_STUB_ONLY', training_qualifying=False, | ||
| 173 | + torch=torch.__version__, torch_path=torch.__file__, pytest=pytest.__version__, | ||
| 174 | + exit_code=int(status), denied=denied, native_npu_shmem='NOT_RUN'), sort_keys=True)) | ||
| 175 | + raise SystemExit(int(status) if status else int(bool(denied))) | ||
| 176 | + | ||
| 177 | + | ||
| 178 | +if __name__ == '__main__': | ||
| 179 | + main() | ||
| @@ -0,0 +1,173 @@ | |||
| 1 | +"""Stdlib budget IO tests; real Windows long paths are a separate explicit case.""" | ||
| 2 | + | ||
| 3 | +import contextlib | ||
| 4 | +import hashlib | ||
| 5 | +import importlib.util | ||
| 6 | +import io | ||
| 7 | +import json | ||
| 8 | +import os | ||
| 9 | +from pathlib import Path | ||
| 10 | +import shutil | ||
| 11 | +import stat | ||
| 12 | +import subprocess | ||
| 13 | +import sys | ||
| 14 | +import tempfile | ||
| 15 | +import unittest | ||
| 16 | +from unittest import mock | ||
| 17 | + | ||
| 18 | + | ||
| 19 | +COUNTER = Path(__file__).resolve().with_name('count_moonep_minimal.py') | ||
| 20 | +SPEC = importlib.util.spec_from_file_location('budget_counter_under_test', COUNTER) | ||
| 21 | +MODULE = importlib.util.module_from_spec(SPEC) | ||
| 22 | +SPEC.loader.exec_module(MODULE) | ||
| 23 | +LEGACY_HEAD = 'd4505dd4347fff0f45eb4ec7131307d2b792df30' | ||
| 24 | +LEGACY_SHA256 = 'b05adadce34ffc6d660d6db64b8e95cb5c2906cbab60658bb9e5511c97ac571a' | ||
| 25 | + | ||
| 26 | + | ||
| 27 | +def legacy_source(): | ||
| 28 | + raw = subprocess.check_output(['git', '-C', str(MODULE.ROOT), 'show', | ||
| 29 | + LEGACY_HEAD+':tests_extend/host/count_moonep_minimal.py']) | ||
| 30 | + if hashlib.sha256(raw).hexdigest() != LEGACY_SHA256: | ||
| 31 | + raise AssertionError('original counter source differs from fixed reproduction') | ||
| 32 | + return raw | ||
| 33 | + | ||
| 34 | + | ||
| 35 | +def fixture_io(path): | ||
| 36 | + """Independent test fixture IO, without the counter's path implementation.""" | ||
| 37 | + value = str(path) | ||
| 38 | + if os.name == 'nt': | ||
| 39 | + value = '\\\\?\\UNC\\'+value[2:] if value.startswith('\\\\') else '\\\\?\\'+value | ||
| 40 | + return Path(value) | ||
| 41 | + | ||
| 42 | + | ||
| 43 | +class BudgetIOProof(unittest.TestCase): | ||
| 44 | + def setUp(self): | ||
| 45 | + self.base = Path(tempfile.mkdtemp(prefix='moonep-budget-host-')).resolve() | ||
| 46 | + self.addCleanup(self.remove_fixture) | ||
| 47 | + | ||
| 48 | + def remove_fixture(self): | ||
| 49 | + target = self.base.resolve(strict=True) | ||
| 50 | + if target.parent != Path(tempfile.gettempdir()).resolve(strict=True) or not target.name.startswith('moonep-budget-host-'): | ||
| 51 | + raise AssertionError('refuse cleanup outside this named test temporary directory') | ||
| 52 | + shutil.rmtree(fixture_io(target)) | ||
| 53 | + | ||
| 54 | + def capture(self, main, arguments): | ||
| 55 | + output = io.StringIO() | ||
| 56 | + with mock.patch.object(sys, 'argv', ['count_moonep_minimal.py', *arguments]), contextlib.redirect_stdout(output): | ||
| 57 | + main() | ||
| 58 | + return json.loads(output.getvalue()) | ||
| 59 | + | ||
| 60 | + def test_windows_prefix_conversion_is_pure_path_logic_not_unc_access(self): | ||
| 61 | + drive, unc = 'C:\\fixture\\file.py', '\\\\server\\share\\file.py' | ||
| 62 | + self.assertEqual(MODULE.windows_io_name(drive), '\\\\?\\'+drive) | ||
| 63 | + self.assertEqual(MODULE.windows_io_name(unc), '\\\\?\\UNC\\server\\share\\file.py') | ||
| 64 | + self.assertEqual(str(MODULE.display_path(MODULE.windows_io_name(drive))), drive) | ||
| 65 | + self.assertEqual(str(MODULE.display_path(MODULE.windows_io_name(unc))), unc) | ||
| 66 | + self.assertEqual(MODULE.windows_io_name(MODULE.windows_io_name(drive)), MODULE.windows_io_name(drive)) | ||
| 67 | + | ||
| 68 | + def test_short_paths_scope_formulas_overlap_and_binary_unknown_match_legacy(self): | ||
| 69 | + repo = self.base/'repo' | ||
| 70 | + repo.mkdir() | ||
| 71 | + (repo/'tracked.py').write_bytes(b'# comment\n\nx=1\n') | ||
| 72 | + (repo/'new.py').write_bytes(b'') | ||
| 73 | + (repo/'data.bin').write_bytes(b'a\0b') | ||
| 74 | + | ||
| 75 | + def git(*arguments): | ||
| 76 | + if arguments[0] == 'ls-files': return b'new.py\0' | ||
| 77 | + if arguments[0] == 'rev-parse': return b'fixture-head\n' | ||
| 78 | + if '--numstat' in arguments: return b'3\t4\ttracked.py\n-\t-\tdata.bin\n' | ||
| 79 | + return b'tracked.py\0data.bin\0deleted.py\0' | ||
| 80 | + | ||
| 81 | + legacy = {'__file__': str(COUNTER), '__name__': 'original_budget_fixture'} | ||
| 82 | + exec(compile(legacy_source(), str(COUNTER), 'exec'), legacy) | ||
| 83 | + legacy['ROOT'], legacy['git'] = repo, git | ||
| 84 | + arguments = ['--support', str(repo), '--support', str(repo/'tracked.py')] | ||
| 85 | + original = self.capture(legacy['main'], arguments) | ||
| 86 | + with mock.patch.object(MODULE, 'ROOT', repo), mock.patch.object(MODULE, 'git', git): | ||
| 87 | + current = self.capture(MODULE.main, arguments) | ||
| 88 | + self.assertEqual(current, original) | ||
| 89 | + self.assertEqual(set(current['complete_target_comparison']), {'tracked.py', 'new.py', 'data.bin'}) | ||
| 90 | + self.assertEqual(current['complete_target_comparison']['tracked.py']['physical_lines'], 3) | ||
| 91 | + self.assertEqual(current['untracked']['new.py']['physical_lines'], 0) | ||
| 92 | + self.assertIsNone(current['complete_file_lines']) | ||
| 93 | + self.assertEqual(current['additional_support'], {}) | ||
| 94 | + self.assertFalse(current['deleted_lines_subtracted']) | ||
| 95 | + self.assertEqual(current['comparisons']['target']['tracked_deleted_not_credited'], 4) | ||
| 96 | + self.assertEqual(current['comparisons']['target']['binary_unknown'], ['data.bin']) | ||
| 97 | + | ||
| 98 | + def test_missing_file_only_false_other_io_errors_propagate(self): | ||
| 99 | + self.assertFalse(MODULE.regular_file(self.base/'deleted.py')) | ||
| 100 | + original = PermissionError('injected denied file metadata') | ||
| 101 | + with mock.patch.object(MODULE, 'checked_stat', side_effect=original): | ||
| 102 | + with self.assertRaises(PermissionError) as caught: | ||
| 103 | + MODULE.regular_file(self.base/'denied.py') | ||
| 104 | + self.assertIs(caught.exception, original) | ||
| 105 | + with mock.patch.object(MODULE, 'checked_stat', return_value=type('Info', (), {'st_mode': stat.S_IFDIR})()): | ||
| 106 | + self.assertFalse(MODULE.regular_file(self.base)) | ||
| 107 | + | ||
| 108 | + def test_actual_symlink_is_rejected_without_following(self): | ||
| 109 | + target = self.base/'target.py' | ||
| 110 | + target.write_bytes(b'x\n') | ||
| 111 | + link = self.base/'linked.py' | ||
| 112 | + try: | ||
| 113 | + link.symlink_to(target) | ||
| 114 | + except OSError as error: | ||
| 115 | + self.skipTest('actual symlink capability unavailable: '+str(error)) | ||
| 116 | + for action in (lambda: MODULE.record(link), lambda: MODULE.canonical_path(link), | ||
| 117 | + lambda: list(MODULE.support_files(self.base))): | ||
| 118 | + with self.assertRaises(ValueError): action() | ||
| 119 | + | ||
| 120 | + @unittest.skipUnless(os.name == 'nt', 'real Windows junction branch NOT_RUN on this OS') | ||
| 121 | + def test_actual_windows_junction_is_rejected(self): | ||
| 122 | + target, link = self.base/'target', self.base/'junction' | ||
| 123 | + target.mkdir() | ||
| 124 | + created = subprocess.run(['cmd', '/c', 'mklink', '/J', str(link), str(target)], capture_output=True) | ||
| 125 | + if created.returncode: | ||
| 126 | + self.skipTest('actual junction capability unavailable: '+created.stderr.decode(errors='replace')) | ||
| 127 | + try: | ||
| 128 | + with self.assertRaises(ValueError): MODULE.canonical_path(link) | ||
| 129 | + with self.assertRaises(ValueError): list(MODULE.support_files(self.base)) | ||
| 130 | + finally: | ||
| 131 | + os.rmdir(fixture_io(link)) # Remove this link only, never recursively its target. | ||
| 132 | + | ||
| 133 | + @unittest.skipUnless(os.name == 'nt', 'actual Windows >260/>350 filesystem proof NOT_RUN on this OS') | ||
| 134 | + def test_actual_windows_long_paths_old_omission_and_complete_new_cli(self): | ||
| 135 | + support = self.base/'support' | ||
| 136 | + long = support/('a'*95)/('b'*95) | ||
| 137 | + deep = long/('c'*95) | ||
| 138 | + payloads = {support/'short.py': (b'# short\n\npass\n', 3), | ||
| 139 | + long/'long.py': (b'# long\n\nvalue = 7\n', 3), | ||
| 140 | + deep/'deep.py': (b'first\r\n\r\nlast', 3), | ||
| 141 | + deep/'empty.txt': (b'', 0), deep/'binary.bin': (b'a\0b\n', None)} | ||
| 142 | + self.assertGreater(len(str(long/'long.py')), 260) | ||
| 143 | + self.assertGreater(len(str(deep/'deep.py')), 350) | ||
| 144 | + expected = {} | ||
| 145 | + for path, (data, lines) in payloads.items(): | ||
| 146 | + fixture_io(path.parent).mkdir(parents=True, exist_ok=True) | ||
| 147 | + fixture_io(path).write_bytes(data) | ||
| 148 | + expected[str(path)] = dict(bytes=len(data), sha256=hashlib.sha256(data).hexdigest(), physical_lines=lines) | ||
| 149 | + legacy = self.base/'original_counter.py' | ||
| 150 | + legacy.write_bytes(legacy_source()) | ||
| 151 | + # Exact original bytes/real Git/real intended __file__; only the fixture support outcome is asserted. | ||
| 152 | + bootstrap = ("from pathlib import Path; import sys; source=Path(sys.argv.pop(1)).read_bytes(); " | ||
| 153 | + "filename=sys.argv.pop(1); sys.argv[0]=filename; " | ||
| 154 | + "exec(compile(source,filename,'exec'),{'__file__':filename,'__name__':'__main__'})") | ||
| 155 | + previous = subprocess.run([sys.executable, '-I', '-S', '-B', '-c', bootstrap, str(legacy), | ||
| 156 | + str(COUNTER), '--support', str(support)], capture_output=True, text=True, check=True, timeout=120) | ||
| 157 | + old = json.loads(previous.stdout)['additional_support'] | ||
| 158 | + self.assertEqual(set(old), {str(support/'short.py')}, 'legacy long-path omission must reproduce on this Windows host') | ||
| 159 | + current = subprocess.run([sys.executable, '-I', '-S', '-B', str(COUNTER), '--support', str(support), | ||
| 160 | + '--support', str(deep), '--support', str(support/'short.py'), '--support', str(COUNTER)], | ||
| 161 | + capture_output=True, text=True, check=True, timeout=120) | ||
| 162 | + result = json.loads(current.stdout) | ||
| 163 | + self.assertEqual(result['additional_support'], expected) | ||
| 164 | + self.assertIsNone(result['additional_support_lines']) | ||
| 165 | + self.assertTrue(all(not path.startswith('\\\\?\\') for path in result['additional_support'])) | ||
| 166 | + print(json.dumps(dict(scope='ACTUAL_WINDOWS_LONGPATH_FIXTURE_ONLY_NOT_BROAD_REPO_BUDGET', | ||
| 167 | + expected_files=len(expected), legacy_files=len(old), fixed_files=len(result['additional_support']), | ||
| 168 | + absolute_lengths=[len(str(path)) for path in payloads], bytes_and_sha_and_lines='EXACT', | ||
| 169 | + binary_total='UNKNOWN_PRESERVED'), sort_keys=True)) | ||
| 170 | + | ||
| 171 | + | ||
| 172 | +if __name__ == '__main__': | ||
| 173 | + unittest.main(verbosity=2) | ||
| @@ -0,0 +1,407 @@ | |||
| 1 | +"""Pure CPU wrapper contracts and static native-source checks, not native math. | ||
| 2 | + | ||
| 3 | +The original GMM unit imports torch_npu and creates a real device backend at | ||
| 4 | +collection. This small fixture loads the actual wrapper with inert builders | ||
| 5 | +and no dispatcher registration, so it can run under the explicit host guard. | ||
| 6 | +""" | ||
| 7 | +import importlib.util | ||
| 8 | +import hashlib | ||
| 9 | +import json | ||
| 10 | +from pathlib import Path | ||
| 11 | +import sys | ||
| 12 | +from types import ModuleType, SimpleNamespace | ||
| 13 | + | ||
| 14 | +import pytest | ||
| 15 | +import torch | ||
| 16 | + | ||
| 17 | + | ||
| 18 | +ROOT = Path(__file__).resolve().parents[2] | ||
| 19 | + | ||
| 20 | + | ||
| 21 | +@pytest.fixture | ||
| 22 | +def wrapper(monkeypatch): | ||
| 23 | + builders = ModuleType('mindspeed.op_builder') | ||
| 24 | + builders.GMMOpBuilder = builders.GMMV2OpBuilder = lambda: SimpleNamespace(load=lambda: None) | ||
| 25 | + common = ModuleType('mindspeed.op_builder.builder') | ||
| 26 | + common.AS_LIBRARY = object() | ||
| 27 | + old_add = ModuleType('mindspeed.ops.npu_groupmatmul_add') | ||
| 28 | + old_add.npu_groupmatmul_add_fp32 = lambda *args: pytest.fail('unrelated old wrapper invoked') | ||
| 29 | + for name, module in ((builders.__name__, builders), (common.__name__, common), (old_add.__name__, old_add)): | ||
| 30 | + monkeypatch.setitem(sys.modules, name, module) | ||
| 31 | + monkeypatch.setattr(torch.library, 'impl', lambda *args: lambda function: function) | ||
| 32 | + spec = importlib.util.spec_from_file_location('minimal_gmm_wrapper', ROOT/'mindspeed/ops/gmm.py') | ||
| 33 | + result = importlib.util.module_from_spec(spec) | ||
| 34 | + spec.loader.exec_module(result) | ||
| 35 | + return result | ||
| 36 | + | ||
| 37 | + | ||
| 38 | +def values(): | ||
| 39 | + return (torch.zeros(3, 4, dtype=torch.bfloat16), | ||
| 40 | + torch.zeros(3, 2, dtype=torch.bfloat16), | ||
| 41 | + torch.zeros(2, 4, 2), torch.tensor([2, 3], dtype=torch.int64)) | ||
| 42 | + | ||
| 43 | + | ||
| 44 | +def test_add_actual_wrapper_preserves_four_arg_identity_and_raw_version(wrapper, monkeypatch): | ||
| 45 | + dy, x, scratch, prefix = values() | ||
| 46 | + seen = [] | ||
| 47 | + def call(*args): | ||
| 48 | + seen.append(args) | ||
| 49 | + return scratch | ||
| 50 | + monkeypatch.setattr(wrapper, '_standard_binding', lambda: SimpleNamespace(npu_grouped_matmul_add_fp32_out=call)) | ||
| 51 | + before = scratch._version | ||
| 52 | + assert wrapper.npu_grouped_matmul_add_fp32_out(dy, x, scratch, prefix) is scratch | ||
| 53 | + assert all(actual is expected for actual, expected in zip(seen[0], (dy, x, scratch, prefix))) | ||
| 54 | + assert scratch._version == before + 1 | ||
| 55 | + | ||
| 56 | + | ||
| 57 | +@pytest.mark.parametrize('fault', ['dtype', 'shape', 'prefix', 'stride', 'grad', 'negative']) | ||
| 58 | +def test_add_invalid_metadata_never_calls_binding(wrapper, monkeypatch, fault): | ||
| 59 | + dy, x, scratch, prefix = values() | ||
| 60 | + if fault == 'dtype': dy = dy.float() | ||
| 61 | + elif fault == 'shape': scratch = scratch[:, :3] | ||
| 62 | + elif fault == 'prefix': prefix = prefix.int() | ||
| 63 | + elif fault == 'stride': x = torch.zeros(2, 3, dtype=torch.bfloat16).t() | ||
| 64 | + elif fault == 'grad': x.requires_grad_(True) | ||
| 65 | + elif fault == 'negative': x = torch._neg_view(x) | ||
| 66 | + monkeypatch.setattr(wrapper, '_standard_binding', lambda: pytest.fail('invalid metadata reached loader')) | ||
| 67 | + with pytest.raises((TypeError, ValueError, RuntimeError)): | ||
| 68 | + wrapper.npu_grouped_matmul_add_fp32_out(dy, x, scratch, prefix) | ||
| 69 | + | ||
| 70 | + | ||
| 71 | +def test_add_return_copy_rejected_without_version_handoff(wrapper, monkeypatch): | ||
| 72 | + dy, x, scratch, prefix = values() | ||
| 73 | + monkeypatch.setattr(wrapper, '_standard_binding', lambda: SimpleNamespace( | ||
| 74 | + npu_grouped_matmul_add_fp32_out=lambda *args: scratch.clone())) | ||
| 75 | + before = scratch._version | ||
| 76 | + with pytest.raises(RuntimeError, match='output identity'): | ||
| 77 | + wrapper.npu_grouped_matmul_add_fp32_out(dy, x, scratch, prefix) | ||
| 78 | + assert scratch._version == before | ||
| 79 | + | ||
| 80 | + | ||
| 81 | +def test_v5_actual_wrapper_keeps_zero_copy_transpose_ref(wrapper, monkeypatch): | ||
| 82 | + x = torch.zeros(3, 2, dtype=torch.bfloat16) | ||
| 83 | + weight = torch.zeros(4, 2, dtype=torch.bfloat16).t() | ||
| 84 | + out = torch.empty(3, 4, dtype=torch.bfloat16) | ||
| 85 | + counts = torch.tensor([3]) | ||
| 86 | + def call(actual_x, refs, actual_out, actual_counts): | ||
| 87 | + assert actual_x is x and refs[0] is weight and actual_out is out and actual_counts is counts | ||
| 88 | + return out | ||
| 89 | + monkeypatch.setattr(wrapper, '_standard_binding', lambda: SimpleNamespace(npu_gmm_v5_out=call)) | ||
| 90 | + before = out._version | ||
| 91 | + assert wrapper.npu_gmm_v5_out(x, [weight], out, counts) is out | ||
| 92 | + assert out._version == before + 1 | ||
| 93 | + | ||
| 94 | + | ||
| 95 | +def test_standard_selector_explicit_files_immutable_and_no_builder_on_error(wrapper, tmp_path, monkeypatch): | ||
| 96 | + main = tmp_path/'libopapi.so' | ||
| 97 | + main.write_bytes(b'inert host file, never loaded') | ||
| 98 | + monkeypatch.setenv('MINDSPEED_MOONEP_OPAPI', str(main)) | ||
| 99 | + monkeypatch.setenv('MINDSPEED_MOONEP_OPAPI_DEPENDENCIES', '') | ||
| 100 | + binding = object() | ||
| 101 | + monkeypatch.setattr(wrapper.GMMFunction.builder2, 'load', lambda: binding) | ||
| 102 | + assert wrapper._standard_binding() is binding | ||
| 103 | + other = tmp_path/'other' | ||
| 104 | + other.mkdir() | ||
| 105 | + (other/'libopapi.so').write_bytes(b'other inert selected file') | ||
| 106 | + monkeypatch.setenv('MINDSPEED_MOONEP_OPAPI', str(other/'libopapi.so')) | ||
| 107 | + with pytest.raises(RuntimeError, match='selection changed'): | ||
| 108 | + wrapper._standard_binding() | ||
| 109 | + | ||
| 110 | + | ||
| 111 | +@pytest.mark.parametrize('entry', ['', 'libopapi.so', 'libcust_opapi.so', 'missing/libopapi.so']) | ||
| 112 | +def test_selector_invalid_path_rejects_before_builder(wrapper, tmp_path, monkeypatch, entry): | ||
| 113 | + path = tmp_path/entry if entry.startswith('libcust') else Path(entry) | ||
| 114 | + if entry.startswith('libcust'): path.write_bytes(b'not loaded') | ||
| 115 | + monkeypatch.setenv('MINDSPEED_MOONEP_OPAPI', str(path) if entry else '') | ||
| 116 | + monkeypatch.delenv('MINDSPEED_MOONEP_OPAPI_DEPENDENCIES', raising=False) | ||
| 117 | + with pytest.raises(RuntimeError): | ||
| 118 | + wrapper._standard_binding() | ||
| 119 | + | ||
| 120 | + | ||
| 121 | +def test_selector_warm_call_uses_frozen_module_without_filesystem(wrapper, tmp_path, monkeypatch): | ||
| 122 | + main = tmp_path/'libopapi.so' | ||
| 123 | + main.write_bytes(b'inert host selection, never loaded') | ||
| 124 | + monkeypatch.setenv('MINDSPEED_MOONEP_OPAPI', str(main)) | ||
| 125 | + monkeypatch.setenv('MINDSPEED_MOONEP_OPAPI_DEPENDENCIES', '') | ||
| 126 | + binding, loads = object(), [] | ||
| 127 | + monkeypatch.setattr(wrapper.GMMFunction.builder2, 'load', lambda: loads.append('load') or binding) | ||
| 128 | + assert wrapper._standard_binding() is binding | ||
| 129 | + for method in ('is_absolute', 'is_file', 'resolve'): | ||
| 130 | + monkeypatch.setattr(Path, method, lambda *args, **kwargs: pytest.fail('warm filesystem query')) | ||
| 131 | + for _ in range(8): | ||
| 132 | + assert wrapper._standard_binding() is binding | ||
| 133 | + assert loads == ['load'] | ||
| 134 | + # A changed raw path or dependency string is rejected before any lookup. | ||
| 135 | + for key, value in (('MINDSPEED_MOONEP_OPAPI', str(main)+'/alias'), | ||
| 136 | + ('MINDSPEED_MOONEP_OPAPI_DEPENDENCIES', '/changed/dependency.so')): | ||
| 137 | + with monkeypatch.context() as changed: | ||
| 138 | + changed.setenv(key, value) | ||
| 139 | + with pytest.raises(RuntimeError, match='selection changed'): | ||
| 140 | + wrapper._standard_binding() | ||
| 141 | + | ||
| 142 | + | ||
| 143 | +@pytest.mark.parametrize('error', ['missing standard symbol', 'wrong symbol provider', 'inert load failed']) | ||
| 144 | +def test_selector_failed_cold_load_never_publishes_cache(wrapper, tmp_path, monkeypatch, error): | ||
| 145 | + main = tmp_path/'libopapi.so' | ||
| 146 | + main.write_bytes(b'inert host selection, never loaded') | ||
| 147 | + monkeypatch.setenv('MINDSPEED_MOONEP_OPAPI', str(main)) | ||
| 148 | + monkeypatch.setenv('MINDSPEED_MOONEP_OPAPI_DEPENDENCIES', '') | ||
| 149 | + loads = [] | ||
| 150 | + def reject(): | ||
| 151 | + loads.append('load') | ||
| 152 | + raise RuntimeError(error) | ||
| 153 | + monkeypatch.setattr(wrapper.GMMFunction.builder2, 'load', reject) | ||
| 154 | + with pytest.raises(RuntimeError, match=error): | ||
| 155 | + wrapper._standard_binding() | ||
| 156 | + assert loads == ['load'] | ||
| 157 | + assert wrapper._standard_selection is None and wrapper._standard_module is None | ||
| 158 | + | ||
| 159 | + | ||
| 160 | +@pytest.mark.parametrize('key', ['MINDSPEED_MOONEP_OPAPI', 'MINDSPEED_MOONEP_OPAPI_DEPENDENCIES']) | ||
| 161 | +def test_selector_environment_changed_during_load_never_publishes(wrapper, tmp_path, monkeypatch, key): | ||
| 162 | + main = tmp_path/'libopapi.so' | ||
| 163 | + main.write_bytes(b'inert host selection, never loaded') | ||
| 164 | + monkeypatch.setenv('MINDSPEED_MOONEP_OPAPI', str(main)) | ||
| 165 | + monkeypatch.setenv('MINDSPEED_MOONEP_OPAPI_DEPENDENCIES', '') | ||
| 166 | + def load(): | ||
| 167 | + monkeypatch.setenv(key, 'changed during cold load') | ||
| 168 | + return object() | ||
| 169 | + monkeypatch.setattr(wrapper.GMMFunction.builder2, 'load', load) | ||
| 170 | + with pytest.raises(RuntimeError, match='selection changed'): | ||
| 171 | + wrapper._standard_binding() | ||
| 172 | + assert wrapper._standard_selection is None and wrapper._standard_module is None | ||
| 173 | + | ||
| 174 | + | ||
| 175 | +def test_selector_concurrent_first_calls_publish_one_complete_module(wrapper, tmp_path, monkeypatch): | ||
| 176 | + from concurrent.futures import ThreadPoolExecutor | ||
| 177 | + from threading import Event | ||
| 178 | + | ||
| 179 | + main = tmp_path/'libopapi.so' | ||
| 180 | + main.write_bytes(b'inert host selection, never loaded') | ||
| 181 | + monkeypatch.setenv('MINDSPEED_MOONEP_OPAPI', str(main)) | ||
| 182 | + monkeypatch.setenv('MINDSPEED_MOONEP_OPAPI_DEPENDENCIES', '') | ||
| 183 | + entered, release, second_started = Event(), Event(), Event() | ||
| 184 | + binding, loads = object(), [] | ||
| 185 | + def load(): | ||
| 186 | + loads.append('load') | ||
| 187 | + entered.set() | ||
| 188 | + assert release.wait(5), 'test did not release inert loader' | ||
| 189 | + return binding | ||
| 190 | + def second(): | ||
| 191 | + second_started.set() | ||
| 192 | + return wrapper._standard_binding() | ||
| 193 | + monkeypatch.setattr(wrapper.GMMFunction.builder2, 'load', load) | ||
| 194 | + with ThreadPoolExecutor(max_workers=2) as pool: | ||
| 195 | + first = pool.submit(wrapper._standard_binding) | ||
| 196 | + try: | ||
| 197 | + assert entered.wait(5) | ||
| 198 | + assert wrapper._standard_selection is None and wrapper._standard_module is None | ||
| 199 | + other = pool.submit(second) | ||
| 200 | + assert second_started.wait(5) | ||
| 201 | + finally: | ||
| 202 | + release.set() | ||
| 203 | + assert first.result(timeout=5) is binding | ||
| 204 | + assert other.result(timeout=5) is binding | ||
| 205 | + assert loads == ['load'] | ||
| 206 | + | ||
| 207 | + | ||
| 208 | +def test_selector_warm_cache_does_not_skip_operand_guards(wrapper, tmp_path, monkeypatch): | ||
| 209 | + main = tmp_path/'libopapi.so' | ||
| 210 | + main.write_bytes(b'inert host selection, never loaded') | ||
| 211 | + monkeypatch.setenv('MINDSPEED_MOONEP_OPAPI', str(main)) | ||
| 212 | + monkeypatch.setenv('MINDSPEED_MOONEP_OPAPI_DEPENDENCIES', '') | ||
| 213 | + binding = SimpleNamespace(npu_gmm_v5_out=lambda *args: pytest.fail('invalid operand reached native')) | ||
| 214 | + monkeypatch.setattr(wrapper.GMMFunction.builder2, 'load', lambda: binding) | ||
| 215 | + assert wrapper._standard_binding() is binding | ||
| 216 | + x = torch.zeros(3, 2, dtype=torch.bfloat16) | ||
| 217 | + out = torch.empty(3, 4, dtype=torch.bfloat16) | ||
| 218 | + with pytest.raises(ValueError, match='weight refs must match'): | ||
| 219 | + wrapper.npu_gmm_v5_out(x, [torch.zeros(2, 5, dtype=torch.bfloat16)], out, | ||
| 220 | + torch.tensor([3], dtype=torch.int64)) | ||
| 221 | + | ||
| 222 | + | ||
| 223 | +def test_native_source_retains_owner_and_uses_only_standard_phase_pair(): | ||
| 224 | + source = (ROOT/'mindspeed/ops/csrc/cann/gmm.cpp').read_text() | ||
| 225 | + moon = source[source.index('namespace moonep_standard'):] | ||
| 226 | + assert 'aclnnPointerGroupedMatmulAdd' not in source | ||
| 227 | + assert 'ACLNN_CMD(' not in moon | ||
| 228 | + assert 'current.stream()' in moon and 'current.stream(false)' not in moon | ||
| 229 | + assert moon.index('current.synchronize(); // checked completion') < moon.index('call->release();') | ||
| 230 | + assert 'retained = call' in moon and 'process restart required' in moon | ||
| 231 | + assert 'ACL_FORMAT_ND' in moon and 'ACL_FORMAT_NCL' not in moon | ||
| 232 | + assert 'true, false, 2, 0, &bytes' in moon | ||
| 233 | + assert 'groups, nullptr, nullptr, nullptr, 3, 0, 1, 0' in moon | ||
| 234 | + assert 'descriptors.resize(descriptors.size() - items.size())' in moon | ||
| 235 | + assert 'TORCH_CHECK(call->executor' in moon | ||
| 236 | + assert '!value.is_neg() && !value.is_conj()' in moon | ||
| 237 | + | ||
| 238 | + | ||
| 239 | +def test_python_source_compiles_without_importing_native(): | ||
| 240 | + package = ROOT/'mindspeed/core/transformer/moe/moonep' | ||
| 241 | + modules = {'moonep.py', 'moonep_contract.py', 'moonep_executor.py', | ||
| 242 | + 'moonep_runtime.py', 'virtual_expert_load_balancer.py'} | ||
| 243 | + assert {path.name for path in package.glob('*.py')} == modules | {'__init__.py'} | ||
| 244 | + for name in modules | {'__init__.py'}: | ||
| 245 | + path = package/name | ||
| 246 | + compile(path.read_bytes(), str(path), 'exec') | ||
| 247 | + compile((ROOT/'mindspeed/ops/gmm.py').read_bytes(), 'gmm.py', 'exec') | ||
| 248 | + | ||
| 249 | + | ||
| 250 | +@pytest.fixture | ||
| 251 | +def probe(monkeypatch, tmp_path): | ||
| 252 | + artifact = tmp_path/'inert.so' | ||
| 253 | + artifact.write_bytes(b'host fixture only, never loaded') | ||
| 254 | + native = SimpleNamespace(__file__=str(artifact), moonep_standard_backend_info=lambda: {'symbol': str(artifact)}) | ||
| 255 | + gmm = ModuleType('mindspeed.ops.gmm') | ||
| 256 | + gmm.__file__ = str(artifact) | ||
| 257 | + gmm._standard_binding = lambda: native | ||
| 258 | + gmm.npu_gmm_v5_out = gmm.npu_grouped_matmul_add_fp32_out = lambda *args: pytest.fail('math executed') | ||
| 259 | + npu = ModuleType('torch_npu') | ||
| 260 | + npu.__version__ = 'INERT_HOST_FIXTURE' | ||
| 261 | + monkeypatch.setitem(sys.modules, gmm.__name__, gmm) | ||
| 262 | + monkeypatch.setitem(sys.modules, npu.__name__, npu) | ||
| 263 | + monkeypatch.setitem(sys.modules, 'torch_npu._C', SimpleNamespace(__file__=str(artifact))) | ||
| 264 | + path = ROOT/'tests_extend/system_tests/moonep/validate_lplusb_gmm_contract.py' | ||
| 265 | + spec = importlib.util.spec_from_file_location('inert_build_probe', path) | ||
| 266 | + result = importlib.util.module_from_spec(spec) | ||
| 267 | + spec.loader.exec_module(result) | ||
| 268 | + return result | ||
| 269 | + | ||
| 270 | + | ||
| 271 | +def test_existing_probe_build_only_exits_before_device_or_math(probe, monkeypatch, capsys): | ||
| 272 | + facts = dict(scope='INERT_IDENTITY_FACTS_ONLY') | ||
| 273 | + seen = [] | ||
| 274 | + monkeypatch.setattr(probe, '_backend_facts', lambda args: seen.append('identity') or facts) | ||
| 275 | + monkeypatch.setattr(torch, 'npu', SimpleNamespace(set_device=lambda *args: pytest.fail('device selected')), raising=False) | ||
| 276 | + monkeypatch.setattr(torch, 'randn', lambda *args, **kwargs: pytest.fail('tensor created')) | ||
| 277 | + monkeypatch.setattr(sys, 'argv', ['validate_lplusb_gmm_contract.py', '--build-only']) | ||
| 278 | + probe.main() | ||
| 279 | + first, last = [json.loads(line) for line in capsys.readouterr().out.splitlines()] | ||
| 280 | + assert seen == ['identity', 'identity'] | ||
| 281 | + assert first['scope'] == last['scope'] == 'S0_BUILD_LOAD_SYMBOLS_ONLY' | ||
| 282 | + assert last['backend_stable'] and last['training_qualifying'] is False | ||
| 283 | + assert last['tensors'] == 'NOT_CREATED' and last['math'] == 'NOT_RUN' | ||
| 284 | + | ||
| 285 | + | ||
| 286 | +@pytest.mark.parametrize('bad', [float('nan'), float('inf'), -float('inf')]) | ||
| 287 | +def test_later_group_nonfinite_cannot_hide_behind_python_reductions(probe, bad): | ||
| 288 | + metrics = [(0., 0., 1.), (bad, bad, bad)] | ||
| 289 | + assert not probe._finite_metrics(metrics) | ||
| 290 | + # A later NaN really can be ignored by the old max/min expressions. | ||
| 291 | + if bad != bad: | ||
| 292 | + assert max(item[1] for item in metrics) == 0. | ||
| 293 | + assert min(item[2] for item in metrics) == 1. | ||
| 294 | + | ||
| 295 | + | ||
| 296 | +def test_actual_full_g_probe_rejects_later_nan_group(probe, monkeypatch, capsys): | ||
| 297 | + class CPUFixture: | ||
| 298 | + npu = SimpleNamespace(synchronize=lambda: None, memory_allocated=lambda: 0) | ||
| 299 | + def __getattr__(self, name): | ||
| 300 | + original = getattr(torch, name) | ||
| 301 | + if name in ('randn', 'tensor', 'empty', 'full'): | ||
| 302 | + def allocate(*args, **kwargs): | ||
| 303 | + kwargs['device'] = 'cpu' | ||
| 304 | + return original(*args, **kwargs) | ||
| 305 | + return allocate | ||
| 306 | + return original | ||
| 307 | + def producer(dy, x, scratch, prefix): | ||
| 308 | + begin = 0 | ||
| 309 | + for index, end in enumerate(prefix.tolist()): | ||
| 310 | + scratch[index].add_(dy[begin:end].float().t() @ x[begin:end].float()) | ||
| 311 | + begin = end | ||
| 312 | + scratch[2].fill_(float('nan')) # first active group remains finite | ||
| 313 | + return scratch | ||
| 314 | + monkeypatch.setattr(probe, 'torch', CPUFixture()) | ||
| 315 | + monkeypatch.setattr(probe, 'npu_grouped_matmul_add_fp32_out', producer) | ||
| 316 | + assert not probe.full_g_wgrad_probe([2, 0, 3], 4, 8) | ||
| 317 | + assert 'NONFINITE_GROUP_METRICS' in capsys.readouterr().out | ||
| 318 | + | ||
| 319 | + | ||
| 320 | +def test_backend_identity_reads_actual_files_and_does_not_qualify(probe, monkeypatch, tmp_path): | ||
| 321 | + main = tmp_path/'sdk/lib64/libopapi.so' | ||
| 322 | + main.parent.mkdir(parents=True) | ||
| 323 | + main.write_bytes(b'inert standard path') | ||
| 324 | + headers = tmp_path/'sdk/include/aclnnop' | ||
| 325 | + headers.mkdir(parents=True) | ||
| 326 | + for name in ('aclnn_grouped_matmul_v5.h', 'aclnn_grouped_matmul_add_v2.h'): | ||
| 327 | + (headers/name).write_bytes(b'inert header') | ||
| 328 | + monkeypatch.setenv('MINDSPEED_MOONEP_OPAPI', str(main)) | ||
| 329 | + monkeypatch.setattr(probe, '_selected_maps', lambda required: [probe._file_fact(path) for path in sorted(required)]) | ||
| 330 | + facts = probe._backend_facts(SimpleNamespace(v5_header=None, addv2_header=None)) | ||
| 331 | + assert facts['headers']['v5']['sha256'] == hashlib.sha256(b'inert header').hexdigest() | ||
| 332 | + assert facts['source_mapping'] == 'UNKNOWN' | ||
| 333 | + assert facts['mapping_evidence'] == 'PATH_HASH_ONLY_NOT_MAPPING_FD_PROOF' | ||
| 334 | + assert set(facts['modules']) == {'compute', 'torch_C', 'npu_C'} | ||
| 335 | + assert len(facts['selected_maps']) == 2 # CPU _C and one shared inert file | ||
| 336 | + | ||
| 337 | + | ||
| 338 | +def test_selected_maps_facts_contain_no_ranges_and_reject_missing_or_deleted(probe, tmp_path): | ||
| 339 | + paths = [tmp_path/name for name in ('libtorch_npu.so', 'libascendcl.so', 'libopapi.so', 'libnnopbase.so', 'module.so')] | ||
| 340 | + for path in paths: path.write_bytes(path.name.encode()) | ||
| 341 | + maps = tmp_path/'maps' | ||
| 342 | + lines = ['1000-2000 r-xp 0 00:00 1 '+str(path) for path in paths] | ||
| 343 | + maps.write_text('\n'.join(lines)+ '\n1000-2000 r-xp 0 00:00 1 /missing/unrelated.so') | ||
| 344 | + facts = probe._selected_maps({str(paths[-1])}, maps) | ||
| 345 | + assert len(facts) == 5 and all(set(fact) == {'path', 'sha256', 'file_stat_device', 'file_stat_inode', 'map_backings'} for fact in facts) | ||
| 346 | + assert all(fact['map_backings'] == [dict(device='00:00', inode=1)] for fact in facts) | ||
| 347 | + maps.write_text('\n'.join(lines[1:])) | ||
| 348 | + with pytest.raises(RuntimeError, match='mappings missing'): | ||
| 349 | + probe._selected_maps({str(paths[-1])}, maps) | ||
| 350 | + maps.write_text('\n'.join(lines[:-1]+[lines[-1]+' (deleted)'])) | ||
| 351 | + with pytest.raises(RuntimeError, match='image was deleted'): | ||
| 352 | + probe._selected_maps({str(paths[-1])}, maps) | ||
| 353 | + | ||
| 354 | + | ||
| 355 | +@pytest.mark.parametrize('transpose', [True, False]) | ||
| 356 | +def test_v5_probe_checks_offset_canaries_and_actual_refs(probe, monkeypatch, transpose): | ||
| 357 | + def oracle(x, refs, out, counts): | ||
| 358 | + assert x.storage_offset() == out.storage_offset() == 128 | ||
| 359 | + assert all(ref.storage_offset() == 128 for ref in refs) | ||
| 360 | + assert all(ref.is_contiguous() != transpose for ref in refs) | ||
| 361 | + begin = 0 | ||
| 362 | + for rows, ref in zip(counts.tolist(), refs): | ||
| 363 | + out[begin:begin+rows].copy_((x[begin:begin+rows].float() @ ref.float()).bfloat16()) | ||
| 364 | + begin += rows | ||
| 365 | + return out | ||
| 366 | + monkeypatch.setattr(probe, 'npu_gmm_v5_out', oracle) | ||
| 367 | + assert probe.v5_out_probe([2, 0, 3], 4, 8, transpose=transpose, device='cpu') | ||
| 368 | + def corrupt(x, refs, out, counts): | ||
| 369 | + oracle(x, refs, out, counts) | ||
| 370 | + out._base[0] = 0 | ||
| 371 | + return out | ||
| 372 | + monkeypatch.setattr(probe, 'npu_gmm_v5_out', corrupt) | ||
| 373 | + assert not probe.v5_out_probe([2, 0, 3], 4, 8, transpose=transpose, device='cpu') | ||
| 374 | + def mutate_input(x, refs, out, counts): | ||
| 375 | + x.fill_(1) | ||
| 376 | + return oracle(x, refs, out, counts) | ||
| 377 | + monkeypatch.setattr(probe, 'npu_gmm_v5_out', mutate_input) | ||
| 378 | + assert not probe.v5_out_probe([2, 0, 3], 4, 8, transpose=transpose, device='cpu') | ||
| 379 | + def mutate_unused_weight(x, refs, out, counts): | ||
| 380 | + refs[1].fill_(3) # zero-token group's math cannot reveal this write | ||
| 381 | + return oracle(x, refs, out, counts) | ||
| 382 | + monkeypatch.setattr(probe, 'npu_gmm_v5_out', mutate_unused_weight) | ||
| 383 | + assert not probe.v5_out_probe([2, 0, 3], 4, 8, transpose=transpose, device='cpu') | ||
| 384 | + | ||
| 385 | + | ||
| 386 | +def test_moonep_package_keeps_one_runtime_and_no_eager_imports(): | ||
| 387 | + import ast | ||
| 388 | + import importlib | ||
| 389 | + import sys | ||
| 390 | + | ||
| 391 | + prefix = 'mindspeed.core.transformer.moe.moonep' | ||
| 392 | + package = importlib.import_module(prefix) | ||
| 393 | + body = ast.parse(Path(package.__file__).read_bytes()).body | ||
| 394 | + assert len(body) == 1 and isinstance(body[0], ast.Expr) | ||
| 395 | + assert isinstance(body[0].value, ast.Constant) and isinstance(body[0].value.value, str) | ||
| 396 | + runtime = importlib.import_module(prefix+'.moonep_runtime') | ||
| 397 | + executor = importlib.import_module(prefix+'.moonep_executor') | ||
| 398 | + experts = importlib.import_module(prefix+'.virtual_expert_load_balancer') | ||
| 399 | + assert executor._VirtualExperts is experts._VirtualExperts | ||
| 400 | + assert sys.modules[prefix+'.moonep_runtime'] is runtime | ||
| 401 | + for name in ('moonep_contract', 'moonep_executor', 'moonep_runtime', | ||
| 402 | + 'virtual_expert_load_balancer'): | ||
| 403 | + assert 'mindspeed.core.transformer.moe.'+name not in sys.modules | ||
| 404 | + assert not (Path(package.__file__).parent.parent/(name+'.py')).exists() | ||
| 405 | + aliases = [module for module in list(sys.modules.values()) | ||
| 406 | + if isinstance(module, ModuleType) and vars(module).get('__file__') == runtime.__file__] | ||
| 407 | + assert len(aliases) == 1 | ||