Repository navigation
[optimizer] support mixed optimizers - #3269
Conversation
f9565de to
f3dc352
Compare
| 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. |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
Yeah, we should go with full mode 2 to make it simpler, thanks. Also synced with Tianyu offline.
|
side comment: ci seemed to be including unchanged files in current pr into lint checks. |
| def __len__(self) -> int: | ||
| return len(self.schedulers) | ||
|
|
||
| def get_lr_metrics(self) -> dict[str, float]: |
There was a problem hiding this comment.
| def get_lr_metrics(self) -> dict[str, float]: | |
| def get_metrics(self) -> dict[str, float]: |
| scheduler.last_epoch = last_epoch | ||
| scheduler._step_count = last_epoch + 1 | ||
| scheduler._last_lr = scheduler.get_lr() |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
Yeah it works since the current lr scheduler in torchtitan are pure lambda functions. Added a note on this.
There was a problem hiding this comment.
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)) |
There was a problem hiding this comment.
Not sure if it's at least worth it to still call this first, then do the overrides you are doing.
There was a problem hiding this comment.
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.
| # 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], |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
"Info completeness" is not convincing -- you got complete info to restore anyway.
I would suggest removing, and adding a note to explain.
cc @fegin
There was a problem hiding this comment.
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.
| class Config(Configurable.Config): | ||
| name: str = "AdamW" | ||
| """Optimizer to use""" | ||
| """Default optimizer type, used when param_groups is not specified.""" |
There was a problem hiding this comment.
I personally dislike having such branches. I don't think it's terrible to always let users specify at least one param group.
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
Agreed. That's a cleaner separation.
| optimizer_classes = { | ||
| "Adam": torch.optim.Adam, | ||
| "AdamW": torch.optim.AdamW, | ||
| "SGD": torch.optim.SGD, |
There was a problem hiding this comment.
SGD is not necessary, removed.
| 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) |
There was a problem hiding this comment.
groups_by_opt sounds a bad name -- different groups can have the same optimizer cls.
There was a problem hiding this comment.
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.
| 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) |
There was a problem hiding this comment.
this doesn't sound right, you are losing all kwargs but the fused / foreach ones
There was a problem hiding this comment.
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.
| result[pg.optimizer_name].append( | ||
| { | ||
| "params": matched, | ||
| "_label": label, |
There was a problem hiding this comment.
This is for logging, like in wandb, one can log the lr values of each optimizer-param-group pair.
| group_kwargs["weight_decay"] = ( | ||
| default_kwargs["weight_decay"] * pg.weight_decay_multiplier | ||
|
|
||
| label = re.sub(r"[^a-zA-Z0-9._]", "", pg.pattern.replace("|", "_or_")) |
There was a problem hiding this comment.
what is this line doing? why can't we just log the pattern?
There was a problem hiding this comment.
Was thinking the patterns in re pattern may affect logging strings, and it was wrong to assume that. Switched to use plain re pattern.
| class Config(Configurable.Config): | ||
| name: str = "AdamW" | ||
| """Optimizer to use""" | ||
| """Default optimizer type, used when param_groups is not specified.""" |
There was a problem hiding this comment.
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.
| # 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], |
There was a problem hiding this comment.
"Info completeness" is not convincing -- you got complete info to restore anyway.
I would suggest removing, and adding a note to explain.
cc @fegin
| scheduler.last_epoch = last_epoch | ||
| scheduler._step_count = last_epoch + 1 | ||
| scheduler._last_lr = scheduler.get_lr() |
|
|
||
| Use as a convenience for the common case:: | ||
|
|
||
| OptimizersContainer.Config(param_groups=default_adamw(lr=3e-4)) |
There was a problem hiding this comment.
why don't we make it directly return the whole OptimizerContainer.Config(...)?
There was a problem hiding this comment.
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.
| "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) |
There was a problem hiding this comment.
nit: list param_groups before implementation
| """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()``.""" |
There was a problem hiding this comment.
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.
| 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). |
There was a problem hiding this comment.
don't mention DTensor, as many optimizer don't have fused impl regardless
| result[pg.optimizer_name].append( | ||
| { | ||
| "params": matched, | ||
| "_label": pg.pattern, |
There was a problem hiding this comment.
can we just call it pattern or _pattern?
There was a problem hiding this comment.
Switched to pattern.
| result.append({"params": grouped_params[i], **group_kwargs}) | ||
|
|
||
| return result | ||
| return dict(result) |
There was a problem hiding this comment.
why can't we return result?
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
I feel this also helps dedup weight-tied params
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
other than potentially making things looking worse here, why don't we extend this optimization #3269 (comment) across model_parts?
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
(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.
There was a problem hiding this comment.
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.
| ) | ||
|
|
||
|
|
||
| def rl_grpo_qwen3_debug() -> RLTrainer.Config: |
There was a problem hiding this comment.
rebase accident, removed.
|
|
||
| weight_decay: float = 0.1 | ||
| """Weight decay to use""" | ||
| param_group_configs: list[ParamGroupConfig] = field(default_factory=list) |
There was a problem hiding this comment.
| 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
There was a problem hiding this comment.
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], |
There was a problem hiding this comment.
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, {}) |
There was a problem hiding this comment.
this should be a safe change.
| scheduler.last_epoch = last_epoch | ||
| scheduler._step_count = last_epoch + 1 | ||
| scheduler._last_lr = scheduler.get_lr() |
There was a problem hiding this comment.
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.
|
|
||
| weight_decay_multiplier: float = 1.0 | ||
| """Multiplied with the global optimizer weight_decay to get this group's weight_decay.""" | ||
| optimizer_name: str = "AdamW" |
There was a problem hiding this comment.
Do we want both optimizer_name and optimizer_kwargs to have no default values
There was a problem hiding this comment.
thx for the catch. both should have no defaults, updated.
| f"Optimizer param_groups pattern '{pg.pattern}' " | ||
| f"matched no parameters" | ||
| ) | ||
|
|
There was a problem hiding this comment.
Should this be a warning or hard error? Can we clarify the expectation of this, whether it is acceptable to not have a match?
There was a problem hiding this comment.
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, {}) |
There was a problem hiding this comment.
this should be a safe change.
There was a problem hiding this comment.
Do we still want to support Optimizer In Backward? Maybe easier to just delete if no one is using this feature. cc., @tianyu-l
There was a problem hiding this comment.
Yes, let's delete it. If complaints show up later, we reconsider.
There was a problem hiding this comment.
sounds good, deleted.
| pass | ||
|
|
||
|
|
||
| class OptimizersInBackwardContainer(OptimizersContainer): |
There was a problem hiding this comment.
IIRC there was a test in features.py in CI for this, but I'm not seeing it deleted.
There was a problem hiding this comment.
Thanks for the catch, removed.
…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.
…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.
…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).
…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.
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.
… 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.
…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
… 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.

Summary:
OptimizersContainer: different parameter groups can now use different optimizers (e.g., SGD for MoE router gates, AdamW for everything else)ParamGroupConfigredesigned with two override modes: same optimizer with kwargs overrides, or switch to a different optimizer entirely via optimizer_name + optimizer_kwargsOptimizersContainer.Configintooptimizer_kwargsdict for optimizer-agnostic configbase_lrs. Correct for mixed optimizers and resharding_validate_paramsto verify every trainable parameter is assigned to exactly one optimizerqwen3_debugmodel_moe_param_groupsconfig as a runnable example with AdamW + SGD