Skip to content

guardrail: detect silent 4-bit / 8-bit quantization bypass (#5344) - #5430

Closed
danielhanchen wants to merge 31 commits into
mainfrom
fix-issue-5344-quantization-guardrail
Closed

danielhanchen wants to merge 31 commits into
mainfrom
fix-issue-5344-quantization-guardrail

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Summary

Multiple users on #5344 reported load_in_4bit=True silently being ignored, with the model loading at near full precision instead of QLoRA size. The reports cover several different triggers (Studio + Windows + local safetensors, gemma-4-26B-A4B in the Python API, multi-GPU dispatch). What they share is the failure mode: the runtime BitsAndBytesConfig is built and passed correctly, but the resulting model contains either zero or only-attention bnb modules.

This PR adds a post-load guardrail that catches both shapes and emits a clear warning instead of letting the user discover the bug via a confusing VRAM blow-up.

Failure modes detected

  1. Total bypass. load_in_4bit=True requested, zero bitsandbytes.nn.Linear4bit / Linear8bitLt modules in the loaded model. Usually a transformers/bnb version mismatch or a backend-incompatible device_map.

  2. Partial bypass. bnb quantized the nn.Linear modules but a large fraction of weight bytes live in non-nn.Linear Parameters that are not in the bnb skip list. This catches the Gemma-4 MoE class where Gemma4TextExperts stores experts as fused 3D nn.Parameter tensors for torch._grouped_mm; bnb.replace_with_bnb_linear only swaps nn.Linear instances, so the fused expert weights stay in BF16 and dominate the VRAM footprint. The warning names the worst-offending parameter paths so the user can correlate immediately.

Example warning

Unsloth: load_in_4bit=True is partially applied. bitsandbytes quantized
~0.77 GB of nn.Linear weights, but ~42.54 GB of non-nn.Linear floating
Parameters were left unquantized (e.g. fused MoE expert tensors, custom
Linear-like wrappers). Examples: model.language_model.layers.0.experts.
gate_up_proj (torch.bfloat16, (128, 1408, 2816)), model.language_model.
layers.0.experts.down_proj (torch.bfloat16, (128, 2816, 704)), ...
The model's effective VRAM footprint is close to its full-precision size.
See https://github.com/unslothai/unsloth/issues/5344.

Design notes

  • warnings.warn (not raise) so CPU / MLX / AMD-without-bnb backends that legitimately have no Linear4bit are not broken.
  • Helper lives in vision.py (_warn_if_quantization_silently_dropped) and is reused from FastLlamaModel.from_pretrained via the existing import there, so both code paths share one implementation.
  • Constants _BNB_QUANT_CLASS_NAMES, _GUARDRAIL_SKIP_PATTERNS, _GUARDRAIL_BULK_WEIGHT_NUMEL are at module top so they can be extended for new bnb backends or new skip-list patterns without touching the helper.
  • Partial-bypass threshold is suspect_bytes >= 2 * quantized_bytes so attention-only checkpoints with small heads do not false-fire.

Tests

tests/test_issue_5344_guardrail.py covers 7 cases, all passing:

  • fires on total 4-bit silent bypass
  • silent on a successful 4-bit load
  • silent for full_finetuning=True
  • silent when no quantization requested
  • fires on total 8-bit silent bypass
  • fires on partial-quant (MoE fused experts unquantized)
  • silent when only skip-list tensors (norms, embeds) remain unquantized
$ python -m pytest tests/test_issue_5344_guardrail.py -q
.......                                                                  [100%]
7 passed in 0.49s

Out of scope

This PR only adds detection. The actual fix for the Gemma-4 MoE partial-bypass case (per-expert Linear4bit swap so gemma-4-26B-A4B-it fits at 4-bit on a single GPU) ships as a separate follow-up.

Refs #5344

Test plan

  • pytest tests/test_issue_5344_guardrail.py passes (7/7)
  • No regression on healthy paths: unsloth/gemma-3-1b-it (local + HF), unsloth/gemma-4-E2B-it (local + HF), unsloth/gemma-3-1b-it-unsloth-bnb-4bit all load with no warning emitted
  • Fires correctly on unsloth/gemma-4-26B-A4B-it with the actual offending parameter paths in the message

Some users report that load_in_4bit=True is silently ignored on certain
checkpoints and the model is loaded in full precision. This adds a post-load
guardrail in FastBaseModel.from_pretrained and FastLlamaModel.from_pretrained
that detects two failure modes and emits a clear warning instead of letting
the user discover the issue via a confusing VRAM blow-up.

1. Total bypass: load_in_4bit=True requested, zero bitsandbytes Linear4bit /
   Linear8bitLt modules in the loaded model. Usually a transformers / bnb
   version mismatch or a backend-incompatible device_map.

2. Partial bypass: bnb quantized nn.Linear but a large fraction of weight
   bytes live in non-nn.Linear Parameters that are not in the bnb skip list.
   This catches the Gemma-4 MoE class where Gemma4TextExperts stores experts
   as fused 3D nn.Parameter tensors for torch._grouped_mm; bnb's
   replace_with_bnb_linear only swaps nn.Linear instances, so the fused
   expert weights stay in BF16 and dominate the VRAM footprint. The
   warning names the worst offenders so the user can correlate.

warnings.warn (not raise) so CPU / MLX / AMD-without-bnb backends that
legitimately have no Linear4bit modules are not broken.

Tests in tests/test_issue_5344_guardrail.py cover both branches plus the
full-finetuning, no-quant, and skip-list cases.

Refs #5344

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

This pull request implements a guardrail to detect and warn users when bitsandbytes quantization is silently bypassed, either completely or partially, during model loading. The changes include a new validation function _warn_if_quantization_silently_dropped in vision.py, its integration into Llama and Vision model loading paths, and a suite of unit tests. Review feedback highlights a NameError in llama.py where full_finetuning is undefined and a logic flaw in the guardrail that misses int8 parameters for 8-bit quantization, which would lead to false positive warnings.

Comment thread unsloth/models/llama.py Outdated
model,
load_in_4bit = load_in_4bit,
load_in_8bit = kwargs.get("load_in_8bit", False),
full_finetuning = full_finetuning,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

critical

The variable full_finetuning is not defined in the scope of FastLlamaModel.from_pretrained. Unlike FastBaseModel.from_pretrained in vision.py, FastLlamaModel.from_pretrained does not include full_finetuning in its signature. This will result in a NameError at runtime. You should extract it from kwargs or pass a default value.

Suggested change
full_finetuning = full_finetuning,
full_finetuning = kwargs.get("full_finetuning", False),

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.

Fixed. Both call sites in llama.py now pass full_finetuning = kwargs.get("full_finetuning", False) (llama.py:2734, llama.py:2800), so the name is never read out of scope.

Comment thread unsloth/models/vision.py

# Failure mode 2: partial bypass. Walk named_parameters and find large
# floating tensors outside the skip list. If they aggregate to >= 2x the
# quantized payload, partial quant is essentially negating 4-bit savings.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

high

The guardrail currently only counts torch.uint8 parameters towards quantized_bytes. While 4-bit quantization uses uint8 storage, bitsandbytes 8-bit quantization (Linear8bitLt) uses torch.int8. If load_in_8bit=True is used, quantized_bytes will remain 0, causing the partial bypass check at line 200 to trigger a false positive warning. Additionally, ensure that the resulting warning message is dynamically generated to include the specific configuration values (e.g., suspect_bytes and quantized_bytes) to ensure accuracy and avoid confusion.

Suggested change
# quantized payload, partial quant is essentially negating 4-bit savings.
if p.dtype in (torch.uint8, torch.int8):
References
  1. User-facing warning messages should be dynamically generated to include the specific configuration values they refer to, rather than using hardcoded examples, to ensure accuracy and avoid confusion.

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.

Fixed. The payload test is now p.dtype in (torch.uint8, torch.int8) (vision.py:315), so Int8Params counts towards quantized_bytes instead of being read as unquantized bulk.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 21, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 21, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 21, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 21, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex security review

chatgpt-codex-connector[bot]

This comment was marked as resolved.

`bnb_4bit_quant_storage=float16/bfloat16` is what FSDP QLoRA requires, and it
gives the packed Params4bit a FLOATING dtype. An unquantized Params4bit also
reads float32 until it reaches the device, so the dtype never identified a
packed payload in the first place; uint8 was only the default.

On such a load the old test failed twice over: the packed weights were counted
as suspect bulk weight, and quantized_bytes stayed at zero, so the
`quantized_bytes > 0` gate then suppressed the partial-bypass warning outright.
A real bypass alongside float storage was silent.

Payloads are now matched on Params4bit / Int8Params with the dtype kept as a
fallback. Confirmed against bitsandbytes 0.50.2 rather than from the symptom:
Params4bit reports float32 under every quant_storage setting before it is
moved, so the class is the only stable identifier.

The negative control shrinks the packed payload until the fused experts really
do dominate; it produces no warning at all on the previous head and warns here.
@danielhanchen

Copy link
Copy Markdown
Member Author

Simulation

issue: REAL (#5344 still open) | PR as submitted: DEFECTIVE, 4 fixed here | merge: YES AFTER staging CI is green

Asking Unsloth to load a model in 4-bit can silently not happen: you get a full-precision model, the same out-of-memory you were avoiding, and no message saying why. It can also half-happen on mixture-of-experts models, where the big fused expert weights stay full-size because the quantizer only converts ordinary layers. This adds a warning for both, so a load that ignored the request says so instead of just running out of memory later.

It does not fix #5344 and does not claim to. It reports the failure; the per-expert conversion is #5432.

# today after this PR
1 4-bit requested, zero bnb modules: silent, full precision warns, names the known triggers and the device_map="cuda:0" workaround
2 fused MoE experts left BF16 while nn.Linear was quantized: silent warns with both byte totals and example tensor names
3 4-bit requested, load came back 8-bit warns, and explicitly does not claim full precision
4 pre-quantized 8-bit repo loaded with the default load_in_4bit=True silent: the checkpoint declares its width, nothing was dropped
5 Falcon-H1 / Nemotron-H out_proj, skipped on purpose silent
6 CPU or disk offloaded layers under llm_int8_enable_fp32_cpu_offload silent, and a real bypass reports the offloaded bytes separately
7 bnb_4bit_quant_storage=bfloat16 with a genuine partial bypass warns; was silent before

Rows 3 to 7 are the four defects fixed here plus the false positive rows 4 and 5 prevent. Rows 6 and 7 came from this round's review and each produce no warning at all on the previous head.

Evidence

The helper was replaced with a raiser and a real 4-bit load run: EXECUTED [causal] and EXECUTED [seqcls]. The first attempt printed NOT EXECUTED on both, which turned out to be the harness importing site-packages rather than the worktree. Worth recording, because a dead-code result that is really a path bug reads identically.

Input space enumerated over 432 cells (model shape x quantization config x load_in_4bit x load_in_8bit x full_finetuning): 396 identical to the PR as submitted, 36 moved, 0 new crashes. Of the 36, 26 are the new wrong-width detection, 6 report a more accurate cause than "partially applied", and 4 are the skip-modules false positive going silent. 337 cells are silent on both sides, which is the unchanged experience for anyone who never hits this.

Cost, since this runs on every load: median of 7, 0.630 ms at a 32-layer shape and 0.886 ms at 80 layers, and 0.382 us when full_finetuning=True short-circuits it. Nothing is added inside any decode or per-layer path.

The merge takes main's structure wholesale after four months of drift. git diff origin/main on the two loader files removes exactly one line, the duplicate transformers_version import vision.py carried twice, and otherwise only adds.

Not proven

No real Gemma-4 MoE load; failure mode 2 is proven on synthetic modules shaped like Gemma4TextExperts. No real FSDP QLoRA run, no real multi-GPU or CPU-offload load: those three are proven from the bitsandbytes and transformers sources plus hand-placed parameters. The local environment is transformers 5.17.0, outside the declared <=5.5.0 ceiling, so neither the floor nor the pinned ceiling was exercised locally; staging CI covers that and had not finished at the time of writing.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

FastSentenceTransformer's fast encoder path and FastDiffusionModel both
construct a BitsAndBytesConfig and hand it straight to SentenceTransformer(...)
or model_cls.from_pretrained(...), so neither passed through either guardrail
call site and both could return a full-precision model in silence.

The diffusion call takes check_partial=False, which is new. bnb converts only
nn.Linear and Conv1D (transformers/integrations/bitsandbytes.py:189), so a
Conv2d-heavy UNet legitimately keeps large float weights and the partial-bypass
ratio, tuned for LLM parameter naming, would warn on every correctly quantized
diffusion load. Total bypass is naming-agnostic and still runs there.

Three tests: a diffusion-shaped model stays silent under check_partial=False, a
total bypass is still caught under the same flag, and the same diffusion-shaped
model DOES warn with the default, so the flag is a gate rather than a blanket.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 21, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 21, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@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: f856ed0309

ℹ️ 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/sentence_transformer.py Outdated
_warn_if_quantization_silently_dropped(
st_model,
load_in_4bit = load_in_4bit,
load_in_8bit = 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 Forward the 8-bit request to the encoder guard

When an encoder is loaded with load_in_8bit=True and load_in_16bit=False, this fast path is selected, but it only constructs a BitsAndBytesConfig for 4-bit loads. Passing a hard-coded False here prevents the new guardrail from reporting that the 8-bit request was silently ignored, so the model can still load at full precision without any warning. Pass the actual load_in_8bit value so this bypass is detected.

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.

Right, and it was my regression from the previous commit. Fixed in c14ab37: the call now passes the real load_in_8bit.

Confirmed by running it rather than by reading. With the helper replaced by a raiser, FastSentenceTransformer.from_pretrained(..., load_in_8bit=True, load_in_16bit=False) now reaches the guardrail with {'load_in_4bit': False, 'load_in_8bit': True}. Against the previous head the same load arrived with load_in_8bit=False, so the guardrail returned early and the bypass went unreported, exactly as you describe.

Comment thread unsloth/models/vision.py Outdated
Comment on lines +360 to +362
if quantized_devices and p.device not in quantized_devices:
offloaded_bytes += nbytes
continue

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 Count unquantized weights on every accelerator

On a multi-GPU device map, a large floating parameter may be placed on (for example) cuda:1 while all bnb parameters happen to be on cuda:0. This condition classifies that parameter as CPU/disk offload solely because its device is absent from quantized_devices, excluding real accelerator-resident full-precision bytes and potentially suppressing the partial-bypass warning entirely. Only actual CPU/meta offloads should be excluded; floating weights on other accelerator devices must remain suspect.

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 also mine: this is a regression from the offload fix two commits back. Fixed in c14ab37.

The exclusion keyed on "device not among the quantized devices", which excuses a float weight on a second ACCELERATOR just as readily as one on cpu. That is the multi-GPU case you name, and those bytes are accelerator-resident full precision, so excusing them suppressed the partial-bypass warning outright.

Only cpu and meta are excused now, and only when the payload does not live there too, so a cpu-only bnb load still treats its cpu floats as suspect rather than excusing them as offload.

The regression test puts the payload on cpu and the fused experts on cuda:0: no warning at all on the previous head, warns here. It needs a real accelerator, since the whole point is a device that is neither cpu nor meta, so it skips where there is none.

Two regressions from the previous two commits, both caught in review.

The offload exclusion keyed on "device not among the quantized devices", which
also excuses a float weight sitting on a SECOND accelerator. That is the
multi-GPU case: bnb lands the payload on cuda:0, the fused experts sit on
cuda:1, and those bytes are accelerator-resident full precision, not an
offload. Excusing them suppressed the partial-bypass warning outright. Only cpu
and meta are excused now, and only when the payload does not live there too, so
a cpu-only bnb load still treats its cpu floats as suspect.

The encoder call passed a hardcoded load_in_8bit=False. That path builds a bnb
config for 4-bit only, so an 8-bit request there IS the silent bypass the
guardrail exists to report, and the hardcoded flag hid precisely that case.

The multi-GPU test produces no warning at all on the previous head and warns
here. It needs a real accelerator, since the point is a device that is neither
cpu nor meta, so it skips where there is none.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: c14ab37c94

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

auto-addresses-issue Pre-flight: appears to address an open issue auto-approved Auto-review approved the PR conflicts# edge case# new-feature# non-studio# still-needed# Stale but the problem is still present on main; review it

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant