From f8ec544bef230383d62af5c365d60b6f723d761d Mon Sep 17 00:00:00 2001 From: xuxinglei Date: Sat, 7 Nov 2026 02:29:18 +0800 Subject: [PATCH] fix(loss): normalize replicated router AUX under loss parallelism --- .../components/functional/aux_loss.py | 32 ++++++++++--- .../models/xing_4/modeling_xing4_0.py | 2 +- hyper_parallel/trainer/base.py | 3 +- .../ut/components/functional/test_aux_loss.py | 45 +++++++++++++++++++ tests/ut/trainer/test_aux_loss_scaling.py | 19 +++++--- 5 files changed, 85 insertions(+), 16 deletions(-) diff --git a/hyper_parallel/components/functional/aux_loss.py b/hyper_parallel/components/functional/aux_loss.py index 2d3aae5397..02f6a281a7 100644 --- a/hyper_parallel/components/functional/aux_loss.py +++ b/hyper_parallel/components/functional/aux_loss.py @@ -32,6 +32,7 @@ class _AuxLossScaleState: scale: torch.Tensor | float = 1.0 active: bool = False + tp_replicas: int = 1 handles: list[Any] = field(default_factory=list) @@ -39,14 +40,19 @@ class _AuxLossScaleState: @contextmanager -def aux_loss_scale_context() -> Iterator[None]: +def aux_loss_scale_context(*, loss_parallel: bool = False, tp_size: int = 1) -> Iterator[None]: """Isolate auxiliary gradient scaling for one forward/backward microstep. Call :func:`bind_aux_loss_scale` on the local scalar task loss before weighting it. Keep this context active through backward so checkpoint recomputation observes the same scale. Nested contexts are independent. + + Args: + loss_parallel: Whether the task loss has partitioned vocabulary gradients. + tp_size: Positive tensor-parallel degree. Only explicitly replicated + auxiliary means use this degree for gradient normalization. """ - state = _AuxLossScaleState() + state = _AuxLossScaleState(tp_replicas=tp_size if loss_parallel else 1) token = _AUX_LOSS_STATE.set(state) try: yield @@ -91,20 +97,23 @@ class _AuxLossAutoScaler(torch.autograd.Function): main_loss_backward_scale = torch.tensor(1.0) @staticmethod - def forward(ctx: Any, output: torch.Tensor, aux_loss: torch.Tensor) -> torch.Tensor: + def forward(ctx: Any, output: torch.Tensor, aux_loss: torch.Tensor, + tp_replicated: bool = False) -> torch.Tensor: """Save the auxiliary loss and return the output unchanged. Args: ctx: Autograd context for the auxiliary loss and scale state. output: Forward tensor carrying the injected gradient. aux_loss: Scalar objective whose gradient is injected in backward. + tp_replicated: Whether the auxiliary mean is replicated across TP ranks. """ ctx.save_for_backward(aux_loss) ctx.scale_state = _AUX_LOSS_STATE.get() + ctx.tp_replicated = tp_replicated return output @staticmethod - def backward(ctx: Any, grad_output: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: + def backward(ctx: Any, grad_output: torch.Tensor) -> tuple[torch.Tensor | None, ...]: """Pass through the output gradient and inject the auxiliary-loss gradient. Args: @@ -118,8 +127,12 @@ def backward(ctx: Any, grad_output: torch.Tensor) -> tuple[torch.Tensor, torch.T ) if isinstance(scale, torch.Tensor): scale = scale.to(device=aux_loss.device, dtype=aux_loss.dtype) + tp_replicas = ctx.scale_state.tp_replicas if ctx.tp_replicated and ctx.scale_state is not None else 1 + if tp_replicas > 1: + scale = scale / tp_replicas aux_loss_grad = torch.ones_like(aux_loss) * scale - return grad_output, aux_loss_grad + gradients = (grad_output, aux_loss_grad) + return gradients + (None,) if len(ctx.needs_input_grad) == 3 else gradients @staticmethod def set_loss_scale(scale: torch.Tensor) -> None: @@ -127,12 +140,17 @@ def set_loss_scale(scale: torch.Tensor) -> None: _AuxLossAutoScaler.main_loss_backward_scale = scale -def aux_loss_auto_scale(output: torch.Tensor, aux_loss: torch.Tensor) -> torch.Tensor: +def aux_loss_auto_scale(output: torch.Tensor, aux_loss: torch.Tensor, *, + tp_replicated: bool = False) -> torch.Tensor: """Attach an auxiliary-loss gradient to an unchanged forward tensor. Args: output: Main forward output. aux_loss: Scalar auxiliary loss whose gradient should be injected. + tp_replicated: The auxiliary mean represents the same objective on each + TP rank. Average its injected gradients when loss parallelism keeps + task-loss gradients partitioned; leave partial auxiliary objectives + at the default. Returns: ``output`` unchanged in value, with an autograd edge to ``aux_loss``. @@ -140,7 +158,7 @@ def aux_loss_auto_scale(output: torch.Tensor, aux_loss: torch.Tensor) -> torch.T state = _AUX_LOSS_STATE.get() if state is not None: state.active = True - return _AuxLossAutoScaler.apply(output, aux_loss) + return _AuxLossAutoScaler.apply(output, aux_loss, tp_replicated) def set_aux_loss_scale(scale: torch.Tensor) -> None: diff --git a/hyper_parallel/models/xing_4/modeling_xing4_0.py b/hyper_parallel/models/xing_4/modeling_xing4_0.py index 91653070ea..681da7a5b0 100644 --- a/hyper_parallel/models/xing_4/modeling_xing4_0.py +++ b/hyper_parallel/models/xing_4/modeling_xing4_0.py @@ -296,7 +296,7 @@ def _attach_balance_loss(self, weights: torch.Tensor, scores: torch.Tensor, indi affinity = differentiable_all_reduce(normalized.sum(dim=1), "sum", group) / tokens loss = (affinity * load).sum(dim=-1).mean() * self.num_experts self.last_aux_loss = loss.detach() - return aux_loss_auto_scale(weights, loss * self.aux_loss_coeff) + return aux_loss_auto_scale(weights, loss * self.aux_loss_coeff, tp_replicated=True) @property def tokens_per_expert(self) -> torch.Tensor: diff --git a/hyper_parallel/trainer/base.py b/hyper_parallel/trainer/base.py index b2b1955d6b..eedfde7a66 100644 --- a/hyper_parallel/trainer/base.py +++ b/hyper_parallel/trainer/base.py @@ -813,7 +813,8 @@ def forward_backward_step( if channel_loss_callback is not None else nullcontext() ) - with micro_step_context, aux_loss_scale_context(): + with micro_step_context, aux_loss_scale_context( + loss_parallel=self.mesh.loss_parallel, tp_size=self.mesh.tp_size): micro_batch = self.preforward(micro_batch) # TextTrainer passes loss-only fields separately. Keep the legacy # BaseTrainer/VLM one-dictionary call contract working as well. diff --git a/tests/ut/components/functional/test_aux_loss.py b/tests/ut/components/functional/test_aux_loss.py index 21651f9cbf..e2838884f1 100644 --- a/tests/ut/components/functional/test_aux_loss.py +++ b/tests/ut/components/functional/test_aux_loss.py @@ -14,6 +14,7 @@ # ============================================================================ """Auxiliary gradients must follow the scalar objective under recomputation.""" +from concurrent.futures import ThreadPoolExecutor import unittest import torch @@ -109,3 +110,47 @@ def test_no_auxiliary_loss_leaves_main_gradient_unchanged(self) -> None: bind_aux_loss_scale(loss) (loss * 0.25).backward() torch.testing.assert_close(value.grad, torch.tensor(1.0)) + + @arg_mark(plat_marks=["cpu_linux", "cpu_macos"], level_mark="level0", + card_mark="onecard", essential_mark="essential") + def test_tp_replica_averaging_is_explicit(self) -> None: + """ + Feature: Replicated auxiliary means under loss parallelism. + Description: A replicated mean and a partial objective share one backward context. + Expectation: Only the declared mean is averaged, only for TP loss parallelism. + """ + for loss_parallel, tp_size, divisor in ((True, 2, 2), (False, 2, 1), (True, 1, 1)): + with self.subTest(loss_parallel=loss_parallel, tp_size=tp_size): + main = torch.tensor(4.0, requires_grad=True) + replicated = torch.tensor(2.0, requires_grad=True) + partial = torch.tensor(3.0, requires_grad=True) + with aux_loss_scale_context(loss_parallel=loss_parallel, tp_size=tp_size): + output = aux_loss_auto_scale(main, replicated.square(), tp_replicated=True) + output = aux_loss_auto_scale(output, partial.square()) + loss = output.square() + bind_aux_loss_scale(loss) + (loss * 5).backward() + torch.testing.assert_close(output, main.detach()) + torch.testing.assert_close(main.grad, torch.tensor(40.0)) + torch.testing.assert_close(replicated.grad, torch.tensor(20.0 / divisor)) + torch.testing.assert_close(partial.grad, torch.tensor(30.0)) + + @arg_mark(plat_marks=["cpu_linux", "cpu_macos"], level_mark="level0", + card_mark="onecard", essential_mark="essential") + def test_replica_metadata_survives_checkpoint_and_backward_thread(self) -> None: + """ + Feature: Replicated auxiliary-loss lifecycle. + Description: Non-reentrant recomputation and backward run in a different Python context. + Expectation: The original autograd context retains both the multiplier and TP degree. + """ + value = torch.tensor(2.0, requires_grad=True) + + def forward(inputs: torch.Tensor) -> torch.Tensor: + return aux_loss_auto_scale(inputs.square(), inputs.pow(3), tp_replicated=True) + + with aux_loss_scale_context(loss_parallel=True, tp_size=2): + loss = checkpoint(forward, value, use_reentrant=False) + bind_aux_loss_scale(loss) + with ThreadPoolExecutor(max_workers=1) as executor: + executor.submit((loss * 7).backward).result() + torch.testing.assert_close(value.grad, torch.tensor(70.0)) diff --git a/tests/ut/trainer/test_aux_loss_scaling.py b/tests/ut/trainer/test_aux_loss_scaling.py index f64e597375..41771b7dad 100644 --- a/tests/ut/trainer/test_aux_loss_scaling.py +++ b/tests/ut/trainer/test_aux_loss_scaling.py @@ -30,20 +30,22 @@ class AuxiliaryModel(nn.Module): """Synthetic model with two independently injected auxiliary objectives.""" - def __init__(self, enabled: bool) -> None: + def __init__(self, enabled: bool, replicated_router: bool = False) -> None: """Create the scalar parameters for the main and auxiliary branches.""" super().__init__() self.main = nn.Parameter(torch.tensor(2.0)) self.router = nn.Parameter(torch.tensor(3.0)) self.indexer = nn.Parameter(torch.tensor(4.0)) self.enabled = enabled + self.replicated_router = replicated_router def forward(self, input_ids: torch.Tensor, use_cache: bool = False) -> torch.Tensor: """Return the main scalar while attaching optional penalties.""" del use_cache output = self.main.square() * input_ids.mean() if self.enabled: - output = aux_loss_auto_scale(output, self.router.square() * input_ids.mean()) + output = aux_loss_auto_scale(output, self.router.square() * input_ids.mean(), + tp_replicated=self.replicated_router) output = aux_loss_auto_scale(output, self.indexer.square() * input_ids.mean()) return output @@ -59,17 +61,18 @@ def test_unequal_microbatches_match_weighted_explicit_objective(self) -> None: Description: Two microsteps contribute 1/4 and 3/4 to every gradient branch. Expectation: The actual Trainer backward matches the explicitly token-weighted reference. """ - for enabled in (False, True): - with self.subTest(enabled=enabled): + for enabled, loss_parallel in ((False, False), (True, False), (True, True)): + with self.subTest(enabled=enabled, loss_parallel=loss_parallel): trainer = BaseTrainer.__new__(BaseTrainer) trainer.device = torch.device("cpu") - trainer.model = AuxiliaryModel(enabled) + trainer.model = AuxiliaryModel(enabled, replicated_router=loss_parallel) trainer.model_fwd_context = nullcontext() trainer.model_bwd_context = nullcontext() trainer.graph_compiler = None trainer.model_integration = Mock() trainer.config = SimpleNamespace(training=SimpleNamespace(empty_cache_before_backward=False)) - trainer.mesh = SimpleNamespace(dp_cp_mesh=None, sequence_parallel=False, dp_size=1, cp_size=1) + trainer.mesh = SimpleNamespace(dp_cp_mesh=None, sequence_parallel=False, dp_size=1, cp_size=1, + loss_parallel=loss_parallel, tp_size=2) trainer.loss_fn = lambda model_output, labels: model_output trainer.step_token_counts = {"foundation_tokens": torch.tensor(4)} prefix = "hyper_parallel.trainer.runtime.metrics.all_reduce" @@ -80,7 +83,9 @@ def test_unequal_microbatches_match_weighted_explicit_objective(self) -> None: weighted_input = 0.25 + 0.75 * 2 torch.testing.assert_close(trainer.model.main.grad, torch.tensor(4 * weighted_input)) if enabled: - torch.testing.assert_close(trainer.model.router.grad, torch.tensor(6 * weighted_input)) + router_divisor = 2 if loss_parallel else 1 + torch.testing.assert_close( + trainer.model.router.grad, torch.tensor(6 * weighted_input / router_divisor)) torch.testing.assert_close(trainer.model.indexer.grad, torch.tensor(8 * weighted_input)) else: self.assertIsNone(trainer.model.router.grad)