Diff Coverage

Diff: origin/master...HEAD, staged and unstaged changes

Source File Diff Coverage (%) Missing Lines
hyper_parallel/components/modules/engram/base_engram.py 100%  
hyper_parallel/components/modules/engram/host_engram_table.py 50.0% 141
hyper_parallel/components/modules/gate.py 75.0% 141
hyper_parallel/components/modules/mhc/mega_mhc.py 50.0% 85
hyper_parallel/components/modules/mhc/mhc_pre.py 100%  
hyper_parallel/components/modules/mhc/pipelined_mhc.py 100%  
hyper_parallel/components/modules/module_family.py 91.7% 254
hyper_parallel/components/modules/moe/grouped_experts/__init__.py 100%  
hyper_parallel/components/modules/moe/grouped_experts/ep/ep_grouped_experts.py 61.9% 43,45,50,52,79-83,100-103,119-121
hyper_parallel/components/modules/moe/grouped_experts/ep/ep_mega_grouped_experts.py 0.0% 17-18,21,29,35
hyper_parallel/components/modules/moe/grouped_experts/ep/moonep_grouped_experts.py 52.4% 46-47,55-60,79,83
hyper_parallel/components/modules/moe/grouped_experts/grouped_experts.py 87.6% 70,132,135,140,142,157,190,210,259,262,264,266,268,270,295,344,346,359,396,398-400
hyper_parallel/components/modules/moe/grouped_experts/grouped_experts_family.py 90.3% 48,53,56
hyper_parallel/components/modules/moe/grouped_experts/mega_grouped_experts.py 83.3% 44
hyper_parallel/components/modules/rms_norm.py 100%  
hyper_parallel/distributed/_builder/default_templates.py 100%  
hyper_parallel/distributed/_builder/planner.py 93.0% 316,318,354
hyper_parallel/distributed/expert_parallel/ep_context.py 78.9% 32,34,36,39,68,107,112,137,139,143,146,150
hyper_parallel/distributed/expert_parallel/moonep_context.py 43.5% 39-46,59,78,91,110,124
hyper_parallel/distributed/module_binding.py 44.4% 167-171
hyper_parallel/components/modules/engram/host_engram_table.py
137
138
139
140
141
142
143
144
        Returns:
            An empty converter list, matching members whose initialization is
            fully owned by ``reset_parameters``.
        """
        return []

    def forward(self, global_ids: torch.Tensor) -> torch.Tensor:
        """Look up global row IDs through the owner-local CPU table.
hyper_parallel/components/modules/gate.py
137
138
139
140
141
142
143
144
145
        Returns:
            An empty converter list, matching members whose initialization is
            fully owned by ``reset_parameters``.
        """
        return []

    def forward(self, hidden_states: torch.Tensor,
                correction_bias: torch.Tensor | None = None) -> tuple[torch.Tensor, ...]:
        """Return flattened logits, scaled weights and selected expert IDs."""
hyper_parallel/components/modules/mhc/mega_mhc.py
81
82
83
84
85
86
87
88
89
        Returns:
            An empty converter list, matching members whose initialization is
            fully owned by ``reset_parameters``.
        """
        return []

    def _apply(self, fn: Any, recurse: bool = True) -> MegaMhcModule:
        """Preserve declared FP32 parameters and gradients during conversion."""
        # The predictor uses FP32 even when the enclosing model uses BF16.
hyper_parallel/components/modules/module_family.py
250
251
252
253
254
255
256
257
258
    Conversion-only modules may rely on their ordinary children for initialization.
    """
    make_transforms = getattr(module, "make_transforms", None)
    if make_transforms is not None and not callable(make_transforms):
        raise TypeError("replacement make_transforms must be callable")
    reset_parameters = getattr(module, "reset_parameters", None)
    reset_owner = next((base for base in type(module).__mro__ if "reset_parameters" in vars(base)), None)
    custom_reset = (callable(reset_parameters) and reset_owner is not None
                    and not reset_owner.__module__.startswith("torch.nn."))
hyper_parallel/components/modules/moe/grouped_experts/ep/ep_grouped_experts.py
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
    Source adapters must convert names, shapes and mathematics before this point.
    Dense TP is allowed; each EP owner keeps complete experts (ETP=1).
    """
    if set(sharding.params) != {"gate_up_proj", "down_proj"}:
        raise ValueError("EP experts require complete canonical expert ownership")
    if any(axes != {"ep": Shard(0)} for axes in sharding.params.values()):
        raise ValueError("TP-extend-EP requires only contiguous expert Shard(0), without expert TP sharding")
    config = module.config
    expected = {"gate_up_proj": (config.num_experts, 2 * config.intermediate_size, config.hidden_size),
                "down_proj": (config.num_experts, config.hidden_size, config.intermediate_size)}
    if any(tuple(module.get_parameter(name).shape) != shape for name, shape in expected.items()):
        raise ValueError("TP-extend-EP requires complete canonical expert matrices")
    if module.config.num_experts % context.axis_sizes["ep"]:
        raise ValueError("EP size must divide the global expert count")


