Repository navigation
Skip TRL's redundant kbit prep for models Unsloth already prepared - #11494
Conversation
TRL's prepare_peft_model calls PEFT's prepare_model_for_kbit_training, which freezes every parameter and then upcasts each one that is not a Params4bit to float32. The parameter that matters is the lm_head: Unsloth keeps it out of quantization on purpose so a distillation loss can project through it, so it is dense, it is frozen, and at a large vocabulary it is enormous. Upcasting a frozen tensor buys nothing. fp32 master weights only matter for parameters an optimizer updates, and PEFT sets requires_grad = False on everything immediately before the cast. Unsloth's own prepare_model_for_kbit_training already reflects this: it passes train_lm_head = False and gets fp32 through mixed precision rather than by materialising fp32 weights. Measured on Kaggle 2x T4, both with the weights already loaded and sharded across both cards: 4.74 GiB for Qwen3.8 (248320 tokens) and 5.01 GiB for Muse Glimmer, each of which turns a model that loaded fine into an OOM while the trainer is still being constructed. patch_trl_rl_trainers strips this call from each generated trainer, but that does not reach the case: GKDTrainer subclasses SFTTrainer, the generated _UnslothGKDTrainer inherits TRL's pristine SFTTrainer, and super().__init__ walks straight into the unpatched call. TRL fixed this themselves in 0.24.0 by adding "and not isinstance(model, PeftModel)" to the branch, which is exactly our case since Unsloth has applied LoRA before the trainer is built. So apply that same clause to older TRL rather than inventing a different rule, and leave 0.24.0 and above alone. Two details worth keeping. The rewritten function is exec'd against the module's live __dict__ rather than a copy, so a later rebinding in trl.models.utils stays visible to it exactly as it would to the original. And every module that re-exports the name is rebound, not just the definition: each trainer module does "from ..models import prepare_peft_model" at import time, which in TRL 0.22.2 is seven modules, and sft_trainer is the one GKD inherits. If the branch is not spelled the way we expect, the patch bails rather than editing blindly. Verified against a real trl 0.22.2 install, and across trl 0.22.2, 0.23.0, 0.24.0, 0.25.1, 0.26.2 and 1.13.0 with PEFT 0.18.0, 0.19.0 and 0.20.0: below 0.24.0 we patch, at or above it we stay out of the way, and in every combination an already-PEFT model skips the upcast while a plain quantized model is still prepared.
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: b1d5bf2a69
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| if Version(trl.__version__) >= Version("0.24.0"): return False | ||
| except Exception: | ||
| return False |
There was a problem hiding this comment.
Handle TRL's
unknown source-tree version
When TRL is used directly from a source checkout or otherwise lacks distribution metadata, its own __init__.py sets __version__ = "unknown"; parsing that value raises, and this broad handler returns before inspecting the function source. Consequently, affected pre-0.24 installations keep the redundant k-bit preparation and can still incur the multi-GiB upcast/OOM this change is intended to prevent. Use the module's existing version fallback or continue with the guarded source-pattern check when the version is unavailable.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Correct, and reproduced: trl/init.py falls back to version = "unknown" when the distribution metadata is absent, Version("unknown") raises, and the handler returned before the source check ran, so a pre-0.24 source checkout kept the upcast.
Fixed in ad7d739. The import is now separate from the version parse, and an unparseable version falls through to the source check rather than bailing. Falling through is safe because that check is self-guarding: the matched text ends in a colon, and 0.24.0 and above spell the branch as if is_qlora and not is_sharded_qlora and not isinstance(model, PeftModel):, so they cannot match it.
Two tests added. Before the fix, an unknown version left the guard uninstalled and prepare_model_for_kbit_training still ran; after it, the guard installs and the upcast is skipped. The second test pins the safety argument by pointing an unknown version at a 0.24-style body and asserting the function is left untouched. Suite is 21 passing.
Does this change normal SFT or GRPO?It rebinds Ran QLoRA SFT and GRPO on trl 0.22.2, 4-bit, unsloth/Qwen3-0.6B, 3 steps, seed 3407, base vs head. 4-bit on purpose, since the guarded branch only runs when
Losses are bit-identical between arms. The call count is the part that matters. It is 0 on every arm including the ones where the guard is installed and active, so this is not inert because it failed to apply. It applied, and the call site is simply not on those paths: Worth noting the guard also prevents a correctness bug, not only the memory cost. |
…line The guard re-executes TRL's own prepare_peft_model with one branch condition corrected, so the value handed to compile and exec is built rather than written out, which is what the gate is there to catch. Recorded with a reason rather than restructured: the source comes from inspect.getsource on the installed trl package, never from user input or a network fetch, and the rewrite only happens when the exact expected branch text is present exactly once. Anything else and the patch bails and leaves TRL alone.
|
Correction to the table in the description: Muse Glimmer's vocabulary is 202048, not 262144. The measured 5.01 GiB upcast stands, and 202048 is the number consistent with it. The Qwen3.8 row (248320, 4.74 GiB) is unaffected. |
TRL run from a source tree with no distribution metadata sets
__version__ = "unknown" in its own __init__.py. Version("unknown") raises,
the broad handler returned before the source check ran, and the install kept
the redundant upcast: exactly the pre-0.24 case this exists for.
Split the import from the version parse, and on an unparseable version fall
through instead of bailing. That is safe because the source check is
self-guarding: the matched text carries a trailing colon, and 0.24.0 and above
spell the branch with the clause already in it, so they never match.
Two tests: an unknown version still gets guarded, and an unknown version does
not patch a TRL that already carries the clause.
|
@codex review |
|
@codex security review |
|
Codex Review: Didn't find any major issues. Swish! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
…nslothai#11494) * Skip TRL's redundant kbit prep for models Unsloth already prepared TRL's prepare_peft_model calls PEFT's prepare_model_for_kbit_training, which freezes every parameter and then upcasts each one that is not a Params4bit to float32. The parameter that matters is the lm_head: Unsloth keeps it out of quantization on purpose so a distillation loss can project through it, so it is dense, it is frozen, and at a large vocabulary it is enormous. Upcasting a frozen tensor buys nothing. fp32 master weights only matter for parameters an optimizer updates, and PEFT sets requires_grad = False on everything immediately before the cast. Unsloth's own prepare_model_for_kbit_training already reflects this: it passes train_lm_head = False and gets fp32 through mixed precision rather than by materialising fp32 weights. Measured on Kaggle 2x T4, both with the weights already loaded and sharded across both cards: 4.74 GiB for Qwen3.8 (248320 tokens) and 5.01 GiB for Muse Glimmer, each of which turns a model that loaded fine into an OOM while the trainer is still being constructed. patch_trl_rl_trainers strips this call from each generated trainer, but that does not reach the case: GKDTrainer subclasses SFTTrainer, the generated _UnslothGKDTrainer inherits TRL's pristine SFTTrainer, and super().__init__ walks straight into the unpatched call. TRL fixed this themselves in 0.24.0 by adding "and not isinstance(model, PeftModel)" to the branch, which is exactly our case since Unsloth has applied LoRA before the trainer is built. So apply that same clause to older TRL rather than inventing a different rule, and leave 0.24.0 and above alone. Two details worth keeping. The rewritten function is exec'd against the module's live __dict__ rather than a copy, so a later rebinding in trl.models.utils stays visible to it exactly as it would to the original. And every module that re-exports the name is rebound, not just the definition: each trainer module does "from ..models import prepare_peft_model" at import time, which in TRL 0.22.2 is seven modules, and sft_trainer is the one GKD inherits. If the branch is not spelled the way we expect, the patch bails rather than editing blindly. Verified against a real trl 0.22.2 install, and across trl 0.22.2, 0.23.0, 0.24.0, 0.25.1, 0.26.2 and 1.13.0 with PEFT 0.18.0, 0.19.0 and 0.20.0: below 0.24.0 we patch, at or above it we stay out of the way, and in every combination an already-PEFT model skips the upcast while a plain quantized model is still prepared. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Record the rewritten prepare_peft_model in the dynamic-execution baseline The guard re-executes TRL's own prepare_peft_model with one branch condition corrected, so the value handed to compile and exec is built rather than written out, which is what the gate is there to catch. Recorded with a reason rather than restructured: the source comes from inspect.getsource on the installed trl package, never from user input or a network fetch, and the rewrite only happens when the exact expected branch text is present exactly once. Anything else and the patch bails and leaves TRL alone. * Apply the guard when TRL's version cannot be parsed TRL run from a source tree with no distribution metadata sets __version__ = "unknown" in its own __init__.py. Version("unknown") raises, the broad handler returned before the source check ran, and the install kept the redundant upcast: exactly the pre-0.24 case this exists for. Split the import from the version parse, and on an unparseable version fall through instead of bailing. That is safe because the source check is self-guarding: the matched text carries a trailing colon, and 0.24.0 and above spell the branch with the clause already in it, so they never match. Two tests: an unknown version still gets guarded, and an unknown version does not patch a TRL that already carries the clause. --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
A 27B model that loads fine across two T4s can still OOM while the trainer is being constructed, asking for close to 5 GiB it does not need.
What happens
TRL's
prepare_peft_modelcalls PEFT'sprepare_model_for_kbit_training, which freezes every parameter and then upcasts each one that is not aParams4bitto float32. The parameter that matters is thelm_head. Unsloth keeps it out of quantization on purpose so a distillation loss can project through it, so it is dense, it is frozen, and at a large vocabulary it is enormous.Upcasting a frozen tensor buys nothing. fp32 master weights only matter for parameters an optimizer updates, and PEFT sets
requires_grad = Falseon everything immediately before the cast. Unsloth's ownprepare_model_for_kbit_trainingalready reflects that view: it passestrain_lm_head = Falseand gets fp32 through mixed precision rather than by materialising fp32 weights.Measured on Kaggle 2x T4, in both cases with the weights already loaded and sharded across both cards:
Why the existing guard does not catch it
patch_trl_rl_trainersalready strips this call from each generated trainer:That rewrite only touches the generated class's own
__init__.GKDTrainersubclassesSFTTrainer, the generated_UnslothGKDTrainerinherits TRL's pristineSFTTrainer, andsuper().__init__walks straight into the unpatched call:The fix
TRL fixed this themselves in 0.24.0, by adding one clause to the branch:
That clause is exactly our case, because Unsloth has applied LoRA before the trainer is built. So this applies the same clause to older TRL rather than inventing a different rule, and leaves 0.24.0 and above completely alone.
Two details are deliberate:
__dict__, not a copy of it. A copy would freezeprepare_model_for_kbit_training,get_peft_modeland friends at patch time, so a later rebinding intrl.models.utilswould be invisible to the replacement while the original would have seen it.from ..models import prepare_peft_modelat import time, which in TRL 0.22.2 is seven modules, andsft_traineris the one GKD actually inherits.If the branch is not spelled the way we expect, the patch bails rather than editing blindly.
Testing
tests/test_kbit_prep_guard.py, 6 tests. The fixture is TRL 0.22.2's real function body rather than a paraphrase, so a change in how the branch is spelled shows up as a failure here instead of as a silent no-op in the field. It covers the negative control (a model that has not been through PEFT still gets prepared), idempotence, that all seven re-exporting modules are rebound, that TRL at or above 0.24.0 is untouched, and that a respelled branch is left alone.Also verified against a real installed trl 0.22.2, and swept across versions:
0.22.2 was additionally run against PEFT 0.18.0, 0.19.0 and 0.20.0, all identical. The existing
tests/test_sft_config_subclass_downcast.pystill passes, 19 tests in total.What this does not fix
Qwen3.8 on 2x T4 gets past this and then hits a separate dtype inconsistency: Unsloth reports
Using float16 precision for qwen3_5 won't work! Using float32.while the denselm_headis still materialised astorch.float16, and the first training step fails withexpected mat1 and mat2 to have the same dtype, but got: c10::BFloat16 != c10::Half. That is unrelated to this change and I will raise it separately.