Skip to content

Add global batch-wise MoE auxiliary loss - #4772

Merged
pianpwk merged 21 commits into
mainfrom
gh/pianpwk/103/head
Oct 12, 2026
Merged

pianpwk merged 21 commits into
mainfrom
gh/pianpwk/103/head

Conversation

@pianpwk

@pianpwk pianpwk commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

[ghstack-poisoned]
[ghstack-poisoned]
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Sep 17, 2026
pianpwk added a commit that referenced this pull request Sep 17, 2026
ghstack-source-id: a21e261
Pull Request resolved: #4772
[ghstack-poisoned]
pianpwk added a commit that referenced this pull request Sep 17, 2026
ghstack-source-id: 961706c
Pull Request resolved: #4772
@pianpwk
pianpwk marked this pull request as ready for review September 18, 2026 22:27
@pytorch-bot pytorch-bot Bot added ciflow/fake-pg Run 1-GPU Fake PG integration tests ciflow/rl labels Sep 18, 2026
Comment thread torchtitan/models/gpt_oss/__init__.py Outdated
hidden_dim=hidden_dim,
num_experts=8,
top_k=4,
load_balance_coeff=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.

did you find out which load balancing scheme gpt-oss use from literature?

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/models/qwen3/__init__.py Outdated
comm_backend=moe_comm_backend,
non_blocking_capacity_factor=non_blocking_capacity_factor,
),
aux_loss_coeff=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.

I think we also need to make this None for qwen
https://github.com/pytorch/torchtitan/blob/main/torchtitan/models/common/config_utils.py#L316

Actually default should be None to avoid mistake in the future.

Comment thread torchtitan/models/qwen3/__init__.py Outdated

def _post_optimizer_build_fn(optimizers, model_parts, parallel_dims):
"""Register step pre-hooks for load balancing and aux-loss accumulators."""
register_moe_load_balancing_hook(optimizers, model_parts, parallel_dims)

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.

don't need this?

Comment on lines +326 to +327
elif aux_loss_type == "global_batch_wise":
aux_loss = GlobalBatchWiseLoadBalanceLoss.Config(coeff=aux_loss_coeff)

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.

sounds unambiguous to just

Suggested change
elif aux_loss_type == "global_batch_wise":
aux_loss = GlobalBatchWiseLoadBalanceLoss.Config(coeff=aux_loss_coeff)
elif aux_loss_type == "batch_wise":
aux_loss = BatchWiseLoadBalanceLoss.Config(coeff=aux_loss_coeff)

Comment thread torchtitan/models/common/moe.py Outdated
)


def _reduce_token_partials(

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.

does it make sense to put them under AuxLoss for now?

Comment thread torchtitan/models/common/moe.py Outdated
Comment on lines +689 to +692
if self._cumulative_expert_counts_E is None:
self._cumulative_expert_counts_E = torch.zeros_like(
global_counts_E, dtype=torch.float32
)

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.

may not be cudagraph friendly if we reuse cudagraph for every spmd (outer) grad accum? But I think we probably will move to all spmd grad accum steps captured in one big cudagraph anyway. cc @fegin

That said, any reason we don't allocate memory for the final shape upfront?

Comment thread torchtitan/config/validation.py Outdated
Comment on lines +37 to +40
"GlobalBatchWiseLoadBalanceLoss with multiple microbatches is "
"incompatible with activation checkpointing because recomputation "
"would advance its rolling expert counts. Disable activation "
"checkpointing or use MicrobatchWiseLoadBalanceLoss."

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.

Sounds too big of a limitation, as models using this loss cannot be trained with AC anymore.

On the other hand, I believe torch_remat can work around this? @anijain2305

[ghstack-poisoned]
[ghstack-poisoned]
pianpwk added a commit that referenced this pull request Sep 29, 2026
ghstack-source-id: fa71f93
Pull Request resolved: #4772
Comment thread torchtitan/config/validation.py Outdated
"would read rolling expert counts from later microbatches. Disable "
"activation checkpointing, use one pipeline microbatch, or use "
"MicrobatchWiseLoadBalanceLoss."
)

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 am looking into this, but seems like it's a bug that actually helps modeling, because this is mutable state?

say you have pp schedule like
f0 f1 f2 f3 b0 b1 b2 b3

with no AC, b0 will read the stats buffer saved from counts(f0), so it's just the first batch
b1 reads counts(f0) + counts(f1), so it's the rolling approximate

with AC, it seems the buffer is not snapshotted, but used when b0 recomputes f0. but now f0-f3 have accumulated into the buffer, so it actually reads the global stat counts(f0) + counts(f1) + counts(f2) + counts(f3), which is not approximate but exact lol

but also the exact numerics will depend on PP schedule
@soulitzer in case this makes sense to you, maybe i'm doing something 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.

oh, sounds subtle

  • the accumulation idea itself is approximation
  • the only problem with PP is that different schedules don't get the same numerics
  • but I guess it's hard for future features to be developed when comparing numerics -- people might have forgot that the aux loss can change "drastically" when changing schedules, so I'm OK with erroring out
  • in particular, the original paper only mentions grad accum, not PP at all

@pianpwk

pianpwk commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor Author

@tianyu-l just updated, should now follow flow of

  • zero buffer is instantiated, zeroed in optimizer pre hook
  • for stats accumulation, use remat.is_recomputing / AC check (should support both fullAC & SAC?) suggested by @soulitzer to see if we're in recomputed FWD, accumulate if in original
  • BWD always reads buffer at the time, so microbatch + AC is good, but PP microbatch + AC has a weird beneficial bug

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

Please address remaining comments before landing.

Comment thread torchtitan/trainer.py Outdated
Comment on lines +229 to +233
validate_batch_wise_aux_loss(
model_config,
num_pp_microbatches=self.num_pp_microbatches,
activation_checkpoint_enabled=config.activation_checkpoint 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.

this can be put in TrainingEngine.Config.__post_init__()?

Comment thread torchtitan/models/common/moe.py Outdated
Comment on lines +596 to +598
if torch.compiler.is_compiling():
# No eager replay under compile; the partitioner rematerializes instead.
return 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.

I think we can remove this because we recently deprecated per-block compilation.

Comment thread torchtitan/models/common/moe.py Outdated
if torch.compiler.is_compiling():
# No eager replay under compile; the partitioner rematerializes instead.
return False
return remat.is_recomputing() or torch._C._current_graph_task_id() != -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.

can inline this

Comment thread torchtitan/config/validation.py Outdated
"would read rolling expert counts from later microbatches. Disable "
"activation checkpointing, use one pipeline microbatch, or use "
"MicrobatchWiseLoadBalanceLoss."
)

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, sounds subtle

  • the accumulation idea itself is approximation
  • the only problem with PP is that different schedules don't get the same numerics
  • but I guess it's hard for future features to be developed when comparing numerics -- people might have forgot that the aux loss can change "drastically" when changing schedules, so I'm OK with erroring out
  • in particular, the original paper only mentions grad accum, not PP at all

[ghstack-poisoned]
[ghstack-poisoned]
pianpwk added a commit that referenced this pull request Oct 7, 2026
ghstack-source-id: d2bf2b7
Pull Request resolved: #4772
),
checkpointer=None,
activation_checkpoint=SelectiveAC.Config(),
activation_checkpoint=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.

it should work with torch_remat right? cc @anijain2305

[ghstack-poisoned]
[ghstack-poisoned]
@pianpwk
pianpwk requested a review from SherlockNoMad as a code owner October 7, 2026 23:26
pianpwk added a commit that referenced this pull request Oct 7, 2026
ghstack-source-id: 5e594b1
Pull Request resolved: #4772
@pytorch-bot

pytorch-bot Bot commented Oct 7, 2026

Copy link
Copy Markdown

