Diff Coverage

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

Source File Diff Coverage (%) Missing Lines
hyper_parallel/components/losses/moe_aux_loss.py 19.4% 52-68,71,74-80
hyper_parallel/components/modules/module_family.py 0.0% 223
hyper_parallel/components/modules/moe/gate.py 15.6% 70,98-100,102-108,140,161,176-178,206-209,212,217,229-233,236,259,272-273,277,282-284,296-298,307,317-320,322-323,327-328,357-358,362,366,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 25.5% 39-42,45-48,50,58-59,61-62,64-65,74-77,82-84,97,99,103-105,109-111,134-135,139-140,148-160,164,171-174,179-181,190-203,207,222-226,228
hyper_parallel/components/modules/moe/grouped_experts/ep/moonep_grouped_experts.py 9.5% 48-49,80-93,96-98
hyper_parallel/components/modules/moe/grouped_experts/grouped_experts.py 21.9% 41-47,51,93-98,353-354,391-393,396-397,399,424-425,481
hyper_parallel/components/modules/moe/grouped_experts/grouped_experts_family.py 20.0% 57-58,63,67
hyper_parallel/components/modules/moe/moe_utils.py 31.7% 43-49,61-62,74-80,96-98,108-110,128-131,134-136,152-153,156-160,220-225,227
hyper_parallel/components/modules/moe/router.py 32.4% 45,59,63-65,69,73-78,80,115-121,131-133
hyper_parallel/components/modules/moe/router_training.py 21.7% 37-42,54-58,61-77,80-81,85-87,90,92-94,98-99,102,108-111,113,117,128-137,139-145,149,157,159-163,166-170,176-180,182-183,196-203
hyper_parallel/components/modules/moe/shared_expert.py 15.0% 226,263-271,273-282,348,352,363-364,387-396
hyper_parallel/components/modules/moe/shared_expert_overlap.py 11.5% 40-50,52,55-56,58,61-64,66,68-70
hyper_parallel/components/modules/runtime.py 31.8% 27-31,33-37,46-47,56-58
hyper_parallel/distributed/expert_parallel/ep_context.py 17.8% 62-63,69-77,84-94,96,100-105,139-140,147-149,152,154,196
hyper_parallel/distributed/expert_parallel/moonep_context.py 21.2% 42-46,57-61,63,66-68,86-91,93-95,97,101,104-105,107-108,111-113,128-131,133-135,153,155
hyper_parallel/distributed/expert_parallel/moonep_planner.py 6.9% 32-43,45-63,76-85,87-89,92-94,109-113,118-120,122-131,135-141,143-145,147-151,154
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
    Returns:
        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]
    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)
    valid = torch.ones(num_tokens, device=scores.device, dtype=torch.float32)
    if token_mask is not None:
        valid = token_mask.to(dtype=torch.float32)
    indices = sequence_ids.unsqueeze(-1) * num_experts + selected_experts
    counts = scores.new_zeros(num_sequences * num_experts).scatter_add(
        0, indices.reshape(-1), valid.unsqueeze(-1).expand(-1, top_k).reshape(-1),
    ).view(num_sequences, num_experts)
    probability_sum = scores.new_zeros(num_sequences, num_experts).index_add(
        0, sequence_ids, probabilities * valid.unsqueeze(-1),
    )
    for group in sequence_partition_groups:
        dist.all_reduce(counts, group=group)
        probability_sum = differentiable_all_reduce(probability_sum, "sum", group)
    assignments = counts.sum(dim=-1, keepdim=True)
    token_count = (assignments / top_k).clamp_min(1.0)
    losses = num_experts * ((counts / assignments.clamp_min(1.0)) * (probability_sum / token_count)).sum(-1)
    return losses.sum() / (assignments > 0).sum().clamp_min(1)
hyper_parallel/components/modules/module_family.py
219
220
221
222
223
224
225
226
227
    if required not in signature.parameters:
        raise TypeError(f"member {member.variant!r} must explicitly accept {required}")
    # FamilyRequest checks public names; family validation sees every option before this point.
    # Members need not declare options used only by another implementation in the family.
    kwargs = {name: value for name, value in member.arguments.items() if name in signature.parameters}
    runtime = {"config": config, "module": module, "module_fqn": fqn, "context": context}
    kwargs.update({name: value for name, value in runtime.items() if name in signature.parameters})
    signature.bind(**kwargs)
    return kwargs
hyper_parallel/components/modules/moe/gate.py
66
67
68
69
70
71
72
73
74
        raise ValueError("top_k must be an integer in [1, num_experts]")
    if (isinstance(routed_scaling_factor, bool) or not isinstance(routed_scaling_factor, (int, float))
            or not isfinite(routed_scaling_factor)):
        raise ValueError("routed_scaling_factor must be finite")
    if not all((isinstance(normalize_topk, bool), isinstance(sorted_indices, bool))):
        raise TypeError("normalize_topk and sorted_indices must be bool")
    selection = scores
    if correction_bias is not None:
        if (correction_bias.device != scores.device or not correction_bias.is_floating_point()
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
    Returns:
        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)


