Skip to content

Skip TRL's redundant kbit prep for models Unsloth already prepared - #11494

Merged
danielhanchen merged 4 commits into
mainfrom
fix-kbit-prep-peft-upcast
Sep 22, 2026
Merged

danielhanchen merged 4 commits into
mainfrom
fix-kbit-prep-peft-upcast

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

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_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 that view: it passes train_lm_head = False and 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:

model vocabulary upcast asks for free on that card
Qwen3.8 27B 248320 4.74 GiB 2.92 GiB
Muse Glimmer 30B 262144 5.01 GiB 0.23 GiB

Why the existing guard does not catch it

patch_trl_rl_trainers already strips this call from each generated trainer:

init = init.replace("model = prepare_peft_model(model, peft_config, args)", "pass")

That rewrite only touches the generated class's own __init__. GKDTrainer subclasses SFTTrainer, the generated _UnslothGKDTrainer inherits TRL's pristine SFTTrainer, and super().__init__ walks straight into the unpatched call:

UnslothGKDTrainer.py                __init__
trl/trainer/sft_trainer.py          __init__
trl/models/utils.py                 prepare_peft_model
peft/utils/other.py                 prepare_model_for_kbit_training
                                    param.data = param.data.to(torch.float32)

The fix

TRL fixed this themselves in 0.24.0, by adding one clause to the branch:

# trl 0.22.2
if is_qlora and not is_sharded_qlora:
# trl 0.24.0 and later
if is_qlora and not is_sharded_qlora and not isinstance(model, PeftModel):

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:

  • The rewritten function is exec'd against the module's live __dict__, not a copy of it. A copy would freeze prepare_model_for_kbit_training, get_peft_model and friends at patch time, so a later rebinding in trl.models.utils would be invisible to the replacement while the original would have seen it.
  • 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 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:

trl upstream guarded we patch already-PEFT skips upcast plain still prepared
0.22.2 no yes yes yes
0.23.0 no yes yes yes
0.24.0 yes no yes yes
0.25.1 yes no yes yes
0.26.2 yes no yes yes
1.13.0 n/a, symbol moved no n/a n/a

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.py still 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 dense lm_head is still materialised as torch.float16, and the first training step fails with expected 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.

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.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 22, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-22T10:41:23.842050Z ad7d739 Manual request
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment thread unsloth/models/rl.py Outdated
Comment on lines +1023 to +1025
if Version(trl.__version__) >= Version("0.24.0"): return False
except Exception:
return False

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@danielhanchen

Copy link
Copy Markdown
Member Author

Does this change normal SFT or GRPO?

It rebinds prepare_peft_model in every TRL module that re-exports it, sft_trainer and grpo_trainer included, so "it only affects GKD" needed measuring rather than asserting.

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 is_qlora is true.

mode arm guard installed prepare_peft_model calls loss adapters changed
SFT head yes 0 2.799461523691813 112/112
SFT main no 0 2.799461523691813 112/112
GRPO head yes 0 5.240241686503092e-07 112/112
GRPO main no 0 5.240241686503092e-07 112/112

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: patch_trl_rl_trainers already strips prepare_peft_model from the generated UnslothSFTTrainer and UnslothGRPOTrainer, and the generated files contain zero occurrences of it. The only route to TRL's copy is inheriting the pristine SFTTrainer, which is the GKD case this PR is about.

Worth noting the guard also prevents a correctness bug, not only the memory cost. prepare_model_for_kbit_training sets requires_grad = False on every parameter, and it is designed to run before get_peft_model. Reaching it with a model that is already a PeftModel freezes the adapters too. That is presumably why TRL added the not isinstance(model, PeftModel) clause rather than only reordering the cast.

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

Copy link
Copy Markdown
Member Author

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

Copy link
Copy Markdown
Member Author

@codex review

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex security review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Swish!

Reviewed commit: ad7d739e3b

ℹ️ 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".

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 22, 2026
@danielhanchen
danielhanchen merged commit c960baa into main Sep 22, 2026
34 of 36 checks passed
@danielhanchen
danielhanchen deleted the fix-kbit-prep-peft-upcast branch September 22, 2026 11:52
shaojun pushed a commit to shaojun/unsloth that referenced this pull request Sep 29, 2026
…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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant