Skip to content

[checkpoint] Reject lr_scheduler loads without optimizer - #4168

Merged
tianyu-l merged 1 commit into
pytorch:mainfrom
taking-lying-flat:agent/restore-optimizer-lr-on-scheduler-load
Aug 20, 2026
Merged

tianyu-l merged 1 commit into
pytorch:mainfrom
taking-lying-flat:agent/restore-optimizer-lr-on-scheduler-load

Conversation

@taking-lying-flat

@taking-lying-flat taking-lying-flat commented Aug 16, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • reject checkpoint configurations that load lr_scheduler while excluding optimizer
  • keep the documented resharding path supported, where lr_scheduler is excluded and optimizer is loaded
  • leave LRSchedulersContainer.load_state_dict() responsible only for restoring scheduler state

Root cause

The previous version of this PR repaired the optimizer learning rate after loading scheduler state without optimizer state. Review feedback identified that this mixed restore has no established supported use case: the scheduler and optimizer states are coupled, and restoring only the scheduler leaves a newly initialized optimizer with inconsistent state.

The configuration is now rejected before checkpoint loading instead of silently repairing part of an unsupported state combination.

Impact

exclude_from_loading=["optimizer"] now raises a clear configuration error unless lr_scheduler is also excluded. Full optimizer and scheduler restores are unchanged. Existing resharding configurations that load the optimizer while excluding the scheduler remain supported.

Validation

  • Python bytecode compilation
  • pinned ufmt formatting check
  • pyrefly type check
  • smoke validation of all four optimizer/lr_scheduler exclusion combinations

No test files are added or changed.

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

pytorch-bot Bot commented Aug 16, 2026 •

Copy link
Copy Markdown

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

@taking-lying-flat
taking-lying-flat marked this pull request as ready for review August 16, 2026 00:56

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

When checkpoint loading excludes the optimizer with exclude_from_loading=["optimizer"], the newly constructed optimizer retains its initialization learning rate. The scheduler metric reports the restored rate, but the first optimizer.step() uses the stale rate; scheduler.step() only realigns it afterward.

I wonder if we should ban this case: exclude_from_loading should always include optimizer and lr_scheduler or exclude them simultaneously. Or is there a valid use case to independently exclude them when resuming checkpoint?

@taking-lying-flat
taking-lying-flat force-pushed the agent/restore-optimizer-lr-on-scheduler-load branch from 3d17be2 to 478fdf7 Compare August 17, 2026 20:44

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

I don't know why people would only load LRScheduler but not optimizer state_dict. From the document, exclude_from_loading seems to be introduced to do resharding as LRScheduler and dataloader do not support resharding. Maybe we should just re-brand this flag to do resharding only for model and optimizer unless there is a specific use case other than resharding.

@taking-lying-flat

Copy link
Copy Markdown
Contributor Author

@tianyu-l
I took another look at this, and I believe this is a new and separate training correctness issue. It is unrelated to the RL/EP+TP problem discussed in the current thread.

Problem summary

TorchTitan's ChatDataset pads incomplete packed sequences with EOS tokens and sets the corresponding labels to IGNORE_INDEX. However, neither IGNORE_INDEX nor an attention mask prevents those padding positions from passing through the Transformer blocks and reaching the MoE router.

An attention mask controls which keys/values are visible during attention. It does not remove the query position from the model, skip the FFN/MoE sublayer, or suppress stateful side effects inside the router. IGNORE_INDEX only removes the final language-model loss for that position.

The resulting execution is still:

padded input token
    -> embedding
    -> attention
    -> hidden state
    -> MoE router
    -> top-k expert selection
    -> routing_map
    -> tokens_per_expert_E
    -> expert-bias update

In the current TorchTitan MoE implementation, tokens_per_expert_E is computed by summing the complete routing map. Consequently, padding tokens are treated as real expert load. These invalid counts are later globally reduced and used by the auxiliary-loss-free load-balancing hook to update expert_bias_E.

This can cause:

  1. Incorrect expert-load statistics and monitoring.
  2. Padding-dependent expert-bias updates.
  3. A systematic routing bias when padding ratios are high or differ across ranks.
  4. Unnecessary router, expert-dispatch, communication, and expert-compute work.

The validity mask cannot safely be inferred from labels because prompt tokens can also have IGNORE_INDEX while remaining valid model inputs. It also cannot be inferred from the token ID because TorchTitan uses EOS for padding, while EOS is also a valid document-boundary token.

TorchTitan source locations

Repository:
https://github.com/pytorch/torchtitan

  1. Padding is introduced by ChatDataset

Source path:
torchtitan/hf_datasets/text_datasets.py

Relevant class/function:
ChatDataset._iter_greedy_packed()

