Diff Coverage

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

Source File Diff Coverage (%) Missing Lines
hyper_parallel/components/losses/moe_aux_loss.py 93.5% 53,59
hyper_parallel/components/modules/module_family.py 100%  
hyper_parallel/components/modules/moe/gate.py 90.6% 99,104,232,371-372,376
hyper_parallel/components/modules/moe/grouped_experts/ep/ep_grouped_experts.py 33.3% 104,125
hyper_parallel/components/modules/moe/grouped_experts/ep/ep_mega_grouped_experts.py 96.1% 46,59,110,180
hyper_parallel/components/modules/moe/grouped_experts/ep/moonep_grouped_experts.py 19.0% 80-93,96-98
hyper_parallel/components/modules/moe/grouped_experts/grouped_experts.py 87.5% 95,98,354,425
hyper_parallel/components/modules/moe/grouped_experts/grouped_experts_family.py 100%  
hyper_parallel/components/modules/moe/moe_utils.py 95.2% 76,80,159
hyper_parallel/components/modules/moe/router.py 88.2% 75,77,80,116
hyper_parallel/components/modules/moe/router_training.py 95.8% 79,96,145,186,203
hyper_parallel/components/modules/moe/shared_expert.py 100%  
hyper_parallel/components/modules/moe/shared_expert_overlap.py 92.3% 62,69
hyper_parallel/components/modules/runtime.py 100%  
hyper_parallel/distributed/expert_parallel/ep_context.py 84.4% 85,87,89,93,96,100,140
hyper_parallel/distributed/expert_parallel/moonep_context.py 42.3% 57-61,63,66-68,86-91,93-95,97,101,104-105,107-108,111-113,129,153,155
hyper_parallel/distributed/expert_parallel/moonep_planner.py 98.9% 62
hyper_parallel/distributed/module_binding.py 0.0% 170-172,174
hyper_parallel/trainer/base.py 100%  
hyper_parallel/trainer/callbacks/__init__.py 100%  
hyper_parallel/trainer/callbacks/moe_monitor_callback.py 100%  
hyper_parallel/components/losses/moe_aux_loss.py
49
50
51
52
53
54
55
56
57
        Unweighted mean over nonempty sequences. Empty or fully masked inputs
        return a differentiable zero, including when a local shard is empty.
    """
    if scores.ndim != 2 or selected_experts.ndim != 2 or scores.shape[0] != selected_experts.shape[0]:
        raise ValueError("scores and selected_experts must have shapes [T, E] and [T, K]")
    num_tokens, num_experts = scores.shape
    if num_sequences <= 0 or sequence_ids.shape != (num_tokens,) or sequence_ids.dtype != torch.long:
        raise ValueError("sequence_ids must be int64 [T] and num_sequences must be positive")
    top_k = selected_experts.shape[1]
55
56
57
58
59
60
61
62
63
    if num_sequences <= 0 or sequence_ids.shape != (num_tokens,) or sequence_ids.dtype != torch.long:
        raise ValueError("sequence_ids must be int64 [T] and num_sequences must be positive")
    top_k = selected_experts.shape[1]
    if not 0 < top_k <= num_experts:
        raise ValueError("top_k must be positive and no greater than num_experts")
    if token_mask is not None and (token_mask.shape != (num_tokens,) or token_mask.dtype != torch.bool):
        raise ValueError("token_mask must be a boolean tensor with shape [T]")
    scores = scores.float()
    probabilities = scores / scores.sum(dim=-1, keepdim=True).clamp_min(torch.finfo(torch.float32).tiny)
hyper_parallel/components/modules/moe/gate.py
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
        Balanced global expert IDs with the same shape, dtype and device.
        Learned routing weights are deliberately left unchanged by callers.
    """
    if indices.ndim != 2 or indices.dtype not in (torch.int32, torch.int64):
        raise ValueError("indices must be integer [tokens, top_k]")
    if any(isinstance(value, bool) or not isinstance(value, int) or value < 1
           for value in (num_experts, ep_size)) or num_experts % ep_size:
        raise ValueError("num_experts must be positive and divisible by the positive EP owner count")
    if not 1 <= indices.shape[1] <= num_experts:
        raise ValueError("top_k must be in [1, num_experts]")
    slots = torch.arange(indices.numel(), device=indices.device)
    local_experts = num_experts // ep_size
    fixed = (slots % ep_size) * local_experts + (slots // ep_size) % local_experts
    return fixed.reshape_as(indices).to(indices.dtype)
228
229
230
231
232
233
234
235
236
        """Apply training to the final expert IDs and their learned weights."""
        if self.router_fix_router:
            indices = balanced_expert_indices(indices, self.num_experts, self.router_ep_size)
        if scores is None:
            scores = routing_scores(logits, self.scoring_func) if self.training and self.aux_loss_coeff else logits
        weights = self._apply_router_training(
            hidden, scores, weights, indices, token_mask, sequence_ids, num_sequences, sequence_partition_groups,
        )
        return weights, indices
367
368
369
370
371
372
373
374
375
376
377
378
379
380
                                       sequence_ids=sequence_ids, num_sequences=num_sequences,
                                       sequence_partition_groups=sequence_partition_groups)
        if image_mask is not None and not image_mask.is_contiguous():
            raise ValueError("image_mask must be contiguous for native MegaGate")
        logits, weights, indices = self._native_forward(hidden_states, image_mask)
        weights, indices = self._finish_routing(
            hidden_states, logits, weights, indices, token_mask, sequence_ids,
            num_sequences, sequence_partition_groups,
        )
        return logits, weights, indices

    @classmethod
    def from_module(cls, module: nn.Module, **configuration: Any) -> MegaGateModule:
        """Retain declared settings without configuration overrides.
hyper_parallel/components/modules/moe/grouped_experts/ep/ep_grouped_experts.py
100
101
102
103
104
105
106
107
108
        """
        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,
                                        overlap_compute=overlap_compute)

    def combine(
        self, values: Tensor, send_splits: list[int] | None, recv_splits: list[int] | None, recv_inverse: Tensor | None,
121
122
123
124
125
126
127
128
129
            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,
                                       overlap_compute=overlap_compute)

    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