class GateModule(RouterTrainingMixin, nn.Module):
    """Own common gate configuration, projection state, initialization and routing math.
136
137
138
139
140
141
142
143
144
                    or tuple(weight.shape) != (self.num_experts, self.hidden_size)):
                raise ValueError("source weight must be a floating Parameter [num_experts, hidden_size]")
            self.weight = weight
            self.train(module.training)
        self._init_router_training(source, context, self.weight, module)

    def _set_routing_settings(self, source: Any) -> None:
        """Validate dimensions, scoring, TopK normalization and initialization policy."""
        for name in ("hidden_size", "num_experts", "top_k"):
157
158
159
160
161
162
163
164
165
                or not isfinite(self.routed_scaling_factor)):
            raise ValueError("routed_scaling_factor must be finite")
        self.normalize_topk = getattr(source, "normalize_topk", self.top_k > 1)
        self.sorted_indices = getattr(source, "sorted_indices", False)
        if not all((isinstance(self.normalize_topk, bool), isinstance(self.sorted_indices, bool))):
            raise TypeError("normalize_topk and sorted_indices must be bool")
        self.initializer_range = source.initializer_range
        if (isinstance(self.initializer_range, bool) or not isinstance(self.initializer_range, (int, float))
                or not isfinite(self.initializer_range) or self.initializer_range < 0):
172
173
174
175
176
177
178
179
180
181

    def reset_parameters(self) -> None:
        """Initialize the projection after direct/meta construction."""
        nn.init.normal_(self.weight, std=self.initializer_range)
        bias = getattr(self, "bias", None)
        if bias is not None:
            nn.init.zeros_(bias)

    def make_transforms(self) -> list:
        """Declare that this member keeps parameter names and layouts unchanged.
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
            sequence_partition_groups: Override existing token-partition groups for aux-loss.
        """
        if hidden_states.ndim < 2 or hidden_states.shape[-1] != self.hidden_size:
            raise ValueError("hidden_states must end in hidden_size and include a token dimension")
        token_mask, sequence_ids = self._metadata(hidden_states, token_mask, sequence_ids)
        own_bias = getattr(self, "bias", None)
        if own_bias is not None:
            correction_bias = own_bias if correction_bias is None else own_bias + correction_bias
        logits = F.linear(  # pylint: disable=not-callable
            hidden_states.reshape(-1, self.hidden_size).float(), self.weight.float())
        scores = routing_scores(logits, self.scoring_func)
        weights, indices = select_topk_scores(
            scores, top_k=self.top_k, correction_bias=correction_bias,
            routed_scaling_factor=self.routed_scaling_factor,
            normalize_topk=self.normalize_topk, sorted_indices=self.sorted_indices)
        weights, indices = self._finish_routing(
            hidden_states, logits, weights, indices, token_mask, sequence_ids,
            num_sequences, sequence_partition_groups, scores=scores,
        )
        return logits, weights, indices
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
                        sequence_ids: torch.Tensor | None, num_sequences: int | None,
                        sequence_partition_groups: tuple | None, *, scores: torch.Tensor | None = None,
                        ) -> tuple[torch.Tensor, torch.Tensor]:
        """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


@lru_cache(maxsize=None)
def _plan_for_device(device: torch.device) -> Any:
255
256
257
258
259
260
261
262
263

    def __init__(self, *, config: Any = None, module: nn.Module | None = None,
                 module_fqn: str = "", context: Mapping[str, Any] | None = None) -> None:
        """Construct or adopt the public MegaGate without accepting model-specific subclasses."""
        del module_fqn
        if (config is None) == (module is None):
            raise ValueError("provide exactly one of config or module")
        if module is not None:
            self._validate_source(module)
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
        vision_enabled = (getattr(source, "vision_enabled", False)
                          if config is not None else getattr(source, "bias_vl", None) is not None)
        if not isinstance(vision_enabled, bool):
            raise TypeError("vision_enabled must be bool")
        super().__init__(config=config, module=module, context=context)
        self._initialize_correction_state(module, vision_enabled)

    def _initialize_correction_state(self, module: nn.Module | None, vision_enabled: bool) -> None:
        """Initialize or adopt the fused backend's text and optional image biases."""
        vision_enabled = vision_enabled or getattr(self, "bias_vl", None) is not None
        for name in ("bias", "bias_vl"):
            if name == "bias_vl" and not vision_enabled:
                self.register_parameter(name, None)
                continue
            existing = getattr(self, name, None)
            if existing is not None:
                continue
            if module is None:
                parameter = nn.Parameter(torch.zeros(self.num_experts, dtype=torch.float32, device=self.weight.device))
            else:
                parameter = getattr(module, name, None)
292
293
294
295
296
297
298
299
300
301
302
            setattr(self, name, parameter)

    def reset_parameters(self) -> None:
        """Reset common projection/bias and the fused variant's optional vision bias."""
        super().reset_parameters()
        if getattr(self, "bias_vl", None) is not None:
            nn.init.zeros_(self.bias_vl)

    @classmethod
    def _validate_source(cls, module: nn.Module) -> None:
        if module.__class__ is cls:
303
304
305
306
307
308
309
310
311
            return
        if not module.__class__.__module__.startswith("hyper_multicore.modules.mega_gate"):
            raise TypeError("MegaGate family accepts only the public MegaGate; use a model adapter for other routers")
        # Existing HyperMulticore modules remain valid sources; this is not a base class.
        from hyper_multicore.modules.mega_gate import (  # pylint: disable=import-outside-toplevel
            MegaGate as SourceMegaGate,
        )

        if module.__class__ is not SourceMegaGate:
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332

    def _torch_forward(self, hidden_states: torch.Tensor,
                       image_mask: torch.Tensor | None, **metadata: Any) -> tuple[torch.Tensor, ...]:
        """Keep fused vision selection local to this variant; training counts stay standard."""
        if image_mask is None:
            return super().forward(hidden_states, **metadata)
        correction_bias = torch.where(image_mask.reshape(-1, 1), self.bias_vl, self.bias)
        logits = F.linear(  # pylint: disable=not-callable
            hidden_states.reshape(-1, self.hidden_size).float(), self.weight.float())
        scores = routing_scores(logits, self.scoring_func)
        weights, indices = select_topk_scores(
            scores, top_k=self.top_k, correction_bias=correction_bias,
            routed_scaling_factor=self.routed_scaling_factor,
            normalize_topk=self.normalize_topk, sorted_indices=self.sorted_indices)
        weights, indices = self._finish_routing(hidden_states, logits, weights, indices, scores=scores, **metadata)
        return logits, weights, indices

    def _native_forward(self, hidden_states: torch.Tensor,
                        image_mask: torch.Tensor | None) -> tuple[torch.Tensor, ...]:
        # Only the fused execution path requires the optional native package.
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
            sequence_partition_groups: Override token-partition groups for aux-loss.
        """
        if hidden_states.ndim < 2 or hidden_states.shape[-1] != self.hidden_size:
            raise ValueError("hidden_states must end in hidden_size and include a token dimension")
        token_mask, sequence_ids = self._metadata(hidden_states, token_mask, sequence_ids)
        image_mask = local_router_metadata(image_mask, hidden_states, self.router_tp_mesh)
        if image_mask is not None:
            if self.bias_vl is None:
                raise ValueError("image_mask requires vision_enabled=True when constructing MegaGate")
            if (image_mask.shape != hidden_states.shape[:-1] or image_mask.dtype != torch.bool
                    or image_mask.device != hidden_states.device):
                raise ValueError("image_mask must be BOOL [batch, sequence] on the hidden_states device")
        if self.scoring_func != "sqrtsoftplus" or hidden_states.device.type != "npu" or hidden_states.numel() == 0:
            return self._torch_forward(hidden_states, image_mask, token_mask=token_mask,
                                       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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
    def __init__(self, config: Any, *, dispatch_mode: str = "push",
                 initial_capacity_factor: float | None = None,
                 capacity_growth_factor: float | None = None) -> None:
        """Record algorithm facts and the existing Mega transport options."""
        if config.top_k is None:
            raise ValueError("MegaKernel requires config.top_k from the model or explicit standalone config")
        if config.activation is not None:
            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

    def configure(self, group: Any) -> None:
        """Borrow the existing ordered EP group and the upstream numerical implementation.
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69

        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

        config = self.config
        executor = MegaMoeExperts(
            hidden_size=config.hidden_size, intermediate_size=config.intermediate_size,
            num_experts=config.num_experts, top_k=config.top_k, ep_group=group,
            numerics_options=MegaMoeNumericsOptions(
                swiglu_limit=config.swiglu_limit, clamp_after_silu=False,
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
                apply_probs_before_fc2=config.routing_weight_mode == "before_fc2",
            ),
            tuning_options=MegaMoeTuningOptions(**self.tuning),
        )
        if any(True for _ in executor.parameters()):
            executor.close()
            raise RuntimeError("MegaKernel requires the parameterless HyperMulticore executor API")
        self.executor = executor

    def __call__(self, hidden: Tensor, ids: Tensor, weights: Tensor,
                 gate_up: Tensor, down: Tensor) -> Tensor:
        """Pass current canonical weights directly; the native executor infers EOI layout."""
        if self.executor is None:
            raise RuntimeError("prepare_module_runtimes must run before MegaKernel forward")
        return self.executor(
            hidden, ids, weights,
            expert_weights=(gate_up, down),
        )
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
        Args:
            runtimes: Configured peers with compatible serial execution resources.
        """
        # The native package owns allocation, sharing and in-flight lifetime validation.
        from hyper_multicore import MegaMoeExperts  # pylint: disable=C0415

        MegaMoeExperts.share_execution_resources([runtime.executor for runtime in runtimes])

    def close(self) -> None:
        """Release native storage after its final reader has completed."""
        if self.executor is not None:
            self.executor.close()
            self.executor = None


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):
    """Run one fused token-level call; the kernel owns its transport and restoration."""
130
131
132
133
134
135
136
137
138
139
140
141
142
143
            dispatch_mode: Existing Mega push or pull transport policy.
            initial_capacity_factor: Optional push receive-capacity factor.
            capacity_growth_factor: Optional push growth factor.
        """
        super().__init__(config=config, module=module, module_fqn=module_fqn, context=context)
        self._runtime = _MegaExpertsRuntime(
            self.config, dispatch_mode=dispatch_mode, initial_capacity_factor=initial_capacity_factor,
            capacity_growth_factor=capacity_growth_factor,
        )
        self._ep_group: Any = None
        self._parallel_bound = False

    def bind_parallel(self, binding: ParallelBinding) -> None:
        """Borrow the actual expert group; preserve the existing fused backend limits.
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167

        Args:
            binding: Existing job topology; no new process group or ordinary EPContext.
        """
        mesh = binding.mesh_binding.mesh_context
        if mesh.ep_size <= 1:
            raise ValueError("MegaMoE requires EP>1; use ordinary GroupedExperts for EP=1")
        if mesh.pp_size > 1:
            raise ValueError("the existing MegaMoe lifecycle requires PP=1")
        if mesh.tp_size > 1 and not mesh.sequence_parallel:
            raise ValueError("MegaMoe with dense TP requires EP>1 and sequence_parallel=true")
        axis = binding.mesh_binding.axis_mesh("ep")
        group = axis.get_group()
        if self._parallel_bound and self._ep_group is not group:
            raise ValueError("MegaKernel already has a different communication owner")
        self._ep_group = group
        self._parallel_bound = True

    def parallel_module_spec(self) -> ParallelModuleSpec:
        """Declare canonical ownership and a fused token-level protocol."""
        return ParallelModuleSpec(
            protocol="grouped_experts.forward.mega", binding_kind="mesh",
            stages={"forward": ("hidden_states", "topk_ids", "topk_weights")}, validate=_validate_mega_layout,
        )
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
        )

    def runtime_group_key(self) -> tuple:
        """Group only serial native executors with compatible scratch requirements."""
        config = self.config
        if not self._parallel_bound:
            raise RuntimeError("bind_parallel must run before preparing MegaKernel runtimes")
        return (type(self), self._ep_group, config, self.gate_up_proj.device, self.gate_up_proj.dtype,
                tuple(self._runtime.tuning.items()))

    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:
        """Configure after materialization and share scratch across compatible serial layers.
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211

        Args:
            experts: Peers with the same runtime_group_key, before their first forward.
        """
        peers = [cls._bound_runtime(expert) for expert in experts]
        if all(runtime.executor is not None for runtime, _ in peers):
            return
        created = []
        try:
            for runtime, group in peers:
                if runtime.executor is None:
                    runtime.configure(group)
                    created.append(runtime)
            _MegaExpertsRuntime.share([runtime for runtime, _ in peers])
        except Exception:
            for runtime in created:
                runtime.close()
            raise

    def close_runtime(self) -> None:
        """Close this native executor after its final backward."""
        self._runtime.close()

    def forward(self, hidden_states: Tensor, topk_ids: Tensor | None = None,
                topk_weights: Tensor | None = None, **kwargs: Tensor) -> Tensor:
        """Keep original token routes and current FSDP-restored parameters in one fused call.
218
219
220
221
222
223
224
225
226
227
228

        Returns:
            Expert contributions restored to the original hidden_states shape.
        """
        topk_ids, topk_weights = match_grouped_experts_inputs(topk_ids, topk_weights, kwargs)
        self.validate_and_flatten_inputs(hidden_states, topk_ids, topk_weights)
        if topk_ids.shape[1] != self.config.top_k:
            raise ValueError("MegaKernel top-k width must match its configured native executor")
        parameters = tuple(value.to_local() if isinstance(value, DTensor) else value
                           for value in (self.gate_up_proj, self.down_proj))
        return self._runtime(hidden_states, topk_ids, topk_weights, *parameters)