Relevant upstream lines at the time of investigation:

  • Lines 535-543: when the next sample does not fit, the remaining sequence is padded with EOS and labels are filled with IGNORE_INDEX.
  • Lines 559-567: the remaining buffer at the end of the dataset is padded in the same way.
  • Lines 590-598: _flush_buffers() returns only input, positions, and labels; it does not return an explicit token-validity/padding mask.

Source URL:
https://github.com/pytorch/torchtitan/blob/main/torchtitan/hf_datasets/text_datasets.py

  1. Qwen3 forwards every hidden-state position into MoE

Source path:
torchtitan/models/qwen3/model.py

Relevant class/function:
Qwen3TransformerBlock.forward()

Relevant upstream lines:

  • Lines 54-65: attention_masks are passed only to the attention module.
  • Lines 62-63: the complete hidden-state tensor is subsequently passed to self.moe(...), without token-validity information.

Source URL:
https://github.com/pytorch/torchtitan/blob/main/torchtitan/models/qwen3/model.py

  1. MoE counts every routed position

Source path:
torchtitan/models/common/moe.py

Relevant class/function:
MoE.forward()

Relevant upstream lines:

  • Lines 422-426: the router selects top-k experts for every B x L position.
  • Lines 428-437: routing_map_BLE is constructed and summed over batch and sequence dimensions.
  • Lines 439-446: the complete count is accumulated into tokens_per_expert_E.
  • Lines 448-453: the same physical token counts are used by expert dispatch.

Source URL:
https://github.com/pytorch/torchtitan/blob/main/torchtitan/models/common/moe.py

  1. The counts affect future expert routing

Source path:
torchtitan/components/optimizer/optimizer.py

Relevant function:
_update_expert_bias()

Relevant upstream lines:

  • Lines 454-483: tokens_per_expert_E is collected and reduced across distributed meshes.
  • Lines 510-518: the reduced counts are used to calculate expert_bias_delta_E and update expert_bias_E.
  • Line 511 references the auxiliary-loss-free load-balancing method described by DeepSeek-V3.

Source URL:
https://github.com/pytorch/torchtitan/blob/main/torchtitan/components/optimizer/optimizer.py

Why this is an architectural issue

There are three different token-mask semantics:

  1. attention mask: controls attention visibility;
  2. loss mask: controls which positions contribute to the training objective;
  3. valid-token mask: controls whether a position participates in routing statistics, router losses, dispatch, communication, and expert computation.

TorchTitan currently has the first two concepts in different forms, but no first-class valid-token contract that can be propagated through the data pipeline, model input API, CP/TP/SPMD layouts, and the MoE router.

This is why a seemingly small MoE fix quickly expands into dataset, Trainer/Validator, model-forward, context-parallel, SPMD-sharding, and MoE changes. I do not think such a broad patch should be submitted before the intended input contract is agreed upon.

Research: other distributed/MoE frameworks

  1. NVIDIA Megatron-LM

Megatron-LM currently has the most complete explicit design. MoELayer.forward accepts padding_mask and passes it into the router. The router uses it when calculating router z-loss, auxiliary load-balancing losses, valid-token counts, and auxiliary-loss-free expert-bias statistics.

Important detail: for expert-bias statistics, Megatron masks the routing map used for statistics. The routing/dispatch result can remain separate from the statistical count. This distinction is useful for a conservative correctness fix.

Source paths:

  • megatron/core/transformer/moe/moe_layer.py
  • megatron/core/transformer/moe/router.py
  • megatron/core/transformer/moe/moe_utils.py

Relevant symbols:

  • MoELayer.forward(..., padding_mask=None)
  • TopKRouter.forward(..., padding_mask=None)
  • TopKRouter.routing(..., padding_mask=None)
  • TopKRouter._apply_expert_bias(..., padding_mask=None)
  • TopKRouter.apply_z_loss(..., padding_mask=None)
  • get_tokens_per_expert_and_token_count(..., with_padding_mask=...)

Research URLs:
https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/core/transformer/moe/moe_layer.py
https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/core/transformer/moe/router.py
https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/core/transformer/moe/moe_utils.py
https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/core/transformer/moe/README.md

  1. Microsoft DeepSpeed

DeepSpeed's MoE Top-1 gating path accepts used_token. It multiplies the one-hot expert mask by used_token before calculating exp_counts, capacity, combine weights, and the dispatch mask.

However, support is not uniform across every Top-K implementation: TopKGate forwards used_token to the Top-1 path, while the Top-2 and general Top-K paths have different interfaces. It is therefore useful prior art, but not a complete framework-wide token-validity contract.

Source path:
deepspeed/moe/sharded_moe.py

Relevant symbols:

  • top1gating(..., used_token=None)
  • TopKGate.forward(..., used_token=None)

Research URL:
https://github.com/deepspeedai/DeepSpeed/blob/master/deepspeed/moe/sharded_moe.py

  1. Google Flaxformer

