Skip to content

[moe] load-balancing aux loss - #3000

Closed
pianpwk wants to merge 1 commit into
mainfrom
moe_aux_loss_v2
Closed

pianpwk wants to merge 1 commit into
mainfrom
moe_aux_loss_v2

Conversation

@pianpwk

@pianpwk pianpwk commented Apr 16, 2026 •

Copy link
Copy Markdown
Contributor

Adds MoE load-balancing aux loss following #2061.

For PP/compile compatibility, the aux_loss is implemented as an autograd.Function for loss gradient injection, following https://github.com/mlc-ai/pith-train/blob/main/pithtrain/modules/load_balance.py. Added a unit test to show this approach matches in numerics, to standard (loss + aux_loss).backward(). This is configured as a local_map region

We support 2 aux loss functions: batch-wise (batch-level stats) and seq-wise (seq-level stats). For parallelism compatibility, we allreduce routing expert counts across meshes:

  • for batch-wise, we allreduce counts across DP (batch-dim), CP (seq-dim), and TP (seq-dim when EP enabled), as a [# experts] tensor
  • for seq-wise, we allreduce counts across CP & TP on same conditions, as a [BS, # experts] tensor, as we cannot aggregate across batch dim.

The unsupported cases for batch-wise aux loss are gradient accumulation, and PP (w/ microbatching, but titan bans non-microbatched PP anyways), as the expert counts are approximate. Currently we error out for this (too strict?)

seq-wise aux loss (aux loss settings aren't in CLI): MODULE=deepseek_v3 CONFIG=deepseek_v3_debugmodel NGPU=4 ./run_train.sh

step:  1  loss:  8.04721  grad_norm:  4.0597  memory: 22.19GiB(28.04%)  tps: 4,794  tflops: 2.60  mfu: 0.83%
step:  5  loss:  4.42904  grad_norm:  2.3887  memory: 22.25GiB(28.12%)  tps: 19,275  tflops: 10.47  mfu: 3.35%
step: 10  loss:  3.85238  grad_norm:  1.5835  memory: 22.25GiB(28.12%)  tps: 19,077  tflops: 10.36  mfu: 3.32%

batch-wise aux loss (Qwen3 MoE debug uses batch-wise aux loss): MODULE=qwen3 CONFIG=qwen3_moe_debug NGPU=4 ./run_train.sh

step:  1  loss:  8.07451  grad_norm:  2.5818  memory:  3.84GiB(4.85%)  tps: 2,089  tflops: 2.32  mfu: 0.74%
step:  5  loss:  5.07399  grad_norm:  2.6846  memory:  4.43GiB(5.60%)  tps: 23,166  tflops: 25.74  mfu: 8.25%
step: 10  loss:  4.51730  grad_norm:  2.5816  memory:  4.43GiB(5.60%)  tps: 24,027  tflops: 26.70  mfu: 8.56%

seq-wise, compile: MODULE=deepseek_v3 CONFIG=deepseek_v3_debugmodel NGPU=4 ./run_train.sh --compile.enable

step:  1  loss:  8.13759  grad_norm:  4.0312  memory: 16.86GiB(21.31%)  tps: 360  tflops: 0.20  mfu: 0.06%
step:  5  loss:  4.35701  grad_norm:  2.3747  memory: 16.90GiB(21.35%)  tps: 28,007  tflops: 15.21  mfu: 4.87%
step: 10  loss:  3.82011  grad_norm:  1.4143  memory: 16.90GiB(21.35%)  tps: 28,781  tflops: 15.63  mfu: 5.01%

seq-wise, compile + PP=4 (1F1B): LOG_RANK=3 MODULE=deepseek_v3 CONFIG=deepseek_v3_debugmodel NGPU=4 ./run_train.sh --compile.enable --parallelism.pipeline_parallel_degree=4 --parallelism.pipeline_parallel_schedule="1F1B" --parallelism.pipeline_parallel_microbatch_size=1

step:  1  loss:  8.14354  grad_norm:  3.2394  memory:  0.78GiB(0.98%)  tps: 71  tflops: 0.04  mfu: 0.01%
step:  5  loss:  4.65961  grad_norm:  2.6585  memory:  0.80GiB(1.01%)  tps: 9,895  tflops: 5.37  mfu: 1.72%
step: 10  loss:  4.15489  grad_norm:  2.1032  memory:  0.80GiB(1.01%)  tps: 10,878  tflops: 5.91  mfu: 1.89%

seq-wise, compile + FSDP=2, PP=2 (Interleaved1F1B): LOG_RANK=3 MODULE=deepseek_v3 CONFIG=deepseek_v3_debugmodel NGPU=4 ./run_train.sh --compile.enable --parallelism.pipeline_parallel_degree=2 --parallelism.data_parallel_shard_degree=2 --parallelism.pipeline_parallel_schedule="Interleaved1F1B" --parallelism.pipeline_parallel_microbatch_size=1

step:  1  loss:  8.09411  grad_norm:  3.5881  memory:  2.64GiB(3.34%)  tps: 212  tflops: 0.12  mfu: 0.04%
step:  5  loss:  4.43106  grad_norm:  2.5952  memory:  2.69GiB(3.40%)  tps: 14,186  tflops: 7.70  mfu: 2.47%
step: 10  loss:  3.84682  grad_norm:  1.7512  memory:  2.69GiB(3.40%)  tps: 13,517  tflops: 7.34  mfu: 2.35%

seq-wise, FSDP=2, PP=2 (ZBV). no compile, no AC (ZBV + compile/AC fails): LOG_RANK=1 MODULE=deepseek_v3 CONFIG=deepseek_v3_debugmodel NGPU=4 ./run_train.sh --parallelism.pipeline_parallel_degree=2 --parallelism.data_parallel_shard_degree=2 --parallelism.pipeline_parallel_schedule="ZBVZeroBubble" --parallelism.pipeline_parallel_microbatch_size=1 --activation_checkpoint.mode=none

step:  1  loss:  8.20286  grad_norm:  3.3025  memory:  2.67GiB(3.38%)  tps: 1,364  tflops: 0.74  mfu: 0.24%
step:  5  loss:  4.45793  grad_norm:  2.4340  memory:  2.71GiB(3.43%)  tps: 9,726  tflops: 5.28  mfu: 1.69%
step: 10  loss:  3.96624  grad_norm:  1.8390  memory:  2.71GiB(3.43%)  tps: 9,671  tflops: 5.25  mfu: 1.68%

batch-wise + PP errors, as aux loss is not additive over microbatches: NGPU=2 COMM_MODE=fake_backend MODULE=qwen3 CONFIG=qwen3_moe_debug ./run_train.sh --training.steps 1 --parallelism.pipeline_parallel_degree 2 --parallelism.pipeline_parallel_microbatch_size 4

ValueError: batch_wise MoE aux loss is incompatible with pipeline parallelism because TorchTitan PP schedules split batches into pipeline microbatches. Use sequence_wise instead.

batch-wise + gradient accumulation errors, as aux loss is not additive over gradient accumulation microbatches: NGPU=2 COMM_MODE=fake_backend MODULE=qwen3 CONFIG=qwen3_moe_debug ./run_train.sh --training.steps 1 --parallelism.data_parallel_shard_degree 2 --training.global_batch_size 16

ValueError: batch_wise MoE aux loss is incompatible with gradient accumulation. Use sequence_wise instead or set training.global_batch_size to local_batch_size * data-parallel degree.

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Apr 16, 2026
@pianpwk pianpwk changed the title pp auxloss [moe] load-balancing aux loss Apr 21, 2026
@tianyu-l
tianyu-l requested a review from shuhuayu April 22, 2026 23:06
Comment thread torchtitan/models/common/moe.py Outdated
ctx.aux_loss_weight, # pyrefly: ignore [missing-attribute]
)
(aux_grad,) = torch.autograd.grad(aux_loss, scores_detached)
return grad_scores + aux_grad, None, None, None, None, None, None, None

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

note (@tianyu-l): prefer compute aux_loss in fwd & save

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.

iirc, this is something (nested autograd) @xmfan wanted to avoid for graph breaks? We can 1) write the grad function analytically, can be tedious or 2) use torch.func.grad to transform the aux loss function, which is perhaps the simplest approach, or 3) use torch.library.custom_op+ register_autograd as in deepep.py. I think all of these approaches can avoid the global config added in this pr torch._dynamo.config.trace_autograd_ops = True, which can have side effects globally. Maybe Simon can correct me if anything not making sense.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I went with torch.func.grad to remove the flag, but it seems the loss computation is still in backwards. I don't think we save any memory by computing the loss in FWD.

