Skip to content

Keep weight_decay when embedding_learning_rate is set - #11470

Merged
danielhanchen merged 11 commits into
unslothai:mainfrom
vineethsaivs:fix-embedding-lr-weight-decay-20260921
Sep 22, 2026
Merged

danielhanchen merged 11 commits into
unslothai:mainfrom
vineethsaivs:fix-embedding-lr-weight-decay-20260921

Conversation

@vineethsaivs

@vineethsaivs vineethsaivs commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

Setting embedding_learning_rate routes optimizer creation through _create_unsloth_optimizer, which read the decay from optimizer_kwargs:

weight_decay = optimizer_kwargs.get("weight_decay", 0.0)

transformers keeps the decay on the param groups and only puts it in optimizer_kwargs for schedule-free and stable_adamw, so for every ordinary optimizer the 0.0 default won. get_optimizer_cls_and_kwargs returns {'lr': 0.0002, 'betas': ..., 'eps': ...} for adamw_torch. The run trained with no weight decay at all, nothing was printed, and the value the user set was still visible on the config. It hit the whole model, not just the embeddings. _create_q_galore_optimizer in the same file already reads self.args.weight_decay.

It reads the decay from the config now, and splits the groups on Trainer.get_decay_parameter_names, because restoring the decay without that would start decaying biases and norm weights, which the super().create_optimizer() path this replaces excludes. Combinations no parameter falls into are not emitted.

Correcting the partition changes the optimizer's group layout, so a checkpoint written by the old code is migrated on load instead of refused, and the scheduler state keyed to that layout (base_lrs, _last_lr, min_lrs) moves with it. Anything that is not exactly the old shape is still refused, so torch raises as it does today rather than pairing a parameter with another parameter's moments.

One behavioural note, since it is easy to read the wrong thing into it: AdamW's decoupled decay applies p -= lr * wd * p, so each group's decay is scaled by that group's learning rate. A 4x smaller embedding LR therefore also means 4x weaker decay on the embeddings. That is what stock HF does with any per-group LR, but weight_decay=0.01 is not uniform shrinkage across the model.

Tests: tests/utils/test_unsloth_optimizer_weight_decay.py. The first case fails on main (weight_decay=0.1 produces two groups both at 0.0); the resume, scheduler-remap and pickling cases were added over the review rounds and each fails without its fix. tests/utils/test_create_optimizer_model_arg.py is unchanged. Review results, including the full tests/utils run and the FSDP and schedule-free gaps that were not exercised, are in @danielhanchen's comments below.

Setting embedding_learning_rate routes optimizer creation through
_create_unsloth_optimizer, which read the decay from optimizer_kwargs.
transformers keeps the decay on the param groups and only puts it in
optimizer_kwargs for schedule-free and stable_adamw, so the .get(..., 0.0)
default always won: the run trained with no weight decay at all, silently, with
the value the user set still on the config. _create_q_galore_optimizer in the
same file already reads self.args.weight_decay.

Read it from the config, and split the groups on
Trainer.get_decay_parameter_names so restoring the decay does not start
decaying biases and norm weights, which the path this replaces excludes.
@danielhanchen

Copy link
Copy Markdown
Member

Confirmed against unsloth/trainer.py where _create_unsloth_optimizer reads optimizer_kwargs.get("weight_decay", 0.0) while transformers only puts the decay there for schedule-free and stable_adamw, so the user's value was silently dropped, and splitting on get_decay_parameter_names matches the path this replaces. Will get this reviewed.

@danielhanchen danielhanchen self-assigned this Sep 22, 2026
The decay fix is right, but splitting non_embeddings and embeddings each into
a decay and a no-decay group emits four groups where there used to be two, and
on a LoRA run two of them are always empty: nothing trains a bias or a norm, so
both no-decay groups come back with no params.

An empty group is not free. AdafactorSchedule.get_lr reads group["params"][0]
with no emptiness guard, so optim="adafactor" now raises IndexError. And
torch's load_state_dict rejects a checkpoint whose group count differs from the
optimizer's, so every run checkpointed before this stopped being resumable,
even at weight_decay=0.

Dropping the empty groups fixes both and costs nothing: the categories are
logical, they do not have to each be a group. _create_q_galore_optimizer in
this same file already guards its groups the same way. A LoRA run is back to
the two groups it always had, in the same order and the same sizes, so old
checkpoints load again.

test_create_optimizer_model_arg asserted on param_groups[1] being empty, which
was only ever incidental; it now asserts what it meant.
@danielhanchen

Copy link
Copy Markdown
Member

Reviewed this properly: reproduced the defect, checked the fix against what Trainer.create_optimizer would have built, and ran it on a real model. Verdict first.

issue: REAL | PR as submitted: DEFECTIVE, 2 fixed by me | merge: YES, once staging Core and Backend CI land.

Setting a different learning rate for the embeddings quietly threw away the weight decay you asked for, for the whole model, while still showing your value on the config. The PR reads the decay from the right place and, like ordinary training does, keeps biases and normalisation weights out of it. Anyone who set both a weight decay and an embedding learning rate was training with no decay at all and now gets the decay they asked for; everyone else sees no change.

The bug is real and it spans the whole supported range

Only schedule-free and stable_adamw write weight_decay into optimizer_kwargs. I checked the source at the floor (4.51.3), at 4.57.6 and at the ceiling (5.5.0): the same two, every time. So optimizer_kwargs.get("weight_decay", 0.0) returned the default for every ordinary optimizer, across every transformers this repo declares.

optim weight_decay in optimizer_kwargs? kwargs keys
adamw_torch no lr, betas, eps
adamw_torch_fused no lr, betas, eps, fused
adamw_8bit no lr, betas, eps, optim_bits, is_paged
paged_adamw_8bit no lr, betas, eps, optim_bits, is_paged
adafactor no lr, relative_step, scale_parameter

On a real run, Llama-3.2-1B LoRA with modules_to_save embeddings, weight_decay=0.01, embedding_learning_rate=5e-5, adamw_8bit, 30 steps:

arm groups group weight_decay
merge base 2 [0.0, 0.0]
this PR 2 [0.01, 0.01]

And analytically, which is the part that actually settles it. With a zero gradient AdamW's only effect on a decayed parameter is p <- p * (1 - lr * weight_decay):

base (pre-PR)
  proj.weight                                          1.0000000000   expected 0.9999800000  MISMATCH
  proj.bias                                            1.0000000000   expected 1.0000000000  ok
  norm.weight                                          1.0000000000   expected 1.0000000000  ok
  model.embed_tokens.modules_to_save.default.weight    1.0000000000   expected 0.9999950000  MISMATCH

head (this PR)
  proj.weight                                          0.9999799728   expected 0.9999800000  ok
  proj.bias                                            1.0000000000   expected 1.0000000000  ok
  norm.weight                                          1.0000000000   expected 1.0000000000  ok
  model.embed_tokens.modules_to_save.default.weight    0.9999951124   expected 0.9999950000  ok

The embedding decays at its own 5e-5, biases and norms are untouched, and the partition matches Trainer.get_decay_parameter_names exactly. Splitting on it was the right call, not an extra.

This is live in the shipped notebooks: the CPT ones set weight_decay = 0.001 next to embedding_learning_rate = 1e-5.

Two things I had to fix before this could merge

Splitting each of non_embeddings and embeddings into a decay and a no-decay group emits four groups where there used to be two, and on a LoRA run two of them are always empty, because nothing trains a bias or a norm. An empty group is not free.

1. optim="adafactor" started raising. AdafactorSchedule.get_lr reads group["params"][0] with no emptiness guard:

groups=4 empty=1
AdafactorSchedule: IndexError: list index out of range

2. Every existing checkpoint stopped resuming. load_state_dict rejects a mismatched group count outright, and bitsandbytes reimplements the same check, so this hit 8-bit too:

optim=adamw_torch  main groups=2 sizes=[3, 1]
                   head groups=4 sizes=[1, 2, 1, 0]
  resume main -> head: ValueError: loaded state dict has a different number of parameter groups

I pushed a commit that drops the empty groups. The four categories are logical; they do not each have to be a group. _create_q_galore_optimizer in the same file already guards its own groups this way, so after your change the two optimizer builders in one file disagreed. With the empty ones dropped a LoRA run is back to the two groups it always had, same order and same sizes, and both problems go away:

AdafactorSchedule.get_lr() -> [0.0002, 5e-05]
resume main -> head: OK

I also reworded the param_groups[1] == [] assertion in test_create_optimizer_model_arg.py. That test is about a model without embeddings not raising; the index was incidental, and under the four-way split it was passing for a different reason than it used to. Three regression tests added, all three fail on your version and pass on the merged one.

