Skip to content

Add LoggedAuxLoss and its first usage: the DeepSeek-V3 sequence-wise MoE balance loss - #3864

Merged
tianyu-l merged 8 commits into
pytorch:mainfrom
sdmyzlp:br_aux_loss
Sep 10, 2026
Merged

tianyu-l merged 8 commits into
pytorch:mainfrom
sdmyzlp:br_aux_loss

Conversation

@sdmyzlp

@sdmyzlp sdmyzlp commented Jul 5, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Adds LoggedAuxLoss (torchtitan/models/common/aux_loss.py): a framework for auxiliary objectives that live inside the model. A per-layer loss value has nowhere to go in the model output, so the framework carries it in two other ways:

  • Injection. The value is fed back through an identity autograd Function on a carrier tensor: the forward returns the carrier unchanged, the backward supplies ones for the loss term. An objective can then shape the router's weights without being part of the returned loss, which is what pipeline parallelism requires.
  • Metrics. Every instance accumulates its value in the forward, inside a retained torch_remat region so activation checkpointing never re-runs the side effect. A step pre-hook rolls the instances into per-group registers, and collect_aux_loss_metrics reduces them once per log step: summed over the configured reduce mesh and the pipeline stages, and divided by the build-time instance count, i.e. the mean over layers.

SeqwiseLoadBalanceLoss (torchtitan/models/common/moe.py) is its first usage. It implements the DeepSeek-V3 Sec 2.1.2 per-forward balance loss (Eqs 17-20):

$$f_i = \frac{E}{K T} \sum_t \mathbf{1}[t \to i], \qquad s'_{t,i} = \frac{s_{t,i}}{\sum_j s_{t,j}}, \qquad p_i = \frac{1}{T} \sum_t s'_{t,i}, \qquad L_{bal} = \sum_i f_i p_i$$

The balancing unit is one forward's folded token stream, a DP-local microbatch. Global balance stays with the auxiliary-loss-free bias path.

The plumbing that comes with it:

  • The router builds its one-hot routing map, returns it instead of the full scores, and passes it to the loss, so the loss counts exactly the tokens the router counted.
  • make_moe_config(aux_loss_coeff=...) enables the loss at 1e-3 for every deepseek_v3 flavor.
  • Both trainers set the step's denominator before the gradient-accumulation loop and log the metric.

Normalization

Each rank contributes a token-additive loss and the framework divides by the global valid-token count, the same denominator the main loss uses; no per-rank or per-microbatch averaging is applied. The result is the per-token mean and does not depend on DP degree, PP microbatches or gradient accumulation.

Tests

tests/unit_tests/cpu/test_aux_loss.py covers six behaviors: value, register and injected gradient against an explicit Eqs 17-20 reference; accumulation across forwards and roll-up/zero semantics; no double count under torch_remat.checkpointing; the Config ownership make_moe_config relies on; an 8-rank CPU float64 + gloo spmd_types case (dp2/cp2/tp2) with EP on and off and the typechecker on and off; and the pipeline-stage summation of the collected metric. The test_moe.py and gpu test_remat.py stubs follow the router's new return value.

