Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / distributed / module_binding.py: 82%
137 statements
« prev ^ index » next coverage.py v7.13.1, created at 2026-12-05 05:12 +0800
« prev ^ index » next coverage.py v7.13.1, created at 2026-12-05 05:12 +0800
1# Copyright 2026 Huawei Technologies Co., Ltd
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14# ============================================================================
15"""Explicit stage protocols and resource-only binding for family and native modules."""
17from __future__ import annotations
19import inspect
20from copy import deepcopy
21from collections.abc import Callable, Mapping
22from dataclasses import dataclass, field
23from types import MappingProxyType
24from typing import Any
26from torch import nn
28from hyper_parallel.components.modules.module_family import _same_mesh, get_family_build_info
29from hyper_parallel.core.dtensor.placement_types import Replicate, Shard
30from hyper_parallel.components.modules.moe.shared_expert_overlap import bind_shared_expert_overlap
31from hyper_parallel.distributed.context_parallel.cp_context import CPContext
32from hyper_parallel.distributed.expert_parallel.ep_context import EPContext
33from hyper_parallel.distributed.expert_parallel.moonep_context import MoonEPContext
36@dataclass(frozen=True)
37class ParallelModuleSpec:
38 """A class-owned execution protocol; validation proves its supported layouts."""
40 protocol: str
41 binding_kind: str = "none"
42 stages: Mapping[str, tuple[str, ...]] = field(default_factory=dict)
43 validate: Callable | None = None
44 options: Mapping[str, Any] = field(default_factory=dict)
45 version: str = "1"
46 validate_materialized: Callable | None = None
48 def __post_init__(self) -> None:
49 if not self.protocol or not self.version:
50 raise ValueError("parallel protocol and version must be non-empty")
51 if self.binding_kind not in ("none", "cp", "ep", "mesh"):
52 raise ValueError("binding_kind must be none, cp, ep or mesh")
53 if self.binding_kind != "none" and (not self.stages or self.validate is None):
54 raise ValueError("parallel members must declare stage signatures and a layout validator")
55 object.__setattr__(self, "stages", MappingProxyType({name: tuple(args) for name, args in self.stages.items()}))
56 object.__setattr__(self, "options", MappingProxyType(deepcopy(dict(self.options))))
59@dataclass(frozen=True)
60class NativeParallelBindingRequest:
61 """Bind an existing component whose class already delegates explicit stages."""
63 match: tuple[str, ...]
64 parallel: ParallelModuleSpec
65 sharding: Callable
67 def __post_init__(self) -> None:
68 if isinstance(self.match, str) or not self.match or not all(isinstance(name, str) for name in self.match):
69 raise ValueError("native matches must be a non-empty tuple of module FQN patterns")
70 if not callable(self.sharding) or not isinstance(self.parallel, ParallelModuleSpec):
71 raise ValueError("native binding requires a complete layout provider and ParallelModuleSpec")
72 object.__setattr__(self, "match", tuple(self.match))
75@dataclass(frozen=True)
76class MeshBinding:
77 """Borrowed topology; all communication groups are owned by MeshContext."""
79 mesh_context: Any
81 def axis_mesh(self, axis: str) -> Any:
82 """Return a prebuilt one-dimensional mesh without constructing groups.
84 Args:
85 axis: cp or ep, in the runtime's established rank order.
86 """
87 if axis == "ep":
88 region = self.mesh_context.fsdp_moe_mesh
89 if region is not None:
90 return region["ep"]
91 region = self.mesh_context.device_mesh
92 if region is None or axis not in tuple(region.mesh_dim_names or ()):
93 raise ValueError(f"no prebuilt {axis!r} mesh is available for parallel binding")
94 return region[axis]
97@dataclass(frozen=True)
98class ParallelBinding:
99 """One resource object injected through a class-defined bind_parallel method."""
101 mesh_binding: MeshBinding
102 cp_context: CPContext | None = None
103 ep_context: EPContext | None = None
106def validate_parallel_module(module: nn.Module, parallel: ParallelModuleSpec, sharding: Any, context: Any) -> None:
107 """Validate class stages and capabilities after owned-layout port checks.
109 Args:
110 module: Actual final member or native component.
111 parallel: Versioned stage declaration from the class/model spec.
112 sharding: Final ModuleShardingSpec after user overrides.
113 context: Immutable logical layout context.
114 """
115 for name, arguments in parallel.stages.items():
116 implementation = inspect.getattr_static(type(module), name, None)
117 if not callable(implementation):
118 raise ValueError(f"parallel stage {name!r} must be implemented in the module class")
119 inspect.signature(getattr(module, name)).bind(**dict.fromkeys(arguments))
120 if parallel.binding_kind != "none":
121 implementation = inspect.getattr_static(type(module), "bind_parallel", None)
122 if not callable(implementation):
123 raise ValueError("parallel modules must define bind_parallel(binding) in their class")
124 inspect.signature(module.bind_parallel).bind(None)
125 if getattr(sharding, "_ep_stack", None):
126 raise ValueError("explicit expert stages cannot inherit legacy whole-MoE stacking")
127 _validate_parallel_ports(sharding)
128 if parallel.binding_kind == "ep":
129 _validate_expert_ownership(module, parallel, sharding, context)
130 if parallel.validate is not None:
131 parallel.validate(module=module, sharding=sharding, context=context)
134def _validate_parallel_ports(sharding):
135 """Allow original TP boundaries while explicit CP/EP restores its own ownership."""
136 # CP/EP own their internal exchanges; the original boundary executor may
137 # still redistribute TP ports around the member's local computation.
138 for source, destination in ((sharding.in_src, sharding.in_dst), (sharding.out_src, sharding.out_dst)):
139 if source == destination or destination is None:
140 continue
141 if not sharding.is_boundary or source is None or set(source) != set(destination):
142 raise ValueError("explicit stage modules require complete TP boundary ports")
143 for port, begin in source.items():
144 end = destination[port]
145 if any(begin.get(axis, Replicate()) != end.get(axis, Replicate())
146 for axis in (set(begin) | set(end)) - {"tp"}):
147 raise ValueError("explicit stages must restore non-TP ownership themselves")
150def _validate_expert_ownership(module, parallel, sharding, context):
151 """Check the bound EP mesh against local and global expert ownership."""
152 experts = parallel.options.get("num_experts")
153 expert_type = type(experts)
154 if expert_type is not int or experts < 1 or experts % context.axis_sizes["ep"]:
155 raise ValueError("EP protocols must declare a divisible global num_experts")
156 sharded = {name: named["ep"] for name, named in sharding.params.items()
157 if isinstance(named.get("ep"), Shard)}
158 if not sharded:
159 raise ValueError("EP transport requires explicit DTensor expert ownership")
160 for name, placement in sharded.items():
161 parameter = module.get_parameter(name)
162 if placement.dim != 0 or parameter.shape[0] != experts:
163 raise ValueError("EPContext supports balanced contiguous expert Shard(0) ownership")
166def _build_ep_context(mesh_binding: MeshBinding, parallel: ParallelModuleSpec) -> EPContext:
167 """Choose the declared EP runtime while borrowing the existing expert mesh."""
168 moonep = parallel.options.get("moonep", False)
169 if not isinstance(moonep, bool):
170 raise ValueError("the moonep runtime option must be bool")
171 mesh = mesh_binding.axis_mesh("ep")
172 overlap = parallel.options.get("overlap_shared_expert", True)
173 if moonep:
174 return MoonEPContext(mesh, num_experts=parallel.options["num_experts"],
175 replica_capacity=parallel.options.get("moonep_replica_capacity"),
176 overlap_shared_expert=overlap)
177 return EPContext(mesh, num_experts=parallel.options["num_experts"], overlap_shared_expert=overlap)
180def bind_parallel_modules(model: nn.Module, plan: Any, mesh_context: Any) -> None:
181 """Inject shared resources after layout and before activation wrappers/FSDP2.
183 Args:
184 model: Final model tree with computation-sharded parameters.
185 plan: Plan carrying validated family/native protocol declarations.
186 mesh_context: Existing HyperParallel MeshContext; never a new topology.
187 """
188 mesh_binding = MeshBinding(mesh_context)
189 prepared = []
190 for fqn, parallel in plan.parallel_modules.items():
191 if parallel.binding_kind == "none":
192 continue
193 module = model.get_submodule(fqn)
194 existing = getattr(module, "_hp_parallel_binding", None)
195 if existing is not None:
196 info = get_family_build_info(module)
197 cached = info.layout if info is not None else None
198 if (cached is None or not cached.applied or cached.parallel != parallel
199 or not _same_mesh(existing.mesh_binding.mesh_context, mesh_context)):
200 raise ValueError(f"module {fqn!r} already has a communication owner")
201 continue
202 cp = CPContext(mesh_binding.axis_mesh("cp")) if parallel.binding_kind == "cp" else None
203 ep = _build_ep_context(mesh_binding, parallel) if parallel.binding_kind == "ep" else None
204 prepared.append((fqn, module, ParallelBinding(mesh_binding, cp, ep)))
205 for fqn, module, binding in prepared:
206 module.bind_parallel(binding)
207 module._hp_parallel_binding = binding # pylint: disable=protected-access
208 if binding.ep_context is not None:
209 bind_shared_expert_overlap(model, fqn, binding.ep_context)
210 model._hp_parallel_module_specs = dict(plan.parallel_modules) # pylint: disable=protected-access
213def validate_materialized_modules(model: nn.Module) -> None:
214 """Check final device/kernel resources after materialization and before compile.
216 Args:
217 model: Final loaded model whose class protocols may validate physical resources.
218 """
219 for fqn, parallel in getattr(model, "_hp_parallel_module_specs", {}).items():
220 module = model.get_submodule(fqn)
221 if parallel.validate_materialized is not None:
222 parallel.validate_materialized(module=module, binding=getattr(module, "_hp_parallel_binding", None))