The rest

  • Construct plus three steps on adamw_torch, adamw_torch_fused, adamw_8bit, paged_adamw_8bit, adamw_bnb_8bit, adafactor: all clean.
  • tests/utils/: 400 passed, 1 failed, and that one (test_batched_leftpad_generation_gpu) fails identically at the merge base. Pre-existing.
  • LFM2.5 1.2B continued-pretraining notebook runs unchanged on the branch, train_loss 1.707.
  • Peak memory identical at 5.405 GB across all six arms. Throughput is not resolvable on this box, two base arms differing only by a hyperparameter base discards came out 34% apart, so I am not claiming a throughput number either way.
  • The four red checks on this PR are from the stale base, not from your diff: the Core zoo failures are all unsloth_zoo GGUF-tree tests against pinned rev ab82c50 while zoo main is 90cade4, and the Shell installer failure is the AMD selection block with _amd_prefer_discrete_gfx: command not found. This touches no shell. I restaged on fresh main: Lint, Version Compat, Notebooks, Wheel and workflow-trigger lint are green, Core and Backend are still queued.

What I could not prove

  • FSDP. The delayed path behind your require_embedding_match guard was not run on real sharded hardware.
  • Full finetuning with trainable norms plus embedding_learning_rate still cannot resume a pre-change checkpoint, 2 groups becomes 3. That is inherent to correcting the partition and would need a migration shim. LoRA, which is what the notebooks do, resumes fine.
  • schedule-free and stable_adamw: neither schedulefree nor torch-optimi is installed here. Those are the two where optimizer_kwargs does carry the decay, and you keep kwargs precedence for them, which is right; their biases and norms will stop decaying, which is the intended correction but worth saying out loud.
  • Single GPU only, nothing distributed.

Separately, unsloth_zoo/training_utils.py has its own two-group builder with no embedding split and hard-coded [0]/[1] indexing. Out of scope here, but it should probably be reconciled.

Nice find, and the diagnosis in the description was exactly right.

@danielhanchen

Copy link
Copy Markdown
Member

Ran the full simulation pass on this. Verdict is unchanged and this is good to merge:

issue: REAL | PR as submitted: DEFECTIVE, 2 fixed by me | merge: YES

Restaged on fresh main and Core, all three Core zoo legs, Version Compat, Lint, Notebooks, Wheel and workflow-trigger lint are green. The four red checks here were stale-base artifacts, as expected. Three corrections and additions to what I posted earlier.

Correction: the Adafactor crash is upstream's, not one this PR invented

I said optim="adafactor" "started raising". That was right about the path but wrong about the origin, and the difference matters for what anyone should do about it. Stock Trainer.create_optimizer already emits an empty group for a LoRA-shaped model, and AdafactorSchedule already dies on it, with no unsloth in the process:

stock transformers Trainer.create_optimizer grouping:
  groups: 2 sizes: [2, 0]
  AdafactorSchedule: IndexError: list index out of range

transformers/optimization.py:1320 reads group["params"][0] with no guard. So the bug is upstream's. What the four-way split did was remove the accidental immunity the embedding_learning_rate path happened to have, because it used to produce two non-empty groups. Dropping the empty groups restores that immunity. Worth an upstream issue, but nothing to change here.

The decay bug was live on the Studio default path

Not a niche flag combination. Studio's CPT path builds UnslothTrainer with embedding_learning_rate (studio/backend/core/training/trainer.py:4316-4333) and its weight_decay default is 0.001 (studio/backend/models/training.py:509, core/training/worker.py:4510). Every Studio continued-pretraining run was training with no decay while showing 0.001 in the UI. That path also resumes (trainer.py:4513), and it is LoRA-shaped, which is exactly the case the empty-group fix keeps resumable.

Two resume corners I am reporting rather than patching

Both are consequences of correcting the partition, and neither is fixed by dropping empty groups. I have left them alone because "should a resumed run adopt the new config or preserve checkpoint state" is your call and the maintainers', not something to change quietly inside this PR.

1. A narrow second resume failure. With embedding_learning_rate set, nothing matching modules_to_save, on the non-delayed path, the group count now matches but the sizes do not. Verified across two processes each running its own tree's real function:

base (47e595c7d): groups=2 sizes=[2, 0] wd=[0.0, 0.0]
head (c1511fbb2): groups=2 sizes=[1, 1] wd=[0.1, 0.0]
resume base -> head: ValueError: loaded state dict contains a parameter group that doesn't match the size of optimizer's group

Same class of thing for full finetuning with trainable norms, where 2 groups become 3. Fixing either needs a migration shim.

2. Resuming a pre-fix run silently keeps the old behaviour. A pure-LoRA run resumed from a checkpoint written before this change keeps weight_decay=0.0, because load_state_dict overwrites group hyperparameters from the saved dict:

