Draft
[WIP] feat(npu): integrate official URMA pointer PUSH with L+B Buffer #1
Jia_AustinAdd on Oct 21
[WIP] feat(npu): integrate official URMA pointer PUSH with L+B Buffer #1
Draft
Jia_AustinAdd on Oct 21
Total: 15 files changed+781-31
@@ -0,0 +1,45 @@
1+# Official L+B URMA pointer PUSH
2+ 
3+This increment combines official MoonEP PR #9 (d7a9baeb) and PR #10
4+(7492d7da). MindSpeed PR #4106 (7834780e) is the framework baseline.
5+It does not depend on, import, or link the separate ascend-moonep provider.
6+ 
7+The existing continuous-home API remains available. The L+B path instantiates
8+the same `urma_push_core.h` as `Run<true>` and reads canonical local expert
9+addresses directly. Parameter identity, DDP/optimizer backing and checkpoint
10+keys do not change. A pointer table is metadata; no weight staging is added.
11+ 
12+## Selection and completion
13+ 
14+MindSpeed defaults to `--moonep-prefetch-engine=mte`. Select `urma` explicitly;
15+capability and native checks run across ranks before SHMEM initialization.
16+Planning, dispatch, combine and GradReduce stay on MTE in this candidate.
17+Use one official `ShmemRuntime`, with SDK 6b023443 and its default two-QP
18+initialization. No explicit QP, stripe, or custom CQ protocol is used.
19+ 
20+Both sync projections and the existing async collective SPI retain native
21+pre/post barriers. URMA does not support `required_owners_v1` in this increment;
22+that combination fails before bank allocation. The existing MTE path remains.
23+Source Tensor aliases, pointer metadata, plan and slots remain retained through
24+native completion or the existing async final-use retirement. Query/submission
25+failure poisons and keeps backing; ordinary pending completion only defers
26+destroy. Finalize SHMEM successfully before releasing physical allocations.
27+ 
28+The formula probe deliberately permits L=1/B=7 for prefetch only. Production
29+MindSpeed still constructs B=L, and GradReduce retains its original B=L check.
30+The formula and every transfer include the full BF16 FC1/FC2 byte count.
31+ 
32+## Evidence boundary
33+ 
34+Historical continuous-source p95 2.850/2.864 ms and separate-provider partial
35+3.077/3.061 ms are comparison evidence only. This new combined source requires
36+its own build, device, numerical and complete ABBA gates. UDMA GradReduce's
37+historical fault is not repaired or validated by this increment.
38+ 
39+The standalone pointer probe is `npu_patch/benchmarks/bench_pointer_push.py`.
40+Run fresh processes for MTE/URMA/URMA/MTE, 10 warmup and 50 measured iterations
41+per arm. Require both URMA nearest-rank p95 values of the per-iteration maximum
42+over eight ranks to be <=4.3 ms. Keep H7168/FFN3072, FC1(6144,7168),
43+FC2(7168,3072), and 924844032 logical TX/RX bytes per rank. Timing begins before
44+FC1 submission and ends after the consumer waits for both peer-visible events.
45+The report uses single-direction GB/s and GiB/s without an additional 0.7.
Mhost_tests/async_fakes.py+5-0File content is under review, please try again later
Ahost_tests/test_contiguous_lplusb_source.py+70-0File content is under review, please try again later
Mhost_tests/test_sync_lplusb.py+7-2File content is under review, please try again later
Ahost_tests/test_unified_urma_prefetch.py+166-0File content is under review, please try again later
@@ -40,5 +40,20 @@
40 "lane_count": 1,40 "lane_count": 1,
41 "repeatable_steps": true,41 "repeatable_steps": true,
42 "strict_zero_copy": true42 "strict_zero_copy": true
43+ },
44+ "prefetch_engines": [
45+ "mte",
46+ "urma"
47+ ],
48+ "urma_push": {
49+ "schema": 1,
50+ "pointer_source": true,
51+ "contiguous_source": true,
52+ "contiguous_native_abi": 1,
53+ "native_abi": 1,
54+ "completion_modes": [
55+ "collective"
56+ ],
57+ "shared_core_sha256": "26e966899f19fe199148b73c00920c126da7a64f2aff3eb1ea20283340cd84b2"
43 }58 }
44}59}
Mnpu_patch/api.py+144-25File content is under review, please try again later
@@ -0,0 +1,178 @@
1+"""Canonical-pointer PUSH mechanism and complete consumer-visible formula probe.
2+ 
3+Run each arm in fresh torchrun processes. MTE/URMA share Buffer, plans, source
4+Parameters, destination descriptors, setup, checks and timing boundaries.
5+"""
6+import argparse
7+from datetime import timedelta
8+import hashlib
9+import json
10+import math
11+import os
12+from pathlib import Path
13+import subprocess
14+import time
15+import traceback
16+ 
17+ 
18+def digest(path): return hashlib.sha256(Path(path).read_bytes()).hexdigest()
19+ 
20+ 
21+def atomic_json(path, value):
22+ tmp=path.with_suffix('.tmp');tmp.write_text(json.dumps(value,indent=2));tmp.replace(path)
23+ 
24+ 
25+def run(args, state):
26+ import torch
27+ import torch_npu
28+ rank,world,local=(int(os.environ[k]) for k in ('RANK','WORLD_SIZE','LOCAL_RANK'))
29+ torch.npu.set_device(local)
30+ import torch.distributed as dist
31+ import npu_patch
32+ from npu_patch import Buffer, ShmemRuntime, _C
33+ from npu_patch.buffer_c import create_vmm_physical, sym_tensor, symmetric_descriptors, reset_symmetric_descriptors
34+ from npu_patch.planning import allocate_planning_outputs
35+ if not 2<=world<=8 or args.iters<=0 or args.warmup<0:
36+ raise ValueError('requires 2..8 ranks and positive iterations')
37+ if args.kind=='formula' and (world!=8 or args.multi_chunk or args.delay_owner!=-1):
38+ raise ValueError('formula requires exact EP8 shapes without injected delay')
39+ if args.payload_diag and (args.kind!='sentinel' or args.multi_chunk):
40+ raise ValueError('payload snapshots are a tiny diagnostic, never formal performance')
41+ state['payload_diagnostic']=args.payload_diag
42+ repo=Path(npu_patch.__file__).resolve().parent.parent
43+ state['source_sha']=subprocess.check_output(['git','rev-parse','HEAD'],cwd=repo,text=True).strip()
44+ if state['source_sha']!=args.expect_source or subprocess.check_output(
45+ ['git','status','--porcelain','--untracked-files=no'],cwd=repo,text=True):
46+ raise RuntimeError('source mismatch or dirty tree')
47+ os.environ.setdefault('GLOO_SOCKET_IFNAME','lo')
48+ dist.init_process_group('gloo',timeout=timedelta(seconds=180))
49+ slots=world-1
50+ local_experts=1 if args.kind=='formula' else 2
51+ shapes=((6144,7168),(7168,3072)) if args.kind=='formula' else (
52+ ((8193,16384),(3,5)) if args.multi_chunk else ((3,5),(5,3)))
53+ buffer=Buffer(S=1,H=5,K=1,E=world*local_experts,num_ep_ranks=world,
54+ B=slots,group=dist.group.WORLD,explicitly_destroy=True,
55+ use_udma=False,prefetch_use_udma=args.engine == 'urma')
56+ allocations=[create_vmm_physical((slots,*shape),torch.bfloat16,local)[0] for shape in shapes]
57+ # Separate ordinary allocations deliberately have no contiguous source arena.
58+ sources=[[torch.nn.Parameter(torch.empty(shape,dtype=torch.bfloat16,device='npu'),requires_grad=False)
59+ for _ in range(local_experts)] for shape in shapes]
60+ plan,_=allocate_planning_outputs(buffer._ctx)
61+ state['_keepalive']=[buffer,allocations,sources,plan]
62+ uid=[bytes(_C.acl_shmem_get_unique_id()) if rank==0 else None]
63+ dist.broadcast_object_list(uid,src=0)
64+ # Both arms use identical SDK initialization; only payload engine differs.
65+ ShmemRuntime.init_with_buffer(group=dist.group.WORLD,uid_bytes=uid[0],enable_udma=True)
66+ buffer._ensure_shmem_views()
67+ destinations=[sym_tensor(allocation) for allocation in allocations]
68+ state['_keepalive'].append(destinations)
69+ receipt=json.loads(args.build_identity.read_text())
70+ if receipt.get('source_sha') != args.expect_source:
71+ raise RuntimeError('native build source differs from selected formula source')
72+ expected=receipt.get('artifacts',receipt)
73+ mapped={str(Path(line.split()[-1]).resolve()) for line in Path('/proc/self/maps').read_text().splitlines()
74+ if 'libshmem.so' in line or 'libshmem_utils.so' in line or 'libascend_moonep_kernels.so' in line or 'npu_patch/_C.' in line}
75+ if len([p for p in mapped if Path(p).name=='libshmem.so'])!=1:
76+ raise RuntimeError('missing or duplicate SHMEM runtime')
77+ native={}
78+ for name,identity in expected.items():
79+ if not isinstance(identity,dict):continue
80+ path=str(Path(identity['path']).resolve())
81+ if path not in mapped or digest(path)!=identity['sha256']:
82+ raise RuntimeError('loaded DSO differs from frozen build: '+name)
83+ native[name]=dict(path=path,sha256=digest(path),inode=Path(path).stat().st_ino)
84+ state['native']=native
85+ q0,consumer=torch.npu.Stream(),torch.npu.current_stream()
86+ patterns=[(torch.arange(math.prod(shape),device='npu',dtype=torch.int32)%13).to(torch.bfloat16).reshape(shape)
87+ for shape in shapes]
88+ for iteration in range(args.warmup+args.iters):
89+ case=0 if args.kind=='formula' else iteration%4
90+ rows=([[peer*local_experts+slot%local_experts for slot,peer in enumerate(
91+ peer for peer in range(world) if peer!=receiver)] for receiver in range(world)]
92+ if case==0 else [[-1]*slots for _ in range(world)] if case==1 else
93+ [[receiver*local_experts]*slots for receiver in range(world)] if case==2 else
94+ [[((receiver+1)%world)*local_experts+local_experts-1]*slots for receiver in range(world)])
95+ plan.experts_to_copy.copy_(torch.tensor(rows,dtype=torch.int32,device='npu'))
96+ for projection in range(2):
97+ for index,source in enumerate(sources[projection]):
98+ source.copy_(patterns[projection]+float((rank*local_experts+index)*16+projection*2+iteration%4))
99+ destinations[projection].fill_(-17)
100+ if args.payload_diag:
101+ snapshot=dict(rank=rank,iteration=iteration,plan=plan.experts_to_copy.detach().cpu(),
102+ sources=[[source.detach().cpu() for source in projection] for projection in sources])
103+ path=args.out/f'payload_input_rank{rank}_iter{iteration}.pt'
104+ torch.save(snapshot,path)
105+ atomic_json(path.with_suffix('.json'),dict(file=path.name,sha256=digest(path),
106+ source_sha=state['source_sha'],diagnostic=True,performance_acceptance=False))
107+ producer=torch.npu.Event();producer.record(consumer)
108+ torch.npu.synchronize();dist.barrier()
109+ if rank==args.delay_owner and iteration==0:time.sleep(.03)
110+ begin,end=torch.npu.Event(enable_timing=True),torch.npu.Event(enable_timing=True)
111+ visible=[torch.npu.Event(),torch.npu.Event()]
112+ with torch.npu.stream(q0):
113+ q0.wait_event(producer);begin.record(q0)
114+ for projection in range(2):
115+ buffer._prefetch_expert_weights(plan,sources[projection],destinations[projection])
116+ visible[projection].record(q0)
117+ for event in visible:consumer.wait_event(event)
118+ end.record(consumer);end.synchronize()
119+ elapsed=float(begin.elapsed_time(end))
120+ for projection in range(2):
121+ for slot,expert in enumerate(rows[rank]):
122+ want=(torch.full_like(patterns[projection],-17) if expert<0 else
123+ patterns[projection]+float(expert*16+projection*2+iteration%4))
124+ if not torch.equal(destinations[projection][slot],want):
125+ if args.payload_diag:
126+ path=args.out/f'payload_mismatch_rank{rank}_iter{iteration}_proj{projection}_slot{slot}.pt'
127+ actual=destinations[projection][slot].detach().cpu()
128+ expected_value=want.detach().cpu()
129+ torch.save(dict(actual=actual,expected=expected_value,
130+ destination=destinations[projection].detach().cpu(),plan=plan.experts_to_copy.detach().cpu()),path)
131+ state['first_mismatch']=dict(iteration=iteration,projection=projection,slot=slot,
132+ expert=expert,owner=expert//local_experts,local_expert=expert%local_experts,
133+ actual=actual.flatten().tolist(),expected=expected_value.flatten().tolist(),
134+ file=path.name,sha256=digest(path))
135+ raise AssertionError(f'payload mismatch rank={rank} iteration={iteration} projection={projection} slot={slot}')
136+ nbytes=sum(math.prod(shape)*2 for shape in shapes)
137+ tx=sum(expert>=0 and expert//local_experts==rank and receiver!=rank
138+ for receiver,row in enumerate(rows) for expert in row)*nbytes
139+ rx=sum(expert>=0 and expert//local_experts!=rank for expert in rows[rank])*nbytes
140+ if args.kind=='formula' and (tx!=924844032 or rx!=924844032):raise AssertionError('formula bytes changed')
141+ state['records'].append(dict(iteration=iteration,warmup=iteration<args.warmup,
142+ milliseconds=elapsed,tx_bytes=tx,rx_bytes=rx,case=case,payload_exact=True))
143+ torch.npu.synchronize();dist.barrier();ShmemRuntime.finalize()
144+ destinations.clear();buffer.destroy()
145+ for allocation in reversed(allocations):allocation._vmm_allocation.destroy()
146+ if symmetric_descriptors():raise AssertionError('live allocation after teardown')
147+ reset_symmetric_descriptors()
148+ state.update(schema=1,rank=rank,world=world,physical_device=local,engine=args.engine,
149+ kind=args.kind,shapes=shapes,benchmark_sha256=digest(__file__),status='PASS',closed=True)
150+ state.pop('_keepalive')
151+ atomic_json(args.out/f'rank{rank}.json',state)
152+ dist.destroy_process_group()
153+ 
154+ 
155+def main():
156+ parser=argparse.ArgumentParser(description=__doc__)
157+ parser.add_argument('--engine',choices=('mte','urma'),required=True)
158+ parser.add_argument('--kind',choices=('sentinel','formula'),default='sentinel')
159+ parser.add_argument('--multi-chunk',action='store_true')
160+ parser.add_argument('--delay-owner',type=int,default=-1)
161+ parser.add_argument('--payload-diag',action='store_true')
162+ parser.add_argument('--expect-source',required=True)
163+ parser.add_argument('--build-identity',type=Path,required=True)
164+ parser.add_argument('--warmup',type=int,default=10)
165+ parser.add_argument('--iters',type=int,default=50)
166+ parser.add_argument('--out',type=Path,required=True)
167+ args=parser.parse_args();args.out.mkdir(parents=True,exist_ok=True)
168+ state=dict(rank=int(os.environ['RANK']),records=[],closed=False)
169+ try:run(args,state)
170+ except BaseException:
171+ # Keep backing reachable until process termination on uncertain completion.
172+ failure={k:v for k,v in state.items() if k!='_keepalive'}
173+ failure['traceback']=traceback.format_exc()
174+ atomic_json(args.out/f'failure_rank{state["rank"]}.json',failure)
175+ raise
176+ 
177+ 
178+if __name__=='__main__':main()
@@ -0,0 +1,36 @@
1+"""Canonical local-home proof. No allocation, runtime initialization or copies."""
2+ 
3+ 
4+def canonical_contiguous_home(refs):
5+ """Return a legal [L,M,N] alias, or reject before a native submission.
6+ 
7+ Tensor-local contiguity alone says nothing about inter-expert order. The
8+ shared storage, positive dense offsets and full extent are all required.
9+ Parameter objects need not be replaced or rebound.
10+ """
11+ refs = tuple(refs)
12+ if not refs:
13+ raise ValueError('continuous source requires local expert references')
14+ first = refs[0]
15+ if first.ndim != 2 or not first.is_contiguous():
16+ raise ValueError('continuous source requires contiguous expert matrices')
17+ shape, elements = tuple(first.shape), first.numel()
18+ if elements <= 0 or str(first.dtype) != 'torch.bfloat16':
19+ raise ValueError('continuous source requires nonempty BF16 matrices')
20+ storage = first.untyped_storage()
21+ start, size = first.storage_offset(), first.element_size()
22+ for index, ref in enumerate(refs):
23+ if (tuple(ref.shape) != shape or ref.dtype != first.dtype or
24+ ref.device != first.device or not ref.is_contiguous()):
25+ raise ValueError('continuous source matrix contracts differ')
26+ if ref.untyped_storage()._cdata != storage._cdata:
27+ raise ValueError('continuous source requires one legal canonical backing')
28+ if (ref.storage_offset() != start + index * elements or
29+ ref.data_ptr() != first.data_ptr() + index * elements * size):
30+ raise ValueError('continuous source requires positive dense expert order')
31+ if start < 0 or (start + len(refs) * elements) * size > storage.nbytes():
32+ raise ValueError('continuous source exceeds canonical storage extent')
33+ # as_strided checks the same actual Storage bounds; detach owns independent
34+ # metadata and retains the original backing if a Parameter wrapper changes.
35+ return first.detach().as_strided(
36+ (len(refs), *shape), (elements, shape[1], 1), storage_offset=start)
Mnpu_patch/native/CMakeLists.txt+1-0File content is under review, please try again later
Mnpu_patch/native/csrc/lplusb_runtime.cpp+73-4File content is under review, please try again later
@@ -4,6 +4,12 @@
4 4 
5namespace ascend_moonep {5namespace ascend_moonep {
6 6 
7+bool LPlusBUrmaAvailable();
8+void LPlusBOwnerPushUrmaContiguous(torch::Tensor home, torch::Tensor slots,
9+ torch::Tensor plan, int64_t rank, int64_t global_experts);
10+void LPlusBOwnerPushUrma(torch::Tensor pointers, torch::Tensor slots,
11+ torch::Tensor plan, int64_t rank, int64_t local_experts);
12+ 
7void LPlusBOwnerReadyInit(torch::Tensor ready);13void LPlusBOwnerReadyInit(torch::Tensor ready);
8 14 
9void LPlusBOwnerPush(15void LPlusBOwnerPush(
Mnpu_patch/native/csrc/pybind.cpp+9-0File content is under review, please try again later
Mnpu_patch/native/include/ascend_moonep/kernels/launch.h+5-0File content is under review, please try again later
Anpu_patch/native/kernels/lplusb_urma_push.cpp+21-0File content is under review, please try again later