hyper_parallel/components/modules/moe/grouped_experts/ep/moonep_grouped_experts.py
44
45
46
47
48
49
50
51
52
53
            module_fqn: Source expert boundary for replacement metadata.
            context: Builder-provided model configuration and initialization facts.
            moonep_replica_capacity: Remote expert slots per rank; None means E/EP.
        """
        super().__init__(config=config, module=module, module_fqn=module_fqn, context=context)
        self.moonep_replica_capacity = moonep_replica_capacity
        self.ep_context: MoonEPContext | None = None

    def bind_parallel(self, binding: ParallelBinding) -> None:
        """Borrow the job-owned MoonEP context with matching home ownership.
 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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55


def _normalize_swiglu_limit(limit: Any) -> float | None:
    """Validate a source/config clamp and normalize disabled values once at construction."""
    if limit is None:
        return None
    if isinstance(limit, bool) or not isinstance(limit, (int, float)) or not math.isfinite(limit):
        raise ValueError("swiglu_limit/limit must be None or a finite number")
    if limit > 0:
        return limit
    warnings.warn(
        f"swiglu_limit/limit={limit} <= 0 disables clamping; using unclamped SwiGLU.",
        UserWarning, stacklevel=4,
    )
    return None


@dataclass(frozen=True)
class GroupedExpertsConfig:
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
            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")
        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"),
349
350
351
352
353
354
355
356
357
358
        Returns:
            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,
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
        # Empty ranks avoid unsupported empty GMM calls while retaining gradients to both weights.
        fc1 = (grouped_matmul(hidden, gate_up, group_list=group_list)  # pylint: disable=not-callable
               if hidden.shape[0] else hidden @ gate_up[0])
        activation = self.config.activation
        if self.config.swiglu_limit is not None:
            gate, up = fc1.chunk(2, dim=-1)
            activated = swiglu_activation(
                gate, up, limit=self.config.swiglu_limit, activation_dtype="float32",
            ).to(hidden.dtype)
        elif activation is not None:
            activated = activation(*fc1.chunk(2, dim=-1)).to(hidden.dtype)
        else:
            activated = npu_swiglu(fc1)
        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)
420
421
422
423
424
425
426
427
428
429
        Returns:
            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, ...],
477
478
479
480
481
482
        hidden, counts, weights, send_splits, recv_splits, recv_inverse = self.dispatch(
            hidden, ids, counts, weights, overlap_compute=overlap_compute,
        )
        values = self.compute_experts(hidden, counts, self.gate_up_proj, self.down_proj, weights)
        values = self.combine(values, send_splits, recv_splits, recv_inverse, overlap_compute=combine_overlap_compute)
        return self.unpermute(values, unpermute_indices, topk_weights, output_shape)
hyper_parallel/components/modules/moe/grouped_experts/grouped_experts_family.py
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
            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.axis_sizes["ep"] == 1 and any((member.selectors["megakernel"], member.selectors["moonep"])):
        warnings.warn(
            "megakernel=True or moonep=True requires EP>1; EP=1 falls back to ordinary GroupedExperts. "
            "Mega transport options are ignored.",
            UserWarning, stacklevel=3,
        )
    elif not member.selectors["megakernel"] and (
            member.arguments.get("dispatch_mode", "push") != "push"
            or member.arguments.get("initial_capacity_factor") is not None
            or member.arguments.get("capacity_growth_factor") is not None):
        raise ValueError("Mega transport options require megakernel=True")


