diff --git a/hyper_parallel/distributed/expert_parallel/moonep/checkpoint.py b/hyper_parallel/distributed/expert_parallel/moonep/checkpoint.py index ed72acea5..ab16f6c76 100644 --- a/hyper_parallel/distributed/expert_parallel/moonep/checkpoint.py +++ b/hyper_parallel/distributed/expert_parallel/moonep/checkpoint.py @@ -27,12 +27,15 @@ from hyper_parallel.core.activation_memory.recompute_state import get_recompute_state +SUPPORTS_MULTI_EXPERT_CHECKPOINT = True + + @dataclass class _Tape: """一次checkpoint调用的小型记录;例如原F7和R7共享同一K7和router ID。""" - execution: tuple[Any, Any] | None = None - routes: dict = field(default_factory=dict) + executions: list[tuple[Any, Any]] = field(default_factory=list) + routes: list[tuple[Any, torch.Tensor]] = field(default_factory=list) identity: Any = None @@ -42,29 +45,36 @@ class _Scope: tape: _Tape replay: bool - execution_consumed: bool = False + execution_index: int = 0 + route_index: int = 0 _SCOPE: ContextVar[_Scope | None] = ContextVar("moonep_checkpoint_scope", default=None) def bind_execution(executor: Any, create_key: Any) -> Any: - """原始前向分配key,重放取回旧key;例如两次layer7调用仍指向同一次原图。""" + """Allocate one key per original call and reuse its key at the same replay position.""" scope = _SCOPE.get() if scope is None: return create_key() if not scope.replay: - if scope.tape.execution is not None: - raise ValueError("MoonEP重计算键映射要求一个checkpoint区域仅执行一次专家模块") key = create_key() - scope.tape.execution = executor, key + scope.tape.executions.append((executor, key)) return key - if scope.tape.execution is None or scope.execution_consumed: + calls = scope.tape.executions + index = scope.execution_index + if index >= len(calls): raise RuntimeError("重放出现原始前向不存在的专家调用") - expected, key = scope.tape.execution - scope.execution_consumed = True + expected, key = calls[index] if expected is not executor: raise RuntimeError("重计算专家调用顺序发生变化") + if index: + # The preceding expert has finished reading its replicas. Keeping every + # replay lease until backward would exhaust the bounded weight slots. + previous, previous_key = calls[index - 1] + previous.runtime.release_replay_lease(previous_key) + scope.execution_index += 1 + executor.runtime.statistics["recomputations"] += 1 return key @@ -74,16 +84,29 @@ def is_replaying() -> bool: return scope is not None and scope.replay +def is_replay_demand(key: Any) -> bool: + """Whether the replayed expert has reached its actual parameter restoration hook.""" + scope = _SCOPE.get() + return (scope is not None and scope.replay and scope.execution_index > 0 + and scope.tape.executions[scope.execution_index - 1][1] is key) + + def checkpoint_route_ids(router: Any, probabilities: torch.Tensor, top_k: int, *, sorted: bool = True) -> torch.Tensor: """只复用离散top-k ID;例如R7仍从新logits可微gather分数以保留router梯度。""" scope = _SCOPE.get() if scope is not None and scope.replay: - return scope.tape.routes[id(router)] + if scope.route_index >= len(scope.tape.routes): + raise RuntimeError("MoonEP replay produced an extra routing call") + expected, ids = scope.tape.routes[scope.route_index] + if expected is not router: + raise RuntimeError("MoonEP router order changed during replay") + scope.route_index += 1 + return ids with torch.no_grad(): ids = probabilities.topk(top_k, dim=-1, sorted=sorted).indices if scope is not None: - scope.tape.routes[id(router)] = ids + scope.tape.routes.append((router, ids)) return ids @@ -109,8 +132,8 @@ def _phase(block: torch.nn.Module, tape: _Tape, replay: bool) -> Iterator[None]: if state is None or state.is_recomputing != replay: raise RuntimeError("MoonEP要求Hyper eager非重入checkpoint入口") if replay: - if tape.identity is not state.invocation_id or tape.execution is None: - raise RuntimeError("MoonEP重放必须关联原始单专家区域调用") + if tape.identity is not state.invocation_id or not tape.executions: + raise RuntimeError("MoonEP重放必须关联原始专家区域调用") else: tape.identity = state.invocation_id scope = _Scope(tape, replay) @@ -122,14 +145,21 @@ def _phase(block: torch.nn.Module, tape: _Tape, replay: bool) -> Iterator[None]: if getattr(module, "hsdp_scheduler", None) is not None} for scheduler in schedulers.values(): stack.enter_context(_suspend_forward_prefetch(scheduler)) - executor, key = tape.execution - prepare_resources = getattr(executor.runtime, "prepare_backward_resources", None) - if prepare_resources is not None: - prepare_resources(key) - executor.runtime.statistics["recomputations"] += 1 + # The last original call for a runtime is its first real + # backward demand, even though replay runs in forward order. + restored = set() + for executor, key in reversed(tape.executions): + runtime = executor.runtime + if id(runtime) not in restored: + prepare_resources = getattr(runtime, "prepare_backward_resources", None) + if prepare_resources is not None: + prepare_resources(key) + restored.add(id(runtime)) yield - if replay and not scope.execution_consumed: - raise RuntimeError("重放没有执行原始专家调用") + if replay and scope.execution_index != len(tape.executions): + raise RuntimeError("重放没有执行全部原始专家调用") + if replay and scope.route_index != len(tape.routes): + raise RuntimeError("MoonEP replay did not consume all original routing calls") finally: _SCOPE.reset(token) @@ -145,10 +175,10 @@ def context_factory() -> tuple[Any, Any]: def wrap_moonep_checkpoint(block: torch.nn.Module) -> torch.nn.Module: - """为单MoE区域安装Hyper非重入重计算,应在FSDP包装前调用。 + """为MoE区域安装Hyper非重入重计算,应在FSDP包装前调用。 Args: - block: 包含一次专家执行的decoder区域,不包含checkpoint参数输入。 + block: 包含一次或多次专家执行的decoder区域,不包含checkpoint参数输入。 Returns: checkpoint包装后的同语义模块;early_stop关闭以保证collective完整重放。 diff --git a/hyper_parallel/distributed/expert_parallel/moonep/fsdp_hooks.py b/hyper_parallel/distributed/expert_parallel/moonep/fsdp_hooks.py index 1c79ccee8..b729d8d99 100644 --- a/hyper_parallel/distributed/expert_parallel/moonep/fsdp_hooks.py +++ b/hyper_parallel/distributed/expert_parallel/moonep/fsdp_hooks.py @@ -57,10 +57,14 @@ def _prefetch(self) -> None: if key in self.runtime.weight_leases: return self.executor.prepare_forward(key, *values) + elif (self.runtime.trace and self.runtime.trace[-1] in self.runtime.replay_released + and self.runtime.trace[-1].layer == self.executor.layer): + # Real backward has restored this expert after its replay lease was released. + key = self.runtime.trace[-1] else: key = self.runtime.prefetch_key(self.executor) if (key is None or key in self.runtime.weight_leases - or key in self.runtime.pending_weight_preparations): + or (pending is None and key in self.runtime.pending_weight_preparations)): return self.runtime.prepare_restored_weights(key) statistic = "fsdp_ep_demand_preparations" if pending is not None else "fsdp_ep_prefetches" diff --git a/hyper_parallel/distributed/expert_parallel/moonep/lifecycle.py b/hyper_parallel/distributed/expert_parallel/moonep/lifecycle.py index 0c297aa62..3bba1811f 100644 --- a/hyper_parallel/distributed/expert_parallel/moonep/lifecycle.py +++ b/hyper_parallel/distributed/expert_parallel/moonep/lifecycle.py @@ -21,7 +21,7 @@ import torch -from hyper_parallel.distributed.expert_parallel.moonep.checkpoint import bind_execution +from hyper_parallel.distributed.expert_parallel.moonep.checkpoint import bind_execution, is_replay_demand @dataclass(frozen=True) @@ -51,6 +51,7 @@ def __init__(self, executors: list) -> None: self.weight_leases: dict[ExecutionKey, Any] = {} self.forward_inputs: dict[int, tuple[ExecutionKey, tuple]] = {} self.fsdp_layers: set[int] = set() + self.replay_released: set[ExecutionKey] = set() self.pending_weight_preparations: dict[ExecutionKey, Any] = {} self.backward_weight_ready: Optional[tuple[ExecutionKey, Any]] = None self.statistics = Counter() @@ -70,6 +71,11 @@ def prepare(self, key: ExecutionKey, *, ready_events: tuple = ()) -> Any: """ raise NotImplementedError + @abstractmethod + def release(self, key: ExecutionKey) -> None: + """Return this backend's consumed weight lease after its final reader.""" + raise NotImplementedError + @staticmethod def _record_weight_dependency(device: torch.device) -> Any: """Capture existing device work without synchronizing the host.""" @@ -81,7 +87,7 @@ def _record_weight_dependency(device: torch.device) -> Any: return event def prepare_restored_weights(self, key: ExecutionKey) -> None: - """Remember restored homes and prepare only the next execution. + """Prepare a current replay demand or queue a home for ordered backward prefetch. Args: key: Original or replayed invocation restored by the existing FSDP hook. @@ -94,17 +100,18 @@ def prepare_restored_weights(self, key: ExecutionKey) -> None: return if key.version != self.version or key not in self.executions or key not in self.trace: raise RuntimeError("restored MoonEP weights require a live execution at the current version") - if key not in self.pending_weight_preparations: + demand = is_replay_demand(key) + if demand or key not in self.pending_weight_preparations: executor, _ = self.executions[key] device = executor.read_weights()[0].device self.pending_weight_preparations[key] = self._record_weight_dependency(device) - self._prepare_next_weights() + self._prepare_next_weights(key if demand else None) - def _prepare_next_weights(self) -> None: + def _prepare_next_weights(self, replay_key: Optional[ExecutionKey] = None) -> None: """Submit at a deterministic hook or EP exit, never by event polling.""" if not self.trace: return - key = self.trace[-1] + key = self.trace[-1] if replay_key is None else replay_key if key not in self.pending_weight_preparations or key in self.weight_leases: return events = [self.pending_weight_preparations[key]] @@ -142,6 +149,12 @@ def prefetch_after_backward(self, key: ExecutionKey, device: torch.device) -> No self.backward_weight_ready = self.trace[-1], self._record_weight_dependency(device) self._prepare_next_weights() + def release_replay_lease(self, key: ExecutionKey) -> None: + """Return an intermediate replay lease after the expert's final forward reader.""" + self.release(key) + if key.layer in self.fsdp_layers: + self.replay_released.add(key) + def new_key(self, executor: Any) -> ExecutionKey: """Allocate an original invocation; checkpoint replay reuses this key. @@ -168,6 +181,7 @@ def complete(self, key: ExecutionKey) -> tuple[Any, Any]: if not self.trace or self.trace[-1] != key: raise RuntimeError("MoonEP backward completion must follow reverse original-forward order") self.trace.pop() + self.replay_released.discard(key) return self.executions.pop(key) def forward_key(self, executor: Any, hidden: Any, ids: Any, scores: Any, diff --git a/tests/torch/expert_parallel/_test_moonep_multi_checkpoint.py b/tests/torch/expert_parallel/_test_moonep_multi_checkpoint.py new file mode 100644 index 000000000..849b7ef2b --- /dev/null +++ b/tests/torch/expert_parallel/_test_moonep_multi_checkpoint.py @@ -0,0 +1,133 @@ +# Copyright 2026 Huawei Technologies Co., Ltd +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================ +"""Compare a two-expert checkpoint with separate regions on four EP2 x FSDP2 ranks.""" + +import argparse +import os +from pathlib import Path + +import torch +import torch.distributed as dist +import torch_npu # noqa: F401 + +from hyper_parallel import fully_shard, init_device_mesh +from hyper_parallel.core.dtensor.placement_types import Shard +from hyper_parallel.core.fully_shard.utils import MixedPrecisionPolicy +from hyper_parallel.core.multicore.modules.routed_experts import transport +from hyper_parallel.distributed.expert_parallel.moonep import configure_moonep, wrap_moonep_checkpoint +from hyper_parallel.distributed.expert_parallel.moonep.runtime import local_tensor +from tests.torch.expert_parallel._test_moonep_fsdp_accumulation import Block, Experts + + +class TwoStreams(torch.nn.Module): + """Exercise sibling expert branches whose gradients meet at a shared input.""" + + def __init__(self, branches: list) -> None: + super().__init__() + self.branches = torch.nn.ModuleList(branches) + + def forward(self, x: torch.Tensor, ids: torch.Tensor, scores: torch.Tensor) -> torch.Tensor: + u = self.branches[0](x.sin(), ids[0], scores[0]) + g = self.branches[1](x.cos(), ids[1], scores[1]) + return u + g + + +def run(args: argparse.Namespace) -> None: + """Run separate torchruns for split and whole and compare all local gradients.""" + rank = int(os.environ["RANK"]) + torch.npu.set_device(int(os.environ["LOCAL_RANK"])) + torch.npu.config.allow_internal_format = False + device = torch.device("npu", torch.npu.current_device()) + dist.init_process_group("hccl") + mesh = init_device_mesh("npu", (2, 2), mesh_dim_names=("efs", "ep")) + ep, efs = mesh["ep"], mesh["efs"] + if args.native_dir: + transport.get_routed_experts_paths = lambda: tuple( + args.native_dir / f"libhyper_parallel_routed_experts_{name}.so" for name in ("kernels", "torch")) + generator = torch.Generator().manual_seed(1729) + experts, branches = [], [] + for _ in range(2): + gate = torch.randn(6, 256, 128, generator=generator) * 0.025 + down = torch.randn(6, 128, 128, generator=generator) * 0.025 + expert = Experts(gate.chunk(2)[ep.get_local_rank()].to(device), + down.chunk(2)[ep.get_local_rank()].to(device), ep, args.backend, 2) + experts.append(expert) + branch = Block(expert) + branches.append(wrap_moonep_checkpoint(branch) if args.layout == "split" else branch) + model = TwoStreams(branches) + if args.layout == "whole": + model = wrap_moonep_checkpoint(model) + options = dict(mesh=efs, reshard_after_forward=True, shard_placement_fn=lambda _: Shard(1), + mp_policy=MixedPrecisionPolicy(param_dtype=torch.bfloat16, reduce_dtype=torch.float32, + cast_forward_inputs=False)) + for expert in experts: + fully_shard(expert, **options) + fully_shard(model, **options) + experts[0].set_modules_to_forward_prefetch([experts[1]]) + experts[1].set_modules_to_backward_prefetch([experts[0]]) + runtime = configure_moonep(model) + generator.manual_seed(9000 + rank) + args.output.mkdir(parents=True, exist_ok=True) + for step, rows in enumerate((64, 95)): + model.zero_grad(set_to_none=True) + x = torch.randn(rows, 128, generator=generator).bfloat16().to(device).requires_grad_() + ids = torch.randint(1, 6, (2, rows, 2), generator=generator) + ids[:, :, 0] = 0 + scores = torch.rand(2, rows, 2, generator=generator).to(device).requires_grad_() + dy = torch.randn(rows, 128, generator=generator).to(device) + y = model(x, ids.to(device), scores) + loss = (y.float() * dy).sum() + if args.backend == "megakernel": + runtime.backward(loss) + else: + loss.backward() + runtime.finish_step() + assert not runtime.replay_released and not runtime.weight_leases + assert runtime.statistics["recomputations"] == 2 * (step + 1) + result = {"output": y.detach().cpu(), "dx": x.grad.cpu(), "dscores": scores.grad.cpu()} + for i, expert in enumerate(experts): + for name in ("gate_up", "down"): + result[f"{i}.{name}"] = local_tensor(getattr(expert, name).grad).cpu() + baseline = args.output / f"split_rank{rank}_step{step}.pt" + if args.layout == "split": + torch.save(result, baseline) + else: + expected = torch.load(baseline, weights_only=True) + for name, tensor in result.items(): + if not tensor.isfinite().all() or not tensor.count_nonzero(): + raise AssertionError(f"rank {rank} step {step}: invalid {name}") + torch.testing.assert_close(tensor, expected[name], atol=0, rtol=0, + msg=lambda msg: f"rank {rank} step {step} {name}: {msg}") + stats = torch.tensor([runtime.statistics["max_live_weight_leases"], runtime.statistics["remote_experts_max"]], + device=device) + dist.all_reduce(stats, op=dist.ReduceOp.MAX) + max_leases, remote_experts = stats.tolist() + assert max_leases <= 2 and remote_experts > 0, (max_leases, remote_experts) + if args.backend == "megakernel": + runtime.close() + dist.barrier() + if rank == 0: + print(f"PASS {args.backend} {args.layout}: 4 ranks, 2 training steps, max leases={max_leases}, " + f"max remote experts={remote_experts}", flush=True) + dist.destroy_process_group() + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--backend", choices=("nonfused", "megakernel"), required=True) + parser.add_argument("--layout", choices=("split", "whole"), required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--native-dir", type=Path) + run(parser.parse_args()) diff --git a/tests/ut/auto_models/distributed/test_moonep_lifecycle.py b/tests/ut/auto_models/distributed/test_moonep_lifecycle.py index ce0de090d..5021a64d7 100644 --- a/tests/ut/auto_models/distributed/test_moonep_lifecycle.py +++ b/tests/ut/auto_models/distributed/test_moonep_lifecycle.py @@ -87,7 +87,7 @@ def test_replay_context_does_not_read_weights_before_module_hooks(self): prepare_backward_resources=mock.Mock(), statistics={"recomputations": 0}) executor = SimpleNamespace(runtime=lifecycle) - tape = moonep_checkpoint._Tape(execution=(executor, key), identity=identity) + tape = moonep_checkpoint._Tape(executions=[(executor, key)], identity=identity) phase = SimpleNamespace(is_recomputing=True, invocation_id=identity) with mock.patch.object(moonep_checkpoint, "get_recompute_state", return_value=phase): with moonep_checkpoint._phase(torch.nn.Module(), tape, True): @@ -96,6 +96,34 @@ def test_replay_context_does_not_read_weights_before_module_hooks(self): lifecycle.prepare.assert_not_called() self.assertEqual(lifecycle.statistics["recomputations"], 1) + @arg_mark(plat_marks=["cpu_linux"], level_mark="level0", card_mark="dryrun", essential_mark="essential") + def test_checkpoint_route_order_and_count(self) -> None: + """Replay original IDs even if the recomputed scores would select different experts.""" + router, other = object(), object() + probs = torch.tensor([[1., 0.]]) + flipped = probs.flip(-1) + block, tape = torch.nn.Module(), moonep_checkpoint._Tape() + phase = SimpleNamespace(is_recomputing=False, invocation_id=object()) + executor = SimpleNamespace(runtime=SimpleNamespace(statistics={"recomputations": 0})) + with mock.patch.object(moonep_checkpoint, "get_recompute_state", return_value=phase): + with moonep_checkpoint._phase(block, tape, False): + for scores in (probs, flipped): + checkpoint_route_ids(router, scores, 1) + moonep_checkpoint.bind_execution(executor, object) + phase.is_recomputing = True + with self.assertRaisesRegex(RuntimeError, "consume all"): + with moonep_checkpoint._phase(block, tape, True): + moonep_checkpoint.bind_execution(executor, object) + with self.assertRaisesRegex(RuntimeError, "router order"): + with moonep_checkpoint._phase(block, tape, True): + checkpoint_route_ids(other, probs, 1) + with moonep_checkpoint._phase(block, tape, True): + moonep_checkpoint.bind_execution(executor, object) + self.assertEqual(checkpoint_route_ids(router, flipped, 1).item(), 0) + self.assertEqual(checkpoint_route_ids(router, probs, 1).item(), 1) + with self.assertRaisesRegex(RuntimeError, "extra routing"): + checkpoint_route_ids(router, flipped, 1) + def test_checkpoint_single_execution_error_contract(self) -> None: """Keep zero-call forward, one-call replay and all single-record rejection boundaries.""" identity, key = object(), object() @@ -107,8 +135,6 @@ def test_checkpoint_single_execution_error_contract(self) -> None: with mock.patch.object(moonep_checkpoint, "get_recompute_state", return_value=state): with moonep_checkpoint._phase(block, tape, False): self.assertIs(moonep_checkpoint.bind_execution(executor, factory), key) - with self.assertRaisesRegex(ValueError, "仅执行一次"): - moonep_checkpoint.bind_execution(executor, factory) factory.assert_called_once_with() state.is_recomputing = True with moonep_checkpoint._phase(block, tape, True): @@ -119,22 +145,20 @@ def test_checkpoint_single_execution_error_contract(self) -> None: with self.assertRaisesRegex(RuntimeError, "没有执行"): with moonep_checkpoint._phase(block, tape, True): pass - with moonep_checkpoint._phase(block, tape, True): - with self.assertRaisesRegex(RuntimeError, "顺序发生变化"): + with self.assertRaisesRegex(RuntimeError, "顺序发生变化"): + with moonep_checkpoint._phase(block, tape, True): moonep_checkpoint.bind_execution(object(), factory) - with self.assertRaisesRegex(RuntimeError, "不存在"): - moonep_checkpoint.bind_execution(executor, factory) state.invocation_id = object() - with self.assertRaisesRegex(RuntimeError, "原始单专家"): + with self.assertRaisesRegex(RuntimeError, "原始专家"): with moonep_checkpoint._phase(block, tape, True): pass state.is_recomputing = False empty = moonep_checkpoint._Tape() with moonep_checkpoint._phase(block, empty, False): pass - self.assertIsNone(empty.execution) + self.assertEqual(empty.executions, []) state.is_recomputing = True - with self.assertRaisesRegex(RuntimeError, "原始单专家"): + with self.assertRaisesRegex(RuntimeError, "原始专家"): with moonep_checkpoint._phase(block, empty, True): pass self.assertIs(moonep_checkpoint._SCOPE.get(), previous) @@ -161,8 +185,8 @@ def test_nested_checkpoint_scope_restores_after_normal_and_error_exit(self) -> N self.assertIs(moonep_checkpoint._SCOPE.get().tape, outer) state.invocation_id = parent_id moonep_checkpoint.bind_execution(object(), object) - self.assertIsNotNone(inner.execution) - self.assertIsNotNone(outer.execution) + self.assertEqual(len(inner.executions), 1) + self.assertEqual(len(outer.executions), 1) self.assertIs(moonep_checkpoint._SCOPE.get(), previous) @@ -412,6 +436,28 @@ def test_checkpoint_prefetch_and_eval_train_match(self): # 独立脚本路径只预取紧邻前一专家;较大的旧 depth 值不再预留空槽。 self._run_model(False, 4) + @arg_mark(plat_marks=["cpu_linux"], level_mark="level0", card_mark="dryrun", essential_mark="essential") + def test_whole_region_replays_repeated_expert_and_router(self) -> None: + """A shared block called twice must keep both keys, route choices and gradients.""" + def run(checkpointed): + torch.manual_seed(212) + first, second = _Block(), _Block() + model = torch.nn.Sequential(first, second, first) + runtime = configure_moonep(model, prefetch_depth=0) + if checkpointed: + model = wrap_moonep_checkpoint(model) + x = torch.randn(6, 8, requires_grad=True) + output = model(x) + output.square().sum().backward() + runtime.finish_step() + self.assertLessEqual(runtime.statistics["max_live_weight_leases"], 2) + self.assertFalse(runtime.replay_released) + self.assertEqual(runtime.statistics["plans"], 3) + return [output.detach(), x.grad, *(param.grad for param in model.parameters())] + + for actual, expected in zip(run(True), run(False)): + torch.testing.assert_close(actual, expected, rtol=0, atol=0) + def test_explicit_backward_matches_independent_autograd(self): """比较dX、两组dW及前向;例如限幅端点和空专家都经过独立torch公式。""" for activation, limit in (('clipped', 0.0), ('clipped', 0.3), ('swiglu', 0.0)): diff --git a/tests/ut/distributed/expert_parallel/moonep/test_lifecycle.py b/tests/ut/distributed/expert_parallel/moonep/test_lifecycle.py index 8dd66d51a..de11b2940 100644 --- a/tests/ut/distributed/expert_parallel/moonep/test_lifecycle.py +++ b/tests/ut/distributed/expert_parallel/moonep/test_lifecycle.py @@ -59,6 +59,10 @@ def prepare(self, key: ExecutionKey, *, ready_events: tuple = ()) -> Any: self.weight_leases[key] = object() return self.weight_leases[key] + def release(self, key: ExecutionKey) -> None: + """Return a recorded, previously prepared lease.""" + del self.weight_leases[key] + def retire_backward(self, key: ExecutionKey) -> None: """Model release and completion before an expert exit. @@ -73,6 +77,34 @@ def retire_backward(self, key: ExecutionKey) -> None: class TestRestoredWeightOrder(unittest.TestCase): """Exercise early, late, absent and deep prefetch notifications.""" + @arg_mark(plat_marks=["cpu_linux"], level_mark="level0", card_mark="dryrun", essential_mark="essential") + def test_replay_uses_current_home_fence_and_preserves_reverse_order(self) -> None: + """Feature: Multi-expert replay. + + Description: Recompute the first expert while true backward still points at the second. + Expectation: Use the newest home fence and restore released weights for true backward. + """ + runtime = _RecordedLifecycle(2) + first, last = runtime.keys + with patch.object(runtime, "_record_weight_dependency", + side_effect=["prefetch", "replay_home", "last_home", "ep_exit", "backward_home"]): + runtime.prepare_restored_weights(first) + with patch("hyper_parallel.distributed.expert_parallel.moonep.lifecycle.is_replay_demand", + side_effect=lambda key: key is first): + runtime.prepare_restored_weights(first) + self.assertEqual(runtime.submissions, [(first, ("replay_home",))]) + self.assertEqual(runtime.trace, [first, last]) + runtime.release_replay_lease(first) + runtime.prepare_restored_weights(last) + runtime.retire_backward(last) + # A shared executor can be ambiguous to a speculative prefetch. + runtime.prefetch_key = lambda executor: None + MoonEPAllGatherExtension(runtime.executors[0], runtime).fsdp_post_unshard(None) + self.assertEqual(runtime.submissions[-1], (first, ("backward_home", "ep_exit"))) + runtime.retire_backward(first) + self.assertFalse(runtime.replay_released) + self.assertFalse(runtime.pending_weight_preparations) + @arg_mark(plat_marks=["cpu_linux"], level_mark="level0", card_mark="dryrun", essential_mark="essential") def test_early_home_is_deferred_until_current_ep_exit(self) -> None: """Feature: Early restoration. diff --git a/tests/ut/distributed/expert_parallel/moonep/test_sparse_admission.py b/tests/ut/distributed/expert_parallel/moonep/test_sparse_admission.py index 762bc4ae2..c890462f7 100644 --- a/tests/ut/distributed/expert_parallel/moonep/test_sparse_admission.py +++ b/tests/ut/distributed/expert_parallel/moonep/test_sparse_admission.py @@ -187,7 +187,7 @@ def test_replay_reuses_key_without_retiring_backward_storage(self): self.runtime.arena = arena expert = self.executors[0] key = self.runtime.new_key(expert) - scope = SimpleNamespace(replay=True, execution_consumed=False, tape=SimpleNamespace(execution=(expert, key))) + scope = SimpleNamespace(replay=True, execution_index=0, tape=SimpleNamespace(executions=[(expert, key)])) factory = Mock(side_effect=lambda: self.runtime.new_key(expert)) with patch.object(checkpoint, "_SCOPE", SimpleNamespace(get=lambda: scope)): replay_key = checkpoint.bind_execution(expert, factory)