pre-fix checkpoint was written with weight_decay=[0.0, 0.0]
head, FRESH run                    -> weight_decay=[0.1, 0.1]
head, RESUMED from that checkpoint -> weight_decay=[0.0, 0.0]

I checked before blaming the PR for this, and it is stock torch: build a plain AdamW with wd=[0.1], load a wd=[0.0] state dict, and you get [0.0]. So it is not a regression, but it is worth knowing that upgrading fixes fresh runs only, not in-flight ones.

Evidence behind the verdict

  • Executed-line proof, instrumented. Line trace over a real UnslothTrainer on real Llama-3.2-1B LoRA, with both arms building a working optimizer so the negative arm means something: with embedding_learning_rate=5e-5 all four changed lines are hit; with it unset, none are. My first attempt at this used a SimpleNamespace stand-in that died on super() before reaching the code, so its "not hit" proved nothing; I threw it away.
  • ast diff of trainer.py: 64 cells, 62 identical, 2 changed, 0 added, 0 removed. Module-level statements identical as a sequence, 32 vs 32.
  • Changed predicate enumerated over its full input space, both arms running the real function from their own tree: 16 cells, 4 identical, 4 decay corrected, 8 raising alike on both arms (the pre-existing require_embedding_match guard), 0 violations. lr routing unchanged in every non-raising cell, every trainable parameter appearing exactly once on both arms.
  • Floor corner executed, not just read: isolated venv at transformers 4.51.3 / trl 0.18.2, the oldest the repo declares. Signature matches, bug premise holds, 8/8 grouping cells correct with zero empty groups, analytic decay identity holds at both learning rates.
  • Import time, arms interleaved, n=12 a side: base median 15.09 ms, head 14.64 ms, delta -0.45 ms against a within-arm spread of 7 to 9.6 ms. Unchanged. A first non-interleaved run showed head 32% slower and was pure drift.
  • Symbol audit: the two new kwargs have one definition, one production caller, two test callers, and no reader anywhere in unsloth, unsloth_zoo, studio or the CLI.
  • Determinism: group order is a literal tuple, within-group order is named_parameters() order through an insertion-ordered dict, and decay_parameter_names is only ever membership-tested, never iterated, so PYTHONHASHSEED cannot reach the output.

Still not proven

FSDP's delayed path on real sharded hardware. schedule-free and stable_adamw were not run because neither package is installed here; I read trainer_optimizer.py:520,527,550,558 and the value placed in optimizer_kwargs is args.weight_decay itself, so the .get() precedence is a no-op and cannot conflict, but that is inference from source rather than execution. Single GPU, nothing distributed. Windows and macOS did not run, which I think is justified by the diff having no platform surface, but that is an argument rather than a measurement.

One unrelated thing worth a separate issue: current main is red on test_docker_credential_probe.py and test_docker_hub_readme.py. Both fail on upstream main with no PR involved and both pass on this PR's merge base, so something landed on main recently that broke them. That is what the staging Backend CI red is, not anything here.

@danielhanchen

Copy link
Copy Markdown
Member

Checked the approach against upstream sources, since "matches what the replaced path did" and "is the right thing to do" are different claims. Both hold.

Reading the decay from the config rather than optimizer_kwargs is correct. Confirmed straight from transformers v4.57.6 trainer.py: create_optimizer puts "weight_decay": self.args.weight_decay and "weight_decay": 0.0 into the two param group dicts, and for the adamw_torch path optimizer_kwargs.update(adam_kwargs) where adam_kwargs holds only betas and eps on top of lr. There is no weight_decay key in optimizer_kwargs in that branch at all, so optimizer_kwargs.get("weight_decay", 0.0) could only ever have returned the default. The premise in the description is exactly right.

Splitting on bias/norm is the long-standing convention, not an embellishment. It goes back to the original google-research/bert optimization.py, which configures exclude_from_weight_decay=["LayerNorm", "layer_norm", "bias"]. HF's get_decay_parameter_names is the same idea done by module type instead of substring, precisely because substring matching was fragile across naming conventions. So deriving the partition from get_decay_parameter_names rather than hand-rolling a no_decay list is the more robust of the two standard options.

Dropping the empty groups matches the closest reference implementation. timm/optim/_param_groups.py is the canonical version of this exact problem, a cross product of (layer or role) x (decay or no-decay), and it never emits an empty group, in both of its functions:

  • param_groups_weight_decay filters post-hoc, if no_decay: groups.append(...) / if decay: groups.append(...).
  • param_groups_layer_decay creates a group lazily on first assignment (if group_name not in param_groups), so a combination no parameter falls into is never instantiated at all.