Flaxformer exposes ignore_padding_tokens in its router. Depending on the router implementation, padding tokens may be removed from routing masks or have their routing probabilities down-weighted. Its load-balancing calculation is also based on the masked routing information.

The implementation infers padding by checking whether the token hidden state is all zero. That convention is suitable for its T5-style stack, but it would be fragile as a general TorchTitan contract because residual connections, biases, and model-specific embeddings do not guarantee zero hidden states for padding positions.

Source path:
flaxformer/architectures/moe/routing.py

Relevant symbols:

  • Router.ignore_padding_tokens
  • Router.call()
  • TokensChooseMaskedRouter
  • TokensChooseScatterRouter

Research URL:
https://github.com/google/flaxformer/blob/main/flaxformer/architectures/moe/routing.py

  1. Hugging Face Transformers / NLLB-MoE

NLLB-MoE passes padding information into its router and masks padding positions in the expert routing masks. Transformers also contains MoE load-balancing functions that use attention_mask to exclude padding from tokens_per_expert and router-probability statistics.

This demonstrates the expected mathematical behavior, but the implementation is model-specific and overloads attention_mask rather than defining a universal valid-token abstraction.

Source path:
src/transformers/models/nllb_moe/modeling_nllb_moe.py

Relevant symbols:

  • NllbMoeTop2Router.route_tokens(..., padding_mask=None)
  • NllbMoeSparseMLP.forward(..., padding_mask=None)
  • load_balancing_loss_func(..., attention_mask=None)

Research URL:
https://github.com/huggingface/transformers/blob/main/src/transformers/models/nllb_moe/modeling_nllb_moe.py

  1. Algorithm references

DeepSeek-V3 technical report, including auxiliary-loss-free load balancing:
https://arxiv.org/abs/2412.19437

Switch Transformers, including expert load-balancing loss:
https://arxiv.org/abs/2101.03961

GShard, including sparse expert routing and capacity:
https://arxiv.org/abs/2006.16668

Suggested direction

I suggest agreeing on a first-class token-validity contract before implementing a broad patch. The conceptual API should keep attention visibility, loss participation, and token validity separate.

A staged approach could be:

Phase 1: correctness only

  • Propagate explicit valid-token information.
  • Exclude invalid tokens from tokens_per_expert_E, expert-bias updates, router auxiliary losses, router z-loss, and metrics.
  • Do not change dispatch, expert communication, model outputs, checkpoints, or the padding-free path.

Phase 2: reduce padding at the source

  • Improve sequence packing and variable-length batching.
  • Avoid generating padding where practical.

Phase 3: performance optimization

  • Compact valid tokens before MoE dispatch.
  • Skip padding in All-to-All communication and expert computation.
  • Restore the original B x L layout after expert combine.

Suggested correctness criterion

For the same real-token sequence, adding arbitrary right padding must not change:

  • the per-expert valid-token counts;
  • the expert-bias update;
  • router auxiliary losses or z-loss, when enabled;
  • the outputs and gradients of valid token positions.

The existing behavior should remain unchanged when no padding is present.

I initially explored an implementation, but correctly propagating a new mask required changes across the dataset, Trainer/Validator input processing, model forward APIs, context parallelism, SPMD layouts, and MoE sharding. That seems too broad for a small bug-fix PR, so I am raising this new architectural concern here first and would prefer to agree on the contract and scope before proposing code.

@taking-lying-flat
taking-lying-flat force-pushed the agent/restore-optimizer-lr-on-scheduler-load branch from 478fdf7 to 27b58a4 Compare August 19, 2026 12:29
@taking-lying-flat taking-lying-flat changed the title [lr_scheduler] Restore optimizer learning rates during load [checkpoint] Reject lr_scheduler loads without optimizer Aug 19, 2026
@tianyu-l

Copy link
Copy Markdown
Contributor

@taking-lying-flat thanks a lot.

We are aware of this issue in torchtitan, and plan to fix. It'd be great if you could help.

Let's go with what you said

The conceptual API should keep attention visibility, loss participation, and token validity separate.

Propagate explicit valid-token information.

At a high level, we should pass this padding mask from dataloader (for pretraining) and batcher (for RL training). In particular, the megatron direction sounds proper.

If you have a more concrete (pseudo)code proposal, I can help view. Thanks again!

btw we are consolidating bsz and seq_len dimension, in #4121

@taking-lying-flat

Copy link
Copy Markdown
Contributor Author

@tianyu-l @fegin

@tianyu-l

Copy link
Copy Markdown
Contributor

could you rebase and fix lint

@taking-lying-flat
taking-lying-flat force-pushed the agent/restore-optimizer-lr-on-scheduler-load branch from 27b58a4 to c220794 Compare August 20, 2026 11:54
@tianyu-l
tianyu-l merged commit b1d8ebc into pytorch:main Aug 20, 2026
22 checks passed
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.

3 participants