Skip to content

[optimizer] support mixed optimizers - #3269

Merged
shuhuayu merged 7 commits into
pytorch:mainfrom
shuhuayu:opt
Jun 4, 2026
Merged

shuhuayu merged 7 commits into
pytorch:mainfrom
shuhuayu:opt

Conversation

@shuhuayu

@shuhuayu shuhuayu commented May 7, 2026

Copy link
Copy Markdown
Contributor

Summary:

  1. Add mixed optimizer support to OptimizersContainer: different parameter groups can now use different optimizers (e.g., SGD for MoE router gates, AdamW for everything else)
  2. ParamGroupConfig redesigned with two override modes: same optimizer with kwargs overrides, or switch to a different optimizer entirely via optimizer_name + optimizer_kwargs
  3. Move Adam-specific fields (beta1, beta2, eps, weight_decay) from default OptimizersContainer.Config into optimizer_kwargs dict for optimizer-agnostic config
  4. Adapt LR scheduler checkpointing for mixed optimizers: save only last_epoch (plus full state for observability), restore by recomputing lr from each scheduler's own base_lrs. Correct for mixed optimizers and resharding
  5. Add per-optimizer-group LR logging to TensorBoard/WandB (e.g., lr/AdamW_default, lr/SGD_.router.gate.)
  6. Add init-time optimizer summary log showing param counts, labels, and key kwargs per group
  7. Add _validate_params to verify every trainable parameter is assigned to exactly one optimizer
  8. Add qwen3_debugmodel_moe_param_groups config as a runnable example with AdamW + SGD

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label May 7, 2026
@shuhuayu
shuhuayu force-pushed the opt branch 2 times, most recently from f9565de to f3dc352 Compare May 7, 2026 21:04
Comment thread torchtitan/components/optimizer.py Outdated
Comment on lines +48 to +50
1. **Same optimizer, different hyperparams** (``optimizer_name`` is None):
``optimizer_kwargs`` are merged on top of the global optimizer defaults.
Unspecified kwargs inherit from the global 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.

Now that we support different optimizers, can we internally just merge the two logic? We already create a separate optimizer object regardless it is mode 1 (different parameter groups) or mode 2 (different optimizer classes). If that will make the optimizer container logic simpler, we should go with this route. I don't see obvious downside of creating multiple optimizer objects.

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.

No, we do not create separate optimizer objects if it is mode 1. Pytorch natively supports it if there are several param_groups with their own kwargs, see below.

for opt_name, param_groups in groups_by_opt.items():
    opt_cls = self._resolve_optimizer_cls(opt_name)
    self.optimizers.append(opt_cls(param_groups))

But I agree that we can simplify the logic. We can remove the default optimizer, and config all optimizer setups use param_groups, which is basically using mode 2 for all parameters. What do you think?

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 know PyTorch natively supports mode 1.

My point is that if we always use mode 2 to implement the logic regardless it is mode 1 or mode 2, will it be simpler?

We can assume there is only one parameter group per optimizer.. And it sounds like your response align with the point:We can remove the default optimizer, and config all optimizer setups use param_groups, which is basically using mode 2 for all parameters. What do you think?. But I will leave it to you to decide.

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.

Yeah, we should go with full mode 2 to make it simpler, thanks. Also synced with Tianyu offline.

@shuhuayu

shuhuayu commented May 31, 2026 •

Copy link
Copy Markdown
Contributor Author

Linearized the parameter group optimizer configs for mixed optimizer case as discussed. Now support two parallel entry points, same internal path:

  • Base case. Set name, lr, optimizer_kwargs on Config for all parameters. A catch-all param group is generated automatically. No param_groups needed. OptimizersContainer.Config(lr=8e-4)set lr for default AdamW optimizer. OptimizersContainer.Config(name="SGD", lr=1e-2, optimizer_kwargs={"momentum": 0.9}) uses SGD for parameters and set its parameters.
  • Per param group case. Specify param_groups explicitly for per-parameter-group optimizer control. Config's name, lr, optimizer_kwargs are ignored. OptimizersContainer.Config(param_groups=[ ParamGroupConfig(pattern=r"\.router\.", optimizer_name="SGD", optimizer_kwargs={"lr": 1e-4, ...}), ParamGroupConfig(pattern=r".*", optimizer_name="AdamW", optimizer_kwargs={"lr": 8e-4, ...}), ])