42
43
44
45
46
47
48
49
50
            raise ValueError(
                "MegaKernel supports SwiGLU with optional swiglu_limit, not arbitrary activation callables"
            )
        if dispatch_mode not in ("push", "pull"):
            raise ValueError("Mega dispatch_mode must be push or pull")
        self.config = config
        self.tuning = {"dispatch_mode": dispatch_mode, "initial_capacity_factor": initial_capacity_factor,
                       "capacity_growth_factor": capacity_growth_factor}
        self.executor = None
55
56
57
58
59
60
61
62
        Args:
            group: Job-owned process group with contiguous expert ownership.
        """
        if self.executor is not None:
            return
        # The optional accelerator package is loaded only for an explicitly selected Mega member.
        from hyper_multicore import MegaMoeExperts, MegaMoeNumericsOptions  # pylint: disable=C0415
        from hyper_multicore.experimental import MegaMoeTuningOptions  # pylint: disable=C0415
106
107
108
109
110
111
112
113
114


def _validate_mega_layout(*, module, sharding, context) -> None:
    if context.axis_sizes["ep"] <= 1:
        raise ValueError("MegaMoE requires EP>1; use ordinary GroupedExperts for EP=1")
    validate_ep_layout(module=module, sharding=sharding, context=context)


class EPMegaGroupedExperts(GroupedExpertsModule):
176
177
178
179
180
181
182
183
184

    def _bound_runtime(self) -> tuple[_MegaExpertsRuntime, Any]:
        """Return the native holder and EP group after parallel binding."""
        if not self._parallel_bound:
            raise RuntimeError("bind_parallel must run before preparing MegaKernel runtimes")
        return self._runtime, self._ep_group

    @classmethod
    def prepare_runtime_group(cls, experts: list["EPMegaGroupedExperts"]) -> None:
hyper_parallel/components/modules/moe/grouped_experts/ep/moonep_grouped_experts.py
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102

        Returns:
            Routed token outputs [...,H]; routing weights are applied exactly once.
        """
        if self.ep_context is None:
            raise ValueError("MoonEP experts must be bound before forward")
        first = kwargs.pop("overlap_compute", None)
        second = kwargs.pop("combine_overlap_compute", None)
        topk_ids, topk_weights = match_grouped_experts_inputs(topk_ids, topk_weights, kwargs)
        output_shape = tuple(hidden_states.shape)
        hidden_states = self.validate_and_flatten_inputs(hidden_states, topk_ids, topk_weights)
        hidden, ids, _, weights, source_inverse = self.permute(hidden_states, topk_ids, topk_weights)
        plan = self.ep_context.plan(ids)
        gate, down = self.gate_up_proj, self.down_proj
        gate = gate.to_local() if isinstance(gate, DTensor) else gate
        down = down.to_local() if isinstance(down, DTensor) else down
        gate, down = self.ep_context.expert_weights(gate, down, plan)
        hidden, counts, weights, receive_inverse = self.ep_context.dispatch(
            hidden, weights, plan=plan, overlap_compute=first,
        )
        values = self.compute_experts(hidden, counts, gate, down, weights)
        values = self.ep_context.combine(values, plan, receive_inverse, overlap_compute=second)
        return self.unpermute(values, source_inverse, topk_weights, output_shape)

    def parallel_module_spec(self) -> ParallelModuleSpec:
        """Declare fixed home ownership and the collective MoonEP protocol."""
        return ParallelModuleSpec(
hyper_parallel/components/modules/moe/grouped_experts/grouped_experts.py
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
        if self.routing_weight_mode not in ("output", "before_fc2"):
            raise ValueError("routing_weight_mode must be output or before_fc2")
        top_k_type = type(self.top_k)
        if self.top_k is not None and (top_k_type is not int or not 1 <= self.top_k <= self.num_experts):
            raise ValueError("top_k must be a positive integer no greater than num_experts")
        object.__setattr__(self, "swiglu_limit", _normalize_swiglu_limit(self.swiglu_limit))
        if self.activation is not None and self.swiglu_limit is not None:
            raise ValueError("declare either a custom activation or swiglu_limit")


_EXPERT_CONFIG_KEYS = {
    "num_experts": ("num_experts", "num_local_experts", "n_routed_experts"),
350
351
352
353
354
355
356
357
358
            Activations, counts, probabilities, then three None values for absent EP transport.
        """
        del expert_ids
        if overlap_compute is not None:
            overlap_compute()
        return hidden_states, tokens_per_expert, routing_weights, None, None, None

    def compute_experts(
        self, hidden_states: Tensor, tokens_per_expert: Tensor, gate_up_proj: Tensor, down_proj: Tensor,
421
422
423
424
425
426
427
428
429
            The original slot outputs [S,H].
        """
        del send_splits, recv_splits, recv_inverse
        if overlap_compute is not None:
            overlap_compute()
        return values

    def unpermute(
        self, values: Tensor, unpermute_indices: Tensor, topk_weights: Tensor, output_shape: tuple[int, ...],
hyper_parallel/components/modules/moe/moe_utils.py
72
73
74
75
76
77
78
79
80
81
82
83
84
        context: Existing logical topology.
    """
    del context
    if set(sharding.params) != {name for name, _ in module.named_parameters()}:
        raise ValueError("router requires complete parameter ownership")
    if any(value != Replicate() for axes in sharding.params.values() for value in axes.values()):
        raise ValueError("router parameters must be replicated across computation axes")
    if sharding.is_boundary or sharding.in_src or sharding.in_dst or sharding.out_src or sharding.out_dst:
        raise ValueError("router token redistribution belongs to the containing MoE")


class _AccumulateRouterLoad(torch.autograd.Function):
    """Count a training microbatch once, even when its forward is recomputed."""
155
156
157
158
159
160
161
162
163
    # differences before the sign update.
    direction = (total - counts * num_experts).sign()
    delta = (update_rate * direction.float()).to(device=bias.device, dtype=bias.dtype)
    if isinstance(bias, DTensor):
        delta = distribute_tensor(delta, bias.device_mesh, bias.placements)
    bias.add_(delta)


def sync_and_update_expert_bias(
hyper_parallel/components/modules/moe/router.py
71
72
73
74
75
76
77
78
79
80
81
82
83
84
    @staticmethod
    def _validate_dimensions(source: Any, dim: int) -> None:
        for name, value in (("dim", dim), ("num_experts", source.num_experts), ("top_k", source.top_k)):
            if isinstance(value, bool) or not isinstance(value, int) or value < 1:
                raise ValueError(f"{name} must be a positive integer")
        if source.top_k > source.num_experts:
            raise ValueError("top_k cannot exceed num_experts")
        if (isinstance(source.route_scale, bool) or not isinstance(source.route_scale, (float, int))
                or not isfinite(source.route_scale)):
            raise ValueError("route_scale must be finite")

    @staticmethod
    def _validate_groups(source: Any) -> None:
        """Validate expert-group coverage and the number of selectable experts."""
112
113
114
115
116
117
118
119
120
            num_sequences: Number of logical samples when sequence_ids is provided.
            sequence_partition_groups: Override existing token-partition groups for aux-loss.
        """
        if x.ndim < 2 or x.shape[-1] != self.gate.in_features:
            raise ValueError("x must include tokens and end in dim")
        token_mask, sequence_ids = self._metadata(x, token_mask, sequence_ids)
        correction_bias = getattr(self, "bias", None)
        if correction_bias is not None:
            expert_bias = correction_bias if expert_bias is None else correction_bias + expert_bias
hyper_parallel/components/modules/moe/router_training.py
75
76
77
78
79
80
81
82
83
            return
        if counts is None:
            counts = torch.zeros(self.num_experts, dtype=torch.int64, device=weight.device)
        if counts.shape != (self.num_experts,) or counts.dtype != torch.int64 or counts.device != weight.device:
            raise ValueError("source tokens_per_expert must be int64 [num_experts] on the weight device")
        self.register_buffer("tokens_per_expert", counts, persistent=False)
        register_rebuildable_buffer(self, "tokens_per_expert", value=torch.zeros(
            self.num_experts, dtype=torch.int64, device="cpu",
        ))
 92
 93
 94
 95
 96
 97
 98
 99
100
                                     requires_grad=False)
        else:
            if (not isinstance(parameter, nn.Parameter) or parameter.shape != (self.num_experts,)
                    or parameter.dtype != torch.float32 or parameter.device != weight.device):
                raise ValueError("source bias must be an FP32 Parameter [num_experts] on the weight device")
            parameter.requires_grad_(False)
        self.register_parameter("bias", parameter)

    def _apply(self, fn: Any, recurse: bool = True) -> Any:
141
142
143
144
145
146
147
148
149
        dp_groups = tuple(device_mesh[name].get_group() for name in names
                          if name in ("dp", "dp_replicate", "dp_shard") and device_mesh[name].size() > 1)
        owners = binding.mesh_binding.axis_mesh("ep").size() if mesh.ep_size > 1 else 1
        if self.num_experts % owners:
            raise ValueError("router expert count must be divisible by the physical EP owner count")
        self.router_ep_size = owners
        self.router_tp_mesh = tp_mesh
        self.sequence_partition_groups = sequence_groups
        self.expert_bias_update_groups = dp_groups + sequence_groups
182
183
184
185
186
187
188
189
190
            sequence_ids = torch.arange(num_sequences, device=hidden.device).repeat_interleave(hidden.shape[-2])
            num_sequences = max(1, num_sequences)
        elif (sequence_ids.shape != hidden.shape[:-1] or sequence_ids.dtype != torch.int64
              or sequence_ids.device != hidden.device or num_sequences is None):
            raise ValueError("sequence_ids must be local int64 token metadata with num_sequences")
        return sequence_load_balancing_loss(
            scores, indices, sequence_ids.reshape(-1), num_sequences, valid,
            self.sequence_partition_groups if groups is None else groups,
        )
199
200
201
202
203
204
205
206
207
        """
        del num_recomputations
        rate = self.expert_bias_update_rate if lr is None else lr
        if isinstance(rate, bool) or not isinstance(rate, (int, float)) or not isfinite(rate) or rate < 0:
            raise ValueError("lr must be finite and nonnegative")
        rate = float(rate)
        if self.enable_expert_bias:
            update_router_bias(self.bias, self.tokens_per_expert, rate)
        if self.tokens_per_expert is not None:
hyper_parallel/components/modules/moe/shared_expert_overlap.py
58
59
60
61
62
63
64
65
66
    def compute_fc2() -> None:
        """Keep both phases inside normal module calls, retaining module/FSDP hooks."""
        nonlocal intermediate, shared_output
        if intermediate is None:
            raise RuntimeError("shared FC2 requires this invocation's completed FC1")
        shared_output = shared(intermediate, stage="fc2")
        intermediate = None

    routed = experts(hidden_states, topk_ids, topk_weights,
65
66
67
68
69
70

    routed = experts(hidden_states, topk_ids, topk_weights,
                     overlap_compute=compute_fc1, combine_overlap_compute=compute_fc2)
    if shared_output is None:
        raise RuntimeError("the transport must execute both shared phases before returning")
    return routed, shared_output
hyper_parallel/distributed/expert_parallel/ep_context.py
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
        *, overlap_compute: Callable[[], None] | None = None,
    ) -> Tensor:
        """Restore peer-major rows and send the outputs back to their source."""
        if overlap_compute is not None and not callable(overlap_compute):
            raise ValueError("overlap_compute must be a callable or None")
        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)
        returned = self._exchange(values, recv_splits, send_splits, async_op=overlap_compute is not None)
        self._run_overlap(overlap_compute, returned)
136
137
138
139
140
141
142
143
144
            owner-local expert-major rows [R]. The caller retains them for combine.
        """
        _validate_slot_inputs(hidden_states, expert_ids, routing_weights)
        if overlap_compute is not None and not callable(overlap_compute):
            raise ValueError("overlap_compute must be a callable or None")
        ids = expert_ids.to(torch.int64)
        # Fixed-size counting rejects invalid/drop IDs on device and retains empty experts.
        global_counts = ids.new_zeros(self.num_experts).scatter_add_(0, ids, torch.ones_like(ids))
        counts = global_counts.reshape(self.mesh.size(), self.local_experts).sum(dim=1)
hyper_parallel/distributed/expert_parallel/moonep_context.py
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72

        Returns:
            Per-call transport splits, permutations and compute-table counts.
        """
        ids = expert_ids.to(torch.int64)
        counts = ids.new_zeros(self.num_experts).scatter_add_(0, ids, torch.ones_like(ids))
        gathered = [torch.empty_like(counts) for _ in range(self.mesh.size())]
        if self.mesh.size() > 1:
            dist.all_gather(gathered, counts, group=self.mesh.get_group())
        else:
            gathered[0] = counts
        # The collective baseline plans on small integer histograms, like PR #1485.
        # This eager synchronization is not the official fused device planner.
        global_counts = torch.stack(gathered).cpu().numpy()
        allocation = select_allocation(global_counts, self.replica_capacity)
        return compile_plan(global_counts, allocation, ids, self.rank)

    def dispatch(
        self, hidden_states: Tensor, routing_weights: Tensor | None = None,
        *, plan: dict, overlap_compute: Callable[[], None] | None = None,
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
        Returns:
            Compute-major activations [R,H], counts [C], optional probabilities [R],
            and the receiver inverse permutation [R]. C includes home and remote rows.
        """
        send, receive, order = plan["token_send"], plan["token_recv"], plan["source_order"]
        asynchronous = overlap_compute is not None
        hidden = self._exchange(hidden_states.index_select(0, order), send, receive, async_op=asynchronous)
        weights = None
        if routing_weights is not None:
            weights = self._exchange(routing_weights.index_select(0, order).unsqueeze(-1), send, receive,
                                     async_op=asynchronous).reshape(-1)
        self._run_overlap(overlap_compute, hidden, weights)
        counts, receive_order = plan["counts"], plan["receive_order"]
        if hidden.shape[0] and hidden.device.type == "npu":
            # torch_npu is optional for CPU import and planning tests.
            from hyper_parallel.components.functional.moe_token_permute import (  # pylint: disable=C0415
                moe_token_permute,
            )

            rows = torch.arange(counts.numel(), device=counts.device).repeat_interleave(
                counts, output_size=hidden.shape[0],
            )
            ids = torch.empty_like(rows).scatter_(0, receive_order, rows)
            hidden, inverse = moe_token_permute(hidden.contiguous(), ids.to(torch.int32).unsqueeze(-1))
        else:
            hidden = hidden.index_select(0, receive_order)
            inverse = torch.empty_like(receive_order, dtype=torch.int32).scatter_(
                0, receive_order, torch.arange(receive_order.numel(), device=receive_order.device, dtype=torch.int32),
            )
        if weights is not None:
            weights = weights.index_select(0, receive_order)
        return hidden, counts, weights, inverse

    def expert_weights(self, gate_up: Tensor, down: Tensor, plan: dict) -> tuple[Tensor, Tensor]:
        """Exchange only needed replicas using differentiable all-to-all.
125
126
127
128
129
130
131
132
133
            returns replica gradients to home before the original Parameters' hooks.
            No Parameter, FSDP storage state or process group is created here.
        """
        if not plan["weight_exchange"]:
            return gate_up, down
        indices = plan["send_experts"]
        packet = torch.cat((gate_up.index_select(0, indices).flatten(1),
                            down.index_select(0, indices).flatten(1)), dim=1)
        remote = self._exchange(packet, plan["weight_send"], plan["weight_recv"])
149
150
151
152
153
154
155

        Returns:
            Source expert-major outputs [S,H], before the algorithm's final unpermute.
        """
        values = self._combine_slots(values, plan["token_send"], plan["token_recv"], recv_inverse,
                                     overlap_compute=overlap_compute)
        return values.index_select(0, plan["source_inverse"].to(torch.int64))
hyper_parallel/distributed/expert_parallel/moonep_planner.py
58
59
60
61
62
63
64
65
66
                allocation[logical_id, owner] -= amount
                remaining[expert] -= amount
                quota -= amount
                if remaining[expert] == 0:
                    position += 1
    return allocation


def select_allocation(counts: np.ndarray, replica_capacity: int | None = None) -> np.ndarray:
hyper_parallel/distributed/module_binding.py
166
167
168
169
170
171
172
173
174
175
176
177
178
    """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")
    mesh = mesh_binding.axis_mesh("ep")
    if moonep:
        return MoonEPContext(mesh, num_experts=parallel.options["num_experts"],
                             replica_capacity=parallel.options.get("moonep_replica_capacity"))
    return EPContext(mesh, 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.