class EPGroupedExperts(GroupedExpertsModule):
    """Reuse the default algorithm and override only transport/binding stages."""
75
76
77
78
79
80
81
82
83
84
85
86
87

        Args:
            binding: Job-owned EP resources with matching global expert ownership.
        """
        if not isinstance(binding.ep_context, EPContext) or binding.ep_context.num_experts != self.config.num_experts:
            raise ValueError("binding requires an EP context with the same global expert count")
        if self.ep_context is not None and self.ep_context is not binding.ep_context:
            raise ValueError("EP experts already have a different communication owner")
        self.ep_context = binding.ep_context

    def dispatch(
        self, hidden_states: Tensor, expert_ids: Tensor, tokens_per_expert: Tensor,
        routing_weights: Tensor | None = None,
 96
 97
 98
 99
100
101
102
103
104
105
106
107

        Returns:
            Owner-local hidden/counts/weights, this call's split lists and received-row inverse mapping.
        """
        del tokens_per_expert
        if self.ep_context is None:
            raise RuntimeError("bind_parallel must run before EP dispatch")
        return self.ep_context.dispatch(hidden_states, expert_ids, routing_weights)

    def combine(
        self, values: Tensor, send_splits: list[int] | None, recv_splits: list[int] | None, recv_inverse: Tensor | None,
    ) -> Tensor:
115
116
117
118
119
120
121
122
123
124

        Returns:
            Source expert-major outputs [S,H], before token unpermutation.
        """
        if self.ep_context is None or send_splits is None or recv_splits is None or recv_inverse is None:
            raise RuntimeError("EP combine requires a bound context and this call's transport arguments")
        return self.ep_context.combine(values, send_splits, recv_splits, recv_inverse)

    def parallel_module_spec(self) -> ParallelModuleSpec:
        """Describe transport signatures and ownership without allocating runtime resources.
hyper_parallel/components/modules/moe/grouped_experts/ep/ep_mega_grouped_experts.py
13
14
15
16
17
18
19
20
21
22
23
24
25
# limitations under the License.
# ============================================================================
"""Reserved EP/Mega binding; no second EP transport or Mega resource manager."""

from hyper_parallel.components.modules.moe.grouped_experts.mega_grouped_experts import MegaGroupedExperts
from hyper_parallel.distributed.module_binding import ParallelBinding


class EPMegaGroupedExperts(MegaGroupedExperts):
    """Reserve the job-mesh entry for the same fused Mega execution point.

    The final protocol must convey expert ownership and an explicit EP group
    to the core runtime. It must not compose ordinary dispatch/combine around
25
26
27
28
29
30
31
32
33
    to the core runtime. It must not compose ordinary dispatch/combine around
    an executor that already performs those transfers.
    """

    def bind_parallel(self, binding: ParallelBinding) -> None:
        """Reserve borrowing the HP job mesh for the future fused runtime.

        Args:
            binding: Job-owned parallel resources; no expert parameters are transferred.
31
32
33
34
35

        Args:
            binding: Job-owned parallel resources; no expert parameters are transferred.
        """
        raise NotImplementedError("EP/Mega mesh binding and fused protocol are not implemented")
hyper_parallel/components/modules/moe/grouped_experts/ep/moonep_grouped_experts.py
42
43
44
45
46
47
48
49
50
        Args:
            config: Canonical global algorithm configuration, exclusive with module.
            module: Canonical source whose parameters and training state are retained.
        """
        super().__init__(config=config, module=module)
        self.ep_context: MoonEPContext | None = None

    def bind_parallel(self, binding: ParallelBinding) -> None:
        """Borrow the job-owned MoonEP context with matching home ownership.
