Draft
[WIP] feat(npu): unify URMA PUSH APIs and L+B sync/async prefetch #9
Jia_AustinAdd on Oct 21
[WIP] feat(npu): unify URMA PUSH APIs and L+B sync/async prefetch #9
Draft
Total: 96 files changed+17844-2615
| @@ -0,0 +1,3 @@ | |||
| 1 | +{ | ||
| 2 | + "cmake.sourceDirectory": "D:/Workspace/z00984998/MoonEP_FBoverlap/moonfb/MoonEP/npu_patch/native" | ||
| 3 | +} | ||
| @@ -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. | ||
| @@ -0,0 +1,215 @@ | |||
| 1 | +"""Execute the production Buffer methods with host fakes, without torch/CANN. | ||
| 2 | + | ||
| 3 | +These tests prove Python ordering/ownership and failure rules, not native | ||
| 4 | +asynchrony, peer completion or actual overlap. | ||
| 5 | +""" | ||
| 6 | + | ||
| 7 | +import ast | ||
| 8 | +from dataclasses import dataclass | ||
| 9 | +import gc | ||
| 10 | +from pathlib import Path | ||
| 11 | +import types | ||
| 12 | +import unittest | ||
| 13 | +import warnings | ||
| 14 | +import weakref | ||
| 15 | +import runpy | ||
| 16 | + | ||
| 17 | + | ||
| 18 | +API = Path(__file__).resolve().parents[1] / "npu_patch" / "api.py" | ||
| 19 | + | ||
| 20 | + | ||
| 21 | +class Tensor: | ||
| 22 | + def __init__(self, shape, dtype="bf16", address=1000, device=0): | ||
| 23 | + self.shape = shape | ||
| 24 | + self.ndim = len(shape) | ||
| 25 | + self.dtype = dtype | ||
| 26 | + self.address = address | ||
| 27 | + self.device = device | ||
| 28 | + | ||
| 29 | + def is_contiguous(self): | ||
| 30 | + return True | ||
| 31 | + | ||
| 32 | + def data_ptr(self): | ||
| 33 | + return self.address | ||
| 34 | + | ||
| 35 | + def detach(self): | ||
| 36 | + # Independent metadata over the same modelled backing. Actual storage | ||
| 37 | + # retention is tested separately with real CPU torch storage handles. | ||
| 38 | + return Tensor(self.shape, self.dtype, self.address, self.device) | ||
| 39 | + | ||
| 40 | + def numel(self): | ||
| 41 | + result = 1 | ||
| 42 | + for dim in self.shape: | ||
| 43 | + result *= dim | ||
| 44 | + return result | ||
| 45 | + | ||
| 46 | + def element_size(self): | ||
| 47 | + return 2 if self.dtype == "bf16" else 8 | ||
| 48 | + | ||
| 49 | + | ||
| 50 | +class Plan: | ||
| 51 | + dedup_mode = 'rank' | ||
| 52 | + | ||
| 53 | + def __init__(self): | ||
| 54 | + self.experts_to_copy = Tensor((2, 2), "i32", 7000) | ||
| 55 | + | ||
| 56 | + | ||
| 57 | +class PeerFences: | ||
| 58 | + """A tiny controllable device-fence model shared by fake ranks.""" | ||
| 59 | + | ||
| 60 | + def __init__(self, world=1): | ||
| 61 | + self.world = world | ||
| 62 | + self.rounds = {} | ||
| 63 | + | ||
| 64 | + def arrive(self, generation, rank, dependencies): | ||
| 65 | + arrivals = self.rounds.setdefault(generation, {}) | ||
| 66 | + if rank in arrivals: | ||
| 67 | + raise AssertionError("duplicate native fence submission") | ||
| 68 | + arrivals[rank] = tuple(dependencies) | ||
| 69 | + fences = self | ||
| 70 | + | ||
| 71 | + class Fence: | ||
| 72 | + def is_ready(self): | ||
| 73 | + return (len(arrivals) == fences.world and | ||
| 74 | + all(dep.is_ready() for deps in arrivals.values() for dep in deps)) | ||
| 75 | + | ||
| 76 | + return Fence() | ||
| 77 | + | ||
| 78 | + | ||
| 79 | +class Environment: | ||
| 80 | + def __init__(self, peers=None, rank=0): | ||
| 81 | + self.trace = [] | ||
| 82 | + self.fail = None | ||
| 83 | + self.initialized = True | ||
| 84 | + self.native_hook = None | ||
| 85 | + self.peers = peers or PeerFences() | ||
| 86 | + self.rank = rank | ||
| 87 | + self.fence_round = 0 | ||
| 88 | + env = self | ||
| 89 | + | ||
| 90 | + class Event: | ||
| 91 | + def __init__(self, stream): | ||
| 92 | + self.stream = stream | ||
| 93 | + self.dependencies = tuple(stream.dependencies) | ||
| 94 | + self.completed = not stream.blocked | ||
| 95 | + | ||
| 96 | + def is_ready(self): | ||
| 97 | + return self.completed and all(dep.is_ready() for dep in self.dependencies) | ||
| 98 | + | ||
| 99 | + def query(self): | ||
| 100 | + env.trace.append(("query", self.stream.name)) | ||
| 101 | + if env.fail == "query": | ||
| 102 | + raise RuntimeError("event query failed") | ||
| 103 | + return self.is_ready() | ||
| 104 | + | ||
| 105 | + class Stream: | ||
| 106 | + def __init__(self, device=0, priority=0, name="q0"): | ||
| 107 | + self.device = device | ||
| 108 | + self.name = name | ||
| 109 | + self.npu_stream = 17 | ||
| 110 | + self.dependencies = [] | ||
| 111 | + self.blocked = False | ||
| 112 | + | ||
| 113 | + def record_event(self): | ||
| 114 | + env.trace.append(("record", self.name)) | ||
| 115 | + if env.fail == ("record", self.name): | ||
| 116 | + raise RuntimeError("record failed") | ||
| 117 | + return Event(self) | ||
| 118 | + | ||
| 119 | + def wait_event(self, event): | ||
| 120 | + env.trace.append(("wait", self.name, event.stream.name)) | ||
| 121 | + if env.fail == ("wait", self.name): | ||
| 122 | + raise RuntimeError("wait failed") | ||
| 123 | + self.dependencies.append(event) | ||
| 124 | + | ||
| 125 | + def synchronize(self): | ||
| 126 | + env.trace.append(("sync", self.name)) | ||
| 127 | + raise AssertionError("unexpected blocking stream wait") | ||
| 128 | + | ||
| 129 | + self.Stream = Stream | ||
| 130 | + self.producer = Stream(name="producer") | ||
| 131 | + self.current = self.producer | ||
| 132 | + | ||
| 133 | + class StreamContext: | ||
| 134 | + def __init__(self, stream): | ||
| 135 | + self.stream = stream | ||
| 136 | + | ||
| 137 | + def __enter__(self): | ||
| 138 | + self.previous = env.current | ||
| 139 | + env.current = self.stream | ||
| 140 | + | ||
| 141 | + def __exit__(self, *exc): | ||
| 142 | + env.current = self.previous | ||
| 143 | + | ||
| 144 | + def make_pointer_table(addresses, dtype, device): | ||
| 145 | + env.trace.append(("metadata", env.current.name)) | ||
| 146 | + tensor = Tensor((len(addresses),), dtype, 8000, device) | ||
| 147 | + tensor.values = tuple(addresses) | ||
| 148 | + return tensor | ||
| 149 | + | ||
| 150 | + def native(*args): | ||
| 151 | + env.trace.append(("native", env.current.name)) | ||
| 152 | + if env.native_hook: | ||
| 153 | + env.native_hook(args) | ||
| 154 | + if env.fail == "native": | ||
| 155 | + raise RuntimeError("native submit uncertain") | ||
| 156 | + | ||
| 157 | + def peer_fence(stream): | ||
| 158 | + env.trace.append(("peer_fence", env.current.name)) | ||
| 159 | + assert stream == env.current.npu_stream | ||
| 160 | + if env.fail == "peer_fence": | ||
| 161 | + raise RuntimeError("peer fence submit uncertain") | ||
| 162 | + fence = env.peers.arrive(env.fence_round, env.rank, env.current.dependencies) | ||
| 163 | + env.fence_round += 1 | ||
| 164 | + env.current.dependencies.append(fence) | ||
| 165 | + | ||
| 166 | + class Allocation: | ||
| 167 | + def destroy(self): | ||
| 168 | + env.trace.append(("free",)) | ||
| 169 | + | ||
| 170 | + def create_context(*args, **kwargs): | ||
| 171 | + def grad_reduce(ctx, table, slot, plan, *, rank, num_sms): | ||
| 172 | + native(table, slot, plan, rank, slot.shape[0]) | ||
| 173 | + return { | ||
| 174 | + "device": 0, "rank": env.rank, "group": None, | ||
| 175 | + "_shmem_views_ready": True, "num_sms": 32, | ||
| 176 | + "kernels": {"grad_reduce": types.SimpleNamespace(compute_targets=grad_reduce, destroy=lambda: None)}, | ||
| 177 | + "vmm_chunks": {name: Allocation() for name in ( | ||
| 178 | + "hidden_buf", "weights_buf", "barrier_buf")}, | ||
| 179 | + } | ||
| 180 | + | ||
| 181 | + tree = ast.parse(API.read_text(encoding="utf-8")) | ||
| 182 | + classes = [node for node in tree.body if isinstance(node, ast.ClassDef) | ||
| 183 | + and node.name in ("Buffer", "_PrefetchReceipt", "_PrefetchOperation")] | ||
| 184 | + helpers = [node for node in tree.body if isinstance(node, ast.FunctionDef) | ||
| 185 | + and node.name == '_async_stream_barrier'] | ||
| 186 | + future = ast.ImportFrom(module="__future__", names=[ast.alias(name="annotations")], level=0) | ||
| 187 | + module = ast.fix_missing_locations(ast.Module(body=[future, *helpers, *classes], type_ignores=[])) | ||
| 188 | + self.namespace = { | ||
| 189 | + "__name__": __name__, "dataclass": dataclass, | ||
| 190 | + "grad_reduce_workspace_elements": runpy.run_path(str(API.parent / '_grad_reduce_contract.py'))['workspace_elements'], | ||
| 191 | + "warnings": warnings, "Sequence": tuple, | ||
| 192 | + "_create_context": create_context, | ||
| 193 | + "_logical_context_from_plan": lambda *args: None, | ||
| 194 | + "create_sym_tensor_from_ptr": lambda pointer, shape, dtype, device: Tensor(shape, dtype, pointer, device), | ||
| 195 | + "MoonEPCommPlan": Plan, | ||
| 196 | + "_C": types.SimpleNamespace(_lplusb_owner_push=native, _lplusb_owner_reduce=native, LPLUS_B_BUFFER_SYNC_ABI=2, | ||
| 197 | + GRAD_REDUCE_POINTER_ABI=1, | ||
| 198 | + acl_shmem_barrier_all_on_stream=peer_fence), | ||
| 199 | + "ShmemRuntime": types.SimpleNamespace(is_initialized=lambda: env.initialized), | ||
| 200 | + "torch": types.SimpleNamespace( | ||
| 201 | + Tensor=Tensor, bfloat16="bf16", int32="i32", int64="i64", | ||
| 202 | + float32="fp32", tensor=make_pointer_table), | ||
| 203 | + "torch_npu": types.SimpleNamespace(npu=types.SimpleNamespace( | ||
| 204 | + Stream=Stream, stream=StreamContext, | ||
| 205 | + current_stream=lambda device=None: env.current, | ||
| 206 | + synchronize=lambda: env.trace.append(("device_sync",)))), | ||
| 207 | + "dist": types.SimpleNamespace( | ||
| 208 | + is_initialized=lambda: True, | ||
| 209 | + barrier=lambda **kwargs: env.trace.append(("barrier",))), | ||
| 210 | + } | ||
| 211 | + exec(compile(module, str(API), "exec"), self.namespace) | ||
| 212 | + self.Buffer = self.namespace["Buffer"] | ||
| 213 | + | ||
| 214 | + def buffer(self): | ||
| 215 | + return self.Buffer(4, 5, 1, 4, 2, explicitly_destroy=True) | ||
| @@ -0,0 +1,73 @@ | |||
| 1 | +"""P2 dry-run capacity depends on final-use intervals, not cycle counts.""" | ||
| 2 | + | ||
| 3 | +import importlib.util | ||
| 4 | +from pathlib import Path | ||
| 5 | +import sys | ||
| 6 | +import types | ||
| 7 | +import unittest | ||
| 8 | + | ||
| 9 | + | ||
| 10 | +SOURCE = Path(__file__).resolve().parents[1] / "npu_patch" | ||
| 11 | +package = types.ModuleType("_moonep_capacity_host") | ||
| 12 | +package.__path__ = [str(SOURCE)] | ||
| 13 | +sys.modules[package.__name__] = package | ||
| 14 | +for name in ("async_session", "async_capacity"): | ||
| 15 | + spec = importlib.util.spec_from_file_location(f"{package.__name__}.{name}", SOURCE / f"{name}.py") | ||
| 16 | + module = importlib.util.module_from_spec(spec) | ||
| 17 | + sys.modules[spec.name] = module | ||
| 18 | + spec.loader.exec_module(module) | ||
| 19 | +capacity = sys.modules[f"{package.__name__}.async_capacity"] | ||
| 20 | +LeaseInterval = capacity.LeaseInterval | ||
| 21 | + | ||
| 22 | + | ||
| 23 | +class CapacityContractTest(unittest.TestCase): | ||
| 24 | + def test_f1_and_b0_keep_their_banks_until_real_final_use(self): | ||
| 25 | + leases = [ | ||
| 26 | + LeaseInterval("fc1_weight", "F0", 0, 6, (2, 128, 256), "bf16"), | ||
| 27 | + LeaseInterval("fc1_weight", "F1", 3, 9, (2, 128, 256), "bf16"), | ||
| 28 | + LeaseInterval("fc1_weight", "B0", 6, 12, (2, 128, 256), "bf16"), | ||
| 29 | + LeaseInterval("Z3", "B0", 5, 11, (32, 128), "bf16"), | ||
| 30 | + LeaseInterval("R1", "B0", 7, 10, (32, 128), "bf16"), | ||
| 31 | + ] | ||
| 32 | + plan = capacity.derive_capacity(leases) | ||
| 33 | + self.assertEqual(plan.pools["fc1_weight"].count, 2) | ||
| 34 | + self.assertEqual([bank.index for bank in plan.assignments[:3]], [0, 1, 0]) | ||
| 35 | + self.assertNotEqual(plan.assignments[3].role, plan.assignments[4].role) | ||
| 36 | + # A cycle boundary is not sufficient if B0 still reads F0's bank. | ||
| 37 | + delayed = [*leases] | ||
| 38 | + delayed[0] = LeaseInterval("fc1_weight", "F0", 0, 7, (2, 128, 256), "bf16") | ||
| 39 | + self.assertEqual(capacity.derive_capacity(delayed).pools["fc1_weight"].count, 3) | ||
| 40 | + | ||
| 41 | + def test_half_open_final_use_allows_reuse_at_exact_boundary(self): | ||
| 42 | + leases = [LeaseInterval("Z1", "F0", 0, 3, (32, 128), "bf16"), | ||
| 43 | + LeaseInterval("Z1", "F1", 3, 6, (16, 128), "bf16")] | ||
| 44 | + plan = capacity.derive_capacity(leases) | ||
| 45 | + self.assertEqual(plan.pools["Z1"].count, 1) | ||
| 46 | + self.assertEqual(plan.pools["Z1"].shape, (32, 128)) | ||
| 47 | + self.assertEqual(plan.assignments[0], plan.assignments[1]) | ||
| 48 | + | ||
| 49 | + def test_rank_manifest_is_address_free_and_physical_bytes_are_granular(self): | ||
| 50 | + leases = [LeaseInterval("fc2_grad", (0, "B0"), 0, 2, (2, 256, 128), "fp32")] | ||
| 51 | + plan = capacity.derive_capacity(leases) | ||
| 52 | + manifest = plan.manifest(topology={"EP": 2, "TP": 1}, granularity=2 * 1024 * 1024) | ||
| 53 | + self.assertEqual(manifest["banks"]["fc2_grad"]["count"], 1) | ||
| 54 | + self.assertEqual(plan.physical_bytes(2 * 1024 * 1024), 2 * 1024 * 1024) | ||
| 55 | + self.assertEqual(capacity.manifest_digest(manifest), capacity.manifest_digest(dict(manifest))) | ||
| 56 | + self.assertNotIn("B0", str(manifest)) | ||
| 57 | + self.assertNotIn("0x", str(manifest)) | ||
| 58 | + different = plan.manifest(topology={"EP": 4, "TP": 1}, granularity=2 * 1024 * 1024) | ||
| 59 | + self.assertNotEqual(capacity.manifest_digest(manifest), capacity.manifest_digest(different)) | ||
| 60 | + | ||
| 61 | + def test_mixed_dtype_or_invalid_final_use_fails_before_allocation(self): | ||
| 62 | + for bad in ( | ||
| 63 | + [LeaseInterval("Z1", "F0", 1, 1, (32, 128), "bf16")], | ||
| 64 | + [LeaseInterval("Z1", "F0", 1, 2, (32, 128), "bf16"), | ||
| 65 | + LeaseInterval("Z1", "F1", 2, 3, (32, 128), "fp32")], | ||
| 66 | + [LeaseInterval("Z1", None, 1, 2, (32, 128), "bf16")], | ||
| 67 | + ): | ||
| 68 | + with self.subTest(bad=bad), self.assertRaises(ValueError): | ||
| 69 | + capacity.derive_capacity(bad) | ||
| 70 | + | ||
| 71 | + | ||
| 72 | +if __name__ == "__main__": | ||
| 73 | + unittest.main() | ||
| @@ -0,0 +1,100 @@ | |||
| 1 | +"""Real P2 lane methods with controllable stream and native-fence fakes.""" | ||
| 2 | + | ||
| 3 | +import importlib.util | ||
| 4 | +from pathlib import Path | ||
| 5 | +import sys | ||
| 6 | +import types | ||
| 7 | +import unittest | ||
| 8 | + | ||
| 9 | +from host_tests.async_fakes import Environment, PeerFences | ||
| 10 | + | ||
| 11 | + | ||
| 12 | +SOURCE = Path(__file__).resolve().parents[1] / "npu_patch" | ||
| 13 | +package = types.ModuleType("_moonep_lane_host") | ||
| 14 | +package.__path__ = [str(SOURCE)] | ||
| 15 | +sys.modules[package.__name__] = package | ||
| 16 | +for name in ("async_session", "async_lane"): | ||
| 17 | + spec = importlib.util.spec_from_file_location(f"{package.__name__}.{name}", SOURCE / f"{name}.py") | ||
| 18 | + module = importlib.util.module_from_spec(spec) | ||
| 19 | + sys.modules[spec.name] = module | ||
| 20 | + spec.loader.exec_module(module) | ||
| 21 | +session = sys.modules[f"{package.__name__}.async_session"] | ||
| 22 | +AsyncLane = sys.modules[f"{package.__name__}.async_lane"].AsyncLane | ||
| 23 | + | ||
| 24 | + | ||
| 25 | +class AsyncLaneContractTest(unittest.TestCase): | ||
| 26 | + def lane(self, env): | ||
| 27 | + return AsyncLane(q0=env.Stream(name="q0"), | ||
| 28 | + stream_context=env.namespace["torch_npu"].npu.stream, | ||
| 29 | + native_release_barrier=env.namespace["_C"].acl_shmem_barrier_all_on_stream, | ||
| 30 | + bank_capacities={"weight": 2}) | ||
| 31 | + | ||
| 32 | + def submit(self, lane, env, ordinal, bank): | ||
| 33 | + return lane.submit(generation=(0, ordinal), kind=session.OperationKind.PREFETCH_FC1, | ||
| 34 | + ordinal=ordinal, banks=(session.BankKey("weight", bank),), | ||
| 35 | + resources=(object(),), producer_stream=env.producer, | ||
| 36 | + native_submit=lambda: env.namespace["_C"]._lplusb_owner_push()) | ||
| 37 | + | ||
| 38 | + def test_multi_live_fifo_and_release_only_after_native_peer_fence(self): | ||
| 39 | + peers = PeerFences(world=2) | ||
| 40 | + env0, env1 = Environment(peers, 0), Environment(peers, 1) | ||
| 41 | + lanes = [self.lane(env0), self.lane(env1)] | ||
| 42 | + envs = [env0, env1] | ||
| 43 | + first = [self.submit(lane, env, 0, 0) for lane, env in zip(lanes, envs)] | ||
| 44 | + second = [self.submit(lane, env, 1, 1) for lane, env in zip(lanes, envs)] | ||
| 45 | + consumers = [env.Stream(name="consumer") for env in envs] | ||
| 46 | + consumers[1].blocked = True | ||
| 47 | + for lane, receipt, consumer in zip(lanes, first, consumers): | ||
| 48 | + lane.wait_peer_visible(receipt, consumer_stream=consumer) | ||
| 49 | + lane.record_final_use(receipt, consumer_stream=consumer) | ||
| 50 | + self.assertFalse(lanes[0].try_release(first[0], ordinal=2)) | ||
| 51 | + self.assertFalse(lanes[1].try_release(first[1], ordinal=2)) | ||
| 52 | + self.assertEqual(lanes[0].session.active_count, 2) | ||
| 53 | + self.assertEqual(env0.trace.count(("peer_fence", "q0")), 1) | ||
| 54 | + lanes[1].session._rows[first[1].ordinal].final_use.completed = True | ||
| 55 | + self.assertTrue(lanes[0].try_release(first[0], ordinal=2)) | ||
| 56 | + self.assertTrue(lanes[1].try_release(first[1], ordinal=2)) | ||
| 57 | + self.assertEqual(lanes[0].session.active_count, 1) | ||
| 58 | + self.assertIs(lanes[0].session.row_for(second[0]).receipt, second[0]) | ||
| 59 | + self.assertFalse(any(event[0] in ("sync", "device_sync", "barrier") | ||
| 60 | + for env in envs for event in env.trace)) | ||
| 61 | + | ||
| 62 | + def test_native_failure_poisons_and_retains_rows(self): | ||
| 63 | + env = Environment() | ||
| 64 | + lane = self.lane(env) | ||
| 65 | + env.fail = "native" | ||
| 66 | + with self.assertRaisesRegex(RuntimeError, "native submit uncertain"): | ||
| 67 | + self.submit(lane, env, 0, 0) | ||
| 68 | + self.assertTrue(lane.session.poisoned) | ||
| 69 | + self.assertEqual(lane.session.active_count, 1) | ||
| 70 | + with self.assertRaisesRegex(RuntimeError, "POISONED"): | ||
| 71 | + self.submit(lane, env, 1, 1) | ||
| 72 | + | ||
| 73 | + def test_release_consumes_ordered_q0_step_once(self): | ||
| 74 | + env = Environment() | ||
| 75 | + lane = self.lane(env) | ||
| 76 | + receipt = self.submit(lane, env, 0, 0) | ||
| 77 | + consumer = env.Stream(name="consumer") | ||
| 78 | + lane.wait_peer_visible(receipt, consumer_stream=consumer) | ||
| 79 | + lane.record_final_use(receipt, consumer_stream=consumer) | ||
| 80 | + with self.assertRaisesRegex(ValueError, "out-of-order"): | ||
| 81 | + lane.try_release(receipt, ordinal=2) | ||
| 82 | + self.assertEqual(lane.session.next_ordinal, 1) | ||
| 83 | + self.assertTrue(lane.try_release(receipt, ordinal=1)) | ||
| 84 | + self.assertEqual(lane.session.next_ordinal, 2) | ||
| 85 | + | ||
| 86 | + def test_final_use_is_exactly_once_and_one_consumer_stream(self): | ||
| 87 | + env = Environment() | ||
| 88 | + lane = self.lane(env) | ||
| 89 | + receipt = self.submit(lane, env, 0, 0) | ||
| 90 | + a, b = env.Stream(name="a"), env.Stream(name="b") | ||
| 91 | + lane.wait_peer_visible(receipt, consumer_stream=a) | ||
| 92 | + with self.assertRaisesRegex(ValueError, "one declared consumer"): | ||
| 93 | + lane.wait_peer_visible(receipt, consumer_stream=b) | ||
| 94 | + lane.record_final_use(receipt, consumer_stream=a) | ||
| 95 | + with self.assertRaisesRegex(RuntimeError, "exactly once"): | ||
| 96 | + lane.record_final_use(receipt, consumer_stream=a) | ||
| 97 | + | ||
| 98 | + | ||
| 99 | +if __name__ == "__main__": | ||
| 100 | + unittest.main() | ||
| @@ -0,0 +1,163 @@ | |||
| 1 | +"""Real provider batch methods: ordering, delayed peers and uncertain failure.""" | ||
| 2 | +import gc | ||
| 3 | +import unittest | ||
| 4 | +import weakref | ||
| 5 | + | ||
| 6 | +from host_tests.async_fakes import Environment, PeerFences | ||
| 7 | +from host_tests.test_async_lane import AsyncLane, session | ||
| 8 | + | ||
| 9 | + | ||
| 10 | +class ReleaseBatchTest(unittest.TestCase): | ||
| 11 | + def prepared(self, env=None, *, missing_final=False, generation=(0, 'layer', 0)): | ||
| 12 | + env = env or Environment() | ||
| 13 | + kind = session.OperationKind.PREFETCH_FC1 | ||
| 14 | + steps = [('submit', kind, generation)] * 2 + [('release', kind, generation)] * 2 | ||
| 15 | + lane = AsyncLane(q0=env.Stream(name='q0'), | ||
| 16 | + stream_context=env.namespace['torch_npu'].npu.stream, | ||
| 17 | + native_release_barrier=env.namespace['_C'].acl_shmem_barrier_all_on_stream, | ||
| 18 | + bank_capacities={'weight': 2}, expected_steps=steps) | ||
| 19 | + receipts = [] | ||
| 20 | + consumer = env.Stream(name='consumer') | ||
| 21 | + for index in range(2): | ||
| 22 | + receipt = lane.submit(generation=generation, kind=kind, ordinal=index, | ||
| 23 | + banks=(session.BankKey('weight', index),), resources=(object(),), | ||
| 24 | + producer_stream=env.producer, native_submit=lambda: None) | ||
| 25 | + lane.wait_peer_visible(receipt, consumer_stream=consumer) | ||
| 26 | + if not (missing_final and index == 1): | ||
| 27 | + lane.record_final_use(receipt, consumer_stream=consumer) | ||
| 28 | + receipts.append(receipt) | ||
| 29 | + env.trace.clear() | ||
| 30 | + return env, lane, tuple((r, i + 2) for i, r in enumerate(receipts)) | ||
| 31 | + | ||
| 32 | + def test_all_fences_queued_before_first_query_same_order_no_early_retirement(self): | ||
| 33 | + env, lane, steps = self.prepared() | ||
| 34 | + lane.session.row_for(steps[0][0]).final_use.completed = False | ||
| 35 | + self.assertEqual(lane.try_release_batch(steps), 0) | ||
| 36 | + self.assertEqual(lane.session.next_ordinal, 4) | ||
| 37 | + self.assertEqual(lane.session.active_count, 2) | ||
| 38 | + self.assertEqual(lane.session.active_bank_count, 2) | ||
| 39 | + first_query = env.trace.index(('query', 'q0')) | ||
| 40 | + self.assertEqual(env.trace[:first_query].count(('peer_fence', 'q0')), 2) | ||
| 41 | + before = env.fence_round | ||
| 42 | + self.assertEqual(lane.try_release_batch(steps), 0) | ||
| 43 | + self.assertEqual(env.fence_round, before) | ||
| 44 | + lane.session.row_for(steps[0][0]).final_use.completed = True | ||
| 45 | + self.assertEqual(lane.try_release_batch(steps), 2) | ||
| 46 | + self.assertEqual(lane.session.active_count, 0) | ||
| 47 | + self.assertEqual(lane.session.active_bank_count, 0) | ||
| 48 | + | ||
| 49 | + def test_delayed_peer_holds_both_banks_until_native_peer_fences(self): | ||
| 50 | + peers = PeerFences(world=2) | ||
| 51 | + _, a, sa = self.prepared(Environment(peers, 0)) | ||
| 52 | + _, b, sb = self.prepared(Environment(peers, 1)) | ||
| 53 | + b.session.row_for(sb[1][0]).final_use.completed = False | ||
| 54 | + self.assertEqual(a.try_release_batch(sa), 0) | ||
| 55 | + self.assertEqual(b.try_release_batch(sb), 1) | ||
| 56 | + self.assertEqual(a.try_release_batch(sa), 1) | ||
| 57 | + self.assertEqual(a.session.active_bank_count, 1) | ||
| 58 | + b.session.row_for(sb[1][0]).final_use.completed = True | ||
| 59 | + self.assertEqual(a.try_release_batch(sa[1:]), 1) | ||
| 60 | + self.assertEqual(b.try_release_batch(sb[1:]), 1) | ||
| 61 | + | ||
| 62 | + def test_preflight_last_missing_final_use_has_zero_native_side_effect(self): | ||
| 63 | + env, lane, steps = self.prepared(missing_final=True) | ||
| 64 | + with self.assertRaisesRegex(RuntimeError, 'every final use'): | ||
| 65 | + lane.try_release_batch(steps) | ||
| 66 | + self.assertEqual(env.trace, []) | ||
| 67 | + self.assertEqual(lane.session.next_ordinal, 2) | ||
| 68 | + self.assertFalse(lane.session.poisoned) | ||
| 69 | + | ||
| 70 | + def test_invalid_batch_is_transactional(self): | ||
| 71 | + for mutate in ( | ||
| 72 | + lambda s: (s[0], s[0]), | ||
| 73 | + lambda s: (s[0], (s[1][0], 4)), | ||
| 74 | + lambda s: ((s[0][0], True), s[1]), | ||
| 75 | + lambda s: (s[1], s[0]), | ||
| 76 | + lambda s: (), | ||
| 77 | + ): | ||
| 78 | + env, lane, steps = self.prepared() | ||
| 79 | + with self.assertRaises((ValueError, TypeError)): | ||
| 80 | + lane.try_release_batch(mutate(steps)) | ||
| 81 | + self.assertEqual(env.trace, []) | ||
| 82 | + self.assertFalse(lane.session.poisoned) | ||
| 83 | + self.assertEqual(lane.session.next_ordinal, 2) | ||
| 84 | + | ||
| 85 | + def test_foreign_and_cross_generation_rejected_before_enqueue(self): | ||
| 86 | + env, lane, steps = self.prepared() | ||
| 87 | + _, other, other_steps = self.prepared() | ||
| 88 | + with self.assertRaisesRegex(ValueError, 'foreign'): | ||
| 89 | + lane.try_release_batch((steps[0], other_steps[1])) | ||
| 90 | + self.assertEqual(env.trace, []) | ||
| 91 | + # Deliberately represent a schedule that interleaves generations. | ||
| 92 | + # No native side effect is allowed even if ordinals would be valid. | ||
| 93 | + from dataclasses import replace | ||
| 94 | + row = lane.session.row_for(steps[1][0]) | ||
| 95 | + receipt = replace(row.receipt, generation=(1, 'layer', 0)) | ||
| 96 | + row.receipt = receipt | ||
| 97 | + with self.assertRaisesRegex(ValueError, 'one generation'): | ||
| 98 | + lane.try_release_batch((steps[0], (receipt, 3))) | ||
| 99 | + self.assertEqual(env.trace, []) | ||
| 100 | + | ||
| 101 | + def test_partial_enqueue_failure_poison_retains_all_resources(self): | ||
| 102 | + env, lane, steps = self.prepared() | ||
| 103 | + original = lane._native_release_barrier | ||
| 104 | + count = 0 | ||
| 105 | + def fail_second(stream): | ||
| 106 | + nonlocal count | ||
| 107 | + count += 1 | ||
| 108 | + if count == 2: | ||
| 109 | + raise RuntimeError('second enqueue uncertain') | ||
| 110 | + original(stream) | ||
| 111 | + lane._native_release_barrier = fail_second | ||
| 112 | + with self.assertRaisesRegex(RuntimeError, 'second enqueue'): | ||
| 113 | + lane.try_release_batch(steps) | ||
| 114 | + self.assertTrue(lane.session.poisoned) | ||
| 115 | + self.assertEqual(lane.session.active_count, 2) | ||
| 116 | + self.assertEqual(lane.session.active_bank_count, 2) | ||
| 117 | + self.assertFalse(any(t[0] == 'query' for t in env.trace)) | ||
| 118 | + | ||
| 119 | + def test_query_failure_poison_and_pending_storage_gc(self): | ||
| 120 | + class Resource: pass | ||
| 121 | + env, lane, steps = self.prepared() | ||
| 122 | + resource = Resource() | ||
| 123 | + ref = weakref.ref(resource) | ||
| 124 | + lane.session.row_for(steps[0][0]).resources += (resource,) | ||
| 125 | + del resource | ||
| 126 | + env.fail = 'query' | ||
| 127 | + with self.assertRaisesRegex(RuntimeError, 'query failed'): | ||
| 128 | + lane.try_release_batch(steps) | ||
| 129 | + gc.collect() | ||
| 130 | + self.assertIsNotNone(ref()) | ||
| 131 | + self.assertTrue(lane.session.poisoned) | ||
| 132 | + self.assertEqual(lane.session.active_bank_count, 2) | ||
| 133 | + | ||
| 134 | + def test_completed_prefix_only_and_retry_after_partial_retirement(self): | ||
| 135 | + env, lane, steps = self.prepared() | ||
| 136 | + lane.session.row_for(steps[1][0]).final_use.completed = False | ||
| 137 | + self.assertEqual(lane.try_release_batch(steps), 1) | ||
| 138 | + self.assertEqual(lane.session.active_count, 1) | ||
| 139 | + with self.assertRaisesRegex(ValueError, 'stale'): | ||
| 140 | + lane.try_release_batch(steps) | ||
| 141 | + lane.session.row_for(steps[1][0]).final_use.completed = True | ||
| 142 | + self.assertEqual(lane.try_release_batch(steps[1:]), 1) | ||
| 143 | + self.assertEqual(env.trace.count(('peer_fence', 'q0')), 2) | ||
| 144 | + | ||
| 145 | + def test_serial_path_still_queries_before_second_enqueue(self): | ||
| 146 | + env, lane, steps = self.prepared() | ||
| 147 | + for receipt, ordinal in steps: | ||
| 148 | + self.assertTrue(lane.try_release(receipt, ordinal=ordinal)) | ||
| 149 | + kinds = [item[0] for item in env.trace] | ||
| 150 | + fences = [i for i, kind in enumerate(kinds) if kind == 'peer_fence'] | ||
| 151 | + queries = [i for i, kind in enumerate(kinds) if kind == 'query'] | ||
| 152 | + self.assertLess(fences[0], queries[0]) | ||
| 153 | + self.assertLess(queries[0], fences[1]) | ||
| 154 | + | ||
| 155 | + def test_unfrozen_schedule_rejects_batch(self): | ||
| 156 | + env, lane, steps = self.prepared() | ||
| 157 | + lane.session._expected_steps = None | ||
| 158 | + with self.assertRaisesRegex(ValueError, 'frozen schedule'): | ||
| 159 | + lane.try_release_batch(steps) | ||
| 160 | + self.assertEqual(env.trace, []) | ||
| 161 | + | ||
| 162 | + | ||
| 163 | +if __name__ == '__main__': unittest.main() | ||
| @@ -0,0 +1,254 @@ | |||
| 1 | +"""The P2 provider ledger runs without torch; native completion needs NPU.""" | ||
| 2 | + | ||
| 3 | +import gc | ||
| 4 | +import importlib.util | ||
| 5 | +from pathlib import Path | ||
| 6 | +import threading | ||
| 7 | +import unittest | ||
| 8 | +import weakref | ||
| 9 | + | ||
| 10 | + | ||
| 11 | +SOURCE = Path(__file__).resolve().parents[1] / "npu_patch/async_session.py" | ||
| 12 | +spec = importlib.util.spec_from_file_location("async_session_contract", SOURCE) | ||
| 13 | +module = importlib.util.module_from_spec(spec) | ||
| 14 | +import sys | ||
| 15 | +sys.modules[spec.name] = module | ||
| 16 | +spec.loader.exec_module(module) | ||
| 17 | +AsyncSession = module.AsyncSession | ||
| 18 | +BankKey = module.BankKey | ||
| 19 | +OperationKind = module.OperationKind | ||
| 20 | +OperationReceipt = module.OperationReceipt | ||
| 21 | + | ||
| 22 | + | ||
| 23 | +class Backing: | ||
| 24 | + pass | ||
| 25 | + | ||
| 26 | + | ||
| 27 | +class AsyncSessionContractTest(unittest.TestCase): | ||
| 28 | + def session(self): | ||
| 29 | + return AsyncSession({"fc1_weight": 2, "Z1": 2, "R1": 1}) | ||
| 30 | + | ||
| 31 | + def test_multilive_generations_hold_distinct_banks_until_verified_retire(self): | ||
| 32 | + session = self.session() | ||
| 33 | + bank0, bank1 = BankKey("fc1_weight", 0), BankKey("fc1_weight", 1) | ||
| 34 | + first = session.submit(generation=(0, "F0"), kind=OperationKind.PREFETCH_FC1, | ||
| 35 | + ordinal=0, banks=(bank0,), enqueue=lambda row: None) | ||
| 36 | + second = session.submit(generation=(0, "F1"), kind=OperationKind.PREFETCH_FC1, | ||
| 37 | + ordinal=1, banks=(bank1,), enqueue=lambda row: None) | ||
| 38 | + self.assertEqual((session.active_count, session.next_ordinal), (2, 2)) | ||
| 39 | + self.assertIs(session.row_for(first, kind=OperationKind.PREFETCH_FC1).receipt, first) | ||
| 40 | + with self.assertRaisesRegex(RuntimeError, "still leased"): | ||
| 41 | + session.submit(generation=(0, "B0"), kind=OperationKind.PREFETCH_FC1, | ||
| 42 | + ordinal=2, banks=(bank0,), enqueue=lambda row: self.fail("native called")) | ||
| 43 | + self.assertEqual(session.next_ordinal, 2) | ||
| 44 | + session.retire_after_peer_final_use(first) | ||
| 45 | + third = session.submit(generation=(0, "B0"), kind=OperationKind.PREFETCH_FC1, | ||
| 46 | + ordinal=2, banks=(bank0,), enqueue=lambda row: None) | ||
| 47 | + self.assertEqual(session.active_count, 2) | ||
| 48 | + self.assertIsNot(third, second) | ||
| 49 | + with self.assertRaisesRegex(ValueError, "stale"): | ||
| 50 | + session.row_for(first) | ||
| 51 | + | ||
| 52 | + def test_empty_keeps_kind_and_ordinal_without_claiming_data_bank(self): | ||
| 53 | + seen = [] | ||
| 54 | + session = self.session() | ||
| 55 | + receipt = session.submit(generation=(0, "F0"), kind=OperationKind.PREFETCH_FC1, | ||
| 56 | + ordinal=0, empty=True, | ||
| 57 | + enqueue=lambda row: seen.append((row.receipt.kind, row.empty))) | ||
| 58 | + self.assertEqual(seen, [(OperationKind.PREFETCH_FC1, True)]) | ||
| 59 | + self.assertEqual(receipt.ordinal, 0) | ||
| 60 | + second = session.submit(generation=(0, "F1"), kind=OperationKind.PREFETCH_FC1, | ||
| 61 | + ordinal=1, empty=True, banks=(BankKey("Z1", 0),), enqueue=lambda row: None) | ||
| 62 | + self.assertTrue(session.row_for(second).empty) | ||
| 63 | + self.assertEqual(session.next_ordinal, 2) | ||
| 64 | + | ||
| 65 | + def test_invalid_ordinal_and_capacity_reject_before_native(self): | ||
| 66 | + session = self.session() | ||
| 67 | + called = [] | ||
| 68 | + enqueue = lambda row: called.append(row) | ||
| 69 | + for kwargs in ( | ||
| 70 | + dict(ordinal=1, banks=()), | ||
| 71 | + dict(ordinal=0, banks=(BankKey("unknown", 0),)), | ||
| 72 | + dict(ordinal=0, banks=(BankKey("Z1", 2),)), | ||
| 73 | + dict(ordinal=0, banks=(BankKey("Z1", 0), BankKey("Z1", 0))), | ||
| 74 | + ): | ||
| 75 | + with self.assertRaises((ValueError, RuntimeError)): | ||
| 76 | + session.submit(generation=(0, "F0"), kind=OperationKind.DISPATCH, | ||
| 77 | + enqueue=enqueue, **kwargs) | ||
| 78 | + self.assertEqual((called, session.next_ordinal, session.active_count), ([], 0, 0)) | ||
| 79 | + | ||
| 80 | + def test_callback_failure_poisons_session_and_retains_backing(self): | ||
| 81 | + for failure in (RuntimeError, KeyboardInterrupt): | ||
| 82 | + with self.subTest(failure=failure): | ||
| 83 | + session = self.session() | ||
| 84 | + backing = Backing() | ||
| 85 | + alive = weakref.ref(backing) | ||
| 86 | + | ||
| 87 | + def uncertain(row): | ||
| 88 | + self.assertEqual(row.state, "PREPARING") | ||
| 89 | + raise failure("native completion uncertain") | ||
| 90 | + | ||
| 91 | + with self.assertRaises(failure): | ||
| 92 | + session.submit(generation=(0, "F0"), kind=OperationKind.DISPATCH, | ||
| 93 | + ordinal=0, banks=(BankKey("Z1", 0),), | ||
| 94 | + resources=(backing,), enqueue=uncertain) | ||
| 95 | + del backing | ||
| 96 | + gc.collect() | ||
| 97 | + self.assertIsNotNone(alive()) | ||
| 98 | + self.assertTrue(session.poisoned) | ||
| 99 | + self.assertEqual(session.active_count, 1) | ||
| 100 | + self.assertEqual(session._rows[0].state, "POISONED") | ||
| 101 | + with self.assertRaisesRegex(RuntimeError, "POISONED"): | ||
| 102 | + session.submit(generation=(0, "F1"), kind=OperationKind.DISPATCH, | ||
| 103 | + ordinal=1, enqueue=lambda row: None) | ||
| 104 | + | ||
| 105 | + def test_receipt_identity_kind_generation_and_no_completion_claim(self): | ||
| 106 | + session = self.session() | ||
| 107 | + receipt = session.submit(generation=(0, "F0"), kind=OperationKind.COMBINE, | ||
| 108 | + ordinal=0, enqueue=lambda row: None) | ||
| 109 | + self.assertEqual(session.row_for(receipt).state, "SUBMITTED") | ||
| 110 | + self.assertFalse(hasattr(receipt, "peer_visible")) | ||
| 111 | + forged = OperationReceipt(receipt.session, receipt.ordinal, receipt.generation, receipt.kind) | ||
| 112 | + for token in (forged, AsyncSession({}).submit( | ||
| 113 | + generation=(0, "F0"), kind=OperationKind.COMBINE, | ||
| 114 | + ordinal=0, enqueue=lambda row: None)): | ||
| 115 | + with self.assertRaisesRegex(ValueError, "foreign or forged"): | ||
| 116 | + session.row_for(token) | ||
| 117 | + with self.assertRaisesRegex(ValueError, "kind mismatch"): | ||
| 118 | + session.row_for(receipt, kind=OperationKind.DISPATCH) | ||
| 119 | + with self.assertRaisesRegex(ValueError, "generation mismatch"): | ||
| 120 | + session.row_for(receipt, generation=(0, "F1")) | ||
| 121 | + | ||
| 122 | + def test_one_host_submission_thread(self): | ||
| 123 | + session = self.session() | ||
| 124 | + session.submit(generation=(0, "F0"), kind=OperationKind.EMPTY, | ||
| 125 | + ordinal=0, empty=True, enqueue=lambda row: None) | ||
| 126 | + errors = [] | ||
| 127 | + | ||
| 128 | + def from_other_thread(): | ||
| 129 | + try: | ||
| 130 | + session.submit(generation=(0, "F1"), kind=OperationKind.EMPTY, | ||
| 131 | + ordinal=1, empty=True, enqueue=lambda row: None) | ||
| 132 | + except RuntimeError as exc: | ||
| 133 | + errors.append(str(exc)) | ||
| 134 | + | ||
| 135 | + worker = threading.Thread(target=from_other_thread) | ||
| 136 | + worker.start() | ||
| 137 | + worker.join(2) | ||
| 138 | + self.assertFalse(worker.is_alive()) | ||
| 139 | + self.assertEqual(errors, ["async session requires one host submission thread"]) | ||
| 140 | + self.assertEqual(session.next_ordinal, 1) | ||
| 141 | + | ||
| 142 | + def test_external_writer_claims_bank_before_submit_and_cannot_be_stolen(self): | ||
| 143 | + session = self.session() | ||
| 144 | + bank = BankKey("Z1", 0) | ||
| 145 | + lease = session.acquire_bank(generation="F0", bank=bank) | ||
| 146 | + self.assertEqual(session.active_bank_count, 1) | ||
| 147 | + with self.assertRaisesRegex(RuntimeError, "still leased"): | ||
| 148 | + session.acquire_bank(generation="F1", bank=bank) | ||
| 149 | + with self.assertRaisesRegex(ValueError, "wrong-generation"): | ||
| 150 | + session.submit(generation="F1", kind=OperationKind.COMBINE, | ||
| 151 | + ordinal=0, leases=(lease,), enqueue=lambda row: self.fail("native")) | ||
| 152 | + self.assertEqual(session.next_ordinal, 0) | ||
| 153 | + receipt = session.submit(generation="F0", kind=OperationKind.COMBINE, | ||
| 154 | + ordinal=0, leases=(lease,), enqueue=lambda row: None) | ||
| 155 | + self.assertEqual(session.active_bank_count, 1) | ||
| 156 | + session.retire_after_peer_final_use(receipt) | ||
| 157 | + self.assertEqual(session.active_bank_count, 0) | ||
| 158 | + | ||
| 159 | + def test_release_ordinal_is_one_fifo_step(self): | ||
| 160 | + session = self.session() | ||
| 161 | + receipt = session.submit(generation="F0", kind=OperationKind.EMPTY, | ||
| 162 | + ordinal=0, enqueue=lambda row: None) | ||
| 163 | + row = session.row_for(receipt) | ||
| 164 | + row.final_use = object() | ||
| 165 | + with self.assertRaisesRegex(ValueError, "out-of-order"): | ||
| 166 | + session.claim_release_ordinal(receipt, 2) | ||
| 167 | + session.claim_release_ordinal(receipt, 1) | ||
| 168 | + self.assertEqual((row.release_ordinal, session.next_ordinal), (1, 2)) | ||
| 169 | + with self.assertRaisesRegex(RuntimeError, "one unclaimed"): | ||
| 170 | + session.claim_release_ordinal(receipt, 2) | ||
| 171 | + | ||
| 172 | + def repeatable(self, epoch=0): | ||
| 173 | + generation = (epoch, 0, 0, "layer1", 0, 0) | ||
| 174 | + steps = (("submit", OperationKind.DISPATCH, generation), | ||
| 175 | + ("release", OperationKind.DISPATCH, generation)) | ||
| 176 | + return steps | ||
| 177 | + | ||
| 178 | + def complete_step(self, session, epoch, *, pending=False): | ||
| 179 | + receipt = session.submit(generation=self.repeatable(epoch)[0][2], | ||
| 180 | + kind=OperationKind.DISPATCH, ordinal=epoch * 2, | ||
| 181 | + banks=(BankKey("Z1", 0),), enqueue=lambda row: None) | ||
| 182 | + session.row_for(receipt).final_use = object() | ||
| 183 | + session.claim_release_ordinal(receipt, epoch * 2 + 1) | ||
| 184 | + if not pending: | ||
| 185 | + session.retire_after_peer_final_use(receipt) | ||
| 186 | + return receipt | ||
| 187 | + | ||
| 188 | + def test_sixteen_steps_keep_one_ledger_banks_and_absolute_ordinals(self): | ||
| 189 | + ledger = AsyncSession({"Z1": 1}, expected_steps=self.repeatable()) | ||
| 190 | + cookie = ledger._cookie | ||
| 191 | + for epoch in range(16): | ||
| 192 | + if epoch: | ||
| 193 | + ledger.advance_schedule(self.repeatable(epoch), ordinal_base=epoch * 2) | ||
| 194 | + receipt = self.complete_step(ledger, epoch) | ||
| 195 | + self.assertEqual(ledger.next_ordinal, (epoch + 1) * 2) | ||
| 196 | + self.assertEqual((ledger.active_count, ledger.active_bank_count), (0, 0)) | ||
| 197 | + self.assertIs(ledger._cookie, cookie) | ||
| 198 | + self.assertEqual(len(ledger._expected_steps), 2) | ||
| 199 | + with self.assertRaisesRegex(ValueError, "stale"): | ||
| 200 | + ledger.row_for(receipt) | ||
| 201 | + | ||
| 202 | + def test_pending_release_prevents_next_epoch_without_mutation(self): | ||
| 203 | + ledger = AsyncSession({"Z1": 1}, expected_steps=self.repeatable()) | ||
| 204 | + receipt = self.complete_step(ledger, 0, pending=True) | ||
| 205 | + with self.assertRaisesRegex(RuntimeError, "pending work"): | ||
| 206 | + ledger.advance_schedule(self.repeatable(1), ordinal_base=2) | ||
| 207 | + self.assertEqual((ledger.next_ordinal, ledger._schedule_base), (2, 0)) | ||
| 208 | + self.assertIs(ledger.row_for(receipt).receipt, receipt) | ||
| 209 | + ledger.retire_after_peer_final_use(receipt) | ||
| 210 | + ledger.advance_schedule(self.repeatable(1), ordinal_base=2) | ||
| 211 | + | ||
| 212 | + def test_stale_epoch_gap_reordered_work_and_reset_ordinal_are_rejected(self): | ||
| 213 | + ledger = AsyncSession({"Z1": 1}, expected_steps=self.repeatable()) | ||
| 214 | + self.complete_step(ledger, 0) | ||
| 215 | + for steps, base in ((self.repeatable(), 2), (self.repeatable(2), 2), | ||
| 216 | + (tuple(reversed(self.repeatable(1))), 2), | ||
| 217 | + (self.repeatable(1), 0), (self.repeatable(1)[:1], 2)): | ||
| 218 | + with self.subTest(steps=steps, base=base), self.assertRaises(ValueError): | ||
| 219 | + ledger.advance_schedule(steps, ordinal_base=base) | ||
| 220 | + self.assertEqual(ledger._schedule_base, 0) | ||
| 221 | + ledger.advance_schedule(self.repeatable(1), ordinal_base=2) | ||
| 222 | + with self.assertRaisesRegex(ValueError, "step bank generation"): | ||
| 223 | + ledger.acquire_bank(generation=self.repeatable(0)[0][2], bank=BankKey("Z1", 0)) | ||
| 224 | + with self.assertRaises(ValueError): | ||
| 225 | + ledger.submit(generation=self.repeatable(0)[0][2], kind=OperationKind.DISPATCH, | ||
| 226 | + ordinal=2, enqueue=lambda row: self.fail("stale native submit")) | ||
| 227 | + | ||
| 228 | + def test_unfinished_external_writer_and_poison_block_advance(self): | ||
| 229 | + ledger = AsyncSession({"Z1": 1}, expected_steps=self.repeatable()) | ||
| 230 | + self.complete_step(ledger, 0) | ||
| 231 | + ledger.acquire_bank(generation=self.repeatable(1)[0][2], bank=BankKey("Z1", 0)) | ||
| 232 | + with self.assertRaisesRegex(RuntimeError, "pending work"): | ||
| 233 | + ledger.advance_schedule(self.repeatable(1), ordinal_base=2) | ||
| 234 | + ledger.poison(RuntimeError("uncertain native")) | ||
| 235 | + with self.assertRaisesRegex(RuntimeError, "POISONED"): | ||
| 236 | + ledger.advance_schedule(self.repeatable(1), ordinal_base=2) | ||
| 237 | + | ||
| 238 | + def test_repeatable_boundary_rejects_foreign_host_thread(self): | ||
| 239 | + ledger = AsyncSession({"Z1": 1}, expected_steps=self.repeatable()) | ||
| 240 | + self.complete_step(ledger, 0) | ||
| 241 | + failures = [] | ||
| 242 | + def advance(): | ||
| 243 | + try: | ||
| 244 | + ledger.advance_schedule(self.repeatable(1), ordinal_base=2) | ||
| 245 | + except RuntimeError as exc: | ||
| 246 | + failures.append(str(exc)) | ||
| 247 | + worker = threading.Thread(target=advance) | ||
| 248 | + worker.start() | ||
| 249 | + worker.join(2) | ||
| 250 | + self.assertEqual(failures, ["async session requires one host submission thread"]) | ||
| 251 | + | ||
| 252 | + | ||
| 253 | +if __name__ == "__main__": | ||
| 254 | + unittest.main() | ||
| @@ -0,0 +1,46 @@ | |||
| 1 | +"""Execute real launch selection and pre-allocation guards without NPU.""" | ||
| 2 | +import ast | ||
| 3 | +from pathlib import Path | ||
| 4 | +from types import SimpleNamespace as NS | ||
| 5 | +import unittest | ||
| 6 | + | ||
| 7 | +API=Path(__file__).resolve().parents[1]/'npu_patch/api.py' | ||
| 8 | + | ||
| 9 | +def load(name,native): | ||
| 10 | + tree=ast.parse(API.read_text(encoding='utf-8')) | ||
| 11 | + node=next(n for n in tree.body if isinstance(n,ast.FunctionDef) and n.name==name) | ||
| 12 | + ns={'_C':native} | ||
| 13 | + body=[ast.ImportFrom(module='__future__',names=[ast.alias(name='annotations')],level=0),node] | ||
| 14 | + exec(compile(ast.fix_missing_locations(ast.Module(body=body,type_ignores=[])),str(API),'exec'),ns) | ||
| 15 | + return ns[name] | ||
| 16 | + | ||
| 17 | +class AsyncStreamBarrierTest(unittest.TestCase): | ||
| 18 | + def test_one_collective_same_stream_default_and_aiv(self): | ||
| 19 | + calls=[] | ||
| 20 | + native=NS(acl_shmem_barrier_all_on_stream=lambda s:calls.append(('mixed',s)), | ||
| 21 | + _acl_shmem_barrier_all_aiv_on_stream=lambda s:calls.append(('aiv',s))) | ||
| 22 | + submit=load('_async_stream_barrier',native) | ||
| 23 | + submit({},19);submit({'async_stream_barrier_mode':'mixed'},23) | ||
| 24 | + submit({'async_stream_barrier_mode':'aiv'},29) | ||
| 25 | + self.assertEqual(calls,[('mixed',19),('mixed',23),('aiv',29)]) | ||
| 26 | + | ||
| 27 | + def test_bad_mode_and_native_failure_never_fallback(self): | ||
| 28 | + calls=[] | ||
| 29 | + def fail(s):raise RuntimeError('native launch failure') | ||
| 30 | + native=NS(acl_shmem_barrier_all_on_stream=lambda s:calls.append(s), | ||
| 31 | + _acl_shmem_barrier_all_aiv_on_stream=fail) | ||
| 32 | + submit=load('_async_stream_barrier',native) | ||
| 33 | + with self.assertRaises(ValueError):submit({'async_stream_barrier_mode':'bad'},19) | ||
| 34 | + with self.assertRaisesRegex(RuntimeError,'native launch failure'): | ||
| 35 | + submit({'async_stream_barrier_mode':'aiv'},19) | ||
| 36 | + self.assertEqual(calls,[]) | ||
| 37 | + | ||
| 38 | + def test_capability_rejected_before_any_allocation(self): | ||
| 39 | + for native in (NS(),NS(ASYNC_STREAM_BARRIER_ABI=True),NS(ASYNC_STREAM_BARRIER_ABI=2), | ||
| 40 | + NS(ASYNC_STREAM_BARRIER_ABI=1,_acl_shmem_barrier_all_aiv_on_stream=None)): | ||
| 41 | + with self.subTest(native=native),self.assertRaisesRegex(RuntimeError,'native barrier ABI v1'): | ||
| 42 | + load('_create_context',native)(4,5,1,4,2,async_stream_barrier_mode='aiv') | ||
| 43 | + with self.assertRaisesRegex(ValueError,'async_stream_barrier_mode'): | ||
| 44 | + load('_create_context',NS())(4,5,1,4,2,async_stream_barrier_mode='bad') | ||
| 45 | + | ||
| 46 | +if __name__=='__main__':unittest.main() | ||
| @@ -0,0 +1,286 @@ | |||
| 1 | +"""Actual Buffer/Plan/lane on CPU tensors; streams and rank transport are doubles. | ||
| 2 | + | ||
| 3 | +This exercises the migrated methods together, not NPU kernels or physical overlap. | ||
| 4 | +""" | ||
| 5 | +import contextlib | ||
| 6 | +from types import SimpleNamespace | ||
| 7 | + | ||
| 8 | +import pytest | ||
| 9 | +import torch | ||
| 10 | + | ||
| 11 | +from host_tests.test_sync_lplusb import provider, buffer_for | ||
| 12 | + | ||
| 13 | + | ||
| 14 | +def configure(provider, monkeypatch, prefetch_completion='collective', q0_schedule=None): | ||
| 15 | + api = provider.api | ||
| 16 | + monkeypatch.setattr(api.GradReduceOp, 'compute', | ||
| 17 | + lambda *a, **k: pytest.fail('async canonical targets used dense Op entry')) | ||
| 18 | + buffer = buffer_for(provider, capacity=4) | ||
| 19 | + key_type, kind = api.BankKey, api.OperationKind | ||
| 20 | + buffer._async_plan_cookie = object() | ||
| 21 | + buffer._ctx['_async_plan_cookie'] = buffer._async_plan_cookie | ||
| 22 | + buffer._async_plan_generations = {} | ||
| 23 | + buffer._async_pointer_tables = {} | ||
| 24 | + buffer._async_sources = {} | ||
| 25 | + buffer._async_views = {} | ||
| 26 | + buffer._async_meta_sources = {} | ||
| 27 | + buffer._async_meta_views = {} | ||
| 28 | + buffer._async_owner_ready_sources = {} | ||
| 29 | + buffer._async_owner_ready_views = {} | ||
| 30 | + buffer._async_owned_sources = {} | ||
| 31 | + buffer._async_footprint_bytes = 0 | ||
| 32 | + buffer._async_manifest = {} | ||
| 33 | + buffer._async_views_ready = False | ||
| 34 | + | ||
| 35 | + class Event: | ||
| 36 | + def __init__(self, dependencies=()): | ||
| 37 | + self.dependencies, self.complete = tuple(dependencies), True | ||
| 38 | + self._ready = False | ||
| 39 | + def query(self): | ||
| 40 | + if not self.complete: | ||
| 41 | + return False | ||
| 42 | + if not self._ready: | ||
| 43 | + self._ready = all(event.query() for event in self.dependencies) | ||
| 44 | + return self._ready | ||
| 45 | + | ||
| 46 | + class Stream: | ||
| 47 | + device = torch.device('cpu') | ||
| 48 | + npu_stream = 7 | ||
| 49 | + def __init__(self): | ||
| 50 | + self.dependencies = [] | ||
| 51 | + def wait_event(self, event): | ||
| 52 | + self.dependencies.append(event) | ||
| 53 | + def record_event(self): | ||
| 54 | + return Event(self.dependencies) | ||
| 55 | + | ||
| 56 | + q0, q1 = Stream(), Stream() | ||
| 57 | + current = [q1] | ||
| 58 | + @contextlib.contextmanager | ||
| 59 | + def stream(value): | ||
| 60 | + previous, current[0] = current[0], value | ||
| 61 | + try: | ||
| 62 | + yield | ||
| 63 | + finally: | ||
| 64 | + current[0] = previous | ||
| 65 | + monkeypatch.setattr(api.torch_npu.npu, 'stream', stream) | ||
| 66 | + monkeypatch.setattr(api.torch_npu.npu, 'current_stream', lambda device=None: current[0]) | ||
| 67 | + monkeypatch.setattr(api.torch_npu.npu, 'synchronize', lambda: pytest.fail('hot device synchronize')) | ||
| 68 | + | ||
| 69 | + operations = (kind.DISPATCH, kind.PREFETCH_FC1, kind.COMBINE, | ||
| 70 | + kind.DISPATCH_BWD, kind.REDUCE_FC1, kind.COMBINE_BWD) | ||
| 71 | + schedule = tuple(('submit', op, (0, 'layer0')) for op in operations[:3]) | ||
| 72 | + schedule += tuple(('release', op, (0, 'layer0')) for op in operations[:3]) | ||
| 73 | + schedule += tuple(('submit', op, (0, 'layer0')) for op in operations[3:]) | ||
| 74 | + schedule += tuple(('release', op, (0, 'layer0')) for op in operations[3:]) | ||
| 75 | + if q0_schedule is not None: | ||
| 76 | + schedule = tuple(q0_schedule) | ||
| 77 | + roles = ('Z1', 'Z2', 'Z3', 'Z4', 'fc1_weight', 'fc1_grad') | ||
| 78 | + for role in roles: | ||
| 79 | + shape = (2, 16, 16) if role.startswith('fc1') else (8, 16) | ||
| 80 | + tensor = torch.zeros(shape, dtype=torch.float32 if role.endswith('_grad') else torch.bfloat16) | ||
| 81 | + key = key_type(role, 0) | ||
| 82 | + buffer._async_sources[key] = buffer._async_views[key] = tensor | ||
| 83 | + provider.owners[tensor.data_ptr()] = tensor | ||
| 84 | + if role.startswith('Z'): | ||
| 85 | + meta = torch.zeros(8, dtype=torch.int32) | ||
| 86 | + buffer._async_meta_views[key] = meta | ||
| 87 | + provider.owners[meta.data_ptr()] = meta | ||
| 88 | + | ||
| 89 | + def barrier(handle): | ||
| 90 | + assert current[0] is q0 | ||
| 91 | + provider.calls.append(('native_peer_barrier',)) | ||
| 92 | + provider.native.acl_shmem_barrier_all_on_stream = barrier | ||
| 93 | + buffer._comm_stream = q0 | ||
| 94 | + buffer._async_lane = api.AsyncLane(q0=q0, stream_context=stream, | ||
| 95 | + native_release_barrier=barrier, bank_capacities={role: 1 for role in roles}, expected_steps=schedule) | ||
| 96 | + weights = tuple(torch.eye(16, dtype=torch.bfloat16) * (index + 1) for index in range(2)) | ||
| 97 | + targets = tuple(torch.zeros(16, 16) for _ in range(2)) | ||
| 98 | + refs = {tensor.data_ptr(): tensor for tensor in (*weights, *targets)} | ||
| 99 | + def push(table, slot, plan, rank, count): | ||
| 100 | + assert current[0] is q0 | ||
| 101 | + for index, pointer in enumerate(table.tolist()): | ||
| 102 | + slot[index].copy_(refs[pointer]) | ||
| 103 | + def reduce(table, slot, plan, rank, count): | ||
| 104 | + assert current[0] is q0 | ||
| 105 | + # Single-process native transport double; the real GradReduceOp validates | ||
| 106 | + # and launches this callback. Match MTE's local valid-slot semantics. | ||
| 107 | + for source_slot, expert in enumerate(plan[rank].tolist()): | ||
| 108 | + if expert >= 0: | ||
| 109 | + refs[int(table[expert - rank * count])].add_(slot[source_slot]) | ||
| 110 | + slot[source_slot].zero_() | ||
| 111 | + provider.native._lplusb_owner_push = push | ||
| 112 | + provider.native.grad_reduce_targets = reduce | ||
| 113 | + provider.native._lplusb_owner_reduce = lambda *args: pytest.fail('async used legacy owner reduce') | ||
| 114 | + ready_epochs = [] | ||
| 115 | + if prefetch_completion == 'required_owners_v1': | ||
| 116 | + ready = torch.zeros((2, 16), dtype=torch.int32) | ||
| 117 | + buffer._async_owner_ready_views[key_type('fc1_weight', 0)] = ready | ||
| 118 | + buffer._async_manifest['prefetch_completion'] = dict(mode=prefetch_completion) | ||
| 119 | + def push_ready(table, slot, plan, flags, rank, count, epoch): | ||
| 120 | + assert flags is ready and current[0] is q0 | ||
| 121 | + ready_epochs.append((epoch, flags.data_ptr())) | ||
| 122 | + push(table, slot, plan, rank, count) | ||
| 123 | + provider.native._lplusb_owner_push_ready = push_ready | ||
| 124 | + buffer._register_async_projection_refs(weights, role='fc1_weight') | ||
| 125 | + buffer._register_async_projection_refs(targets, role='fc1_grad') | ||
| 126 | + buffer._async_views_ready = True | ||
| 127 | + # This single-process transport double maps each source token to two experts. | ||
| 128 | + planning = buffer._ctx['kernels']['planning'].compute | ||
| 129 | + def complete_rows(ctx, topk, tpe, cu, plan, **kwargs): | ||
| 130 | + planning(ctx, topk, tpe, cu, plan, **kwargs) | ||
| 131 | + cu.fill_(ctx['NvS']) | ||
| 132 | + plan.experts_to_copy[0, 0] = 0 | ||
| 133 | + plan.experts_to_copy[0, 1] = 1 | ||
| 134 | + buffer._ctx['kernels']['planning'].compute = complete_rows | ||
| 135 | + return SimpleNamespace(buffer=buffer, q0=q0, q1=q1, weights=weights, targets=targets, | ||
| 136 | + schedule=schedule, ready_epochs=ready_epochs) | ||
| 137 | + | ||
| 138 | + | ||
| 139 | +def release(buffer, receipt, ordinal, q1): | ||
| 140 | + buffer._wait_async(receipt, required='peer_visible', consumer_stream=q1) | ||
| 141 | + buffer._record_async_final_use(receipt, consumer_stream=q1) | ||
| 142 | + assert buffer._release_async(receipt, ordinal=ordinal) | ||
| 143 | + | ||
| 144 | + | ||
| 145 | +@pytest.mark.parametrize('step_count', [1, 3]) | ||
| 146 | +@pytest.mark.parametrize('prefetch_completion', ['collective', 'required_owners_v1']) | ||
| 147 | +def test_real_tensor_forward_backward_and_repeated_steps(provider, monkeypatch, step_count, prefetch_completion): | ||
| 148 | + state = configure(provider, monkeypatch, prefetch_completion) | ||
| 149 | + buffer, q1 = state.buffer, state.q1 | ||
| 150 | + original_banks = {key: value.data_ptr() for key, value in buffer._async_views.items()} | ||
| 151 | + original_tables = {key: value[1].data_ptr() for key, value in buffer._async_pointer_tables.items()} | ||
| 152 | + for step in range(step_count): | ||
| 153 | + generation, base = (step, 'layer0'), 12 * step | ||
| 154 | + if step: | ||
| 155 | + schedule = tuple((action, op, generation) for action, op, _ in state.schedule) | ||
| 156 | + buffer._begin_async_step(schedule, ordinal_base=base, weight_ready=q1.record_event(), producer_stream=q1) | ||
| 157 | + with pytest.raises(ValueError, match='another Buffer'): | ||
| 158 | + buffer._submit_prefetch_projection(plan, state.weights, projection='fc1', | ||
| 159 | + bank_index=0, generation=generation, ordinal=base, producer_stream=q1) | ||
| 160 | + assert buffer._async_lane.session.next_ordinal == base | ||
| 161 | + hidden = (torch.arange(64).reshape(4, 16) % 4 + step).to(torch.bfloat16) | ||
| 162 | + indices = torch.zeros(4, 2, dtype=torch.int32) | ||
| 163 | + counts = torch.zeros(4, dtype=torch.int32) | ||
| 164 | + route = torch.full((4, 2), 0.5) | ||
| 165 | + d, dispatched, dispatched_route, _, plan = buffer._submit_dispatch(hidden, | ||
| 166 | + generation=generation, ordinal=base, activation_role='Z1', bank_index=0, | ||
| 167 | + route_weights_sk=route, topk_experts_sk=indices, tokens_per_expert=counts, producer_stream=q1) | ||
| 168 | + w, slots = buffer._submit_prefetch_projection(plan, state.weights, projection='fc1', | ||
| 169 | + bank_index=0, generation=generation, ordinal=base + 1, producer_stream=q1) | ||
| 170 | + if prefetch_completion == 'required_owners_v1': | ||
| 171 | + ready = buffer._async_owner_ready_views[provider.api.BankKey('fc1_weight', 0)] | ||
| 172 | + assert state.ready_epochs == [(12 * i + 2, ready.data_ptr()) for i in range(step + 1)] | ||
| 173 | + else: | ||
| 174 | + assert state.ready_epochs == [] | ||
| 175 | + for receipt in (d, w): | ||
| 176 | + buffer._wait_async(receipt, required='peer_visible', consumer_stream=q1) | ||
| 177 | + lease, z2, z2_route = buffer._acquire_async_activation(role='Z2', bank_index=0, generation=generation) | ||
| 178 | + assert dispatched_route.data_ptr() == buffer._async_meta_views[provider.api.BankKey('Z1', 0)].data_ptr() | ||
| 179 | + torch.testing.assert_close(dispatched_route, route.flatten()) | ||
| 180 | + z2_route.copy_(dispatched_route) | ||
| 181 | + for index in range(2): | ||
| 182 | + z2[index::2].copy_(dispatched[index::2].float() @ slots[index].float().t()) | ||
| 183 | + c, output, combined_route = buffer._submit_combine(plan, lease, generation=generation, | ||
| 184 | + ordinal=base + 2, producer_stream=q1, route_weights_nvs=z2_route) | ||
| 185 | + reference_input = hidden.float().requires_grad_() | ||
| 186 | + reference_weights = [weight.float().requires_grad_() for weight in state.weights] | ||
| 187 | + reference = sum(torch.nn.functional.linear(reference_input, weight) for weight in reference_weights) | ||
| 188 | + reference.sum().backward() | ||
| 189 | + buffer._wait_async(c, required='peer_visible', consumer_stream=q1) | ||
| 190 | + torch.testing.assert_close(output.float(), reference.detach(), rtol=0, atol=0) | ||
| 191 | + torch.testing.assert_close(combined_route, route) | ||
| 192 | + for index, receipt in enumerate((d, w, c)): | ||
| 193 | + release(buffer, receipt, base + 3 + index, q1) | ||
| 194 | + | ||
| 195 | + db, dy, _, _, _ = buffer._submit_dispatch(torch.ones_like(hidden), plan=plan, | ||
| 196 | + generation=generation, ordinal=base + 6, activation_role='Z3', bank_index=0, producer_stream=q1) | ||
| 197 | + buffer._wait_async(db, required='peer_visible', consumer_stream=q1) | ||
| 198 | + grad_lease, grad_slot = buffer._acquire_async_grad(projection='fc1', bank_index=0, generation=generation) | ||
| 199 | + before = [target.clone() for target in state.targets] | ||
| 200 | + for index in range(2): | ||
| 201 | + grad_slot[index].copy_(dy[index::2].float().t() @ hidden.float()) | ||
| 202 | + reduce = buffer._submit_reduce_projection(plan, state.targets, projection='fc1', grad_lease=grad_lease, | ||
| 203 | + generation=generation, ordinal=base + 7, producer_stream=q1) | ||
| 204 | + lease, z4, _ = buffer._acquire_async_activation(role='Z4', bank_index=0, generation=generation) | ||
| 205 | + for index in range(2): | ||
| 206 | + z4[index::2].copy_(dy[index::2].float() @ state.weights[index].float()) | ||
| 207 | + cb, dinput, _ = buffer._submit_combine(plan, lease, generation=generation, | ||
| 208 | + ordinal=base + 8, producer_stream=q1, backward=True) | ||
| 209 | + for index, receipt in enumerate((db, reduce, cb)): | ||
| 210 | + release(buffer, receipt, base + 9 + index, q1) | ||
| 211 | + buffer._retire_async_generation(generation) | ||
| 212 | + torch.testing.assert_close(dinput.float(), reference_input.grad, rtol=0, atol=0) | ||
| 213 | + for prior, actual, expected in zip(before, state.targets, reference_weights): | ||
| 214 | + torch.testing.assert_close(actual - prior, expected.grad, rtol=0, atol=0) | ||
| 215 | + assert torch.count_nonzero(grad_slot) == 0 | ||
| 216 | + assert buffer._async_lane.session.active_count == buffer._async_lane.session.active_bank_count == 0 | ||
| 217 | + assert buffer._async_lane.session.next_ordinal == base + 12 | ||
| 218 | + assert original_banks == {key: value.data_ptr() for key, value in buffer._async_views.items()} | ||
| 219 | + assert original_tables == {key: value[1].data_ptr() for key, value in buffer._async_pointer_tables.items()} | ||
| 220 | + assert any(row[0] == 'native_peer_barrier' for row in provider.calls) | ||
| 221 | + | ||
| 222 | + | ||
| 223 | +def test_plan_clone_preserves_owner_and_independently_copies_prefix(provider): | ||
| 224 | + buffer = buffer_for(provider, capacity=4) | ||
| 225 | + cookie = buffer._ctx['_async_plan_cookie'] = object() | ||
| 226 | + plan, cu = provider.api.allocate_planning_outputs(buffer._ctx) | ||
| 227 | + cu.fill_(8) | ||
| 228 | + clone = plan.clone() | ||
| 229 | + assert clone._async_owner_cookie is plan._async_owner_cookie is cookie | ||
| 230 | + torch.testing.assert_close(clone.cu_seqlens, cu) | ||
| 231 | + assert clone.cu_seqlens.data_ptr() != cu.data_ptr() | ||
| 232 | + | ||
| 233 | + | ||
| 234 | +def test_async_reduce_valid_slot_clear_and_changing_generations(provider, monkeypatch): | ||
| 235 | + kind = provider.api.OperationKind.REDUCE_FC1 | ||
| 236 | + state = configure(provider, monkeypatch, q0_schedule=( | ||
| 237 | + ('submit', kind, (0, 'sparse')), ('release', kind, (0, 'sparse')))) | ||
| 238 | + buffer, q1 = state.buffer, state.q1 | ||
| 239 | + bank = buffer._async_views[provider.api.BankKey('fc1_grad', 0)] | ||
| 240 | + initial = [t.clone() for t in state.targets] | ||
| 241 | + expected = [t.clone() for t in state.targets] | ||
| 242 | + addresses = tuple(t.data_ptr() for t in state.targets) | ||
| 243 | + pointer_tables = {k: v[1].data_ptr() for k, v in buffer._async_pointer_tables.items()} | ||
| 244 | + # Fresh bank starts zero; only active slots are produced. Changed plans | ||
| 245 | + # exercise slots becoming active after an unused generation. | ||
| 246 | + for step, row in enumerate(((0, -1), (-1, -1), (-1, 1), (1, 0))): | ||
| 247 | + generation = (step, 'sparse') | ||
| 248 | + steps = (('submit', provider.api.OperationKind.REDUCE_FC1, generation), | ||
| 249 | + ('release', provider.api.OperationKind.REDUCE_FC1, generation)) | ||
| 250 | + if step: | ||
| 251 | + buffer._begin_async_step(steps, ordinal_base=2*step, | ||
| 252 | + weight_ready=q1.record_event(), producer_stream=q1) | ||
| 253 | + plan, _ = provider.api.allocate_planning_outputs(buffer._ctx) | ||
| 254 | + plan.experts_to_copy.fill_(-1) | ||
| 255 | + for slot, expert in enumerate(row): | ||
| 256 | + plan.experts_to_copy[0, slot] = expert | ||
| 257 | + if expert >= 0: | ||
| 258 | + assert torch.count_nonzero(bank[slot]) == 0 | ||
| 259 | + bank[slot].add_(step + slot + 1) | ||
| 260 | + expected[expert].add_(step + slot + 1) | ||
| 261 | + lease, _ = buffer._acquire_async_grad(projection='fc1', bank_index=0, generation=generation) | ||
| 262 | + receipt = buffer._submit_reduce_projection(plan, state.targets, projection='fc1', | ||
| 263 | + grad_lease=lease, generation=generation, ordinal=2*step, producer_stream=q1) | ||
| 264 | + release(buffer, receipt, 2*step+1, q1) | ||
| 265 | + buffer._retire_async_generation(generation) | ||
| 266 | + assert torch.count_nonzero(bank) == 0 | ||
| 267 | + # Invalid slots are explicitly left unchanged, even when nonzero. This is | ||
| 268 | + # a diagnostic sentinel, not a production write to an unused slot. | ||
| 269 | + generation = (4, 'sparse') | ||
| 270 | + steps = (('submit', provider.api.OperationKind.REDUCE_FC1, generation), | ||
| 271 | + ('release', provider.api.OperationKind.REDUCE_FC1, generation)) | ||
| 272 | + buffer._begin_async_step(steps, ordinal_base=8, weight_ready=q1.record_event(), producer_stream=q1) | ||
| 273 | + plan, _ = provider.api.allocate_planning_outputs(buffer._ctx) | ||
| 274 | + plan.experts_to_copy.fill_(-1) | ||
| 275 | + bank.fill_(123) | ||
| 276 | + lease, _ = buffer._acquire_async_grad(projection='fc1', bank_index=0, generation=generation) | ||
| 277 | + receipt = buffer._submit_reduce_projection(plan, state.targets, projection='fc1', | ||
| 278 | + grad_lease=lease, generation=generation, ordinal=8, producer_stream=q1) | ||
| 279 | + release(buffer, receipt, 9, q1) | ||
| 280 | + buffer._retire_async_generation(generation) | ||
| 281 | + assert torch.all(bank == 123) | ||
| 282 | + assert tuple(t.data_ptr() for t in state.targets) == addresses | ||
| 283 | + assert {k: v[1].data_ptr() for k, v in buffer._async_pointer_tables.items()} == pointer_tables | ||
| 284 | + for actual, wanted, before in zip(state.targets, expected, initial): | ||
| 285 | + torch.testing.assert_close(actual, wanted, atol=0, rtol=0) | ||
| 286 | + assert torch.any(actual != before) | ||
| @@ -0,0 +1,70 @@ | |||
| 1 | +"""Real CPU Tensor/storage tests; no device/runtime initialization.""" | ||
| 2 | +import importlib.util | ||
| 3 | +from pathlib import Path | ||
| 4 | +import gc | ||
| 5 | + | ||
| 6 | +import pytest | ||
| 7 | +import torch | ||
| 8 | + | ||
| 9 | +ROOT = Path(__file__).resolve().parents[1] | ||
| 10 | +SPEC = importlib.util.spec_from_file_location('canonical_source', ROOT/'npu_patch/lplusb_source.py') | ||
| 11 | +MODULE = importlib.util.module_from_spec(SPEC) | ||
| 12 | +SPEC.loader.exec_module(MODULE) | ||
| 13 | +home = MODULE.canonical_contiguous_home | ||
| 14 | + | ||
| 15 | + | ||
| 16 | +def test_dense_parameters_alias_original_canonical_backing(): | ||
| 17 | + backing = torch.arange(5*3*7, dtype=torch.float32).to(torch.bfloat16).reshape(5,3,7) | ||
| 18 | + refs = tuple(torch.nn.Parameter(backing[i], requires_grad=False) for i in range(1,4)) | ||
| 19 | + result = home(refs) | ||
| 20 | + assert tuple(result.shape) == (3,3,7) | ||
| 21 | + assert result.untyped_storage()._cdata == backing.untyped_storage()._cdata | ||
| 22 | + assert result.data_ptr() == refs[0].data_ptr() | ||
| 23 | + result[1].fill_(11) | ||
| 24 | + assert torch.equal(refs[1], torch.full_like(refs[1], 11)) | ||
| 25 | + refs[2].data.fill_(13) | ||
| 26 | + assert torch.equal(result[2], refs[2]) | ||
| 27 | + | ||
| 28 | + | ||
| 29 | +@pytest.mark.parametrize('indices', [(2,1,0), (0,2), (1,1)]) | ||
| 30 | +def test_reverse_padding_and_duplicate_rows_are_rejected(indices): | ||
| 31 | + backing = torch.empty(3,3,7,dtype=torch.bfloat16) | ||
| 32 | + with pytest.raises(ValueError, match='positive dense'): | ||
| 33 | + home([backing[i] for i in indices]) | ||
| 34 | + | ||
| 35 | + | ||
| 36 | +def test_distinct_storages_are_not_forged_into_one_view(): | ||
| 37 | + with pytest.raises(ValueError, match='one legal canonical backing'): | ||
| 38 | + home([torch.empty(3,7,dtype=torch.bfloat16) for _ in range(2)]) | ||
| 39 | + | ||
| 40 | + | ||
| 41 | +def test_single_expert_is_legal_without_proving_multi_expert_layout(): | ||
| 42 | + source = torch.empty(3,7,dtype=torch.bfloat16) | ||
| 43 | + assert home([source]).data_ptr() == source.data_ptr() | ||
| 44 | + | ||
| 45 | + | ||
| 46 | +def test_noncontiguous_matrix_dtype_and_empty_list_rejected(): | ||
| 47 | + for refs in ([], [torch.empty(3,7,dtype=torch.bfloat16).T], [torch.empty(3,7)]): | ||
| 48 | + with pytest.raises(ValueError): home(refs) | ||
| 49 | + | ||
| 50 | + | ||
| 51 | +def test_alias_retains_original_storage_when_parameter_rebound(): | ||
| 52 | + backing = torch.empty(3,3,7,dtype=torch.bfloat16) | ||
| 53 | + refs = [torch.nn.Parameter(backing[i],requires_grad=False) for i in range(3)] | ||
| 54 | + result, address = home(refs), refs[0].data_ptr() | ||
| 55 | + for ref in refs: ref.data = torch.zeros_like(ref) | ||
| 56 | + del backing | ||
| 57 | + gc.collect() | ||
| 58 | + assert result.data_ptr() == address | ||
| 59 | + with pytest.raises(ValueError, match='one legal canonical backing'): home(refs) | ||
| 60 | + | ||
| 61 | + | ||
| 62 | +def test_native_local_L_is_separate_from_global_E_and_uses_existing_kernel(): | ||
| 63 | + source = (ROOT/'npu_patch/native/csrc/lplusb_runtime.cpp').read_text() | ||
| 64 | + begin = source.index('void LPlusBOwnerPushUrmaContiguous(') | ||
| 65 | + end = source.index('void LPlusBOwnerPushUrma(', begin) | ||
| 66 | + code = source[begin:end] | ||
| 67 | + assert 'ops::LaunchPrefetchPushLocal(home, slots, plan, global_experts)' in code | ||
| 68 | + assert 'prefetch_weight_push_udma_do' not in code | ||
| 69 | + assert 'aclshmemx_barrier_all_on_stream' not in code | ||
| 70 | + assert 'aclshmem_malloc' not in code | ||
| @@ -0,0 +1,187 @@ | |||
| 1 | +"""Real Op and launcher dispatch contracts; native execution is a test double.""" | ||
| 2 | +import ast | ||
| 3 | +from pathlib import Path | ||
| 4 | +from types import SimpleNamespace | ||
| 5 | + | ||
| 6 | +import pytest | ||
| 7 | +import torch | ||
| 8 | + | ||
| 9 | +from host_tests.test_sync_lplusb import provider | ||
| 10 | + | ||
| 11 | + | ||
| 12 | +@pytest.mark.parametrize('shape', [(6144, 7168), (7168, 3072), (3, 5)]) | ||
| 13 | +def test_op_accepts_frozen_canonical_table_without_staging(provider, monkeypatch, shape): | ||
| 14 | + # Only tiny CPU tensors are necessary: the Op reads matrix metadata, not data. | ||
| 15 | + slots = torch.empty(1).expand(6, *shape) | ||
| 16 | + table = torch.arange(6, dtype=torch.int64) | ||
| 17 | + plan = torch.zeros((8, 6), dtype=torch.int32) | ||
| 18 | + seen = [] | ||
| 19 | + monkeypatch.setitem(provider.api.GradReduceOp.compute_targets.__globals__, 'launch_grad_reduce_targets', | ||
| 20 | + lambda *a, **k: seen.append((a, k))) | ||
| 21 | + monkeypatch.setitem(provider.api.GradReduceOp.compute.__globals__, 'launch_grad_reduce', | ||
| 22 | + lambda *a, **k: pytest.fail('pointer contract reached dense launcher')) | ||
| 23 | + monkeypatch.setattr(torch, 'stack', lambda *a, **k: pytest.fail('staged targets')) | ||
| 24 | + provider.api.GradReduceOp().compute_targets(dict(E=48, R=8, B=6), table, slots, plan, rank=0, num_sms=32) | ||
| 25 | + assert seen[0][0][0] is table and seen[0][0][1] is slots | ||
| 26 | + with pytest.raises(ValueError, match='canonical target pointers'): | ||
| 27 | + provider.api.GradReduceOp().compute_targets(dict(E=48, R=8, B=6), table[:5], slots, plan, 0, 32) | ||
| 28 | + | ||
| 29 | + | ||
| 30 | +def test_op_dense_shape_contract_is_preserved(provider): | ||
| 31 | + op = provider.api.GradReduceOp() | ||
| 32 | + ctx = dict(E=4, R=2, B=2) | ||
| 33 | + plan = torch.zeros(2, 2, dtype=torch.int32) | ||
| 34 | + op.compute(ctx, torch.zeros(2, 3, 5), torch.zeros(2, 3, 5), plan, 0, 8) | ||
| 35 | + with pytest.raises(ValueError, match='reduce_buffer'): | ||
| 36 | + op.compute(ctx, torch.zeros(2, 5, 3), torch.zeros(2, 3, 5), plan, 0, 8) | ||
| 37 | + | ||
| 38 | + | ||
| 39 | +@pytest.mark.parametrize('entry,shape,dtype,error_type', [ | ||
| 40 | + # Preserve the original dense entry: it reads matrix dimensions before | ||
| 41 | + # validation, so a 1-D pointer table fails with IndexError before launch. | ||
| 42 | + ('compute', (2,), torch.int64, IndexError), | ||
| 43 | + ('compute_targets', (2, 3, 5), torch.float32, ValueError), | ||
| 44 | + ('compute_targets', (2,), torch.float32, ValueError), | ||
| 45 | +]) | ||
| 46 | +def test_op_rejects_wrong_memory_contract_without_launch(provider, monkeypatch, entry, shape, dtype, error_type): | ||
| 47 | + op = provider.api.GradReduceOp() | ||
| 48 | + for name in ('launch_grad_reduce', 'launch_grad_reduce_targets'): | ||
| 49 | + monkeypatch.setitem(op.compute.__globals__, name, | ||
| 50 | + lambda *a, **k: pytest.fail('invalid contract was launched')) | ||
| 51 | + with pytest.raises(error_type): | ||
| 52 | + getattr(op, entry)(dict(E=4, R=2, B=2), torch.zeros(shape, dtype=dtype), | ||
| 53 | + torch.zeros(2, 3, 5), torch.zeros(2, 2, dtype=torch.int32), 0, 8) | ||
| 54 | + | ||
| 55 | + | ||
| 56 | +def launcher_namespace(provider, *, use_udma=True): | ||
| 57 | + source = Path(__file__).resolve().parents[1]/'npu_patch/launchers.py' | ||
| 58 | + tree = ast.parse(source.read_text(encoding='utf-8')) | ||
| 59 | + functions = [n for n in tree.body if isinstance(n, ast.FunctionDef) | ||
| 60 | + and n.name in ('launch_grad_reduce', 'launch_grad_reduce_targets')] | ||
| 61 | + calls = [] | ||
| 62 | + native = SimpleNamespace(compute=lambda *a: calls.append(('dense', a)), | ||
| 63 | + compute_targets=lambda *a: calls.append(('pointer', a))) | ||
| 64 | + ns = dict(__package__='npu_patch', torch=torch, _GRAD_REDUCE=native, | ||
| 65 | + _env_use_udma=lambda _: use_udma) | ||
| 66 | + exec(compile(ast.Module(body=functions, type_ignores=[]), str(source), 'exec'), ns) | ||
| 67 | + return ns, calls | ||
| 68 | + | ||
| 69 | + | ||
| 70 | +class DeviceTensor: | ||
| 71 | + device = SimpleNamespace(type='npu') | ||
| 72 | + def __init__(self, shape, dtype): | ||
| 73 | + self.shape, self.dtype, self.ndim = shape, dtype, len(shape) | ||
| 74 | + def numel(self): | ||
| 75 | + import math | ||
| 76 | + return math.prod(self.shape) | ||
| 77 | + def is_contiguous(self): | ||
| 78 | + return True | ||
| 79 | + | ||
| 80 | + | ||
| 81 | +@pytest.mark.parametrize('pointer', [False, True]) | ||
| 82 | +@pytest.mark.parametrize('use_udma', [False, True]) | ||
| 83 | +def test_launcher_selects_backend_for_both_memory_contracts(provider, pointer, use_udma): | ||
| 84 | + ns, calls = launcher_namespace(provider, use_udma=use_udma) | ||
| 85 | + provider.native.GRAD_REDUCE_POINTER_UDMA_ABI = 3 | ||
| 86 | + targets = DeviceTensor((2,) if pointer else (2, 3, 5), torch.int64 if pointer else torch.float32) | ||
| 87 | + slots, plan = DeviceTensor((2, 3, 5), torch.float32), DeviceTensor((2, 2), torch.int32) | ||
| 88 | + workspace = DeviceTensor((512 * 1024 * 2 * 64,), torch.float32) | ||
| 89 | + if pointer: | ||
| 90 | + ns['launch_grad_reduce_targets'](targets, slots, plan, 0, 128, | ||
| 91 | + udma_workspace=workspace) | ||
| 92 | + else: | ||
| 93 | + ns['launch_grad_reduce'](targets, slots, plan, 0, 128, None, 0, 0, None) | ||
| 94 | + kind, args = calls[0] | ||
| 95 | + assert kind == ('pointer' if pointer else 'dense') | ||
| 96 | + assert args[:3] == (targets, slots, plan) | ||
| 97 | + assert args[3:10] == (2, 3, 5, 2, 2, 0, 64) | ||
| 98 | + assert args[10] is use_udma | ||
| 99 | + if pointer: | ||
| 100 | + assert len(args) == 12 | ||
| 101 | + assert args[11] is (workspace if use_udma else None) | ||
| 102 | + | ||
| 103 | + | ||
| 104 | +@pytest.mark.parametrize('abi', [None, 0, 1, 2, '3', True, 3.0]) | ||
| 105 | +def test_launcher_rejects_old_udma_pointer_build(provider, abi): | ||
| 106 | + provider.native.GRAD_REDUCE_POINTER_UDMA_ABI = abi | ||
| 107 | + ns, calls = launcher_namespace(provider) | ||
| 108 | + with pytest.raises(RuntimeError, match='pointer UDMA ABI v3'): | ||
| 109 | + ns['launch_grad_reduce_targets'](DeviceTensor((2,), torch.int64), | ||
| 110 | + DeviceTensor((2, 3, 5), torch.float32), DeviceTensor((2, 2), torch.int32), 0, 8) | ||
| 111 | + assert calls == [] | ||
| 112 | + | ||
| 113 | + | ||
| 114 | +@pytest.mark.parametrize('shape,dtype', [(None, None), ((10,), torch.float32), | ||
| 115 | + ((512*1024*2*8,), torch.int32)]) | ||
| 116 | +def test_launcher_requires_setup_scratch_without_allocating(provider, monkeypatch, shape, dtype): | ||
| 117 | + provider.native.GRAD_REDUCE_POINTER_UDMA_ABI = 3 | ||
| 118 | + ns, calls = launcher_namespace(provider) | ||
| 119 | + monkeypatch.setattr(torch, 'empty', lambda *a, **k: pytest.fail('allocated during submit')) | ||
| 120 | + scratch = None if shape is None else DeviceTensor(shape, dtype) | ||
| 121 | + with pytest.raises(ValueError, match='setup-owned local FP32 workspace'): | ||
| 122 | + ns['launch_grad_reduce_targets'](DeviceTensor((2,), torch.int64), | ||
| 123 | + DeviceTensor((2, 3, 5), torch.float32), DeviceTensor((2, 2), torch.int32), | ||
| 124 | + 0, 8, udma_workspace=scratch) | ||
| 125 | + assert calls == [] | ||
| 126 | + | ||
| 127 | + | ||
| 128 | +def test_ordered_workspace_covers_peer_slots_at_small_block_count(provider): | ||
| 129 | + provider.native.GRAD_REDUCE_POINTER_UDMA_ABI = 3 | ||
| 130 | + ns, calls = launcher_namespace(provider) | ||
| 131 | + targets = DeviceTensor((6,), torch.int64) | ||
| 132 | + slots = DeviceTensor((6, 3, 5), torch.float32) | ||
| 133 | + plan = DeviceTensor((8, 6), torch.int32) | ||
| 134 | + old = DeviceTensor((512 * 1024 * 2 * 4,), torch.float32) | ||
| 135 | + with pytest.raises(ValueError, match='setup-owned local FP32 workspace'): | ||
| 136 | + ns['launch_grad_reduce_targets'](targets, slots, plan, 0, 4, udma_workspace=old) | ||
| 137 | + assert not calls | ||
| 138 | + new = DeviceTensor((512 * 1024 * 8 * 6,), torch.float32) | ||
| 139 | + ns['launch_grad_reduce_targets'](targets, slots, plan, 0, 4, udma_workspace=new) | ||
| 140 | + assert calls[0][1][-1] is new | ||
| 141 | + | ||
| 142 | + | ||
| 143 | +def test_op_passes_setup_scratch_by_identity(provider, monkeypatch): | ||
| 144 | + seen = [] | ||
| 145 | + op = provider.api.GradReduceOp() | ||
| 146 | + monkeypatch.setitem(op.compute_targets.__globals__, 'launch_grad_reduce_targets', | ||
| 147 | + lambda *a, **k: seen.append((a, k))) | ||
| 148 | + scratch = torch.empty(1) | ||
| 149 | + op.compute_targets(dict(E=4, R=2, B=2, _grad_reduce_target_workspace=scratch), | ||
| 150 | + torch.zeros(2, dtype=torch.int64), torch.zeros(2, 3, 5), | ||
| 151 | + torch.zeros(2, 2, dtype=torch.int32), 0, 8) | ||
| 152 | + assert seen[0][1]['udma_workspace'] is scratch | ||
| 153 | + | ||
| 154 | + | ||
| 155 | +@pytest.mark.parametrize('udma_abi', [None, 1]) | ||
| 156 | +def test_mte_pointer_entry_remains_compatible_with_old_extension(provider, udma_abi): | ||
| 157 | + ns, calls = launcher_namespace(provider, use_udma=False) | ||
| 158 | + if udma_abi is not None: | ||
| 159 | + provider.native.GRAD_REDUCE_POINTER_UDMA_ABI = udma_abi | ||
| 160 | + ns['launch_grad_reduce_targets'](DeviceTensor((2,), torch.int64), | ||
| 161 | + DeviceTensor((2, 3, 5), torch.float32), DeviceTensor((2, 2), torch.int32), 0, 8) | ||
| 162 | + assert calls[0][0] == 'pointer' | ||
| 163 | + assert len(calls[0][1]) == 10 | ||
| 164 | + | ||
| 165 | + | ||
| 166 | +@pytest.mark.parametrize('abi', [None, 0, '1', True, 1.0]) | ||
| 167 | +def test_launcher_rejects_old_pointer_build_without_launch(provider, abi): | ||
| 168 | + provider.native.GRAD_REDUCE_POINTER_ABI = abi | ||
| 169 | + ns, calls = launcher_namespace(provider) | ||
| 170 | + with pytest.raises(RuntimeError, match='pointer ABI v1'): | ||
| 171 | + ns['launch_grad_reduce_targets'](DeviceTensor((2,), torch.int64), | ||
| 172 | + DeviceTensor((2, 3, 5), torch.float32), DeviceTensor((2, 2), torch.int32), | ||
| 173 | + 0, 8) | ||
| 174 | + assert calls == [] | ||
| 175 | + | ||
| 176 | + | ||
| 177 | +@pytest.mark.parametrize('entry', ['launch_grad_reduce', 'launch_grad_reduce_targets']) | ||
| 178 | +def test_launcher_rejects_the_other_contract_without_fallback(provider, entry): | ||
| 179 | + ns, calls = launcher_namespace(provider) | ||
| 180 | + slots = DeviceTensor((2, 3, 5), torch.float32) | ||
| 181 | + plan = DeviceTensor((2, 2), torch.int32) | ||
| 182 | + with pytest.raises(AssertionError): | ||
| 183 | + if entry == 'launch_grad_reduce': | ||
| 184 | + ns[entry](DeviceTensor((2,), torch.int64), slots, plan, 0, 8, None, 0, 0, None) | ||
| 185 | + else: | ||
| 186 | + ns[entry](DeviceTensor((2, 3, 5), torch.float32), slots, plan, 0, 8) | ||
| 187 | + assert calls == [] | ||
| @@ -0,0 +1,224 @@ | |||
| 1 | +"""Run the real replay/Op on CPU; device/SHMEM/native math are explicit doubles.""" | ||
| 2 | +import contextlib | ||
| 3 | +import json | ||
| 4 | +import os | ||
| 5 | +import sys | ||
| 6 | +from types import ModuleType, SimpleNamespace | ||
| 7 | + | ||
| 8 | +import pytest | ||
| 9 | +import torch | ||
| 10 | + | ||
| 11 | +from host_tests.test_sync_lplusb import provider | ||
| 12 | +from host_tests.test_grad_reduce_udma_layout_replay import replay | ||
| 13 | +from host_tests.test_grad_reduce_op import DeviceTensor, launcher_namespace | ||
| 14 | + | ||
| 15 | + | ||
| 16 | +@pytest.mark.parametrize('height,width', [(6144, 7168), (7168, 3072)]) | ||
| 17 | +@pytest.mark.parametrize('use_udma', [False, True]) | ||
| 18 | +def test_dense_replay_packs_original_native_parameters(provider, monkeypatch, height, width, use_udma): | ||
| 19 | + namespace, calls = launcher_namespace(provider, use_udma=use_udma) | ||
| 20 | + op = provider.api.GradReduceOp() | ||
| 21 | + monkeypatch.setitem(op.compute.__globals__, 'launch_grad_reduce', namespace['launch_grad_reduce']) | ||
| 22 | + monkeypatch.setitem(op.compute_targets.__globals__, 'launch_grad_reduce_targets', | ||
| 23 | + lambda *a, **k: pytest.fail('dense reached pointer launcher')) | ||
| 24 | + home = DeviceTensor((6, height, width), torch.float32) | ||
| 25 | + source = DeviceTensor((6, height, width), torch.float32) | ||
| 26 | + plan = DeviceTensor((8, 6), torch.int32) | ||
| 27 | + replay._submit_reduce('dense', op, dict(E=48, R=8, B=6), home, | ||
| 28 | + object(), source, plan, 5, 32) | ||
| 29 | + assert len(calls) == 1 and calls[0][0] == 'dense' | ||
| 30 | + assert calls[0][1][:3] == (home, source, plan) | ||
| 31 | + assert calls[0][1][3:] == (6, height, width, 8, 6, 5, 32, use_udma) | ||
| 32 | + | ||
| 33 | + | ||
| 34 | +@pytest.fixture | ||
| 35 | +def dense_replay(provider, monkeypatch): | ||
| 36 | + original_spec = replay.layout_spec | ||
| 37 | + original_path = replay.Path | ||
| 38 | + empty, tensor = torch.empty, torch.tensor | ||
| 39 | + real_op = provider.api.GradReduceOp | ||
| 40 | + monkeypatch.setattr(replay, 'SHAPES', {'fc1': (6, 3, 5), 'fc2': (6, 5, 3)}) | ||
| 41 | + | ||
| 42 | + def run(layout='compact', sequence='fc2', rank=0, fail_call=None, entry='dense', backend='udma'): | ||
| 43 | + use_udma = backend == 'udma' | ||
| 44 | + # Keep production descriptor count/order/bank indices, but use tiny | ||
| 45 | + # CPU storage. Production byte sizes/offsets have independent tests. | ||
| 46 | + spec = original_spec(layout) | ||
| 47 | + sizes = tuple(6 * 3 * 5 * 4 if i in spec['banks'].values() else 4 | ||
| 48 | + for i in range(len(spec['sizes']))) | ||
| 49 | + offsets = tuple(sum(sizes[:i]) for i in range(len(sizes))) | ||
| 50 | + small = dict(sizes=sizes, offsets=offsets, banks=spec['banks'], bytes=sum(sizes)) | ||
| 51 | + backing = torch.zeros(sum(sizes) // 4, dtype=torch.float32) | ||
| 52 | + descriptors, destroyed, calls, allocations, events, home_tensors = [], [], [], [], [], [] | ||
| 53 | + state = dict(status='FAIL', stage='imports') | ||
| 54 | + workspace = 'none' if not use_udma else 'native' if entry == 'dense' else 'shared' | ||
| 55 | + args = SimpleNamespace(entry=entry, backend=backend, layout=layout, workspace=workspace, | ||
| 56 | + sequence=sequence, start_round=0, rounds=4) | ||
| 57 | + initialized = False | ||
| 58 | + | ||
| 59 | + def create(shape, dtype, device): | ||
| 60 | + index = len(descriptors) | ||
| 61 | + source = backing.view(torch.uint8).narrow(0, offsets[index], sizes[index]).view(dtype).reshape(shape) | ||
| 62 | + source._vmm_allocation = SimpleNamespace(destroy=lambda: destroyed.append(index)) | ||
| 63 | + descriptors.append((source.data_ptr(), sizes[index])) | ||
| 64 | + return source, source._vmm_allocation, source.data_ptr() | ||
| 65 | + | ||
| 66 | + def init(**kwargs): | ||
| 67 | + nonlocal initialized | ||
| 68 | + assert kwargs['descriptors'] == tuple(descriptors) | ||
| 69 | + assert kwargs['enable_udma'] is use_udma and kwargs['qp_count'] == (2 if use_udma else 0) | ||
| 70 | + initialized = True | ||
| 71 | + events.append('init') | ||
| 72 | + | ||
| 73 | + def finalize(): | ||
| 74 | + nonlocal initialized | ||
| 75 | + initialized = False | ||
| 76 | + events.append('finalize') | ||
| 77 | + | ||
| 78 | + def cpu_empty(*args, **kwargs): | ||
| 79 | + allocations.append(args[0]) | ||
| 80 | + kwargs.pop('device', None) | ||
| 81 | + # CPU scratch is a metadata double, not an actual 128 MiB buffer. | ||
| 82 | + if args[0] == 512 * 1024 * 2 * 32: | ||
| 83 | + return empty(1, **kwargs) | ||
| 84 | + result = empty(*args, **kwargs) | ||
| 85 | + if result.dtype == torch.float32 and result.ndim == 3: | ||
| 86 | + home_tensors.append(result) | ||
| 87 | + return result | ||
| 88 | + | ||
| 89 | + def cpu_tensor(*args, **kwargs): | ||
| 90 | + if entry == 'dense': | ||
| 91 | + assert kwargs.get('dtype') != torch.int64, 'dense allocated a pointer table' | ||
| 92 | + kwargs.pop('device', None) | ||
| 93 | + return tensor(*args, **kwargs) | ||
| 94 | + | ||
| 95 | + def synchronize(): | ||
| 96 | + if state['stage'] == 'after_sync' and state['call'] == fail_call: | ||
| 97 | + raise RuntimeError('injected 507035') | ||
| 98 | + | ||
| 99 | + def accumulate(rows, source, plan, kwargs): | ||
| 100 | + assert source.shape == replay.SHAPES[state['projection']] | ||
| 101 | + assert kwargs['rank'] == rank and kwargs['num_sms'] == 32 | ||
| 102 | + for key in ('ASCEND_MOONEP_USE_UDMA', 'ASCEND_MOONEP_GRAD_REDUCE_USE_UDMA'): | ||
| 103 | + assert os.environ[key] == ('1' if use_udma else '0') | ||
| 104 | + calls.append((state['round'], state['projection'])) | ||
| 105 | + events.append(entry) | ||
| 106 | + for expert, row in enumerate(rows): | ||
| 107 | + assert bool(torch.all(row == 100 + rank * 6 + expert)) | ||
| 108 | + for slot, row in enumerate(source): | ||
| 109 | + assert bool(torch.all(row == replay.slot_value(state['projection'], state['round'], rank, slot))) | ||
| 110 | + # Explicit CPU replacement of cross-rank native accumulation. | ||
| 111 | + for src, row in enumerate(plan.tolist()): | ||
| 112 | + for slot, expert in enumerate(row): | ||
| 113 | + if expert >= 0 and expert // 6 == rank: | ||
| 114 | + rows[expert % 6].add_(replay.slot_value(state['projection'], state['round'], src, slot)) | ||
| 115 | + for slot, expert in enumerate(plan[rank].tolist()): | ||
| 116 | + if expert >= 0: | ||
| 117 | + source[slot].zero_() | ||
| 118 | + | ||
| 119 | + def native_dense(home, source, plan, **kwargs): | ||
| 120 | + assert entry == 'dense', 'targets reached dense launcher' | ||
| 121 | + assert home.shape == source.shape and home.is_contiguous() and home.dtype == torch.float32 | ||
| 122 | + accumulate(tuple(home.unbind(0)), source, plan, kwargs) | ||
| 123 | + | ||
| 124 | + def native_targets(table, source, plan, **kwargs): | ||
| 125 | + assert entry == 'targets', 'dense reached compute_targets' | ||
| 126 | + assert table.dtype == torch.int64 and table.shape == (6,) | ||
| 127 | + if use_udma: | ||
| 128 | + assert kwargs['udma_workspace'] is not None | ||
| 129 | + else: | ||
| 130 | + assert 'udma_workspace' not in kwargs | ||
| 131 | + pointers = {row.data_ptr(): row for home in home_tensors for row in home.unbind(0)} | ||
| 132 | + accumulate([pointers[p] for p in table.tolist()], source, plan, kwargs) | ||
| 133 | + | ||
| 134 | + def exchange(store, key, peer, world, value): | ||
| 135 | + if key == 'configuration': | ||
| 136 | + config = json.loads(value) | ||
| 137 | + assert config['entry'] == entry and config['workspace'] == workspace | ||
| 138 | + assert config['backend'] == backend | ||
| 139 | + return [value] * world | ||
| 140 | + | ||
| 141 | + package = sys.modules['npu_patch'] | ||
| 142 | + monkeypatch.setattr(package, '__file__', 'host-provider.py', raising=False) | ||
| 143 | + monkeypatch.setattr(provider.native, '__file__', 'host-native.so', raising=False) | ||
| 144 | + # Dense and MTE targets must not require pointer UDMA ABI 3. | ||
| 145 | + monkeypatch.delattr(provider.native, 'GRAD_REDUCE_POINTER_UDMA_ABI', raising=False) | ||
| 146 | + if entry == 'targets' and use_udma: | ||
| 147 | + monkeypatch.setattr(provider.native, 'GRAD_REDUCE_POINTER_UDMA_ABI', 3, raising=False) | ||
| 148 | + monkeypatch.setattr(package, 'ShmemRuntime', SimpleNamespace( | ||
| 149 | + is_initialized=lambda: initialized, init_with_buffer=init, finalize=finalize), raising=False) | ||
| 150 | + monkeypatch.setattr(package, 'runtime_library_info', lambda: {'sha256': 'host-double'}, raising=False) | ||
| 151 | + buffer_c = sys.modules['npu_patch.buffer_c'] | ||
| 152 | + monkeypatch.setattr(buffer_c, 'create_vmm_physical', create) | ||
| 153 | + monkeypatch.setattr(buffer_c, 'symmetric_descriptors', lambda: tuple(descriptors), raising=False) | ||
| 154 | + monkeypatch.setattr(buffer_c, 'reset_symmetric_descriptors', descriptors.clear, raising=False) | ||
| 155 | + device_module = ModuleType('npu_patch._device') | ||
| 156 | + device_module.local_device_index = lambda local_rank: local_rank | ||
| 157 | + monkeypatch.setitem(sys.modules, device_module.__name__, device_module) | ||
| 158 | + npu = SimpleNamespace(Stream=lambda **kwargs: object(), set_device=lambda device: None, | ||
| 159 | + stream=lambda stream: contextlib.nullcontext(), synchronize=synchronize) | ||
| 160 | + monkeypatch.setattr(sys.modules['torch_npu'], 'npu', npu) | ||
| 161 | + monkeypatch.setattr(torch, 'npu', npu, raising=False) | ||
| 162 | + monkeypatch.setattr(torch, 'empty', cpu_empty) | ||
| 163 | + monkeypatch.setattr(torch, 'tensor', cpu_tensor) | ||
| 164 | + monkeypatch.setattr(torch.distributed, 'init_process_group', lambda *a: None) | ||
| 165 | + monkeypatch.setattr(torch.distributed, 'get_rank', lambda: rank) | ||
| 166 | + monkeypatch.setattr(torch.distributed, 'get_world_size', lambda: 8) | ||
| 167 | + monkeypatch.setattr(torch.distributed, 'destroy_process_group', lambda: events.append('destroy_pg')) | ||
| 168 | + monkeypatch.setattr(torch.distributed.distributed_c10d, '_get_default_store', lambda: object()) | ||
| 169 | + monkeypatch.setattr(sys.modules['npu_patch.ops'], 'GradReduceOp', lambda **kwargs: real_op()) | ||
| 170 | + monkeypatch.setitem(real_op.compute.__globals__, 'launch_grad_reduce', native_dense) | ||
| 171 | + monkeypatch.setitem(real_op.compute_targets.__globals__, 'launch_grad_reduce_targets', native_targets) | ||
| 172 | + monkeypatch.setattr(replay, 'layout_spec', lambda name: small) | ||
| 173 | + monkeypatch.setattr(replay, '_exchange', exchange) | ||
| 174 | + monkeypatch.setattr(replay, '_sha', lambda path: 'host-double') | ||
| 175 | + maps = SimpleNamespace(read_text=lambda: '0-1 r-xp 0 00:00 0 /host/libascend_moonep_kernels.so') | ||
| 176 | + monkeypatch.setattr(replay, 'Path', lambda path: maps if path == '/proc/self/maps' else original_path(path)) | ||
| 177 | + monkeypatch.setenv('LOCAL_RANK', str(rank)) | ||
| 178 | + # Opposite inherited settings must be overridden in both directions. | ||
| 179 | + monkeypatch.setenv('ASCEND_MOONEP_USE_UDMA', '0' if use_udma else '1') | ||
| 180 | + monkeypatch.setenv('ASCEND_MOONEP_GRAD_REDUCE_USE_UDMA', '0' if use_udma else '1') | ||
| 181 | + if fail_call is None: | ||
| 182 | + replay._run(args, state) | ||
| 183 | + else: | ||
| 184 | + with pytest.raises(RuntimeError, match='injected 507035'): | ||
| 185 | + replay._run(args, state) | ||
| 186 | + return SimpleNamespace(state=state, calls=calls, events=events, allocations=allocations, | ||
| 187 | + destroyed=destroyed, sizes=sizes) | ||
| 188 | + return run | ||
| 189 | + | ||
| 190 | + | ||
| 191 | +@pytest.mark.parametrize('layout', ['compact', 'model']) | ||
| 192 | +@pytest.mark.parametrize('sequence', ['fc2', 'fc1-fc2']) | ||
| 193 | +@pytest.mark.parametrize('rank', [0, 5]) | ||
| 194 | +@pytest.mark.parametrize('entry', ['dense', 'targets']) | ||
| 195 | +@pytest.mark.parametrize('backend', ['mte', 'udma']) | ||
| 196 | +def test_replay_runs_real_op_and_all_oracles(dense_replay, layout, sequence, rank, entry, backend): | ||
| 197 | + result = dense_replay(layout, sequence, rank, entry=entry, backend=backend) | ||
| 198 | + assert result.state['status'] == 'PASS' | ||
| 199 | + assert result.calls == [(r, p) for r in range(4) for p in sequence.split('-')] | ||
| 200 | + assert result.allocations == ([512 * 1024 * 2 * 32] if entry == 'targets' and backend == 'udma' else []) + [ | ||
| 201 | + (6, 3, 5), (6, 5, 3), (8, 6)] | ||
| 202 | + assert result.state['descriptor_sizes'] == result.sizes | ||
| 203 | + assert result.state['backend'] == backend | ||
| 204 | + assert result.state['shmem_udma_enabled'] is (backend == 'udma') | ||
| 205 | + assert result.state['shmem_qp_count'] == (2 if backend == 'udma' else 0) | ||
| 206 | + assert result.state['native_workspace_bytes'] == (128 * 1024 * 1024 if backend == 'udma' else 0) | ||
| 207 | + assert result.state['workspace_policy'] == ( | ||
| 208 | + 'not_used' if backend == 'mte' else 'native_per_call' if entry == 'dense' else 'setup_owned') | ||
| 209 | + assert result.state['native_pre_post_barriers'] is (entry == 'targets') | ||
| 210 | + assert all((bank['table'] is None) == (entry == 'dense') for bank in result.state['banks'].values()) | ||
| 211 | + assert all((bank['workspace'] is None) == (entry == 'dense' or backend == 'mte') | ||
| 212 | + for bank in result.state['banks'].values()) | ||
| 213 | + assert result.destroyed == list(reversed(range(len(result.sizes)))) | ||
| 214 | + assert result.events[-2:] == ['finalize', 'destroy_pg'] | ||
| 215 | + | ||
| 216 | + | ||
| 217 | +@pytest.mark.parametrize('backend', ['mte', 'udma']) | ||
| 218 | +@pytest.mark.parametrize('entry', ['dense', 'targets']) | ||
| 219 | +def test_fourth_call_failure_preserves_boundary_without_teardown(dense_replay, entry, backend): | ||
| 220 | + result = dense_replay(fail_call=4, entry=entry, backend=backend) | ||
| 221 | + assert result.calls == [(r, 'fc2') for r in range(4)] | ||
| 222 | + assert (result.state['round'], result.state['call'], result.state['stage']) == (3, 4, 'after_sync') | ||
| 223 | + assert 'finalize' not in result.events and 'destroy_pg' not in result.events | ||
| 224 | + assert result.destroyed == [] | ||
| @@ -0,0 +1,206 @@ | |||
| 1 | +"""Host-only replay sizing/oracles and failure-exit checks; no NPU evidence.""" | ||
| 2 | +import importlib.util | ||
| 3 | +import io | ||
| 4 | +import json | ||
| 5 | +from pathlib import Path | ||
| 6 | +import subprocess | ||
| 7 | +import sys | ||
| 8 | +from contextlib import redirect_stdout | ||
| 9 | +from unittest.mock import patch | ||
| 10 | + | ||
| 11 | +import pytest | ||
| 12 | + | ||
| 13 | + | ||
| 14 | +SCRIPT = Path(__file__).resolve().parents[1] / 'npu_patch/scripts/validate_grad_reduce_udma_layout.py' | ||
| 15 | +spec = importlib.util.spec_from_file_location('udma_layout_replay', SCRIPT) | ||
| 16 | +replay = importlib.util.module_from_spec(spec) | ||
| 17 | +spec.loader.exec_module(replay) | ||
| 18 | + | ||
| 19 | + | ||
| 20 | +def test_model_layout_matches_captured_rank6_inventory(): | ||
| 21 | + layout = replay.layout_spec('model') | ||
| 22 | + assert len(layout['sizes']) == 24 | ||
| 23 | + assert layout['bytes'] == 5339348992 | ||
| 24 | + assert layout['banks'] == {'fc1': 8, 'fc2': 11} | ||
| 25 | + assert layout['offsets'][8] == 396361728 | ||
| 26 | + assert layout['offsets'][11] == 2510290944 | ||
| 27 | + assert layout['sizes'][8] == 1056964608 | ||
| 28 | + assert layout['sizes'][11] == 528482304 | ||
| 29 | + assert all(size % (2 << 20) == 0 for size in layout['sizes']) | ||
| 30 | + | ||
| 31 | + | ||
| 32 | +@pytest.mark.parametrize('layout_name', ['model', 'compact']) | ||
| 33 | +def test_source_shapes_fill_their_entire_registered_descriptor(layout_name): | ||
| 34 | + layout = replay.layout_spec(layout_name) | ||
| 35 | + for projection, (slots, height, width) in replay.SHAPES.items(): | ||
| 36 | + assert slots == 6 | ||
| 37 | + assert slots * height * width * 4 == layout['sizes'][layout['banks'][projection]] | ||
| 38 | + assert layout['bytes'] == sum(layout['sizes']) | ||
| 39 | + assert layout['offsets'][0] == 0 | ||
| 40 | + for index in range(1, len(layout['sizes'])): | ||
| 41 | + assert layout['offsets'][index] == layout['offsets'][index-1] + layout['sizes'][index-1] | ||
| 42 | + | ||
| 43 | + | ||
| 44 | +def test_compact_control_keeps_same_banks_but_removes_other_descriptors(): | ||
| 45 | + layout = replay.layout_spec('compact') | ||
| 46 | + assert layout['sizes'] == (1056964608, 528482304) | ||
| 47 | + assert layout['offsets'] == (0, 1056964608) | ||
| 48 | + | ||
| 49 | + | ||
| 50 | +def test_hotspot_oracle_accumulates_every_source_and_preserves_other_experts(): | ||
| 51 | + name, plan = replay.plan_for_round(1) | ||
| 52 | + assert name == 'hotspot' | ||
| 53 | + assert plan == [[0] * 6 for _ in range(8)] | ||
| 54 | + for projection in ('fc1', 'fc2'): | ||
| 55 | + expected = 100 + sum(replay.slot_value(projection, 1, source, slot) | ||
| 56 | + for source in range(8) for slot in range(6)) | ||
| 57 | + assert replay.expected_values(projection, 1, plan, 0) == [expected, 101, 102, 103, 104, 105] | ||
| 58 | + assert replay.expected_values(projection, 1, plan, 6) == list(range(136, 142)) | ||
| 59 | + | ||
| 60 | + | ||
| 61 | +def test_balanced_plan_delivers_one_contribution_to_each_local_expert(): | ||
| 62 | + _, plan = replay.plan_for_round(0) | ||
| 63 | + for owner in range(8): | ||
| 64 | + expected = [] | ||
| 65 | + for expert in range(6): | ||
| 66 | + source = (owner - expert - 1) % 8 | ||
| 67 | + assert plan[source][expert] == owner * 6 + expert | ||
| 68 | + expected.append(100 + owner * 6 + expert + replay.slot_value('fc2', 0, source, expert)) | ||
| 69 | + assert replay.expected_values('fc2', 0, plan, owner) == expected | ||
| 70 | + | ||
| 71 | + | ||
| 72 | +def test_empty_and_random_plans_are_deterministic_and_valid(): | ||
| 73 | + assert replay.plan_for_round(2) == ('empty', [[-1] * 6 for _ in range(8)]) | ||
| 74 | + for index in (3, 7, 11): | ||
| 75 | + assert replay.plan_for_round(index) == replay.plan_for_round(index) | ||
| 76 | + _, plan = replay.plan_for_round(index) | ||
| 77 | + assert all(len(row) == 6 for row in plan) | ||
| 78 | + assert all(-1 <= value < 48 for row in plan for value in row) | ||
| 79 | + | ||
| 80 | + | ||
| 81 | +def test_oracle_values_remain_exact_fp32_integers_over_allowed_rounds(): | ||
| 82 | + plan = [[0] * 6 for _ in range(8)] | ||
| 83 | + for projection in ('fc1', 'fc2'): | ||
| 84 | + for round_index in range(1000): | ||
| 85 | + assert 0 < max(replay.expected_values(projection, round_index, plan, 0)) < 2**24 | ||
| 86 | + | ||
| 87 | + | ||
| 88 | +def test_help_does_not_import_npu_or_initialize_devices(): | ||
| 89 | + result = subprocess.run([sys.executable, '-B', str(SCRIPT), '--help'], | ||
| 90 | + capture_output=True, text=True, timeout=20) | ||
| 91 | + assert result.returncode == 0, result.stderr | ||
| 92 | + assert '--layout' in result.stdout | ||
| 93 | + assert '--workspace' in result.stdout | ||
| 94 | + assert '--sequence' in result.stdout | ||
| 95 | + assert '--start-round' in result.stdout | ||
| 96 | + assert '--entry' in result.stdout | ||
| 97 | + assert '--backend' in result.stdout | ||
| 98 | + | ||
| 99 | + | ||
| 100 | +@pytest.mark.parametrize('sequence', ['fc1-fc2', 'fc2-fc1', 'fc1', 'fc2']) | ||
| 101 | +def test_sequence_cli_preserves_resource_configuration(sequence): | ||
| 102 | + with patch.object(replay, '_run') as run, patch.object(sys, 'argv', | ||
| 103 | + [str(SCRIPT), '--layout', 'compact', '--workspace', 'separate', '--sequence', sequence]): | ||
| 104 | + replay.main() | ||
| 105 | + args, _ = run.call_args.args | ||
| 106 | + assert (args.layout, args.workspace, args.sequence, args.rounds) == ( | ||
| 107 | + 'compact', 'separate', sequence, 20) | ||
| 108 | + assert args.start_round == 0 | ||
| 109 | + assert args.entry == 'targets' | ||
| 110 | + assert args.backend == 'udma' | ||
| 111 | + | ||
| 112 | + | ||
| 113 | +@pytest.mark.parametrize('entry', ['dense', 'targets']) | ||
| 114 | +@pytest.mark.parametrize('layout', ['compact', 'model']) | ||
| 115 | +def test_mte_cli_selects_no_udma_workspace(entry, layout): | ||
| 116 | + with patch.object(replay, '_run') as run, patch.object(sys, 'argv', | ||
| 117 | + [str(SCRIPT), '--entry', entry, '--backend', 'mte', '--layout', layout]): | ||
| 118 | + replay.main() | ||
| 119 | + args, _ = run.call_args.args | ||
| 120 | + assert (args.entry, args.backend, args.workspace) == (entry, 'mte', 'none') | ||
| 121 | + | ||
| 122 | + | ||
| 123 | +@pytest.mark.parametrize('entry', ['dense', 'targets']) | ||
| 124 | +@pytest.mark.parametrize('workspace', ['native', 'shared', 'separate']) | ||
| 125 | +def test_mte_rejects_udma_workspace_before_device_imports(entry, workspace): | ||
| 126 | + with patch.object(replay, '_run') as run, patch.object(sys, 'argv', | ||
| 127 | + [str(SCRIPT), '--layout', 'compact', '--entry', entry, | ||
| 128 | + '--backend', 'mte', '--workspace', workspace]): | ||
| 129 | + with pytest.raises(SystemExit) as error: | ||
| 130 | + replay.main() | ||
| 131 | + assert error.value.code == 2 | ||
| 132 | + run.assert_not_called() | ||
| 133 | + | ||
| 134 | + | ||
| 135 | +@pytest.mark.parametrize('layout', ['compact', 'model']) | ||
| 136 | +@pytest.mark.parametrize('explicit_workspace', [False, True]) | ||
| 137 | +def test_original_dense_cli_uses_native_workspace(layout, explicit_workspace): | ||
| 138 | + argv = [str(SCRIPT), '--entry', 'dense', '--layout', layout] | ||
| 139 | + if explicit_workspace: | ||
| 140 | + argv += ['--workspace', 'native'] | ||
| 141 | + with patch.object(replay, '_run') as run, patch.object(sys, 'argv', argv): | ||
| 142 | + replay.main() | ||
| 143 | + args, _ = run.call_args.args | ||
| 144 | + assert (args.entry, args.workspace, args.layout) == ('dense', 'native', layout) | ||
| 145 | + | ||
| 146 | + | ||
| 147 | +@pytest.mark.parametrize('entry,workspace', [('dense', 'shared'), ('dense', 'separate'), ('targets', 'native')]) | ||
| 148 | +def test_wrong_workspace_contract_is_rejected_before_device_imports(entry, workspace): | ||
| 149 | + with patch.object(replay, '_run') as run, patch.object(sys, 'argv', | ||
| 150 | + [str(SCRIPT), '--layout', 'compact', '--entry', entry, '--workspace', workspace]): | ||
| 151 | + with pytest.raises(SystemExit) as error: | ||
| 152 | + replay.main() | ||
| 153 | + assert error.value.code == 2 | ||
| 154 | + run.assert_not_called() | ||
| 155 | + | ||
| 156 | + | ||
| 157 | +def test_cold_random_cli_selects_captured_plan_and_data_index(): | ||
| 158 | + with patch.object(replay, '_run') as run, patch.object(sys, 'argv', | ||
| 159 | + [str(SCRIPT), '--layout', 'compact', '--sequence', 'fc2', | ||
| 160 | + '--start-round', '3', '--rounds', '1']): | ||
| 161 | + replay.main() | ||
| 162 | + args, _ = run.call_args.args | ||
| 163 | + assert (args.start_round, args.rounds) == (3, 1) | ||
| 164 | + name, plan = replay.plan_for_round(args.start_round) | ||
| 165 | + assert name == 'random' | ||
| 166 | + assert plan[5] == [-1, -1, 30, 1, -1, 19] | ||
| 167 | + assert replay.slot_value('fc2', args.start_round, 5, 2) == 2332 | ||
| 168 | + | ||
| 169 | + | ||
| 170 | +@pytest.mark.parametrize('start,rounds', [(-1, 1), (1000, 1), (999, 2)]) | ||
| 171 | +def test_invalid_round_window_is_rejected_before_device_imports(start, rounds): | ||
| 172 | + with patch.object(replay, '_run') as run, patch.object(sys, 'argv', | ||
| 173 | + [str(SCRIPT), '--layout', 'compact', '--start-round', str(start), '--rounds', str(rounds)]): | ||
| 174 | + with pytest.raises(SystemExit) as error: | ||
| 175 | + replay.main() | ||
| 176 | + assert error.value.code == 2 | ||
| 177 | + run.assert_not_called() | ||
| 178 | + | ||
| 179 | + | ||
| 180 | +class ProbeExit(BaseException): | ||
| 181 | + pass | ||
| 182 | + | ||
| 183 | + | ||
| 184 | +def test_uncertain_device_failure_exits_with_cached_state(): | ||
| 185 | + def fail(args, state): | ||
| 186 | + state.update(rank=6, projection='fc2', call=2, stage='after_sync') | ||
| 187 | + raise RuntimeError('injected 507035') | ||
| 188 | + console = io.StringIO() | ||
| 189 | + with patch.object(replay, '_run', fail), patch.object(replay.os, '_exit', side_effect=ProbeExit) as exit_, \ | ||
| 190 | + patch.object(sys, 'argv', [str(SCRIPT), '--layout', 'model']), redirect_stdout(console): | ||
| 191 | + with pytest.raises(ProbeExit): | ||
| 192 | + replay.main() | ||
| 193 | + exit_.assert_called_once_with(1) | ||
| 194 | + row = json.loads(console.getvalue().split('[MOONEP_UDMA_LAYOUT_FAILURE] ', 1)[1]) | ||
| 195 | + assert row['stage'] == 'after_sync' and row['projection'] == 'fc2' | ||
| 196 | + assert row['error'] == 'injected 507035' | ||
| 197 | + | ||
| 198 | + | ||
| 199 | +def test_broken_console_still_bypasses_device_teardown(): | ||
| 200 | + with patch.object(replay, '_run', side_effect=RuntimeError('device failure')), \ | ||
| 201 | + patch.object(replay.os, '_exit', side_effect=ProbeExit) as exit_, \ | ||
| 202 | + patch('builtins.print', side_effect=OSError('broken console')), \ | ||
| 203 | + patch.object(sys, 'argv', [str(SCRIPT), '--layout', 'model']): | ||
| 204 | + with pytest.raises(ProbeExit): | ||
| 205 | + replay.main() | ||
| 206 | + exit_.assert_called_once_with(1) | ||
| @@ -0,0 +1,131 @@ | |||
| 1 | +"""Production descriptor/lifecycle code with explicit native and bootstrap doubles.""" | ||
| 2 | +import importlib | ||
| 3 | +import sys | ||
| 4 | +from pathlib import Path | ||
| 5 | +from types import ModuleType, SimpleNamespace | ||
| 6 | + | ||
| 7 | +import pytest | ||
| 8 | +import torch | ||
| 9 | + | ||
| 10 | + | ||
| 11 | +@pytest.fixture | ||
| 12 | +def memory(monkeypatch): | ||
| 13 | + package = ModuleType('npu_patch') | ||
| 14 | + package.__path__ = [str(Path(__file__).resolve().parents[1]/'npu_patch')] | ||
| 15 | + for name in tuple(sys.modules): | ||
| 16 | + if name == 'npu_patch' or name.startswith('npu_patch.'): | ||
| 17 | + monkeypatch.delitem(sys.modules, name) | ||
| 18 | + monkeypatch.setitem(sys.modules, 'npu_patch', package) | ||
| 19 | + native = ModuleType('npu_patch._C') | ||
| 20 | + native.__getattr__ = lambda name: lambda *args, **kwargs: 0 | ||
| 21 | + monkeypatch.setitem(sys.modules, native.__name__, native) | ||
| 22 | + common = ModuleType('npu_patch._common') | ||
| 23 | + common.ACLSHMEM_DATA_OP_MTE, common.ACLSHMEM_DATA_OP_UDMA = 1, 2 | ||
| 24 | + common.compute_shmem_mem_size = lambda *args, **kwargs: 0 | ||
| 25 | + monkeypatch.setitem(sys.modules, common.__name__, common) | ||
| 26 | + monkeypatch.setattr(torch, 'npu', SimpleNamespace(current_device=lambda: 2), raising=False) | ||
| 27 | + module = importlib.import_module('npu_patch.buffer_c') | ||
| 28 | + runtime = importlib.import_module('npu_patch.shmem_runtime') | ||
| 29 | + calls = [] | ||
| 30 | + runtime.torch = SimpleNamespace(npu=torch.npu, int64=torch.int64, uint8=torch.uint8, | ||
| 31 | + device=lambda *args: 'cpu', tensor=lambda values, **kwargs: torch.tensor(values, dtype=kwargs['dtype']), | ||
| 32 | + empty=lambda count, **kwargs: torch.empty(count, dtype=kwargs['dtype'])) | ||
| 33 | + def broadcast(value, *, src, group): | ||
| 34 | + calls.append(('broadcast', src)) | ||
| 35 | + value.copy_(torch.tensor([3] if value.dtype == torch.int64 else list(b'uid'), dtype=value.dtype)) | ||
| 36 | + runtime.dist = SimpleNamespace(get_rank=lambda group=None: 1, get_world_size=lambda group=None: 2, | ||
| 37 | + get_global_rank=lambda group, rank: 6, broadcast=broadcast) | ||
| 38 | + runtime.audit_loaded_shmem_library = lambda: calls.append(('audit',)) or dict(realpath='/mock/libshmem.so', sha256='0'*64) | ||
| 39 | + runtime.symmetric_descriptors = lambda: [(10, 64, 20, b'')] | ||
| 40 | + runtime.shmem_init_with_buffer = lambda *args, **kwargs: calls.append(('uid_init', args, kwargs)) | ||
| 41 | + runtime.shmem_init_with_ip_port = lambda *args, **kwargs: calls.append(('ip_init', args, kwargs)) | ||
| 42 | + yield SimpleNamespace(buffer=module, runtime=runtime, calls=calls) | ||
| 43 | + for name in ('npu_patch.buffer_c', 'npu_patch.shmem_runtime', 'npu_patch._device', 'npu_patch.runtime_audit'): | ||
| 44 | + sys.modules.pop(name, None) | ||
| 45 | + | ||
| 46 | + | ||
| 47 | +@pytest.mark.parametrize('udma', [False, True]) | ||
| 48 | +def test_uid_bootstrap_audits_first_and_preserves_subgroup_and_engine(memory, udma): | ||
| 49 | + runtime = memory.runtime | ||
| 50 | + runtime.ShmemRuntime.init_with_buffer(group=object(), enable_udma=udma) | ||
| 51 | + assert memory.calls[0] == ('audit',) | ||
| 52 | + assert [row for row in memory.calls if row[0]=='broadcast'] == [('broadcast',6),('broadcast',6)] | ||
| 53 | + kind, args, kwargs = memory.calls[-1] | ||
| 54 | + assert kind == 'uid_init' and args[1:4] == (1, 2, b'uid') | ||
| 55 | + assert kwargs['device_id'] == 2 # current visible device, never EP rank 1 | ||
| 56 | + assert kwargs['data_op_engine_type'] == (3 if udma else 1) | ||
| 57 | + assert kwargs['qp_count'] == (2 if udma else 0) | ||
| 58 | + evidence = runtime.runtime_library_info() | ||
| 59 | + evidence['realpath'] = '/modified' | ||
| 60 | + assert runtime.runtime_library_info()['realpath'] == '/mock/libshmem.so' | ||
| 61 | + | ||
| 62 | + | ||
| 63 | +@pytest.mark.parametrize('udma', [False, True]) | ||
| 64 | +def test_ip_bootstrap_audits_before_native(memory, udma): | ||
| 65 | + runtime = memory.runtime | ||
| 66 | + runtime.ShmemRuntime.init_with_ip_port(rank=1, world_size=2, ip_port='tcp://mock:1234', enable_udma=udma) | ||
| 67 | + assert [row[0] for row in memory.calls] == ['audit','ip_init'] | ||
| 68 | + assert memory.calls[-1][2]['enable_udma'] is udma | ||
| 69 | + assert memory.calls[-1][2]['device_id'] == 2 | ||
| 70 | + | ||
| 71 | + | ||
| 72 | +def test_audit_failure_blocks_uid_generation_and_native_init(memory): | ||
| 73 | + def fail(): | ||
| 74 | + raise RuntimeError('multiple SHMEM images') | ||
| 75 | + memory.runtime.audit_loaded_shmem_library = fail | ||
| 76 | + with pytest.raises(RuntimeError, match='multiple SHMEM'): | ||
| 77 | + memory.runtime.ShmemRuntime.init_with_buffer() | ||
| 78 | + assert memory.calls == [] and not memory.runtime.ShmemRuntime.is_initialized() | ||
| 79 | + | ||
| 80 | + | ||
| 81 | +def test_finalize_failure_retains_heap_and_blocks_reinitialization(memory): | ||
| 82 | + runtime = memory.runtime | ||
| 83 | + runtime.ShmemRuntime._initialized = True | ||
| 84 | + runtime.shmem_finalize = lambda: 17 | ||
| 85 | + with pytest.raises(RuntimeError, match='failed with 17'): | ||
| 86 | + runtime.ShmemRuntime.finalize() | ||
| 87 | + assert runtime.ShmemRuntime.is_initialized() and runtime.ShmemRuntime._poisoned | ||
| 88 | + with pytest.raises(RuntimeError, match='reinitialization is forbidden'): | ||
| 89 | + runtime.ShmemRuntime.init_with_buffer() | ||
| 90 | + | ||
| 91 | + | ||
| 92 | +@pytest.mark.parametrize('bootstrap', ['uid','ip']) | ||
| 93 | +def test_descriptor_registry_is_frozen_during_native_init_and_failed_init_rolls_back(memory, bootstrap): | ||
| 94 | + module = memory.buffer | ||
| 95 | + allocation = module.VmmAllocation(10, 20, 0, 64) | ||
| 96 | + def failed(*args, **kwargs): | ||
| 97 | + with pytest.raises(RuntimeError, match='active heap'): | ||
| 98 | + module.register_symmetric_descriptor(allocation) | ||
| 99 | + raise RuntimeError('native failure') | ||
| 100 | + if bootstrap == 'uid': | ||
| 101 | + module.acl_shmem_init_with_buffers = failed | ||
| 102 | + invoke = lambda: module.shmem_init_with_buffer([(10,64,20,b'')],1,2,b'uid',device_id=2) | ||
| 103 | + else: | ||
| 104 | + module.acl_shmem_init_with_buffers_ip_port = failed | ||
| 105 | + invoke = lambda: module.shmem_init_with_ip_port(1,2,'tcp://mock:1234',[(10,64,20,b'')],device_id=2) | ||
| 106 | + with pytest.raises(RuntimeError, match='native failure'): | ||
| 107 | + invoke() | ||
| 108 | + assert not module._SHMEM_BACKING_LOCKED and not module._VMM_REGISTRY | ||
| 109 | + | ||
| 110 | + | ||
| 111 | +def test_vmm_allocation_preserves_visible_and_physical_device_ids(memory, monkeypatch): | ||
| 112 | + module = memory.buffer | ||
| 113 | + monkeypatch.setenv('ASCEND_RT_VISIBLE_DEVICES','4,5,7') | ||
| 114 | + module.torch = SimpleNamespace(npu=torch.npu, device=lambda name:name) | ||
| 115 | + module.acl_vmm_granularity = lambda device: 64 | ||
| 116 | + created, freed = [], [] | ||
| 117 | + module.acl_vmm_alloc_source = lambda size, device, access: created.append((size,device,access)) or (100,200,0,size,b'fabric') | ||
| 118 | + module.acl_vmm_free_source = lambda va, handle: freed.append((va,handle)) | ||
| 119 | + module.create_sym_tensor_from_ptr = lambda *args: SimpleNamespace() | ||
| 120 | + tensor, _, _ = module.create_vmm_physical((4,8),torch.float32,2) | ||
| 121 | + assert created == [(128,2,7)] | ||
| 122 | + module._SHMEM_BACKING_LOCKED = True | ||
| 123 | + with pytest.raises(RuntimeError, match='backing'): | ||
| 124 | + tensor._vmm_allocation.destroy() | ||
| 125 | + assert freed == [] | ||
| 126 | + module.acl_shmem_finalize = lambda: 9 | ||
| 127 | + assert module.shmem_finalize() == 9 and module._SHMEM_BACKING_LOCKED | ||
| 128 | + module.acl_shmem_finalize = lambda: 0 | ||
| 129 | + assert module.shmem_finalize() == 0 and not module._SHMEM_BACKING_LOCKED | ||
| 130 | + tensor._vmm_allocation.destroy() | ||
| 131 | + assert freed == [(100,200)] | ||
| @@ -0,0 +1,34 @@ | |||
| 1 | +"""Regression for the real A5 host/device parameter packing failure.""" | ||
| 2 | +from pathlib import Path | ||
| 3 | +import runpy | ||
| 4 | +import struct | ||
| 5 | + | ||
| 6 | +import pytest | ||
| 7 | + | ||
| 8 | +CHECK = runpy.run_path(str(Path(__file__).resolve().parents[1] / | ||
| 9 | + 'npu_patch/scripts/validate_ordered_grad_kernel_abi.py')) | ||
| 10 | + | ||
| 11 | + | ||
| 12 | +def metadata(fields): | ||
| 13 | + result = struct.pack('<HHIII', 0x10, 12, 10, 64, 0) | ||
| 14 | + for index, offset, size in fields: | ||
| 15 | + result += struct.pack('<HHIIIIHHIIII', 0x11, 36, | ||
| 16 | + 0, index, offset, size, size, 1, 0, 0, 0, 0) | ||
| 17 | + return result | ||
| 18 | + | ||
| 19 | + | ||
| 20 | +def test_aligned_argument_contract(): | ||
| 21 | + assert CHECK['validate_metadata'](metadata(CHECK['EXPECTED']))['argument_bytes'] == 64 | ||
| 22 | + | ||
| 23 | + | ||
| 24 | +def test_a303_compiled_host_layout_is_rejected(): | ||
| 25 | + # Recorded ParamInfo from the failed CPU4 device binary: epn then matrix. | ||
| 26 | + rows = CHECK['EXPECTED'][:5] + [(5, 40, 4), (6, 44, 8), | ||
| 27 | + (7, 52, 4), (8, 56, 4), (9, 60, 4)] | ||
| 28 | + with pytest.raises(ValueError, match='unaligned parameter'): | ||
| 29 | + CHECK['validate_metadata'](metadata(rows)) | ||
| 30 | + | ||
| 31 | + | ||
| 32 | +def test_missing_device_image_is_not_build_evidence(): | ||
| 33 | + with pytest.raises(ValueError, match='absent'): | ||
| 34 | + CHECK['validate_binary'](b'not a device ELF') | ||
| @@ -0,0 +1,116 @@ | |||
| 1 | +"""Execute the actual host launch branch with CPU fault-injection stubs. | ||
| 2 | + | ||
| 3 | +Only <<<...>>> launch syntax is lowered; the host conditions and return paths | ||
| 4 | +are compiled unchanged. This tests submission order/error propagation, not | ||
| 5 | +device execution, FP32 arithmetic, or remote completion. | ||
| 6 | +""" | ||
| 7 | +from pathlib import Path | ||
| 8 | +import shutil | ||
| 9 | +import subprocess | ||
| 10 | + | ||
| 11 | +import pytest | ||
| 12 | + | ||
| 13 | + | ||
| 14 | +SOURCE = (Path(__file__).resolve().parents[1] / | ||
| 15 | + 'npu_patch/native/kernels/moonep_grad_reduce_udma.cpp') | ||
| 16 | + | ||
| 17 | + | ||
| 18 | +@pytest.fixture(scope='module') | ||
| 19 | +def launch_binary(tmp_path_factory): | ||
| 20 | + compiler = shutil.which('g++') or shutil.which('c++') | ||
| 21 | + if compiler is None: | ||
| 22 | + pytest.skip('CPU C++ compiler required for native host fault injection') | ||
| 23 | + text = SOURCE.read_text(encoding='utf-8') | ||
| 24 | + begin = text.index('static int LaunchGradReduceUdma(') | ||
| 25 | + end = text.index('\nextern "C"', begin) | ||
| 26 | + host = text[begin:end] | ||
| 27 | + # Exactly one site for each kernel: unexpected source changes fail closed. | ||
| 28 | + for name, stub, blocks in [ | ||
| 29 | + ('MoonEPShmemGradReduceUdmaOrderedTargets', 'ordered', 'blocks'), | ||
| 30 | + ('MoonEPShmemClearValidGradSlots', 'clear', '1'), | ||
| 31 | + ('MoonEPShmemGradReduceUdmaFused', 'legacy', 'blocks'), | ||
| 32 | + ]: | ||
| 33 | + token = f'{name}<<<{blocks}, nullptr, stream>>>' | ||
| 34 | + assert host.count(token) == 1 | ||
| 35 | + host = host.replace(token, stub) | ||
| 36 | + assert '<<<' not in host | ||
| 37 | + prelude = r''' | ||
| 38 | +#include <cstdint> | ||
| 39 | +#include <cstdlib> | ||
| 40 | +#include <iostream> | ||
| 41 | +#include <string> | ||
| 42 | +#include <vector> | ||
| 43 | +constexpr int ACL_SUCCESS = 0; | ||
| 44 | +constexpr int ACL_ERROR_INVALID_PARAM = 7; | ||
| 45 | +constexpr int ACL_RT_THREAD_LEVEL = 0; | ||
| 46 | +int scenario, last_error; | ||
| 47 | +std::vector<std::string> events; | ||
| 48 | +int aclrtPeekAtLastError(int) { return last_error; } | ||
| 49 | +int aclrtGetLastError(int) { std::abort(); } // Never erase the first error. | ||
| 50 | +int aclshmem_n_pes() { return scenario == 6 ? 3 : 2; } | ||
| 51 | +uint64_t shmemx_get_ffts_config() { return 0; } | ||
| 52 | +template<class... T> void ordered(T...) { | ||
| 53 | + events.push_back("ordered"); | ||
| 54 | + last_error = scenario == 2 ? 43 : 0; | ||
| 55 | +} | ||
| 56 | +int moonep_prefetch_barrier_vec(void*) { | ||
| 57 | + events.push_back("vector_barrier"); | ||
| 58 | + // Deliberately do not set last_error: the caller must check this return. | ||
| 59 | + return scenario == 3 ? 47 : 0; | ||
| 60 | +} | ||
| 61 | +template<class... T> void clear(T...) { | ||
| 62 | + events.push_back("clear"); | ||
| 63 | + last_error = scenario == 4 ? 53 : 0; | ||
| 64 | +} | ||
| 65 | +template<class... T> void legacy(T...) { std::abort(); } | ||
| 66 | +''' | ||
| 67 | + main = r''' | ||
| 68 | +int main(int argc, char** argv) { | ||
| 69 | + if (argc != 2) return 2; | ||
| 70 | + scenario = std::atoi(argv[1]); | ||
| 71 | + last_error = scenario == 1 ? 41 : 0; | ||
| 72 | + int data = 0; | ||
| 73 | + auto* stream = scenario == 5 ? nullptr : static_cast<void*>(&data); | ||
| 74 | + int status = LaunchGradReduceUdma(stream, &data, &data, &data, | ||
| 75 | + &data, 1, 3, 5, 2, 1, 0, 8, true); | ||
| 76 | + std::cout << status; | ||
| 77 | + for (auto const& event : events) std::cout << " " << event; | ||
| 78 | + std::cout << "\n"; | ||
| 79 | +} | ||
| 80 | +''' | ||
| 81 | + directory = tmp_path_factory.mktemp('ordered_host_launch') | ||
| 82 | + source = directory / 'host.cpp' | ||
| 83 | + binary = directory / 'host' | ||
| 84 | + source.write_text(prelude + host + main, encoding='utf-8') | ||
| 85 | + result = subprocess.run([compiler, '-std=c++17', '-Wall', '-Wextra', | ||
| 86 | + str(source), '-o', str(binary)], | ||
| 87 | + capture_output=True, text=True, timeout=60) | ||
| 88 | + assert result.returncode == 0, result.stderr | ||
| 89 | + return binary | ||
| 90 | + | ||
| 91 | + | ||
| 92 | +@pytest.mark.parametrize('scenario,expected', [ | ||
| 93 | + (0, '0 ordered vector_barrier clear'), | ||
| 94 | + (1, '41'), # Preserve a pre-existing ACL error. | ||
| 95 | + (2, '43 ordered'), # Failed GET/reduce launch: no barrier. | ||
| 96 | + (3, '47 ordered vector_barrier'), # Failed barrier: must not clear slots. | ||
| 97 | + (4, '53 ordered vector_barrier clear'), | ||
| 98 | + (5, '7'), # Invalid stream: no launch. | ||
| 99 | + (6, '7'), # SHMEM world mismatch: no launch. | ||
| 100 | +]) | ||
| 101 | +def test_ordered_submission_fails_closed(launch_binary, scenario, expected): | ||
| 102 | + result = subprocess.run([str(launch_binary), str(scenario)], | ||
| 103 | + capture_output=True, text=True, timeout=5) | ||
| 104 | + assert result.returncode == 0, result.stderr | ||
| 105 | + assert result.stdout.strip() == expected | ||
| 106 | + | ||
| 107 | + | ||
| 108 | +def test_local_sync_and_inter_pe_collective_stay_in_different_kernels(): | ||
| 109 | + text = SOURCE.read_text(encoding='utf-8') | ||
| 110 | + begin = text.index('void MoonEPShmemGradReduceUdmaOrderedTargets(') | ||
| 111 | + end = text.index('\nextern "C"', begin) | ||
| 112 | + kernel = text[begin:end] | ||
| 113 | + assert 'SyncAll<true>();' in kernel | ||
| 114 | + assert 'aclshmemx_barrier' not in kernel | ||
| 115 | + assert 'SetAtomicAdd' not in kernel | ||
| 116 | + assert 'moonep_prefetch_barrier_vec' not in kernel | ||
| @@ -0,0 +1,22 @@ | |||
| 1 | +"""Actual setup sizing helper; CPU bounds do not prove device execution.""" | ||
| 2 | +from pathlib import Path | ||
| 3 | +import runpy | ||
| 4 | +import pytest | ||
| 5 | + | ||
| 6 | +workspace_elements = runpy.run_path(str(Path(__file__).resolve().parents[1] / | ||
| 7 | + 'npu_patch/_grad_reduce_contract.py'))['workspace_elements'] | ||
| 8 | + | ||
| 9 | + | ||
| 10 | +def test_ep8_l6_32_preserves_current_workspace_bytes(): | ||
| 11 | + assert workspace_elements(8, 6, 32) * 4 == 128 << 20 | ||
| 12 | + | ||
| 13 | + | ||
| 14 | +def test_peer_slot_bound_exceeds_old_scratch_for_small_core_count(): | ||
| 15 | + assert workspace_elements(8, 6, 4) * 4 == 96 << 20 | ||
| 16 | + assert workspace_elements(8, 0, 32) == 512 * 1024 * 64 | ||
| 17 | + | ||
| 18 | + | ||
| 19 | +@pytest.mark.parametrize('shape,error', [((8,-1,32),ValueError),((0,6,32),ValueError), | ||
| 20 | + ((8,6,0),ValueError),((8,6,True),TypeError),((1<<31,1<<31,32),OverflowError)]) | ||
| 21 | +def test_invalid_or_overflowing_scratch_is_rejected(shape,error): | ||
| 22 | + with pytest.raises(error):workspace_elements(*shape) | ||
| @@ -0,0 +1,30 @@ | |||
| 1 | +"""Execute production pre-allocation guards with no accelerator imports.""" | ||
| 2 | +import ast | ||
| 3 | +from pathlib import Path | ||
| 4 | +from types import SimpleNamespace | ||
| 5 | +import unittest | ||
| 6 | + | ||
| 7 | + | ||
| 8 | +class PreallocationPolicyTest(unittest.TestCase): | ||
| 9 | + def context(self, **kwargs): | ||
| 10 | + path=Path(__file__).resolve().parents[1]/'npu_patch/api.py' | ||
| 11 | + tree=ast.parse(path.read_text(encoding='utf-8')) | ||
| 12 | + node=next(n for n in tree.body if isinstance(n,ast.FunctionDef) and n.name=='_create_context') | ||
| 13 | + future=ast.ImportFrom(module='__future__',names=[ast.alias(name='annotations')],level=0) | ||
| 14 | + ns={'_C':SimpleNamespace()} | ||
| 15 | + exec(compile(ast.fix_missing_locations(ast.Module(body=[future,node],type_ignores=[])),str(path),'exec'),ns) | ||
| 16 | + return ns['_create_context'](4,5,1,4,2,**kwargs) | ||
| 17 | + | ||
| 18 | + def test_invalid_reduce_budget_never_reaches_torch_allocation(self): | ||
| 19 | + for blocks in (0,65,-1,True,1.5,'8'): | ||
| 20 | + with self.subTest(blocks=blocks),self.assertRaisesRegex(ValueError,'grad_reduce_num_sms'): | ||
| 21 | + self.context(grad_reduce_num_sms=blocks) | ||
| 22 | + | ||
| 23 | + def test_missing_aiv_abi_and_bad_mode_reject_before_allocation(self): | ||
| 24 | + with self.assertRaisesRegex(RuntimeError,'barrier ABI v1'): | ||
| 25 | + self.context(prefetch_barrier_mode='aiv') | ||
| 26 | + with self.assertRaisesRegex(ValueError,'prefetch_barrier_mode'): | ||
| 27 | + self.context(prefetch_barrier_mode='unsafe') | ||
| 28 | + | ||
| 29 | + | ||
| 30 | +if __name__=='__main__':unittest.main() | ||
| @@ -0,0 +1,139 @@ | |||
| 1 | +"""Standalone pointer contract and partial-submission ownership, CPU only.""" | ||
| 2 | +import gc | ||
| 3 | +import importlib.util | ||
| 4 | +from pathlib import Path | ||
| 5 | +import unittest | ||
| 6 | +import weakref | ||
| 7 | +import types | ||
| 8 | +import sys | ||
| 9 | +from unittest.mock import patch | ||
| 10 | + | ||
| 11 | +ROOT = Path(__file__).resolve().parents[1] | ||
| 12 | +spec = importlib.util.spec_from_file_location('prefetch_pointer_contract', ROOT/'npu_patch/prefetch_pointer.py') | ||
| 13 | +module = importlib.util.module_from_spec(spec) | ||
| 14 | +spec.loader.exec_module(module) | ||
| 15 | + | ||
| 16 | + | ||
| 17 | +class Device: | ||
| 18 | + type = 'npu' | ||
| 19 | + | ||
| 20 | + | ||
| 21 | +DEVICE = Device() | ||
| 22 | + | ||
| 23 | + | ||
| 24 | +class Tensor: | ||
| 25 | + def __init__(self, shape, address=1024, dtype='bf16', contiguous=True): | ||
| 26 | + self.shape, self.ndim, self.dtype = shape, len(shape), dtype | ||
| 27 | + self.device, self.address, self.contiguous = DEVICE, address, contiguous | ||
| 28 | + def is_contiguous(self): return self.contiguous | ||
| 29 | + def data_ptr(self): return self.address | ||
| 30 | + def numel(self): | ||
| 31 | + result = 1 | ||
| 32 | + for dim in self.shape: result *= dim | ||
| 33 | + return result | ||
| 34 | + def element_size(self): return 2 if self.dtype == 'bf16' else 4 | ||
| 35 | + def cpu(self): raise AssertionError('no device reads during validation') | ||
| 36 | + def item(self): raise AssertionError('no device reads during validation') | ||
| 37 | + | ||
| 38 | + | ||
| 39 | +class Event: | ||
| 40 | + def __init__(self, done=False, fail=None): self.done, self.fail = done, fail | ||
| 41 | + def record(self): | ||
| 42 | + if self.fail == 'record': raise RuntimeError('record failed') | ||
| 43 | + def query(self): | ||
| 44 | + if self.fail == 'query': raise RuntimeError('query failed') | ||
| 45 | + return self.done | ||
| 46 | + def synchronize(self): | ||
| 47 | + if self.fail == 'wait': raise RuntimeError('wait failed') | ||
| 48 | + self.done = True | ||
| 49 | + | ||
| 50 | + | ||
| 51 | +class PointerContract(unittest.TestCase): | ||
| 52 | + def test_runtime_poison_rejects_before_table_allocation_or_native(self): | ||
| 53 | + torch = types.SimpleNamespace(bfloat16='bf16', int32='i32') | ||
| 54 | + native = types.SimpleNamespace(PREFETCH_PUSH_POINTER_ABI=1, | ||
| 55 | + _prefetch_push_available=lambda: True) | ||
| 56 | + runtime = types.SimpleNamespace(_poisoned=True, _udma_enabled=True, | ||
| 57 | + is_initialized=lambda: True) | ||
| 58 | + with patch.object(module, '__package__', '_pointer_fixture'), patch.dict(sys.modules, { | ||
| 59 | + 'torch': torch, 'torch_npu': types.SimpleNamespace(), | ||
| 60 | + '_pointer_fixture': types.SimpleNamespace(_C=native), | ||
| 61 | + '_pointer_fixture.shmem_runtime': types.SimpleNamespace(ShmemRuntime=runtime)}): | ||
| 62 | + with self.assertRaisesRegex(RuntimeError, 'initialized URMA SHMEM'): | ||
| 63 | + module.launch_prefetch_push_ptrs([Tensor((3,5))], Tensor((7,3,5),20000), | ||
| 64 | + Tensor((8,7),dtype='i32'), 1) | ||
| 65 | + def valid(self, refs=None, slots=None, plan=None, sms=1): | ||
| 66 | + return module.validate_pointer_sources( | ||
| 67 | + [Tensor((3,5),9000),Tensor((3,5),1000)] if refs is None else refs, | ||
| 68 | + Tensor((7,3,5),20000) if slots is None else slots, | ||
| 69 | + Tensor((8,7),dtype='i32') if plan is None else plan, | ||
| 70 | + sms, bf16='bf16', int32='i32') | ||
| 71 | + def test_reverse_separate_and_duplicate_sources_are_legal(self): | ||
| 72 | + a,b=Tensor((3,5),9000),Tensor((3,5),1000) | ||
| 73 | + self.assertEqual(self.valid([a,b,a]),(a,b,a)) | ||
| 74 | + def test_l_different_from_b_and_empty_slots(self): | ||
| 75 | + self.valid([Tensor((3,5))]) | ||
| 76 | + self.valid(slots=Tensor((0,3,5)),plan=Tensor((8,0),dtype='i32')) | ||
| 77 | + def test_invalid_sources(self): | ||
| 78 | + for refs in ([],[Tensor((3,5),0)],[Tensor((3,5),dtype='fp32')], | ||
| 79 | + [Tensor((5,3))],[Tensor((3,5),contiguous=False)], [123]): | ||
| 80 | + with self.subTest(refs=refs), self.assertRaises((ValueError,AttributeError)): | ||
| 81 | + self.valid(refs) | ||
| 82 | + def test_source_destination_overlap_rejected(self): | ||
| 83 | + with self.assertRaises(ValueError): self.valid([Tensor((3,5),20010)]) | ||
| 84 | + def test_wrong_device_and_plan_and_ub_rejected(self): | ||
| 85 | + slots=Tensor((7,3,5),20000); slots.device=Device() | ||
| 86 | + for kwargs in (dict(slots=slots),dict(plan=Tensor((7,),dtype='i32')), | ||
| 87 | + dict(plan=Tensor((8,6),dtype='i32')), | ||
| 88 | + dict(slots=Tensor((15737,3,5)),plan=Tensor((8,15737),dtype='i32')), | ||
| 89 | + dict(sms=True),dict(plan=Tensor((0,7),dtype='i32'))): | ||
| 90 | + with self.subTest(kwargs=kwargs), self.assertRaises(ValueError): self.valid(**kwargs) | ||
| 91 | + def test_core_not_duplicated_and_no_lplusb_dependency(self): | ||
| 92 | + p=ROOT/'npu_patch/native/kernels/prefetch_pointer_push_udma.cpp' | ||
| 93 | + self.assertIn('moonep_urma_push::Run<true>',p.read_text()) | ||
| 94 | + native=(ROOT/'npu_patch/native/csrc/ops/prefetch.cpp').read_text() | ||
| 95 | + self.assertNotIn('lplusb',native.lower()) | ||
| 96 | + pointer = native[native.index('torch::Tensor LaunchPrefetchPushPointers'):].split('torch::Tensor LaunchPrefetchPushLocal')[0] | ||
| 97 | + self.assertEqual(pointer.count('PrefetchBarrier(stream, aiv_barrier)'),2) | ||
| 98 | + helper = native.split('void PrefetchBarrier',1)[1].split('void CheckNpuContiguous',1)[0] | ||
| 99 | + self.assertIn('moonep_prefetch_barrier_vec(stream)',helper) | ||
| 100 | + self.assertIn('aclshmemx_barrier_all_on_stream(stream)',helper) | ||
| 101 | + | ||
| 102 | + | ||
| 103 | +class PendingLifetime(unittest.TestCase): | ||
| 104 | + def test_retains_until_event_completion(self): | ||
| 105 | + owner=module._PendingPushes(); source=Tensor((3,5)); ref=weakref.ref(source); event=Event() | ||
| 106 | + result=owner.submit((source,),lambda:'destination',lambda:event) | ||
| 107 | + self.assertEqual(result,'destination') | ||
| 108 | + del source;gc.collect();self.assertIsNotNone(ref()) | ||
| 109 | + owner.collect();self.assertEqual(len(owner.pending),1) | ||
| 110 | + event.done=True;owner.collect();gc.collect();self.assertIsNone(ref()) | ||
| 111 | + def test_partial_launch_and_record_failure_poison_and_retain(self): | ||
| 112 | + def fail(): raise RuntimeError('partial launch') | ||
| 113 | + for launch,make_event in ((fail,Event),(lambda:None,lambda:Event(fail='record'))): | ||
| 114 | + owner=module._PendingPushes(); source=Tensor((3,5)); ref=weakref.ref(source) | ||
| 115 | + with self.assertRaises(RuntimeError): owner.submit((source,),launch,make_event) | ||
| 116 | + del source;gc.collect();self.assertIsNotNone(ref()) | ||
| 117 | + for operation in (owner.collect,owner.drain): | ||
| 118 | + with self.assertRaises(RuntimeError): operation() | ||
| 119 | + self.assertEqual(len(owner.pending),1) | ||
| 120 | + def test_query_failure_preserves_whole_pending_list(self): | ||
| 121 | + owner=module._PendingPushes() | ||
| 122 | + owner.submit((1,),lambda:None,lambda:Event()) | ||
| 123 | + owner.submit((2,),lambda:None,lambda:Event(fail='query')) | ||
| 124 | + first=owner.pending[0][0];first.done=True | ||
| 125 | + with self.assertRaisesRegex(RuntimeError,'query'):owner.collect() | ||
| 126 | + self.assertTrue(owner.poisoned);self.assertEqual(len(owner.pending),2) | ||
| 127 | + def test_drain_wait_failure_does_not_release_completed_rows(self): | ||
| 128 | + owner=module._PendingPushes() | ||
| 129 | + owner.submit((1,),lambda:None,lambda:Event()) | ||
| 130 | + owner.submit((2,),lambda:None,lambda:Event(fail='wait')) | ||
| 131 | + with self.assertRaisesRegex(RuntimeError,'wait'):owner.drain() | ||
| 132 | + self.assertTrue(owner.poisoned);self.assertEqual(len(owner.pending),2) | ||
| 133 | + def test_drain_waits_all_transfers_then_releases(self): | ||
| 134 | + owner=module._PendingPushes();events=[Event(),Event()] | ||
| 135 | + for event in events:owner.submit((1,),lambda:None,lambda:event) | ||
| 136 | + owner.drain();self.assertTrue(all(e.done for e in events));self.assertEqual(owner.pending,[]) | ||
| 137 | + | ||
| 138 | + | ||
| 139 | +if __name__ == '__main__': unittest.main() | ||
| @@ -0,0 +1,64 @@ | |||
| 1 | +"""Run without torch or NPU: python -m unittest discover -s host_tests -p test_prefetch_push_contract.py.""" | ||
| 2 | +import importlib.util | ||
| 3 | +from pathlib import Path | ||
| 4 | +import unittest | ||
| 5 | + | ||
| 6 | +path = Path(__file__).resolve().parents[1] / "npu_patch/_prefetch_contract.py" | ||
| 7 | +spec = importlib.util.spec_from_file_location("push_contract", path) | ||
| 8 | +contract = importlib.util.module_from_spec(spec) | ||
| 9 | +spec.loader.exec_module(contract) | ||
| 10 | + | ||
| 11 | +class Device: | ||
| 12 | + type = "npu" | ||
| 13 | + | ||
| 14 | +class Tensor: | ||
| 15 | + device = Device() | ||
| 16 | + def __init__(self, shape, dtype="bf16", contiguous=True): | ||
| 17 | + self.shape, self.dtype, self.ndim = shape, dtype, len(shape) | ||
| 18 | + self.contiguous = contiguous | ||
| 19 | + def is_contiguous(self): | ||
| 20 | + return self.contiguous | ||
| 21 | + def cpu(self): | ||
| 22 | + raise AssertionError("metadata validation must not copy/synchronize") | ||
| 23 | + def item(self): | ||
| 24 | + raise AssertionError("metadata validation must not read device data") | ||
| 25 | + | ||
| 26 | +class PushContract(unittest.TestCase): | ||
| 27 | + def valid(self, home=None, slots=None, plan=None, sms=1): | ||
| 28 | + contract.validate_push_layout( | ||
| 29 | + home or Tensor((8,6144,7168)), slots or Tensor((7,6144,7168)), | ||
| 30 | + plan or Tensor((8,7),"int32"), sms, bf16="bf16", int32="int32") | ||
| 31 | + def test_formula(self): | ||
| 32 | + self.valid() | ||
| 33 | + def test_empty_slots(self): | ||
| 34 | + self.valid(slots=Tensor((0,6144,7168)), plan=Tensor((8,0),"int32")) | ||
| 35 | + def test_wrong_plan_axis(self): | ||
| 36 | + with self.assertRaises(ValueError): | ||
| 37 | + self.valid(plan=Tensor((7,),"int32")) | ||
| 38 | + def test_wrong_projection(self): | ||
| 39 | + with self.assertRaises(ValueError): | ||
| 40 | + self.valid(slots=Tensor((7,7168,3072))) | ||
| 41 | + def test_wrong_dtype(self): | ||
| 42 | + with self.assertRaises(TypeError): | ||
| 43 | + self.valid(plan=Tensor((8,7),"int64")) | ||
| 44 | + def test_noncontiguous(self): | ||
| 45 | + with self.assertRaises(ValueError): | ||
| 46 | + self.valid(home=Tensor((8,6144,7168),contiguous=False)) | ||
| 47 | + def test_ub_overflow(self): | ||
| 48 | + with self.assertRaises(ValueError): | ||
| 49 | + self.valid(slots=Tensor((15737,1,1)),home=Tensor((8,1,1)), | ||
| 50 | + plan=Tensor((8,15737),"int32")) | ||
| 51 | + def test_sms_bool_rejected(self): | ||
| 52 | + with self.assertRaises(ValueError): | ||
| 53 | + self.valid(sms=True) | ||
| 54 | + def test_expert_index_overflow(self): | ||
| 55 | + with self.assertRaises(ValueError): | ||
| 56 | + self.valid(home=Tensor((2147483648,6144,7168))) | ||
| 57 | + def test_different_device(self): | ||
| 58 | + slots=Tensor((7,6144,7168)) | ||
| 59 | + slots.device=Device() | ||
| 60 | + with self.assertRaises(ValueError): | ||
| 61 | + self.valid(slots=slots) | ||
| 62 | + | ||
| 63 | +if __name__ == "__main__": | ||
| 64 | + unittest.main() | ||
| @@ -0,0 +1,352 @@ | |||
| 1 | +"""Real CPU tensors and production Buffer; NPU streams/transport are explicit doubles.""" | ||
| 2 | +import contextlib | ||
| 3 | +import importlib | ||
| 4 | +import sys | ||
| 5 | +from pathlib import Path | ||
| 6 | +from types import ModuleType, SimpleNamespace | ||
| 7 | + | ||
| 8 | +import pytest | ||
| 9 | +import torch | ||
| 10 | + | ||
| 11 | + | ||
| 12 | +PACKAGE = Path(__file__).resolve().parents[1] / 'npu_patch' | ||
| 13 | + | ||
| 14 | + | ||
| 15 | +@pytest.fixture | ||
| 16 | +def provider(monkeypatch): | ||
| 17 | + # Load the actual Python provider without loading its NPU package initializer. | ||
| 18 | + package = ModuleType('npu_patch') | ||
| 19 | + package.__path__ = [str(PACKAGE)] | ||
| 20 | + for name in tuple(sys.modules): | ||
| 21 | + if name == 'npu_patch' or name.startswith('npu_patch.'): | ||
| 22 | + monkeypatch.delitem(sys.modules, name) | ||
| 23 | + monkeypatch.setitem(sys.modules, 'npu_patch', package) | ||
| 24 | + calls, owners = [], {} | ||
| 25 | + | ||
| 26 | + class Stream: | ||
| 27 | + npu_stream = 7 | ||
| 28 | + def wait_stream(self, other): | ||
| 29 | + calls.append(('wait_stream', other)) | ||
| 30 | + def record_event(self): | ||
| 31 | + calls.append(('event',)) | ||
| 32 | + return object() | ||
| 33 | + def synchronize(self): | ||
| 34 | + calls.append(('synchronize',)) | ||
| 35 | + | ||
| 36 | + current = Stream() | ||
| 37 | + class Event: | ||
| 38 | + def record(self, stream): pass | ||
| 39 | + def query(self): return True | ||
| 40 | + npu = ModuleType('torch_npu') | ||
| 41 | + npu.npu = SimpleNamespace(Stream=Stream, Event=Event, current_stream=lambda: current, | ||
| 42 | + stream=lambda stream: contextlib.nullcontext(), synchronize=lambda: calls.append(('sync_device',))) | ||
| 43 | + monkeypatch.setitem(sys.modules, 'torch_npu', npu) | ||
| 44 | + native = ModuleType('npu_patch._C') | ||
| 45 | + native.LPLUS_B_BUFFER_SYNC_ABI = 2 | ||
| 46 | + native.GRAD_REDUCE_POINTER_ABI = 1 | ||
| 47 | + native._lplusb_owner_push = lambda *args: calls.append(('push', args)) | ||
| 48 | + native._lplusb_owner_reduce = lambda *args: calls.append(('reduce', args)) | ||
| 49 | + monkeypatch.setitem(sys.modules, native.__name__, native) | ||
| 50 | + package._C = native | ||
| 51 | + common = ModuleType('npu_patch._common') | ||
| 52 | + common.BARRIER_SLOTS = 1 | ||
| 53 | + common.OP_WS_BYTES_DEFAULT = 1 | ||
| 54 | + common.dispatch_sync_buffer_nbytes = lambda ranks: 1 | ||
| 55 | + def barrier(ctx, stream): | ||
| 56 | + ctx['_barrier_round'] += 1 | ||
| 57 | + calls.append(('barrier', stream)) | ||
| 58 | + common.cross_rank_barrier = barrier | ||
| 59 | + common.record_streams = lambda tensors, stream: calls.append(('record_streams',)) | ||
| 60 | + monkeypatch.setitem(sys.modules, common.__name__, common) | ||
| 61 | + backing = ModuleType('npu_patch.buffer_c') | ||
| 62 | + backing._OWNER_SOURCE_VA_ATTR = '_moonep_owner_source_va' | ||
| 63 | + backing._SLOT_SOURCE_VA_ATTR = '_moonep_slot_source_va' | ||
| 64 | + def from_pointer(pointer, shape, dtype, device): | ||
| 65 | + owner = owners[pointer] | ||
| 66 | + # Independent Tensor metadata over the same CPU storage, no copy. | ||
| 67 | + return torch.empty(0, dtype=dtype).set_(owner.untyped_storage(), 0, tuple(shape)) | ||
| 68 | + backing.create_sym_tensor_from_ptr = from_pointer | ||
| 69 | + backing.sym_tensor = lambda tensor: tensor | ||
| 70 | + for name in ('create_sym_tensor_from_source', 'create_vmm_physical', 'map_to_sym_ptr', 'acl_vmm_granularity'): | ||
| 71 | + setattr(backing, name, lambda *args, **kwargs: None) | ||
| 72 | + def granularity(device): | ||
| 73 | + calls.append(('granularity', device)) | ||
| 74 | + return 64 | ||
| 75 | + backing.acl_vmm_granularity = granularity | ||
| 76 | + monkeypatch.setitem(sys.modules, backing.__name__, backing) | ||
| 77 | + kernel_op = ModuleType('npu_patch.kernel_op') | ||
| 78 | + kernel_op.KernelOp = object | ||
| 79 | + monkeypatch.setitem(sys.modules, kernel_op.__name__, kernel_op) | ||
| 80 | + launchers = ModuleType('npu_patch.launchers') | ||
| 81 | + launchers.planning_workspace_sizes = lambda *args: (1, 1) | ||
| 82 | + launchers._env_use_udma = lambda name: False | ||
| 83 | + for name in ('launch_combine_op', 'launch_dispatch_op', 'launch_dispatch_profile_op', | ||
| 84 | + 'launch_planning_op', 'launch_prefetch'): | ||
| 85 | + setattr(launchers, name, lambda *args, **kwargs: None) | ||
| 86 | + native.grad_reduce_targets = lambda *args: calls.append(('grad_reduce', args)) | ||
| 87 | + def launch_grad_reduce_targets(table, slot, plan, *, rank, num_sms): | ||
| 88 | + calls.append(('grad_reduce_grid', min(num_sms, 64))) | ||
| 89 | + native.grad_reduce_targets(table, slot, plan, rank, table.numel()) | ||
| 90 | + launchers.launch_grad_reduce = lambda *args, **kwargs: None | ||
| 91 | + launchers.launch_grad_reduce_targets = launch_grad_reduce_targets | ||
| 92 | + monkeypatch.setitem(sys.modules, launchers.__name__, launchers) | ||
| 93 | + runtime = ModuleType('npu_patch.shmem_runtime') | ||
| 94 | + runtime.ShmemRuntime = SimpleNamespace(is_initialized=lambda: False) | ||
| 95 | + monkeypatch.setitem(sys.modules, runtime.__name__, runtime) | ||
| 96 | + api = importlib.import_module('npu_patch.api') | ||
| 97 | + yield SimpleNamespace(api=api, calls=calls, owners=owners, native=native, runtime=runtime) | ||
| 98 | + for name in ('npu_patch.api', 'npu_patch.planning'): | ||
| 99 | + sys.modules.pop(name, None) | ||
| 100 | + | ||
| 101 | + | ||
| 102 | +def buffer_for(provider, capacity=8): | ||
| 103 | + api = provider.api | ||
| 104 | + ctx = dict(S=capacity, K=2, H=16, R=2, E=4, B=2, rank=0, | ||
| 105 | + _shmem_views_ready=True, _barrier_round=0, | ||
| 106 | + hidden_buf=torch.full((capacity * 2, 16), 9, dtype=torch.bfloat16), | ||
| 107 | + weights_buf=torch.empty(capacity * 2, dtype=torch.int32), | ||
| 108 | + carrier_row_ids=torch.arange(capacity * 2, dtype=torch.int32), | ||
| 109 | + carrier_unused=torch.empty(capacity * 2, dtype=torch.bool), | ||
| 110 | + dispatch_sync_buffer=torch.empty(1, dtype=torch.uint8), | ||
| 111 | + combine_sync_buffer=torch.empty(1, dtype=torch.uint8)) | ||
| 112 | + ctx.update(N=capacity * 2, NvS=capacity * 2, group=None, num_sms=32) | ||
| 113 | + ctx['hidden_buf_local'] = ctx['hidden_buf'][:] | ||
| 114 | + ctx['weights_buf_local'] = ctx['weights_buf'][:] | ||
| 115 | + provider.owners[ctx['hidden_buf'].data_ptr()] = ctx['hidden_buf'] | ||
| 116 | + provider.owners[ctx['weights_buf'].data_ptr()] = ctx['weights_buf'] | ||
| 117 | + def planning(context, topk, tpe, cu, plan, **kwargs): | ||
| 118 | + provider.calls.append(('planning',)) | ||
| 119 | + plan.experts_to_copy.fill_(-1) | ||
| 120 | + cu.fill_(int(context['NvS']) - 1) | ||
| 121 | + def dispatch(context, hidden, route, plan, **kwargs): | ||
| 122 | + provider.calls.append(('dispatch',)) | ||
| 123 | + n = int(context['NvS']) | ||
| 124 | + context['hidden_buf'][:n].copy_(hidden.repeat_interleave(2, 0)) | ||
| 125 | + if route is not None: | ||
| 126 | + context['weights_buf'].view(torch.float32)[:n].copy_(route.flatten()) | ||
| 127 | + def combine(context, output, plan, output_sk=None, **kwargs): | ||
| 128 | + provider.calls.append(('combine',)) | ||
| 129 | + n = int(context['NvS']) | ||
| 130 | + output.copy_(context['hidden_buf'][:n].reshape(context['S'], 2, 16).sum(1)) | ||
| 131 | + if output_sk is not None: | ||
| 132 | + output_sk.copy_(context['weights_buf'].view(torch.float32)[:n].reshape(context['S'], 2)) | ||
| 133 | + ctx['kernels'] = dict(grad_reduce=provider.api.GradReduceOp(), | ||
| 134 | + planning=SimpleNamespace(compute=planning), dispatch=SimpleNamespace(compute=dispatch), | ||
| 135 | + combine=SimpleNamespace(compute=combine)) | ||
| 136 | + buffer = api.Buffer.__new__(api.Buffer) | ||
| 137 | + # This fixture deliberately bypasses __init__; mirror its frozen default. | ||
| 138 | + buffer._async_release_mode = 'serial' | ||
| 139 | + buffer._ctx, buffer._destroyed, buffer._shmem_ready = ctx, False, True | ||
| 140 | + buffer.explicitly_destroy = True | ||
| 141 | + buffer._comm_stream = SimpleNamespace(wait_stream=lambda stream: provider.calls.append(('wait_stream',)), | ||
| 142 | + record_event=lambda: object()) | ||
| 143 | + return buffer | ||
| 144 | + | ||
| 145 | + | ||
| 146 | +@pytest.mark.parametrize('prefetch_completion', ['collective', 'required_owners_v1']) | ||
| 147 | +def test_async_prepare_imports_dependencies_and_registers_banks(provider, monkeypatch, prefetch_completion): | ||
| 148 | + # Import the actual api module, rather than injecting Buffer's globals via | ||
| 149 | + # an AST fixture: a missing production import must fail this setup path. | ||
| 150 | + api = provider.api | ||
| 151 | + capacity = importlib.import_module('npu_patch.async_capacity') | ||
| 152 | + buffer = buffer_for(provider) | ||
| 153 | + buffer._ctx['device'] = 0 | ||
| 154 | + buffer._async_lane = None | ||
| 155 | + monkeypatch.setattr(provider.native, 'acl_shmem_barrier_all_on_stream', | ||
| 156 | + lambda stream: None, raising=False) | ||
| 157 | + if prefetch_completion == 'required_owners_v1': | ||
| 158 | + provider.native.LPLUS_B_OWNER_READY_ABI = 1 | ||
| 159 | + provider.native._lplusb_owner_ready_init = lambda ready: None | ||
| 160 | + provider.native._lplusb_owner_push_ready = lambda *args: None | ||
| 161 | + allocations = [] | ||
| 162 | + | ||
| 163 | + def create(shape, dtype, device): | ||
| 164 | + provider.calls.append(('allocate', tuple(shape))) | ||
| 165 | + tensor = torch.empty(shape, dtype=dtype) | ||
| 166 | + owner = SimpleNamespace(size=64, destroyed=False) | ||
| 167 | + owner.destroy = lambda: setattr(owner, 'destroyed', True) | ||
| 168 | + tensor._vmm_allocation = owner | ||
| 169 | + allocations.append(owner) | ||
| 170 | + return tensor, owner, tensor.data_ptr() | ||
| 171 | + | ||
| 172 | + monkeypatch.setattr(api, 'create_vmm_physical', create) | ||
| 173 | + generation = (0, 'F0') | ||
| 174 | + plan = capacity.derive_capacity([ | ||
| 175 | + capacity.LeaseInterval('Z1', generation, 0, 2, (16, 16), 'bf16')]) | ||
| 176 | + kind = api.OperationKind.DISPATCH | ||
| 177 | + schedule = (('submit', kind, generation), ('release', kind, generation)) | ||
| 178 | + try: | ||
| 179 | + digest = buffer._prepare_async( | ||
| 180 | + plan, topology={'EP': 2}, q0_schedule=schedule, projection_sources={}, | ||
| 181 | + prefetch_completion=prefetch_completion) | ||
| 182 | + assert digest == capacity.manifest_digest(buffer._async_manifest) | ||
| 183 | + assert buffer._async_manifest['granularity'] == 64 | ||
| 184 | + assert ('prefetch_completion' in buffer._async_manifest) == (prefetch_completion == 'required_owners_v1') | ||
| 185 | + assert provider.calls[0] == ('granularity', 0) | ||
| 186 | + assert len(allocations) == 2 # Activation and route-metadata backing. | ||
| 187 | + assert buffer._async_footprint_bytes == 128 | ||
| 188 | + key = api.BankKey('Z1', 0) | ||
| 189 | + assert tuple(buffer._async_sources[key].shape) == (16, 16) | ||
| 190 | + assert tuple(buffer._async_meta_sources[key].shape) == (16,) | ||
| 191 | + assert buffer._async_lane is not None | ||
| 192 | + assert not provider.runtime.ShmemRuntime.is_initialized() | ||
| 193 | + finally: | ||
| 194 | + for owner in allocations: | ||
| 195 | + owner.destroy() | ||
| 196 | + buffer._destroyed = True | ||
| 197 | + | ||
| 198 | + | ||
| 199 | +@pytest.mark.parametrize('tokens', [3, 8]) | ||
| 200 | +@pytest.mark.parametrize('zero_copy,router_zero_copy', [(False, False), (False, True), (True, False), (True, True)]) | ||
| 201 | +@pytest.mark.parametrize('async_finish', [False, True]) | ||
| 202 | +def test_dispatch_keeps_independent_zero_copy_flags_and_positive_prefix(provider, tokens, zero_copy, router_zero_copy, async_finish): | ||
| 203 | + buffer = buffer_for(provider) | ||
| 204 | + hidden = torch.arange(tokens * 16).reshape(tokens, 16).to(torch.bfloat16) | ||
| 205 | + route = torch.full((tokens, 2), .5) | ||
| 206 | + before = buffer._ctx['hidden_buf'][tokens * 2:].clone() | ||
| 207 | + result = buffer.dispatch(hidden, route, torch.zeros(tokens, 2, dtype=torch.int32), | ||
| 208 | + torch.zeros(4, dtype=torch.int32), zero_copy=zero_copy, | ||
| 209 | + router_weights_zero_copy=router_zero_copy, async_finish=async_finish) | ||
| 210 | + z, probs, cu, plan = result[:4] | ||
| 211 | + expected = hidden.repeat_interleave(2, 0) | ||
| 212 | + expected[-1].zero_() # transport double marks one unused carrier row | ||
| 213 | + torch.testing.assert_close(z, expected, atol=0, rtol=0) | ||
| 214 | + assert (z.data_ptr() == buffer._ctx['hidden_buf'].data_ptr()) == zero_copy | ||
| 215 | + assert (probs.data_ptr() == buffer._ctx['weights_buf'].data_ptr()) == router_zero_copy | ||
| 216 | + if zero_copy: | ||
| 217 | + assert z._base is None | ||
| 218 | + assert plan.cu_seqlens is cu | ||
| 219 | + assert buffer._ctx['S'] == 8 and buffer._ctx['_barrier_round'] == 1 | ||
| 220 | + torch.testing.assert_close(buffer._ctx['hidden_buf'][tokens * 2:], before) | ||
| 221 | + clone = plan.clone() | ||
| 222 | + assert clone.cu_seqlens.data_ptr() != cu.data_ptr() | ||
| 223 | + output, returned_route, event = buffer.combine( | ||
| 224 | + plan, z, probs, zero_copy=zero_copy, router_weights_zero_copy=router_zero_copy, | ||
| 225 | + async_finish=async_finish) | ||
| 226 | + torch.testing.assert_close(output, expected.reshape(tokens, 2, 16).sum(1)) | ||
| 227 | + assert returned_route.shape == route.shape | ||
| 228 | + assert buffer._ctx['_barrier_round'] == 2 | ||
| 229 | + # Destruction is exercised separately with explicit owners/native doubles. | ||
| 230 | + buffer._destroyed = True | ||
| 231 | + | ||
| 232 | + | ||
| 233 | +@pytest.mark.parametrize('tokens', [3, 8]) | ||
| 234 | +def test_custom_autograd_outputs_allow_in_place_expert_writes_without_owning_carrier_graph(provider, tokens): | ||
| 235 | + buffer = buffer_for(provider) | ||
| 236 | + class Dispatch(torch.autograd.Function): | ||
| 237 | + @staticmethod | ||
| 238 | + def forward(ctx, hidden, route): | ||
| 239 | + z, probs, _, _ = buffer.dispatch( | ||
| 240 | + hidden, route, torch.zeros(tokens, 2, dtype=torch.int32), | ||
| 241 | + torch.zeros(4, dtype=torch.int32), zero_copy=True, router_weights_zero_copy=True) | ||
| 242 | + return z, probs | ||
| 243 | + @staticmethod | ||
| 244 | + def backward(ctx, dz, dp): | ||
| 245 | + return None, None | ||
| 246 | + hidden = torch.ones(tokens, 16, dtype=torch.bfloat16, requires_grad=True) | ||
| 247 | + route = torch.full((tokens, 2), .5, requires_grad=True) | ||
| 248 | + z, probs = Dispatch.apply(hidden, route) | ||
| 249 | + z.mul_(2) # FC2 writes into this multi-output Function's carrier in production | ||
| 250 | + assert z.grad_fn is not None | ||
| 251 | + assert buffer._ctx['hidden_buf_local'].grad_fn is None | ||
| 252 | + assert buffer._ctx['weights_buf_local'].grad_fn is None | ||
| 253 | + assert probs.data_ptr() == buffer._ctx['weights_buf_local'].data_ptr() | ||
| 254 | + buffer._destroyed = True | ||
| 255 | + | ||
| 256 | + | ||
| 257 | +@pytest.mark.parametrize('tokens', [0, -1, 9]) | ||
| 258 | +def test_invalid_logical_prefix_is_rejected_before_transport(provider, tokens): | ||
| 259 | + buffer = buffer_for(provider) | ||
| 260 | + with pytest.raises(ValueError, match='logical token count'): | ||
| 261 | + provider.api._logical_context(buffer._ctx, tokens) | ||
| 262 | + if tokens == 0: | ||
| 263 | + with pytest.raises(ValueError, match='logical token count'): | ||
| 264 | + buffer.dispatch(torch.empty(0, 16, dtype=torch.bfloat16), None, | ||
| 265 | + torch.empty(0, 2, dtype=torch.int32), torch.zeros(4, dtype=torch.int32)) | ||
| 266 | + assert provider.calls == [] | ||
| 267 | + buffer._destroyed = True | ||
| 268 | + | ||
| 269 | + | ||
| 270 | +def plan_for(provider, buffer): | ||
| 271 | + ctx = provider.api._logical_context(buffer._ctx, 3) | ||
| 272 | + plan, cu = provider.api.allocate_planning_outputs(ctx) | ||
| 273 | + plan.experts_to_copy.fill_(-1) | ||
| 274 | + return plan | ||
| 275 | + | ||
| 276 | + | ||
| 277 | +def test_sync_projection_uses_canonical_pointer_metadata_and_rejects_aliases(provider): | ||
| 278 | + buffer = buffer_for(provider) | ||
| 279 | + plan = plan_for(provider, buffer) | ||
| 280 | + sources = tuple(torch.randn(4, 8).to(torch.bfloat16) for _ in range(2)) | ||
| 281 | + saved = tuple(value.clone() for value in sources) | ||
| 282 | + slots = torch.zeros(2, 4, 8, dtype=torch.bfloat16) | ||
| 283 | + buffer._prefetch_expert_weights(plan, sources, slots) | ||
| 284 | + kind, args = provider.calls[-1] | ||
| 285 | + assert kind == 'push' and args[0].dtype == torch.int64 | ||
| 286 | + assert args[0].tolist() == [value.data_ptr() for value in sources] | ||
| 287 | + assert args[1] is slots and args[2] is plan.experts_to_copy | ||
| 288 | + for actual, expected in zip(sources, saved): | ||
| 289 | + torch.testing.assert_close(actual, expected, atol=0, rtol=0) | ||
| 290 | + targets = tuple(torch.zeros(4, 8) for _ in range(2)) | ||
| 291 | + grad_slots = torch.zeros(2, 4, 8) | ||
| 292 | + buffer._reduce_expert_grads(plan, targets, grad_slots) | ||
| 293 | + assert provider.calls[-1][0] == 'reduce' | ||
| 294 | + count = len(provider.calls) | ||
| 295 | + for bad_targets in ((targets[0], targets[0]), tuple(grad_slots.unbind())): | ||
| 296 | + with pytest.raises(ValueError, match='overlap|alias'): | ||
| 297 | + buffer._reduce_expert_grads(plan, bad_targets, grad_slots) | ||
| 298 | + with pytest.raises(TypeError, match='contiguous'): | ||
| 299 | + buffer._prefetch_expert_weights(plan, tuple(value.float() for value in sources), slots) | ||
| 300 | + assert len(provider.calls) == count | ||
| 301 | + buffer._destroyed = True | ||
| 302 | + | ||
| 303 | + | ||
| 304 | +def test_foreign_plan_layout_and_live_heap_teardown_fail_closed(provider): | ||
| 305 | + buffer = buffer_for(provider) | ||
| 306 | + plan = plan_for(provider, buffer) | ||
| 307 | + foreign = provider.api.MoonEPCommPlan(**{**{field: getattr(plan, field) for field in plan.__dataclass_fields__}, 'K': 1}) | ||
| 308 | + with pytest.raises(RuntimeError, match='token/top-k'): | ||
| 309 | + buffer._prefetch_expert_weights(foreign, (torch.zeros(4, 8, dtype=torch.bfloat16),) * 2, | ||
| 310 | + torch.zeros(2, 4, 8, dtype=torch.bfloat16)) | ||
| 311 | + provider.runtime.ShmemRuntime.is_initialized = lambda: True | ||
| 312 | + with pytest.raises(RuntimeError, match='finalize SHMEM'): | ||
| 313 | + buffer.destroy() | ||
| 314 | + assert not buffer.destroyed and buffer._ctx is not None and provider.calls == [] | ||
| 315 | + buffer._destroyed = True | ||
| 316 | + | ||
| 317 | + | ||
| 318 | +def test_projection_rejects_stale_native_abi_and_non_lplusb_slot_layout(provider): | ||
| 319 | + buffer = buffer_for(provider) | ||
| 320 | + plan = plan_for(provider, buffer) | ||
| 321 | + refs = tuple(torch.zeros(4, 8, dtype=torch.bfloat16) for _ in range(2)) | ||
| 322 | + slots = torch.zeros(2, 4, 8, dtype=torch.bfloat16) | ||
| 323 | + provider.native.LPLUS_B_BUFFER_SYNC_ABI = 1 | ||
| 324 | + with pytest.raises(RuntimeError, match='native ABI v2'): | ||
| 325 | + buffer._prefetch_expert_weights(plan, refs, slots) | ||
| 326 | + provider.native.LPLUS_B_BUFFER_SYNC_ABI = 2 | ||
| 327 | + buffer._ctx['E'] = 6 | ||
| 328 | + # Distinct source/slot counts are legal for the formula probe, but a plan | ||
| 329 | + # from another E/R layout remains invalid before any native submission. | ||
| 330 | + with pytest.raises(RuntimeError, match='another Buffer layout'): | ||
| 331 | + buffer._prefetch_expert_weights(plan, refs, slots) | ||
| 332 | + assert provider.calls == [] | ||
| 333 | + buffer._destroyed = True | ||
| 334 | + | ||
| 335 | + | ||
| 336 | +@pytest.mark.parametrize('tokens', [3, 8]) | ||
| 337 | +def test_dispatch_backward_route_gradient_uses_existing_metadata_carrier(provider, tokens): | ||
| 338 | + buffer = buffer_for(provider) | ||
| 339 | + carrier = buffer._ctx['weights_buf_local'].view(torch.float32) | ||
| 340 | + carrier.fill_(19) | ||
| 341 | + gradient = torch.arange(tokens * 2, dtype=torch.float32) | ||
| 342 | + staged = buffer._stage_route_weights_for_combine(gradient) | ||
| 343 | + assert staged.data_ptr() == carrier.data_ptr() | ||
| 344 | + torch.testing.assert_close(staged, gradient, atol=0, rtol=0) | ||
| 345 | + assert torch.all(carrier[tokens * 2:] == 19) | ||
| 346 | + for value, exception in [(gradient.to(torch.bfloat16), TypeError), | ||
| 347 | + (torch.zeros(2, 3), ValueError), (torch.zeros(17), ValueError), | ||
| 348 | + (torch.zeros(12)[::2], ValueError)]: | ||
| 349 | + with pytest.raises(exception): | ||
| 350 | + buffer._stage_route_weights_for_combine(value) | ||
| 351 | + assert buffer._ctx['hidden_buf_local'].grad_fn is None | ||
| 352 | + buffer._destroyed = True | ||
| @@ -0,0 +1,166 @@ | |||
| 1 | +"""Production source ownership and engine contracts, without importing NPU libs.""" | ||
| 2 | +import ast | ||
| 3 | +import gc | ||
| 4 | +import hashlib | ||
| 5 | +import json | ||
| 6 | +from pathlib import Path | ||
| 7 | +from types import SimpleNamespace | ||
| 8 | + | ||
| 9 | +import pytest | ||
| 10 | +import torch | ||
| 11 | + | ||
| 12 | +ROOT = Path(__file__).resolve().parents[1] | ||
| 13 | + | ||
| 14 | + | ||
| 15 | +def production_methods(): | ||
| 16 | + source = ROOT / 'npu_patch/api.py' | ||
| 17 | + tree = ast.parse(source.read_text()) | ||
| 18 | + cls = next(n for n in tree.body if isinstance(n, ast.ClassDef) and n.name == 'Buffer') | ||
| 19 | + names = {'_prefetch_expert_weights', '_validate_lplusb_refs', '_lplusb_pointer_table', | ||
| 20 | + '_urma_prefetch_capability', '_register_async_projection_refs', | ||
| 21 | + '_async_projection_pointer_table'} | ||
| 22 | + nodes = [n for n in cls.body if isinstance(n, ast.FunctionDef) and n.name in names] | ||
| 23 | + for n in nodes: n.decorator_list = [] | ||
| 24 | + ns = dict(torch=torch) | ||
| 25 | + exec(compile(ast.fix_missing_locations(ast.Module(body=nodes, type_ignores=[])), str(source), 'exec'), ns) | ||
| 26 | + ns['Buffer'] = SimpleNamespace(**{name: ns[name] for name in names}) | ||
| 27 | + return ns | ||
| 28 | + | ||
| 29 | + | ||
| 30 | +def harness(engine='mte'): | ||
| 31 | + ns = production_methods() | ||
| 32 | + events, submissions = [], [] | ||
| 33 | + class Event: | ||
| 34 | + done = False | ||
| 35 | + def record(self, stream): pass | ||
| 36 | + def query(self): return self.done | ||
| 37 | + def event(): | ||
| 38 | + e = Event(); events.append(e); return e | ||
| 39 | + def submit(*args): submissions.append(args) | ||
| 40 | + native = SimpleNamespace(LPLUS_B_BUFFER_SYNC_ABI=2, PREFETCH_PUSH_POINTER_ABI=1, | ||
| 41 | + _lplusb_owner_push=submit, _prefetch_push_pointers=submit, | ||
| 42 | + _prefetch_push_available=lambda: True) | ||
| 43 | + ns['_C'] = native | ||
| 44 | + ns['torch_npu'] = SimpleNamespace(npu=SimpleNamespace(Event=event, current_stream=lambda: object())) | ||
| 45 | + # Source-only execution uses real CPU storage; replace only the runtime import. | ||
| 46 | + import sys | ||
| 47 | + runtime = SimpleNamespace(ShmemRuntime=SimpleNamespace(is_initialized=lambda: True, _udma_enabled=True)) | ||
| 48 | + ctx = dict(rank=0, E=4, R=2, _prefetch_use_udma=engine == 'urma') | ||
| 49 | + buf = SimpleNamespace(_prefetch_poisoned=False, _prefetch_leases=[], | ||
| 50 | + _require_ctx=lambda: ctx, _ensure_shmem_views=lambda: None, | ||
| 51 | + _validate_lplusb_plan=lambda *a, **kw: object(), | ||
| 52 | + _lplusb_pointer_table=ns['_lplusb_pointer_table']) | ||
| 53 | + return ns, buf, events, submissions, runtime | ||
| 54 | + | ||
| 55 | + | ||
| 56 | +def test_source_alias_survives_parameter_rebinding_until_completion(): | ||
| 57 | + ns, buf, events, calls, _ = harness() | ||
| 58 | + source = torch.nn.Parameter(torch.ones(3, 5, dtype=torch.bfloat16), requires_grad=False) | ||
| 59 | + other = torch.nn.Parameter(torch.ones_like(source), requires_grad=False) | ||
| 60 | + token = source.untyped_storage()._weak_ref() | ||
| 61 | + original = source.data_ptr() | ||
| 62 | + try: | ||
| 63 | + ns['_prefetch_expert_weights'](buf, object(), (source, other), torch.empty(2,3,5,dtype=source.dtype)) | ||
| 64 | + assert buf._prefetch_leases[0][5][0].data_ptr() == original | ||
| 65 | + source.data = torch.zeros_like(source) | ||
| 66 | + gc.collect() | ||
| 67 | + assert not torch.UntypedStorage._expired(token) | ||
| 68 | + events[0].done = True | ||
| 69 | + ns['_prefetch_expert_weights'](buf, object(), (source, other), torch.empty(2,3,5,dtype=source.dtype)) | ||
| 70 | + gc.collect() | ||
| 71 | + assert torch.UntypedStorage._expired(token) | ||
| 72 | + finally: | ||
| 73 | + torch.UntypedStorage._free_weak_ref(token) | ||
| 74 | + | ||
| 75 | + | ||
| 76 | +def test_submit_and_query_failure_poison_and_retain_original_lease(): | ||
| 77 | + ns, buf, events, calls, _ = harness() | ||
| 78 | + refs = tuple(torch.empty(3,5,dtype=torch.bfloat16) for _ in range(2)) | ||
| 79 | + slots = torch.empty(2,3,5,dtype=torch.bfloat16) | ||
| 80 | + ns['_prefetch_expert_weights'](buf, object(), refs, slots) | ||
| 81 | + original = buf._prefetch_leases | ||
| 82 | + def fail(): raise RuntimeError('completion query failed') | ||
| 83 | + events[0].query = fail | ||
| 84 | + with pytest.raises(RuntimeError, match='query failed'): | ||
| 85 | + ns['_prefetch_expert_weights'](buf, object(), refs, slots) | ||
| 86 | + assert buf._prefetch_poisoned and buf._prefetch_leases is original | ||
| 87 | + assert len(calls) == 1 | ||
| 88 | + | ||
| 89 | + | ||
| 90 | +def test_formula_metadata_accepts_one_local_source_and_seven_slots(): | ||
| 91 | + ns, *_ = harness() | ||
| 92 | + source = torch.empty(3,5,dtype=torch.bfloat16) | ||
| 93 | + slots = torch.empty(7,3,5,dtype=source.dtype) | ||
| 94 | + table, ranges = ns['_lplusb_pointer_table']([source], slots, dtype=source.dtype, | ||
| 95 | + operation='prefetch', expected_refs=1) | ||
| 96 | + assert table.tolist() == [source.data_ptr()] | ||
| 97 | + with pytest.raises(ValueError, match='exactly 7'): | ||
| 98 | + ns['_lplusb_pointer_table']([source], slots, dtype=source.dtype, operation='reduce') | ||
| 99 | + | ||
| 100 | + | ||
| 101 | +def test_async_pointer_registration_distinguishes_local_experts_from_slots(): | ||
| 102 | + ns, *_ = harness() | ||
| 103 | + ns['BankKey'] = lambda role, index: (role, index) | ||
| 104 | + ns['torch_npu'] = SimpleNamespace(npu=SimpleNamespace( | ||
| 105 | + current_stream=lambda **kwargs: SimpleNamespace(record_event=lambda: object()))) | ||
| 106 | + source = torch.ones(3, 5, dtype=torch.bfloat16) | ||
| 107 | + slots = torch.empty(7, 3, 5, dtype=source.dtype) | ||
| 108 | + buf = SimpleNamespace(_async_lane=object(), _async_views_ready=False, | ||
| 109 | + _async_sources={('fc1_weight',0):slots, ('fc1_grad',0):slots.float()}, | ||
| 110 | + _async_pointer_tables={}, _require_ctx=lambda: dict(E=8,R=8), | ||
| 111 | + _validate_lplusb_refs=ns['_validate_lplusb_refs']) | ||
| 112 | + ns['_register_async_projection_refs'](buf, [source], role='fc1_weight') | ||
| 113 | + table, _ = ns['_async_projection_pointer_table'](buf, [source.detach()], slots, | ||
| 114 | + role='fc1_weight', dtype=source.dtype, operation='prefetch') | ||
| 115 | + assert table.tolist() == [source.data_ptr()] | ||
| 116 | + with pytest.raises(ValueError, match='exactly 7'): | ||
| 117 | + ns['_register_async_projection_refs'](buf, [source.float()], role='fc1_grad') | ||
| 118 | + | ||
| 119 | + | ||
| 120 | +def test_pointer_order_handles_reverse_and_gapped_backing_without_copy(): | ||
| 121 | + ns, *_ = harness() | ||
| 122 | + backing = torch.empty(3,2,3,5,dtype=torch.bfloat16) | ||
| 123 | + refs = [backing[2,0], backing[1,0], backing[0,0]] | ||
| 124 | + table, _ = ns['_lplusb_pointer_table'](refs, torch.empty(3,3,5,dtype=backing.dtype), | ||
| 125 | + dtype=backing.dtype, operation='prefetch') | ||
| 126 | + assert table.tolist() == [ref.data_ptr() for ref in refs] | ||
| 127 | + | ||
| 128 | + | ||
| 129 | +def test_shared_core_identity_and_required_owners_rejection_before_allocation(): | ||
| 130 | + core = ROOT / 'npu_patch/native/include/ascend_moonep/kernels/urma_push_core.h' | ||
| 131 | + caps = json.loads((ROOT/'npu_patch/_integration_capabilities.json').read_text()) | ||
| 132 | + assert hashlib.sha256(core.read_bytes()).hexdigest() == caps['urma_push']['shared_core_sha256'] | ||
| 133 | + source = ROOT/'npu_patch/api.py' | ||
| 134 | + tree = ast.parse(source.read_text()) | ||
| 135 | + cls = next(n for n in tree.body if isinstance(n, ast.ClassDef) and n.name == 'Buffer') | ||
| 136 | + method = next(n for n in cls.body if isinstance(n, ast.FunctionDef) and n.name == '_prepare_async') | ||
| 137 | + ns = dict(ShmemRuntime=SimpleNamespace(is_initialized=lambda: False)) | ||
| 138 | + exec(compile(ast.fix_missing_locations(ast.Module(body=[method],type_ignores=[])),str(source),'exec'),ns) | ||
| 139 | + def allocation_reached(): raise AssertionError('admission must reject before capability/allocation work') | ||
| 140 | + buf = SimpleNamespace(_require_ctx=lambda: {'_prefetch_use_udma': True}, | ||
| 141 | + _async_lane=None, _async_capability=allocation_reached) | ||
| 142 | + with pytest.raises(RuntimeError, match='collective completion only'): | ||
| 143 | + ns['_prepare_async'](buf, None, topology={}, q0_schedule=(), projection_sources={}, | ||
| 144 | + prefetch_completion='required_owners_v1') | ||
| 145 | + kernel = (ROOT/'npu_patch/native/kernels/prefetch_pointer_push_udma.cpp').read_text() | ||
| 146 | + assert 'Run<true>' in kernel and 'MOONEP_URMA_PUSH_ENABLED' not in kernel | ||
| 147 | + | ||
| 148 | + | ||
| 149 | +def test_unbuilt_urma_capability_fails_closed(): | ||
| 150 | + ns, *_ = harness() | ||
| 151 | + ns['_C']._prefetch_push_available = lambda: False | ||
| 152 | + with pytest.raises(RuntimeError, match='no MTE fallback'): | ||
| 153 | + ns['_urma_prefetch_capability']() | ||
| 154 | + | ||
| 155 | + | ||
| 156 | +def test_pending_completion_defers_destroy_without_poisoning_normal_work(): | ||
| 157 | + source = ROOT/'npu_patch/api.py' | ||
| 158 | + tree = ast.parse(source.read_text()) | ||
| 159 | + method = next(n for n in ast.walk(tree) if isinstance(n, ast.FunctionDef) and n.name == 'destroy') | ||
| 160 | + ns = {} | ||
| 161 | + exec(compile(ast.fix_missing_locations(ast.Module(body=[method],type_ignores=[])),str(source),'exec'),ns) | ||
| 162 | + lease = [SimpleNamespace(query=lambda: False), object()] | ||
| 163 | + buf = SimpleNamespace(_destroyed=False, _prefetch_poisoned=False, _prefetch_leases=[lease]) | ||
| 164 | + with pytest.raises(RuntimeError, match='outstanding'): | ||
| 165 | + ns['destroy'](buf) | ||
| 166 | + assert not buf._prefetch_poisoned and buf._prefetch_leases[0] is lease | ||