Repository navigation
Add LoggedAuxLoss and its first usage: the DeepSeek-V3 sequence-wise MoE balance loss - #3864
Conversation
|
|
96e4048 to
2def8b1
Compare
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 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. |
913a9a5 to
5bbf76f
Compare
pianpwk
left a comment
There was a problem hiding this comment.
thank you for the PR! leaving some thoughts
| def typecheck_forward( | ||
| carrier: torch.Tensor, aux_loss: torch.Tensor | ||
| ) -> torch.Tensor: | ||
| return _AuxLossInjection.apply(carrier, aux_loss) |
There was a problem hiding this comment.
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 :)
| aux_loss_cfg.ac_doubled = ( | ||
| config.activation_checkpoint is not None | ||
| and not config.compile.enable | ||
| ) |
There was a problem hiding this comment.
do you know how well this handles partial (e.g. selective) AC? are there cases where this isn't recomputed, but other parts are
There was a problem hiding this comment.
actually I would check how to utilize
torchtitan/torchtitan/components/optimizer.py
Lines 428 to 429 in 51c197c
| 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() |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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
| """Pop and reset the accumulated value, correcting for AC double-write.""" | ||
| val = self._acc.detach().clone() | ||
| if self.ac_doubled: | ||
| val = val / 2 |
There was a problem hiding this comment.
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):
- zeroing out should be at least once per training step
- if there's no microbatching + grad accum, one effective solution could be to keep a separate buffer for logging reads, and on every
inject()call, overwrite that buffer, and zero out _acc. So if AC runs we just write the same value twice - microbatching + gradient accumulation complicates things, because in some cases, we likely want the stats after all microbatches (flow is FWD1 -> ACFWD1 -> FWD2 -> ACFWD2 -> ...). e.g. for batch-wise loss, it seems desirable to really get global stats: https://arxiv.org/abs/2501.11873. Though that requires more work, e.g. inject on last microbatch, could be one approach, but happy to hear any ideas. My previous attempt in [moe] load-balancing aux loss #3000 bans microbatching altogether, but that could be too strict.
- Allow branching on whether you are in AC region with is_checkpoint_enabled pytorch#160888 is an older pytorch PR (maybe being revived), which would ideally skip accumulation in AC (cc @soulitzer)
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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, | ||
| ) |
There was a problem hiding this comment.
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, |
There was a problem hiding this comment.
-
I had to change
router_score_func="sigmoid"androuter_route_norm=Truein my PR to match the paper, maybe I was wrong? please do double check -
nit: would be nice to add a comment somewhere referencing, e.g.
Computes Sequence-Wise Auxiliary Loss (DeepSeek-V3 Equations 17-20). -
was there a reason behind not supporting batch-wise loss in this PR? I understand it complicates things more.
| 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()) |
There was a problem hiding this comment.
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.
|
@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, |
There was a problem hiding this comment.
what does this mean? Please add docstring
| class Config(Module.Config): | ||
| coeff: float | ||
| """Aux loss coefficient. Scales the gradient contribution.""" | ||
| tag: str = "aux_loss" |
There was a problem hiding this comment.
can we just use class name, instead of introducing another tag
| self.register_buffer( | ||
| "_acc", torch.zeros((), dtype=torch.float32), persistent=False | ||
| ) |
There was a problem hiding this comment.
what's this? Can we give it an expanded name, and add docstring?
| 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 = ( |
There was a problem hiding this comment.
the aux-loss-free load balancing is handling this here https://github.com/pytorch/torchtitan/blob/main/torchtitan/components/optimizer.py#L441
can we follow?
| 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() |
There was a problem hiding this comment.
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.
|
@sdmyzlp would you like to follow up on this PR? |
|
@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
But either way, code under #3864 (comment) needs to be adapted. |
@tianyu-l The paper isn't clear about how the seqwise loss should be implemented — its 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 |
There was a problem hiding this comment.
@anijain2305 could you review the remat usage in this PR?
There was a problem hiding this comment.
Sorry for the late reply. The torch_remat usage looks good to me.
| 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``. |
There was a problem hiding this comment.
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
- sum of per-microbatch loss, divided by 4, or
- 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:
- sum of per-microbatch loss on the non-padding tokens, divided by 4, or
- sum of per-non-padding-token loss, divided by total amount of non-padding tokens?
There was a problem hiding this comment.
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:
where
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
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.
There was a problem hiding this comment.
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
c413868 to
ce71827
Compare
tianyu-l
left a comment
There was a problem hiding this comment.
Looks great, only some minor feedbacks left -- please update the golden loss files and get ready for merge. Thanks!
| 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." | ||
| ) |
There was a problem hiding this comment.
let's remove this, to make both our life easier #4419
| return grad_carrier, torch.ones_like(aux_loss) | ||
|
|
||
|
|
||
| class LoggedAuxLoss(Module): |
There was a problem hiding this comment.
| class LoggedAuxLoss(Module): | |
| class AuxLoss(Module): |
because soon we'll have proper logging support for every module
| 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``. |
There was a problem hiding this comment.
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.
ce71827 to
4422c97
Compare
|
Warning: Unknown label
Please add the new label to .github/pytorch-probot.yml |
|
Thank you for the contribution! RL side may need adaption, I'll follow up. |
…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.
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:torch_rematregion so activation checkpointing never re-runs the side effect. A step pre-hook rolls the instances into per-group registers, andcollect_aux_loss_metricsreduces 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):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:
make_moe_config(aux_loss_coeff=...)enables the loss at 1e-3 for every deepseek_v3 flavor.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.pycovers 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 undertorch_remat.checkpointing; the Config ownershipmake_moe_configrelies 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. Thetest_moe.pyand gputest_remat.pystubs follow the router's new return value.Follow-ups
torch_rematregion only takes effect underRegionAC; under the PyTorch-checkpoint policies (FullAC,SelectiveAC) the enclosing block is replayed and the logged metric over-counts (2x underFullAC). The injected gradient is unaffected..item()today; it should go through the GPU-tensor logging framework (TODO Add distributed tensor logging #4202 inaux_loss.py) once that lands.