Same conclusion two different ways, and the same one _create_q_galore_optimizer already reached in this file. The general guidance around optimizer group counts agrees: a changed group count is what breaks load_state_dict on resume (torch/optim/optimizer.py, and the PyTorch forum thread collecting the usual ways people hit it), which is what made the empty groups worth removing rather than tolerating.

One determinism note, because two sources warn about it. The advice is that a set must not be used as params, since set iteration order can shift between runs and that would scramble group indices in the checkpoint. This code is fine: decay_parameter_names is turned into a set but only ever membership-tested, and the thing actually iterated is the insertion-ordered dict built from named_parameters(). Verified rather than assumed, five PYTHONHASHSEED values, identical group signature every time, md5 e2c991f697651358cf4f000c8de20f97.

One behavioural nuance worth stating in the description. AdamW's decoupled decay applies p -= lr * wd * p, so the decay is scaled by each group's learning rate. Giving the embeddings a 4x smaller LR therefore also gives them 4x weaker decay, which is visible in the analytic numbers I posted earlier (0.9999951 for the embedding at 5e-5 versus 0.9999800 for the body at 2e-4). That is exactly what stock HF would do with a per-group LR, so it is correct rather than surprising, but anyone reading weight_decay=0.01 and expecting uniform shrinkage across the model should know the embedding group is not decaying at the same rate.

Twelve comment lines to five. The two facts that are not visible from the
code stay: transformers only puts weight_decay in optimizer_kwargs for
schedule-free and stable_adamw, and an empty group breaks both
AdafactorSchedule and resume.
Splitting the decay out gives a model with trainable biases or norms more
param groups than the two it was checkpointed with, and torch requires the
counts and per-group sizes to match, so resume_from_checkpoint raised
instead of continuing. Fixing only the optimizer moves the failure one line
later into the scheduler, which overwrites base_lrs wholesale, so both are
handled.

The remap is exact rather than inferred: torch keys saved state by a
parameter's position in the flat concatenation of its groups, and the old
layout (non-embeddings then embeddings, each in named_parameters order) is
reproducible from the model, so old position maps to parameter maps to new
position one to one. Anything that is not exactly that old shape is refused
and torch raises as before, because pairing a parameter with another
parameter's moments would corrupt a run in silence where today it stops.

A resumed run now also gets the decay it was configured with rather than the
0.0 the old checkpoint recorded.

The two resume tests fail without this and pass with it; the third asserts
the refusal and is a guard against a future over-eager migration rather than
a regression test for this commit.
Two gaps in the previous commit, both reproduced.

The migration was gated on the group COUNT differing, which misses the case
where it does not. A model with no trainable embedding has a legacy layout of
[all non-embeddings, empty embeddings] and a new one of [decayed,
non-decayed]: two groups either way, different sizes, and torch rejects it on
the size check instead. Gated on the shape now, so the count coinciding no
longer hides it.

reduce_lr_on_plateau also carries a per-group min_lrs. Expanding base_lrs and
_last_lr but not that one let a two-element list replace a correctly sized
one, and the next reduction raised once it walked the optimizer's groups.

Both new tests fail without these and pass with them.
…er by role

Two more gaps, both silent rather than loud, both reproduced.

A LoRA resume needs no reshaping because the old and new layouts coincide, so
the migration was skipped and torch loaded the group hyperparameters from the
checkpoint, including the weight_decay=0.0 this change exists to correct. The
decay was silently off again for the most common shape there is. Every
recognisably legacy checkpoint is offered to the migration now, not only the
ones whose shape moved.

The scheduler remap keyed on list length, and two entries can mean two things:
with no trainable embedding both current groups are non-embeddings, so a saved
[ordinary, embedding] pair is the same length yet handed the second group the
embedding rate. Remapped by role instead, which is the identity whenever the
roles already line up.

Both new tests fail without these and pass with them.
My own regression, and a worse one than the bug it sat next to. A scheduler's
state_dict is its __dict__ minus the optimizer, so assigning the wrapper to
the instance put an unpicklable closure into it: torch.save raised
PicklingError on the FIRST checkpoint of any run with embedding_learning_rate
set, whether or not anything was ever resumed.

Overridden on a per-instance subclass instead, so it lives on the class and
never reaches the state dict. isinstance and the class name are unchanged.
The optimizer hook was never affected, since Optimizer.state_dict builds its
result explicitly rather than from __dict__, and the test now saves both.

Fails without this with PicklingError, passes with it.
…imizer state

Two more, both reproduced, both silent.