The base case is kept for code simplicity for the case of one optimizer for all. Both cases produce a list[ParamGroupConfig] that feeds into the same linearized _build_param_groups code path.

As an exampled in torchtitan/models/qwen3/config_registry.py, the wandb log shows:
image

@shuhuayu

Copy link
Copy Markdown
Contributor Author

side comment: ci seemed to be including unchanged files in current pr into lint checks.

Comment thread torchtitan/components/lr_scheduler.py Outdated
def __len__(self) -> int:
return len(self.schedulers)

def get_lr_metrics(self) -> dict[str, float]:

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
def get_lr_metrics(self) -> dict[str, float]:
def get_metrics(self) -> dict[str, float]:

Comment on lines +241 to +243
scheduler.last_epoch = last_epoch
scheduler._step_count = last_epoch + 1
scheduler._last_lr = scheduler.get_lr()

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 feel this has too much assumptions on the LR scheduler internal, e.g. last_epoch is enough to determine the current lr. This sounds fine if torchtitan lr scheduler is simple enough, but let's document that?

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.

Yeah it works since the current lr scheduler in torchtitan are pure lambda functions. Added a note on this.

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.

cc @fegin

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 feel this has too much assumptions on the LR scheduler internal

IMHO, this is not avoidable. The LR scheduler state_dict doesn't have a good design to support resharding. An alternative is that we don't assume resharding is supported for optimizer and lr_scheduler if we want to keep this simple.

# of schedulers between save and load).
last_epoch = state_dict["last_epoch"]
for scheduler in self.schedulers:
scheduler.load_state_dict(copy.deepcopy(state_dict))

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.

Not sure if it's at least worth it to still call this first, then do the overrides you are doing.

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.

Previously state_dict is saved from the schedulers[0], if we stick to that and call load_state_dict on schedulers[1] which has different learning rate, this would be a bug. load_state_dict overwrites base_lrs with the saved values, so schedulers[1] would get schedulers[0]'s learning rate. Setting last_epoch directly avoids this, since each scheduler keeps its own base_lrs from construction, and recomputes _last_lr from there.