def grouped_experts_sharding(
    *, module: nn.Module, module_fqn: str, member: ResolvedFamily, context: FamilyShardingContext,
hyper_parallel/components/modules/moe/moe_utils.py
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53

    Returns:
        Metadata matching exactly the router input token dimensions.
    """
    if tensor is None or tensor.shape == states.shape[:-1]:
        return tensor
    length = states.shape[-2]
    expected = (*states.shape[:-2], length * tp_mesh.size()) if tp_mesh is not None else None
    if expected is None or tuple(tensor.shape) != expected:
        raise ValueError("router metadata must match local or TP-gathered token dimensions")
    return tensor.narrow(-1, tp_mesh.get_local_rank() * length, length)


def router_sharding(*, module: nn.Module, module_fqn: str, member: Any, context: Any) -> ModuleShardingSpec:
    """Declare complete replicated router state without another token boundary.
57
58
59
60
61
62
63
64
65
66
        module_fqn: Diagnostic path supplied by the family builder.
        member: Resolved family member.
        context: Existing logical topology.
    """
    del module_fqn, member, context
    return ModuleShardingSpec(params={name: {} for name, _ in module.named_parameters()},
                              in_src={}, in_dst={}, is_boundary=False)


def validate_router_layout(*, module: nn.Module, sharding: ModuleShardingSpec, context: Any) -> None:
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
        module: Router owning projection and optional correction state.
        sharding: Final family layout after user overrides.
        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."""
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
            weights: Routing-weight gradient carrier.
            counts: Immutable local microbatch counts.
        accumulator: Integer step-level expert counts.
        """
        ctx.save_for_backward(counts)
        ctx.accumulator = accumulator
        return weights

    @staticmethod
    def backward(ctx: Any, gradient: torch.Tensor) -> tuple[torch.Tensor, None, None]:
        """Accumulate integer counts without retaining the model graph.
104
105
106
107
108
109
110
111
112
113
114
        Args:
            ctx: Context saved by forward.
            gradient: Unchanged gradient for the routing weights.
        """
        with SkipDTensorDispatch(), torch.no_grad():
            ctx.accumulator.add_(ctx.saved_tensors[0])
        return gradient, None, None



def accumulate_router_load(
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
        selected_experts: Actual selected indices, shaped [T, K].
        token_mask: Boolean token mask; true tokens contribute.
        accumulator: Integer [E] step counter.
    """
    selected_experts = selected_experts.to(torch.int64)
    num_tokens, top_k = selected_experts.shape
    valid = selected_experts.new_ones(num_tokens) if token_mask is None else token_mask.reshape(-1).long()
    counts = torch.zeros_like(accumulator).scatter_add(
        0, selected_experts.reshape(-1), valid.unsqueeze(-1).expand(-1, top_k).reshape(-1),
    )
    if torch.is_grad_enabled() and not weights.requires_grad:
        weights = weights.detach().requires_grad_()
    return _AccumulateRouterLoad.apply(weights, counts, accumulator)



@torch.no_grad()
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
        bias: Expert correction parameter [E], possibly sharded.
        counts: Global int64 expert assignment counts [E].
        update_rate: Nonnegative step size for the sign update.
    """
    num_experts = counts.shape[-1]
    total = counts.sum(dim=-1, keepdim=True)
    # Compare in integer arithmetic so rounding cannot erase small load
    # 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(
    moe: nn.Module,
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
        uses TP×CP×DP group synchronization for global batch statistics.
        Model adapters may provide ``expert_bias_update_groups`` and
        ``expert_bias_update_rate`` to override generic groups and update speed.
    """
    groups = getattr(moe, "expert_bias_update_groups", None)
    if groups is None:
        groups = (tp_group, cp_group, dp_group)
    for group in groups:
        if group is not None:
            dist.all_reduce(moe.tokens_per_expert, group=getattr(group, "group", group))

    moe.update_expert_bias(
        lr=getattr(moe, "expert_bias_update_rate", lr),
        num_recomputations=num_recomputations,
    )
hyper_parallel/components/modules/moe/router.py
41
42
43
44
45
46
47
48
49
        if (config is None) == (module is None):
            raise ValueError("provide exactly one of config or module")
        source = config if config is not None else module
        dim = config.dim if config is not None else module.gate.in_features
        self._validate_dimensions(source, dim)
        self._validate_groups(source)
        if source.score_func not in ("sigmoid", "softmax"):
            raise ValueError("score_func must be 'sigmoid' or 'softmax'")
        for name in ("num_experts", "top_k", "score_func", "num_expert_groups",
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
            self.gate = module.gate
            self.train(module.training)
        else:
            self.gate = nn.Linear(config.dim, config.num_experts, bias=False)
        self._init_router_training(source, context, self.gate.weight, module)

    def reset_parameters(self) -> None:
        """Reset owned correction state; the Linear child keeps its native initialization."""
        bias = getattr(self, "bias", None)
        if bias is not None:
            nn.init.zeros_(bias)

    def make_transforms(self) -> list:
        """Keep public router checkpoint names, including the native Linear child, unchanged."""
        return []

    @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."""
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
            sequence_ids: Int64 logical sample IDs for packed/partitioned sequences.
            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
        scores = routing_scores(self.gate(x.reshape(-1, x.shape[-1])).float(), self.score_func)
        if self.route_scale != 1.0:
            scores = scores * self.route_scale
        selection_scores = scores
        if self.num_expert_groups is not None:
127
128
129
130
131
132
133
134
135
136
137
        if expert_bias is not None:
            selection_scores = selection_scores + expert_bias.float()
        selected_experts = selection_scores.topk(self.top_k, dim=-1).indices
        top_scores = scores.gather(1, selected_experts)
        if self.router_fix_router:
            selected_experts = balanced_expert_indices(selected_experts, self.num_experts, self.router_ep_size)
        top_scores = self._apply_router_training(
            x, scores, top_scores, selected_experts, token_mask, sequence_ids,
            num_sequences, sequence_partition_groups,
        )
        counts = torch.bincount(selected_experts.flatten(), minlength=self.num_experts)
hyper_parallel/components/modules/moe/router_training.py
33
34
35
36
37
38
39
40
41
42
43
44
45
46
from hyper_parallel.models.materialization import register_rebuildable_buffer


def _setting(sources: tuple, names: tuple[str, ...], default: Any) -> Any:
    for source in sources:
        for name in names:
            value = source.get(name) if isinstance(source, Mapping) else getattr(source, name, None)
            if value is not None:
                return value
    return default


class RouterTrainingMixin:
    """Keep family-owned routing state independent of any model adapter or Trainer."""
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 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
103
104
105
106

    def _init_router_training(self, source: Any, context: Mapping[str, Any] | None,
                              weight: nn.Parameter, module: nn.Module | None = None) -> None:
        """Resolve router options and install state for backward accounting."""
        sources = (*tuple((context or {}).get("module_configs", ())), source)
        self.router_fix_router = _setting(sources, ("router_fix_router",), False)
        if not isinstance(self.router_fix_router, bool):
            raise ValueError("router_fix_router must be bool")
        for name, aliases in (
                ("aux_loss_coeff", ("router_aux_loss_coeff", "router_aux_loss_coef", "aux_loss_coeff")),
                ("expert_bias_update_rate", ("router_bias_update_rate", "expert_bias_update_rate"))):
            value = _setting(sources, aliases, 0.0)
            if isinstance(value, bool) or not isinstance(value, (int, float)) or not isfinite(value) or value < 0:
                raise ValueError(f"{aliases[0]} must be finite and nonnegative")
            setattr(self, name, float(value))
        self.enable_expert_bias = self.expert_bias_update_rate > 0
        self.last_aux_loss = None
        self.router_ep_size = 1
        self.router_tp_mesh = None
        self.sequence_partition_groups = ()
        self.expert_bias_update_groups = None
        counts = getattr(module, "tokens_per_expert", None)
        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",
        ))
        if self.enable_expert_bias:
            self._register_correction_state(module, weight)

    def _register_correction_state(self, module: nn.Module | None, weight: nn.Parameter) -> None:
        """Create or adopt the expert bias used for auxiliary-loss-free balancing."""
        parameter = getattr(module, "bias", None)
        if parameter is None:
            parameter = nn.Parameter(torch.zeros(self.num_experts, dtype=torch.float32, device=weight.device),
                                     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:
        """Keep selection correction state and its gradients FP32 during dtype conversion."""
        parameters = tuple(getattr(self, name, None) for name in self.fp32_parameter_names)
        protected = {id(value) for parameter in parameters if parameter is not None
                     for value in (parameter, parameter.grad) if value is not None}

        def apply(tensor: torch.Tensor) -> torch.Tensor:
            """Apply storage conversion while preserving correction precision.

            Args:
                tensor: Parameter, gradient or buffer visited by the module conversion.
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120

            Args:
                tensor: Parameter, gradient or buffer visited by the module conversion.
            """
            converted = fn(tensor)
            if id(tensor) not in protected or converted.dtype == torch.float32:
                return converted
            return converted.float() if tensor.is_meta else tensor.to(device=converted.device, dtype=torch.float32)

        return super()._apply(apply, recurse=recurse)

    def parallel_module_spec(self) -> ParallelModuleSpec:
        """Declare a replicated router that borrows existing statistics meshes."""
        return ParallelModuleSpec(
            protocol="moe.router.statistics", binding_kind="mesh",
            stages={"forward": (self._router_input_name,)}, validate=validate_router_layout,
        )
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153

        Args:
            binding: Job-owned mesh resources; no new process groups are created.
        """
        mesh = binding.mesh_binding.mesh_context
        device_mesh = mesh.device_mesh
        names = tuple(device_mesh.mesh_dim_names or ()) if device_mesh is not None else ()
        tp_partitioned = mesh.sequence_parallel or mesh.ep_size > 1
        tp_mesh = device_mesh["tp"] if "tp" in names and tp_partitioned else None
        sequence_axes = [device_mesh["cp"]] if "cp" in names else []
        if tp_mesh is not None:
            sequence_axes.append(tp_mesh)
        sequence_groups = tuple(axis.get_group() for axis in sequence_axes if axis.size() > 1)
        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

    def _metadata(self, hidden: torch.Tensor, token_mask: torch.Tensor | None,
                  sequence_ids: torch.Tensor | None) -> tuple:
        return tuple(local_router_metadata(value, hidden, self.router_tp_mesh)
                     for value in (token_mask, sequence_ids))

    def _apply_router_training(self, hidden: torch.Tensor, scores: torch.Tensor, weights: torch.Tensor,
                               indices: torch.Tensor, token_mask: torch.Tensor | None,
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
                               indices: torch.Tensor, token_mask: torch.Tensor | None,
                               sequence_ids: torch.Tensor | None,
                               num_sequences: int | None, groups: tuple | None) -> torch.Tensor:
        """Attach auxiliary gradients and count the routes consumed by backward."""
        if token_mask is not None and (token_mask.shape != hidden.shape[:-1] or token_mask.dtype != torch.bool
                                       or token_mask.device != hidden.device):
            raise ValueError("token_mask must be boolean and match local token shape and device")
        valid = None if token_mask is None else token_mask.reshape(-1)
        self.last_aux_loss = None
        if self.training and self.aux_loss_coeff:
            auxiliary = self._sequence_auxiliary(
                hidden, scores, indices, valid, sequence_ids, num_sequences, groups,
            )
            self.last_aux_loss = auxiliary.detach()
            weights = aux_loss_auto_scale(weights, auxiliary * self.aux_loss_coeff)
        if self.training and self.enable_expert_bias:
            weights = accumulate_router_load(weights, indices, token_mask, self.tokens_per_expert)
        return weights

    def _sequence_auxiliary(self, hidden: torch.Tensor, scores: torch.Tensor, indices: torch.Tensor,
                            valid: torch.Tensor | None, sequence_ids: torch.Tensor | None,
                            num_sequences: int | None, groups: tuple | None) -> torch.Tensor:
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
    def _sequence_auxiliary(self, hidden: torch.Tensor, scores: torch.Tensor, indices: torch.Tensor,
                            valid: torch.Tensor | None, sequence_ids: torch.Tensor | None,
                            num_sequences: int | None, groups: tuple | None) -> torch.Tensor:
        """Resolve token ownership and evaluate sequence load balancing."""
        if sequence_ids is None:
            num_sequences = prod(hidden.shape[:-2])
            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,
        )
192
193
194
195
196
197
198
199
200
201
202
203
        Args:
            lr: Override update speed, otherwise use the configured rate.
            num_recomputations: Compatibility argument; backward counters need no replay correction.
        """
        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)
        self.tokens_per_expert.zero_()
hyper_parallel/components/modules/moe/shared_expert.py
222
223
224
225
226
227
228
229
230
            raise ValueError("provide exactly one of config or module")
        if config is not None:
            if module is not None:
                raise ValueError("provide config or module, not both")
            self._initialize_from_config(config)
            return
        config = getattr(module, "config", None)
        self.config = config
        self._source_is_fused = all(
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
        self.train(module.training)

    def _initialize_from_config(self, config: Any) -> None:
        """Create the separate gate, up and down projections for a new shared expert."""
        _validate_mlp_config(config)
        if not isinstance(config.return_bias_tuple, bool):
            raise TypeError("return_bias_tuple must be bool")
        self.config = config
        self._gate_size = self._up_size = config.intermediate_size
        self._source_is_fused = False
        self._source_is_separate = True
        self._return_bias_tuple = config.return_bias_tuple
        self.activation_func = partial(local_swiglu, limit=self.swiglu_limit,
                                       activation_dtype=self.activation_dtype)
        if self._preserve_source_layout:
            if config.return_bias_tuple:
                raise ValueError("separate SharedExpert returns a tensor, not a bias tuple")
            self.gate_proj = nn.Linear(config.hidden_size, config.intermediate_size, bias=config.bias)
            self.up_proj = nn.Linear(config.hidden_size, config.intermediate_size, bias=config.bias)
            self.down_proj = nn.Linear(config.intermediate_size, config.hidden_size, bias=config.bias)
            return
        self.linear_fc1 = LinearWithMatmul(config.hidden_size, 2 * config.intermediate_size, bias=config.bias)
        self.linear_fc2 = LinearWithMatmul(config.intermediate_size, config.hidden_size, bias=config.bias)
        return

    def _set_clamped_activation(self, config: Any) -> None:
        if self.swiglu_limit > 0 or self.activation_dtype == "float32":
            hidden_act = getattr(config, "hidden_act", getattr(config, "hidden_activation", None))
344
345
346
347
348
349
350
351
352
353
354
355
            Activated intermediate [..., intermediate_size], retaining source dtype policy.
        """
        if self._preserve_source_layout:
            intermediate = torch.cat((self.gate_proj(hidden_states), self.up_proj(hidden_states)), dim=-1)
            return self.activation_func(intermediate).to(hidden_states.dtype)
        intermediate, bias = self.linear_fc1(hidden_states)
        if bias is not None:
            intermediate = intermediate + bias
        return self.activation_func(intermediate)

    def forward_fc2(self, intermediate: torch.Tensor) -> torch.Tensor | tuple[torch.Tensor, Optional[torch.Tensor]]:
        """Apply the second projection during combine, preserving the output-bias protocol.
359
360
361
362
363
364
365
366
367
368

        Returns:
            Shared output [..., hidden_size], or the source's (output, output_bias) pair.
        """
        if self._preserve_source_layout:
            return self.down_proj(intermediate)
        output, output_bias = self.linear_fc2(intermediate)
        if not self._return_bias_tuple:
            if output_bias is not None:
                output = output + output_bias
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
            x: Compatibility alias for hidden_states.
            stage: Full MLP, FC1 plus activation, or FC2 using an already activated intermediate.
                Staged callers use module(..., stage=...) so module/FSDP hooks still run.
        """
        if (hidden_states is None) == (x is None):
            raise ValueError("provide exactly one of hidden_states or x")
        hidden_states = x if hidden_states is None else hidden_states
        if stage == "fc1":
            return self.forward_fc1(hidden_states)
        if stage == "fc2":
            return self.forward_fc2(hidden_states)
        if stage != "full":
            raise ValueError("shared expert stage must be full, fc1 or fc2")
        return self.forward_fc2(self.forward_fc1(hidden_states))

    def reset_parameters(self) -> None:
        """Initialize owned projections after meta materialization."""
        if self._preserve_source_layout:
hyper_parallel/components/modules/moe/shared_expert_overlap.py
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
    Returns:
        Routed and shared outputs. Shared output retains the source bias-tuple protocol;
        callers retain their original gating, mask and merge arithmetic.
    """
    if not isinstance(overlap_shared_expert, bool):
        raise ValueError("overlap_shared_expert must be bool")
    if overlap_shared_expert and not getattr(experts, "shared_expert_overlap_supported", False):
        raise ValueError("this executor has no shared-expert overlap schedule; disable overlap or select ordinary EP")
    context = getattr(experts, "ep_context", None)
    if not overlap_shared_expert or context is None or context.mesh.size() == 1:
        return experts(hidden_states, topk_ids, topk_weights), shared(hidden_states)
    if not getattr(shared, "split_forward_supported", False):
        raise ValueError("shared expert must support module(..., stage='fc1'/'fc2') for communication overlap")
    intermediate = None
    shared_output = None

    def compute_fc1() -> None:
        """Overwrite invocation-local intermediates so checkpoint replay cannot reuse stale activations."""
        nonlocal intermediate, shared_output
        shared_output = None
        intermediate = shared(hidden_states, stage="fc1")

    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,
                     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/components/modules/runtime.py
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41


def _runtime_groups(model: nn.Module) -> Iterator[list[nn.Module]]:
    """Group unique runtime owners by compatible execution resources."""
    groups: dict[Any, list[nn.Module]] = {}
    seen = set()
    for module in model.modules():
        key = getattr(module, "runtime_group_key", None)
        if callable(key):
            # Transparent wrappers may delegate this bound method to their child.
            owner = getattr(key, "__self__", module)
            if id(owner) not in seen:
                groups.setdefault(key(), []).append(owner)
                seen.add(id(owner))
    yield from groups.values()


def prepare_module_runtimes(model: nn.Module) -> None:
    """Prepare declared module groups after FSDP wrapping and materialization.
42
43
44
45
46
47
48
49
50
51

    Args:
        model: Final module tree. Ordinary modules declare no runtime group.
    """
    for modules in _runtime_groups(model):
        modules[0].prepare_runtime_group(modules)


def close_module_runtimes(model: nn.Module) -> None:
    """Release declared runtimes after every forward and backward has completed.
52
53
54
55
56
57
58

    Args:
        model: Final model tree; each holder releases its own runtime reference.
    """
    for modules in _runtime_groups(model):
        for module in modules:
            module.close_runtime()
hyper_parallel/distributed/expert_parallel/ep_context.py
58
59
60
61
62
63
64
65
66
67
    def _exchange(self, tensor: Tensor, send: list[int], receive: list[int], *, async_op: bool = False) -> Tensor:
        """Share one synchronous/lazy exchange entry between dispatch and combine."""
        if self.mesh.size() == 1:
            return tensor
        if async_op:
            return ep_all_to_all_async(tensor, send, receive, self.mesh.get_group())
        return ep_all_to_all(tensor, send, receive, self.mesh.get_group())

    @staticmethod
    def _run_overlap(compute: Callable[[], None] | None, *payloads: Tensor | None) -> None:
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81

    @staticmethod
    def _run_overlap(compute: Callable[[], None] | None, *payloads: Tensor | None) -> None:
        """Drain outstanding payloads before propagating an independent computation failure."""
        if compute is None:
            return
        try:
            compute()
        except Exception:
            for payload in payloads:
                if payload is not None:
                    _functional_collectives.wait_tensor(payload)
            raise

    def _combine_slots(
        self, values: Tensor, send_splits: list[int], recv_splits: list[int], recv_inverse: Tensor,
        *, overlap_compute: Callable[[], None] | None = None,
 80
 81
 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
        self, values: Tensor, send_splits: list[int], recv_splits: list[int], recv_inverse: Tensor,
        *, 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)
        return returned


class EPContext(_EPTransport):
    """Dispatch each route to its contiguous Shard(0) expert owner."""
135
136
137
138
139
140
141
142
143
144
            send/receive split lists and the inverse mapping from received rows to
            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)
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
        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)
        send, receive = self._slot_split_sizes(counts, routing_weights is not None)
        # Ascending global IDs already group rows by rank under contiguous expert ownership.
        asynchronous = overlap_compute is not None
        hidden = self._exchange(hidden_states.contiguous(), send, receive, async_op=asynchronous)
        global_ids = self._exchange(ids[:, None].contiguous(), send, receive, async_op=asynchronous).reshape(-1)
        weights = None
        if routing_weights is not None:
            weights = self._exchange(routing_weights[:, None].contiguous(), send, receive,
                                     async_op=asynchronous).reshape(-1)
        self._run_overlap(overlap_compute, hidden, global_ids, weights)
        # AsyncCollectiveTensor inserts the wait at these first non-view consumers.
        local_ids = global_ids - self.rank * self.local_experts
        local_counts = local_ids.new_zeros(self.local_experts).scatter_add_(
            0, local_ids, torch.ones_like(local_ids),
192
193
194
195
196
197

        Returns:
            Source-side slot outputs; the Experts algorithm restores original tokens.
        """
        return self._combine_slots(values, send_splits, recv_splits, recv_inverse,
                                   overlap_compute=overlap_compute)
hyper_parallel/distributed/expert_parallel/moonep_context.py
38
39
40
41
42
43
44
45
46
47
48
49
            mesh: Existing one-dimensional TP-extend-EP mesh.
            num_experts: Global number of home experts, divisible by the mesh size.
            replica_capacity: Maximum distinct remote experts per rank; None means E/EP.
        """
        super().__init__(mesh, num_experts=num_experts)
        capacity = self.local_experts if replica_capacity is None else replica_capacity
        if isinstance(capacity, bool) or not isinstance(capacity, Integral) or capacity < 0:
            raise ValueError("moonep_replica_capacity must be a nonnegative integer or None")
        self.replica_capacity = int(capacity)

    def plan(self, expert_ids: Tensor) -> dict:
        """Compile a deterministic plan from all sources' prepared slot counts.
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.
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
            Home rows followed by temporary remote rows. The collective adjoint
            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"])
        first, second = remote.split((gate_up[0].numel(), down[0].numel()), dim=1)
        return (torch.cat((gate_up, first.reshape(-1, *gate_up.shape[1:]))),
                torch.cat((down, second.reshape(-1, *down.shape[1:]))))

    def combine(
        self, values: Tensor, plan: dict, recv_inverse: Tensor,
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67


def _allocate(totals: np.ndarray, targets: np.ndarray, fill_deficit: bool) -> np.ndarray:
    """Split sender/receiver quotas across experts in descending load order."""
    ranks = targets.size
    home = totals.reshape(ranks, -1)
    balance = home.sum(axis=1) - targets
    quotas = np.zeros((ranks, ranks), dtype=np.int64)
    for _ in range(ranks - 1):
        source, target = balance.argmax(), balance.argmin()
        amount = -balance[target]
        if not fill_deficit:
            amount = min(balance[source], amount)
        quotas[source, target] += amount
        balance[source] -= amount
        balance[target] += amount

    allocation = np.zeros((totals.size, ranks), dtype=np.int64)
    for owner in range(ranks):
        remaining = home[owner].copy()
        allocation[owner * home.shape[1]:(owner + 1) * home.shape[1], owner] = remaining
        experts = np.argsort(-remaining, kind="stable")
        position = 0
        for destination in np.argsort(-quotas[owner], kind="stable"):
            quota = quotas[owner, destination]
            while quota > 0:
                expert = experts[position]
                amount = min(remaining[expert], quota)
                logical_id = owner * home.shape[1] + expert
                allocation[logical_id, destination] += amount
                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:
    """Apply the moonep_with_fsdp partial-fill policy with the whole-deficit fallback.
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98

    Returns:
        Real row allocation in [logical expert, execution rank] order.
    """
    ranks, experts = counts.shape
    local = experts // ranks
    capacity = local if replica_capacity is None else replica_capacity
    totals = counts.sum(axis=0)
    total = totals.sum()
    targets = total // ranks + (np.arange(ranks) < total % ranks)
    allocation = _allocate(totals, targets, fill_deficit=False)
    remote = np.arange(experts)[:, None] // local != np.arange(ranks)
    minimum = np.maximum(totals.reshape(ranks, local).sum(axis=1) - targets, 0).sum()
    if (allocation[remote].sum() == minimum and np.all(allocation.sum(axis=0) == targets)
            and np.all(((allocation > 0) & remote).sum(axis=0) <= capacity)):
        return allocation
    allocation = _allocate(totals, targets, fill_deficit=True)
    valid = (not np.any(allocation < 0), np.array_equal(allocation.sum(axis=1), totals),
             np.array_equal(allocation.sum(axis=0), targets),
             np.all(((allocation > 0) & remote).sum(axis=0) <= capacity))
    if not all(valid):
        raise RuntimeError(f"MoonEP cannot balance routes within replica capacity {capacity}")
    return allocation


def compile_plan(counts: np.ndarray, allocation: np.ndarray, ids: torch.Tensor, rank: int) -> dict:
    """Compile source and receiver permutations without copying token IDs to the host.
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158

    Returns:
        Invocation-local split lists, compute counts and permutation tensors.
    """
    ranks, experts = counts.shape
    local = experts // ranks
    source_ends = counts.cumsum(axis=0)
    target_ends = allocation.cumsum(axis=1)
    overlap = np.maximum(
        np.minimum(source_ends[:, :, None], target_ends[None])
        - np.maximum((source_ends - counts)[:, :, None], (target_ends - allocation)[None]),
        0,
    )
    recv_rows = overlap[:, :, rank]
    token_send = overlap[rank].sum(axis=0).tolist()
    token_recv = recv_rows.sum(axis=1).tolist()

    expert_ids = np.arange(experts)
    owners = expert_ids // local
    remote = (allocation > 0) & (owners[:, None] != np.arange(ranks))
    weight_send = remote[owners == rank].sum(axis=0).tolist()
    weight_recv = remote[:, rank].reshape(ranks, local).sum(axis=1).tolist()
    send_experts = np.nonzero(remote[owners == rank].T)[1]
    received_experts = expert_ids[remote[:, rank]]
    home_experts = expert_ids[owners == rank]
    active = np.concatenate((home_experts, received_experts))
    boundaries = allocation[active, rank].cumsum()

    # Sender packets are destination-major, with ascending expert IDs per peer.
    # Receiver packets are source-major; expand one offset per (expert, source) segment.
    recv_starts = (recv_rows.flatten().cumsum() - recv_rows.flatten()).reshape(recv_rows.shape)
    lengths = recv_rows[:, active].T.flatten()
    recv_offsets = recv_starts[:, active].T.flatten() - (lengths.cumsum() - lengths)
    offset = (source_ends - counts)[rank] - (counts[rank].cumsum() - counts[rank])
    rows = (offset, target_ends.flatten(), recv_offsets, lengths, send_experts, boundaries)
    metadata = torch.from_numpy(np.concatenate(rows)).to(ids.device)
    offset, ends, recv_offsets, lengths, send, boundaries = metadata.split([row.size for row in rows])

    positions = torch.arange(ids.numel(), device=ids.device)
    ordinals = positions + offset[ids]
    destinations = (ordinals[:, None] >= ends.view(experts, ranks)[ids]).sum(dim=1)
    # Inputs are already expert-major; stable destination sorting retains that order per peer.
    source_order = destinations.float().argsort(stable=True)
    source_inverse = torch.empty_like(source_order, dtype=torch.int32)
    source_inverse.scatter_(0, source_order, positions.int())
    received = sum(token_recv)
    receive_order = torch.arange(received, device=ids.device) + torch.repeat_interleave(
        recv_offsets, lengths, output_size=received,
    )
    return {
        "token_send": token_send, "token_recv": token_recv,
        "weight_send": weight_send, "weight_recv": weight_recv, "weight_exchange": bool(remote.any()),
        "send_experts": send, "source_order": source_order, "source_inverse": source_inverse,
        "receive_order": receive_order, "counts": torch.diff(boundaries, prepend=boundaries.new_zeros(1)),
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.