accelerator.prepare swaps self.optimizer for an AcceleratedOptimizer before
create_scheduler runs, and that wrapper defines no __getattr__, so asking it
for the recorded roles returned None and the scheduler hook quietly installed
nothing on the ordinary training path. The lookup unwraps now. The test pins
the absence of __getattr__ on the real class, so it stops passing if accelerate
ever changes that.

The migration also rebuilt each group from the freshly constructed one and
restored only lr, which resets anything an optimizer keeps per group.
Schedule-free holds its own progress there (k, weight_sum, lr_max), so the
saved per-parameter state would have come back beside reset group state. The
saved group is the base now, and only what deliberately changed, the params
and the corrected weight_decay, is overridden.

Both new tests fail without these and pass with them.
…egacy

Length cannot tell a legacy [ordinary, embedding] pair from a current pair
that is two non-embedding groups, which is what you get when
embedding_learning_rate is set and no embedding is trainable. Remapping the
latter copied the first group's value over the second, so distinct per-group
min_lr floors written by this very code came back collapsed.

transformers loads the optimizer before the scheduler, so the optimizer hook
now records whether what it just saw was the old layout, and the scheduler
remaps only then. The scheduler tests follow that same order, which is what
the trainer actually does.

Fails without this with min_lrs collapsing to the first floor.
Post-convergence pass. Six rounds of fixes left overlapping explanations, one
of them sitting above a guard that had since moved. Comments and docstrings
only, AST verified, 224 comment lines to 205 in this file.

Every surviving line is a fact the code does not state: why the saved group is
the base, why the hook is on a subclass, why the scheduler remap is gated on
the optimizer, and why the lookup unwraps.
@danielhanchen

Copy link
Copy Markdown
Member

Review record, carried over from the mirror this was reviewed on: danielhanchen/unsloth-staging-review#62. Codex only reviews on demand in repos the requesting account controls, so a third-party PR gets mirrored and reviewed there; every fix went to this branch, not the mirror.

Writing this by hand rather than pasting the generated transcript, because re-mirroring onto fresh main between rounds detached the earlier inline findings and the auto-record ended up showing only the two clean rounds. That would read as "Codex found nothing", which is the opposite of what happened.

Six rounds, nine findings, all genuine, all fixed. Converged at CODEX_APPROVED. Each one I reproduced before agreeing, and each fix has a test that fails without it.

# finding severity fixed in
1 resume of a pre-split checkpoint raises, group counts differ P1 36715967a
2 migration missed when the counts coincide but the sizes differ P1 ad0704a3f
3 reduce_lr_on_plateau per-group min_lrs not remapped P2 ad0704a3f
4 LoRA resume kept the legacy weight_decay=0.0, silently P1 18241ee61
5 equal-length scheduler state remapped by position, wrong lr P1 18241ee61
6 scheduler hook leaked into state_dict, unpicklable P1 91a4d6cfc
7 roles invisible behind AcceleratedOptimizer, hook no-op P1 4ee5fdb4e
8 migration reset per-group optimizer state P1 4ee5fdb4e
9 a current two-group checkpoint mistaken for a legacy one P2 7f488d6f3

Finding 6 was the one worth the whole exercise, and it was mine, not the original PR's. Assigning the wrapper to the scheduler instance put a closure into its state_dict, and a scheduler's state_dict is its __dict__ minus the optimizer, so torch.save raised PicklingError on the first checkpoint of any run with embedding_learning_rate set, resume or no resume. That is a far worse regression than the resume break it sat beside. It is on a per-instance subclass now.

Findings 1 to 5 and 7 to 9 are all the same shape: correcting the decay partition changes the optimizer's group layout, and everything keyed to that layout, the optimizer state, base_lrs, _last_lr, min_lrs, has to follow. The migration is exact rather than inferred, since torch keys saved state by a parameter's position in the flat concatenation of its groups and the old layout is reproducible from the model. Anything that is not exactly the old shape is refused so torch raises as before, because pairing a parameter with another parameter's moments would corrupt a run in silence where today it stops.

I had flagged finding 1 in my own review and written it off as inherent to correcting the partition. It was not, and the review was right to push.

What I still could not prove. schedulefree and torch-optimi are not installed here, so finding 8's test seeds k and weight_sum onto ordinary AdamW groups and asserts they survive; that pins the mechanism, the group dict being carried through, but it is not schedule-free exercised end to end. FSDP's delayed path was never run on sharded hardware. Single GPU throughout.

tests/utils is 411 passed, 1 failed, and that one failure reproduces identically at the merge base.

@vineethsaivs

Copy link
Copy Markdown
Contributor Author

Added the decay-scaling note to the description, along with the group-layout migration. Finding 6 is the one I would not have got to: the closure in the scheduler state_dict breaks the very first save, not just resume.

@danielhanchen

Copy link
Copy Markdown
Member

CI status at head 983b9fe57, with base arms rather than assertions.

Staging CI on fresh main (the org queue has been backed up all day, which is what the staging repos exist for): Lint, Notebooks, Wheel, Version Compat and workflow-trigger lint green. Core and Backend CI red, and both are pre-existing on main:

  • Core zoo (HF=4.57.6 + TRL<1) and Core (HF=default + TRL=default). Base arm: upstream main at ffbc3a5f8, no PR involved, fails the identical two jobs and passes the other four. The failures are test_import_fixes_drift.py::test_transformers_scopes_a_submodules_conversion_mapping and test_vllm_fused_skip_module_aliases.py, neither of which touches this diff. All 51 drift tests pass locally on this branch, and the only files changed between the last green staging head and this one are unsloth/trainer.py and the optimizer test. I re-ran the failed jobs first to rule out a flake; they are reproducible, which is why the base arm matters.
  • Backend CI: test_docker_credential_probe.py and test_docker_hub_readme.py. Both fail on current upstream main with no PR and both pass on this PR's own merge base, so something that landed on main broke them. Worth its own issue.

tests/utils locally: 411 passed, 1 failed, and that one failure (test_batched_leftpad_generation_gpu) reproduces identically at the merge base.

On the UI: no screenshots, because there is nothing to show, and I would rather say that than post a pair that proves nothing. weightDecay is a one-way input in Studio, from the control through mappers.ts to the backend, and there are zero readers of param_groups anywhere in the frontend or the backend routes. The field rendered 0.001 before this PR and renders 0.001 after; what changed is whether that number is honoured, not what is drawn. The one genuinely new string is the migration notice in the training log, and it only appears when resuming a checkpoint written before this change, which the before side cannot produce by construction.

@danielhanchen
danielhanchen merged commit ed004ac into unslothai:main Sep 22, 2026
6 of 27 checks passed
shaojun pushed a commit to shaojun/unsloth that referenced this pull request Sep 29, 2026
* Keep weight_decay when embedding_learning_rate is set

Setting embedding_learning_rate routes optimizer creation through
_create_unsloth_optimizer, which read the decay from optimizer_kwargs.
transformers keeps the decay on the param groups and only puts it in
optimizer_kwargs for schedule-free and stable_adamw, so the .get(..., 0.0)
default always won: the run trained with no weight decay at all, silently, with
the value the user set still on the config. _create_q_galore_optimizer in the
same file already reads self.args.weight_decay.

Read it from the config, and split the groups on
Trainer.get_decay_parameter_names so restoring the decay does not start
decaying biases and norm weights, which the path this replaces excludes.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Drop the empty param groups the four-way split creates

The decay fix is right, but splitting non_embeddings and embeddings each into
a decay and a no-decay group emits four groups where there used to be two, and
on a LoRA run two of them are always empty: nothing trains a bias or a norm, so
both no-decay groups come back with no params.

An empty group is not free. AdafactorSchedule.get_lr reads group["params"][0]
with no emptiness guard, so optim="adafactor" now raises IndexError. And
torch's load_state_dict rejects a checkpoint whose group count differs from the
optimizer's, so every run checkpointed before this stopped being resumable,
even at weight_decay=0.

Dropping the empty groups fixes both and costs nothing: the categories are
logical, they do not have to each be a group. _create_q_galore_optimizer in
this same file already guards its groups the same way. A LoRA run is back to
the two groups it always had, in the same order and the same sizes, so old
checkpoints load again.

test_create_optimizer_model_arg asserted on param_groups[1] being empty, which
was only ever incidental; it now asserts what it meant.

* Tighten the comments on the decay fix

Twelve comment lines to five. The two facts that are not visible from the
code stay: transformers only puts weight_decay in optimizer_kwargs for
schedule-free and stable_adamw, and an empty group breaks both
AdafactorSchedule and resume.

* Migrate a pre-split optimizer checkpoint instead of refusing it

Splitting the decay out gives a model with trainable biases or norms more
param groups than the two it was checkpointed with, and torch requires the
counts and per-group sizes to match, so resume_from_checkpoint raised
instead of continuing. Fixing only the optimizer moves the failure one line
later into the scheduler, which overwrites base_lrs wholesale, so both are
handled.

