Repository navigation
guardrail: detect silent 4-bit / 8-bit quantization bypass (#5344) - #5430
danielhanchen wants to merge 31 commits into
Conversation
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
There was a problem hiding this comment.
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.
| model, | ||
| load_in_4bit = load_in_4bit, | ||
| load_in_8bit = kwargs.get("load_in_8bit", False), | ||
| full_finetuning = full_finetuning, |
There was a problem hiding this comment.
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.
| full_finetuning = full_finetuning, | |
| full_finetuning = kwargs.get("full_finetuning", False), |
There was a problem hiding this comment.
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.
|
|
||
| # 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. |
There was a problem hiding this comment.
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.
| # quantized payload, partial quant is essentially negating 4-bit savings. | |
| if p.dtype in (torch.uint8, torch.int8): |
References
- 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.
There was a problem hiding this comment.
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.
|
@codex security review |
`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.
Simulation
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.
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. EvidenceThe helper was replaced with a raiser and a real 4-bit load run: Input space enumerated over 432 cells (model shape x quantization config x 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 The merge takes main's structure wholesale after four months of drift. Not provenNo real Gemma-4 MoE load; failure mode 2 is proven on synthetic modules shaped like |
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.
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 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".
| _warn_if_quantization_silently_dropped( | ||
| st_model, | ||
| load_in_4bit = load_in_4bit, | ||
| load_in_8bit = False, |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
| if quantized_devices and p.device not in quantized_devices: | ||
| offloaded_bytes += nbytes | ||
| continue |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. Nice work! 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". |
Summary
Multiple users on #5344 reported
load_in_4bit=Truesilently 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 runtimeBitsAndBytesConfigis 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
Total bypass.
load_in_4bit=Truerequested, zerobitsandbytes.nn.Linear4bit/Linear8bitLtmodules in the loaded model. Usually a transformers/bnb version mismatch or a backend-incompatibledevice_map.Partial bypass. bnb quantized the
nn.Linearmodules but a large fraction of weight bytes live in non-nn.LinearParameters that are not in the bnb skip list. This catches the Gemma-4 MoE class whereGemma4TextExpertsstores experts as fused 3Dnn.Parametertensors fortorch._grouped_mm;bnb.replace_with_bnb_linearonly swapsnn.Linearinstances, 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
Design notes
warnings.warn(not raise) so CPU / MLX / AMD-without-bnb backends that legitimately have noLinear4bitare not broken.vision.py(_warn_if_quantization_silently_dropped) and is reused fromFastLlamaModel.from_pretrainedvia the existing import there, so both code paths share one implementation._BNB_QUANT_CLASS_NAMES,_GUARDRAIL_SKIP_PATTERNS,_GUARDRAIL_BULK_WEIGHT_NUMELare at module top so they can be extended for new bnb backends or new skip-list patterns without touching the helper.suspect_bytes >= 2 * quantized_bytesso attention-only checkpoints with small heads do not false-fire.Tests
tests/test_issue_5344_guardrail.pycovers 7 cases, all passing:full_finetuning=TrueOut of scope
This PR only adds detection. The actual fix for the Gemma-4 MoE partial-bypass case (per-expert
Linear4bitswap sogemma-4-26B-A4B-itfits at 4-bit on a single GPU) ships as a separate follow-up.Refs #5344
Test plan
pytest tests/test_issue_5344_guardrail.pypasses (7/7)unsloth/gemma-3-1b-it(local + HF),unsloth/gemma-4-E2B-it(local + HF),unsloth/gemma-3-1b-it-unsloth-bnb-4bitall load with no warning emittedunsloth/gemma-4-26B-A4B-itwith the actual offending parameter paths in the message