Comment thread torchtitan/components/lr_scheduler.py Outdated
# loading, plus full per-scheduler state for observability/debugging.
return {
"last_epoch": self.schedulers[0].last_epoch,
"schedulers": [s.state_dict() for s in self.schedulers],

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 not used

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.

You are right, schedulers are never used, and we recompute it from base_lrs in construction. As we commented above, this is for the info completeness of a checkpoint.

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.

"Info completeness" is not convincing -- you got complete info to restore anyway.

I would suggest removing, and adding a note to explain.

cc @fegin

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.

Removed. What i meant is from checkpoint itself we can recover all lrs. Currently we can get complete info in load_state_dict because we used info from our construction code plus checkpoint. But I think perhaps I was overthinking, let's remove it.

Comment thread torchtitan/components/optimizer.py Outdated
class Config(Configurable.Config):
name: str = "AdamW"
"""Optimizer to use"""
"""Default optimizer type, used when param_groups is not specified."""

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 personally dislike having such branches. I don't think it's terrible to always let users specify at least one param group.

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.

ideally yes. I kept this only for simplicity. I did not figure out how users who use the default optimizer adamw for all, can change its config conveniently. Like keeping this base case we can use optimizer=OptimizersContainer.Config(lr=8e-4), but if users need to specify this param group, which requires explicit rewrite

OptimizersContainer.Config(
    param_groups=[
        ParamGroupConfig(
            pattern=r".*",
            optimizer_name="AdamW",
            optimizer_kwargs={"lr": 8e-4, "betas": (0.9, 0.95), "eps": 1e-8, "weight_decay": 0.1},
        ),
    ],
)

Another way i can think of is to use a helper function like default_adamw(lr=xxx) that can return this ParamGroupConfig? but that means we need other functions like default_muon(lr=xxx), or we can create a function default_optimizer(name=xxx, lr=xxx). What do you think?

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.

Another way i can think of is to use a helper function like default_adamw(lr=xxx) that can return this ParamGroupConfig?

Feel free to do that. Users can do whatever in the config space, just don't have to have the complexity in actual optimizer class.

E.g. model_registry() functions is programming in config space, not actual runtime space.

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.

Agreed. That's a cleaner separation.

Comment thread torchtitan/components/optimizer.py Outdated
optimizer_classes = {
"Adam": torch.optim.Adam,
"AdamW": torch.optim.AdamW,
"SGD": torch.optim.SGD,

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 adding this?

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.

SGD is not necessary, removed.

Comment thread torchtitan/components/optimizer.py Outdated
self._model_part_indices: list[int] = []

for part_idx, model in enumerate(self.model_parts):
groups_by_opt = self._build_param_groups(model, param_groups, impl_kwargs)

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.

groups_by_opt sounds a bad name -- different groups can have the same optimizer cls.

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.

Switched to groups_by_opt_name. here we are building a dict {optimizer_name: [param_group_dicts]} to group parameters by its optimizer name. When config mixed optimizers, we config optimizers for each param_groups; when build optimizers, we build for each each optimizer for efficiency, and each optimizer can be used in several param_groups.

Comment thread torchtitan/components/optimizer.py Outdated
self._register_bf16_optimizer_state_hook()
self._validate_length(len(self.model_parts))
self._post_init(all_params, optimizer_kwargs)
self._post_init(all_params, impl_kwargs)

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 doesn't sound right, you are losing all kwargs but the fused / foreach ones

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, we lost some kwargs compared to the previous use. I realize we may not need to pass real kwargs to it at all. Actual optimizers are added here self.optimizers.append(opt_cls(opt_param_groups)), and Optimizer.__init__ is called to support register_step_pre_hook, no kwargs needed at all.

Comment thread torchtitan/components/optimizer.py Outdated
result[pg.optimizer_name].append(
{
"params": matched,
"_label": label,

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 for?

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 for logging, like in wandb, one can log the lr values of each optimizer-param-group pair.

@tianyu-l
tianyu-l requested a review from fegin May 31, 2026 21:12
Comment thread torchtitan/components/optimizer.py Outdated
group_kwargs["weight_decay"] = (
default_kwargs["weight_decay"] * pg.weight_decay_multiplier

label = re.sub(r"[^a-zA-Z0-9._]", "", pg.pattern.replace("|", "_or_"))

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 is this line doing? why can't we just log the pattern?

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.

Was thinking the patterns in re pattern may affect logging strings, and it was wrong to assume that. Switched to use plain re pattern.

Comment thread torchtitan/components/optimizer.py Outdated
class Config(Configurable.Config):
name: str = "AdamW"
"""Optimizer to use"""
"""Default optimizer type, used when param_groups is not specified."""

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.

Another way i can think of is to use a helper function like default_adamw(lr=xxx) that can return this ParamGroupConfig?

Feel free to do that. Users can do whatever in the config space, just don't have to have the complexity in actual optimizer class.

E.g. model_registry() functions is programming in config space, not actual runtime space.

Comment thread torchtitan/components/lr_scheduler.py Outdated
# loading, plus full per-scheduler state for observability/debugging.
return {
"last_epoch": self.schedulers[0].last_epoch,
"schedulers": [s.state_dict() for s in self.schedulers],

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.

"Info completeness" is not convincing -- you got complete info to restore anyway.

I would suggest removing, and adding a note to explain.

cc @fegin

Comment on lines +241 to +243
scheduler.last_epoch = last_epoch
scheduler._step_count = last_epoch + 1
scheduler._last_lr = scheduler.get_lr()

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.

cc @fegin

Comment thread torchtitan/components/optimizer.py Outdated

Use as a convenience for the common case::

OptimizersContainer.Config(param_groups=default_adamw(lr=3e-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.

why don't we make it directly return the whole OptimizerContainer.Config(...)?

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.

That's cleaner for the default standalone case. Switched to that. Users can define their own per parameter group helper function like the current one to compose with each other.

Comment thread torchtitan/components/optimizer.py Outdated
"implementation='fused_opt_states_bf16' is only supported "
f"for Adam/AdamW, got optimizer '{self.name}'"
)
param_groups: list[ParamGroupConfig] = field(default_factory=default_adamw)

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: list param_groups before implementation

Comment thread torchtitan/components/optimizer.py Outdated
"""Per-parameter-group optimizer configurations. Each entry specifies a
regex pattern and a self-contained optimizer setup.
Patterns are checked in order; first match wins.
Defaults to ``default_adamw()``."""

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.

No, why?

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.

Previously we used default_factory=default_adamw on param_groups, but removed it after we make default_adamw return a complete OptimizersContainer.Config. As for the part of "first match wins, this is because in _build_param_groupswe used theclaimed` set, and only add new param group configs when there is no existing matches.

Comment thread torchtitan/components/optimizer.py Outdated
Specify which optimizer implementation to use:
Optimizer implementation mode applied to all optimizer instances.
Per-param-group ``optimizer_kwargs`` can override this (e.g.
``"fused": False`` for optimizers that don't support fused with DTensor).

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 mention DTensor, as many optimizer don't have fused impl regardless

Comment thread torchtitan/components/optimizer.py Outdated
result[pg.optimizer_name].append(
{
"params": matched,
"_label": pg.pattern,

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 call it pattern or _pattern?

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.

Switched to pattern.

Comment thread torchtitan/components/optimizer.py Outdated
result.append({"params": grouped_params[i], **group_kwargs})

return result
return dict(result)

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 can't we return result?

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.

We can. dict(result) is a defensive step to avoid the case there is an access of non-existing keys. Since there is no such access, we can directly use result.

string for logging.
"""
result: dict[str, list[dict[str, Any]]] = defaultdict(list)
claimed: set[str] = set() # first-match-wins

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 feel this also helps dedup weight-tied params

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.

Conceptually yes, even the tie-parameter appear twice, it will only receive configs once. But here we used for name, param in model.named_parameters(), and named_parameters() will do the deduplication silently since pytorch uses id(param) for that.

}
result = {}
for opt, part_idx in zip(self.optimizers, self._model_part_indices):
sd = func(self.model_parts[part_idx], opt)

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.

other than potentially making things looking worse here, why don't we extend this optimization #3269 (comment) across model_parts?

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.

not sure iiuc, if you are referring to one optimizer per type across all model parts, here are some reasons why we could not do that: 1) get_optimizer_state_dict needs a single model part to resolve parameter
FQNs, and 2) in pp, different model parts may be on different devices.

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) is legit, but I'm sure it can be worked around by not using get_optimizer_state_dict (maybe not worth it)
(2) is not real, different model_parts refer to different PP stages on the same local device (in interleaved schedules). E.g. layer 0, 1, 4, 5 on PP rank 0; layer 2, 3, 6, 7 on PP rank 1. On rank 0, model_parts[0] has 0, 1; model_parts[1] has 4, 5.

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.

Thx for the correction on 2). I was wrong on that. For 1) it is doable by changing checkpointing logic and can be complex. I am leaning to keep the current per-model-part grouping, and optimize it later if multiple optimizer instances matters.

@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 good to me, despite a couple of nits.

Please ask @fegin for final stamp.

)


def rl_grpo_qwen3_debug() -> RLTrainer.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.

why adding this?

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.

rebase accident, removed.

Comment thread torchtitan/components/optimizer.py Outdated

weight_decay: float = 0.1
"""Weight decay to use"""
param_group_configs: list[ParamGroupConfig] = field(default_factory=list)

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
param_group_configs: list[ParamGroupConfig] = field(default_factory=list)
param_groups: list[ParamGroupConfig] = field(default_factory=list)

I guess my point is

  • if it's already inside a Config, there's no need to call it config explicitly
  • if it's mixed with actual objects, e.g. in build_param_groups(), then you have to make it explicit

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.

make sense, updated.

if not config.param_groups:
params = [p for p in model.parameters() if p.requires_grad]
return [{"params": params, **default_kwargs}]
param_group_configs: list[ParamGroupConfig],

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.

yes, here we should use ..._configs

# functionality such as hooks.
Optimizer.__init__(self, all_params, optimizer_kwargs)
# functionality such as hooks (e.g. register_step_pre_hook for MoE load balancing).
Optimizer.__init__(self, all_params, {})

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.

@fegin please review this

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 should be a safe change.

Comment on lines +241 to +243
scheduler.last_epoch = last_epoch
scheduler._step_count = last_epoch + 1
scheduler._last_lr = scheduler.get_lr()

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 feel this has too much assumptions on the LR scheduler internal

IMHO, this is not avoidable. The LR scheduler state_dict doesn't have a good design to support resharding. An alternative is that we don't assume resharding is supported for optimizer and lr_scheduler if we want to keep this simple.

Comment thread torchtitan/components/optimizer.py Outdated

weight_decay_multiplier: float = 1.0
"""Multiplied with the global optimizer weight_decay to get this group's weight_decay."""
optimizer_name: str = "AdamW"

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 we want both optimizer_name and optimizer_kwargs to have no default values

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.

thx for the catch. both should have no defaults, updated.

f"Optimizer param_groups pattern '{pg.pattern}' "
f"matched no parameters"
)

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 this be a warning or hard error? Can we clarify the expectation of this, whether it is acceptable to not have a match?

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 think an error is more informative since a warning can be silently ignored in training logs.

# functionality such as hooks.
Optimizer.__init__(self, all_params, optimizer_kwargs)
# functionality such as hooks (e.g. register_step_pre_hook for MoE load balancing).
Optimizer.__init__(self, all_params, {})

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 should be a safe change.

Comment thread torchtitan/components/optimizer.py Outdated

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 we still want to support Optimizer In Backward? Maybe easier to just delete if no one is using this feature. cc., @tianyu-l

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.

Yes, let's delete it. If complaints show up later, we reconsider.

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.

sounds good, deleted.

pass


class OptimizersInBackwardContainer(OptimizersContainer):

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 there was a test in features.py in CI for this, but I'm not seeing it deleted.

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.

Thanks for the catch, removed.

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

Good refactor! Some CI failures are real, please fix them.

@shuhuayu
shuhuayu merged commit 632f67f into pytorch:main Jun 4, 2026
20 of 24 checks passed
SherlockNoMad added a commit that referenced this pull request Jun 4, 2026
…er Config

#3269 ("support mixed optimizers") reworked OptimizersContainer.Config: the
flat name=/lr= fields were replaced by a param_groups list of ParamGroupConfig
(pattern + optimizer_name + optimizer_kwargs). Update the test to the new API.
This failure was previously masked by the test_profiler abort earlier in the
set -eux CI script.
SherlockNoMad added a commit that referenced this pull request Jun 4, 2026
…erics test (#3528)

## Why

Both GraphTrainer scheduled CI workflows were red. The workflows run
their test stages under `set -eux`, so the first failing command aborts
the rest — which means fixing one failure unmasks the next.

### Default workflow — gzip trace regression (real bug, masked by a
stale test)

[#3483](#3483) switched the
profiler to write gzip-compressed traces (`rank0_trace.json.gz`), but
the consumer wasn't audited. `_cudagraph_annotate_trace_file` in
`cudagraph.py` — attached to **every** graph_trainer run via
`configs.py` — still read the trace with plain `open()` + `json.load()`,
which raises `UnicodeDecodeError` on the gzip magic byte (`0x8b`). So
any profiled run with CUDA-graph annotations would crash in the
post-processor.

`test_profiler.py` only flagged the path-suffix change (`.json` →
`.json.gz`) because its `TestTracePostProcessorConfig` test used a
**dummy callback** that just records the path and never exercises the
real post-processor — so it masked the actual regression.

### Default workflow — `test_trace_module.py` optimizer Config drift
(unmasked by the fix above)

Once the profiler test stopped aborting the script early, the next stage
surfaced its own failure:
`test_trace_module.py::TestReparametrizeOptimizer::test_titan_optimizers_container`
raised `TypeError: OptimizersContainer.Config.__init__() got an
unexpected keyword argument 'name'`.
[#3269](#3269) ("support mixed
optimizers") reworked `OptimizersContainer.Config`: the flat
`name=`/`lr=` fields were replaced by a `param_groups` list of
`ParamGroupConfig` (`pattern` + `optimizer_name` + `optimizer_kwargs`).
The test still used the old API.

### H100 workflow — flaky DSv3 MoE-EP crash

`test_moe_dsv3_aot_fx_trace_vs_eager` fails as a flaky single-rank
crash: aot_fx_trace losses match the eager baseline **bitwise through
~step 12**, then one EP rank hard-crashes (others SIGTERM). Root cause
is unconfirmed — the crashing rank's traceback isn't captured because
the numerics tests run through `loss_compare.py` → `run_train.sh
--local-ranks-filter 0`, which tees only rank 0. (Note: the earlier
"input_splits D2H race" theory is ruled out —
[#3459](#3459) made that copy
non-blocking intentionally, and the following blocking `output_splits`
copy fences the stream.)

## What

- `cudagraph.py`: make `_cudagraph_annotate_trace_file` read/write
`.json.gz` via `gzip` (falls back to plain text for non-`.gz` paths).
- `test_profiler.py`: fix the stale assertion and add
`test_annotate_post_processor_round_trips_gzip_trace`, which drives the
**real** post-processor over a gzip trace so this path is actually
covered.
- `test_trace_module.py`: update `test_titan_optimizers_container` to
the new mixed-optimizer `OptimizersContainer.Config` API
(`param_groups=[ParamGroupConfig(pattern=r".*", optimizer_name="AdamW",
optimizer_kwargs={"lr": 1e-3})]`).
- `test_numerics.py`: `@unittest.skip` the flaky
`test_moe_dsv3_aot_fx_trace_vs_eager` to unblock CI, with a documented
reason for re-enabling after diagnosis.

## Test

- Default GraphTrainer 8-GPU workflow is **green** on this branch (all
previously-masked stages now run: `test_trace_module`,
`test_precompile`, precompile integration, `test_bitwise_deterministic`,
`test_sac_peak_memory`).
- Locally: `test_profiler.py` post-processor tests pass (E2E skips on
CUDA < 13.1); `test_titan_optimizers_container` passes;
`test_moe_dsv3_aot_fx_trace_vs_eager` skips. Verified the old `open()`
path raises `UnicodeDecodeError` on the gzip file and the new path reads
it.
- `pre-commit` clean on all changed files.
saforem2 added a commit to saforem2/torchtitan that referenced this pull request Jun 7, 2026
…tor still TODO

Documents the 34-commit pull from upstream/main (27aa490..641b5f6,
merge commit fb1c5a3, sitting in worktree ezpz-46th-47th-sync).
Two structural refactors hit ezpz:

  - PR pytorch#3458 (RoPE refactor): REPLAYED in commit 02dd1e7, verified
    by importing + building all agpt + moe flavors under the torch
    2.13 venv. Numerics smoke against baselines still pending.
  - PR pytorch#3269 (mixed-optimizer refactor): NOT YET STARTED. Affects
    OptimizersContainer.Config + 8 custom container subclasses in
    optimizer/containers.py + ~13 callsites in agpt/moe/competition
    config registries.

Also documents that spmd_types==0.2.1 was installed into .venv (new
upstream runtime dep from PR pytorch#3466/pytorch#3467/pytorch#3560) and notes the open
follow-ups (replay PR pytorch#3269, smoke against baselines, audit RL).

Doesn't update upstream-sync.md's "next-sync" reminder banner —
this sync isn't complete yet (ezpz branch is not on the worktree
HEAD).
saforem2 added a commit to saforem2/torchtitan that referenced this pull request Jun 7, 2026
…tainers + configs + train.py

Upstream PR pytorch#3269 ("[optimizer] support mixed optimizers", commit
632f67f) restructured OptimizersContainer in three ways:

1. ``OptimizersContainer.Config`` no longer carries flat ``lr`` /
   ``beta1`` / ``beta2`` / ``eps`` / ``weight_decay`` / ``name``
   fields. It now holds:
       param_groups: list[ParamGroupConfig]
       implementation: Literal["for-loop","foreach","fused",
                               "fused_opt_states_bf16"]
   where each ``ParamGroupConfig(pattern, optimizer_name,
   optimizer_kwargs)`` specifies a regex pattern matching parameter
   FQNs and a self-contained optimizer.
2. ``OptimizersContainer.__init__`` iterates over ``param_groups``,
   walks model params first-match-wins, batches param-groups by
   optimizer_name, and instantiates one optimizer per (model_part,
   optimizer_name) pair. Subclasses override
   ``_resolve_optimizer_cls(name)`` to register additional optimizer
   types beyond Adam/AdamW.
3. New ``default_adamw(lr=8e-4, **kwargs)`` factory in
   ``torchtitan.components.optimizer`` produces a single-group
   catch-all AdamW Config — the convenience drop-in for the common
   case.

ezpz replay across 6 surfaces:

* ``optimizer/containers.py``: each custom container subclass is now
  thin — overrides ``_resolve_optimizer_cls(name)`` to register its
  optimizer class name (Muon, MuonClip, SophiaG, Mano, SPAM,
  ADOPT, AdamWScheduleFree) and that's it. Dropped all flat-field
  Config classes and ``_build_optimizer_kwargs`` helpers (no longer
  called by upstream). Added matching ``default_<name>(lr=...,
  **kwargs)`` factories mirroring upstream's ``default_adamw``.
  Kept extra runtime methods (``SophiaG.update_hessian``,
  ``ScheduleFree.train_mode/eval_mode``, ``_CompositeOptimizer``,
  ``register_muonclip_qk_pairs``). ``TorchMuonOptimizersContainer``
  keeps its bespoke ``__init__`` (shape-based param split that
  doesn't fit the pattern-based grouping model) but reads its
  kwargs from the first ``ParamGroupConfig.optimizer_kwargs``.

* ``optimizer/__init__.py``: re-export the 8 new default_<name>
  factories and the previously-missing ScheduleFree/TorchMuon
  container symbols.

* ``agpt/config_registry.py``, ``moe/config_registry.py``: swap
  baseline ``OptimizersContainer.Config(lr=8e-4)`` to
  ``default_adamw(lr=8e-4)``.

* ``competition/configs.py``: 28 ``<Custom>OptimizersContainer.Config(lr=X)``
  callsites swapped to ``default_<name>(lr=X)``. 19 post-construction
  ``cfg.optimizer.lr = X`` mutations rewritten to
  ``cfg.optimizer.param_groups[0].optimizer_kwargs["lr"] = X``.

* ``train.py``: the ``--optimizer <name> --optimizer.<key>=<val>``
  CLI swap path. Replaced the dataclass-field-walking
  ``_build_optimizer_config`` (which read removed flat fields like
  ``lr`` off ``OptimizersContainer.Config``) with a thin dispatch
  through ``_OPTIMIZER_FACTORIES`` that just calls
  ``default_<name>(**overrides)``. Added a small ``_coerce_override``
  to bool/int/float/str-coerce string CLI values. Dropped the now-unused
  ``dataclasses`` import.

Verified end-to-end under torch 2.13 venv:
  - all 4 agpt configs (debugmodel, 2B, 20B, 80B) build cleanly with
    new optimizer Config shape (param_groups=1 first_pg=AdamW/0.0008).
  - all 10 moe flavors + 3 moe baseline configs (moe_2b, moe_2b_ep,
    moe_debugmodel) build cleanly.
  - 48 of 48 competition configs build cleanly.
  - all 9 ``--optimizer <name>`` swap paths exercised via
    ``_build_optimizer_config`` with single and multi-kwarg overrides.

Together with the RoPE replay in 02dd1e7, this completes the
47th sync's ezpz-side replay. Numerics smoke against pre-merge
baselines is the next step.
saforem2 added a commit to saforem2/torchtitan that referenced this pull request Jun 7, 2026
PR pytorch#3269 (mixed-optimizer refactor) replay landed in bac0a34 —
6 ezpz surfaces updated to fit the new ParamGroupConfig-based shape,
all 48 competition configs + agpt + moe configs build cleanly under
torch 2.13 venv.

Updates upstream-sync.md (status banner: REPLAY COMPLETE; removes
the "still to do" block, replaces with the "replayed" block) and
journal.md (47th-sync entry: both halves done, smoke pending).

Next gate: numerics smoke against pre-merge baselines
(moe_2b_ep 2N + agpt_80b @ TP=2 4N) before merging the worktree
branch back into ezpz.
saforem2 added a commit to saforem2/torchtitan that referenced this pull request Jun 7, 2026
… cfg.optimizer.lr mutations

The 47th-sync optimizer-refactor replay (bac0a34) caught all
``cfg.optimizer.lr = X`` post-construction mutations in
``competition/configs.py`` but missed five in
``moe/config_registry.py`` (moe_16b, moe_671b, moe_10b_2b,
moe_10b_2b_sdpa, smoke_moe_500m_50steps). Each tries to mutate
the now-removed ``OptimizersContainer.Config.lr`` field after
``default_adamw(...)`` builds the param-groups shape, and would
fail at runtime with ``AttributeError: 'Config' object has no
attribute 'lr'``.

Mirror the competition/configs.py fix: write through
``cfg.optimizer.param_groups[0].optimizer_kwargs["lr"]`` instead.

Caught while smoking ``moe_10b_2b`` post-replay.
saforem2 added a commit to saforem2/torchtitan that referenced this pull request Jun 7, 2026
…ixes

Pulled 34 upstream commits (27aa490..641b5f6). Two structural
refactors required ezpz replays — both done, both verified
end-to-end with numerics smokes against the 2026-06-02 baselines.

ezpz commits from the worktree:
  ac6b512 docs(ezpz): 47th sync — smokes + post-smoke fixes summary; mark READY TO MERGE
  8746dfe ezpz/datasets: fix _make_text_processor pickle failure for num_workers>0
  975a5bc ezpz/moe: default moe_10b_2b_sdpa{,_ep} to LBS=1 + AC=selective (only working combo)
  455013e ezpz/moe: replay PR pytorch#3269 in moe/config_registry.py — 5 missed cfg.optimizer.lr mutations
  6871e73 ezpz/optimizer: fix Config-dispatch bug — add subclass Configs so build() instantiates the subclass
  bc89aa8 docs(ezpz): mark 47th sync optimizer half replayed + verified
  bac0a34 ezpz: replay upstream PR pytorch#3269 mixed-optimizer refactor in containers + configs + train.py
  3748b9e docs(ezpz): 47th upstream-sync entry — RoPE replayed, optimizer refactor still TODO
  02dd1e7 ezpz: replay upstream PR pytorch#3458 RoPE refactor in agpt + moe

Smoke verdict (Sunspot 2N + 4N):
  ✅ moe_2b_ep 2N      — baseline bit-identical
  ✅ agpt_80b TP=2 4N  — all 20 steps within ±0.08 nat of baseline
  ✅ agpt_2b           — 10 steps clean (12.95→7.63)
  ✅ agpt_2b_real      — 10 steps, validates CosSinRoPE swap
  ✅ agpt_20b          — 10 steps, noisy but trains
  ✅ moe_2b LBS=2      — 10 steps clean
  ✅ moe_10b_2b_sdpa_ep LBS=1 AC=selective (new default) — 10 steps, 80% mem
  ✅ speedrun_2b_muon  — 10 steps, validates Muon dispatch
  ✅ speedrun_2b_sophiag — 10 steps, validates SophiaG dispatch

Full breakdown in docs/journal.md + docs/upstream-sync.md.

# Conflicts:
#	torchtitan/experiments/ezpz/docs/journal.md
saforem2 added a commit to saforem2/torchtitan that referenced this pull request Jun 28, 2026
… optim-statedict format migration

The clone-pull ckpt-resume break was mis-attributed in-session first to pytorch#3714
(fused-qkv-by-default) and then to the optimizer implementation="fused" flag.
Both ruled out by direct evidence:
- implementation defaulted to "fused" in BOTH 1263e5a (pinned/working) and HEAD
- FusedQKVLinear hooks touch only MODEL state, never tok_embeddings optim state

Verified cause: optimizer state-dict FORMAT migration. 1263e5a uses
get/set_optimizer_state_dict (nested); HEAD uses get_flat_optim_state_dict/
load_flat_optim_state_dict (flat) via pytorch#3623 (772dd1b) + pytorch#3269 (632f67f),
both ancestors of HEAD but not 1263e5a. The .fused-suffixed keys are the new
flat layout applied to all params.

Decision: do NOT build a compat shim (nested->flat migration is hard and can
silently load wrong Adam momentum). Clones stay pinned pre-pytorch#3623 -- they resume
cleanly (2B-256N chain advanced 86200->86674). New known-bug doc + corrected
incident report.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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.

3 participants