The remap is exact rather than inferred: torch keys saved state by a
parameter's position in the flat concatenation of its groups, and the old
layout (non-embeddings then embeddings, each in named_parameters order) is
reproducible from the model, so old position maps to parameter maps to new
position one to one. Anything that is not exactly that old shape is refused
and torch raises as before, because pairing a parameter with another
parameter's moments would corrupt a run in silence where today it stops.

A resumed run now also gets the decay it was configured with rather than the
0.0 the old checkpoint recorded.

The two resume tests fail without this and pass with it; the third asserts
the refusal and is a guard against a future over-eager migration rather than
a regression test for this commit.

* Key the migration on the group shape, and remap the plateau floors

Two gaps in the previous commit, both reproduced.

The migration was gated on the group COUNT differing, which misses the case
where it does not. A model with no trainable embedding has a legacy layout of
[all non-embeddings, empty embeddings] and a new one of [decayed,
non-decayed]: two groups either way, different sizes, and torch rejects it on
the size check instead. Gated on the shape now, so the count coinciding no
longer hides it.

reduce_lr_on_plateau also carries a per-group min_lrs. Expanding base_lrs and
_last_lr but not that one let a two-element list replace a correctly sized
one, and the next reduction raised once it walked the optimizer's groups.

Both new tests fail without these and pass with them.

* Offer every legacy checkpoint to the migration, and remap the scheduler by role

Two more gaps, both silent rather than loud, both reproduced.

A LoRA resume needs no reshaping because the old and new layouts coincide, so
the migration was skipped and torch loaded the group hyperparameters from the
checkpoint, including the weight_decay=0.0 this change exists to correct. The
decay was silently off again for the most common shape there is. Every
recognisably legacy checkpoint is offered to the migration now, not only the
ones whose shape moved.

The scheduler remap keyed on list length, and two entries can mean two things:
with no trainable embedding both current groups are non-embeddings, so a saved
[ordinary, embedding] pair is the same length yet handed the second group the
embedding rate. Remapped by role instead, which is the identity whenever the
roles already line up.

Both new tests fail without these and pass with them.

* Hook the scheduler on a subclass, not on the instance

My own regression, and a worse one than the bug it sat next to. A scheduler's
state_dict is its __dict__ minus the optimizer, so assigning the wrapper to
the instance put an unpicklable closure into it: torch.save raised
PicklingError on the FIRST checkpoint of any run with embedding_learning_rate
set, whether or not anything was ever resumed.

Overridden on a per-instance subclass instead, so it lives on the class and
never reaches the state dict. isinstance and the class name are unchanged.
The optimizer hook was never affected, since Optimizer.state_dict builds its
result explicitly rather than from __dict__, and the test now saves both.

Fails without this with PicklingError, passes with it.

* Find the roles through the accelerate wrapper, and keep per-group optimizer state

Two more, both reproduced, both silent.

accelerator.prepare swaps self.optimizer for an AcceleratedOptimizer before
create_scheduler runs, and that wrapper defines no __getattr__, so asking it
for the recorded roles returned None and the scheduler hook quietly installed
nothing on the ordinary training path. The lookup unwraps now. The test pins
the absence of __getattr__ on the real class, so it stops passing if accelerate
ever changes that.

The migration also rebuilt each group from the freshly constructed one and
restored only lr, which resets anything an optimizer keeps per group.
Schedule-free holds its own progress there (k, weight_sum, lr_max), so the
saved per-parameter state would have come back beside reset group state. The
saved group is the base now, and only what deliberately changed, the params
and the corrected weight_decay, is overridden.

Both new tests fail without these and pass with them.

* Remap the scheduler only when the optimizer says the checkpoint was legacy

Length cannot tell a legacy [ordinary, embedding] pair from a current pair
that is two non-embedding groups, which is what you get when
embedding_learning_rate is set and no embedding is trainable. Remapping the
latter copied the first group's value over the second, so distinct per-group
min_lr floors written by this very code came back collapsed.

transformers loads the optimizer before the scheduler, so the optimizer hook
now records whether what it just saw was the old layout, and the scheduler
remaps only then. The scheduler tests follow that same order, which is what
the trainer actually does.

Fails without this with min_lrs collapsing to the first floor.

* Tighten the comments the review rounds accumulated

Post-convergence pass. Six rounds of fixes left overlapping explanations, one
of them sitting above a guard that had since moved. Comments and docstrings
only, AST verified, 224 comment lines to 205 in this file.

Every surviving line is a fact the code does not state: why the saved group is
the base, why the hook is on a subclass, why the scheduler remap is gated on
the optimizer, and why the lookup unwraps.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: danielhanchen <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants