Repository navigation
Keep weight_decay when embedding_learning_rate is set - #11470
danielhanchen merged 11 commits into
Conversation
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.
|
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. |
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.
|
Reviewed this properly: reproduced the defect, checked the fix against what 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 rangeOnly schedule-free and stable_adamw write
On a real run, Llama-3.2-1B LoRA with
And analytically, which is the part that actually settles it. With a zero gradient AdamW's only effect on a decayed parameter is The embedding decays at its own 5e-5, biases and norms are untouched, and the partition matches This is live in the shipped notebooks: the CPT ones set Two things I had to fix before this could mergeSplitting each of 1. 2. Every existing checkpoint stopped resuming. I pushed a commit that drops the empty groups. The four categories are logical; they do not each have to be a group. I also reworded the The rest
What I could not prove
Separately, Nice find, and the diagnosis in the description was exactly right. |
|
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 inventedI said
The decay bug was live on the Studio default pathNot a niche flag combination. Studio's CPT path builds Two resume corners I am reporting rather than patchingBoth 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 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 I checked before blaming the PR for this, and it is stock torch: build a plain Evidence behind the verdict
Still not provenFSDP's delayed path on real sharded hardware. schedule-free and stable_adamw were not run because neither package is installed here; I read One unrelated thing worth a separate issue: current main is red on |
|
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 Splitting on bias/norm is the long-standing convention, not an embellishment. It goes back to the original google-research/bert Dropping the empty groups matches the closest reference implementation.
Same conclusion two different ways, and the same one One determinism note, because two sources warn about it. The advice is that a One behavioural nuance worth stating in the description. AdamW's decoupled decay applies |
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.
|
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
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 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, 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.
|
|
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. |
|
CI status at head 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.
On the UI: no screenshots, because there is nothing to show, and I would rather say that than post a pair that proves nothing. |
* 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]>
Setting
embedding_learning_rateroutes optimizer creation through_create_unsloth_optimizer, which read the decay fromoptimizer_kwargs:transformers keeps the decay on the param groups and only puts it in
optimizer_kwargsfor schedule-free and stable_adamw, so for every ordinary optimizer the0.0default won.get_optimizer_cls_and_kwargsreturns{'lr': 0.0002, 'betas': ..., 'eps': ...}foradamw_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_optimizerin the same file already readsself.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 thesuper().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, butweight_decay=0.01is not uniform shrinkage across the model.Tests:
tests/utils/test_unsloth_optimizer_weight_decay.py. The first case fails on main (weight_decay=0.1produces two groups both at0.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.pyis unchanged. Review results, including the fulltests/utilsrun and the FSDP and schedule-free gaps that were not exercised, are in @danielhanchen's comments below.