51
52
53
54
55
56
57
58
59
60
61
62
63
64

        Args:
            binding: Existing expert mesh and MoonEP context; no new process group.
        """
        context = binding.ep_context
        if not isinstance(context, MoonEPContext) or context.num_experts != self.config.num_experts:
            raise ValueError("MoonEP experts require a MoonEP context with the same global expert count")
        if self.ep_context is not None and self.ep_context is not context:
            raise ValueError("MoonEP experts already have a different communication owner")
        self.ep_context = context

    def forward(
        self, hidden_states: Tensor, topk_ids: Tensor | None = None, topk_weights: Tensor | None = None,
        **kwargs: Tensor,
75
76
77
78
79
80
81
82
83
84
85
86
87
            The runtime must use the same invocation plan for weight prefetch,
            dispatch, shared compute, combine, replica-gradient return and recompute.
            It must not compose ordinary slot restore around token-level combine.
        """
        raise NotImplementedError("MoonEP execution, replica autograd and invocation lifecycle are not implemented")

    def parallel_module_spec(self) -> ParallelModuleSpec:
        """Declare home Shard(0) ownership and a distinct request-level EP protocol."""
        return ParallelModuleSpec(
            "grouped_experts.forward.moonep", "ep", {"forward": ("hidden_states", "topk_ids", "topk_weights")},
            validate=validate_ep_layout,
            options={"num_experts": self.config.num_experts, "moonep": True},
        )
hyper_parallel/components/modules/moe/grouped_experts/grouped_experts.py
66
67
68
69
70
71
72
73
74
            value = getattr(self, name)
            if not isinstance(value, int) or isinstance(value, bool) or value < 1:
                raise ValueError(f"{name} must be a positive integer")
        if self.routing_weight_mode not in ("output", "before_fc2"):
            raise ValueError("routing_weight_mode must be output or before_fc2")


_EXPERT_CONFIG_KEYS = {
    "num_experts": ("num_experts", "num_local_experts", "n_routed_experts"),
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
def _packed_parameters(module, module_fqn, configs, activation):
    """Validate packed source parameters and their activation contract."""
    parameters = dict(module.named_parameters())
    if set(parameters) != {"gate_up_proj", "down_proj"} or list(module.named_buffers()):
        raise ValueError(f"{module_fqn}: expected canonical experts or two bias-free packed projections")
    if any(weight.ndim != 3 or isinstance(weight, DTensor) or weight.grad is not None
           for weight in parameters.values()):
        raise ValueError(f"{module_fqn}: packed experts must be converted before sharding and backward")
    act_fn = getattr(module, "act_fn", None)
    hidden_act = _match_expert_config_value(configs, "hidden_act", "silu")
    if activation is None and (hidden_act != "silu" or (
            act_fn is not None and type(act_fn) not in (nn.SiLU, SiLUActivation) and act_fn is not F.silu)):
        raise ValueError(f"{module_fqn}: supply the activation for packed experts with non-SwiGLU math")
    if activation is None and getattr(module, "limit", 0) > 0:
        raise ValueError(f"{module_fqn}: supply the model activation for clamped packed experts")
    return parameters


def _packed_dimensions(module, module_fqn, parameters, configs):
153
154
155
156
157
158
159
160
161
        _match_expert_config_value(sources, "hidden_size", hidden),
        _match_expert_config_value(sources, "intermediate_size", width),
    )
    if source_dimensions != (experts, hidden, width) or gate_up.shape != (experts, 2 * width, hidden):
        raise ValueError(f"{module_fqn}: expected packed gate_up_proj [E,2I,H] and down_proj [E,H,I]")
    return experts, hidden, width


class GroupedExpertsModule(nn.Module):
186
187
188
189
190
191
192
193
194
            construction explicitly preserves module.training, including eval mode.
        """
        super().__init__()
        if (config is None) == (module is None):
            raise ValueError("provide exactly one of config or module")
        if module is not None:
            source_config = getattr(module, "config", None)
            if not isinstance(source_config, GroupedExpertsConfig):
                configs = tuple((context or {}).get("module_configs", ())) or (source_config,)
206
207
208
209
210
211
212
213
214
            for name, child in module.named_children():
                self.add_module(name, child)
        else:
            if not isinstance(config, GroupedExpertsConfig):
                raise ValueError("config must be GroupedExpertsConfig")
            self.config = config
            self.gate_up_proj = nn.Parameter(torch.empty(config.num_experts, 2 * config.intermediate_size,
                                                         config.hidden_size))
            self.down_proj = nn.Parameter(torch.empty(config.num_experts, config.hidden_size,
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
        Returns:
            Flattened source tokens [T,H]; routes remain in the caller's local variables.
        """
        if hidden_states.ndim < 1 or hidden_states.shape[-1] != self.config.hidden_size:
            raise ValueError("hidden_states must have shape [..., hidden_size]")
        hidden = hidden_states.reshape(-1, self.config.hidden_size)
        if topk_ids.ndim != 2 or topk_ids.shape[0] != hidden.shape[0] or topk_ids.shape[1] < 1:
            raise ValueError("topk_ids must have shape [flattened_tokens, positive_top_k]")
        if topk_weights.shape != topk_ids.shape:
            raise ValueError("topk_weights must have the same [T,K] shape as topk_ids")
        if topk_ids.dtype not in (torch.int32, torch.int64):
            raise ValueError("topk_ids must have integer int32/int64 dtype")
        if not hidden_states.is_floating_point() or not topk_weights.is_floating_point():
            raise ValueError("hidden_states and topk_weights must have floating-point dtype")
        if hidden.device != topk_ids.device or hidden.device != topk_weights.device:
            raise ValueError("tokens, expert IDs and routing weights must be on the same device")
        return hidden

    def permute(
        self, hidden_states: Tensor, topk_ids: Tensor, topk_weights: Tensor,
291
292
293
294
295
296
297
298
299
            hidden, unpermute_indices = moe_token_permute(
                hidden_states.contiguous(), topk_ids.to(torch.int32).contiguous(),
            )
        else:
            hidden, unpermute_indices = hidden_states, ids.to(torch.int32)
        # The kernel maps original route slots to permuted rows; metadata needs the inverse.
        order = torch.empty_like(unpermute_indices, dtype=torch.int64)
        order.scatter_(0, unpermute_indices.to(torch.int64), torch.arange(ids.numel(), device=ids.device))
        ids = ids[order]
340
341
342
343
344
345
346
347
348
349
350
        down = down.to_local() if isinstance(down, DTensor) else down
        if (gate_up.ndim != 3 or gate_up.shape[0] < 1
                or gate_up.shape[1:] != (2 * self.config.intermediate_size, self.config.hidden_size)
                or down.shape != (gate_up.shape[0], self.config.hidden_size, self.config.intermediate_size)):
            raise ValueError("expert compute requires complete [C,2I,H] and [C,H,I] matrices; ETP is unsupported")
        if tokens_per_expert.shape != (gate_up.shape[0],):
            raise ValueError("tokens_per_expert must describe the current expert compute table")
        hidden = hidden_states
        group_list = tokens_per_expert.to(device=hidden.device, dtype=torch.int64).cumsum(0)
        # The kernel uses input-major projections while checkpoints store linear weights.
        gate_up, down = gate_up.transpose(-2, -1), down.transpose(-2, -1)
355
356
357
358
359
360
361
362
        activation = self.config.activation
        activated = F.silu(gate) * up if activation is None else activation(gate, up).to(hidden.dtype)
        if self.config.routing_weight_mode == "before_fc2":
            if routing_weights is None:
                raise ValueError("before_fc2 requires differentiable slot routing weights")
            activated = (activated * routing_weights.unsqueeze(-1)).to(activated.dtype)
        return (grouped_matmul(activated, down, group_list=group_list)  # pylint: disable=not-callable
                if hidden.shape[0] else activated @ down[0])
392
393
394
395
396
397
398
399
400
401
402
403
404
        Returns:
            Top-k combined output in the original token order and shape [...,H].
        """
        if values.shape != (unpermute_indices.numel(), self.config.hidden_size):
            raise ValueError("combine must return one hidden-size output per source slot")
        if not values.shape[0]:
            if self.config.routing_weight_mode == "output":
                values = values * topk_weights.reshape(-1, 1)
            return values.reshape(output_shape)
        # None implies top-k=1 in the kernel; ones retain top-k summation without reweighting FC2 output.
        probs = topk_weights if self.config.routing_weight_mode == "output" else torch.ones_like(topk_weights)
        output = moe_token_unpermute(
            values.contiguous(), unpermute_indices, probs.contiguous(),
hyper_parallel/components/modules/moe/grouped_experts/grouped_experts_family.py
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
    del context
    if module is not None and not isinstance(module, GroupedExpertsModule):
        gate_up = getattr(module, "gate_up_proj", None)
        if not isinstance(gate_up, nn.Parameter) or gate_up.ndim != 3:
            raise ValueError("staged experts require a canonical member or a packed expert source")
        num_experts = gate_up.shape[0]
    else:
        facts = config if module is None else module.config
        if not isinstance(facts, GroupedExpertsConfig):
            raise ValueError("staged experts require canonical GroupedExpertsConfig")
        num_experts = facts.num_experts
    if num_experts % member.axis_sizes["ep"]:
        raise ValueError("EP size must divide the global expert count")
    if member.variant not in ("local", "ep"):
        raise NotImplementedError(f"expert member {member.variant!r} is registered but execution is not implemented")

hyper_parallel/components/modules/moe/grouped_experts/mega_grouped_experts.py
40
41
42
43
44
            topk_ids: Global model-selected expert IDs [T,K].
            topk_weights: Final differentiable routing weights [T,K].
            **kwargs: Source aliases accepted by the family interface.
        """
        raise NotImplementedError("Mega executor binding, probability contract and lifecycle are not implemented")
hyper_parallel/distributed/_builder/planner.py
312
313
314
315
316
317
318
319
320
321
322
            for axis, placement in axes.items():
                if placement == Replicate():
                    continue
                if axis != EP or placement != Shard(0):
                    return False
                if protocol is None or protocol.binding_kind not in ("ep", "mesh"):
                    return False
        return True

    def _routed_moe_boundaries(self, roles, owned) -> dict[str, str]:
        """Select parent templates before expert ownership hides the MoE structure."""
350
351
352
353
354
355
356
357
358
                            if name.startswith(root + ".") and name not in owned.owned_names]
            # The parent template owns complete replicated math, including otherwise-special parameters.
            for name, role in groups[root]:
                if role == ParamRole.SPECIAL:
                    param_roles[name] = ParamRole.REPLICATED
        return param_roles, groups, boundary_types

    def plan(
        self,
hyper_parallel/distributed/expert_parallel/ep_context.py
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43

def _validate_slot_inputs(hidden: Tensor, ids: Tensor, weights: Tensor | None) -> None:
    """Validate resource-free source slots before entering any collective."""
    if hidden.ndim != 2 or hidden.shape[1] < 1 or not hidden.is_floating_point():
        raise ValueError("slot hidden_states must be floating-point [slots,H] with H>0")
    if ids.shape != (hidden.shape[0],) or ids.dtype not in (torch.int32, torch.int64):
        raise ValueError("expert_ids must have integer dtype and shape [slots]")
    if ids.device != hidden.device:
        raise ValueError("slot activations and expert IDs must share the same device")
    if weights is not None:
        if weights.shape != ids.shape or not weights.is_floating_point() or weights.device != hidden.device:
            raise ValueError("slot routing_weights must be floating-point [slots] on the activation device")


class EPContext:
    """Balanced contiguous expert ownership from HP mesh and Shard(0) layout."""
64
65
66
67
68
69
70
71
72
        received = (ep_exchange_counts(metadata, self.mesh.get_group())
                    if self.mesh.size() > 1 else metadata)
        fields = ep_split_sizes(received.reshape(-1))
        if any(flag != int(weighted) for flag in fields[1::2]):
            raise ValueError("all EP ranks must agree on whether slot routing_weights are transported")
        return ep_split_sizes(counts), fields[::2]

    def dispatch(
        self, hidden_states: Tensor, expert_ids: Tensor, routing_weights: Tensor | None = None,
103
104
105
106
107
108
109
110
111
112
113
114
115
116
            return hidden, local_counts, weights, send, receive, local_ids.to(torch.int32)

        if hidden.device.type == "npu":
            # Keep the optional torch_npu dependency inside the NPU path.
            from hyper_parallel.components.functional.moe_token_permute import (  # pylint: disable=C0415
                moe_token_permute,
            )

            # One expert per received slot keeps this a one-to-one rearrangement.
            hidden, recv_inverse = moe_token_permute(hidden.contiguous(), local_ids.to(torch.int32).view(-1, 1))
        else:
            order = local_ids.argsort(stable=True)
            hidden = hidden.index_select(0, order)
            rows = torch.arange(order.numel(), dtype=torch.int32, device=order.device)
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
        Returns:
            Source-side slot outputs; the Experts algorithm restores original tokens.
        """
        if len(send_splits) != self.mesh.size() or len(recv_splits) != self.mesh.size():
            raise ValueError("slot split lists must follow the current EP group's rank order")
        if values.ndim != 2 or values.shape[0] != sum(recv_splits):
            raise ValueError("slot output must have one row per received slot")
        if recv_inverse.shape != (values.shape[0],) or recv_inverse.dtype != torch.int32:
            raise ValueError("recv_inverse must have dtype int32 and one index per received slot")
        if recv_inverse.device != values.device:
            raise ValueError("slot outputs and recv_inverse must be on the same device")
        if values.shape[0] and values.device.type == "npu":
            # Keep the optional torch_npu dependency inside the NPU path.
            from hyper_parallel.components.functional.moe_token_unpermute import (  # pylint: disable=C0415
                moe_token_unpermute,
            )

            values = moe_token_unpermute(values.contiguous(), recv_inverse)
        elif values.shape[0]:
            values = values.index_select(0, recv_inverse)
        return self._exchange(values, recv_splits, send_splits)
hyper_parallel/distributed/expert_parallel/moonep_context.py
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
        Args:
            mesh: Existing one-dimensional expert mesh, including dense TP ranks.
            num_experts: Global home expert count, divisible by the EP mesh size.
        """
        if mesh is None or mesh.ndim != 1:
            raise ValueError("MoonEPContext requires an existing one-dimensional HP expert mesh")
        if num_experts < 1 or num_experts % mesh.size():
            raise ValueError("num_experts must be positive and divisible by EP size")
        self.mesh = mesh
        self.num_experts = num_experts
        self.local_experts = num_experts // mesh.size()
        self.rank = mesh.get_local_rank()

    def plan(self, hidden_states: Tensor, topk_ids: Tensor, topk_weights: Tensor) -> object:
        """Reserve a per-call allocation/transport plan from original token routes.
55
56
57
58
59
60
61
62
63

        Returns:
            Opaque plan mapping compute rows to home experts, retained through backward/recompute.
        """
        raise NotImplementedError("MoonEP load planning and invocation replay are not implemented")

    def dispatch(
        self, hidden_states: Tensor, topk_ids: Tensor, topk_weights: Tensor, plan: object,
        *, routing_weight_mode: Literal["output", "before_fc2"] = "before_fc2",
74
75
76
77
78
79
80
81
        Returns:
            Expert-major activations [R,H], counts [C], optional probabilities [R].
            Preserve router gradients and leave output-mode weighting to combine.
        """
        raise NotImplementedError("MoonEP token dispatch and differentiable transport are not implemented")

    def prefetch_weights(self, gate_up_proj: Tensor, down_proj: Tensor, plan: object) -> tuple[Tensor, Tensor]:
        """Reserve complete local/replica weight views for the shared expert math.
87
88
89
90
91
92
93
94
95

        Returns:
            Weights [C,H,2I] / [C,I,H]; temporary rows must return gradients to their home owners.
        """
        raise NotImplementedError("MoonEP weight prefetch and temporary compute views are not implemented")

    def combine(
        self, values: Tensor, topk_weights: Tensor, output_shape: tuple[int, ...], plan: object,
        *, routing_weight_mode: Literal["output", "before_fc2"] = "before_fc2",
106
107
108
109
110
111
112
113
        Returns:
            Routed token output in output_shape, with probabilities applied once.
            This token-level result must not pass through ordinary unpermute again.
        """
        raise NotImplementedError("MoonEP output combine and router-weight backward are not implemented")

    def reduce_grad(self, gate_up_grad: Tensor, down_grad: Tensor, plan: object) -> tuple[Tensor, Tensor]:
        """Reserve autograd-owned replica gradient return before FSDP reduction.
120
121
122
123
124
        Returns:
            Home-local gradients with replica contributions summed exactly once.
            The future autograd bridge must complete this before framework gradient reduction.
        """
        raise NotImplementedError("MoonEP replica gradient return and FSDP lifecycle integration are not implemented")
hyper_parallel/distributed/module_binding.py
163
164
165
166
167
168
169
170
171
172
173
174
175


def _build_ep_context(mesh_binding: MeshBinding, parallel: ParallelModuleSpec) -> EPContext | MoonEPContext:
    """Choose the declared EP runtime while borrowing the existing expert mesh."""
    moonep = parallel.options.get("moonep", False)
    if not isinstance(moonep, bool):
        raise ValueError("the moonep runtime option must be bool")
    constructor = MoonEPContext if moonep else EPContext
    return constructor(mesh_binding.axis_mesh("ep"), num_experts=parallel.options["num_experts"])


def bind_parallel_modules(model: nn.Module, plan: Any, mesh_context: Any) -> None:
    """Inject shared resources after layout and before activation wrappers/FSDP2.