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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
87 changes: 87 additions & 0 deletions hyper_parallel/components/functional/router_balance_loss.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
# Copyright 2026 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""Sequence-wise router balancing across token-partition process groups."""

import math
from typing import Any

import torch
import torch.distributed as dist

from hyper_parallel.core.utils.communication import differentiable_all_reduce


def sequence_load_balancing_loss(
scores: torch.Tensor,
selected_experts: torch.Tensor,
sequence_ids: torch.Tensor,
num_sequences: int,
token_mask: torch.Tensor | None = None,
sequence_partition_groups: tuple[Any, ...] = (),
*,
score_epsilon: float = 0.0,
) -> torch.Tensor:
"""Average ``E * sum_i(fraction_i * mean_probability_i)`` over sequences.

Args:
scores: Nonnegative, unbiased scores for all experts, shaped ``[T, E]``.
selected_experts: Top-K experts selected from unbiased scores, shaped ``[T, K]``.
sequence_ids: Logical sample index of each token, shaped ``[T]``.
num_sequences: Global number of samples shared by the token-partition ranks.
token_mask: Optional boolean ``[T]`` mask; true tokens contribute.
sequence_partition_groups: Independent axes partitioning the same
sequences' tokens. Never include a data-parallel/expert-dispatch
group. Probability sums use a differentiable SUM all-reduce;
callers must account for replicated losses in gradient reduction.
score_epsilon: Additive affinity-normalization epsilon.

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]")
if not math.isfinite(score_epsilon) or score_epsilon < 0:
raise ValueError("score_epsilon must be finite and nonnegative")
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()
denominator = scores.sum(dim=-1, keepdim=True)
if score_epsilon:
denominator = denominator + score_epsilon
probabilities = scores / denominator.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)
18 changes: 16 additions & 2 deletions hyper_parallel/distributed/_builder/rule_resolver.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
import functools
import inspect
import logging
from types import MappingProxyType
from typing import Any, Dict, List, Optional, Tuple

from hyper_parallel.core.dtensor.placement_types import Placement
Expand Down Expand Up @@ -617,8 +618,16 @@ def _require_region_dispatch(spec, *, source):
"remove it")


def _resolved_input_placements(spec):
"""Snapshot the enclosing boundary's resolved input destinations."""
return MappingProxyType({
name: MappingProxyType(copy.deepcopy(named))
for name, named in spec.in_dst.items()
})


def _build_local_compute_factory(factory, module, mesh, mesh_dim_names,
expert_mesh, *, configured=None, source):
expert_mesh, *, configured=None, source, input_placements=None):
"""Build a ``@local_compute`` factory into the region compute_fn (apply-time).

The factory is invoked ONCE with the framework context filled BY NAME per
Expand All @@ -632,6 +641,8 @@ def _build_local_compute_factory(factory, module, mesh, mesh_dim_names,
The returned compute fn is validated against the module's forward
signature (validate_local_compute_signature: params must match the
original forward) and bound to *module* by the caller.
Optional ``input_placements`` is a read-only snapshot of the enclosing
boundary's resolved input destinations, keyed by input and mesh-axis names.
"""
# Lazy imports: applier and forward_rewriter both import rule_resolver
# at module level — importing them here at module level would cycle.
Expand All @@ -649,6 +660,7 @@ def _build_local_compute_factory(factory, module, mesh, mesh_dim_names,
"tp_mesh": _get_tp_submesh(mesh, mesh_dim_names),
"cp_mesh": _get_cp_submesh(mesh, mesh_dim_names),
"ep_mesh": expert_mesh,
"input_placements": input_placements,
}
build_kwargs = fill_context_kwargs(
meta, context, configured or {}, source=source)
Expand Down Expand Up @@ -717,7 +729,8 @@ def _resolve_local_compute_fn(module, spec, mesh, mesh_dim_names,
configured = None
compute_fn = _build_local_compute_factory(
factory, module, mesh, mesh_dim_names, expert_mesh,
configured=configured, source=source)
configured=configured, source=source,
input_placements=_resolved_input_placements(spec))
return functools.partial(compute_fn, module)
if spec.region_dispatch is False and spec.inner_wrapper is None:
return module.forward
Expand Down Expand Up @@ -841,6 +854,7 @@ def _resolve_inner_wrapper(module, spec, cp_mesh, mesh, tp_mesh=None,
"tp_mesh": tp_mesh,
"cp_mesh": cp_mesh,
"ep_mesh": ep_mesh,
"input_placements": _resolved_input_placements(spec),
}
if _is_delayed_target(custom):
return _resolve_delayed_inner_wrapper(
Expand Down
4 changes: 2 additions & 2 deletions hyper_parallel/distributed/recipe_spec.py
Original file line number Diff line number Diff line change
Expand Up @@ -515,8 +515,8 @@ def _normalize_out_fields(spec: ModuleShardingSpec) -> ModuleShardingSpec:
# Reserved framework-context names per kind (declaring one means the
# framework fills it by name; configuring a key with the same name errors)
_MESH_FAMILY = frozenset({"mesh", "tp_mesh", "cp_mesh", "ep_mesh"})
FACTORY_CONTEXT = frozenset({"module"}) | _MESH_FAMILY
WRAPPER_CONTEXT = frozenset({"target_module"}) | _MESH_FAMILY
FACTORY_CONTEXT = frozenset({"module", "input_placements"}) | _MESH_FAMILY
WRAPPER_CONTEXT = frozenset({"target_module", "input_placements"}) | _MESH_FAMILY

# Required context per kind (the decorators enforce full declaration --
# the mesh family is always passed by the framework and the user merely
Expand Down
59 changes: 1 addition & 58 deletions hyper_parallel/models/deepseek_v41/aux_loss.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,66 +19,9 @@
from typing import Any

import torch # pylint: disable=forbidden-backend-import
import torch.distributed as dist # pylint: disable=forbidden-backend-import

from hyper_parallel.core.dtensor.dtensor import DTensor, SkipDTensorDispatch, distribute_tensor
from hyper_parallel.core.utils.communication import differentiable_all_reduce


def sequence_load_balancing_loss(
scores: torch.Tensor,
selected_experts: torch.Tensor,
sequence_ids: torch.Tensor,
num_sequences: int,
token_mask: torch.Tensor | None = None,
sequence_partition_groups: tuple[Any, ...] = (),
) -> torch.Tensor:
"""Average ``E * sum_i(fraction_i * mean_probability_i)`` over sequences.

Args:
scores: Nonnegative, unbiased scores for all experts, shaped ``[T, E]``.
selected_experts: Top-K experts selected from unbiased scores, shaped ``[T, K]``.
sequence_ids: Logical sample index of each token, shaped ``[T]``.
num_sequences: Global number of samples shared by the token-partition ranks.
token_mask: Optional boolean ``[T]`` mask; true tokens contribute.
sequence_partition_groups: Independent axes partitioning the same
sequences' tokens. Never include a data-parallel/expert-dispatch
group. Probability sums use a differentiable SUM all-reduce;
callers must account for replicated losses in gradient reduction.

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)
from hyper_parallel.components.functional.router_balance_loss import sequence_load_balancing_loss


class _AccumulateRouterLoad(torch.autograd.Function):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@
from hyper_parallel.distributed.recipe_spec import inner_wrapper
from hyper_parallel.models.deepseek_v3.adapter.distributed.context_parallel import mla_cp_wrapper
from hyper_parallel.models.replacement import method_replacement
from hyper_parallel.models.xing_4.modeling_xing4_0 import Xing4MoE, fusion_attention_with_logit_maxima
from hyper_parallel.models.xing_4.modeling_xing4_0 import fusion_attention_with_logit_maxima


def _rotary(tensor: torch.Tensor, positions: tuple[torch.Tensor, torch.Tensor] | None,
Expand Down Expand Up @@ -87,15 +87,6 @@ def forward(hidden_states: torch.Tensor, position_embeddings: tuple[torch.Tensor
return requests


@inner_wrapper
def xing4_moe_cp_wrapper(target_module: Xing4MoE, mesh: Any, tp_mesh: Any,
cp_mesh: Any, ep_mesh: Any) -> list:
"""Bind sequence-wise router statistics without replacing the MoE computation."""
del mesh, tp_mesh, ep_mesh
target_module.gate.aux_loss_cp_group = cp_mesh.get_group()
return []


def _cp_mesh(context: Mapping[str, Any]) -> Any:
"""Resolve the same mesh used by TextParallelBatch's contiguous CP sharder."""
mesh = context["mesh_context"].cp_mesh
Expand Down
Loading
Loading