Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
76 changes: 53 additions & 23 deletions hyper_parallel/distributed/expert_parallel/moonep/checkpoint.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand All @@ -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


Expand All @@ -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


Expand All @@ -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)
Expand All @@ -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)

Expand All @@ -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完整重放。
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
26 changes: 20 additions & 6 deletions hyper_parallel/distributed/expert_parallel/moonep/lifecycle.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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()
Expand All @@ -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."""
Expand All @@ -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.
Expand All @@ -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]]
Expand Down Expand Up @@ -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.

Expand All @@ -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,
Expand Down
133 changes: 133 additions & 0 deletions tests/torch/expert_parallel/_test_moonep_multi_checkpoint.py
Original file line number Diff line number Diff line change
@@ -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())
Loading