Repository navigation
gpt-oss: load_in_4bit from a BF16 checkpoint no longer loads random experts and router - #14400
Conversation
…ed expert classes The bnb 4-bit gpt-oss classes in unsloth_zoo expect the per-expert split layout of a pre-quantized checkpoint. A fused BF16 checkpoint (a merged fine-tune, a local save, unsloth/gpt-oss-20b-BF16) loaded with load_in_4bit=True went through them, so every expert and the router were left randomly initialised with no error. Only set the _load_in_4bit_ token for gpt-oss when the checkpoint carries a quantization config, refuse when the split classes were already installed for a fused base, and let gpt-oss-20b / 120b named checkpoints without a quantization config take bnb.
|
@codex review |
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: 85505ac6e9
ℹ️ 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".
| quantization_config = getattr(config, "quantization_config", None) | ||
| if not quantization_config: | ||
| return True | ||
| return False |
There was a problem hiding this comment.
Detect the expert layout instead of inferring it from quantization
When a BF16 gpt-oss is quantized through the new stock-class path and then saved with save_pretrained, its bitsandbytes configuration is persisted while its expert tensors retain fused names such as experts.gate_up_proj. On reload, this predicate returns False solely because quantization_config exists, causing _load_in_4bit_ to select the split gate_up_projs.<i> classes; the fused expert and router keys then fail to populate those classes, recreating the random-weight corruption this change is intended to prevent. Determine the layout from checkpoint keys or persist an explicit layout marker rather than using the presence of quantization metadata.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in d56839f, and it went further than the saved-then-reloaded case: unsloth/gpt-oss-20b-bnb-4bit itself has a bitsandbytes config with dense BF16 fused experts, so it hit the same random-expert path. For a bitsandbytes config the layout is now read from the checkpoint's tensor names (index json or safetensors headers locally; get_safetensors_metadata on the Hub, headers only, no weights; cache only when offline): split gate_up_projs. names keep the split classes, fused names load through the stock classes. If the names cannot be read the old rule applies; MXFP4 is unchanged. One more case surfaced: Unsloth's own 4-bit save of fused experts writes packed U8 bytes without absmax / quant state, which no loader can rebuild, so that layout now raises a clear error instead of loading random experts (fixing the save itself is a separate change). New tests: layout rule on CPU, Hub check without weight downloads, and a GPU reload of a dense-fused bnb checkpoint (router exact, experts within NF4 error); 12 failed before, 12 pass now.
| if load_in_4bit and _bnb_compatible_quant and not _gpt_oss_fused: | ||
| string += "_load_in_4bit_" |
There was a problem hiding this comment.
Keep fused 4-bit experts out of the BF16 decode kernel
For the newly enabled BF16-to-BnB path, omitting _load_in_4bit_ leaves the stock fused expert class while gate_up_proj and down_proj become packed Params4bit tensors. During generation once decoding reaches a one-token step, the GPT-OSS fast forward rejects these tensors from its routed fp16/bf16 path and then selects moe_forward_inference_bf16, which passes the packed parameters directly to torch.bmm; their packed shape and dtype are not valid 3-D floating-point operands, so generation fails even though the training-only test passes. Add a fused-NF4 decode path or bypass this optimized BF16 decode branch for packed fused experts.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in unslothai/unsloth-zoo#1908 (merges first): moe_forward_inference_bf16 detects packed 4-bit expert weights and takes the module forward, which dequantizes them, the same fallback it uses for active expert LoRA. Here, d56839f adds a GPU test: generate(max_new_tokens = 4) on a tiny BF16 gpt-oss loaded in 4-bit matches the argmax of a no-cache full forward with per-step logits within 2%; it fails with zoo main (batch2 must be a 3D tensor) and passes with the zoo fix.
| _gpt_oss_fused = "gpt_oss" in model_types_all and bool( | ||
| gpt_oss_checkpoint_has_fused_experts(model_config) | ||
| ) |
There was a problem hiding this comment.
Preserve float32 down-projection accumulation for fused experts
On fp16-only GPUs such as T4/V100, this stock fused 4-bit route bypasses the numerical protection used by the split GPT-OSS implementation: the later custom-dtype rule only matches modules whose names contain down_projs, while the stock class exposes the fused parameter down_proj. The fused grouped-MoE path therefore dequantizes and computes the down projection in fp16, even though GPT-OSS expert down outputs overflow at that precision, producing infinities or NaNs during training. Add equivalent fp32 accumulation/output handling for the fused down_proj path before enabling this layout on forced-float32 devices.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 3a640e8 by refusing that case: the fused 4-bit experts compute in the model dtype, so a non pre-quantized gpt-oss with load_in_4bit and an effective float16 dtype (no bfloat16 on the GPU, or dtype = torch.float16) now raises before loading and points to the pre-quantized unsloth/gpt-oss-20b-unsloth-bnb-4bit, which keeps down_projs in float32. On main this case loaded random experts, so nothing that worked is lost; bfloat16 loads are unchanged.
…ad of overflowing [skip ci]
|
@codex review |
|
Codex Review: Didn't find any major issues. What shall we delve into next? 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". |
… tensor names A fused gpt-oss quantized by Unsloth and saved keeps fused expert names with a bitsandbytes quantization_config, and unsloth/gpt-oss-20b-bnb-4bit stores dense fused experts beside 4-bit attention. Both were routed to the split gate_up_projs classes and loaded random experts. Read the safetensors index or headers (local or Hub, no weight download) and keep the stock fused classes for a fused layout; refuse a save whose packed experts have no quant state. Split pre-quantized and MXFP4 checkpoints are unchanged.
…ogits Needs the unsloth_zoo fix that sends packed bnb 4-bit fused experts to the module forward during one-token decode. [skip ci]
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: d56839fe1a
ℹ️ 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".
| "without their bitsandbytes quantization state, so the experts cannot be restored. Reload the " | ||
| "original 16-bit checkpoint with `load_in_4bit = True` instead." | ||
| ) | ||
| return layout == "fused" |
There was a problem hiding this comment.
Avoid treating unreadable checkpoint layouts as split experts
When a fused bitsandbytes GPT-OSS checkpoint uses a supported nonstandard weight layout—such as save_pretrained(..., safe_serialization=False) producing pytorch_model.bin, or safetensors selected through the loader's variant argument—_checkpoint_tensor_dtypes cannot find the hard-coded unvarianted safetensors files and returns None. This comparison then reports the checkpoint as non-fused, reinstalls the split gate_up_projs.<i> classes, and silently leaves the fused experts/router randomly initialized. Please inspect the actual weight files/variant or fail closed when the layout is unknown rather than selecting the split layout.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 11446b3: the layout reader now follows transformers' file order and variant naming (model.safetensors.index.json, model.safetensors, pytorch_model.bin.index.json, pytorch_model.bin), with the loader's variant passed through. Index files and safetensors headers give the names; a lone local or cached zip-format pytorch_model.bin is opened with torch.load(mmap=True, weights_only=True) for names and dtypes only. When the layout still cannot be read (legacy .bin, or an uncached Hub .bin) and it matters (load_in_4bit, or a bnb 4-bit config in float16), the load now fails closed with a clear error naming the cause and the fixes, except for names marking Unsloth's split pre-quantized repos (unsloth-bnb-4bit), which keep the split answer. New cases cover .bin index (fused and split), lone .bin, legacy .bin, variant safetensors / sharded / .bin index, and Hub variants with a mocked Hub; 9 failed before, all pass now.
| elif load_in_4bit and _bnb_compatible_quant: | ||
| refuse_gpt_oss_fused_4bit_float16(dtype) |
There was a problem hiding this comment.
Reject implicit fused 4-bit loads in float16
When a fused bitsandbytes checkpoint is loaded with load_in_4bit=False on a float16-only GPU, its checkpoint quantization_config still activates the 4-bit quantizer later in FastBaseModel.from_pretrained, but this guard is skipped because it only checks the caller's flag. The fused experts therefore still execute through the unsafe float16 route and can produce infinities or NaNs. Fresh evidence in the current code is that the no-flag branch reconstructs and forwards auto_config.quantization_config at vision.py:3811-3866; base this refusal on the effective checkpoint quantization state as well as load_in_4bit.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 11446b3: the float16 refusal now uses the effective quantization (caller's load_in_4bit, the checkpoint's bnb 4-bit quantization_config, or an explicit bnb 4-bit quantization_config) together with the fused layout and the resolved dtype. Test loads a tiny fused bnb 4-bit gpt-oss directory with dtype=torch.float16 and load_in_4bit=False: it was not refused before, it is now.
…fuse fused 4-bit in float16 by effective quantization The expert layout check for a bitsandbytes gpt-oss checkpoint only read unvarianted safetensors. A fused 4-bit model saved with safe_serialization = False, or loaded with a variant, returned no names and was treated as the split pre-quantized layout, so zoo's split classes were installed and the experts loaded randomly initialised. - Names now come from model.safetensors(.index.json) and pytorch_model.bin.index.json, both with transformers' variant naming, locally and on the Hub (index json only; a single safetensors file is read from the cache or by a header range read, never downloaded). The loader's variant is passed through in loader.py and in the vision.py sync call. - A lone pytorch_model.bin with no index: a local or cached zip file is opened with torch.load(mmap = True, weights_only = True), which reads names and dtypes without the tensor bytes. If that is not possible (legacy format, or an uncached Hub file), the layout cannot be known without loading weights, and guessing split would silently train random experts, so the load fails closed with GptOssUnknownExpertLayoutError naming the cause and the fixes (re-save with safetensors, add the index, or download it first). The one exception is a name containing unsloth-bnb-4bit, the naming of Unsloth's split pre-quantized repos, which keeps the split answer. The error is only raised where the layout matters: load_in_4bit, or a bnb 4-bit config in float16. The float16 refusal for fused 4-bit experts only checked the caller's load_in_4bit. A fused bitsandbytes checkpoint loaded with load_in_4bit = False still applies its own quantization_config, so it ran the fused 4-bit experts in float16. The refusal now uses the effective quantization: the caller's flag, the checkpoint's bnb 4-bit config, or an explicit bnb 4-bit quantization_config, together with the fused layout and the resolved dtype. [skip ci]
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 11446b3acd
ℹ️ 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".
| weight_map = _index_weight_map(index_path) | ||
| out = dict.fromkeys(weight_map) | ||
| for name, shard in weight_map.items(): | ||
| if name.endswith(_FUSED_EXPERT_SUFFIX) and shard.endswith(".safetensors"): |
There was a problem hiding this comment.
Read dtypes from indexed bin shards
When a packed fused checkpoint uses pytorch_model.bin.index.json, this condition skips every shard and leaves the fused gate_up_proj dtype as None. _gpt_oss_bnb_checkpoint_expert_layout can recognize packed byte weights without quantization state only when that dtype is U8/I8, so an indexed checkpoint with no .absmax entries is incorrectly accepted as restorable fused weights instead of raising the intended error; loading then proceeds with unusable packed experts. Read the relevant bin shard metadata as is done for a lone bin, or fail closed when the dtype needed for this check is unknown.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 723c195. Fused expert dtypes are now read from indexed .bin shards (local and cached Hub shards), and when a fused expert has no .absmax and its dtype still cannot be read the layout is reported as unknown, so the load raises GptOssUnknownExpertLayoutError instead of accepting packed bytes.
| subfolder = kwargs.get("subfolder"), | ||
| cache_dir = kwargs.get("cache_dir"), | ||
| local_files_only = local_files_only, | ||
| variant = kwargs.get("variant"), |
There was a problem hiding this comment.
Probe the checkpoint format selected by the caller
When a repository contains both safetensors and PyTorch weights and the caller sets use_safetensors=False, Transformers loads the .bin checkpoint, but this layout probe is not given that flag and always searches safetensors first. If the two representations have different expert layouts—for example, a newly saved fused .bin beside older split safetensors—the probe installs classes for the wrong file and the actual expert/router keys are left randomly initialized. Forward use_safetensors here and in the later sync probe, and make _checkpoint_tensor_dtypes honor the same file-selection order as from_pretrained.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 723c195. _checkpoint_tensor_dtypes takes use_safetensors and filters candidate files the same way from_pretrained does (False skips safetensors, True reads only safetensors); both the loader probe and sync_unsloth_model_name_bnb_flags forward it.
| # Ignore load_in_4bit / load_in_8bit for MXFP4; better to get the config file. Unquantized gpt-oss still takes bnb. | ||
| if ( | ||
| "gpt-oss-20b" in model_name.lower() or "gpt-oss-120b" in model_name.lower() | ||
| ) and getattr(auto_config, "quantization_config", None): |
There was a problem hiding this comment.
Reject unsupported 8-bit fused GPT-OSS loads
When load_in_8bit=True is used with an unquantized gpt-oss-20b or gpt-oss-120b checkpoint, this new condition now forwards the bitsandbytes configuration instead of keeping the checkpoint configuration path. Transformers' 8-bit conversion replaces nn.Linear modules, but the stock GPT-OSS experts are fused nn.Parameter tensors, and the MoE-specific conversion added by Unsloth only handles 4-bit Params4bit; consequently attention layers become 8-bit while the dominant expert tensors remain 16-bit, so a load expected to fit at 8-bit can consume tens of gigabytes more and OOM. Limit this newly enabled path to load_in_4bit, or explicitly support/refuse 8-bit fused experts.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 723c195. Only load_in_4bit takes the new bnb path for unquantized gpt-oss (gpt_oss_keeps_checkpoint_quantization); load_in_8bit keeps the checkpoint configuration path exactly as on main.
…etensors, keep 8-bit off unquantized gpt-oss - Read the fused gate_up_proj dtype from indexed .bin shards (and cached or header-read Hub shards); a fused expert with no .absmax and an unreadable dtype now fails closed instead of loading as dense. - Pass use_safetensors to the expert layout probe and the UNSLOTH_MODEL_NAME sync so they read the same file as from_pretrained (False: pytorch_model.bin only, True: safetensors only). - Unquantized gpt-oss-20b / -120b take the bnb config only for load_in_4bit; load_in_8bit keeps the previous checkpoint config path, since bnb 8-bit leaves the fused expert parameters in 16-bit. [skip ci]
|
@codex review |
|
Codex Review: Didn't find any major issues. Delightful! 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". |
…ward (unslothai#1908) ## Summary A gpt-oss loaded from a BF16 checkpoint with `load_in_4bit = True` keeps the stock fused expert class with bitsandbytes 4-bit (packed 2D `Params4bit`) `gate_up_proj` / `down_proj` (unslothai/unsloth#14400). At the first one-token decode step `moe_forward_inference_bf16` passed those packed tensors to `torch.bmm` and generation failed with `batch2 must be a 3D tensor`. `_has_packed_bnb4bit_experts` detects packed 4-bit expert weights, and `moe_forward_inference_bf16` then uses the module forward (which dequantizes them), the same fallback it already takes for active expert LoRA. Dense experts keep the bmm kernel. ## Tests - `tests/test_gpt_oss_bnb4bit_fused_decode.py` (CPU): 2 failed before (the bmm error), 2 passed after. - With unslothai/unsloth#14400: `generate(max_new_tokens = 4)` on a tiny BF16 gpt-oss loaded in 4-bit gives the same tokens as a no-cache full forward, logits within 2% per step; fails with zoo main, passes with this. - `tests/test_gpt_oss_*.py`: 362 passed, 26 skipped on both main and this branch. ## Not covered - Decode speed of the fallback (module forward per token) is not timed.
… gc-skip tests (unslothai#14504) `Repo tests (CPU, rest)` and `Repo tests (CPU, studio)` fail on main and on every PR based on it. Three test files added by unslothai#14400 and unslothai#14404 trip the repo's own lint tests: - `tests/python/test_accelerator_skip_guards.py::test_no_skip_guard_reads_a_spoofable_accelerator_probe`: skip guards on `torch.cuda.is_available()`, which `tests/_zoo_aggressive_cuda_spoof.py` patches to True, so these tests un-skip on the CPU runners: - `test_gpt_oss_bf16_load_in_4bit.py` lines 99 and 160; - `test_gpt_oss_bnb_checkpoint_layout.py` line 191; - `test_gc_skip_auto.py`, 7 guards. - `tests/test_source_read_encoding.py::test_checked_in_file_reads_name_an_encoding[10]`: `test_gpt_oss_bnb_checkpoint_layout.py:362` opens a file without `encoding`. ## Change - The guards use `has_real_cuda()` from `tests/_shared/real_accelerator.py`, as the other GPU tests do. - The `open()` call names `encoding = "utf-8"`. Test files only. ## Validation - Both lint tests on CPU: 40 passed (they failed on main). - On a GPU, the three edited files on main and on this branch: 78 passed, 2 failed on both sides. `has_real_cuda()` and `torch.cuda.is_available()` agree on a real GPU, so the guards change nothing there. The two failures are the same tests on both sides (`test_bf16_checkpoint_loads_real_weights_in_4bit`, `test_bf16_checkpoint_4bit_generate_matches_prefill`) and are not touched here.
Summary
Loading a gpt-oss checkpoint that is not pre-quantized (a merged fine-tune, a local save,
unsloth/gpt-oss-20b-BF16) withload_in_4bit = Truesilently left every MoE expert and the router randomly initialised._load_in_4bit_in UNSLOTH_MODEL_NAME makes unsloth_zoo install the split-layout bnb classes (experts.gate_up_projs.<i>,router.linear), which only match pre-quantized checkpoints; a fused checkpoint has none of those keys, so they stayed at init and were not quantized either. The only sign was UNEXPECTED / MISSING lines in the load report.Only set
_load_in_4bit_for gpt-oss when the checkpoint has a quantization config (loader.py andsync_unsloth_model_name_bnb_flags). Fused checkpoints keep the stock classes and are quantized by the regular fused MoE bnb path.Raise a clear error if the split classes were already installed for a fused base (adapter-only repo on a BF16 base).
The
gpt-oss-20b/gpt-oss-120bname check that skips the bnb config now only applies when the config has a quantization config (MXFP4), so a BF16 gpt-oss-20b checkpoint is quantized.For a bitsandbytes config the expert layout is read from the checkpoint's tensor names (index json or safetensors headers; headers only on the Hub, no weight download): split
gate_up_projs.<i>names keep the split classes, fused names (for exampleunsloth/gpt-oss-20b-bnb-4bit, dense BF16 experts) load through the stock classes. Unreadable names fall back to the previous rule. A 4-bit save of fused experts without quant state (packed bytes only) raises a clear error instead of loading random experts.Non pre-quantized checkpoints in 4-bit float16 are refused (the fused experts would overflow); bfloat16 is unaffected.
One-token decode on packed fused experts needs gpt-oss: decode packed bnb 4-bit fused experts through the module forward unsloth-zoo#1908 (merge it first).
Pre-quantized split bnb, MXFP4 and 16-bit loads are unchanged.
Tests
tests/test_gpt_oss_bf16_load_in_4bit.py(tiny gpt-oss saved as BF16 with distinct expert / router weights): main 7 failed, this PR 7 passed (torch 2.10, 2.13; 2.14 without bitsandbytes skips the GPU test).LoRA forward + backward gives non-zero expert grads. Existing gpt-oss loader tests unchanged (42 passed, 2 skipped on both).
Not covered
Real 20B weights, transformers 4.x, pre-quantized and MXFP4 checkpoints end to end (unchanged by construction; unit tests cover their config dicts).