@shuhuayu shuhuayu Apr 23, 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.

Yeah, that's by design. We do not compute loss in the forward to avoid coupling with modeling loss which breaks pp. All we need is its gradients in the backward. On the other hand, if we want to log load balancing loss to monitor the healthiness of training, we can do it under torch.no_grad()in the forward.

Comment thread torchtitan/models/common/moe.py Outdated
Comment on lines +181 to +206
with torch.enable_grad():
scores_detached = scores.detach().requires_grad_(True)
if (
ctx.aux_loss_type == "sequence_wise"
): # pyrefly: ignore [missing-attribute]
aux_loss = MoE._sequence_wise_aux_loss(
scores_detached,
selected_experts_indices,
ctx.bs, # pyrefly: ignore [missing-attribute]
ctx.slen, # pyrefly: ignore [missing-attribute]
ctx.top_k, # pyrefly: ignore [missing-attribute]
ctx.aux_loss_weight, # pyrefly: ignore [missing-attribute]
)
else:
num_tokens_per_expert = torch.histc(
selected_experts_indices.view(-1).float(),
bins=ctx.num_experts, # pyrefly: ignore [missing-attribute]
min=0,
max=ctx.num_experts, # pyrefly: ignore [missing-attribute]
)
aux_loss = MoE._batch_wise_aux_loss(
scores_detached,
num_tokens_per_expert,
ctx.top_k, # pyrefly: ignore [missing-attribute]
ctx.aux_loss_weight, # pyrefly: ignore [missing-attribute]
)

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.

why don't we compute these in forward?

Comment thread torchtitan/models/qwen3_vl/model.py Outdated
layer_cfg.moe.router._debug_force_load_balance = (
debug.moe_force_load_balance
)
apply_moe_load_balance_config(

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.

put this at config time, not run time

Comment thread torchtitan/config/configs.py Outdated
Comment on lines +82 to +90
moe_aux_loss_weight: float = 0.0
"""Weight for the MoE auxiliary load-balance loss. 0 disables it."""

moe_aux_loss_type: Literal["sequence_wise", "batch_wise"] = "sequence_wise"
"""Type of MoE auxiliary load-balance loss."""

moe_load_balance_coeff: float | None = 1e-3
"""Coefficient for aux-loss-free bias-based MoE load balancing.
Overrides the model config default when set. None disables it."""

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 this in model_registry not allow to override per CLI job

Comment thread torchtitan/models/common/moe.py Resolved
@rakkit

rakkit commented Apr 23, 2026

Copy link
Copy Markdown
Contributor

would be good if we add a buffer of load_balance_loss together with tokens_per_expert so one can log it out in pre-optim step hook.

@tianyu-l

tianyu-l commented Apr 23, 2026 •

Copy link
Copy Markdown
Contributor

would be good if we add a buffer of load_balance_loss together with tokens_per_expert so one can log it out in pre-optim step hook.

@rakkit Logging capability will be separately addressed by @felipemello1 in a PR similar to #2607. Will tag you for review.

Comment thread torchtitan/models/common/moe.py Outdated
return (f_i * p_i).sum() * aux_loss_weight


class _AuxLossBackward(torch.autograd.Function):

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 we can just use some regular name like LoadBalanceAuxLoss? Did not get why we need to put Backward only in the name.

@pianpwk
pianpwk marked this pull request as ready for review April 28, 2026 17:52
@pianpwk
pianpwk requested a review from tianyu-l April 28, 2026 17:52
router_top_k=3,
router_score_func="softmax",
score_before_experts=False,
aux_loss=MoELoadBalanceAuxLoss.Config(weight=1e-4),

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.

check technical report of dsv3 and see if it's actually used.

IIRC qwen3 used it so let's enable it for qwen3. Need to check gpt-oss as well.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

yes this is from the hyperparams section; I'll check the other 2

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Comment thread torchtitan/trainer.py Outdated
"batch_wise MoE aux loss is incompatible with pipeline "
"parallelism. Use sequence_wise instead."
)
aux_loss.local_batch_size = config.training.local_batch_size

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.

should be done at config time not here.

Comment thread torchtitan/trainer.py Outdated
aux_loss = layer_cfg.moe.aux_loss
if aux_loss.weight > 0:
if aux_loss.type == "batch_wise" and pp_enabled:
raise ValueError(

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.

should be done in update_from_configs fn, not here

Comment thread torchtitan/models/common/moe.py Outdated
config.shared_experts.build() if config.shared_experts is not None else None
)
self.aux_loss = MoELoadBalanceAuxLoss(config.aux_loss)
self.aux_loss.top_k = config.router.top_k

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.

should be set in config time

Comment thread torchtitan/models/common/moe.py Outdated
self.shared_experts = (
config.shared_experts.build() if config.shared_experts is not None else None
)
self.aux_loss = MoELoadBalanceAuxLoss(config.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.

use build, not constructor

Comment thread torchtitan/models/common/moe.py Outdated
class Config:
weight: float = 0.0
"""Weight for the auxiliary load-balance loss. 0 disables it."""
type: Literal["sequence_wise", "batch_wise"] = "sequence_wise"

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 have two subclasses, rather than using a str factory

Comment thread torchtitan/models/common/moe.py Outdated
bs: int,
slen: int,
) -> torch.Tensor:
if self.weight <= 0:

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.

why it would be < 0?

Comment thread torchtitan/models/common/moe.py Outdated
local_batch_size: int | None = None
"""Total local batch size (before microbatching). Used to normalize aux
loss gradients across pipeline-parallel microbatches so they match the
non-PP case. Set automatically by the trainer; None means use the

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.

oh, could you remind me why not using global batch size?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

IIUC this is to match the non-microbatch-pipelining variant; the loss should be averaged across all tokens this sees, but this autograd fn will accumulate gradient across microbatches, so we normalize by micro_bs / local_bs .

Comment thread torchtitan/models/common/moe.py Outdated
- num_tokens_per_expert (torch.Tensor):
Number of tokens assigned to each expert with shape ``(num_experts,)``.
- scores (torch.Tensor):
Full router scores for all experts with shape ``(bs*slen, num_experts)``.

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.

add reasons to have this field returned (for load balance loss)

Comment thread torchtitan/models/common/moe.py Outdated
class _AuxLossBase(torch.autograd.Function):
"""Injects auxiliary load-balance loss gradients at the router scores level.

Identity in forward (returns ``top_scores`` unchanged). In backward,

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.

Identity in forward (returns top_scores unchanged)

Is this even a goal?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

this is so it stays on the autograd graph, will update the docstring

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.

Returning top_scores unchanged sounds necessary, but is it necessary to save all activations for backward and do no-op in forward?

@tianyu-l
tianyu-l requested a review from shuhuayu April 29, 2026 19:49
Comment thread torchtitan/models/common/moe.py Outdated
Expert indices selected for each token with shape ``(bs*slen, top_k)``.
- num_tokens_per_expert (torch.Tensor):
Number of tokens assigned to each expert with shape ``(num_experts,)``.
- scores (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.

nit: can we put scores before top_scores? just put scores together.

Comment thread torchtitan/models/qwen3/model.py Outdated
debug.moe_force_load_balance
)

if training is not None:

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.

why qwen3 has this condition check, what's the difference with other models?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

gonna remove this

Comment thread torchtitan/models/gpt_oss/__init__.py Outdated
),
top_k=top_k,
),
aux_loss=BatchWiseAuxLoss.Config(weight=1e-3),

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 you put some reference here where we know it uses batchwise

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I actually couldn't find arxiv references, so left hf urls - maybe that's inaccurate/weird. also don't have something for llama4 yet.

Comment thread torchtitan/models/llama4/__init__.py Outdated
router=router,
experts=experts,
shared_experts=shared_experts,
aux_loss=BatchWiseAuxLoss.Config(weight=1e-3),

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.

similar

non_blocking_capacity_factor=non_blocking_capacity_factor,
),
aux_loss=BatchWiseAuxLoss.Config(weight=1e-3),
),

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.

similar, we need some references, may be helpful these two

  1. https://arxiv.org/pdf/2505.09388
  2. https://arxiv.org/pdf/2501.11873

Is our batchwise auxloss equivalent to the global batch lbl? How do we compute average loss over dp ranks? Like the equation (4) in the paper 2 above.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

this is batch-wise aux loss yes, currently we ban with PP because it's not additive across microbatches, maybe we should ban with DP too until the count accumulator is implemented.

Comment thread torchtitan/models/common/moe.py Outdated
to ``scores``'s gradient. ``top_scores`` is a pass-through so this node
remains in the autograd graph.

Uses ``torch.func.grad`` instead of nested ``torch.autograd.grad`` to

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 avoiding this global config is part our code iterating process and no need to reveal it to the users.

Comment thread torchtitan/models/common/moe.py Outdated
(
scores,
selected_experts_indices,
) = ctx.saved_tensors

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.

maybe add one line comment if we want to be explicit.

Suggested change
) = ctx.saved_tensors
) = ctx.saved_tensors
# torch.func.grad avoids the graph break that torch.autograd.grad causes under torch.compile

@pianpwk
pianpwk force-pushed the moe_aux_loss_v2 branch 2 times, most recently from fcb7eff to 4f80bc3 Compare April 30, 2026 21:36
Comment thread torchtitan/models/common/moe.py Outdated
indices_per_seq = selected_experts_indices.view(bs, -1)
offset = torch.arange(bs, device=indices_per_seq.device).unsqueeze(1) * num_experts
flat_indices = (indices_per_seq + offset).reshape(-1)
counts = torch.bincount(flat_indices.long(), minlength=bs * num_experts)

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 you double check whether torch.bincout leads to a graph break under torch.compile? Maybe we need .scatter_add on a sparse tensor.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

This runs under compile, I believe capture_scalar_outputs enables capturing the output shape.

@pianpwk
pianpwk force-pushed the moe_aux_loss_v2 branch from 4f80bc3 to e8fe522 Compare May 7, 2026 06:36
num_shared_experts=num_shared_experts,
router_top_k=6,
router_score_func="softmax",
router_score_func="sigmoid",

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.

Why changing default? If aux loss is only supported with sigmoid, let's delete this model variant.

@pianpwk pianpwk May 10, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

need another pair of eyes, but I think default might been wrong? paper looks like sigmoid + route_norm

Image

) -> list[TransformerBlock.Config]:
"""Build per-layer configs for MoE Qwen3 models with depth-scaled inits."""
"""
Build per-layer configs for MoE Qwen3 models with depth-scaled inits.

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.

should load_balance_coeff be None for qwen and llama4, as they use aux loss?

Comment thread torchtitan/models/common/moe.py Outdated
Comment on lines +434 to +435
weight: float = 0.0
"""Weight for the auxiliary load-balance loss. 0 disables it."""

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.

too many ways to disable it -- let's assert weight>0 here. If users want to disable it, they can set moe.aux_loss to None.

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.

also, should it be called coeff to be consistent with loss-free load balance coeff and with other repo?

Comment thread torchtitan/models/common/moe.py Outdated
class SequenceWiseAuxLoss(MoELoadBalanceAuxLoss):
"""Sequence-wise auxiliary load-balance loss (DeepSeek-V3 Eqs 17-20)."""

_autograd_fn = _SequenceWiseAuxLoss

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 didn't get why we need so many layers of nesting.
Can we have MoELoadBalanceAuxLoss inheriting both Configurable and torch.autograd.Function and just have one layer?

Comment thread torchtitan/models/common/moe.py Outdated
return self.token_dispatcher.combine(routed_output, metadata, x, shared_experts)


def _sequence_wise_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 inline these inside the autograd function?

Comment thread torchtitan/trainer.py
Comment on lines +244 to +254
global_batch_size = config.training.global_batch_size
if global_batch_size < 0:
global_batch_size = config.training.local_batch_size * batch_degree
assert global_batch_size > 0
assert (
global_batch_size % (config.training.local_batch_size * batch_degree) == 0
), (
f"global batch size must be multiple of local batch size times "
f"data-parallel degree ({global_batch_size} "
f"% ({config.training.local_batch_size} * {batch_degree}) != 0)"
)

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.

prefer to not change the location for now

Comment thread torchtitan/models/common/moe.py Outdated
class Config(Configurable.Config):
weight: float = 0.0
"""Weight for the auxiliary load-balance loss. 0 disables it."""
top_k: int = 1

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.

shouldn't have a default value. It should be either set in config setup, or passed from other module at run time.

Comment thread torchtitan/models/common/moe.py Outdated
) -> torch.Tensor:
if self.weight == 0:
return top_scores
global_bs = self.global_batch_size or bs

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 unclear what it is doing

@pianpwk pianpwk May 10, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

think this means no normalization when global_batch_size isn't passed (e.g. no microbatching).

Comment thread torchtitan/models/common/moe.py Outdated
if self.weight == 0:
return top_scores
global_bs = self.global_batch_size or bs
scaled_weight = self.weight * bs / global_bs

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 use consistent variable name

Comment thread torchtitan/models/common/moe.py Outdated
class _AuxLossBase(torch.autograd.Function):
"""Injects auxiliary load-balance loss gradients at the router scores level.

Identity in forward (returns ``top_scores`` unchanged). In backward,

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.

Returning top_scores unchanged sounds necessary, but is it necessary to save all activations for backward and do no-op in forward?

@pianpwk
pianpwk force-pushed the moe_aux_loss_v2 branch from e8fe522 to 635df88 Compare May 10, 2026 22:32
Comment thread torchtitan/models/common/moe.py Outdated
min=0,
max=num_experts,
)
p_i = scores.mean(dim=0)

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 seems to be wrong. When computing batch-wise mean, for expert i, we should first compute each token's probability of of choosing expert i, then compute the average over all tokens.

Comment thread torchtitan/models/common/moe.py Outdated
aux_loss_coeff: float,
loss_type: str,
) -> torch.Tensor:
ctx.save_for_backward(scores, selected_experts_indices)

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.

we do not need to save selected_exeprts_indices, we only need to save the values of f_i.

@pianpwk
pianpwk force-pushed the moe_aux_loss_v2 branch from a24192a to 4bd1c6b Compare June 5, 2026 22:57

@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.

Is the plan to land this or #3864?

return _AuxLossAutograd.apply(topk_scores_BLK, aux_loss)


def configure_moe_aux_loss_reduction(model: nn.Module, parallel_dims) -> None:

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.

we can now get these meshes from current mesh global context, right?


@dataclass(kw_only=True, slots=True)
class Config(Module.Config):
type: Literal["sequence_wise", "batch_wise"]

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.

more extensible way should be letting two variants inherit MoELoadBalanceAuxLoss which serves as a base class.

tp_mesh=self.tp_mesh,
)
else:
aux_loss = _batch_wise_load_balance_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.

Should we error out when PP / gradient accumulation is used?

Then I'm worried because our RL stack would almost always need gradient accumulation, so we probably should try to make it work.

@tianyu-l

Copy link
Copy Markdown
Contributor

following up in #3864

@tianyu-l tianyu-l closed this Aug 20, 2026
jialei777 pushed a commit to jialei777/torchtitan that referenced this pull request Oct 19, 2026
Add sequence-wise and global-batch auxiliary load-balancing objectives
for MoE routing. Inject the auxiliary gradient through the selected router
scores, propagate the required batch metadata through sharding, and add a
Qwen3 30B-A3B global-aux recipe.

Based on pytorch#3000. Preserve Qwen3's softmax router because
the auxiliary objective consumes its expert probabilities. Batch-wise LBL
currently rejects pipeline parallelism and gradient accumulation rather
than silently applying an incorrectly scoped objective.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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.

4 participants