Closed
[WIP] feat(npu): add prepared L+B bindings and async communication APIs #19
&NewgateAdd on 23 days agoClosed at 23 days ago
[WIP] feat(npu): add prepared L+B bindings and async communication APIs #19
Closed
&NewgateAdd on 23 days agoClosed at 23 days ago
Total: 46 files changed+3919-159
@@ -260,6 +260,11 @@ ShmemRuntime.finalize()
260buffer.destroy()260buffer.destroy()
261```261```
262 262 
263+`planning_num_sms` 可独立设置主 Planning(含融合的 Combine plan 生成)的 AIV 核数,
264+范围为 8~56,未指定时使用 `num_sms`;Planning 工作区按同一核数预分配。例如
265+`Buffer(..., num_sms=32, planning_num_sms=8, grad_reduce_num_sms=16)`。
266+独立 `prepare_combine_plan()` 的准备 kernel 仍沿用 64 核。
267+ 
263### ubmem(MTE)与 urma(URMA/UDMA)路径:初始化与调用268### ubmem(MTE)与 urma(URMA/UDMA)路径:初始化与调用
264 269 
265planning / dispatch / combine / prefetch / reduce_grad 各有两条 kernel 路径,270planning / dispatch / combine / prefetch / reduce_grad 各有两条 kernel 路径,
@@ -132,9 +132,12 @@ def _load_buffer_api():
132 from .shmem_runtime import ShmemRuntime, runtime_library_info132 from .shmem_runtime import ShmemRuntime, runtime_library_info
133 from .planning import MoonEPCommPlan133 from .planning import MoonEPCommPlan
134 from .api import Buffer134 from .api import Buffer
135+ from .native_async import CommBuffers, LPlusBBinding
135 136 
136 return {137 return {
137 "Buffer": Buffer,138 "Buffer": Buffer,
139+ "CommBuffers": CommBuffers,
140+ "LPlusBBinding": LPlusBBinding,
138 "MoonEPCommPlan": MoonEPCommPlan,141 "MoonEPCommPlan": MoonEPCommPlan,
139 "ShmemRuntime": ShmemRuntime,142 "ShmemRuntime": ShmemRuntime,
140 "runtime_library_info": runtime_library_info,143 "runtime_library_info": runtime_library_info,
@@ -142,7 +145,7 @@ def _load_buffer_api():
142 145 
143 146 
144_BUFFER_API_NAMES = frozenset({147_BUFFER_API_NAMES = frozenset({
145- "Buffer", "MoonEPCommPlan", "ShmemRuntime", "runtime_library_info"148+ "Buffer", "CommBuffers", "LPlusBBinding", "MoonEPCommPlan", "ShmemRuntime", "runtime_library_info"
146})149})
147_BUF_API_CACHE = None150_BUF_API_CACHE = None
148 151 
@@ -156,16 +159,20 @@ def __getattr__(name):
156 raise AttributeError(f"module 'npu_patch' has no attribute {name!r}")159 raise AttributeError(f"module 'npu_patch' has no attribute {name!r}")
157 160 
158 161 
159-from .launchers import launch_grad_reduce, launch_prefetch162+from .launchers import launch_grad_reduce, launch_grad_reduce_targets, launch_prefetch, launch_prefetch_push
160 163 
161__all__ = [164__all__ = [
162 "ShmemInstance",165 "ShmemInstance",
163 "GradReduce",166 "GradReduce",
164 "launch_grad_reduce",167 "launch_grad_reduce",
168+ "launch_grad_reduce_targets",
165 "Buffer",169 "Buffer",
170+ "CommBuffers",
171+ "LPlusBBinding",
166 "MoonEPCommPlan",172 "MoonEPCommPlan",
167 "ShmemRuntime",173 "ShmemRuntime",
168 "runtime_library_info",174 "runtime_library_info",
169 "PrefetchWeight",175 "PrefetchWeight",
170 "launch_prefetch",176 "launch_prefetch",
177+ "launch_prefetch_push",
171]178]
@@ -0,0 +1,54 @@
1+{
2+ "schema": 2,
3+ "provider_abi": "lplusb-buffer-v3",
4+ "devices": [
5+ "Ascend 950DT",
6+ "Ascend 950PR"
7+ ],
8+ "activation_dtypes": [
9+ "bfloat16"
10+ ],
11+ "weight_dtypes": [
12+ "bfloat16"
13+ ],
14+ "gradient_target_dtypes": [
15+ "float32"
16+ ],
17+ "layout": "LOCAL_L_PLUS_B",
18+ "ordinary_source_owner_push": true,
19+ "direct_owner_reduce": true,
20+ "explicit_comm_buffers": true,
21+ "completion_model": {
22+ "synchronous": "current_stream",
23+ "asynchronous": "comm_stream_event"
24+ },
25+ "vmm_granularity_query": true,
26+ "router_topk_max": null,
27+ "native_abis": {
28+ "LPLUS_B_BUFFER_SYNC_ABI": 2,
29+ "GRAD_REDUCE_POINTER_ABI": 1,
30+ "GRAD_REDUCE_POINTER_UDMA_ABI": 3,
31+ "PREFETCH_PUSH_POINTER_ABI": 1
32+ },
33+ "async": {
34+ "schema": 1,
35+ "completion_modes": [
36+ "collective"
37+ ],
38+ "lane_count": 1,
39+ "strict_zero_copy": true
40+ },
41+ "prefetch_engines": [
42+ "mte",
43+ "urma"
44+ ],
45+ "urma_push": {
46+ "schema": 1,
47+ "pointer_source": true,
48+ "native_abi": 1,
49+ "completion_modes": [
50+ "collective"
51+ ],
52+ "shared_core_sha256": "26e966899f19fe199148b73c00920c126da7a64f2aff3eb1ea20283340cd84b2"
53+ }
54+}
@@ -0,0 +1,354 @@
1+"""Prepared L+B benchmarks; imports Ascend dependencies only for a live run."""
2+import argparse
3+from datetime import timedelta
4+import hashlib
5+import json
6+import math
7+import os
8+import socket
9+from pathlib import Path
10+import statistics
11+import subprocess
12+import sys
13+import time
14+ 
15+ 
16+# Keep native resources alive on failure; successful runs explicitly drain/free.
17+_ACTIVE_RESOURCES = []
18+ 
19+ 
20+def parse_args(operation, argv=None):
21+ parser = argparse.ArgumentParser(description=(
22+ "Time Buffer.prefetch_lplusb pointer PUSH" if operation == "prefetch" else
23+ "Time Buffer.reduce_grad(lplusb=...) / GradReduceTargets"))
24+ parser.add_argument("--engine", choices=("ubmem", "urma"), default="urma")
25+ parser.add_argument("--mode", choices=("sync", "async"), default="async")
26+ parser.add_argument("--shmem-udma", choices=("on", "off"), default="on",
27+ help="keep SHMEM initialization identical across MTE/URMA arms (A5)")
28+ parser.add_argument("--barrier-mode", choices=("mixed", "aiv"))
29+ parser.add_argument("--epn", type=int, default=2, help="ordinary home tensors per rank")
30+ parser.add_argument("--B", type=int, help="symmetric slots; default: epn; targets requires B=epn")
31+ parser.add_argument("--H", type=int, default=128)
32+ parser.add_argument("--Hp", type=int, default=128)
33+ parser.add_argument("--pattern", choices=("balanced", "fan-in", "mixed", "local", "empty"),
34+ default="balanced")
35+ parser.add_argument("--active-slots", type=int, help="valid slots per rank; default: B")
36+ parser.add_argument("--remote-peers", type=int, help="balanced/mixed peer span; default: world-1")
37+ if operation == "grad_reduce":
38+ parser.add_argument("--num-sms", type=int, default=8, help="GradReduce payload AIVs, 1..64")
39+ parser.add_argument("--warmup", type=int, default=10)
40+ parser.add_argument("--iters", type=int, default=50)
41+ parser.add_argument("--vmm-page-size", choices=("default", "2m", "1g"), default="2m")
42+ parser.add_argument("--ip-port", help="SHMEM bootstrap URL for multi-node runs")
43+ parser.add_argument("--timeout", type=int, default=180, help="process-group timeout in seconds")
44+ parser.add_argument("--out", type=Path, help="new result directory, files must not already exist")
45+ parser.add_argument("--dry-run", action="store_true", help="print plan/buffer estimates without torch/NPU")
46+ parser.add_argument("--world-size", type=int, help="dry-run world size; live must match torchrun")
47+ args = parser.parse_args(argv)
48+ args.operation = operation
49+ args.B = args.epn if args.B is None else args.B
50+ args.active_slots = args.B if args.active_slots is None else args.active_slots
51+ args.barrier_mode = args.barrier_mode or ("aiv" if args.engine == "urma" else "mixed")
52+ args.num_sms = getattr(args, "num_sms", 1)
53+ for key in ("epn", "B", "H", "Hp", "iters", "timeout"):
54+ if getattr(args, key) <= 0:
55+ parser.error(key + " must be positive")
56+ if args.warmup < 0 or not 0 <= args.active_slots <= args.B:
57+ parser.error("warmup must be nonnegative and active-slots must be in 0..B")
58+ if not 1 <= args.num_sms <= 64:
59+ parser.error("num-sms must be in 1..64")
60+ if args.engine == "urma" and args.shmem_udma != "on":
61+ parser.error("URMA payload requires --shmem-udma on")
62+ if operation == "grad_reduce" and args.B != args.epn:
63+ parser.error("prepared GradReduceTargets currently requires B=epn")
64+ if operation == "prefetch" and args.engine == "ubmem" and args.barrier_mode != "mixed":
65+ parser.error("MTE owner PUSH uses mixed barriers; select --barrier-mode mixed")
66+ world = int(os.environ.get("WORLD_SIZE", args.world_size or 8))
67+ if args.world_size is not None and args.world_size != world:
68+ parser.error("world-size differs from torchrun WORLD_SIZE")
69+ if world < 2:
70+ parser.error("requires at least two ranks")
71+ args.world_size = world
72+ args.remote_peers = world - 1 if args.remote_peers is None else args.remote_peers
73+ if not 1 <= args.remote_peers < world:
74+ parser.error("remote-peers must be in 1..world-1")
75+ return args
76+ 
77+ 
78+def routing_rows(args):
79+ rows = []
80+ for rank in range(args.world_size):
81+ row = []
82+ for slot in range(args.B):
83+ if slot >= args.active_slots or args.pattern == "empty":
84+ row.append(-1)
85+ continue
86+ owner = (rank + 1 + slot % args.remote_peers) % args.world_size
87+ local = slot % args.epn
88+ if args.pattern == "fan-in":
89+ owner, local = 0, slot % args.epn
90+ elif args.pattern == "local" or (args.pattern == "mixed" and slot % 2 == 0):
91+ owner, local = rank, slot % args.epn
92+ row.append(owner * args.epn + local)
93+ rows.append(row)
94+ return rows
95+ 
96+ 
97+def slot_value(rank, slot, slots, iteration):
98+ return 1 + rank * slots + slot + iteration % 7
99+ 
100+ 
101+def grad_reference(rows, rank, epn, slots, iteration):
102+ values = [3 + local for local in range(epn)]
103+ for peer, row in enumerate(rows):
104+ for slot, expert in enumerate(row):
105+ if rank * epn <= expert < (rank + 1) * epn:
106+ values[expert - rank * epn] += slot_value(peer, slot, slots, iteration)
107+ return values
108+ 
109+ 
110+def case_description(args):
111+ rows = routing_rows(args)
112+ itemsize = 2 if args.operation == "prefetch" else 4
113+ matrix_bytes = args.H * args.Hp * itemsize
114+ remote = sum(expert >= 0 and expert // args.epn != rank
115+ for rank, row in enumerate(rows) for expert in row)
116+ valid = sum(expert >= 0 for row in rows for expert in row)
117+ scratch = (512 * 1024 * max(2 * args.num_sms, args.world_size * args.B) * 4
118+ if args.operation == "grad_reduce" and args.engine == "urma" else 0)
119+ return dict(operation=args.operation, engine=args.engine, mode=args.mode,
120+ shmem_udma_enabled=args.shmem_udma == "on", qp_count=2 if args.shmem_udma == "on" else 0,
121+ barrier_mode=args.barrier_mode, world_size=args.world_size,
122+ epn=args.epn, B=args.B, H=args.H, Hp=args.Hp, pattern=args.pattern,
123+ active_slots=args.active_slots, remote_peers=args.remote_peers,
124+ payload_aiv_blocks=(None if args.operation == "prefetch" and args.engine == "ubmem"
125+ else args.num_sms),
126+ payload_block_policy=("native VectorBlocks / ACL_DEV_ATTR_AICORE_CORE_NUM"
127+ if args.operation == "prefetch" and args.engine == "ubmem"
128+ else "fixed URMA PUSH=1" if args.operation == "prefetch"
129+ else "grad_reduce_num_sms"),
130+ warmup=args.warmup, iters=args.iters,
131+ vmm_page_size=args.vmm_page_size, routing=rows,
132+ logical_remote_bytes_per_call=remote * matrix_bytes,
133+ logical_valid_bytes_per_call=valid * matrix_bytes,
134+ tensor_bytes_per_rank=(args.epn + args.B) * matrix_bytes,
135+ udma_scratch_bytes_per_rank=scratch,
136+ estimate_excludes="VMM rounding, Buffer control arenas, allocator/runtime overhead")
137+ 
138+ 
139+def refill(args, rows, rank, refs, slot, iteration):
140+ slot.fill_(-17)
141+ if args.operation == "grad_reduce":
142+ for index, ref in enumerate(refs):
143+ ref.fill_(3 + index)
144+ for index, expert in enumerate(rows[rank]):
145+ if expert >= 0:
146+ slot[index].fill_(slot_value(rank, index, args.B, iteration))
147+ 
148+ 
149+def measure_sample(torch, dist, prepare, submit, iteration):
150+ # Refill and producer completion are outside the timed interval.
151+ prepare(iteration)
152+ torch.npu.synchronize()
153+ dist.barrier()
154+ stream = torch.npu.current_stream()
155+ begin = torch.npu.Event(enable_timing=True)
156+ end = torch.npu.Event(enable_timing=True)
157+ begin.record(stream)
158+ host_begin = time.perf_counter_ns()
159+ done = submit()
160+ host_us = (time.perf_counter_ns() - host_begin) / 1000
161+ if done is not None:
162+ stream.wait_event(done)
163+ end.record(stream)
164+ end.synchronize()
165+ return dict(device_us=float(begin.elapsed_time(end)) * 1000, submit_us=host_us)
166+ 
167+ 
168+def summarize(per_rank, logical_remote_bytes):
169+ count = len(per_rank[0]["samples"])
170+ worst = [max(rank["samples"][i]["device_us"] for rank in per_rank) for i in range(count)]
171+ ordered = sorted(worst)
172+ median = statistics.median(worst)
173+ return dict(rank_count=len(per_rank), sample_count=count,
174+ worst_rank_samples_us=worst, median_us=median,
175+ p95_us=ordered[max(0, math.ceil(.95 * count) - 1)],
176+ min_us=min(worst), max_us=max(worst),
177+ submit_median_us_per_rank=[statistics.median(s["submit_us"] for s in rank["samples"])
178+ for rank in per_rank],
179+ aggregate_logical_remote_GiB_s=(logical_remote_bytes / (median * 1e-6) / 2**30
180+ if median > 0 else 0.0),
181+ timing="public Buffer submit through consumer event join; native barriers included",
182+ excludes="setup, refill, producer synchronize, external HCCL barrier, checks, teardown",
183+ graph_capture=False)
184+ 
185+ 
186+def source_identity(repo):
187+ def git(*args):
188+ result = subprocess.run(["git", *args], cwd=repo, capture_output=True, text=True)
189+ return result.stdout.strip() if result.returncode == 0 else None
190+ return dict(commit=git("rev-parse", "HEAD"),
191+ tracked_changes=git("diff", "HEAD", "--name-only"),
192+ benchmark_sha256={name: hashlib.sha256((Path(__file__).parent / name).read_bytes()).hexdigest()
193+ for name in ("_lplusb_bench.py", "bench_prefetch_push.py",
194+ "bench_grad_reduce_targets.py")})
195+ 
196+ 
197+def loaded_libraries(native):
198+ paths = {Path(native.__file__).resolve()}
199+ maps = Path("/proc/self/maps")
200+ if maps.exists():
201+ for line in maps.read_text().splitlines():
202+ name = line.split()[-1]
203+ if name.startswith("/") and any(s in name for s in ("libascend_moonep", "libshmem")):
204+ paths.add(Path(name).resolve())
205+ return [dict(path=str(p), sha256=hashlib.sha256(p.read_bytes()).hexdigest())
206+ for p in sorted(paths) if p.is_file()]
207+ 
208+ 
209+def _check(torch, dist, args, rows, rank, refs, slot, iteration):
210+ checks = []
211+ if args.operation == "prefetch":
212+ for index, expert in enumerate(rows[rank]):
213+ flat = slot[index].view(-1)
214+ value = -17 if expert < 0 else 1 + expert % 127
215+ marker = -17 if expert < 0 else -(1 + expert // 127)
216+ checks.extend((torch.all(flat[1:] == value), flat[0] == marker))
217+ else:
218+ for target, value in zip(refs, grad_reference(rows, rank, args.epn, args.B, iteration)):
219+ checks.append(torch.all(target == value))
220+ for index, expert in enumerate(rows[rank]):
221+ checks.append(torch.all(slot[index] == (0 if expert >= 0 else -17)))
222+ passed = torch.stack(checks).all().to(torch.int32)
223+ dist.all_reduce(passed, op=dist.ReduceOp.MIN)
224+ if not bool(passed.item()):
225+ raise RuntimeError("collective payload/reference or valid-slot clear check failed")
226+ 
227+ 
228+def run(args):
229+ if args.out:
230+ rank_file = args.out / ("rank_" + os.environ.get("RANK", "0") + ".json")
231+ if rank_file.exists() or (args.out / "summary.json").exists():
232+ raise FileExistsError("use a fresh --out directory for each independent run")
233+ repo = Path(__file__).resolve().parents[2]
234+ sys.path.insert(0, str(repo))
235+ import torch
236+ import torch_npu # noqa: F401 -- registers torch.npu
237+ import torch.distributed as dist
238+ from npu_patch import Buffer, ShmemRuntime, _C
239+ from npu_patch._device import local_device_index
240+ from npu_patch.buffer_c import create_vmm_physical, reset_symmetric_descriptors
241+ from npu_patch.planning import allocate_planning_outputs
242+ 
243+ if "WORLD_SIZE" not in os.environ:
244+ raise RuntimeError("launch a live run with torchrun or run_bench.sh")
245+ local = local_device_index(int(os.environ.get("LOCAL_RANK", 0)))
246+ torch.npu.set_device(local)
247+ device = torch.device("npu", local)
248+ dist.init_process_group("hccl", device_id=device, timeout=timedelta(seconds=args.timeout))
249+ rank = dist.get_rank()
250+ udma = args.engine == "urma"
251+ # Override inherited transport policy so the label cannot silently change.
252+ for name in ("PLANNING", "DISPATCH", "COMBINE", "PREFETCH", "GRAD_REDUCE"):
253+ os.environ["ASCEND_MOONEP_" + name + "_USE_UDMA"] = "0"
254+ os.environ["ASCEND_MOONEP_USE_UDMA"] = "0"
255+ os.environ["MOONEP_GRAD_REDUCE_NATIVE_BARRIER_MODE"] = args.barrier_mode
256+ flags = {"prefetch_use_udma": udma if args.operation == "prefetch" else False,
257+ "grad_reduce_use_udma": udma if args.operation == "grad_reduce" else False}
258+ buffer = Buffer(S=1, H=128, K=1, E=args.world_size * args.epn, B=args.B,
259+ num_ep_ranks=args.world_size, group=dist.group.WORLD,
260+ use_udma=False, num_sms=8, planning_num_sms=8,
261+ grad_reduce_num_sms=args.num_sms,
262+ prefetch_barrier_mode=args.barrier_mode if args.operation == "prefetch" else "mixed",
263+ vmm_page_size=args.vmm_page_size, explicitly_destroy=True, **flags)
264+ _ACTIVE_RESOURCES.append(buffer)
265+ ctx = buffer._ctx
266+ key = "_prefetch_use_udma" if args.operation == "prefetch" else "_grad_reduce_use_udma"
267+ if bool(ctx[key]) != udma:
268+ raise RuntimeError("requested engine unavailable; refusing a mislabeled benchmark")
269+ dtype = torch.bfloat16 if args.operation == "prefetch" else torch.float32
270+ source, _, _ = create_vmm_physical((args.B, args.H, args.Hp), dtype, local,
271+ page_size=args.vmm_page_size)
272+ _ACTIVE_RESOURCES.append(source)
273+ refs = tuple(torch.empty((args.H, args.Hp), dtype=dtype, device=device)
274+ for _ in range(args.epn))
275+ if args.operation == "prefetch":
276+ refs = tuple(torch.nn.Parameter(ref, requires_grad=False) for ref in refs)
277+ _ACTIVE_RESOURCES.append(refs)
278+ rows = routing_rows(args)
279+ plan, _ = allocate_planning_outputs(ctx)
280+ plan.experts_to_copy.copy_(torch.tensor(rows, dtype=torch.int32, device=device))
281+ _ACTIVE_RESOURCES.append(plan)
282+ ShmemRuntime.init_with_buffer(group=dist.group.WORLD,
283+ enable_udma=args.shmem_udma == "on",
284+ qp_count=2 if args.shmem_udma == "on" else 0,
285+ ip_port=args.ip_port)
286+ buffer._ensure_shmem_views()
287+ binding = buffer.prepare_lplusb(refs, source)
288+ _ACTIVE_RESOURCES.append(binding)
289+ slot = binding.slot
290+ if args.operation == "prefetch":
291+ for index, ref in enumerate(refs):
292+ expert = rank * args.epn + index
293+ ref.fill_(1 + expert % 127)
294+ ref.view(-1)[0] = -(1 + expert // 127)
295+ 
296+ def prepare(iteration):
297+ refill(args, rows, rank, refs, slot, iteration)
298+ 
299+ def submit():
300+ if args.operation == "prefetch":
301+ return buffer.prefetch_lplusb(plan, binding, async_finish=args.mode == "async")
302+ return buffer.reduce_grad(plan=plan, lplusb=binding, async_finish=args.mode == "async")
303+ 
304+ # Preflight twice with different GR payloads, then check the final timed call.
305+ for iteration in range(2):
306+ measure_sample(torch, dist, prepare, submit, iteration)
307+ _check(torch, dist, args, rows, rank, refs, slot, iteration)
308+ identity = source_identity(repo)
309+ identity["loaded_libraries"] = loaded_libraries(_C)
310+ identity["runtime"] = dict(hostname=socket.gethostname(), python=sys.version.split()[0],
311+ torch=str(torch.__version__),
312+ torch_npu=getattr(torch_npu, "__version__", None),
313+ ascend_home=os.environ.get("ASCEND_HOME_PATH"), argv=sys.argv)
314+ for iteration in range(args.warmup):
315+ measure_sample(torch, dist, prepare, submit, iteration)
316+ samples = [measure_sample(torch, dist, prepare, submit, iteration)
317+ for iteration in range(args.iters)]
318+ _check(torch, dist, args, rows, rank, refs, slot, args.iters - 1)
319+ result = dict(rank=rank, local_device=local, samples=samples, identity=identity,
320+ payload_checked=True, slot_refill_each_iteration=True,
321+ native_abis={name: getattr(_C, name, None) for name in (
322+ "LPLUS_B_BUFFER_SYNC_ABI", "PREFETCH_PUSH_POINTER_ABI",
323+ "GRAD_REDUCE_POINTER_ABI", "GRAD_REDUCE_POINTER_UDMA_ABI")})
324+ per_rank = [None] * args.world_size
325+ dist.all_gather_object(per_rank, result)
326+ torch.npu.synchronize()
327+ dist.barrier()
328+ ShmemRuntime.finalize()
329+ buffer.destroy()
330+ source._vmm_allocation.destroy()
331+ reset_symmetric_descriptors()
332+ dist.destroy_process_group()
333+ _ACTIVE_RESOURCES.clear()
334+ case = case_description(args)
335+ if args.out:
336+ args.out.mkdir(parents=True, exist_ok=True)
337+ with (args.out / ("rank_" + str(rank) + ".json")).open("x", encoding="utf-8") as file:
338+ json.dump(dict(schema=1, case=case, **result), file, indent=2)
339+ if rank == 0:
340+ report = dict(schema=1, case=case,
341+ summary=summarize(per_rank, case["logical_remote_bytes_per_call"]),
342+ ranks=per_rank)
343+ if args.out:
344+ with (args.out / "summary.json").open("x", encoding="utf-8") as file:
345+ json.dump(report, file, indent=2)
346+ print(json.dumps(report, indent=2), flush=True)
347+ 
348+ 
349+def main(operation, argv=None):
350+ args = parse_args(operation, argv)
351+ if args.dry_run:
352+ print(json.dumps(case_description(args), indent=2))
353+ return
354+ run(args)
@@ -0,0 +1,9 @@
1+"""Prepared L+B grad_reduce benchmark; use --help for options."""
2+if __package__:
3+ from ._lplusb_bench import main
4+else:
5+ from _lplusb_bench import main
6+ 
7+ 
8+if __name__ == "__main__":
9+ main("grad_reduce")
@@ -0,0 +1,9 @@
1+"""Prepared L+B prefetch benchmark; use --help for options."""
2+if __package__:
3+ from ._lplusb_bench import main
4+else:
5+ from _lplusb_bench import main
6+ 
7+ 
8+if __name__ == "__main__":
9+ main("prefetch")
@@ -220,7 +220,7 @@ def _check_combine_inputs(
220 )220 )
221 hidden_key = "hidden_buf_local" if use_udma else "hidden_buf"221 hidden_key = "hidden_buf_local" if use_udma else "hidden_buf"
222 _check_tensor(222 _check_tensor(
223- ctx[hidden_key],223+ ctx[hidden_key][:NvS],
224 f"ctx.{hidden_key}",224 f"ctx.{hidden_key}",
225 (NvS, H),225 (NvS, H),
226 torch.bfloat16,226 torch.bfloat16,
@@ -228,7 +228,7 @@ def _check_combine_inputs(
228 )228 )
229 if output_sk is not None:229 if output_sk is not None:
230 weights_key = "weights_buf_local" if use_udma else "weights_buf"230 weights_key = "weights_buf_local" if use_udma else "weights_buf"
231- weights_buf = ctx[weights_key].view(torch.float32)231+ weights_buf = ctx[weights_key].view(torch.float32)[:NvS]
232 _check_tensor(232 _check_tensor(
233 weights_buf,233 weights_buf,
234 f"ctx.{weights_key}(fp32 view)",234 f"ctx.{weights_key}(fp32 view)",
@@ -290,7 +290,8 @@ def launch_combine(
290def launch_combine_prepared(ctx, output_sh, plan, execution_plan, output_sk=None):290def launch_combine_prepared(ctx, output_sh, plan, execution_plan, output_sk=None):
291 import torch291 import torch
292 import torch_npu292 import torch_npu
293- from .planning import CombineExecutionPlan, _routes, _key293+ from .planning import (CombineExecutionPlan, _routes, _key,
294+ _combine_workspace_layout, prepare_combine_plan)
294 295 
295 if not isinstance(execution_plan, CombineExecutionPlan):296 if not isinstance(execution_plan, CombineExecutionPlan):
296 raise TypeError('execution_plan must be returned by prepare_combine_plan')297 raise TypeError('execution_plan must be returned by prepare_combine_plan')
@@ -300,11 +301,21 @@ def launch_combine_prepared(ctx, output_sh, plan, execution_plan, output_sk=None
300 execution_plan.validate(ctx, plan)301 execution_plan.validate(ctx, plan)
301 stream = torch_npu.npu.current_stream()302 stream = torch_npu.npu.current_stream()
302 stream.wait_event(execution_plan.ready)303 stream.wait_event(execution_plan.ready)
303- weights = ctx['weights_buf_local'].view(torch.float32) if output_sk is not None else None304+ if ('_capacity_ctx' in ctx and
305+ ctx['_capacity_ctx'].get('_combine_workspace_layout') != _combine_workspace_layout(ctx)):
306+ # Buffer's ordered communication lane may revisit an older, shorter
307+ # route after planning/combining a different size. Its immutable tables
308+ # remain valid, but that intervening layout can overwrite its ready
309+ # slots with payload. Rebuild through the upstream collective planner
310+ # before payload launch; every rank follows the same logical sizes.
311+ execution_plan = prepare_combine_plan(ctx, plan)
312+ n = int(ctx['NvS'])
313+ hidden = ctx['hidden_buf_local'][:n]
314+ weights = ctx['weights_buf_local'].view(torch.float32)[:n] if output_sk is not None else None
304 torch.classes.AscendMoonEP.CombineUrma().compute_prepared(315 torch.classes.AscendMoonEP.CombineUrma().compute_prepared(
305- ctx['hidden_buf_local'], weights, ctx['combine_sync_buffer'], ctx['combine_workspace'],316+ hidden, weights, ctx['combine_sync_buffer'], ctx['combine_workspace'],
306 *_routes(plan), output_sh, output_sk, execution_plan.storage, *_key(ctx))317 *_routes(plan), output_sh, output_sk, execution_plan.storage, *_key(ctx))
307- for tensor in (execution_plan.storage, *_routes(plan), ctx['hidden_buf_local'], weights,318+ for tensor in (execution_plan.storage, *_routes(plan), hidden, weights,
308 ctx['combine_workspace'], ctx['combine_sync_buffer'], output_sh,319 ctx['combine_workspace'], ctx['combine_sync_buffer'], output_sh,
309 output_sk):320 output_sk):
310 if tensor is not None:321 if tensor is not None:
@@ -118,14 +118,14 @@ def _check_dispatch_inputs(
118 hidden_sh.device,118 hidden_sh.device,
119 )119 )
120 _check_tensor(120 _check_tensor(
121- ctx["hidden_buf"],121+ ctx["hidden_buf"][:NvS],
122 "ctx.hidden_buf",122 "ctx.hidden_buf",
123 (NvS, H),123 (NvS, H),
124 torch.bfloat16,124 torch.bfloat16,
125 hidden_sh.device,125 hidden_sh.device,
126 )126 )
127 if route_weights_sk is not None:127 if route_weights_sk is not None:
128- weights_buf = ctx["weights_buf"].view(torch.float32)128+ weights_buf = ctx["weights_buf"].view(torch.float32)[:NvS]
129 _check_tensor(129 _check_tensor(
130 weights_buf,130 weights_buf,
131 "ctx.weights_buf(fp32 view)",131 "ctx.weights_buf(fp32 view)",
@@ -9,10 +9,11 @@ keep the ported Ascend tests minimal: they resolve the op object from
9``launch_dispatch_epilogue`` / ``launch_combine_prologue`` steps are folded into9``launch_dispatch_epilogue`` / ``launch_combine_prologue`` steps are folded into
10``launch_dispatch`` / ``launch_combine`` and no longer have their own shims.10``launch_dispatch`` / ``launch_combine`` and no longer have their own shims.
11 11 
12-Two launchers are intentionally *not* shimmed through a Buffer ctx because the12+These launchers are intentionally *not* shimmed through a Buffer ctx because the
13standalone stage tests call them without one:13standalone stage tests call them without one:
14 - ``launch_prefetch(remote_expert, prefetch_buffers, experts_to_copy, num_sms)``14 - ``launch_prefetch(remote_expert, prefetch_buffers, experts_to_copy, num_sms)``
15 - ``launch_grad_reduce(remote_expert_grads, reduce_buffers, plan, rank, ...)``15 - ``launch_grad_reduce(remote_expert_grads, reduce_buffers, plan, rank, ...)``
16+ - ``launch_grad_reduce_targets(target_ptrs, reduce_buffers, plan, rank, num_sms)``
16Their Ascend contracts are described in ``ops.py``.17Their Ascend contracts are described in ``ops.py``.
17"""18"""
18 19 
@@ -142,11 +143,14 @@ def launch_dispatch_op(
142 world_size: int,143 world_size: int,
143 rank: int,144 rank: int,
144 server_dedup: bool = False,145 server_dedup: bool = False,
146+ num_sms: int = 32,
145) -> None:147) -> None:
148+ """Launch dispatch; num_sms controls only the MTE AIV launch width."""
146 global _DISPATCH149 global _DISPATCH
147 if _DISPATCH is None:150 if _DISPATCH is None:
148 _DISPATCH = torch.classes.AscendMoonEP.Dispatch()151 _DISPATCH = torch.classes.AscendMoonEP.Dispatch()
149- _DISPATCH.compute(152+ use_udma = _env_use_udma('dispatch')
153+ args = (
150 hidden_sh,154 hidden_sh,
151 route_weights,155 route_weights,
152 dst,156 dst,
@@ -161,9 +165,12 @@ def launch_dispatch_op(
161 num_topk,165 num_topk,
162 world_size,166 world_size,
163 rank,167 rank,
164- _env_use_udma('dispatch'),168+ use_udma,
165 bool(server_dedup),169 bool(server_dedup),
166 )170 )
171+ if not use_udma:
172+ args += (num_sms,)
173+ _DISPATCH.compute(*args)
167 174 
168 175 
169def launch_dispatch_profile_op(176def launch_dispatch_profile_op(
@@ -225,6 +232,7 @@ def launch_combine_op(
225 world_size: int,232 world_size: int,
226 rank: int,233 rank: int,
227 server_dedup: bool = False,234 server_dedup: bool = False,
235+ num_sms: int = 32,
228) -> None:236) -> None:
229 """Select the native / legacy-rank / server-dedup combine kernel.237 """Select the native / legacy-rank / server-dedup combine kernel.
230 238 
@@ -233,6 +241,7 @@ def launch_combine_op(
233 the execution plan prepared by the planner.241 the execution plan prepared by the planner.
234 - ``use_udma and not server_dedup``: legacy rank-level dedup kernel, which242 - ``use_udma and not server_dedup``: legacy rank-level dedup kernel, which
235 only needs the plan's dst/dup tables.243 only needs the plan's dst/dup tables.
244+ - ``num_sms`` controls only the MTE AIV launch width.
236 """245 """
237 global _COMBINE, _COMBINE_UDMA246 global _COMBINE, _COMBINE_UDMA
238 use_udma = _env_use_udma("combine")247 use_udma = _env_use_udma("combine")
@@ -306,6 +315,7 @@ def launch_combine_op(
306 world_size,315 world_size,
307 rank,316 rank,
308 False,317 False,
318+ num_sms,
309 )319 )
310 320 
311 if route_weights_sk_out is not None and sk_stride != num_topk:321 if route_weights_sk_out is not None and sk_stride != num_topk:
@@ -404,6 +414,57 @@ def launch_prefetch(
404 num_experts, num_sms, 0, _env_use_udma('prefetch'), rank_barriers)414 num_experts, num_sms, 0, _env_use_udma('prefetch'), rank_barriers)
405 415 
406 416 
417+# The URMA PUSH layout validator is licensed under Apache-2.0.
418+def _validate_push_layout(home, slots, plan, num_sms, *, bf16, int32):
419+ """Validate tensor metadata without reading device data or synchronizing."""
420+ if type(num_sms) is not int or num_sms <= 0:
421+ raise ValueError("num_sms must be a positive integer")
422+ if any(t.device.type != "npu" for t in (home, slots, plan)):
423+ raise ValueError("URMA PUSH inputs must be NPU tensors")
424+ if not home.device == slots.device == plan.device:
425+ raise ValueError("URMA PUSH inputs must share one NPU")
426+ if home.dtype != bf16 or slots.dtype != bf16 or plan.dtype != int32:
427+ raise TypeError("URMA PUSH requires BF16 weights and INT32 plan")
428+ if home.ndim != 3 or slots.ndim != 3 or plan.ndim != 2:
429+ raise ValueError("expected home[E,M,N], slots[B,M,N], plan[EP,B]")
430+ if any(not t.is_contiguous() for t in (home, slots, plan)):
431+ raise ValueError("URMA PUSH inputs must be contiguous")
432+ if not 0 < home.shape[0] <= 2147483647 or min(home.shape[1:]) <= 0:
433+ raise ValueError("invalid expert count or projection dimensions")
434+ if home.shape[1:] != slots.shape[1:] or slots.shape[0] != plan.shape[1]:
435+ raise ValueError("incompatible projection or slot shapes")
436+ if not 0 < plan.shape[0] <= 2147483647:
437+ raise ValueError("plan EP must be positive and fit int32")
438+ if slots.shape[0] > 15736:
439+ raise ValueError("plan exceeds URMA PUSH UB scratch capacity")
440+ 
441+ 
442+def launch_prefetch_push(remote_expert, prefetch_buffers, experts_to_copy, num_sms):
443+ """Collectively push BF16 owner weights into symmetric consumer slots.
444+ 
445+ All ranks call with the same contiguous INT32 [EP,B] plan (-1 means empty).
446+ Returns the destination tensor after enqueueing completion barriers on the
447+ current stream. Retain inputs and backing through a completion event; order
448+ producer writes and previous slot consumers before this call.
449+ Requires ShmemRuntime.init_with_buffer(enable_udma=True, qp_count=2).
450+ """
451+ from .shmem_runtime import ShmemRuntime
452+ _validate_push_layout(remote_expert, prefetch_buffers, experts_to_copy, num_sms,
453+ bf16=torch.bfloat16, int32=torch.int32)
454+ if not ShmemRuntime.is_initialized() or not ShmemRuntime._udma_enabled:
455+ raise RuntimeError("URMA PUSH requires an initialized URMA SHMEM runtime")
456+ if "950" not in torch.npu.get_device_name(remote_expert.device):
457+ raise RuntimeError("URMA PUSH requires Ascend950")
458+ global _PREFETCH_WEIGHT
459+ if _PREFETCH_WEIGHT is None:
460+ _PREFETCH_WEIGHT = torch.classes.AscendMoonEP.PrefetchWeight(0)
461+ if not _PREFETCH_WEIGHT.push_available():
462+ raise RuntimeError("native build does not provide URMA PUSH")
463+ return _PREFETCH_WEIGHT.compute_push(
464+ remote_expert, prefetch_buffers, experts_to_copy,
465+ int(remote_expert.shape[0]), num_sms, 0, True)
466+ 
467+ 
407def launch_grad_reduce(468def launch_grad_reduce(
408 remote_expert_grads: torch.Tensor,469 remote_expert_grads: torch.Tensor,
409 remote_reduce_buffers: torch.Tensor,470 remote_reduce_buffers: torch.Tensor,
@@ -474,3 +535,71 @@ def launch_grad_reduce(
474 min(num_sms, 64),535 min(num_sms, 64),
475 _env_use_udma('grad_reduce'),536 _env_use_udma('grad_reduce'),
476 )537 )
538+ 
539+ 
540+def launch_grad_reduce_targets(
541+ target_ptrs: torch.Tensor,
542+ reduce_buffers: torch.Tensor,
543+ experts_to_copy: torch.Tensor,
544+ rank: int,
545+ num_sms: int,
546+ udma_workspace: torch.Tensor | None = None,
547+ *,
548+ use_udma: bool | None = None,
549+) -> None:
550+ """Explicit canonical-pointer contract, distinct from the dense entry.
551+ 
552+ ``target_ptrs`` is a setup-frozen contiguous INT64 [epn] table of local
553+ FP32 matrix addresses. Each target is contiguous [H, H']; targets remain
554+ alive, disjoint and address-stable until completion. They need not be
555+ symmetric or adjacent. Only ``reduce_buffers[B,H,H']`` is a symmetric
556+ source bank. The Buffer supplies its configured backend. Standalone
557+ callers can omit it to use the grad_reduce environment flag. UDMA needs
558+ setup-owned local FP32 scratch of at least
559+ 512*1024*max(2*min(num_sms,64),R*B) elements through completion.
560+ The native entry validates the scratch metadata and capacity.
561+ MTE uses ordered addition; UDMA retains dense UDMA's atomic-add ordering.
562+ Both use pre/post barriers and clear only valid slots.
563+ """
564+ if reduce_buffers.numel() == 0 or experts_to_copy.numel() == 0:
565+ return
566+ 
567+ assert target_ptrs.dtype == torch.int64
568+ assert target_ptrs.is_contiguous() and target_ptrs.ndim == 1
569+ assert reduce_buffers.dtype == torch.float32
570+ assert reduce_buffers.is_contiguous() and reduce_buffers.ndim == 3
571+ assert experts_to_copy.dtype == torch.int32
572+ assert experts_to_copy.is_contiguous() and experts_to_copy.ndim == 2
573+ assert isinstance(rank, int)
574+ assert isinstance(num_sms, int) and num_sms > 0
575+ epn = int(target_ptrs.numel())
576+ B, H, Hp = (int(value) for value in reduce_buffers.shape)
577+ R, plan_B = (int(value) for value in experts_to_copy.shape)
578+ assert plan_B == B
579+ assert 0 <= rank < R
580+ device = target_ptrs.device
581+ assert device.type == "npu"
582+ assert reduce_buffers.device == device
583+ assert experts_to_copy.device == device
584+ 
585+ from . import _C
586+ abi = getattr(_C, "GRAD_REDUCE_POINTER_ABI", None)
587+ if type(abi) is not int or abi != 1:
588+ raise RuntimeError("rebuild native GradReduceOp canonical pointer ABI v1")
589+ if use_udma is None:
590+ use_udma = _env_use_udma('grad_reduce')
591+ blocks = min(num_sms, 64)
592+ udma_abi = getattr(_C, "GRAD_REDUCE_POINTER_UDMA_ABI", None)
593+ unified_backend = type(udma_abi) is int and udma_abi in (2, 3)
594+ if use_udma and (type(udma_abi) is not int or udma_abi != 3):
595+ raise RuntimeError("rebuild native GradReduceOp canonical pointer UDMA ABI v3")
596+ global _GRAD_REDUCE
597+ if _GRAD_REDUCE is None:
598+ _GRAD_REDUCE = torch.classes.AscendMoonEP.GradReduce()
599+ # Older extensions retain the MTE-only signature; updated builds expose
600+ # the same method with optional backend/workspace arguments.
601+ backend_args = ((use_udma, udma_workspace if use_udma else None)
602+ if unified_backend else ())
603+ _GRAD_REDUCE.compute_targets(
604+ target_ptrs, reduce_buffers, experts_to_copy,
605+ epn, H, Hp, R, B, rank, blocks, *backend_args)
@@ -85,6 +85,8 @@ include("${CMAKE_SOURCE_DIR}/cmake/AscendMoonEPKernel.cmake")
85ascend_moonep_add_kernel_library(85ascend_moonep_add_kernel_library(
86 ascend_moonep_kernels86 ascend_moonep_kernels
87 SOURCES87 SOURCES
88+ kernels/lplusb_runtime.cpp
89+ kernels/barrier.cpp
88 kernels/barrier_bench.cpp90 kernels/barrier_bench.cpp
89 kernels/moonep_combine.cpp91 kernels/moonep_combine.cpp
90 kernels/moonep_combine_udma.cpp92 kernels/moonep_combine_udma.cpp
@@ -95,6 +97,8 @@ ascend_moonep_add_kernel_library(
95 kernels/planning.cpp97 kernels/planning.cpp
96 kernels/prefetch.cpp98 kernels/prefetch.cpp
97 kernels/prefetch_udma.cpp99 kernels/prefetch_udma.cpp
100+ kernels/prefetch_push_udma.cpp
101+ kernels/prefetch_pointer_push_udma.cpp
98 INCLUDES102 INCLUDES
99 include103 include
100 kernels104 kernels
@@ -13,6 +13,7 @@
13 13 
14#include "acl/acl.h"14#include "acl/acl.h"
15#include "shmem.h"15#include "shmem.h"
16+#include "ascend_moonep/kernels/launch.h"
16 17 
17namespace ascend_moonep {18namespace ascend_moonep {
18 19 
@@ -773,4 +774,10 @@ void acl_shmem_barrier_all_on_stream(int64_t stream) {
773 reinterpret_cast<aclrtStream>(static_cast<uintptr_t>(stream)));774 reinterpret_cast<aclrtStream>(static_cast<uintptr_t>(stream)));
774}775}
775 776 
777+void acl_shmem_barrier_all_aiv_on_stream(int64_t stream) {
778+ TORCH_CHECK(moonep_async_stream_barrier_vec(
779+ reinterpret_cast<void*>(static_cast<uintptr_t>(stream))) == ACL_SUCCESS,
780+ "asynchronous collective AIV barrier launch failed");
781+}
782+ 
776}783}
@@ -130,4 +130,5 @@ int acl_shmem_init_with_buffers_ip_port(
130 const std::vector<std::tuple<int64_t, int64_t, int64_t, std::string>>& descriptors,130 const std::vector<std::tuple<int64_t, int64_t, int64_t, std::string>>& descriptors,
131 int device_id, bool enable_udma = false, uint32_t qp_count = 0);131 int device_id, bool enable_udma = false, uint32_t qp_count = 0);
132void acl_shmem_barrier_all_on_stream(int64_t stream);132void acl_shmem_barrier_all_on_stream(int64_t stream);
133+void acl_shmem_barrier_all_aiv_on_stream(int64_t stream);
133}134}
@@ -0,0 +1,127 @@
1+#include "csrc/lplusb_runtime.h"
2+ 
3+#include <acl/acl.h>
4+#include <limits>
5+ 
6+#include <torch_npu/csrc/core/npu/NPUStream.h>
7+ 
8+#include "ascend_moonep/kernels/launch.h"
9+#include "csrc/common/check.h"
10+#include "shmem.h"
11+ 
12+namespace ascend_moonep {
13+namespace {
14+ 
15+void CheckCommon(
16+ const torch::Tensor& pointer_table,
17+ const torch::Tensor& slots,
18+ const torch::Tensor& plan,
19+ int64_t rank,
20+ int64_t local_experts)
21+{
22+ TORCH_CHECK(pointer_table.device().type() == c10::DeviceType::PrivateUse1,
23+ "pointer table must be an NPU tensor");
24+ TORCH_CHECK(slots.device().type() == c10::DeviceType::PrivateUse1,
25+ "slot arena must be an NPU tensor");
26+ TORCH_CHECK(plan.device().type() == c10::DeviceType::PrivateUse1,
27+ "experts_to_copy must be an NPU tensor");
28+ TORCH_CHECK(pointer_table.device() == slots.device() && slots.device() == plan.device(),
29+ "pointer table, slot arena and plan must be on the same NPU");
30+ TORCH_CHECK(pointer_table.scalar_type() == torch::kInt64 &&
31+ pointer_table.dim() == 1 && pointer_table.is_contiguous(),
32+ "pointer table must be contiguous INT64 [L]");
33+ TORCH_CHECK(plan.scalar_type() == torch::kInt32 && plan.dim() == 2 && plan.is_contiguous(),
34+ "experts_to_copy must be contiguous INT32 [R,B]");
35+ TORCH_CHECK(slots.is_contiguous() && slots.dim() >= 2,
36+ "slot arena must be contiguous [B,...]");
37+ TORCH_CHECK(local_experts > 0 && pointer_table.numel() == local_experts,
38+ "pointer table length must equal local_experts");
39+ TORCH_CHECK(plan.size(1) == slots.size(0) && plan.size(0) > 0,
40+ "plan [R,B] must match the slot arena B dimension");
41+ TORCH_CHECK(rank >= 0 && rank < plan.size(0), "rank is outside the EP group");
42+ for (int64_t dim = 1; dim < slots.dim(); ++dim) {
43+ TORCH_CHECK(slots.size(dim) > 0, "slot rows must have positive dimensions");
44+ }
45+ TORCH_CHECK(local_experts <= std::numeric_limits<int32_t>::max() &&
46+ plan.size(0) <= std::numeric_limits<int32_t>::max() &&
47+ plan.size(1) <= std::numeric_limits<int32_t>::max(),
48+ "L/R/B exceeds the private kernel int32 contract");
49+}
50+ 
51+int64_t RowElements(const torch::Tensor& slots) {
52+ int64_t elements = 1;
53+ for (int64_t dim = 1; dim < slots.dim(); ++dim) {
54+ TORCH_CHECK(elements <= std::numeric_limits<int64_t>::max() / slots.size(dim),
55+ "slot row extent overflows INT64");
56+ elements *= slots.size(dim);
57+ }
58+ return elements;
59+}
60+ 
61+int32_t VectorBlocks()
62+{
63+ int32_t device_id = 0;
64+ int64_t cores = 0;
65+ ASCEND_MOONEP_CHECK_ACL(aclrtGetDevice(&device_id));
66+ ASCEND_MOONEP_CHECK_ACL(
67+ aclrtGetDeviceInfo(device_id, ACL_DEV_ATTR_AICORE_CORE_NUM, &cores));
68+ TORCH_CHECK(cores > 0 && cores <= std::numeric_limits<int32_t>::max(),
69+ "current NPU reports an invalid AICore count");
70+ return static_cast<int32_t>(cores);
71+}
72+ 
73+} // namespace
74+ 
75+void LPlusBOwnerPush(
76+ torch::Tensor source_ptrs,
77+ torch::Tensor weight_slots,
78+ torch::Tensor experts_to_copy,
79+ int64_t rank,
80+ int64_t local_experts)
81+{
82+ CheckCommon(source_ptrs, weight_slots, experts_to_copy, rank, local_experts);
83+ TORCH_CHECK(weight_slots.scalar_type() == torch::kBFloat16,
84+ "weight slot arena must be BF16");
85+ aclrtStream stream = c10_npu::getCurrentNPUStream().stream();
86+ aclshmemx_barrier_all_on_stream(stream);
87+ const int ret = moonep_lplusb_owner_push(
88+ stream,
89+ reinterpret_cast<const uint64_t*>(source_ptrs.data_ptr<int64_t>()),
90+ weight_slots.data_ptr(), experts_to_copy.data_ptr<int32_t>(),
91+ RowElements(weight_slots),
92+ static_cast<int32_t>(local_experts), static_cast<int32_t>(experts_to_copy.size(0)),
93+ static_cast<int32_t>(experts_to_copy.size(1)), static_cast<int32_t>(rank),
94+ VectorBlocks());
95+ TORCH_CHECK(ret == 0, "L+B owner-push kernel failed with ACL error: ", ret);
96+ // On return, all writes are peer-visible on the same ordered stream.
97+ aclshmemx_barrier_all_on_stream(stream);
98+}
99+ 
100+void LPlusBOwnerReduce(
101+ torch::Tensor target_ptrs,
102+ torch::Tensor grad_slots,
103+ torch::Tensor experts_to_copy,
104+ int64_t rank,
105+ int64_t local_experts)
106+{
107+ CheckCommon(target_ptrs, grad_slots, experts_to_copy, rank, local_experts);
108+ TORCH_CHECK(grad_slots.scalar_type() == torch::kFloat32,
109+ "gradient slot arena must be FP32");
110+ aclrtStream stream = c10_npu::getCurrentNPUStream().stream();
111+ // Publish local pointer-target GMM writes before any owner reads peer slots.
112+ aclshmemx_barrier_all_on_stream(stream);
113+ const int ret = moonep_lplusb_owner_reduce(
114+ stream,
115+ reinterpret_cast<const uint64_t*>(target_ptrs.data_ptr<int64_t>()),
116+ grad_slots.data_ptr(), experts_to_copy.data_ptr<int32_t>(),
117+ RowElements(grad_slots),
118+ static_cast<int32_t>(local_experts), static_cast<int32_t>(experts_to_copy.size(0)),
119+ static_cast<int32_t>(experts_to_copy.size(1)), static_cast<int32_t>(rank),
120+ VectorBlocks());
121+ TORCH_CHECK(ret == 0, "L+B owner-reduce kernel failed with ACL error: ", ret);
122+ // Kernel-internal collective proves all peer reads ended; this barrier
123+ // publishes local target accumulation and slot clearing to the caller.
124+ aclshmemx_barrier_all_on_stream(stream);
125+}
126+ 
127+} // namespace ascend_moonep
@@ -0,0 +1,21 @@
1+#pragma once
2+ 
3+#include <torch/extension.h>
4+ 
5+namespace ascend_moonep {
6+ 
7+void LPlusBOwnerPush(
8+ torch::Tensor source_ptrs,
9+ torch::Tensor weight_slots,
10+ torch::Tensor experts_to_copy,
11+ int64_t rank,
12+ int64_t local_experts);
13+ 
14+void LPlusBOwnerReduce(
15+ torch::Tensor target_ptrs,
16+ torch::Tensor grad_slots,
17+ torch::Tensor experts_to_copy,
18+ int64_t rank,
19+ int64_t local_experts);
20+ 
21+} // namespace ascend_moonep
@@ -1,11 +1,13 @@
1#include "csrc/ops/grad_reduce.h"1#include "csrc/ops/grad_reduce.h"
2 2 
3+#include <algorithm>
3#include <limits>4#include <limits>
4 5 
5#include <torch/extension.h>6#include <torch/extension.h>
6#include <torch_npu/csrc/core/npu/NPUStream.h>7#include <torch_npu/csrc/core/npu/NPUStream.h>
7 8 
8#include "ascend_moonep/kernels/launch.h"9#include "ascend_moonep/kernels/launch.h"
10+#include "shmem.h"
9 11 
10namespace ascend_moonep::ops {12namespace ascend_moonep::ops {
11 13 
@@ -82,9 +84,6 @@ void GradReduce(
82 int64_t rank,84 int64_t rank,
83 int64_t blocks,85 int64_t blocks,
84 bool use_udma) {86 bool use_udma) {
85- // The current grad-reduce implementation has no separate UDMA kernel.
86- // Keep the unified ABI and deliberately use the existing SHMEM path.
87- (void)use_udma;
88 aclrtStream stream = c10_npu::getCurrentNPUStream().stream();87 aclrtStream stream = c10_npu::getCurrentNPUStream().stream();
89 88 
90 CheckNpuContiguous(expert_grads, "expert_grads");89 CheckNpuContiguous(expert_grads, "expert_grads");
@@ -145,4 +144,89 @@ void GradReduce(
145 }144 }
146}145}
147 146 
147+void GradReduceTargets(
148+ torch::Tensor target_ptrs,
149+ torch::Tensor reduce_buffers,
150+ torch::Tensor experts_to_copy,
151+ int64_t epn,
152+ int64_t hidden,
153+ int64_t projection,
154+ int64_t ranks,
155+ int64_t slots,
156+ int64_t rank,
157+ int64_t blocks,
158+ bool use_udma,
159+ torch::Tensor udma_workspace) {
160+ aclrtStream stream = c10_npu::getCurrentNPUStream().stream();
161+ CheckNpuContiguous(target_ptrs, "target_ptrs");
162+ TORCH_CHECK(
163+ target_ptrs.scalar_type() == torch::kInt64 &&
164+ target_ptrs.dim() == 1 && target_ptrs.numel() == epn,
165+ "canonical target pointers must be contiguous INT64 [epn]");
166+ TORCH_CHECK(
167+ target_ptrs.device() == reduce_buffers.device(),
168+ "target_ptrs and reduce_buffers must be on the same device");
169+ CheckCommon(reduce_buffers, experts_to_copy, hidden, projection,
170+ ranks, slots, rank, blocks);
171+ TORCH_CHECK(epn > 0, "epn must be positive");
172+ CheckInt32(epn, "epn");
173+ 
174+ if (use_udma) {
175+ TORCH_CHECK(udma_workspace.defined(), "UDMA grad_reduce requires setup-owned workspace");
176+ CheckNpuContiguous(udma_workspace, "udma_workspace");
177+ TORCH_CHECK(udma_workspace.scalar_type() == torch::kFloat32 &&
178+ udma_workspace.device() == reduce_buffers.device() &&
179+ ranks <= std::numeric_limits<int64_t>::max() / std::max<int64_t>(slots, 1),
180+ "udma_workspace device/dtype or rank-slot product is invalid");
181+ const int64_t regions = std::max<int64_t>(blocks * 2, ranks * slots);
182+ constexpr int64_t tile = 512 * 1024;
183+ TORCH_CHECK(regions <= std::numeric_limits<int64_t>::max() / (tile * sizeof(float)),
184+ "ordered UDMA workspace byte count exceeds int64");
185+ TORCH_CHECK(udma_workspace.numel() >= tile * regions,
186+ "udma_workspace must be local FP32 scratch with at least "
187+ "512*1024*max(blocks*2,ranks*slots) elements on the source device");
188+ }
189+ 
190+ // Publish Q1 slots before peer reads, then publish target updates and
191+ // cleared valid slots before the caller records its completion event.
192+ // UDMA scratch is owned by the caller and allocated during setup, never
193+ // inside this hot submission. Its lifetime covers the entire Q0 operation.
194+ const int pre_barrier_status = moonep_grad_reduce_native_barrier(stream);
195+ TORCH_CHECK(pre_barrier_status == ACL_SUCCESS,
196+ "GR native barrier launch failed: ", pre_barrier_status);
197+ if (use_udma) {
198+ const int ret = moonep_shmem_grad_reduce_targets_udma(
199+ stream,
200+ target_ptrs.data_ptr(),
201+ reduce_buffers.data_ptr(),
202+ udma_workspace.data_ptr(),
203+ experts_to_copy.data_ptr<int32_t>(),
204+ static_cast<int32_t>(epn),
205+ static_cast<int32_t>(hidden),
206+ static_cast<int32_t>(projection),
207+ static_cast<int32_t>(ranks),
208+ static_cast<int32_t>(slots),
209+ static_cast<int32_t>(rank),
210+ static_cast<int32_t>(blocks));
211+ TORCH_CHECK(ret == 0, "canonical grad_reduce kernel failed with ACL error: ", ret);
212+ } else {
213+ const int ret = moonep_shmem_grad_reduce_targets(
214+ stream,
215+ target_ptrs.data_ptr(),
216+ reduce_buffers.data_ptr(),
217+ experts_to_copy.data_ptr<int32_t>(),
218+ static_cast<int32_t>(epn),
219+ static_cast<int32_t>(hidden),
220+ static_cast<int32_t>(projection),
221+ static_cast<int32_t>(ranks),
222+ static_cast<int32_t>(slots),
223+ static_cast<int32_t>(rank),
224+ static_cast<int32_t>(blocks));
225+ TORCH_CHECK(ret == 0, "canonical grad_reduce kernel failed with ACL error: ", ret);
226+ }
227+ const int post_barrier_status = moonep_grad_reduce_native_barrier(stream);
228+ TORCH_CHECK(post_barrier_status == ACL_SUCCESS,
229+ "GR native barrier launch failed: ", post_barrier_status);
230+}
231+ 
148} // namespace ascend_moonep::ops232} // namespace ascend_moonep::ops
@@ -19,4 +19,21 @@ void GradReduce(
19 int64_t blocks,19 int64_t blocks,
20 bool use_udma);20 bool use_udma);
21 21 
22+// Extension for canonical targets; the dense entry and its backend contract
23+// remain unchanged. use_udma selects MTE or UDMA; UDMA requires caller-owned
24+// local workspace. Both use pre/post barriers.
25+void GradReduceTargets(
26+ torch::Tensor target_ptrs,
27+ torch::Tensor reduce_buffers,
28+ torch::Tensor experts_to_copy,
29+ int64_t epn,
30+ int64_t hidden,
31+ int64_t projection,
32+ int64_t ranks,
33+ int64_t slots,
34+ int64_t rank,
35+ int64_t blocks,
36+ bool use_udma = false,
37+ torch::Tensor udma_workspace = {});
38+ 
22} // namespace ascend_moonep::ops39} // namespace ascend_moonep::ops
@@ -44,8 +44,12 @@ void MoonEPCombine(
44 int64_t K,44 int64_t K,
45 int64_t R,45 int64_t R,
46 int64_t rank,46 int64_t rank,
47- bool use_udma) {47+ bool use_udma,
48+ int64_t num_sms) {
48 (void)use_udma;49 (void)use_udma;
50+ TORCH_CHECK(num_sms > 0 &&
51+ static_cast<uint64_t>(num_sms) <= std::numeric_limits<uint32_t>::max(),
52+ "num_sms must be a positive uint32 launch width");
49 CheckNpuContiguous(hidden_buf, "hidden_buf");53 CheckNpuContiguous(hidden_buf, "hidden_buf");
50 CheckNpuContiguous(dst, "dst");54 CheckNpuContiguous(dst, "dst");
51 CheckNpuContiguous(dup_groups, "dup_groups");55 CheckNpuContiguous(dup_groups, "dup_groups");
@@ -137,7 +141,7 @@ void MoonEPCombine(
137 tiling.num_tokens = static_cast<uint32_t>(S);141 tiling.num_tokens = static_cast<uint32_t>(S);
138 tiling.hidden = static_cast<uint32_t>(H);142 tiling.hidden = static_cast<uint32_t>(H);
139 tiling.num_topk = static_cast<uint32_t>(K);143 tiling.num_topk = static_cast<uint32_t>(K);
140- tiling.block_dim = 32u;144+ tiling.block_dim = static_cast<uint32_t>(num_sms);
141 tiling.with_weight = with_weight ? 1u : 0u;145 tiling.with_weight = with_weight ? 1u : 0u;
142 tiling.reserved = 0u;146 tiling.reserved = 0u;
143 147 
@@ -7,7 +7,7 @@ namespace ascend_moonep::ops {
7// Plan-driven moonEP_combine on already-symmetric SHMEM shards.7// Plan-driven moonEP_combine on already-symmetric SHMEM shards.
8// Outputs are caller-allocated. Host ABI mirrors MoonEPDispatch.8// Outputs are caller-allocated. Host ABI mirrors MoonEPDispatch.
9// Provide weight_buf and route_weights_sk_out together, or omit both.9// Provide weight_buf and route_weights_sk_out together, or omit both.
10-// Launch width is fixed at 32 AIV.10+// MTE launch width is controlled by num_sms.
11//11//
12// route_weights_sk_out must be fp32 [S, AlignUp(K, 8)] when present12// route_weights_sk_out must be fp32 [S, AlignUp(K, 8)] when present
13// (kernel DataCopy width).13// (kernel DataCopy width).
@@ -25,6 +25,7 @@ void MoonEPCombine(
25 int64_t K,25 int64_t K,
26 int64_t R,26 int64_t R,
27 int64_t rank,27 int64_t rank,
28- bool use_udma);28+ bool use_udma,
29+ int64_t num_sms = 32);
29 30 
30} // namespace ascend_moonep::ops31} // namespace ascend_moonep::ops
@@ -185,13 +185,18 @@ MoonEPDispatch(
185 int64_t R,185 int64_t R,
186 int64_t rank,186 int64_t rank,
187 bool use_udma,187 bool use_udma,
188- bool server_dedup) {188+ bool server_dedup,
189+ int64_t num_sms) {
189 190 
190 auto args = CheckDispatchArgs(191 auto args = CheckDispatchArgs(
191 hidden_sh, route_weights, dst, dup_groups, dup_loffs, dup_counts,192 hidden_sh, route_weights, dst, dup_groups, dup_loffs, dup_counts,
192 hidden_buf, route_weights_buf, S, H, K, R, rank, use_udma, server_dedup);193 hidden_buf, route_weights_buf, S, H, K, R, rank, use_udma, server_dedup);
193 194 
194 if (!use_udma) {195 if (!use_udma) {
196+ TORCH_CHECK(num_sms > 0 &&
197+ static_cast<uint64_t>(num_sms) <= std::numeric_limits<uint32_t>::max(),
198+ "num_sms must be a positive uint32 launch width");
199+ args.tiling.block_dim = static_cast<uint32_t>(num_sms);
195 // Peer-to-peer MTE path: rank-level dedup only, no UDMA messaging.200 // Peer-to-peer MTE path: rank-level dedup only, no UDMA messaging.
196 LaunchMoonEPDispatchKernel(201 LaunchMoonEPDispatchKernel(
197 hidden_sh, args.route_weights, dst,202 hidden_sh, args.route_weights, dst,
@@ -23,7 +23,8 @@ MoonEPDispatch(
23 int64_t R,23 int64_t R,
24 int64_t rank,24 int64_t rank,
25 bool use_udma,25 bool use_udma,
26- bool server_dedup);26+ bool server_dedup,
27+ int64_t num_sms = 32);
27 28 
28void29void
29MoonEPDispatchProfile(30MoonEPDispatchProfile(
@@ -3,6 +3,7 @@
3#include <acl/acl.h>3#include <acl/acl.h>
4#include <algorithm>4#include <algorithm>
5#include <cstdint>5#include <cstdint>
6+#include <limits>
6 7 
7#include <torch_npu/csrc/core/npu/NPUStream.h>8#include <torch_npu/csrc/core/npu/NPUStream.h>
8 9 
@@ -13,6 +14,15 @@
13 14 
14namespace {15namespace {
15 16 
17+void PrefetchBarrier(aclrtStream stream, bool aiv_only) {
18+ if (aiv_only) {
19+ TORCH_CHECK(moonep_prefetch_barrier_vec(stream) == ACL_SUCCESS,
20+ "URMA prefetch AIV barrier launch failed");
21+ } else {
22+ aclshmemx_barrier_all_on_stream(stream);
23+ }
24+}
25+ 
16void CheckNpuContiguous(const torch::Tensor& tensor, const char* name) {26void CheckNpuContiguous(const torch::Tensor& tensor, const char* name) {
17 TORCH_CHECK(27 TORCH_CHECK(
18 tensor.device().type() == c10::DeviceType::PrivateUse1,28 tensor.device().type() == c10::DeviceType::PrivateUse1,
@@ -41,6 +51,9 @@ torch::Tensor LaunchPrefetch(
41 bool use_udma,51 bool use_udma,
42 bool rank_barriers) {52 bool rank_barriers) {
43 // The current SHMEM runtime is a single global instance.53 // The current SHMEM runtime is a single global instance.
54+ 
55+ TORCH_CHECK(!use_udma || prefetch_weight_push_udma_available() == 1,
56+ "requested URMA GET is unavailable in this native build");
44 (void)instance_id;57 (void)instance_id;
45 (void)num_sms;58 (void)num_sms;
46 // remote_expert is a logical cross-PE view. Its data pointer is the local59 // remote_expert is a logical cross-PE view. Its data pointer is the local
@@ -122,4 +135,108 @@ torch::Tensor LaunchPrefetch(
122 return prefetch_buffers;135 return prefetch_buffers;
123}136}
124 137 
138+ 
139+torch::Tensor LaunchPrefetchPush(
140+ torch::Tensor home, torch::Tensor slots, torch::Tensor plan,
141+ int64_t num_sms, int64_t instance_id, bool use_udma) {
142+ TORCH_CHECK(use_udma, "compute_push requires URMA; no MTE fallback");
143+ TORCH_CHECK(prefetch_weight_push_udma_available() == 1,
144+ "URMA PUSH requires a native Ascend950 build");
145+ TORCH_CHECK(instance_id == 0 && num_sms > 0, "invalid instance_id or num_sms");
146+ CheckNpuContiguous(home, "home");
147+ CheckNpuContiguous(slots, "slots");
148+ CheckNpuContiguous(plan, "plan");
149+ TORCH_CHECK(home.device() == slots.device() && home.device() == plan.device(),
150+ "home, slots and plan must share an NPU");
151+ TORCH_CHECK(home.scalar_type() == torch::kBFloat16 &&
152+ slots.scalar_type() == torch::kBFloat16 &&
153+ plan.scalar_type() == torch::kInt32, "expected BF16 weights and INT32 plan");
154+ TORCH_CHECK(home.dim() == 3 && slots.dim() == 3 && plan.dim() == 2,
155+ "expected home[E,M,N], slots[B,M,N], plan[EP,B]");
156+ TORCH_CHECK(home.size(0) > 0 && home.size(0) <= INT32_MAX &&
157+ home.size(1) > 0 && home.size(2) > 0,
158+ "home dimensions must be positive");
159+ TORCH_CHECK(home.size(1) == slots.size(1) && home.size(2) == slots.size(2) &&
160+ slots.size(0) == plan.size(1), "incompatible projection or slot shapes");
161+ TORCH_CHECK(plan.size(0) == aclshmem_n_pes() && plan.size(0) > 0 &&
162+ plan.size(0) <= INT32_MAX,
163+ "plan EP must match the initialized SHMEM group");
164+ // Reserve the official WQE scratch plus a full local-copy tile below 188 KiB.
165+ TORCH_CHECK(slots.size(0) <= 15736, "plan exceeds URMA PUSH UB scratch capacity");
166+ aclrtStream stream = c10_npu::getCurrentNPUStream().stream();
167+ aclshmemx_barrier_all_on_stream(stream);
168+ ASCEND_MOONEP_CHECK_ACL(prefetch_weight_push_udma_do(stream,
169+ static_cast<uint8_t*>(home.data_ptr()), static_cast<uint8_t*>(slots.data_ptr()),
170+ static_cast<uint8_t*>(plan.data_ptr()), home.size(0),
171+ home.size(1) * home.size(2), slots.size(0)));
172+ aclshmemx_barrier_all_on_stream(stream);
173+ return slots;
174+}
175+ 
176+bool PrefetchPushPointersAvailable() {
177+ return prefetch_pointer_push_udma_available() == 1;
178+}
179+ 
180+namespace {
181+int64_t CheckPushProjection(const torch::Tensor& source, const torch::Tensor& slots,
182+ const torch::Tensor& plan, int64_t local_experts) {
183+ CheckNpuContiguous(source, "source");
184+ CheckNpuContiguous(slots, "slots");
185+ CheckNpuContiguous(plan, "plan");
186+ TORCH_CHECK(source.device() == slots.device() && slots.device() == plan.device(),
187+ "source, slots and plan must share one NPU");
188+ TORCH_CHECK(slots.scalar_type() == torch::kBFloat16 &&
189+ plan.scalar_type() == torch::kInt32 && slots.dim() == 3 && plan.dim() == 2,
190+ "expected BF16 slots[B,M,N] and INT32 plan[EP,B]");
191+ const int64_t ep = plan.size(0);
192+ TORCH_CHECK(ep > 0 && ep == aclshmem_n_pes() && local_experts > 0 &&
193+ local_experts <= INT32_MAX / ep,
194+ "local expert count or SHMEM topology differs");
195+ TORCH_CHECK(plan.size(1) == slots.size(0) && slots.size(0) <= 15736 &&
196+ slots.size(1) > 0 && slots.size(2) > 0 &&
197+ slots.size(1) <= std::numeric_limits<int64_t>::max() / slots.size(2),
198+ "invalid projection, slots or URMA UB extent");
199+ return slots.size(1) * slots.size(2);
200+}
201+}
202+ 
203+torch::Tensor LaunchPrefetchPushPointers(torch::Tensor pointers, torch::Tensor slots,
204+ torch::Tensor plan, int64_t local_experts, bool aiv_barrier) {
205+ TORCH_CHECK(PrefetchPushPointersAvailable(), "URMA pointer PUSH unavailable; no MTE fallback");
206+ const int64_t elements = CheckPushProjection(pointers, slots, plan, local_experts);
207+ TORCH_CHECK(pointers.scalar_type() == torch::kInt64 && pointers.dim() == 1 &&
208+ pointers.numel() == local_experts, "expected INT64 pointer table[L]");
209+ aclrtStream stream = c10_npu::getCurrentNPUStream().stream();
210+ PrefetchBarrier(stream, aiv_barrier);
211+ ASCEND_MOONEP_CHECK_ACL(moonep_prefetch_pointer_push_udma(stream,
212+ reinterpret_cast<uint8_t*>(pointers.data_ptr()),
213+ reinterpret_cast<uint8_t*>(slots.data_ptr()),
214+ reinterpret_cast<uint8_t*>(plan.data_ptr()),
215+ local_experts * plan.size(0), elements, slots.size(0)));
216+ PrefetchBarrier(stream, aiv_barrier);
217+ return slots;
218+}
219+ 
220+torch::Tensor LaunchPrefetchPushLocal(torch::Tensor home, torch::Tensor slots,
221+ torch::Tensor plan, int64_t global_experts, bool aiv_barrier) {
222+ TORCH_CHECK(prefetch_weight_push_udma_available() == 1,
223+ "URMA contiguous PUSH unavailable; no MTE fallback");
224+ TORCH_CHECK(home.dim() == 3 && home.scalar_type() == torch::kBFloat16 &&
225+ plan.dim() == 2 && plan.size(0) > 0 && global_experts > 0 &&
226+ global_experts % plan.size(0) == 0 &&
227+ home.size(0) == global_experts / plan.size(0),
228+ "expected legal local_home[L,M,N] and explicit global E");
229+ const int64_t elements = CheckPushProjection(home, slots, plan, home.size(0));
230+ TORCH_CHECK(home.size(1) == slots.size(1) && home.size(2) == slots.size(2),
231+ "home and slots projection differs");
232+ aclrtStream stream = c10_npu::getCurrentNPUStream().stream();
233+ PrefetchBarrier(stream, aiv_barrier);
234+ ASCEND_MOONEP_CHECK_ACL(prefetch_weight_push_udma_do(stream,
235+ reinterpret_cast<uint8_t*>(home.data_ptr()),
236+ reinterpret_cast<uint8_t*>(slots.data_ptr()),
237+ reinterpret_cast<uint8_t*>(plan.data_ptr()),
238+ global_experts, elements, slots.size(0)));
239+ PrefetchBarrier(stream, aiv_barrier);
240+ return slots;
241+}
125} // namespace ascend_moonep::ops242} // namespace ascend_moonep::ops
@@ -13,4 +13,14 @@ torch::Tensor LaunchPrefetch(
13 bool use_udma,13 bool use_udma,
14 bool rank_barriers = true);14 bool rank_barriers = true);
15 15 
16+ 
17+torch::Tensor LaunchPrefetchPush(
18+ torch::Tensor home, torch::Tensor slots, torch::Tensor plan,
19+ int64_t num_sms, int64_t instance_id, bool use_udma);
20+// Stateless submissions: caller owns Tensor/table lifetime and consumer final use.
21+bool PrefetchPushPointersAvailable();
22+torch::Tensor LaunchPrefetchPushPointers(torch::Tensor pointers, torch::Tensor slots,
23+ torch::Tensor plan, int64_t local_experts, bool aiv_barrier = false);
24+torch::Tensor LaunchPrefetchPushLocal(torch::Tensor home, torch::Tensor slots,
25+ torch::Tensor plan, int64_t global_experts, bool aiv_barrier = false);
16} // namespace ascend_moonep::ops26} // namespace ascend_moonep::ops
@@ -2,7 +2,9 @@
2 2 
3#include "acl_shared_buffer.h"3#include "acl_shared_buffer.h"
4#include "launcher.h"4#include "launcher.h"
5+#include "lplusb_runtime.h"
5#include "shmem.h"6#include "shmem.h"
7+#include "csrc/ops/prefetch.h"
6 8 
7PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {9PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
8 m.doc() = "MoonEP NPU symmetric-memory extension (shmem C++ backend)";10 m.doc() = "MoonEP NPU symmetric-memory extension (shmem C++ backend)";
@@ -12,6 +14,32 @@ PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
12 py::int_(sizeof(aclshmemx_buffer_optional_attr_t));14 py::int_(sizeof(aclshmemx_buffer_optional_attr_t));
13 15 
14 using py::arg;16 using py::arg;
17+ m.attr("PREFETCH_PUSH_POINTER_ABI") = py::int_(1);
18+ m.attr("PREFETCH_PUSH_LOCAL_ABI") = py::int_(1);
19+ m.attr("PREFETCH_PUSH_BARRIER_ABI") = py::int_(1);
20+ m.def("_prefetch_push_available", &ascend_moonep::ops::PrefetchPushPointersAvailable);
21+ m.def("_prefetch_push_pointers", &ascend_moonep::ops::LaunchPrefetchPushPointers,
22+ arg("source_ptrs"), arg("slots"), arg("plan"), arg("local_experts"), arg("aiv_barrier") = false);
23+ m.def("_prefetch_push_local", &ascend_moonep::ops::LaunchPrefetchPushLocal,
24+ arg("local_home"), arg("slots"), arg("plan"), arg("global_experts"), arg("aiv_barrier") = false);
25+ m.def("_prefetch_push_pointers_aiv", [](torch::Tensor p, torch::Tensor s, torch::Tensor plan, int64_t l) {
26+ return ascend_moonep::ops::LaunchPrefetchPushPointers(p, s, plan, l, true);
27+ });
28+ m.def("_prefetch_push_local_aiv", [](torch::Tensor h, torch::Tensor s, torch::Tensor plan, int64_t e) {
29+ return ascend_moonep::ops::LaunchPrefetchPushLocal(h, s, plan, e, true);
30+ });
31+ 
32+ // Private MindSpeed integration. Kept out of Python __all__ and public
33+ // Buffer signatures so existing MoonEP callers are unaffected.
34+ m.attr("LPLUS_B_BUFFER_SYNC_ABI") = py::int_(2);
35+ m.attr("GRAD_REDUCE_POINTER_ABI") = py::int_(1);
36+ m.attr("GRAD_REDUCE_POINTER_UDMA_ABI") = py::int_(3);
37+ m.def("_lplusb_owner_push", &ascend_moonep::LPlusBOwnerPush,
38+ arg("source_ptrs"), arg("weight_slots"), arg("experts_to_copy"),
39+ arg("rank"), arg("local_experts"));
40+ m.def("_lplusb_owner_reduce", &ascend_moonep::LPlusBOwnerReduce,
41+ arg("target_ptrs"), arg("grad_slots"), arg("experts_to_copy"),
42+ arg("rank"), arg("local_experts"));
15 43 
16 m.def("launch_device_barrier_bench", &LaunchDeviceBarrierBench,44 m.def("launch_device_barrier_bench", &LaunchDeviceBarrierBench,
17 arg("iterations"), arg("block_dim") = 32,45 arg("iterations"), arg("block_dim") = 32,
@@ -151,4 +179,9 @@ PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
151 &ascend_moonep::acl_shmem_barrier_all_on_stream,179 &ascend_moonep::acl_shmem_barrier_all_on_stream,
152 arg("stream"),180 arg("stream"),
153 "Global shmem barrier issued on the given aclrtStream");181 "Global shmem barrier issued on the given aclrtStream");
182+ m.attr("ASYNC_STREAM_BARRIER_ABI") = py::int_(1);
183+ m.def("_acl_shmem_barrier_all_aiv_on_stream",
184+ &ascend_moonep::acl_shmem_barrier_all_aiv_on_stream,
185+ arg("stream"),
186+ "Same collective completion using a single AIV participant");
154}187}
@@ -12,6 +12,7 @@
12#include <torch/script.h>12#include <torch/script.h>
13 13 
14#include "shmem.h"14#include "shmem.h"
15+#include "ascend_moonep/kernels/launch.h"
15 16 
16#include "csrc/common/check.h"17#include "csrc/common/check.h"
17#include "csrc/launcher.h"18#include "csrc/launcher.h"
@@ -105,7 +106,15 @@ private:
105 106 
106class PrefetchWeight : public torch::jit::CustomClassHolder {107class PrefetchWeight : public torch::jit::CustomClassHolder {
107public:108public:
109+ 
108 explicit PrefetchWeight(int64_t /*local_mem_size*/) {}110 explicit PrefetchWeight(int64_t /*local_mem_size*/) {}
111+ bool push_available() { return prefetch_weight_push_udma_available() == 1; }
112+ torch::Tensor compute_push(torch::Tensor home, torch::Tensor slots, torch::Tensor plan,
113+ int64_t num_experts, int64_t num_sms, int64_t instance_id, bool use_udma) {
114+ TORCH_CHECK(home.dim() == 3 && home.size(0) == num_experts, "invalid num_experts");
115+ return ascend_moonep::ops::LaunchPrefetchPush(
116+ home, slots, plan, num_sms, instance_id, use_udma);
117+ }
109 118 
110 void destroy() {}119 void destroy() {}
111 120 
@@ -162,6 +171,19 @@ public:
162 blocks,171 blocks,
163 use_udma);172 use_udma);
164 }173 }
174+ 
175+ void compute_targets(
176+ torch::Tensor target_ptrs, torch::Tensor reduce_buffers,
177+ torch::Tensor experts_to_copy, int64_t epn, int64_t hidden,
178+ int64_t projection, int64_t ranks, int64_t slots, int64_t rank,
179+ int64_t blocks, bool use_udma = false,
180+ c10::optional<torch::Tensor> workspace = c10::nullopt) {
181+ TORCH_CHECK(rank == aclshmem_my_pe(),
182+ "rank does not match the active CANN-SHMEM PE");
183+ ascend_moonep::ops::GradReduceTargets(target_ptrs, reduce_buffers, experts_to_copy,
184+ epn, hidden, projection, ranks, slots, rank, blocks, use_udma,
185+ workspace.value_or(torch::Tensor()));
186+ }
165};187};
166 188 
167class Planning : public torch::jit::CustomClassHolder {189class Planning : public torch::jit::CustomClassHolder {
@@ -289,7 +311,8 @@ public:
289 int64_t world_size,311 int64_t world_size,
290 int64_t rank,312 int64_t rank,
291 bool use_udma,313 bool use_udma,
292- bool server_dedup) {314+ bool server_dedup,
315+ int64_t num_sms = 32) {
293 TORCH_CHECK(316 TORCH_CHECK(
294 rank == aclshmem_my_pe(),317 rank == aclshmem_my_pe(),
295 "rank does not match the active CANN-SHMEM PE");318 "rank does not match the active CANN-SHMEM PE");
@@ -309,7 +332,8 @@ public:
309 world_size,332 world_size,
310 rank,333 rank,
311 use_udma,334 use_udma,
312- server_dedup);335+ server_dedup,
336+ num_sms);
313 }337 }
314 338 
315 void compute_profile(339 void compute_profile(
@@ -372,7 +396,8 @@ public:
372 int64_t num_topk,396 int64_t num_topk,
373 int64_t world_size,397 int64_t world_size,
374 int64_t rank,398 int64_t rank,
375- bool use_udma) {399+ bool use_udma,
400+ int64_t num_sms = 32) {
376 TORCH_CHECK(401 TORCH_CHECK(
377 rank == aclshmem_my_pe(),402 rank == aclshmem_my_pe(),
378 "rank does not match the active CANN-SHMEM PE");403 "rank does not match the active CANN-SHMEM PE");
@@ -390,7 +415,8 @@ public:
390 num_topk,415 num_topk,
391 world_size,416 world_size,
392 rank,417 rank,
393- use_udma);418+ use_udma,
419+ num_sms);
394 }420 }
395};421};
396 422 
@@ -576,12 +602,21 @@ static auto prefetch_weight_registry =
576 torch::jit::class_<ascend_moonep::torch_classes::PrefetchWeight>("AscendMoonEP", "PrefetchWeight")602 torch::jit::class_<ascend_moonep::torch_classes::PrefetchWeight>("AscendMoonEP", "PrefetchWeight")
577 .def(torch::jit::init<int64_t>())603 .def(torch::jit::init<int64_t>())
578 .def("compute", &ascend_moonep::torch_classes::PrefetchWeight::compute)604 .def("compute", &ascend_moonep::torch_classes::PrefetchWeight::compute)
605+ .def("compute_push", &ascend_moonep::torch_classes::PrefetchWeight::compute_push)
606+ .def("push_available", &ascend_moonep::torch_classes::PrefetchWeight::push_available)
579 .def("destroy", &ascend_moonep::torch_classes::PrefetchWeight::destroy);607 .def("destroy", &ascend_moonep::torch_classes::PrefetchWeight::destroy);
580 608 
581static auto grad_reduce_registry =609static auto grad_reduce_registry =
582 torch::jit::class_<ascend_moonep::torch_classes::GradReduce>("AscendMoonEP", "GradReduce")610 torch::jit::class_<ascend_moonep::torch_classes::GradReduce>("AscendMoonEP", "GradReduce")
583 .def(torch::jit::init<>())611 .def(torch::jit::init<>())
584- .def("compute", &ascend_moonep::torch_classes::GradReduce::compute);612+ .def("compute", &ascend_moonep::torch_classes::GradReduce::compute)
613+ .def("compute_targets", &ascend_moonep::torch_classes::GradReduce::compute_targets,
614+ "", {torch::arg("target_ptrs"), torch::arg("reduce_buffers"),
615+ torch::arg("experts_to_copy"), torch::arg("epn"),
616+ torch::arg("hidden"), torch::arg("projection"),
617+ torch::arg("ranks"), torch::arg("slots"), torch::arg("rank"),
618+ torch::arg("blocks"), torch::arg("use_udma") = false,
619+ torch::arg("workspace") = c10::IValue()});
585 620 
586static auto planning_registry =621static auto planning_registry =
587 torch::jit::class_<ascend_moonep::torch_classes::Planning>("AscendMoonEP", "Planning")622 torch::jit::class_<ascend_moonep::torch_classes::Planning>("AscendMoonEP", "Planning")
@@ -599,13 +634,26 @@ static auto planning_registry =
599static auto dispatch_registry =634static auto dispatch_registry =
600 torch::jit::class_<ascend_moonep::torch_classes::Dispatch>("AscendMoonEP", "Dispatch")635 torch::jit::class_<ascend_moonep::torch_classes::Dispatch>("AscendMoonEP", "Dispatch")
601 .def(torch::jit::init<>())636 .def(torch::jit::init<>())
602- .def("compute", &ascend_moonep::torch_classes::Dispatch::compute)637+ .def("compute", &ascend_moonep::torch_classes::Dispatch::compute,
638+ "", {torch::arg("hidden_sh"), torch::arg("route_weights"),
639+ torch::arg("dst"), torch::arg("dup_groups"), torch::arg("dup_loffs"),
640+ torch::arg("dup_counts"), torch::arg("hidden_buf"),
641+ torch::arg("route_weights_buf"), torch::arg("sync_buffer"),
642+ torch::arg("num_tokens"), torch::arg("hidden_size"), torch::arg("num_topk"),
643+ torch::arg("world_size"), torch::arg("rank"), torch::arg("use_udma"),
644+ torch::arg("server_dedup"), torch::arg("num_sms") = 32})
603 .def("compute_profile", &ascend_moonep::torch_classes::Dispatch::compute_profile);645 .def("compute_profile", &ascend_moonep::torch_classes::Dispatch::compute_profile);
604 646 
605static auto combine_registry =647static auto combine_registry =
606 torch::jit::class_<ascend_moonep::torch_classes::Combine>("AscendMoonEP", "Combine")648 torch::jit::class_<ascend_moonep::torch_classes::Combine>("AscendMoonEP", "Combine")
607 .def(torch::jit::init<>())649 .def(torch::jit::init<>())
608- .def("compute", &ascend_moonep::torch_classes::Combine::compute);650+ .def("compute", &ascend_moonep::torch_classes::Combine::compute,
651+ "", {torch::arg("hidden_buf"), torch::arg("weight_buf"),
652+ torch::arg("dst"), torch::arg("dup_groups"), torch::arg("dup_loffs"),
653+ torch::arg("dup_counts"), torch::arg("hidden_sk_out"),
654+ torch::arg("route_weights_sk_out"), torch::arg("num_tokens"),
655+ torch::arg("hidden_size"), torch::arg("num_topk"), torch::arg("world_size"),
656+ torch::arg("rank"), torch::arg("use_udma"), torch::arg("num_sms") = 32});
609 657 
610static auto combine_urma_registry =658static auto combine_urma_registry =
611 torch::jit::class_<ascend_moonep::torch_classes::CombineUrma>("AscendMoonEP", "CombineUrma")659 torch::jit::class_<ascend_moonep::torch_classes::CombineUrma>("AscendMoonEP", "CombineUrma")
@@ -10,6 +10,9 @@
10 10 
11extern "C" {11extern "C" {
12 12 
13+// Experimental native GR barrier; public tensor/SPI ABI remains unchanged.
14+ASCEND_MOONEP_EXPORT int moonep_grad_reduce_native_barrier(void* stream);
15+ 
13ASCEND_MOONEP_EXPORT void device_barrier_bench_kernel_do(16ASCEND_MOONEP_EXPORT void device_barrier_bench_kernel_do(
14 void* stream,17 void* stream,
15 int32_t iterations,18 int32_t iterations,
@@ -174,6 +177,19 @@ ASCEND_MOONEP_EXPORT int moonep_shmem_grad_reduce(
174 int32_t rank,177 int32_t rank,
175 int32_t blocks);178 int32_t blocks);
176 179 
180+// Local canonical target pointer table; source slots remain symmetric.
181+ASCEND_MOONEP_EXPORT int moonep_shmem_grad_reduce_targets(
182+ void* stream, void* target_ptrs, void* reduce_buffers,
183+ const int32_t* experts_to_copy, int32_t epn, int32_t hidden,
184+ int32_t projection, int32_t ranks, int32_t slots, int32_t rank,
185+ int32_t blocks);
186+ 
187+ASCEND_MOONEP_EXPORT int moonep_shmem_grad_reduce_targets_udma(
188+ void* stream, void* target_ptrs, void* reduce_buffers, void* workspace,
189+ const int32_t* experts_to_copy, int32_t epn, int32_t hidden,
190+ int32_t projection, int32_t ranks, int32_t slots, int32_t rank,
191+ int32_t blocks);
192+ 
177ASCEND_MOONEP_EXPORT int moonep_shmem_grad_reduce_udma(193ASCEND_MOONEP_EXPORT int moonep_shmem_grad_reduce_udma(
178 void* stream,194 void* stream,
179 void* expert_grads,195 void* expert_grads,
@@ -210,4 +226,41 @@ ASCEND_MOONEP_EXPORT void prefetch_weight_kernel_udma_do(
210 int64_t num_slots,226 int64_t num_slots,
211 int64_t block_dim);227 int64_t block_dim);
212 228 
229+ASCEND_MOONEP_EXPORT int moonep_lplusb_owner_push(
230+ void* stream,
231+ const uint64_t* source_ptrs,
232+ void* weight_slots,
233+ const int32_t* experts_to_copy,
234+ int64_t row_elements,
235+ int32_t local_experts,
236+ int32_t ranks,
237+ int32_t slots,
238+ int32_t rank,
239+ int32_t blocks);
240+ 
241+ASCEND_MOONEP_EXPORT int moonep_lplusb_owner_reduce(
242+ void* stream,
243+ const uint64_t* target_ptrs,
244+ void* grad_slots,
245+ const int32_t* experts_to_copy,
246+ int64_t row_elements,
247+ int32_t local_experts,
248+ int32_t ranks,
249+ int32_t slots,
250+ int32_t rank,
251+ int32_t blocks);
252+ 
253+ 
254+ASCEND_MOONEP_EXPORT int prefetch_pointer_push_udma_available();
255+ASCEND_MOONEP_EXPORT int moonep_prefetch_barrier_vec(void* stream);
256+ASCEND_MOONEP_EXPORT int moonep_async_stream_barrier_vec(void* stream);
257+ASCEND_MOONEP_EXPORT int moonep_prefetch_pointer_push_udma(
258+ void* stream, uint8_t* pointers, uint8_t* slots, uint8_t* plan,
259+ int64_t experts, int64_t row_elements, int64_t num_slots);
260+ 
261+ASCEND_MOONEP_EXPORT int prefetch_weight_push_udma_available();
262+ASCEND_MOONEP_EXPORT int prefetch_weight_push_udma_do(
263+ void* stream, uint8_t* source, uint8_t* slots, uint8_t* plan,
264+ int64_t experts, int64_t row_elements, int64_t num_slots);
265+ 
213} // extern "C"266} // extern "C"
@@ -66,7 +66,7 @@ struct alignas(8) MoonEPCombineTilingData {
66 uint32_t num_tokens; // S66 uint32_t num_tokens; // S
67 uint32_t hidden; // H67 uint32_t hidden; // H
68 uint32_t num_topk; // K68 uint32_t num_topk; // K
69- uint32_t block_dim; // fixed 32 AIV (host always writes 32)69+ uint32_t block_dim; // MTE AIV launch width from num_sms
70 uint32_t with_weight; // 1: gather weights → [S,K]; 0: skip70 uint32_t with_weight; // 1: gather weights → [S,K]; 0: skip
71 uint32_t reserved;71 uint32_t reserved;
72};72};
@@ -90,8 +90,12 @@ struct alignas(8) MoonEPDispatchTilingData {
90 uint32_t rank;90 uint32_t rank;
91 uint32_t with_weights;91 uint32_t with_weights;
92 uint32_t server_dedup;92 uint32_t server_dedup;
93+ uint32_t block_dim; // MTE only; occupies the former tail padding
93};94};
94 95 
96+static_assert(sizeof(MoonEPDispatchTilingData) == 32, "dispatch tiling ABI must remain 32 bytes");
97+static_assert(sizeof(MoonEPCombineTilingData) == 32, "combine tiling ABI must remain 32 bytes");
98+ 
95// Udma dispatch profile ABI (mirrors the UBMEM template-<bool Profile> pattern99// Udma dispatch profile ABI (mirrors the UBMEM template-<bool Profile> pattern
96// from the timing branch): moonep_dispatch_udma_profile_kernel writes each AIV's100// from the timing branch): moonep_dispatch_udma_profile_kernel writes each AIV's
97// metrics as an int64 row into a [kMoonEPAivNum, kMoonEPDispatchUdmaProfileFields]101// metrics as an int64 row into a [kMoonEPAivNum, kMoonEPDispatchUdmaProfileFields]
@@ -0,0 +1,159 @@
1+// SPDX-License-Identifier: Apache-2.0
2+// Shared by the standalone contiguous-home and provider pointer-source bindings.
3+// No allocations, SHMEM initialization, or custom queue protocol belong here.
4+#pragma once
5+#include <cstdint>
6+#include "kernel_operator.h"
7+#include "shmem.h"
8+#include "opdev/bfloat16.h"
9+ 
10+namespace moonep_urma_push {
11+using namespace AscendC;
12+constexpr int32_t kUdmaCannShmemInternalUbStartBytes = 188 * 1024;
13+constexpr int64_t kUdmaPrefetchUbScratchOffset = 64;
14+constexpr int32_t kUdmaUbExpertTabOffset = kUdmaPrefetchUbScratchOffset;
15+constexpr int32_t kUdmaUbAlignBytes = 32;
16+constexpr int64_t kUdmaMaxTransferBytes = 256LL * 1024 * 1024;
17+constexpr uint32_t kUdmaLocalCopyMaxBytes = 65504;
18+constexpr uint32_t kUdmaWqeElements = 256;
19+ 
20+__aicore__ inline int32_t UdmaAlignUp(int32_t value, int32_t alignment)
21+{
22+ return (value + alignment - 1) / alignment * alignment;
23+}
24+ 
25+__aicore__ inline int32_t UdmaAivWorkerIndex()
26+{
27+ const int32_t sub_blocks = static_cast<int32_t>(GetSubBlockNum());
28+ return sub_blocks > 0 ?
29+ static_cast<int32_t>(GetBlockIdx()) / sub_blocks : 0;
30+}
31+ 
32+__aicore__ inline void UdmaCopyLocalExpertChunk(
33+ __gm__ bfloat16_t* destination,
34+ __gm__ bfloat16_t* source,
35+ uint32_t elements,
36+ __ubuf__ bfloat16_t* ub)
37+{
38+ GlobalTensor<bfloat16_t> local_src;
39+ GlobalTensor<bfloat16_t> local_dst;
40+ local_src.SetGlobalBuffer(source, elements);
41+ local_dst.SetGlobalBuffer(destination, elements);
42+ 
43+ LocalTensor<bfloat16_t> local_ub;
44+ local_ub.address_.logicPos = static_cast<uint8_t>(TPosition::VECIN);
45+ local_ub.address_.bufferAddr = reinterpret_cast<uint64_t>(ub);
46+ 
47+ for (uint32_t copied = 0; copied < elements;) {
48+ uint32_t copy_elems = elements - copied;
49+ const uint32_t max_elems = kUdmaLocalCopyMaxBytes / sizeof(bfloat16_t);
50+ if (copy_elems > max_elems) {
51+ copy_elems = max_elems;
52+ }
53+ const DataCopyExtParams copy_params{
54+ 1, static_cast<uint32_t>(copy_elems * sizeof(bfloat16_t)), 0, 0, 0};
55+ const DataCopyPadExtParams<bfloat16_t> pad_params{false, 0, 0, 0};
56+ DataCopyPad(local_ub, local_src[copied], copy_params, pad_params);
57+ SetFlag<HardEvent::MTE2_MTE3>(EVENT_ID1);
58+ WaitFlag<HardEvent::MTE2_MTE3>(EVENT_ID1);
59+ DataCopyPad(local_dst[copied], local_ub, copy_params);
60+ SetFlag<HardEvent::MTE3_MTE2>(EVENT_ID1);
61+ WaitFlag<HardEvent::MTE3_MTE2>(EVENT_ID1);
62+ copied += copy_elems;
63+ }
64+}
65+ 
66+ 
67+template<bool PointerSource>
68+__aicore__ inline void Run(
69+ GM_ADDR source_addr, GM_ADDR slots_addr, GM_ADDR plan_addr,
70+ int64_t experts, int64_t row_elements, int64_t slots)
71+{
72+ if ASCEND_IS_AIC { return; }
73+ if (UdmaAivWorkerIndex() != 0) { return; }
74+ auto* home = reinterpret_cast<__gm__ bfloat16_t*>(source_addr);
75+ auto* pointers = reinterpret_cast<__gm__ uint64_t*>(source_addr);
76+ auto* destination = reinterpret_cast<__gm__ bfloat16_t*>(slots_addr);
77+ auto* plan = reinterpret_cast<__gm__ int32_t*>(plan_addr);
78+ const int32_t ranks = aclshmem_n_pes();
79+ const int32_t rank = aclshmem_my_pe();
80+ const int64_t epn = (experts + ranks - 1) / ranks;
81+ const int32_t data_offset = UdmaAlignUp(
82+ kUdmaUbExpertTabOffset + UdmaAlignUp(
83+ static_cast<int32_t>(2 * slots * sizeof(int32_t)), 32), 32);
84+ TPipe pipe;
85+ TBuf<TPosition::VECOUT> tab_buf, wqe_buf, ub_buf;
86+ pipe.InitBuffer(tab_buf, data_offset);
87+ pipe.InitBuffer(wqe_buf, kUdmaWqeElements * sizeof(bfloat16_t));
88+ pipe.InitBuffer(ub_buf, kUdmaCannShmemInternalUbStartBytes -
89+ data_offset - kUdmaWqeElements * sizeof(bfloat16_t));
90+ auto tab = tab_buf.Get<int32_t>();
91+ auto wqe = wqe_buf.Get<bfloat16_t>();
92+ auto local = ub_buf.Get<bfloat16_t>();
93+ auto* expert_tab = reinterpret_cast<__ubuf__ int32_t*>(tab.GetPhyAddr());
94+ auto* slot_tab = expert_tab + slots;
95+ auto* scratch = reinterpret_cast<__ubuf__ bfloat16_t*>(wqe.GetPhyAddr());
96+ auto* ub = reinterpret_cast<__ubuf__ bfloat16_t*>(local.GetPhyAddr());
97+ Duplicate(wqe, static_cast<bfloat16_t>(0), kUdmaWqeElements);
98+ // SDK WQE construction uses scalar stores through the same raw UB pointer.
99+ // Order the vector clear before those stores; Tensor auto-sync cannot
100+ // infer this pointer handoff. SDK and local-copy events use IDs 0 and 1.
101+ SetFlag<HardEvent::V_S>(EVENT_ID2);
102+ WaitFlag<HardEvent::V_S>(EVENT_ID2);
103+ // Validate the complete plan before this owner submits any payload.
104+ for (int64_t i = 0; i < ranks * slots; ++i) {
105+ if (plan[i] < -1 || plan[i] >= experts) {
106+ AscendC::printf("URMA_PUSH_INVALID_EXPERT rank=%d entry=%ld expert=%d\n",
107+ rank, i, plan[i]);
108+ trap();
109+ }
110+ }
111+ const int64_t max_elements = kUdmaMaxTransferBytes / sizeof(bfloat16_t);
112+ for (int32_t peer = 0; peer < ranks; ++peer) {
113+ int64_t active = 0;
114+ for (int64_t slot = 0; slot < slots; ++slot) {
115+ const int32_t expert = plan[peer * slots + slot];
116+ if (expert >= 0 && expert / epn == rank) {
117+ expert_tab[active] = expert % epn;
118+ slot_tab[active++] = slot;
119+ }
120+ }
121+ for (int64_t i = 0; i < active; ++i) {
122+ __gm__ bfloat16_t* source;
123+ if constexpr (PointerSource) {
124+ source = reinterpret_cast<__gm__ bfloat16_t*>(pointers[expert_tab[i]]);
125+ if (source == nullptr) {
126+ AscendC::printf("URMA_PUSH_NULL_SOURCE rank=%d expert=%d\n",
127+ rank, expert_tab[i]);
128+ trap();
129+ }
130+ } else {
131+ source = home + expert_tab[i] * row_elements;
132+ }
133+ for (int64_t offset = 0; offset < row_elements; offset += max_elements) {
134+ const uint32_t count = static_cast<uint32_t>(
135+ row_elements - offset < max_elements ? row_elements - offset : max_elements);
136+ auto* dst = destination + slot_tab[i] * row_elements + offset;
137+ if (peer == rank) {
138+ UdmaCopyLocalExpertChunk(dst, source + offset, count, ub);
139+ } else {
140+ aclshmemx_udma_put_nbi(dst, source + offset, scratch,
141+ count, peer, EVENT_ID0);
142+ }
143+ }
144+ }
145+ }
146+ // One AIV issues all peers before waiting for their payloads. The SDK has
147+ // finished publishing each UB-staged WQE before put_nbi returns; the WQE
148+ // refers to the retained GM source, not this reusable UB scratch. Queue
149+ // credit and any overflow drain remain owned by the default SDK path.
150+ // No peer-visible publication is permitted until every required quiet has
151+ // returned. The caller's post barrier and consumer events are unchanged.
152+ for (int32_t peer = 0; peer < ranks; ++peer) {
153+ if (peer != rank) {
154+ aclshmemx_udma_quiet(peer);
155+ }
156+ }
157+ aclshmem_quiet();
158+}
159+} // namespace moonep_urma_push
@@ -0,0 +1,35 @@
1+// SPDX-License-Identifier: Apache-2.0
2+ 
3+#include <cstdint>
4+#include <cstdlib>
5+#include <cstring>
6+ 
7+#include "acl/acl.h"
8+#include "kernel_operator.h"
9+#include "shmem.h"
10+ 
11+#include "ascend_moonep/kernels/launch.h"
12+ 
13+using namespace AscendC;
14+ 
15+// Canonical MTE and UDMA GradReduce use one AIV for their WORLD barriers in AIV mode.
16+extern "C" [[bisheng::core_ratio(0, 1)]] __global__ __aicore__
17+void MoonEPGradReduceBarrierAiv(uint64_t ffts_config)
18+{
19+ util_set_ffts_config(ffts_config);
20+ aclshmemx_barrier_all_vec();
21+}
22+ 
23+extern "C" ASCEND_MOONEP_EXPORT int moonep_grad_reduce_native_barrier(void* stream)
24+{
25+ if (stream == nullptr) return ACL_ERROR_INVALID_PARAM;
26+ const char* mode = std::getenv("MOONEP_GRAD_REDUCE_NATIVE_BARRIER_MODE");
27+ if (mode == nullptr || std::strcmp(mode, "mixed") == 0) {
28+ aclshmemx_barrier_all_on_stream(stream);
29+ } else if (std::strcmp(mode, "aiv") == 0) {
30+ MoonEPGradReduceBarrierAiv<<<1, nullptr, stream>>>(shmemx_get_ffts_config());
31+ } else {
32+ return ACL_ERROR_INVALID_PARAM;
33+ }
34+ return aclrtPeekAtLastError(ACL_RT_THREAD_LEVEL);
35+}
@@ -0,0 +1,235 @@
1+// Private L+B provider kernels. These symbols are deliberately absent from
2+// npu_patch.__all__; MindSpeed reaches them through the private extension.
3+ 
4+#include <cstdint>
5+ 
6+#include "acl/acl.h"
7+#include "kernel_operator.h"
8+#include "shmem.h"
9+ 
10+#include "ascend_moonep/kernels/launch.h"
11+#include "opdev/bfloat16.h"
12+ 
13+using namespace AscendC;
14+ 
15+namespace {
16+ 
17+constexpr int32_t kLPlusBUbBytes = 188 * 1024;
18+constexpr uint64_t kLPlusBUbOffset = 64;
19+constexpr int32_t kLPlusBFp32Tile = 12 * 1024;
20+constexpr int32_t kLPlusBFp32TileBytes = kLPlusBFp32Tile * sizeof(float);
21+ 
22+__aicore__ inline int32_t LPlusBWorkerIndex()
23+{
24+ const int32_t sub_blocks = static_cast<int32_t>(GetSubBlockNum());
25+ return sub_blocks > 0 ? static_cast<int32_t>(GetBlockIdx()) / sub_blocks : 0;
26+}
27+ 
28+__aicore__ inline int64_t LPlusBCeilDiv(int64_t value, int64_t divisor)
29+{
30+ return (value + divisor - 1) / divisor;
31+}
32+ 
33+template <typename T>
34+__aicore__ inline LocalTensor<T> LPlusBLocalAt(__ubuf__ T* ptr, int32_t elements, TPosition position)
35+{
36+ LocalTensor<T> tensor;
37+ tensor.address_.logicPos = static_cast<uint8_t>(position);
38+ tensor.address_.bufferAddr = reinterpret_cast<uint64_t>(ptr);
39+ tensor.address_.dataLen = static_cast<uint32_t>((elements * sizeof(T) + 31) & ~31);
40+ return tensor;
41+}
42+ 
43+__aicore__ inline void LPlusBLoadLocalFp32(__ubuf__ float* dst, __gm__ float* src, int32_t elements)
44+{
45+ GlobalTensor<float> source;
46+ source.SetGlobalBuffer(src);
47+ auto local = LPlusBLocalAt(dst, elements, TPosition::VECIN);
48+ DataCopyExtParams params(1, static_cast<uint32_t>(elements * sizeof(float)), 0, 0, 0);
49+ DataCopyPadExtParams<float> pad{false, 0, 0, 0};
50+ DataCopyPad(local, source, params, pad);
51+ PipeBarrier<PIPE_ALL>();
52+}
53+ 
54+__aicore__ inline void LPlusBStoreLocalFp32(__gm__ float* dst, __ubuf__ float* src, int32_t elements)
55+{
56+ GlobalTensor<float> destination;
57+ destination.SetGlobalBuffer(dst);
58+ auto local = LPlusBLocalAt(src, elements, TPosition::VECOUT);
59+ DataCopyExtParams params(1, static_cast<uint32_t>(elements * sizeof(float)), 0, 0, 0);
60+ PipeBarrier<PIPE_ALL>();
61+ DataCopyPad(destination, local, params);
62+ PipeBarrier<PIPE_ALL>();
63+}
64+ 
65+} // namespace
66+ 
67+extern "C" [[bisheng::core_ratio(0, 1)]] __global__ __aicore__
68+void MoonEPLPlusBOwnerPush(
69+ GM_ADDR source_ptrs_addr,
70+ GM_ADDR weight_slots_addr,
71+ GM_ADDR experts_to_copy_addr,
72+ int64_t row_elements,
73+ int32_t local_experts,
74+ int32_t ranks,
75+ int32_t slots,
76+ int32_t rank)
77+{
78+ if ASCEND_IS_AIC {
79+ return;
80+ }
81+ auto* source_ptrs = reinterpret_cast<__gm__ uint64_t*>(source_ptrs_addr);
82+ auto* weight_slots = reinterpret_cast<__gm__ bfloat16_t*>(weight_slots_addr);
83+ auto* plan = reinterpret_cast<__gm__ int32_t*>(experts_to_copy_addr);
84+ const int32_t block = LPlusBWorkerIndex();
85+ const int32_t block_count = GetBlockNum();
86+ const int32_t tile_elements = (kLPlusBUbBytes - static_cast<int32_t>(kLPlusBUbOffset)) /
87+ static_cast<int32_t>(sizeof(bfloat16_t)) / 2;
88+ const int64_t chunks = LPlusBCeilDiv(row_elements, tile_elements);
89+ const int64_t entries = static_cast<int64_t>(ranks) * slots;
90+ const int32_t local_begin = rank * local_experts;
91+ auto* ping = reinterpret_cast<__ubuf__ bfloat16_t*>(kLPlusBUbOffset);
92+ auto* pong = ping + tile_elements;
93+ int32_t buffer = 0;
94+ SetFlag<HardEvent::MTE3_MTE2>(EVENT_ID0);
95+ SetFlag<HardEvent::MTE3_MTE2>(EVENT_ID1);
96+ for (int64_t task = block; task < entries * chunks; task += block_count) {
97+ const int64_t entry = task / chunks;
98+ const int64_t chunk = task % chunks;
99+ const int32_t expert = plan[entry];
100+ if (expert < local_begin || expert >= local_begin + local_experts) {
101+ continue;
102+ }
103+ const int32_t local_expert = expert - local_begin;
104+ const int32_t destination_pe = static_cast<int32_t>(entry / slots);
105+ const int32_t destination_slot = static_cast<int32_t>(entry % slots);
106+ const int64_t begin = chunk * tile_elements;
107+ const int32_t elements = static_cast<int32_t>(
108+ row_elements - begin < tile_elements ? row_elements - begin : tile_elements);
109+ const TEventID event = buffer == 0 ? EVENT_ID0 : EVENT_ID1;
110+ auto* ub = buffer == 0 ? ping : pong;
111+ WaitFlag<HardEvent::MTE3_MTE2>(event);
112+ auto* src = reinterpret_cast<__gm__ bfloat16_t*>(source_ptrs[local_expert]) + begin;
113+ auto* dst = weight_slots + static_cast<int64_t>(destination_slot) * row_elements + begin;
114+ aclshmemx_mte_put_nbi(
115+ dst, src, ub,
116+ static_cast<uint32_t>(tile_elements * sizeof(bfloat16_t)),
117+ static_cast<uint32_t>(elements), destination_pe, event);
118+ SetFlag<HardEvent::MTE3_MTE2>(event);
119+ buffer = 1 - buffer;
120+ }
121+ WaitFlag<HardEvent::MTE3_MTE2>(EVENT_ID0);
122+ WaitFlag<HardEvent::MTE3_MTE2>(EVENT_ID1);
123+ aclshmem_quiet();
124+}
125+ 
126+extern "C" [[bisheng::core_ratio(0, 1)]] __global__ __aicore__
127+void MoonEPLPlusBOwnerReduce(
128+ GM_ADDR target_ptrs_addr,
129+ GM_ADDR grad_slots_addr,
130+ GM_ADDR experts_to_copy_addr,
131+ int64_t row_elements,
132+ int32_t local_experts,
133+ int32_t ranks,
134+ int32_t slots,
135+ int32_t rank)
136+{
137+ if ASCEND_IS_AIC {
138+ return;
139+ }
140+ auto* target_ptrs = reinterpret_cast<__gm__ uint64_t*>(target_ptrs_addr);
141+ auto* grad_slots = reinterpret_cast<__gm__ float*>(grad_slots_addr);
142+ auto* plan = reinterpret_cast<__gm__ int32_t*>(experts_to_copy_addr);
143+ const int32_t block = LPlusBWorkerIndex();
144+ const int32_t block_count = GetBlockNum();
145+ const int32_t local_begin = rank * local_experts;
146+ const int64_t chunks = LPlusBCeilDiv(row_elements, kLPlusBFp32Tile);
147+ auto* accum = reinterpret_cast<__ubuf__ float*>(kLPlusBUbOffset);
148+ auto* remote = reinterpret_cast<__ubuf__ float*>(kLPlusBUbOffset + kLPlusBFp32TileBytes);
149+ auto* zero = reinterpret_cast<__ubuf__ float*>(kLPlusBUbOffset + 2 * kLPlusBFp32TileBytes);
150+ 
151+ for (int32_t local_expert = 0; local_expert < local_experts; ++local_expert) {
152+ const int32_t global_expert = local_begin + local_expert;
153+ auto* target = reinterpret_cast<__gm__ float*>(target_ptrs[local_expert]);
154+ for (int64_t chunk = block; chunk < chunks; chunk += block_count) {
155+ const int64_t begin = chunk * kLPlusBFp32Tile;
156+ const int32_t elements = static_cast<int32_t>(
157+ row_elements - begin < kLPlusBFp32Tile ? row_elements - begin : kLPlusBFp32Tile);
158+ LPlusBLoadLocalFp32(accum, target + begin, elements);
159+ auto accum_in = LPlusBLocalAt(accum, elements, TPosition::VECIN);
160+ auto accum_out = LPlusBLocalAt(accum, elements, TPosition::VECOUT);
161+ for (int32_t pe = 0; pe < ranks; ++pe) {
162+ for (int32_t slot = 0; slot < slots; ++slot) {
163+ if (plan[static_cast<int64_t>(pe) * slots + slot] != global_expert) {
164+ continue;
165+ }
166+ aclshmemx_mte_get_nbi(
167+ remote,
168+ grad_slots + static_cast<int64_t>(slot) * row_elements + begin,
169+ static_cast<uint32_t>(elements), pe, EVENT_ID0);
170+ SetFlag<HardEvent::MTE2_V>(EVENT_ID0);
171+ WaitFlag<HardEvent::MTE2_V>(EVENT_ID0);
172+ auto remote_in = LPlusBLocalAt(remote, elements, TPosition::VECIN);
173+ Add(accum_out, accum_in, remote_in, elements);
174+ PipeBarrier<PIPE_ALL>();
175+ }
176+ }
177+ LPlusBStoreLocalFp32(target + begin, accum, elements);
178+ }
179+ }
180+ 
181+ // All ranks finish remote reads before any rank clears its local slots.
182+ aclshmem_quiet();
183+ aclshmemx_barrier_all_vec();
184+ auto zero_out = LPlusBLocalAt(zero, kLPlusBFp32Tile, TPosition::VECOUT);
185+ Duplicate(zero_out, 0.0F, kLPlusBFp32Tile);
186+ PipeBarrier<PIPE_ALL>();
187+ const int64_t local_elements = static_cast<int64_t>(slots) * row_elements;
188+ const int64_t clear_chunks = LPlusBCeilDiv(local_elements, kLPlusBFp32Tile);
189+ for (int64_t chunk = block; chunk < clear_chunks; chunk += block_count) {
190+ const int64_t begin = chunk * kLPlusBFp32Tile;
191+ const int32_t elements = static_cast<int32_t>(
192+ local_elements - begin < kLPlusBFp32Tile ? local_elements - begin : kLPlusBFp32Tile);
193+ LPlusBStoreLocalFp32(grad_slots + begin, zero, elements);
194+ }
195+}
196+ 
197+extern "C" ASCEND_MOONEP_EXPORT int moonep_lplusb_owner_push(
198+ void* stream, const uint64_t* source_ptrs, void* weight_slots,
199+ const int32_t* experts_to_copy, int64_t row_elements, int32_t local_experts,
200+ int32_t ranks, int32_t slots, int32_t rank, int32_t blocks)
201+{
202+ if (stream == nullptr || source_ptrs == nullptr || weight_slots == nullptr ||
203+ experts_to_copy == nullptr || row_elements <= 0 || local_experts <= 0 ||
204+ ranks <= 0 || slots <= 0 || rank < 0 || rank >= ranks || blocks <= 0 ||
205+ ranks != aclshmem_n_pes()) {
206+ return ACL_ERROR_INVALID_PARAM;
207+ }
208+ (void)aclrtGetLastError(ACL_RT_THREAD_LEVEL);
209+ MoonEPLPlusBOwnerPush<<<blocks, nullptr, stream>>>(
210+ reinterpret_cast<uint8_t*>(const_cast<uint64_t*>(source_ptrs)),
211+ reinterpret_cast<uint8_t*>(weight_slots),
212+ reinterpret_cast<uint8_t*>(const_cast<int32_t*>(experts_to_copy)),
213+ row_elements, local_experts, ranks, slots, rank);
214+ return aclrtPeekAtLastError(ACL_RT_THREAD_LEVEL);
215+}
216+ 
217+extern "C" ASCEND_MOONEP_EXPORT int moonep_lplusb_owner_reduce(
218+ void* stream, const uint64_t* target_ptrs, void* grad_slots,
219+ const int32_t* experts_to_copy, int64_t row_elements, int32_t local_experts,
220+ int32_t ranks, int32_t slots, int32_t rank, int32_t blocks)
221+{
222+ if (stream == nullptr || target_ptrs == nullptr || grad_slots == nullptr ||
223+ experts_to_copy == nullptr || row_elements <= 0 || local_experts <= 0 ||
224+ ranks <= 0 || slots <= 0 || rank < 0 || rank >= ranks || blocks <= 0 ||
225+ ranks != aclshmem_n_pes()) {
226+ return ACL_ERROR_INVALID_PARAM;
227+ }
228+ (void)aclrtGetLastError(ACL_RT_THREAD_LEVEL);
229+ MoonEPLPlusBOwnerReduce<<<blocks, nullptr, stream>>>(
230+ reinterpret_cast<uint8_t*>(const_cast<uint64_t*>(target_ptrs)),
231+ reinterpret_cast<uint8_t*>(grad_slots),
232+ reinterpret_cast<uint8_t*>(const_cast<int32_t*>(experts_to_copy)),
233+ row_elements, local_experts, ranks, slots, rank);
234+ return aclrtPeekAtLastError(ACL_RT_THREAD_LEVEL);
235+}
@@ -36,7 +36,6 @@
36using namespace AscendC;36using namespace AscendC;
37using half_t = __fp16;37using half_t = __fp16;
38using bf16_t = bfloat16_t;38using bf16_t = bfloat16_t;
39-using ascend_moonep::kMoonEPAivNum;
40using ascend_moonep::MoonEPCombineTilingData;39using ascend_moonep::MoonEPCombineTilingData;
41 40 
42namespace {41namespace {
@@ -1044,7 +1043,7 @@ extern "C" ASCEND_MOONEP_EXPORT void moonep_combine_kernel_do(
1044 uint8_t* tiling_host)1043 uint8_t* tiling_host)
1045{1044{
1046 auto* td = reinterpret_cast<MoonEPCombineTilingData*>(tiling_host);1045 auto* td = reinterpret_cast<MoonEPCombineTilingData*>(tiling_host);
1047- moonep_combine_kernel<<<kMoonEPAivNum, nullptr, stream>>>(1046+ moonep_combine_kernel<<<td->block_dim, nullptr, stream>>>(
1048 hidden_buf,1047 hidden_buf,
1049 weight_buf,1048 weight_buf,
1050 dst,1049 dst,
@@ -2,7 +2,7 @@
2// UBMEM implementation — uses SHMEM symmetric window and DataCopyPad + UB/MTE.2// UBMEM implementation — uses SHMEM symmetric window and DataCopyPad + UB/MTE.
3// No URMA/UDMA, no zero-fill.3// No URMA/UDMA, no zero-fill.
4//4//
5-// Architecture: A2/A5, fixed kMoonEPAivNum AIV cores.5+// Architecture: A2/A5, AIV launch width controlled by num_sms.
6//6//
7// Single-kernel design:7// Single-kernel design:
8// Phase 1 (Scatter): cores split routed slots N=S*K.8// Phase 1 (Scatter): cores split routed slots N=S*K.
@@ -19,7 +19,6 @@
19using namespace AscendC;19using namespace AscendC;
20 20 
21using bf16_t = bfloat16_t;21using bf16_t = bfloat16_t;
22-using ascend_moonep::kMoonEPAivNum;
23 22 
24// UB buffer sizing: one bf16 hidden row, weight ping-pong, and route metadata.23// UB buffer sizing: one bf16 hidden row, weight ping-pong, and route metadata.
25// Safety margin: allocate up to 128KB for hidden row (H <= 65536).24// Safety margin: allocate up to 128KB for hidden row (H <= 65536).
@@ -618,6 +617,7 @@ extern "C" [[bisheng::core_ratio(0, 1)]] __global__ __aicore__ void moonep_dispa
618 uint32_t with_weights = tiling.with_weights;617 uint32_t with_weights = tiling.with_weights;
619 618 
620 uint32_t core_idx = get_block_idx();619 uint32_t core_idx = get_block_idx();
620+ uint32_t core_count = get_block_num();
621 621 
622 LocalTensor<uint8_t> ub_base;622 LocalTensor<uint8_t> ub_base;
623 ub_base.address_.logicPos = static_cast<uint8_t>(TPosition::VECIN);623 ub_base.address_.logicPos = static_cast<uint8_t>(TPosition::VECIN);
@@ -635,7 +635,7 @@ extern "C" [[bisheng::core_ratio(0, 1)]] __global__ __aicore__ void moonep_dispa
635 hidden_buf_gm, route_weights_buf_gm,635 hidden_buf_gm, route_weights_buf_gm,
636 S, H, K, tiling.R, NvS,636 S, H, K, tiling.R, NvS,
637 with_weights != 0,637 with_weights != 0,
638- core_idx, kMoonEPAivNum);638+ core_idx, core_count);
639 639 
640 aclshmem_quiet();640 aclshmem_quiet();
641 aclshmemx_barrier_all_vec();641 aclshmemx_barrier_all_vec();
@@ -644,7 +644,7 @@ extern "C" [[bisheng::core_ratio(0, 1)]] __global__ __aicore__ void moonep_dispa
644 644 
645 PlanEpiloguePhase<bf16_t>(645 PlanEpiloguePhase<bf16_t>(
646 ub_base, hbuf, dgrp, dloff, dcnt,646 ub_base, hbuf, dgrp, dloff, dcnt,
647- H, NvS, core_idx, kMoonEPAivNum);647+ H, NvS, core_idx, core_count);
648}648}
649 649 
650 650 
@@ -667,7 +667,7 @@ void moonep_dispatch_kernel_do(
667{667{
668 auto* td = reinterpret_cast<ascend_moonep::MoonEPDispatchTilingData*>(tiling_host);668 auto* td = reinterpret_cast<ascend_moonep::MoonEPDispatchTilingData*>(tiling_host);
669 669 
670- moonep_dispatch_kernel<<<kMoonEPAivNum, nullptr, stream>>>(670+ moonep_dispatch_kernel<<<td->block_dim, nullptr, stream>>>(
671 hidden_sh,671 hidden_sh,
672 route_weights,672 route_weights,
673 dst,673 dst,
@@ -299,7 +299,8 @@ void MoonEPShmemGradReduceFused(
299 int32_t projection,299 int32_t projection,
300 int32_t ranks,300 int32_t ranks,
301 int32_t slots,301 int32_t slots,
302- int32_t rank)302+ int32_t rank,
303+ bool pointer_targets)
303{304{
304 util_set_ffts_config(ffts_addr);305 util_set_ffts_config(ffts_addr);
305 if ASCEND_IS_AIC {306 if ASCEND_IS_AIC {
@@ -307,6 +308,7 @@ void MoonEPShmemGradReduceFused(
307 }308 }
308 309 
309 auto* grads = reinterpret_cast<__gm__ float*>(expert_grads_addr);310 auto* grads = reinterpret_cast<__gm__ float*>(expert_grads_addr);
311+ auto* target_ptrs = reinterpret_cast<__gm__ uint64_t*>(expert_grads_addr);
310 auto* reduce = reinterpret_cast<__gm__ float*>(reduce_buffers_addr);312 auto* reduce = reinterpret_cast<__gm__ float*>(reduce_buffers_addr);
311 auto* plan = reinterpret_cast<__gm__ int32_t*>(experts_to_copy_addr);313 auto* plan = reinterpret_cast<__gm__ int32_t*>(experts_to_copy_addr);
312 const int32_t local_begin = rank * epn;314 const int32_t local_begin = rank * epn;
@@ -324,19 +326,26 @@ void MoonEPShmemGradReduceFused(
324 326 
325 for (int32_t local_expert = 0; local_expert < epn; ++local_expert) {327 for (int32_t local_expert = 0; local_expert < epn; ++local_expert) {
326 const int32_t global_expert = local_begin + local_expert;328 const int32_t global_expert = local_begin + local_expert;
329+ // Adapt pointer targets to the existing dense accumulation contract:
330+ // one expert allocation is a one-row dense view, addressed at row 0.
331+ // Keep global_expert unchanged for matching contributions in the plan.
332+ auto* accum_grads = pointer_targets ?
333+ reinterpret_cast<__gm__ float*>(target_ptrs[local_expert]) :
334+ grads;
335+ const int32_t accum_local_expert = pointer_targets ? 0 : local_expert;
327 for (int64_t tile = block; tile < tiles_per_expert; tile += block_count) {336 for (int64_t tile = block; tile < tiles_per_expert; tile += block_count) {
328 const int64_t tile_begin = tile * kTileElements;337 const int64_t tile_begin = tile * kTileElements;
329 const int32_t elements = static_cast<int32_t>(338 const int32_t elements = static_cast<int32_t>(
330 matrix - tile_begin < kTileElements ?339 matrix - tile_begin < kTileElements ?
331 matrix - tile_begin : kTileElements);340 matrix - tile_begin : kTileElements);
332 AccumulatePlanTile(341 AccumulatePlanTile(
333- grads,342+ accum_grads,
334 reduce,343 reduce,
335 plan,344 plan,
336 accum_ub,345 accum_ub,
337 reduce_ping_ub,346 reduce_ping_ub,
338 reduce_pong_ub,347 reduce_pong_ub,
339- local_expert,348+ accum_local_expert,
340 global_expert,349 global_expert,
341 matrix,350 matrix,
342 tile_begin,351 tile_begin,
@@ -347,27 +356,34 @@ void MoonEPShmemGradReduceFused(
347 }356 }
348 }357 }
349 358 
350- // Every AIV on every rank must reach this collective. Do not add an AIV
351- // early return above it, including for empty plans or blocks with no work.
352 aclshmem_quiet();359 aclshmem_quiet();
353- // This kernel is [[core_ratio(0, 1)]] and launches AIV workers only.360+ if (!pointer_targets) {
354- // The installed CANN-SHMEM generic barrier also includes non-vector361+ // Every AIV on every rank must participate, including idle workers.
355- // participants and deadlocks for this launch shape; use its vector-only362+ // This is an AIV-only kernel; use the vector-only device collective.
356- // device collective so the participant set matches the kernel grid.363+ aclshmemx_barrier_all_vec();
357- aclshmemx_barrier_all_vec();364+ ClearLocalSlots(reduce, plan, accum_ub, matrix, slots, rank,
358- 365+ block, block_count);
359- ClearLocalSlots(366+ }
360- reduce,
361- plan,
362- accum_ub,
363- matrix,
364- slots,
365- rank,
366- block,
367- block_count);
368}367}
369 368 
370-extern "C" ASCEND_MOONEP_EXPORT int moonep_shmem_grad_reduce(369+// Targets use an external barrier before this separate slot-clear kernel.
370+extern "C" [[bisheng::core_ratio(0, 1)]] __global__ __aicore__
371+void MoonEPShmemGradReduceClearValidSlots(
372+ uint64_t ffts_addr, GM_ADDR reduce_buffers_addr,
373+ GM_ADDR experts_to_copy_addr, int64_t matrix, int32_t slots, int32_t rank)
374+{
375+ util_set_ffts_config(ffts_addr);
376+ if ASCEND_IS_AIC {
377+ return;
378+ }
379+ auto* reduce = reinterpret_cast<__gm__ float*>(reduce_buffers_addr);
380+ auto* plan = reinterpret_cast<__gm__ int32_t*>(experts_to_copy_addr);
381+ auto* zero_ub = reinterpret_cast<__ubuf__ float*>(kUbScratchOffset);
382+ ClearLocalSlots(reduce, plan, zero_ub, matrix, slots, rank,
383+ GetWorkerIndex(), GetBlockNum());
384+}
385+ 
386+static int LaunchGradReduce(
371 void* stream,387 void* stream,
372 void* expert_grads,388 void* expert_grads,
373 void* reduce_buffers,389 void* reduce_buffers,
@@ -378,7 +394,8 @@ extern "C" ASCEND_MOONEP_EXPORT int moonep_shmem_grad_reduce(
378 int32_t ranks,394 int32_t ranks,
379 int32_t slots,395 int32_t slots,
380 int32_t rank,396 int32_t rank,
381- int32_t blocks)397+ int32_t blocks,
398+ bool pointer_targets)
382{399{
383 if (stream == nullptr || expert_grads == nullptr ||400 if (stream == nullptr || expert_grads == nullptr ||
384 reduce_buffers == nullptr || experts_to_copy == nullptr ||401 reduce_buffers == nullptr || experts_to_copy == nullptr ||
@@ -404,6 +421,43 @@ extern "C" ASCEND_MOONEP_EXPORT int moonep_shmem_grad_reduce(
404 projection,421 projection,
405 ranks,422 ranks,
406 slots,423 slots,
407- rank);424+ rank,
425+ pointer_targets);
426+ if (!pointer_targets) {
427+ return aclrtPeekAtLastError(ACL_RT_THREAD_LEVEL);
428+ }
429+ auto status = aclrtPeekAtLastError(ACL_RT_THREAD_LEVEL);
430+ if (status != ACL_SUCCESS) {
431+ return status;
432+ }
433+ status = moonep_grad_reduce_native_barrier(stream);
434+ if (status != ACL_SUCCESS) {
435+ return status;
436+ }
437+ MoonEPShmemGradReduceClearValidSlots<<<blocks, nullptr, stream>>>(
438+ shmemx_get_ffts_config(),
439+ reinterpret_cast<std::uint8_t*>(reduce_buffers),
440+ reinterpret_cast<std::uint8_t*>(const_cast<int32_t*>(experts_to_copy)),
441+ static_cast<int64_t>(hidden) * projection, slots, rank);
408 return aclrtPeekAtLastError(ACL_RT_THREAD_LEVEL);442 return aclrtPeekAtLastError(ACL_RT_THREAD_LEVEL);
409}443}
444+ 
445+extern "C" ASCEND_MOONEP_EXPORT int moonep_shmem_grad_reduce(
446+ void* stream, void* expert_grads, void* reduce_buffers,
447+ const int32_t* experts_to_copy, int32_t epn, int32_t hidden,
448+ int32_t projection, int32_t ranks, int32_t slots, int32_t rank,
449+ int32_t blocks)
450+{
451+ return LaunchGradReduce(stream, expert_grads, reduce_buffers, experts_to_copy,
452+ epn, hidden, projection, ranks, slots, rank, blocks, false);
453+}
454+ 
455+extern "C" ASCEND_MOONEP_EXPORT int moonep_shmem_grad_reduce_targets(
456+ void* stream, void* target_ptrs, void* reduce_buffers,
457+ const int32_t* experts_to_copy, int32_t epn, int32_t hidden,
458+ int32_t projection, int32_t ranks, int32_t slots, int32_t rank,
459+ int32_t blocks)
460+{
461+ return LaunchGradReduce(stream, target_ptrs, reduce_buffers, experts_to_copy,
462+ epn, hidden, projection, ranks, slots, rank, blocks, true);
463+}
@@ -53,6 +53,21 @@ __aicore__ inline void ComputeSingle(
53 53 
54using namespace moonEP::gradReduce;54using namespace moonEP::gradReduce;
55 55 
56+extern "C" [[bisheng::core_ratio(0, 1)]] __global__ __aicore__
57+void MoonEPShmemClearValidGradSlots(
58+ GM_ADDR reduce_addr, GM_ADDR plan_addr, int64_t matrix, int32_t slots, int32_t rank)
59+{
60+ AscendC::TPipe pipe; // experimental explicit InitOutput resource lifetime
61+ auto* plan = reinterpret_cast<__gm__ int32_t*>(plan_addr);
62+ GlobalTensor<float> reduce;
63+ reduce.SetGlobalBuffer(reinterpret_cast<__gm__ float*>(reduce_addr));
64+ for (int32_t slot = 0; slot < slots; ++slot) {
65+ if (plan[static_cast<int64_t>(rank) * slots + slot] >= 0) {
66+ InitOutput(reduce[static_cast<int64_t>(slot) * matrix], matrix, 0.0f);
67+ }
68+ }
69+}
70+ 
56extern "C" [[bisheng::core_ratio(0, 1)]] __global__ __aicore__71extern "C" [[bisheng::core_ratio(0, 1)]] __global__ __aicore__
57void MoonEPShmemGradReduceUdmaFused(72void MoonEPShmemGradReduceUdmaFused(
58 uint64_t ffts_addr,73 uint64_t ffts_addr,
@@ -65,7 +80,8 @@ void MoonEPShmemGradReduceUdmaFused(
65 int32_t projection,80 int32_t projection,
66 int32_t ranks,81 int32_t ranks,
67 int32_t slots,82 int32_t slots,
68- int32_t rank)83+ int32_t rank,
84+ bool pointer_targets)
69{85{
70 util_set_ffts_config(ffts_addr);86 util_set_ffts_config(ffts_addr);
71 87 
@@ -74,6 +90,7 @@ void MoonEPShmemGradReduceUdmaFused(
74 const int64_t matrix = static_cast<int64_t>(hidden) * projection;90 const int64_t matrix = static_cast<int64_t>(hidden) * projection;
75 91 
76 auto* grads = reinterpret_cast<__gm__ float*>(expert_grads_addr);92 auto* grads = reinterpret_cast<__gm__ float*>(expert_grads_addr);
93+ auto* target_ptrs = reinterpret_cast<__gm__ uint64_t*>(expert_grads_addr);
77 auto* reduce = reinterpret_cast<__gm__ float*>(reduce_buffers_addr);94 auto* reduce = reinterpret_cast<__gm__ float*>(reduce_buffers_addr);
78 auto* plan = reinterpret_cast<__gm__ int32_t*>(experts_to_copy_addr);95 auto* plan = reinterpret_cast<__gm__ int32_t*>(experts_to_copy_addr);
79 auto* workspace = reinterpret_cast<__gm__ float*>(workspace_addr) + coreIdx * OUTER_LOOP_SIZE;96 auto* workspace = reinterpret_cast<__gm__ float*>(workspace_addr) + coreIdx * OUTER_LOOP_SIZE;
@@ -101,6 +118,12 @@ void MoonEPShmemGradReduceUdmaFused(
101 if (dstRankIdx != rank) {118 if (dstRankIdx != rank) {
102 continue;119 continue;
103 }120 }
121+ // Adapt each canonical allocation as a one-expert dense view,
122+ // just like the MTE kernel; leave the reduction itself unchanged.
123+ auto* accum_grads = pointer_targets ?
124+ reinterpret_cast<__gm__ float*>(target_ptrs[dstExpertIdx]) :
125+ grads;
126+ const int32_t accum_local_expert = pointer_targets ? 0 : dstExpertIdx;
104 127 
105 for (int64_t slotOffset = 0; slotOffset < matrix; slotOffset += OUTER_LOOP_SIZE)128 for (int64_t slotOffset = 0; slotOffset < matrix; slotOffset += OUTER_LOOP_SIZE)
106 {129 {
@@ -108,29 +131,31 @@ void MoonEPShmemGradReduceUdmaFused(
108 if (srcRankIdx != dstRankIdx) {131 if (srcRankIdx != dstRankIdx) {
109 aclshmemx_udma_get_nbi((__gm__ uint8_t*)(workspace), (__gm__ uint8_t*)(reduce + srcSlotIdx * matrix + slotOffset), wqe_scratch, loopSize * sizeof(float), srcRankIdx, 0);132 aclshmemx_udma_get_nbi((__gm__ uint8_t*)(workspace), (__gm__ uint8_t*)(reduce + srcSlotIdx * matrix + slotOffset), wqe_scratch, loopSize * sizeof(float), srcRankIdx, 0);
110 aclshmemx_udma_quiet(srcRankIdx);133 aclshmemx_udma_quiet(srcRankIdx);
111- ComputeSingle(grads + dstExpertIdx * matrix + slotOffset, workspace, ubLocal, loopSize);134+ ComputeSingle(accum_grads + accum_local_expert * matrix + slotOffset, workspace, ubLocal, loopSize);
112 } else {135 } else {
113- ComputeSingle(grads + dstExpertIdx * matrix + slotOffset, reduce + srcSlotIdx * matrix + slotOffset, ubLocal, loopSize);136+ ComputeSingle(accum_grads + accum_local_expert * matrix + slotOffset, reduce + srcSlotIdx * matrix + slotOffset, ubLocal, loopSize);
114 }137 }
115 }138 }
116 }139 }
117 }140 }
118 141 
119 aclshmem_quiet();142 aclshmem_quiet();
120- aclshmemx_barrier_all_vec();143+ if (!pointer_targets) {
121- 144+ // Every AIV participates before core 0 clears the local source slots.
122- if (coreIdx == 0) {145+ aclshmemx_barrier_all_vec();
123- GlobalTensor<float> reduceGm_;146+ if (coreIdx == 0) {
124- reduceGm_.SetGlobalBuffer(reduce);147+ GlobalTensor<float> reduceGm_;
125- for (int32_t localIdx = 0; localIdx < slots; localIdx++) {148+ reduceGm_.SetGlobalBuffer(reduce);
126- if (plan[rank * slots + localIdx] >= 0) {149+ for (int32_t localIdx = 0; localIdx < slots; localIdx++) {
127- InitOutput(reduceGm_[localIdx * matrix], matrix, 0.0f);150+ if (plan[rank * slots + localIdx] >= 0) {
151+ InitOutput(reduceGm_[localIdx * matrix], matrix, 0.0f);
152+ }
128 }153 }
129 }154 }
130 }155 }
131}156}
132 157 
133-extern "C" ASCEND_MOONEP_EXPORT int moonep_shmem_grad_reduce_udma(158+static int LaunchGradReduceUdma(
134 void* stream,159 void* stream,
135 void* expert_grads,160 void* expert_grads,
136 void* reduce_buffers,161 void* reduce_buffers,
@@ -142,7 +167,8 @@ extern "C" ASCEND_MOONEP_EXPORT int moonep_shmem_grad_reduce_udma(
142 int32_t ranks,167 int32_t ranks,
143 int32_t slots,168 int32_t slots,
144 int32_t rank,169 int32_t rank,
145- int32_t blocks)170+ int32_t blocks,
171+ bool pointer_targets)
146{172{
147 if (stream == nullptr || expert_grads == nullptr ||173 if (stream == nullptr || expert_grads == nullptr ||
148 reduce_buffers == nullptr || experts_to_copy == nullptr ||174 reduce_buffers == nullptr || experts_to_copy == nullptr ||
@@ -152,7 +178,15 @@ extern "C" ASCEND_MOONEP_EXPORT int moonep_shmem_grad_reduce_udma(
152 return ACL_ERROR_INVALID_PARAM;178 return ACL_ERROR_INVALID_PARAM;
153 }179 }
154 180 
155- (void)aclrtGetLastError(ACL_RT_THREAD_LEVEL);181+ if (pointer_targets) {
182+ // Preserve an existing error instead of erasing the first failure.
183+ const auto status = aclrtPeekAtLastError(ACL_RT_THREAD_LEVEL);
184+ if (status != ACL_SUCCESS) {
185+ return status;
186+ }
187+ } else {
188+ (void)aclrtGetLastError(ACL_RT_THREAD_LEVEL);
189+ }
156 const int32_t shmem_ranks = aclshmem_n_pes();190 const int32_t shmem_ranks = aclshmem_n_pes();
157 if (shmem_ranks <= 0 || ranks != shmem_ranks) {191 if (shmem_ranks <= 0 || ranks != shmem_ranks) {
158 return ACL_ERROR_INVALID_PARAM;192 return ACL_ERROR_INVALID_PARAM;
@@ -160,15 +194,47 @@ extern "C" ASCEND_MOONEP_EXPORT int moonep_shmem_grad_reduce_udma(
160 194 
161 MoonEPShmemGradReduceUdmaFused<<<blocks, nullptr, stream>>>(195 MoonEPShmemGradReduceUdmaFused<<<blocks, nullptr, stream>>>(
162 shmemx_get_ffts_config(),196 shmemx_get_ffts_config(),
163- reinterpret_cast<std::uint8_t*>(expert_grads),197+ reinterpret_cast<uint8_t*>(expert_grads),
164- reinterpret_cast<std::uint8_t*>(reduce_buffers),198+ reinterpret_cast<uint8_t*>(reduce_buffers),
165- reinterpret_cast<std::uint8_t*>(workspace),199+ reinterpret_cast<uint8_t*>(workspace),
166- reinterpret_cast<std::uint8_t*>(const_cast<int32_t*>(experts_to_copy)),200+ reinterpret_cast<uint8_t*>(const_cast<int32_t*>(experts_to_copy)),
167- epn,201+ epn, hidden, projection, ranks, slots, rank, pointer_targets);
168- hidden,202+ 
169- projection,203+ if (!pointer_targets) {
170- ranks,204+ return aclrtPeekAtLastError(ACL_RT_THREAD_LEVEL);
171- slots,205+ }
172- rank);206+ auto status = aclrtPeekAtLastError(ACL_RT_THREAD_LEVEL);
207+ if (status != ACL_SUCCESS) {
208+ return status;
209+ }
210+ // Every peer must finish reading before any rank clears its source slots.
211+ status = moonep_grad_reduce_native_barrier(stream);
212+ if (status != ACL_SUCCESS) {
213+ return status;
214+ }
215+ MoonEPShmemClearValidGradSlots<<<1, nullptr, stream>>>(
216+ reinterpret_cast<uint8_t*>(reduce_buffers),
217+ reinterpret_cast<uint8_t*>(const_cast<int32_t*>(experts_to_copy)),
218+ static_cast<int64_t>(hidden) * projection, slots, rank);
173 return aclrtPeekAtLastError(ACL_RT_THREAD_LEVEL);219 return aclrtPeekAtLastError(ACL_RT_THREAD_LEVEL);
174}220}
221+ 
222+extern "C" ASCEND_MOONEP_EXPORT int moonep_shmem_grad_reduce_udma(
223+ void* stream, void* expert_grads, void* reduce_buffers, void* workspace,
224+ const int32_t* experts_to_copy, int32_t epn, int32_t hidden,
225+ int32_t projection, int32_t ranks, int32_t slots, int32_t rank,
226+ int32_t blocks)
227+{
228+ return LaunchGradReduceUdma(stream, expert_grads, reduce_buffers, workspace,
229+ experts_to_copy, epn, hidden, projection, ranks, slots, rank, blocks, false);
230+}
231+ 
232+extern "C" ASCEND_MOONEP_EXPORT int moonep_shmem_grad_reduce_targets_udma(
233+ void* stream, void* target_ptrs, void* reduce_buffers, void* workspace,
234+ const int32_t* experts_to_copy, int32_t epn, int32_t hidden,
235+ int32_t projection, int32_t ranks, int32_t slots, int32_t rank,
236+ int32_t blocks)
237+{
238+ return LaunchGradReduceUdma(stream, target_ptrs, reduce_buffers, workspace,
239+ experts_to_copy, epn, hidden, projection, ranks, slots, rank, blocks, true);
240+}
@@ -0,0 +1,50 @@
1+// SPDX-License-Identifier: Apache-2.0
2+#include "ascend_moonep/kernels/launch.h"
3+#include "acl/acl.h"
4+#if defined(CATLASS_ARCH) && CATLASS_ARCH == 3510
5+#include "ascend_moonep/kernels/urma_push_core.h"
6+extern "C" [[bisheng::core_ratio(0, 1)]] __global__ __aicore__
7+void prefetch_barrier_vec(uint64_t ffts_config) {
8+ util_set_ffts_config(ffts_config);
9+ aclshmemx_barrier_all_vec();
10+}
11+extern "C" ASCEND_MOONEP_EXPORT int moonep_prefetch_barrier_vec(void* stream) {
12+ if (stream == nullptr) return ACL_ERROR_INVALID_PARAM;
13+ prefetch_barrier_vec<<<1,nullptr,stream>>>(shmemx_get_ffts_config());
14+ return aclrtPeekAtLastError(ACL_RT_THREAD_LEVEL);
15+}
16+// Separate name makes the async-lane domain distinguishable from prefetch
17+// completion and ordered GradReduce in the device trace. Same SDK team/state.
18+extern "C" [[bisheng::core_ratio(0, 1)]] __global__ __aicore__
19+void async_stream_barrier_vec(uint64_t ffts_config) {
20+ util_set_ffts_config(ffts_config);
21+ aclshmemx_barrier_all_vec();
22+}
23+extern "C" ASCEND_MOONEP_EXPORT int moonep_async_stream_barrier_vec(void* stream) {
24+ if (stream == nullptr) return ACL_ERROR_INVALID_PARAM;
25+ async_stream_barrier_vec<<<1,nullptr,stream>>>(shmemx_get_ffts_config());
26+ return aclrtPeekAtLastError(ACL_RT_THREAD_LEVEL);
27+}
28+extern "C" [[bisheng::core_ratio(0, 1)]] __global__ __aicore__
29+void prefetch_pointer_push_udma(GM_ADDR pointers, GM_ADDR slots, GM_ADDR plan,
30+ int64_t experts, int64_t row_elements, int64_t num_slots) {
31+ moonep_urma_push::Run<true>(pointers,slots,plan,experts,row_elements,num_slots);
32+}
33+extern "C" ASCEND_MOONEP_EXPORT int prefetch_pointer_push_udma_available() { return 1; }
34+extern "C" ASCEND_MOONEP_EXPORT int moonep_prefetch_pointer_push_udma(
35+ void* stream, uint8_t* pointers, uint8_t* slots, uint8_t* plan,
36+ int64_t experts, int64_t row_elements, int64_t num_slots) {
37+ const auto status = aclrtPeekAtLastError(ACL_RT_THREAD_LEVEL);
38+ if (status != ACL_SUCCESS) {
39+ return status;
40+ }
41+ prefetch_pointer_push_udma<<<1,nullptr,stream>>>(pointers,slots,plan,experts,row_elements,num_slots);
42+ return aclrtPeekAtLastError(ACL_RT_THREAD_LEVEL);
43+}
44+#else
45+extern "C" ASCEND_MOONEP_EXPORT int moonep_prefetch_barrier_vec(void*) { return -1; }
46+extern "C" ASCEND_MOONEP_EXPORT int moonep_async_stream_barrier_vec(void*) { return -1; }
47+extern "C" ASCEND_MOONEP_EXPORT int prefetch_pointer_push_udma_available() { return 0; }
48+extern "C" ASCEND_MOONEP_EXPORT int moonep_prefetch_pointer_push_udma(
49+ void*,uint8_t*,uint8_t*,uint8_t*,int64_t,int64_t,int64_t) { return -1; }
50+#endif
@@ -0,0 +1,27 @@
1+// SPDX-License-Identifier: Apache-2.0
2+#include "ascend_moonep/kernels/launch.h"
3+#include "acl/acl.h"
4+#if defined(CATLASS_ARCH) && CATLASS_ARCH == 3510
5+#include "ascend_moonep/kernels/urma_push_core.h"
6+extern "C" [[bisheng::core_ratio(0, 1)]] __global__ __aicore__
7+void prefetch_weight_push_udma(GM_ADDR source, GM_ADDR slots, GM_ADDR plan,
8+ int64_t experts, int64_t row_elements, int64_t num_slots) {
9+ moonep_urma_push::Run<false>(source, slots, plan, experts, row_elements, num_slots);
10+}
11+extern "C" ASCEND_MOONEP_EXPORT int prefetch_weight_push_udma_available() { return 1; }
12+extern "C" ASCEND_MOONEP_EXPORT int prefetch_weight_push_udma_do(
13+ void* stream, uint8_t* source, uint8_t* slots, uint8_t* plan,
14+ int64_t experts, int64_t row_elements, int64_t num_slots) {
15+ const auto status = aclrtPeekAtLastError(ACL_RT_THREAD_LEVEL);
16+ if (status != ACL_SUCCESS) {
17+ return status;
18+ }
19+ prefetch_weight_push_udma<<<1, nullptr, stream>>>(
20+ source, slots, plan, experts, row_elements, num_slots);
21+ return aclrtPeekAtLastError(ACL_RT_THREAD_LEVEL);
22+}
23+#else
24+extern "C" ASCEND_MOONEP_EXPORT int prefetch_weight_push_udma_available() { return 0; }
25+extern "C" ASCEND_MOONEP_EXPORT int prefetch_weight_push_udma_do(
26+ void*, uint8_t*, uint8_t*, uint8_t*, int64_t, int64_t, int64_t) { return -1; }
27+#endif
@@ -0,0 +1,95 @@
1+"""Storage parameters for the native Buffer API, without a scheduling protocol.
2+ 
3+Allocate/register symmetric sources before SHMEM init; prepare these bindings
4+after init and before hot work. The caller still owns final-use/reuse ordering.
5+"""
6+ 
7+from dataclasses import dataclass
8+ 
9+import torch
10+ 
11+from .buffer_c import sym_tensor
12+from .shmem_runtime import ShmemRuntime
13+ 
14+ 
15+def tensor_signature(tensor):
16+ """Metadata only: detect rebinding without reading device data/versions."""
17+ storage = tensor.untyped_storage()
18+ return (tensor.data_ptr(), tuple(tensor.shape), tuple(tensor.stride()),
19+ tensor.storage_offset(), tensor.dtype, tensor.device,
20+ storage._cdata, storage.nbytes())
21+ 
22+ 
23+def symmetric_source(source):
24+ if not ShmemRuntime.is_initialized():
25+ raise RuntimeError("initialize buffer-backed SHMEM before preparing bindings")
26+ if getattr(source, '_vmm_allocation', None) is None:
27+ raise ValueError("expected a registered VMM source tensor")
28+ return sym_tensor(source)
29+ 
30+ 
31+def overlaps(left, right):
32+ if left.device != right.device:
33+ return False
34+ a, b = left.data_ptr(), right.data_ptr()
35+ return (a < b + right.numel() * right.element_size() and
36+ b < a + left.numel() * left.element_size())
37+ 
38+ 
39+@dataclass(frozen=True, eq=False, repr=False)
40+class CommBuffers:
41+ """Prepared hidden/route views. Obtain with Buffer.prepare_comm_buffers.
42+ 
43+ No allocation, lease, generation or completion state is owned by this value.
44+ Backing references keep the original source metadata/physical owners alive;
45+ callers must keep the tensors' storage and layout fixed while bound.
46+ """
47+ 
48+ hidden: torch.Tensor
49+ route: torch.Tensor
50+ sources: tuple
51+ owner: object
52+ 
53+ 
54+@dataclass(frozen=True, eq=False, repr=False)
55+class LPlusBBinding:
56+ """L ordinary canonical matrices plus one symmetric B-slot projection.
57+ 
58+ Pointer metadata is prepared once. Retain this value and the Buffer until
59+ completion, and order all slot consumers before reusing the destination.
60+ """
61+ 
62+ refs: tuple
63+ sources: tuple
64+ slot: torch.Tensor
65+ slot_source: torch.Tensor
66+ table: torch.Tensor
67+ ref_signatures: tuple
68+ owner: object
69+ 
70+ def validate_refs(self, refs):
71+ """Reject a caller that switched canonical matrices after setup."""
72+ validate_unchanged(tuple(refs), self.ref_signatures)
73+ 
74+ 
75+def validate_unchanged(refs, signatures):
76+ if tuple(tensor_signature(ref) for ref in refs) != signatures:
77+ raise ValueError("prepared storage was rebound or its layout changed")
78+ 
79+ 
80+def comm_context(ctx, buffers, owner, carrier):
81+ """Select the symmetric data banks for one call, sharing control and workspace.
82+ 
83+ Each EP rank must select the corresponding banks for the collective.
84+ The caller orders submissions that share the workspace.
85+ """
86+ if not ShmemRuntime.is_initialized() or getattr(ShmemRuntime, '_poisoned', False):
87+ raise RuntimeError('explicit communication storage requires initialized healthy SHMEM')
88+ if not isinstance(buffers, CommBuffers) or buffers.owner is not owner:
89+ raise ValueError("comm_buffers must be prepared by this Buffer")
90+ n, h = int(ctx['NvS']), int(ctx['H'])
91+ local = dict(ctx)
92+ local['_native_comm_buffers'] = True
93+ local['hidden_buf'] = local['hidden_buf_local'] = carrier(buffers.hidden, (n, h), torch.bfloat16)
94+ local['weights_buf'] = local['weights_buf_local'] = carrier(buffers.route, (n,), torch.int32)
95+ return local
@@ -18,6 +18,7 @@ from .launchers import (
18 launch_dispatch_op,18 launch_dispatch_op,
19 launch_dispatch_profile_op,19 launch_dispatch_profile_op,
20 launch_grad_reduce,20 launch_grad_reduce,
21+ launch_grad_reduce_targets,
21 launch_planning_op,22 launch_planning_op,
22 launch_prefetch,23 launch_prefetch,
23)24)
@@ -153,6 +154,7 @@ class DispatchOp(KernelOp):
153 (dest = aclshmem_ptr(ctx['hidden_buf'].data_ptr(), drank) + loff*H*2),154 (dest = aclshmem_ptr(ctx['hidden_buf'].data_ptr(), drank) + loff*H*2),
154 writes weights into ctx['weights_buf'] (remote rank's symmetric chunk).155 writes weights into ctx['weights_buf'] (remote rank's symmetric chunk).
155 - build_dedup_map True only right after fresh planning.156 - build_dedup_map True only right after fresh planning.
157+ - MTE launch width follows self.num_sms; UDMA keeps its fixed schedule.
156 - shmem_instance_id: shmem runtime instance to operate on (default 0; the158 - shmem_instance_id: shmem runtime instance to operate on (default 0; the
157 shmem Python API currently supports a single instance).159 shmem Python API currently supports a single instance).
158 v1 degrade: host put segment scatter per plan.dst ranges.160 v1 degrade: host put segment scatter per plan.dst ranges.
@@ -180,6 +182,7 @@ class DispatchOp(KernelOp):
180 int(ctx["R"]),182 int(ctx["R"]),
181 int(ctx["rank"]),183 int(ctx["rank"]),
182 plan.dedup_mode == "server",184 plan.dedup_mode == "server",
185+ num_sms=self.num_sms,
183 )186 )
184 187 
185 def compute_profile(self, ctx, hidden_sh, route_weights_sk, plan,188 def compute_profile(self, ctx, hidden_sh, route_weights_sk, plan,
@@ -220,6 +223,7 @@ class CombineOp(KernelOp):
220 output_sk [S, K] fp32223 output_sk [S, K] fp32
221 - launcher selects native / legacy-rank UDMA / server-dedup UDMA224 - launcher selects native / legacy-rank UDMA / server-dedup UDMA
222 from the environment and the plan's dedup mode225 from the environment and the plan's dedup mode
226+ - MTE launch width follows self.num_sms; UDMA keeps its fixed schedule
223 """227 """
224 228 
225 def compute(self, ctx, output_sh, plan, output_sk=None,229 def compute(self, ctx, output_sh, plan, output_sk=None,
@@ -252,6 +256,7 @@ class CombineOp(KernelOp):
252 int(ctx["R"]),256 int(ctx["R"]),
253 int(ctx["rank"]),257 int(ctx["rank"]),
254 server_dedup=server_dedup,258 server_dedup=server_dedup,
259+ num_sms=self.num_sms,
255 )260 )
256 261 
257class PrefetchOp(KernelOp):262class PrefetchOp(KernelOp):
@@ -317,6 +322,17 @@ class GradReduceOp(KernelOp):
317 - shmem_instance_id: shmem runtime instance to operate on (default 0; the322 - shmem_instance_id: shmem runtime instance to operate on (default 0; the
318 shmem Python API currently supports a single instance).323 shmem Python API currently supports a single instance).
319 Cross-rank: home rank gets each peer's reduce-buffer rows (host get / RMA).324 Cross-rank: home rank gets each peer's reduce-buffer rows (host get / RMA).
325+ 
326+ compute_targets(ctx, target_ptrs, reduce_buffer, experts_to_copy, rank,
327+ num_sms, shmem_instance_id=0):
328+ - explicit alternative for setup-frozen INT64 [epn] canonical pointers;
329+ no method or launcher selects this contract by inspecting dtype.
330+ - targets are ordinary local contiguous FP32 [H,H'] matrices, disjoint,
331+ address-stable and kept alive by the caller until completion.
332+ - only the [B,H,H'] source bank must be symmetric. MTE is ordered.
333+ Canonical UDMA uses the fused atomic-add kernel with unspecified
334+ accumulation order and setup-owned ctx['_grad_reduce_target_workspace'].
335+ Canonical targets use pre/post barriers and clear only valid source slots.
320 """336 """
321 337 
322 def compute(self, ctx, full_grad_home, reduce_buffer, experts_to_copy,338 def compute(self, ctx, full_grad_home, reduce_buffer, experts_to_copy,
@@ -369,3 +385,31 @@ class GradReduceOp(KernelOp):
369 barrier_off=0,385 barrier_off=0,
370 grid_sync_bar=None,386 grid_sync_bar=None,
371 )387 )
388+ 
389+ def compute_targets(self, ctx, target_ptrs, reduce_buffer, experts_to_copy,
390+ rank, num_sms, shmem_instance_id: int = 0):
391+ """Reduce symmetric slots into explicitly supplied canonical pointers."""
392+ R = int(ctx["R"]); E = int(ctx["E"]); B = int(ctx["B"])
393+ if R <= 0 or E % R:
394+ raise RuntimeError(f"invalid expert layout for grad reduce: E={E}, R={R}")
395+ epn = E // R
396+ if reduce_buffer.ndim != 3:
397+ raise ValueError("GradReduceOp.compute_targets: reduce_buffer must be [B,H,H_prime]")
398+ H, H_prime = map(int, reduce_buffer.shape[1:])
399+ _collect_inputs(
400+ "GradReduceOp.compute_targets",
401+ tensors=(
402+ ("canonical target pointers", target_ptrs, [epn], torch.int64),
403+ ("reduce_buffer", reduce_buffer, [B, H, H_prime], torch.float32),
404+ ("experts_to_copy", experts_to_copy, [R, B], torch.int32),
405+ ),
406+ scalars=(("rank", rank), ("num_sms", num_sms),
407+ ("shmem_instance_id", shmem_instance_id)),
408+ )
409+ workspace = ctx.get('_grad_reduce_target_workspace')
410+ launch_args = {} if workspace is None else {'udma_workspace': workspace}
411+ if '_grad_reduce_use_udma' in ctx:
412+ launch_args['use_udma'] = ctx['_grad_reduce_use_udma']
413+ launch_grad_reduce_targets(
414+ target_ptrs, reduce_buffer, experts_to_copy,
415+ rank=int(rank), num_sms=int(num_sms), **launch_args)
@@ -43,7 +43,12 @@ class MoonEPCommPlan:
43 # so rebuilding a different plan does not invalidate independent snapshots.43 # so rebuilding a different plan does not invalidate independent snapshots.
44 _planning_generation: int = field(default=0, repr=False, compare=False)44 _planning_generation: int = field(default=0, repr=False, compare=False)
45 45 
46+ cu_seqlens: torch.Tensor | None = None
47+ 
46 def __post_init__(self) -> None:48 def __post_init__(self) -> None:
49+ if self.cu_seqlens is not None:
50+ assert self.cu_seqlens.dtype == torch.int32 and self.cu_seqlens.is_contiguous()
51+ assert tuple(self.cu_seqlens.shape) == (int(self.E) + int(self.B),)
47 N = int(self.N)52 N = int(self.N)
48 R = int(self.R)53 R = int(self.R)
49 E = int(self.E)54 E = int(self.E)
@@ -90,6 +95,7 @@ class MoonEPCommPlan:
90 stream.wait_event(execution.ready)95 stream.wait_event(execution.ready)
91 snapshot = type(self)(96 snapshot = type(self)(
92 dst=self.dst.clone(),97 dst=self.dst.clone(),
98+ cu_seqlens=self.cu_seqlens.clone() if self.cu_seqlens is not None else None,
93 experts_to_copy=self.experts_to_copy.clone(),99 experts_to_copy=self.experts_to_copy.clone(),
94 zero_fill_ranges=self.zero_fill_ranges.clone(),100 zero_fill_ranges=self.zero_fill_ranges.clone(),
95 remote_stats=self.remote_stats.clone(),101 remote_stats=self.remote_stats.clone(),
@@ -109,10 +115,11 @@ class MoonEPCommPlan:
109 ready = torch_npu.npu.Event()115 ready = torch_npu.npu.Event()
110 ready.record(stream)116 ready.record(stream)
111 for plan in (self, snapshot):117 for plan in (self, snapshot):
112- for tensor in (plan.dst, plan.experts_to_copy, plan.zero_fill_ranges,118+ for tensor in (plan.dst, plan.cu_seqlens, plan.experts_to_copy,
113- plan.remote_stats, plan.dup_groups, plan.dup_loffs,119+ plan.zero_fill_ranges, plan.remote_stats, plan.dup_groups,
114- plan.dup_counts):120+ plan.dup_loffs, plan.dup_counts):
115- tensor.record_stream(stream)121+ if tensor is not None:
122+ tensor.record_stream(stream)
116 execution.storage.record_stream(stream)123 execution.storage.record_stream(stream)
117 storage.record_stream(stream)124 storage.record_stream(stream)
118 copied_execution = CombineExecutionPlan(125 copied_execution = CombineExecutionPlan(
@@ -146,6 +153,10 @@ def _key(ctx):
146 return tuple(int(ctx[name]) for name in ('S', 'H', 'K', 'R', 'rank'))153 return tuple(int(ctx[name]) for name in ('S', 'H', 'K', 'R', 'rank'))
147 154 
148 155 
156+def _combine_workspace_layout(ctx):
157+ return (int(ctx['NvS']), int(ctx['H']), int(ctx['R']))
158+ 
159+ 
149def _execution_key(ctx):160def _execution_key(ctx):
150 # Keep the five native launch arguments stable. The local cached-plan key161 # Keep the five native launch arguments stable. The local cached-plan key
151 # also binds the private ring ABI and workspace geometry.162 # also binds the private ring ABI and workspace geometry.
@@ -172,12 +183,18 @@ class CombineExecutionPlan:
172 fused: bool = False183 fused: bool = False
173 184 
174 def validate(self, ctx, plan):185 def validate(self, ctx, plan):
175- if ctx is not self.owner_ctx or _execution_key(ctx) != self.key:186+ # Buffer launches use fresh logical views over the same capacity owner.
187+ # Activation banks may change between dispatch, forward and backward
188+ # combine; the immutable routing snapshot contains no bank addresses.
189+ owner = self.owner_ctx.get('_capacity_ctx', self.owner_ctx)
190+ if ctx.get('_capacity_ctx', ctx) is not owner or _execution_key(ctx) != self.key:
176 raise ValueError('execution plan belongs to a different Buffer/topology/shape')191 raise ValueError('execution plan belongs to a different Buffer/topology/shape')
177 if ctx['combine_workspace'].data_ptr() != self.workspace.data_ptr():192 if ctx['combine_workspace'].data_ptr() != self.workspace.data_ptr():
178 raise ValueError('combine workspace changed; collectively prepare a new plan')193 raise ValueError('combine workspace changed; collectively prepare a new plan')
179 if id(plan) != self.routing_id or tuple(map(_stamp, _routes(plan))) != self.route_stamps:194 if id(plan) != self.routing_id or tuple(map(_stamp, _routes(plan))) != self.route_stamps:
180 raise ValueError('routing changed; all ranks must prepare a new execution plan')195 raise ValueError('routing changed; all ranks must prepare a new execution plan')
196+ if plan.combine_execution_plan is not self:
197+ raise ValueError('execution plan was replaced; collectively prepare a new plan')
181 if plan._planning_generation != self.generation:198 if plan._planning_generation != self.generation:
182 raise ValueError('planning was rerun; all ranks must prepare a new execution plan')199 raise ValueError('planning was rerun; all ranks must prepare a new execution plan')
183 if _stamp(self.storage) != self.storage_stamp:200 if _stamp(self.storage) != self.storage_stamp:
@@ -243,6 +260,10 @@ def prepare_combine_plan(ctx, plan, *, storage=None, fused_timing=None):
243 plan._planning_generation, end, ctx, begin, end)260 plan._planning_generation, end, ctx, begin, end)
244 execution.fused = fused261 execution.fused = fused
245 object.__setattr__(plan, 'combine_execution_plan', execution)262 object.__setattr__(plan, 'combine_execution_plan', execution)
263+ # Ready flags live in the shared workspace, unlike immutable route tables.
264+ # A different logical size places payload and flags at different offsets.
265+ owner = ctx.get('_capacity_ctx', ctx)
266+ owner['_combine_workspace_layout'] = _combine_workspace_layout(ctx)
246 return execution267 return execution
247 268 
248 269 
@@ -315,6 +336,7 @@ def allocate_planning_outputs(ctx: dict):
315 336 
316 plan = MoonEPCommPlan(337 plan = MoonEPCommPlan(
317 dst=dst,338 dst=dst,
339+ cu_seqlens=cu_seqlens,
318 experts_to_copy=experts_to_copy,340 experts_to_copy=experts_to_copy,
319 zero_fill_ranges=zero_fill_ranges,341 zero_fill_ranges=zero_fill_ranges,
320 remote_stats=remote_stats,342 remote_stats=remote_stats,
@@ -43,10 +43,12 @@ def audit_loaded_shmem_library(
43) -> dict[str, object]:43) -> dict[str, object]:
44 """Return identity evidence for the one loaded ``libshmem.so`` image.44 """Return identity evidence for the one loaded ``libshmem.so`` image.
45 45 
46- Mappings are deduplicated by the resolved file's ``(st_dev, st_ino)``;46+ Mappings are deduplicated by procfs ``(device, inode)`` so repeated ELF
47- repeated ELF segments are therefore one library. The procfs device/inode47+ segments are one library. The procfs inode must match ``stat(2)``. The
48- fields must also match ``stat(2)``. Any missing, deleted, inconsistent, or48+ device numbers are both reported but may differ when a container path is
49- multiple runtime images fail closed before ACLSHMEM initialization.49+ an overlay/bind-mount view of the mapped host file. Any missing, deleted,
50+ inode-inconsistent, or multiple runtime images fail closed before ACLSHMEM
51+ initialization.
50 """52 """
51 current_platform = sys.platform if platform is None else platform53 current_platform = sys.platform if platform is None else platform
52 if current_platform != "linux":54 if current_platform != "linux":
@@ -92,20 +94,30 @@ def audit_loaded_shmem_library(
92 raise RuntimeError(94 raise RuntimeError(
93 f"cannot resolve loaded libshmem mapping identity: {mapped_path}") from exc95 f"cannot resolve loaded libshmem mapping identity: {mapped_path}") from exc
94 96 
95- if maps_device_number != stat_result.st_dev or maps_inode != stat_result.st_ino:97+ # /proc/<pid>/maps can expose the backing filesystem's device number
98+ # while stat(2) of the same absolute path reports the device number of
99+ # the container's overlay/bind-mount view. In that case the pathname
100+ # and inode still identify the same file, but st_dev legitimately
101+ # differs (for example maps=fd:00 and stat=0:33). An inode mismatch is
102+ # still a replacement/identity failure and must remain fail-closed.
103+ if maps_inode != stat_result.st_ino:
96 raise RuntimeError(104 raise RuntimeError(
97 "loaded libshmem mapping metadata changed during audit: "105 "loaded libshmem mapping metadata changed during audit: "
98 f"{mapped_path} maps dev/inode={maps_device}/{maps_inode}, "106 f"{mapped_path} maps dev/inode={maps_device}/{maps_inode}, "
99 f"stat dev/inode={os.major(stat_result.st_dev):x}:"107 f"stat dev/inode={os.major(stat_result.st_dev):x}:"
100 f"{os.minor(stat_result.st_dev):x}/{stat_result.st_ino}")108 f"{os.minor(stat_result.st_dev):x}/{stat_result.st_ino}")
101 109 
102- identity = (stat_result.st_dev, stat_result.st_ino)110+ identity = (maps_device_number, maps_inode)
103 identities.setdefault(identity, {111 identities.setdefault(identity, {
104 "realpath": str(realpath),112 "realpath": str(realpath),
105 "device": int(stat_result.st_dev),113 "device": int(stat_result.st_dev),
106 "device_major": int(os.major(stat_result.st_dev)),114 "device_major": int(os.major(stat_result.st_dev)),
107 "device_minor": int(os.minor(stat_result.st_dev)),115 "device_minor": int(os.minor(stat_result.st_dev)),
108 "inode": int(stat_result.st_ino),116 "inode": int(stat_result.st_ino),
117+ "maps_device": int(maps_device_number),
118+ "maps_device_major": int(os.major(maps_device_number)),
119+ "maps_device_minor": int(os.minor(maps_device_number)),
120+ "device_alias": bool(maps_device_number != stat_result.st_dev),
109 })121 })
110 122 
111 if len(identities) != 1:123 if len(identities) != 1:
@@ -115,9 +127,10 @@ def audit_loaded_shmem_library(
115 f"{len(identities)}: {paths}")127 f"{len(identities)}: {paths}")
116 128 
117 info = next(iter(identities.values()))129 info = next(iter(identities.values()))
118- identity = (int(info["device"]), int(info["inode"]))130+ path_identity = (int(info["device"]), int(info["inode"]))
119 try:131 try:
120- info["sha256"] = _sha256_file(Path(str(info["realpath"])), identity)132+ info["sha256"] = _sha256_file(
133+ Path(str(info["realpath"])), path_identity)
121 except OSError as exc:134 except OSError as exc:
122 raise RuntimeError(135 raise RuntimeError(
123 f"cannot hash loaded libshmem runtime: {info['realpath']}") from exc136 f"cannot hash loaded libshmem runtime: {info['realpath']}") from exc
@@ -148,6 +148,7 @@ def _npu_extension():
148 os.path.join("native", "csrc", "acl_shared_buffer.cpp"),148 os.path.join("native", "csrc", "acl_shared_buffer.cpp"),
149 os.path.join("native", "csrc", "torch_classes.cpp"),149 os.path.join("native", "csrc", "torch_classes.cpp"),
150 os.path.join("native", "csrc", "launcher.cpp"),150 os.path.join("native", "csrc", "launcher.cpp"),
151+ os.path.join("native", "csrc", "lplusb_runtime.cpp"),
151 os.path.join("native", "csrc", "ops", "moonep_combine.cpp"),152 os.path.join("native", "csrc", "ops", "moonep_combine.cpp"),
152 os.path.join("native", "csrc", "ops", "moonep_combine_udma.cpp"),153 os.path.join("native", "csrc", "ops", "moonep_combine_udma.cpp"),
153 os.path.join("native", "csrc", "ops", "moonep_dispatch.cpp"),154 os.path.join("native", "csrc", "ops", "moonep_dispatch.cpp"),
@@ -239,7 +240,7 @@ def _package_data():
239 if BACKEND != "npu":240 if BACKEND != "npu":
240 return {}241 return {}
241 # Globs are relative to the `npu_patch` package directory.242 # Globs are relative to the `npu_patch` package directory.
242- libs = ["lib/*.so", "lib/*.so.*"]243+ libs = ["lib/*.so", "lib/*.so.*", "_integration_capabilities.json"]
243 return {"npu_patch": libs}244 return {"npu_patch": libs}
244 245 
245 246 
@@ -197,6 +197,7 @@ class ShmemRuntime:
197 """Thin facade over the shmem symmetric-memory runtime lifecycle."""197 """Thin facade over the shmem symmetric-memory runtime lifecycle."""
198 198 
199 _initialized = False199 _initialized = False
200+ _udma_enabled = False
200 _poisoned = False201 _poisoned = False
201 _runtime_library_record = None202 _runtime_library_record = None
202 203 
@@ -286,7 +287,7 @@ class ShmemRuntime:
286 # Fail closed before any SHMEM-native call (including UID generation).287 # Fail closed before any SHMEM-native call (including UID generation).
287 # Loading two libshmem images creates independent process-global288 # Loading two libshmem images creates independent process-global
288 # PE/heap state.289 # PE/heap state.
289- # cls._runtime_library_record = audit_loaded_shmem_library()290+ cls._runtime_library_record = audit_loaded_shmem_library()
290 rank = dist.get_rank(group=group)291 rank = dist.get_rank(group=group)
291 world_size = dist.get_world_size(group=group)292 world_size = dist.get_world_size(group=group)
292 if uid_bytes is None:293 if uid_bytes is None:
@@ -327,6 +328,7 @@ class ShmemRuntime:
327 else ACLSHMEM_DATA_OP_MTE),328 else ACLSHMEM_DATA_OP_MTE),
328 device_id=int(torch.npu.current_device()),329 device_id=int(torch.npu.current_device()),
329 enable_udma=enable_udma, qp_count=qp_count)330 enable_udma=enable_udma, qp_count=qp_count)
331+ cls._udma_enabled = bool(enable_udma)
330 cls._initialized = True332 cls._initialized = True
331 333 
332 @classmethod334 @classmethod
@@ -367,7 +369,7 @@ class ShmemRuntime:
367 return369 return
368 # The IP/port path owns the same process-global runtime and backing as370 # The IP/port path owns the same process-global runtime and backing as
369 # the UID path, so it must pass the identical pre-native audit.371 # the UID path, so it must pass the identical pre-native audit.
370- # cls._runtime_library_record = audit_loaded_shmem_library()372+ cls._runtime_library_record = audit_loaded_shmem_library()
371 if ip_port is None:373 if ip_port is None:
372 ip_port = _env_shmem_ip_port()374 ip_port = _env_shmem_ip_port()
373 if ip_port is None:375 if ip_port is None:
@@ -400,6 +402,7 @@ class ShmemRuntime:
400 else ACLSHMEM_DATA_OP_MTE),402 else ACLSHMEM_DATA_OP_MTE),
401 device_id=int(torch.npu.current_device()),403 device_id=int(torch.npu.current_device()),
402 enable_udma=enable_udma, qp_count=qp_count)404 enable_udma=enable_udma, qp_count=qp_count)
405+ cls._udma_enabled = bool(enable_udma)
403 cls._initialized = True406 cls._initialized = True
404 407 
405 @classmethod408 @classmethod
@@ -422,6 +425,7 @@ class ShmemRuntime:
422 # --- Original implementation (plan A) ---425 # --- Original implementation (plan A) ---
423 # core.finalize()426 # core.finalize()
424 cls._initialized = False427 cls._initialized = False
428+ cls._udma_enabled = False
425 cls._poisoned = False429 cls._poisoned = False
426 return rc430 return rc
427 return 0431 return 0
@@ -0,0 +1,118 @@
1+"""Device acceptance for the additive native APIs; run with fresh workers.
2+ 
3+MOONEP_NATIVE_TEST_UDMA=0 torchrun --nproc-per-node=2 -m pytest -s -x \
4+ test_npu/buffer_test/test_buffer_native_async_extensions.py
5+ 
6+Repeat with world=8, then UDMA=1 on Ascend950 with matching native ABIs.
7+No profiling/performance claim is made by this correctness test.
8+"""
9+import os
10+ 
11+import pytest
12+import torch
13+import torch.distributed as dist
14+import torch_npu
15+ 
16+from npu_patch import Buffer, ShmemRuntime
17+from npu_patch.buffer_c import create_vmm_physical, reset_symmetric_descriptors
18+ 
19+ 
20+def test_native_async_storage_and_lplusb(dist_env):
21+ rank, world = dist_env
22+ if world not in (2, 8):
23+ pytest.skip('acceptance recipe is EP2 or EP8')
24+ raw = os.environ.get('MOONEP_NATIVE_TEST_UDMA', '0')
25+ if raw not in ('0', '1'):
26+ raise ValueError('MOONEP_NATIVE_TEST_UDMA must be 0 or 1')
27+ udma = raw == '1'
28+ if ShmemRuntime.is_initialized():
29+ raise RuntimeError('run this acceptance test alone in fresh workers')
30+ s, h, k, local, b = 16, 128, 1, 2, 2
31+ device = torch.device('npu', torch.npu.current_device())
32+ buffer = Buffer(S=s, H=h, K=k, E=world * local, B=b, num_ep_ranks=world,
33+ group=dist.group.WORLD, explicitly_destroy=True,
34+ prefetch_use_udma=udma, grad_reduce_use_udma=udma)
35+ sources = []
36+ def allocate(shape, dtype):
37+ value, _, _ = create_vmm_physical(shape, dtype, device.index)
38+ sources.append(value)
39+ return value
40+ # Every rank registers the same inventory/order before one-shot SHMEM init.
41+ activation_sources = [(allocate((s * k, h), torch.bfloat16),
42+ allocate((s * k,), torch.int32)) for _ in range(3)]
43+ weight_slots = allocate((b, h, h), torch.bfloat16)
44+ grad_slots = allocate((b, h, h), torch.float32)
45+ weights = tuple(torch.full((h, h), rank * local + i + 1,
46+ dtype=torch.bfloat16, device=device) for i in range(local))
47+ targets = tuple(torch.full((h, h), 10 + rank * local + i,
48+ dtype=torch.float32, device=device) for i in range(local))
49+ ShmemRuntime.init_with_buffer(group=dist.group.WORLD, enable_udma=udma,
50+ qp_count=2 if udma else 0)
51+ banks = [buffer.prepare_comm_buffers(*pair) for pair in activation_sources]
52+ wbind = buffer.prepare_lplusb(weights, weight_slots)
53+ gbind = buffer.prepare_lplusb(targets, grad_slots)
54+ q1 = torch_npu.npu.current_stream()
55+ routes = torch.zeros(s, k, dtype=torch.int32, device=device)
56+ counts = torch.bincount(routes.flatten().long(), minlength=world * local).int()
57+ probabilities = torch.ones(s, k, dtype=torch.float32, device=device)
58+ saved = []
59+ # Three live Z3/R1/Z1-like outputs must survive later communication calls.
60+ for value, bank in zip((1, 2, 3), banks):
61+ hidden = torch.full((s, h), rank * 4 + value, dtype=torch.bfloat16, device=device)
62+ out, probs, cu, plan, done = buffer.dispatch(hidden, probabilities, routes, counts,
63+ async_finish=True, zero_copy=True, router_weights_zero_copy=True, comm_buffers=bank)
64+ saved.append((hidden, out, probs, plan, done, bank))
65+ for hidden, out, probs, plan, done, bank in saved:
66+ q1.wait_event(done)
67+ combined, _, event = buffer.combine(plan, out, async_finish=True,
68+ zero_copy=True, comm_buffers=bank)
69+ q1.wait_event(event)
70+ torch.npu.synchronize()
71+ torch.testing.assert_close(combined, hidden, atol=0, rtol=0)
72+ # Default copying path uses no bank argument and preserves each result.
73+ copied = []
74+ for value in (5, 6):
75+ hidden = torch.full((s, h), value, dtype=torch.bfloat16, device=device)
76+ out, _, _, plan, event = buffer.dispatch(hidden, probabilities, routes, counts,
77+ async_finish=True)
78+ copied.append((hidden, out, plan, event))
79+ for hidden, out, plan, event in copied:
80+ q1.wait_event(event)
81+ result, _, event = buffer.combine(plan, out, async_finish=True)
82+ q1.wait_event(event)
83+ torch.npu.synchronize()
84+ torch.testing.assert_close(result, hidden, atol=0, rtol=0)
85+ 
86+ # Use an explicit replicated ring plan to exercise nonempty and empty slots
87+ # on all ranks, independently of the token planner's load distribution.
88+ plan = saved[-1][3].clone()
89+ ring = torch.full((world, b), -1, dtype=torch.int32)
90+ for peer in range(world):
91+ ring[peer, 0] = ((peer + 1) % world) * local
92+ plan.experts_to_copy.copy_(ring.to(device))
93+ done = buffer.prefetch_lplusb(plan, wbind, async_finish=True)
94+ q1.wait_event(done)
95+ torch.npu.synchronize()
96+ torch.testing.assert_close(wbind.slot[0], torch.full_like(wbind.slot[0],
97+ int(ring[rank, 0]) + 1), atol=0, rtol=0)
98+ for round_id in range(2):
99+ gbind.slot.fill_(99)
100+ gbind.slot[0].fill_(rank + 1)
101+ done = buffer.reduce_grad(plan, async_finish=True, lplusb=gbind)
102+ q1.wait_event(done)
103+ torch.npu.synchronize()
104+ for i, target in enumerate(targets):
105+ contribution = sum(peer + 1 for peer in range(world)
106+ if int(ring[peer, 0]) == rank * local + i)
107+ expected = 10 + rank * local + i + (round_id + 1) * contribution
108+ torch.testing.assert_close(target, torch.full_like(target, expected), atol=0, rtol=0)
109+ assert torch.count_nonzero(gbind.slot[0]).item() == 0
110+ assert torch.all(gbind.slot[1] == 99).item()
111+ # Only successful, globally drained execution may reach teardown.
112+ torch.npu.synchronize()
113+ dist.barrier()
114+ ShmemRuntime.finalize()
115+ buffer.destroy()
116+ for source in sources:
117+ source._vmm_allocation.destroy()
118+ reset_symmetric_descriptors()
@@ -0,0 +1,539 @@
1+# SPDX-License-Identifier: Apache-2.0
Jia_Austin
Jia_AustinJia_Austin23 days ago

可以合入原来ut

likedislike
2+"""Eight-card DSV4 public Buffer e2e test (MTE).
3+ 
4+Derived from the adjacent original e2e test, with eight EP ranks and
5+S=4096, H=7168, K=6, E=48, B=6, Hp=3072, and 32 blocks. Inputs use a
6+rank-seeded random top-k: repeated calls reproduce the same routing.
7+The public sync/async dispatch, separate prefetch, plan reuse, zero-copy,
8+combine, and gradient-reduction checks are retained on the MTE path.
9+All gate/up/down projections use [H, Hp]; this is an operator-chain test,
10+without expert GEMM or a training loop. VMM pages are pinned to 2 MiB
11+during the test and the previous page setting is restored afterwards.
12+ 
13+Run from the MoonEP root:
14+ torchrun --standalone --nproc_per_node=8 -m pytest -s -x test_npu/mte/test_e2e_dsv4.py
15+"""
16+ 
17+import os
18+import sys
19+ 
20+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
21+import torch
22+import torch.distributed as dist
23+ 
24+import torch_npu
25+ 
26+from npu_patch import Buffer, MoonEPCommPlan
27+from kernel_test_utils import (
28+ clone_dedup_plan_fields,
29+ dedup_plan_fields_equal,
30+ dedup_plan_semantic_errors,
31+ init_shmem,
32+ local_device_index,
33+)
34+from moonep.buffer import (
35+ create_full_grad_and_reduce_buffer,
36+ create_full_weight,
37+ projection_home_slice,
38+ projection_slot_slice,
39+ release_owned,
40+)
41+ 
42+ 
43+def make_inputs(rank, S, H, K, E, seed=0):
44+ dev = "npu"
45+ # Reproducible random routing; each rank uses its own fixed seed.
46+ g = torch.Generator(device=dev).manual_seed(seed + rank)
47+ hidden = torch.randn(S, H, dtype=torch.bfloat16, device=dev, generator=g)
48+ weights = torch.rand(S, K, dtype=torch.float32, device=dev, generator=g)
49+ topk = torch.randint(0, E, (S, K), dtype=torch.int32, device=dev, generator=g)
50+ tpe = torch.bincount(topk.flatten(), minlength=E).to(torch.int32)
51+ return hidden, weights, topk, tpe
52+ 
53+ 
54+def _expert_value(expert, H, Hp, dev):
55+ e = torch.full((H, Hp), float(expert), dtype=torch.bfloat16, device=dev)
56+ e += (torch.arange(Hp, dtype=torch.bfloat16, device=dev) * 0.01).view(1, Hp)
57+ e += (torch.arange(H, dtype=torch.bfloat16, device=dev) * 0.0001).view(H, 1)
58+ return e
59+ 
60+ 
61+def make_full_weight(rank, R, E, B, H, Hp, device, source_offset):
62+ """Return ``(full_weight, offset)``.
63+ 
64+ full_weight is built by ``create_full_weight``: it creates this rank's home/slot
65+ VMM chunk and ``[E+B]`` projection, copies ``expert_table[rank*epn:(rank+1)*epn]``
66+ into the home rows plus offset, zeroes the slot rows, and attaches the home/slot
67+ source VAs (the Buffer prefetch_weight VMM path translates through them). expert_table
68+ is generated in full by a deterministic formula and is identical on all ranks (rank-invariant).
69+ """
70+ dev = f"npu:{device}"
71+ expert_table = torch.stack(
72+ [_expert_value(e, H, Hp, dev) for e in range(E)])
73+ full = create_full_weight(
74+ E, B, H, Hp, rank, R, expert_table, source_offset, device=device)
75+ return full, source_offset
76+ 
77+ 
78+def make_prefetch_args(rank, R, E, B, H, Hp, device):
79+ """Return ``(args_dict, meta)``.
80+ 
81+ ``args_dict`` values are the full_weight **tensors** (spread into ``buffer.prefetch_weight(**args)``);
82+ ``meta[name] = (full_weight, offset)`` is for the assertions (slot rows read via
83+ ``projection_slot_slice``).
84+ """
85+ args = {}
86+ meta = {}
87+ for name, offset in (("full_gate_weight", 0.0),
88+ ("full_up_weight", 1.0),
89+ ("full_down_weight", 2.0)):
90+ full, off = make_full_weight(rank, R, E, B, H, Hp, device, offset)
91+ args[name] = full
92+ meta[name] = (full, off)
93+ return args, meta
94+ 
95+ 
96+def assert_prefetched(prefetch_arge, prefetch_meta, experts_to_copy, R):
97+ """``R`` is the *domain* EP size (== group world size), not the global one.
98+ 
99+ The prefetch projection lays ``[E+B]`` global expert rows where ``E =
100+ epn * R``; taking ``R`` from the caller keeps this correct inside an EP
@@ -19,6 +19,7 @@ import torch.distributed as dist
19import torch_npu19import torch_npu
20 20 
21from npu_patch._device import local_device_index21from npu_patch._device import local_device_index
22+from npu_patch._grad_reduce_contract import workspace_elements
22from npu_patch import ShmemRuntime23from npu_patch import ShmemRuntime
23from npu_patch.buffer_c import (24from npu_patch.buffer_c import (
24 create_vmm_physical,25 create_vmm_physical,
@@ -27,6 +28,7 @@ from npu_patch.buffer_c import (
27 symmetric_descriptors,28 symmetric_descriptors,
28)29)
29from npu_patch.launchers import launch_grad_reduce30from npu_patch.launchers import launch_grad_reduce
31+from npu_patch.ops import GradReduceOp
30 32 
31# --- Original implementation (option A: the shmem Python package) ---33# --- Original implementation (option A: the shmem Python package) ---
32# import importlib34# import importlib
@@ -408,6 +410,102 @@ def test_grad_reduce(dist_env, case):
408 run_case(rank, local_rank, R, case)410 run_case(rank, local_rank, R, case)
409 411 
410 412 
413+@pytest.mark.parametrize('shape', [(129, 101), (6144, 7168), (7168, 3072)],
414+ ids=['tail_tile', 'fc1', 'fc2'])
415+@pytest.mark.parametrize('use_udma', [False, True], ids=['mte', 'udma'])
416+def test_grad_reduce_canonical_targets(dist_env, shape, use_udma, monkeypatch):
417+ """Plain independent home allocations, changing plans and valid-only clear.
418+ 
419+ Run in fresh torchrun workers after rebuilding extension + kernel library.
420+ No legacy owner-reduce fallback is allowed. This is correctness, not timing.
421+ """
422+ from npu_patch import _C
423+ import time
424+ rank, local_rank, R = dist_env
425+ device = f'npu:{local_device_index(local_rank)}'
426+ epn, B, blocks = 6, 6, 32
427+ H, Hp = shape
428+ source = None
429+ monkeypatch.setenv('ASCEND_MOONEP_GRAD_REDUCE_USE_UDMA', str(int(use_udma)))
430+ monkeypatch.setattr(_C, '_lplusb_owner_reduce',
431+ lambda *a: pytest.fail('canonical Op used legacy binding'))
432+ try:
433+ source, _, _ = create_vmm_physical((B, H, Hp), torch.float32,
434+ local_device_index(local_rank))
435+ ShmemRuntime.init_with_buffer(group=None, descriptors=symmetric_descriptors(),
436+ enable_udma=use_udma, qp_count=2 if use_udma else 0)
437+ slots = sym_tensor(source)
438+ slots.zero_()
439+ targets = tuple(torch.full((H, Hp), float(100 + e), dtype=torch.float32, device=device)
440+ for e in range(epn))
441+ # Reverse allocation order so a dense base+expert*matrix assumption
442+ # cannot accidentally satisfy the canonical pointer contract.
443+ targets = targets[::-1]
444+ table = torch.tensor([t.data_ptr() for t in targets], dtype=torch.int64, device=device)
445+ addresses = tuple(t.data_ptr() for t in targets)
446+ wanted = [float(100 + epn - 1 - e) for e in range(epn)]
447+ op = GradReduceOp(ws_bytes=0, num_sms=blocks)
448+ ctx = dict(E=R*epn, R=R, B=B)
449+ if use_udma:
450+ ctx['_grad_reduce_target_workspace'] = torch.empty(
451+ workspace_elements(R, B, min(blocks, 64)), dtype=torch.float32, device=device)
452+ plan_cases = ('random', 'empty', 'asymmetric', 'hotspot', 'ring')
453+ for iteration, plan_name in enumerate(plan_cases):
454+ final_round = iteration == len(plan_cases) - 1
455+ plan = (torch.zeros((R, B), dtype=torch.int32, device=device)
456+ if plan_name == 'hotspot' else
457+ PLAN_BUILDERS[plan_name](R, B, epn, device, 7 + iteration))
458+ rows = plan.cpu().tolist()
459+ # Delay one producer before its writes: pointer mode's native pre
460+ # barrier must stop early owners reading an unpublished slot.
461+ if rank == R-1 and iteration == 2:
462+ time.sleep(.05)
463+ was_clean = []
464+ for slot, expert in enumerate(rows[rank]):
465+ if expert >= 0:
466+ was_clean.append(torch.all(slots[slot] == 0))
467+ slots[slot].add_(1 + rank*B + slot + iteration*100)
468+ elif final_round:
469+ # Intentional sentinel only in the final diagnostic round;
470+ # the preceding rounds never write inactive slots.
471+ slots[slot].fill_(-1234)
472+ for pe, row in enumerate(rows):
473+ for slot, expert in enumerate(row):
474+ local = expert - rank*epn
475+ if expert >= 0 and 0 <= local < epn:
476+ wanted[local] += 1 + pe*B + slot + iteration*100
477+ if not use_udma and iteration == 0:
478+ # Torch custom-class defaults preserve the old MTE call.
479+ torch.classes.AscendMoonEP.GradReduce().compute_targets(
480+ table, slots, plan, epn, H, Hp, R, B, rank, blocks)
481+ elif not use_udma and iteration == 1:
482+ # The explicit flag selects MTE even when scratch is supplied.
483+ torch.classes.AscendMoonEP.GradReduce().compute_targets(
484+ table, slots, plan, epn, H, Hp, R, B, rank, blocks,
485+ False, torch.empty(1, dtype=torch.float32, device=device))
486+ else:
487+ op.compute_targets(ctx, table, slots, plan, rank, blocks)
488+ torch.npu.synchronize()
489+ checks = was_clean + [torch.all(t == value) for t, value in zip(targets, wanted)]
490+ checks += [torch.all(slots[s] == (0 if expert >= 0 or not final_round else -1234))
491+ for s, expert in enumerate(rows[rank])]
492+ ok = torch.stack(checks).all().to(torch.int32)
493+ dist.all_reduce(ok, op=dist.ReduceOp.MIN)
494+ assert bool(ok), f'canonical {shape} round={iteration} failed'
495+ assert tuple(t.data_ptr() for t in targets) == addresses
496+ if rank == 0:
497+ print(f'canonical targets shape={shape} actual_blocks={min(blocks,64)} '
498+ f'backend={"UDMA" if use_udma else "MTE"} '
499+ f'changed_plans={len(plan_cases)} valid_slot_clear=True')
500+ finally:
501+ dist.barrier()
502+ if ShmemRuntime.is_initialized():
503+ ShmemRuntime.finalize()
504+ if source is not None:
505+ source._vmm_allocation.destroy()
506+ reset_symmetric_descriptors()
507+ 
508+ 
411def test_grad_reduce_repeated_launch(dist_env):509def test_grad_reduce_repeated_launch(dist_env):
412 rank, local_rank, R = dist_env510 rank, local_rank, R = dist_env
413 dev = f"npu:{local_device_index(local_rank)}"511 dev = f"npu:{local_device_index(local_rank)}"