Warning: Unknown label ciflow/rocm-mi300.
Currently recognized labels are

  • ciflow/b200
  • ciflow/docker
  • ciflow/fake-pg
  • ciflow/h100.8
  • ciflow/real-pg
  • ciflow/rl
  • ciflow/rocm

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

[ghstack-poisoned]
pianpwk added a commit that referenced this pull request Oct 8, 2026
ghstack-source-id: 212cccd
Pull Request resolved: #4772
[ghstack-poisoned]
pianpwk added a commit that referenced this pull request Oct 8, 2026
ghstack-source-id: f3e08b7
Pull Request resolved: #4772
@pianpwk
pianpwk changed the base branch from gh/pianpwk/103/base to main October 8, 2026 04:51
[ghstack-poisoned]
[ghstack-poisoned]
pianpwk added a commit that referenced this pull request Oct 8, 2026
ghstack-source-id: 94bc4c1
Pull Request resolved: #4772
[ghstack-poisoned]
pianpwk added a commit that referenced this pull request Oct 8, 2026
ghstack-source-id: 7906d3e
Pull Request resolved: #4772
for user in node.users:
if not _is_backward_node(user) and "recompute" in user.meta:
user.meta["recompute"] = CheckpointPolicy.MUST_SAVE

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.

@IvanKobzarev checking if this is ok, we have a stats buffer we add_ into, and don't want to double count in AC. We have a context to detect this in eager, not sure if graph trainer has a mechanism that's not policy level

[ghstack-poisoned]
pianpwk added a commit that referenced this pull request Oct 9, 2026
ghstack-source-id: 6bc5de0
Pull Request resolved: #4772
[ghstack-poisoned]
[ghstack-poisoned]
pianpwk added a commit that referenced this pull request Oct 9, 2026
ghstack-source-id: 6bc5b4e
Pull Request resolved: #4772
pianpwk added a commit that referenced this pull request Oct 9, 2026
ghstack-source-id: 6bc5b4e
Pull Request resolved: #4772
[ghstack-poisoned]
[ghstack-poisoned]
pianpwk added a commit that referenced this pull request Oct 9, 2026
ghstack-source-id: 7bfda5b
Pull Request resolved: #4772
[ghstack-poisoned]
[ghstack-poisoned]
pianpwk added a commit that referenced this pull request Oct 12, 2026
ghstack-source-id: 1787f5d
Pull Request resolved: #4772
@pianpwk
pianpwk merged commit 8b4a130 into main Oct 12, 2026
@tianyu-l
tianyu-l deleted the gh/pianpwk/103/head branch October 12, 2026 06:47
pianpwk added a commit that referenced this pull request Oct 14, 2026
Stack from [ghstack](https://github.com/ezyang/ghstack/tree/0.12.0)
(oldest at bottom):
* __->__ #5368

#4772 exported its A10G goldens on a base that predated #5250 (in-place
bf16 Linear WGRAD accumulation), which itself re-baselined every A10G
golden. The final ghstack rebase onto #5250 kept #4772's stale values,
so
the committed real_pg goldens never matched the landed code: step-1
grad_norm already differs (the WGRAD accumulation change), and the
divergence grows from step 2. The PR's real-PG CI only ran the required
subset, which excludes these tests; its fake-PG job failed on both.

These tests intentionally verify the new batch-wise aux-loss policy (the
expert-bias policy is kept only for gpt_oss_pp via
_use_expert_bias_load_balancing), so this refreshes values without
changing configs.

Provenance (torch 2.16.0.dev20261011+cu132, A10G, seed checkpoint per
the
test definitions):
- real_pg: bit-identical across two independent main runs -- job
  114675094754 at 8b4a130 and job 115529499679 at 50474ad.
- fake_pg: bit-identical across four independent ciflow/fake-pg runs on
  PRs based on post-#4772 main (runs 38459347990, 38460226133,
  38460414111, 38466591432) that do not touch core model code.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/fake-pg Run 1-GPU Fake PG integration tests ciflow/real-pg Run the full 8-GPU Real PG integration suite ciflow/rl ciflow/rocm ciflow/rocm-mi300 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.

2 participants