Follow-ups

  • The retained torch_remat region only takes effect under RegionAC; under the PyTorch-checkpoint policies (FullAC, SelectiveAC) the enclosing block is replayed and the logged metric over-counts (2x under FullAC). The injected gradient is unaffected.
  • Metric logging reduces a device scalar and calls .item() today; it should go through the GPU-tensor logging framework (TODO Add distributed tensor logging #4202 in aux_loss.py) once that lands.

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Jul 5, 2026
@pytorch-bot

pytorch-bot Bot commented Jul 5, 2026 •

Copy link
Copy Markdown

Workflows were awaiting approval. CI has now been triggered for the ciflow labels on this PR.

@tianyu-l

tianyu-l commented Jul 7, 2026 •

Copy link
Copy Markdown
Contributor

Haven't looked into details of this PR, but is it covering the same feature as #3000, which is being reviewed. If so shall we move conversation over there?

cc @pianpwk @shuhuayu

@sdmyzlp

sdmyzlp commented Jul 9, 2026 •

Copy link
Copy Markdown
Collaborator Author

Haven't looked into details of this PR, but is it covering the same feature as #3000, which is being reviewed. If so shall we move conversation over there?

Thanks @tianyu-l for the pointer, and cc @pianpwk @shuhuayu.

We have carefully studied #3000 and this PR is built on top of that existing work, with the main modifications summarized in the updated description — the key shift being a universal LoggedAuxLoss design rather than an MoE-specific one, which we hope will also be useful for the implementation of indexer loss feature.

We understand that @pianpwk may currently be focusing on the spmd_types migration, and wonder if we could keep this PR open for further discussion. Would love to hear your thoughts.

@sdmyzlp
sdmyzlp force-pushed the br_aux_loss branch 4 times, most recently from 913a9a5 to 5bbf76f Compare July 13, 2026 14:49

@pianpwk pianpwk left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

thank you for the PR! leaving some thoughts

Comment thread torchtitan/models/common/aux_loss.py Outdated
def typecheck_forward(
carrier: torch.Tensor, aux_loss: torch.Tensor
) -> torch.Tensor:
return _AuxLossInjection.apply(carrier, aux_loss)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

have you tried running with --debug.spmd_typechecking on? I fear this will break, the expectation is that types are re-annotated on the output here, and the autograd function is blackboxed from typechecking.

Since this is just injection, it should be enough to copy types from carrier, e.g.

out = _AuxLossInjection.apply(carrier, aux_loss)
spmd.assert_type(
    out, 
    spmd.get_local_type(carrier),
    spmd.runtime.get_partition_spec(carrier),
)
return out

There's also a WIP doc at #3853 in case it's helpful :)

Comment thread torchtitan/models/common/decoder.py Outdated
aux_loss_cfg.ac_doubled = (
config.activation_checkpoint is not None
and not config.compile.enable
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

do you know how well this handles partial (e.g. selective) AC? are there cases where this isn't recomputed, but other parts are

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

actually I would check how to utilize

def _is_recomputation_enabled(module):
return getattr(module, "checkpoint_impl", None) is CheckpointImpl.NO_REENTRANT

Comment thread torchtitan/models/common/aux_loss.py Outdated
for block in getattr(part, "layers", {}).values():
for module in block.modules():
if isinstance(module, LoggedAuxLoss):
local_sums[(module.reduce_mesh, module.tag)] += module.pop()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this may be called once every log_freq, and if that's not once every training step, then this accumulates stats over multiple steps? I may be wrong.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Coupling logging and clearing seems a bad idea. I'm OK with not handling logging in this PR and worry about it later. It is a limitation I confess, but proper tensor logging needs to be carefully designed.

Fwiw loss-free load balancing stats are also not logged https://github.com/pytorch/torchtitan/blob/main/torchtitan/components/optimizer.py#L431

In fact, could you handle the clearing together with loss-free load balancing, in the optimizer hook.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i did not reabse with latest code, but my local version have lots of code in optimzer prehook to track expert usage, bias, load balance loss, and load balance etc FYI

Comment thread torchtitan/models/common/aux_loss.py Outdated
"""Pop and reset the accumulated value, correcting for AC double-write."""
val = self._acc.detach().clone()
if self.ac_doubled:
val = val / 2

@pianpwk pianpwk Jul 13, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this double-counting, and how the flag is set, plus who's in charge of zeroing out the buffer may be fragile, though I don't really have a better solution. some considerations (just brain dumping):

A short-term solution could be: zero-out accumulator & write to the logging read buffer in inject, avoiding the double counting issue, and don't worry about batch-wise loss, or accumulating across microbatches yet.

cc @tianyu-l @shuhuayu

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I wonder if we could do something like the following:

  def should_run_forward() -> bool:
      if torch.compiler.is_compiling():
          return True                              # folds away at trace time
      return torch._C._current_graph_task_id() == -1   # eager: -1 == not in backward

The idea is that the AC running side effects is mainly an eager issue since compile already doesn't run side effects twice. So we just want a test that works in eager and return a constant True during trace time.

One case this doesn't handle is when AC wraps compile - and the side effect /would/ happen twice in that case, but since Titan only does this for FlexAttention, this seems fine too.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks -- accumulation in the autograd backward replaces the graph_task_id probe: no forward-time side effects, and AC recompute still cannot double-count (backward runs once per microbatch).

},
out_src_shardings=out_src,
out_dst_shardings=out_dst,
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is a nice way to handle it :)

aux_loss_coeff=1e-4,
router_num_expert_groups=8,
router_num_limited_groups=4,
router_route_scale=2.5,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  1. I had to change router_score_func="sigmoid" and router_route_norm=True in my PR to match the paper, maybe I was wrong? please do double check

  2. nit: would be nice to add a comment somewhere referencing, e.g. Computes Sequence-Wise Auxiliary Loss (DeepSeek-V3 Equations 17-20).

  3. was there a reason behind not supporting batch-wise loss in this PR? I understand it complicates things more.

Comment thread torchtitan/models/common/moe.py Outdated
f_BE = counts_BE * (E / (self.top_k * num_tokens_B.unsqueeze(1)))
p_BE = prob_sums_BE / num_tokens_B.unsqueeze(1)
loss_per_seq_B = (f_BE * p_BE).sum(dim=1)
return self.inject(carrier, loss_per_seq_B.sum())

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

once you get to typechecking, this may require a LocalMapConfig in sharding (maybe if EP on for the expert-dim split). let me know if you run into issues with that.

@sdmyzlp

sdmyzlp commented Jul 14, 2026

Copy link
Copy Markdown
Collaborator Author

@pianpwk Many thanks for the detailed review! I'll go through all the points and get back with fixes promptly.

scores_BLE: torch.Tensor,
topk_expert_ids_BLK: torch.Tensor,
*,
carrier: torch.Tensor,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what does this mean? Please add docstring

Comment thread torchtitan/models/common/aux_loss.py Outdated
class Config(Module.Config):
coeff: float
"""Aux loss coefficient. Scales the gradient contribution."""
tag: str = "aux_loss"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can we just use class name, instead of introducing another tag

Comment on lines +89 to +91
self.register_buffer(
"_acc", torch.zeros((), dtype=torch.float32), persistent=False
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what's this? Can we give it an expanded name, and add docstring?

Comment thread torchtitan/models/common/decoder.py Outdated
aux_loss_cfg.global_batch_size = config.training.global_batch_size
# Under compile, functionalize isolates AC recomputation's buffer
# mutation from the module -- only the forward path counts.
aux_loss_cfg.ac_doubled = (

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Comment thread torchtitan/models/common/aux_loss.py Outdated
for block in getattr(part, "layers", {}).values():
for module in block.modules():
if isinstance(module, LoggedAuxLoss):
local_sums[(module.reduce_mesh, module.tag)] += module.pop()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Coupling logging and clearing seems a bad idea. I'm OK with not handling logging in this PR and worry about it later. It is a limitation I confess, but proper tensor logging needs to be carefully designed.

Fwiw loss-free load balancing stats are also not logged https://github.com/pytorch/torchtitan/blob/main/torchtitan/components/optimizer.py#L431

In fact, could you handle the clearing together with loss-free load balancing, in the optimizer hook.

@tianyu-l

tianyu-l commented Aug 1, 2026

Copy link
Copy Markdown
Contributor

@sdmyzlp would you like to follow up on this PR?

@sdmyzlp

sdmyzlp commented Aug 1, 2026

Copy link
Copy Markdown
Collaborator Author

@sdmyzlp would you like to follow up on this PR?

@tianyu-l Yes, I'm still working on this PR and plan to finish it over the weekend. Really sorry for the delay — I'll push the updates as soon as possible.

@tianyu-l

tianyu-l commented Sep 6, 2026

Copy link
Copy Markdown
Contributor

@sdmyzlp In torchtitan, each microbatch on a single DP rank is a 1-D tokens (no batch vs. seq dims), consisting of multiple logical documents padded together. This is a common setup in LLM training / inference, and can be handled by pytorch varlen attention / Flash attention / Flex attention / etc.

Could you be precise about what sequence-wise LB loss mean in deepseek paper? At this point, it could mean either of

  • per DP-local microbatch -- I think this makes sense from an infra perspective. Namely, we want the destinations of All-to-All to be balanced, from each source.
  • per logical document -- This might help inference / decoding? I'm not sure.

But either way, code under #3864 (comment) needs to be adapted.

@sdmyzlp

sdmyzlp commented Sep 9, 2026 •

Copy link
Copy Markdown
Collaborator Author

Could you be precise about what sequence-wise LB loss mean in deepseek paper?

@tianyu-l The paper isn't clear about how the seqwise loss should be implemented — its T is "tokens in a sequence" with no further clarification for the document-packing scenario.

I surveyed the topic and found related material: arXiv:2501.11873 from the Qwen team shows that finer-grained load balancing may hurt model performance: micro-batch level LBL already constrains routing more tightly than global-batch level and inhibits expert specialization, and real-sequence level balancing would go a step further.

Given that DeepSeek-V3 already balances load at the corpus level with the auxiliary-loss-free approach, the seqwise loss should serve an infra purpose: preventing extreme imbalance within a single forward, which wastes expert capacity, rather than shaping specialization.

Also, per-document (varlen-aware) MoE balancing isn't what Megatron-LM or other frameworks do either. So we kept the per-forward interpretation for the time being: one forward (a DP-local microbatch) is the balancing unit.

def inject(self, raw_sum: torch.Tensor, *, carrier: torch.Tensor) -> torch.Tensor:
"""Inject the aux-loss gradient on ``carrier``; accumulate the scaled metric.

The accumulation is a forward side effect, so it runs inside a

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@anijain2305 could you review the remat usage in this PR?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry for the late reply. The torch_remat usage looks good to me.

Comment on lines +403 to +406
The returned value is ``T * L_bal`` (token-mode): Eqs 17-20 define a
per-token-normalized value, while ``LoggedAuxLoss`` scales every auxiliary
loss by ``1 / per_step_denominator`` (the step's token count), so the
sum-type form keeps the injected weight at ``coeff * L_bal``.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's subtle, but I'm slightly skeptical about this.

If I have 2 PP microbatches, each with 2 DP ranks, so I have 4 "local" microbatches. Should I take

  1. sum of per-microbatch loss, divided by 4, or
  2. sum of per-token loss, divided by num_tokens?

1 and 2 would be different when not all microbatches have the same amount of "lb-loss eligible" tokens. E.g. after this ongoing work #4168 (comment), we are going to trim the padding tokens when doing load balancing calculation. After that, which should we do:

  1. sum of per-microbatch loss on the non-padding tokens, divided by 4, or
  2. sum of per-non-padding-token loss, divided by total amount of non-padding tokens?

cc @acisseJZhong

@sdmyzlp sdmyzlp Sep 10, 2026 •

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

sum of per-non-padding-token loss, divided by total amount of non-padding tokens

I lean to this direction (option 2). The contract we propose for any further auxiliary loss is: each rank contributes a token-additive loss, and the framework divides by the global valid-token count -- the same denominator the main loss uses:

$$L = \alpha \cdot \frac{\sum_r L_r}{N_{valid}}, \qquad N_{valid} = \sum_r |S_r|$$

where $S_r$ is rank $r$'s non-padding tokens. No per-rank or per-microbatch averaging is applied, so the result is the per-token mean, independent of DP degree, PP microbatches and gradient accumulation.

The catch is that under the per-DP-microbatch interpretation the seqwise loss is NOT strictly token-additive. Additivity is restored only when the global batch and the microbatch granularity are fixed, and then at the granularity of forwards: with the set of forwards fixed, forward $m$ contributes its value to each of its $T_m$ valid tokens,

$$raw_m = T_m L_m, \qquad \frac{\sum_m raw_m}{N_{valid}} = \frac{\sum_m T_m L_m}{\sum_m T_m},$$

so the framework's divide-then-sum-over-ranks gives the token-weighted mean of the per-forward losses. Recutting the stream into different forwards is the only thing that changes the value. The CP communication in the seqwise loss exists precisely to preserve this per-DP-microbatch interpretation.

As for padding tokens: I refactored the implementation to normalize by the step's global_valid_tokens and to take the token count from the router's routing_map -- instead of inferring it from tensor shapes and mesh degrees. Once padding_mask-like inputs are threaded into TokenChoiceTopKRouter, the masked map gives the non-padding counts and the auxiliary loss should follow.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I lean to this direction (option 2).

I think this matches how cross-entropy loss is computed (although ce is token-wise), will be consistent with batch-wise lb loss, so makes more sense.

Additivity is restored only when the global batch and the microbatch granularity are fixed

Recutting the stream into different forwards is the only thing that changes the value.

Are you saying the loss will change if we change how we organize documents into microbatches? Sure but that'd be true no matter if we take option 1 or option 2 -- it's the nature of "SeqWise" loss.

In fact, given our implementation, I would suggest we rename SeqwiseLoadBalanceLoss to (dp local)MicrobatchWiseLoadBalanceLoss, if it makes sense to you. Later @pianpwk will add a GlobalBatchWiseLoadBalanceLoss

@tianyu-l
tianyu-l requested a review from pianpwk September 9, 2026 02:37
@sdmyzlp
sdmyzlp force-pushed the br_aux_loss branch 2 times, most recently from c413868 to ce71827 Compare September 10, 2026 02:09
@tianyu-l
tianyu-l requested review from anijain2305 and removed request for xmfan September 10, 2026 02:13
@sdmyzlp sdmyzlp changed the title [RFC] Add sequence-wise MoE load-balance auxiliary loss (DeepSeek-V3) Add LoggedAuxLoss and its first usage: the DeepSeek-V3 sequence-wise MoE balance loss Sep 10, 2026

@tianyu-l tianyu-l left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks great, only some minor feedbacks left -- please update the golden loss files and get ready for merge. Thanks!

Comment thread torchtitan/models/common/moe.py Outdated
Comment on lines +438 to +443
if get_spmd_backend() != "spmd_types":
raise ValueError(
"SeqwiseLoadBalanceLoss requires --parallelism.spmd_backend "
f"spmd_types, got {get_spmd_backend()!r}. The per-forward "
"counts all-reduce relies on spmd_types mesh semantics."
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

let's remove this, to make both our life easier #4419

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done

Comment thread torchtitan/models/common/aux_loss.py Outdated
return grad_carrier, torch.ones_like(aux_loss)


class LoggedAuxLoss(Module):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
class LoggedAuxLoss(Module):
class AuxLoss(Module):

because soon we'll have proper logging support for every module

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

applyed

Comment on lines +403 to +406
The returned value is ``T * L_bal`` (token-mode): Eqs 17-20 define a
per-token-normalized value, while ``LoggedAuxLoss`` scales every auxiliary
loss by ``1 / per_step_denominator`` (the step's token count), so the
sum-type form keeps the injected weight at ``coeff * L_bal``.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I lean to this direction (option 2).

I think this matches how cross-entropy loss is computed (although ce is token-wise), will be consistent with batch-wise lb loss, so makes more sense.

Additivity is restored only when the global batch and the microbatch granularity are fixed

Recutting the stream into different forwards is the only thing that changes the value.

Are you saying the loss will change if we change how we organize documents into microbatches? Sure but that'd be true no matter if we take option 1 or option 2 -- it's the nature of "SeqWise" loss.

In fact, given our implementation, I would suggest we rename SeqwiseLoadBalanceLoss to (dp local)MicrobatchWiseLoadBalanceLoss, if it makes sense to you. Later @pianpwk will add a GlobalBatchWiseLoadBalanceLoss

The multimodal models shared a multimodal_context() helper that marked the DP
axis local while preparing vision inputs.  Generalize it into
distributed/spmd_types.spmd_local_context(*axes) so other model code (the
aux-loss counts arithmetic) can use the same mechanism, and migrate the models
to it.  Behavior is unchanged: no-op outside spmd_types and for size-1 axes.
Auxiliary objectives inside the model (MoE load balance, a future DSA indexer
KL, ...) cannot reach the trainer's loss under pipeline parallelism, and a
per-layer loss value has nowhere to go in the model output.  AuxLoss
injects the gradient through an identity autograd Function (its forward returns
the carrier unchanged, its backward feeds the loss value back) and defers
per-step metric readout to the trainer.

The metric accumulates in the model forward inside a retained torch_remat
region so activation checkpointing never re-runs the side effect, is rolled
into per-group registers by an optimizer step pre-hook, and is reduced once per
log step by collect_aux_loss_metrics: summed over the configured reduce mesh
and the pipeline stages and divided by the build-time instance count, i.e. the
mean over all loss instances.

Every auxiliary loss is normalized by the step's global valid-token count
(set_step_denominator), the same denominator the main loss divides by, so its
scale is independent of parallelism degrees and comparable to the main loss.
…from the router

Implement the DeepSeek-V3 Sec 2.1.2 (Eqs 17-20) balance loss as a router-owned
aux loss.  The balancing unit is one forward's folded token stream, i.e. a
DP-local microbatch:

  f_i    = (E / (K T)) sum_t 1[token t routes to expert i]
  s'_t,i = s_t,i / sum_j s_t,j
  p_i    = (1 / T) sum_t s'_t,i
  L_bal  = sum_i f_i p_i

The one-hot counts are non-differentiable: the gradient reaches the router only
through the normalized-score sums and the top-k score carrier.  The counts and
the score sums are Partial over the axes that shard the token dim (CP always, TP
under EP), so they are all-reduced P -> I by axis name over the ambient mesh
before the formula; every rank of a DP group then holds the same value for the
stream.

The loss returns T * L_bal (token mode) so that AuxLoss's
1 / global-valid-tokens scaling lands on the per-token scale, and it evaluates
Eq. 18 in the T-free form f_i = E * counts_i / sum_j counts_j, which equals
(E / (K T)) * counts_i because each token contributes K entries.  The token
count therefore follows the routing map instead of the local shape and the mesh
degrees, so once the router masks padding out of the map the counts exclude it.
The loss no longer requires --parallelism.spmd_backend spmd_types either.

The router builds and returns that one-hot routing map (T, E) instead of the
full scores and passes it to the loss, so the loss counts exactly the tokens the
router counted; MoE and KimiLatentMoE only need the map, and the test stubs
follow the new contract.  make_moe_config installs the loss's own Config (no
extra fields, but a distinct class: Config.build() constructs the class that
owns the config, so the base AuxLoss.Config would build a module without a
forward).
…g them

Both trainers set AuxLoss's step denominator to the global valid-token
count they already resolve for the main loss, before the gradient-accumulation
loop, so auxiliary losses share the main loss's denominator and their
contribution does not depend on DP degree, PP microbatches or gradient
accumulation.  collect_aux_loss_metrics() joins the logged metrics of both
trainers.
Plumb aux_loss_coeff through build_mla_moe_layers and make_moe_config, set it to
1e-3 for all four flavors, and compose the load-balancing and aux-loss step
pre-hooks in the model registry's post_optimizer_build_fn.
… 16B routers

Align the two flavors with the DeepSeek-V3 router (sigmoid affinity with
normalized top-k scores) instead of softmax.  This changes their numerics and
the golden loss values.
…ominator

Compose the load-balancing and aux-loss step pre-hooks for the graph_trainer
deepseek_v3 registry, and set AuxLoss's step denominator in the tests that build
the model outside a trainer (trace and bitwise determinism).  precompile_main
sets it before tracing so the traced forward uses the same denominator a
training run does (the traced graph bakes the value in, hence the TODO there).
Six cases, one per distinct behavior: the value, the register and the injected
gradient against an explicit Eqs 17-20 reference (the gradient comparison also
pins down that the one-hot counts are non-differentiable); accumulation across
forwards plus roll-up/zero semantics; no double count under
torch_remat.checkpointing; the Config ownership make_moe_config relies on; an
8-rank CPU float64 + gloo spmd_types case (dp2/cp2/tp2) with EP token sharding
on and off and the typechecker on and off; and the pipeline-stage summation of
the collected metric.
@pytorch-bot

pytorch-bot Bot commented Sep 10, 2026

Copy link
Copy Markdown

Warning: Unknown label ciflow/graph-trainer.
Currently recognized labels are

  • ciflow/b200
  • ciflow/h100.8
  • ciflow/rl

Please add the new label to .github/pytorch-probot.yml

@tianyu-l

Copy link
Copy Markdown
Contributor

Thank you for the contribution!

RL side may need adaption, I'll follow up.

@tianyu-l
tianyu-l merged commit 183efed into pytorch:main Sep 10, 2026
31 checks passed
saforem2 added a commit to saforem2/torchtitan that referenced this pull request Sep 15, 2026
…pytorch#3864)

The last gap from the triage sweep. pytorch#3864 added LoggedAuxLoss, and core's
train_step calls AuxLoss.set_step_denominator(global_valid_tokens) at
trainer.py:914 so aux losses normalize on the same scale as the main loss.
ezpz overrides train_step and never calls super().__init__(), so it was
missing.

Latent, not load-bearing today: no ezpz config builds an AuxLoss -- every moe
router has aux_loss=None -- so inject() is unreachable. Committed anyway
because inject() RAISES on an unset denominator rather than skipping
(aux_loss.py:186-190), so the first config to enable an aux loss would die at
the first forward with a ValueError pointing at core rather than here.

An adversarial check called this not_a_break on the grounds that inject()
cannot be reached, which is correct for the current configs. Verified both
halves directly: the ValueError is real, and aux_loss is None on every ezpz
router. A guard costs one line; the failure mode it prevents is a confusing
traceback in someone else's file.

82 passed, 2 skipped; 14/14 imports unchanged.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/graph-trainer Run GraphTrainer CI ciflow/rl ciflow/8gpu CLA Signed This label is managed by the Meta Open Source bot.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants