Skip to content

Train gpt-oss MXFP4 LoRA through unsloth-zoo's packed experts when load_in_16bit is not set - #11929

Merged
danielhanchen merged 28 commits into
mainfrom
gpt-oss-mxfp4-lora-packed
Sep 29, 2026
Merged

danielhanchen merged 28 commits into
mainfrom
gpt-oss-mxfp4-lora-packed

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Depends on unslothai/unsloth-zoo#1358 (packed MXFP4 experts). unslothai/unsloth-zoo#1386 is also needed for correct sliding-window masks on transformers 5. Without #1358 this change is a no-op.

Problem

A LoRA load of native gpt-oss (load_in_4bit = False, no load_in_16bit) keeps Mxfp4GptOssExperts, whose triton_kernels matmul_ogs forward has no backward:

  • With triton_kernels importable (vLLM registers its copy), Unsloth's class raises NotImplementedError: Backwards pass using MXFP4 is still under construction!.
  • Without it, the transformers class returns an output detached from the graph. Every LoRA below a MoE layer then trains on the residual-stream gradient only, with no error.

Change

When unsloth-zoo reports that the experts stay packed (keep_mxfp4_experts_packed()), the loader also asks for Mxfp4Config(dequantize = True) on a LoRA load. The experts stay MXFP4 in memory and are decoded one layer at a time inside a differentiable forward.

The native load is unchanged:

  • without unsloth-zoo xFormers wasn't build with CUDA support #1358
  • for full finetuning
  • with UNSLOTH_MXFP4_KEEP_PACKED=0
  • for an explicit device map that offloads to CPU or disk, since unsloth-zoo cannot keep offloaded experts packed and would otherwise make a 16-bit copy at load

Before / after (B200, transformers 5.17)

main this PR
gpt-oss-20b LoRA, triton_kernels absent: gradients vs a bf16 reference grad norm 7.48 vs 12.96, cosine 0.646, layer 0 cosine 0.13 cosine 0.99998 (layer 0 0.9999), loss equal to the reference
gpt-oss-20b LoRA, vLLM installed Backwards pass using MXFP4 is still under construction! trains, cosine 1.000000
gpt-oss-120b, 10-step masked SFT backward raises PASS: wikitext-2 PPL 254.95 (plain transformers 255.72), CE 3.439 to 0.498, experts stay uint8, 84.6 GB peak on one card

Cost

On the same load used only for inference (20b, 3 prompts, 4 loads per arm, shared GPU so treat as noisy):

main this PR
decode, tok/s (vLLM installed / not) 13.1 / 13.5 16.8 / 15.0
2048-token prefill, ms (vLLM installed / not) 224 / 427 660 / 523
peak memory while generating 14.9 GB 16.5 GB

The prefill cost comes from unsloth-zoo #1358 decoding each layer's experts in every forward. UNSLOTH_MXFP4_KEEP_PACKED=0 restores the native load for inference-only use.

Scope

Of 448 load configurations (7 models x 4 load modes x full finetuning x UNSLOTH_MXFP4_KEEP_PACKED x device map x FastLanguageModel / FastModel), 24 change, all native MXFP4 to packed:

  • gpt-oss with load_in_4bit = False or load_in_8bit = True
  • a local gpt-oss MXFP4 directory with the default load_in_4bit = True, since bitsandbytes is turned off for MXFP4 checkpoints

With an unsloth-zoo that lacks #1358, all 448 are identical to main.

Tests

tests/test_mxfp4_lora_packed_experts_dequantize.py has 9 CPU tests. All fail on main and pass here. Reverting the loader change fails the dequantize test, and removing the offload check fails the offload test. The related loader, gpt-oss and MXFP4 test files show no other change in failures on transformers 5.17, 5.4 and 4.57.6.

…t is not set

load_in_4bit = False without load_in_16bit kept the native Mxfp4GptOssExperts, whose
triton_kernels matmul_ogs forward has no backward. With triton_kernels importable (vLLM
registers its copy) Unsloth's class raises "Backwards pass using MXFP4 is still under
construction". Without it, the transformers class returns an output detached from the
graph, so every LoRA below a MoE layer trains on the residual gradient only (gpt-oss-20b:
layer 0 LoRA gradient cosine to the bf16 reference about 0, total norm 7.5 vs 13.0).

When unsloth_zoo keeps the experts packed (keep_mxfp4_experts_packed), ask for
Mxfp4Config(dequantize = True) on that load too. The experts stay MXFP4 in memory and are
decoded one layer at a time inside a differentiable forward. Without that zoo path, for
full finetuning, and with UNSLOTH_MXFP4_KEEP_PACKED=0 the native load is unchanged.
unsloth_zoo cannot keep offloaded experts packed and only learns about the offload once
transformers resolves the map, after the quantization config is built. With an explicit map
that sends layers to cpu or disk, dequantize = True therefore turned every expert into a
bf16 copy at load (gpt-oss-20b: 41.8 GB of GPU memory instead of 13.7 GB) where the native
load did not dequantize before. Check the map in the helper and leave such loads as they were.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 25, 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-29T15:56:19.674965Z 131b53f Manual request
🔒 Security Review ✅ Completed 2026-09-25T12:13:13.883434Z fdd8237 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

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 🔄 Running since 2026-09-25T12:05:54.983140Z fdd8237 PR opened
🔒 Security Review ⚠️ Failed 2026-09-25T12:05:58.109227Z fdd8237 PR opened
ℹ️ 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.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex security review

@chatgpt-codex-connector

Copy link
Copy Markdown

🛡️ Codex Security Review

Security review completed. No security issues were found in this pull request.

Reviewed commit: fdd82379e7

View security finding report

Only the user who started this review can view the report in Codex.

ℹ️ About Codex security reviews in GitHub

This is an experimental Codex feature. Security reviews are triggered when:

  • You comment "@codex security review"
  • A regular code review gets triggered (for example, "@codex review" or when a PR is opened), and you’re opted in so security review runs alongside code review

Once complete, Codex will leave suggestions, or a comment if no findings are found.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

danielhanchen and others added 2 commits September 25, 2026 23:25
…checkpoint to CPU

auto / sequential / balanced resolve after the packed-experts decision, and transformers
spills to CPU or disk once the accelerators are full; unsloth_zoo then dequantizes every
expert to 16 bit. Size the safetensors checkpoint (Hub file metadata or the local folder)
against the accelerators' free memory, capped by max_memory, and keep the native load when
it would not fit. Unknown sizes keep the packed path.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 25, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

…fload, and check packed support first

The Hub lookup now takes the caller's revision. A known checkpoint size with no measured
accelerator capacity (every card excluded or capped at 0 by max_memory) keeps the native
load. The unsloth_zoo packed-path check runs before any sizing, so an older unsloth_zoo
never triggers the Hub lookup or the accelerator probe.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

pre-commit-ci Bot and others added 2 commits September 26, 2026 00:12
…/disk maps, probe only allowed cards, size the cache offline

Count top-level safetensors of the selected variant only: gpt-oss-120b's original/ folder
doubled its size to 121.5 GiB and wrongly turned the packed path off on an 80 GB card. A
device_map naming cpu or disk keeps the native load. With max_memory, only the cards it
allows are probed. When the Hub is unreachable (local_files_only / HF_HUB_OFFLINE), the
cached snapshot for the revision and cache_dir is sized instead.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

…, skip cards that fail the probe, accept torch.device maps and the QuantizationMethod enum
@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

if user_quantization_config is None:
kwargs["quantization_config"] = quantization_config

P1 Badge Apply dequantization to caller-supplied MXFP4 configs

When the caller passes quantization_config=Mxfp4Config() (whose default is dequantize=False), the packed-path check can construct a replacement with dequantize=True, but this condition discards it because user_quantization_config is non-null and leaves the original object in kwargs. The subsequent from_pretrained therefore takes the native MXFP4 expert path, so LoRA below the MoE layers again receives the incomplete/detached gradient this change is intended to fix; update or replace the caller-supplied MXFP4 config when the packed-path gate succeeds.

ℹ️ 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/vision.py
Comment on lines +1299 to +1302
backend = torch.cuda
if not torch.cuda.is_available() and getattr(torch, "xpu", None) is not None:
if torch.xpu.is_available():
backend = torch.xpu

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Probe NPU memory before selecting packed experts

Fresh evidence after the XPU fix is that this repository also supports DEVICE_TYPE="npu", and Accelerate resolves automatic maps using torch.npu.device_count() and torch.npu.mem_get_info(). On such a host CUDA and XPU are unavailable, so this code leaves backend as torch.cuda, sets probed=False, and returns True without any capacity check; an oversized checkpoint can then spill to CPU after dequantize=True was selected and expand into 16-bit weights. Select the active DEVICE_TYPE_TORCH backend rather than special-casing only XPU.

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.

Not changing this. On NPU the Transformers MXFP4 quantizer already sets dequantize=True itself (validate_environment only keeps MXFP4 on cuda, xpu or cpu), so the native load there is a bf16 copy either way and this gate cannot make it larger.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 26, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 26, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 26, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 26, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 26, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 26, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 26, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 26, 2026
danielhanchen and others added 5 commits September 26, 2026 10:07
…download

snapshot_download(local_files_only=True) checks the cached tree listing, which names
files a load never fetches (metal/, original/), so it raised and the size stayed
unknown: an offline load too large for the GPU still took the packed path and zoo
then dequantized every expert to 16 bit.
…s offload, before keeping MXFP4 experts packed

device_map auto / balanced caps every card but the last at size / n, so summing raw free memory said a 60 GiB checkpoint fits on 80 + 4 GiB cards while accelerate would offload experts (which zoo then dequantizes to 16 bit). An explicit map that puts only lm_head, embeddings, norms, attention or the router on CPU no longer turns packed experts off; anything that could hold experts still does.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 29, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 29, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 29, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 29, 2026
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 29, 2026
@unslothai unslothai deleted a comment from shimmyshimmer Sep 29, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 29, 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

Copy link
Copy Markdown

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

Reviewed commit: 131b53fc44

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

danielhanchen added a commit that referenced this pull request Sep 29, 2026
…/api/health) (#12275)

* Wait for the fake nvidia-smi child to start instead of sleeping in the gpu_query tests

Four tests started a thread, slept a fixed 0.15 to 0.5 s, then changed the fake's state, assuming the older child had already read it. On a loaded runner the child can start later and read the state meant for the next reading (seen as test_a_child_started_before_an_invalidation_is_not_joined reading 64 MiB instead of 180000). The fake logs each call after reading its state, so wait for that line.

* Re-measure a cold /api/health call once before failing the launcher-deadline test

A shared CI runner stalled one cold call to 2.06s against the desktop probe's 2.0s timeout (#11929's Python 3.13 shard); the same call takes 1.02-1.07s idle and on a contended core. A fresh process measures again and the lower reading is asserted, so a cold-path regression (checked with a 1.2s first-call delay) still fails while a one-off stall does not. The 2.0s bound itself is unchanged.

* Trim comments
@danielhanchen
danielhanchen merged commit b7a0d71 into main Sep 29, 2026
19 of 24 checks passed
@danielhanchen
danielhanchen deleted the gpt-oss-mxfp4-lora-packed branch September 29, 2026 19:49
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant