Skip to content

Keep the real quantization skip list on save, and add an opt-in multi-GPU device map - #8968

Merged
danielhanchen merged 35 commits into
mainfrom
glimmer-loader-quant-metadata-and-device-map
Aug 25, 2026
Merged

danielhanchen merged 35 commits into
mainfrom
glimmer-loader-quant-metadata-and-device-map

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Aug 16, 2026 •

Copy link
Copy Markdown
Member

Two loader changes that came out of looking at what the Muse Glimmer notebooks have to write by hand.

A saved 4-bit model records a layout it never had

After a 4-bit load, loader.py stamps a synthetic quantization_config onto model.config with llm_int8_skip_modules: None, discarding whatever the load actually used. It does this at two sites, one per loader class.

That field is not decoration. It says which modules were left out of quantization, and it is what a reload rebuilds the module topology from. Writing None over it means a saved adapter describes a base model that never existed.

It is worst for our own dynamic-quant repos, which is most of them. Loading unsloth/Qwen3-0.6B-unsloth-bnb-4bit today:

skip list on the loaded model : ['lm_head', ..., 'model.layers.24.self_attn',
                                 'model.layers.0.self_attn', 'model.layers.2.mlp',
                                 'model.layers.27.mlp.up_proj', ...]
skip list we then save        : None

Every per-layer entry is gone. Same on unsloth/Muse-Glimmer-30B-unsloth-bnb-4bit, whose five entries become None.

Fixed by reading the list off the loaded config instead of writing None. None and [] stay distinct: None means transformers picked the output head itself, [] means it was told to exclude nothing, and they are different instructions on reload.

Verified on real weights, before and after, on transformers 4.57.6 and 5.15.0. The set of Linear4bit versus dense modules and the peak VRAM are byte-identical either way. Only the saved metadata changes.

Multi-GPU placement, opt in with device_map = "unsloth"

unsloth_zoo.device_map_planner.plan_device_map_for_pretrained plans a head-aware split that reserves logit headroom on the output head's card and refuses rather than spilling a bitsandbytes model to CPU. Nothing in unsloth or unsloth_zoo called it. The only caller was the Muse Glimmer GRPO notebook, which hand-rolls about 25 lines of mem_get_info arithmetic to use it.

That is now:

model, tokenizer = FastModel.from_pretrained(
    model_name        = "unsloth/Muse-Glimmer-30B-unsloth-bnb-4bit",
    load_in_4bit      = True,
    device_map        = "unsloth",
    device_map_planner_kwargs = {
        "rows_per_chunk": 128,
        "retained_rows": BATCH_SIZE * max_seq_length,
        "softcapped": True, "temperature_scaled": True,
    },
)

device_map_planner_kwargs is not optional polish. The planner's default retained_rows = 0 models inference, so a GRPO backward needs to say what it retains or the reserve is too small.

Opt in only. "sequential" stays "sequential", "auto" keeps accelerate's meaning, and an explicit dict is returned untouched. UNSLOTH_AUTO_DEVICE_MAP=1 upgrades the default for operators who want it, and upgrades only the default, not a placement the caller chose.

It declines and falls back to "sequential" under a distributed launch (torchrun already gives every rank a whole model), under fast_inference (vLLM owns placement), under full_finetuning, on a non-CUDA backend, and on fewer than two GPUs. A planner that returns None or raises falls back too, since a model that loads the old way beats one that will not load. DeviceMapInfeasible is deliberately allowed through: the planner raises it instead of spilling, and swallowing it would hand the user an OOM in place of a diagnosis.

Resolution happens in llama.py and vision.py, not in loader.py. The mapper can still substitute the repo higher up (a -bnb-4bit name resolving to its 16-bit twin, or the BAD_MAPPINGS rewrites), and a plan sized for the repo the caller named is the wrong plan for the one that loads.

Against the real Muse Glimmer config on a 2 x 16 GB budget:

total weights      : 20.310 GiB
no_split classes   : ['MuseGlimmerTextDecoderLayer', 'MuseGlimmerVisionEncoderLayer']
output head        : lm_head -> cuda:1
head headroom      : 4.104 GiB
  cuda:0  budget 13.05 GiB  weights 11.816 GiB  free 1.234 GiB  reserve 1.158 GiB
  cuda:1  budget 13.68 GiB  weights  8.494 GiB  free 5.186 GiB   <- output head
  spills to CPU/disk: False

and on 2 x 8 GB it raises DeviceMapInfeasible with the per-device numbers rather than placing something that will OOM.

Follow-ups in this PR

device_map = "unsloth" was resolved in llama.py and vision.py but not on the diffusion
route: FastModel dispatches diffusion models before FastBaseModel runs, so the string
reached transformers, which turns an unknown device_map into torch.device("unsloth") and
raises. FastDiffusionModel now resolves it at the leaf as well, and _dispatch_diffusion
forwards device_map_planner_kwargs, which is a named parameter and so was never in **kwargs.

vision.py also planned against the default branch while the load used _revision. A plan
sized from a different revision names modules the checkpoint does not have, and accelerate
raises on the ones left without a device rather than warning.

tests/test_unsloth_device_map_leaks.py covers both: every leaf loader resolves before it
loads, and each planner call gets the same ref the weights do.

Tests

tests/test_bnb_checkpoint_skip_modules.py and tests/test_unsloth_device_map_optin.py, 32 tests, no GPU needed. Both extract the functions with ast so nothing has to import torch's CUDA stack.

The skip-list file pins two rules. First, that nobody rewrites a pre-quantized checkpoint's own list: transformers already prefers it over any runtime config, and writing into it is the only way to get it wrong. unsloth/Llama-3.2-11B-Vision-Instruct-bnb-4bit ships llm_int8_skip_modules: null because it quantized everything, so filling that null in makes transformers build multi_modal_projector as a dense Linear[4096, 7680] against a packed [15728640, 1] tensor and the load dies in load_state_dict. Second, that the saved config matches the load, including None versus [].

The device-map file is mostly about what must not change: five existing device_map values returned untouched, an explicit dict untouched, the env var upgrading only the default, and every decline path asserting the planner is never called.

Full suite, this branch against main, same runner and same working directory:

branch main
failed 37 38
errors 5 5
passed 10489 10456

The failure sets are identical. No test fails on this branch that does not also fail on main.

Checked on transformers 4.57.6 and 5.15.0, with real 4-bit loads of unsloth/Llama-3.2-1B-Instruct and unsloth/Qwen3-0.6B-unsloth-bnb-4bit on both, giving identical module topology and identical peak VRAM against main.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

danielhanchen and others added 2 commits August 16, 2026 08:19
…planner revision

Two leaks in the opt-in device map.

FastModel dispatches diffusion models before FastBaseModel runs, so "unsloth" reached
transformers unresolved, which turns an unknown device_map string into
torch.device("unsloth") and raises. FastDiffusionModel now resolves it at the leaf, the
same place llama.py and vision.py do, and _dispatch_diffusion forwards
device_map_planner_kwargs, which is a named parameter and so never appeared in **kwargs.

vision.py planned against the default branch while the load used _revision. A plan sized
from a different revision either under-budgets or names modules the checkpoint does not
have, and accelerate raises on the missing devices rather than warning.

tests/test_unsloth_device_map_leaks.py pins that every leaf loader resolves before it
loads and that each planner call gets the same ref as the weights.

@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: 9385155dc7

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread unsloth/models/llama.py
Comment on lines +2612 to +2614
token = token,
trust_remote_code = trust_remote_code,
revision = revision,

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 Pass the load's subfolder to the device-map planner

For a model loaded with subfolder=..., Transformers receives that option through **kwargs, but this planner call—and the analogous vision call—only receives the repository root and selected authentication/revision arguments. The planner therefore either reads a different root configuration and returns a map for the wrong module tree, or fails and silently falls back to sequential when the configuration exists only in the subfolder. Forward the same subfolder used by the actual load so the plan describes the checkpoint being instantiated.

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 taking this one.

The planner is exactly as subfolder-blind as the code it sits in, so it adds no new failure mode. Both AutoConfig reads on this path, llama.py:2450 and llama.py:2461, omit subfolder today, and they run about 150 lines before the planner call.

That rules out both halves of the report. If the config exists only in the subfolder, AutoConfig raises at 2461 and the load is already dead, so the planner is never reached and there is nothing to fall back from. If a root config exists but disagrees with the subfolder, then model_config, MODEL_FOR_CAUSAL_LM_MAPPING[model_config.__class__], model_max_seq_length, IS_FALCON_H1 and resolve_attention_implementation are all already derived from that same root config on main, so the load is wrong with or without a device map.

Passing subfolder to the planner alone would make the plan disagree with the config the rest of the function was built from, which is worse than the current consistency. If subfolder support is worth having it belongs on the AutoConfig reads, as a separate change against main, not on this call.

danielhanchen and others added 2 commits August 16, 2026 08:52
loader.py clears load_in_4bit and load_in_8bit whenever the caller passes a
quantization_config, since transformers refuses both at once. The leaf loaders were
handing those cleared flags to the planner, so a full-precision checkpoint about to be
quantized got sized at bf16. The planner refuses to spill a bitsandbytes model to CPU
and raises DeviceMapInfeasible rather than falling back, so a 70B QLoRA that fits on
two cards failed outright.

The skip list has to travel with them. On-the-fly quantization always keeps
SKIP_QUANTIZATION_MODULES in compute dtype and transformers reads that as
modules_to_not_convert, so planning lm_head and a whole vision_tower at 4bit understates
the head device by GiBs. That is the one number the head-aware plan exists to get right.
A pre-quantized checkpoint is unaffected: its own config.json carries the list.

planner_quantization_kwargs in loader_utils.py builds the right inputs for both leaves.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

…ly use

from_pretrained's dtype overrides whatever config.json declares, but the planner only
ever saw the config, so any load that changed dtype was sized wrong by a factor of two.
A float32 load of a bfloat16 checkpoint got an accepted map that OOMs while
materializing, and the default bfloat16 load of a float32 checkpoint raised
DeviceMapInfeasible on a load that fits. All three leaves now pass the dtype the load
is given. In vision.py that means resolving the forced-float32 case before the plan
rather than at the load, so both use one value.

diffusion.py was still handing the planner the bare flags. Its BitsAndBytesConfig skips
lm_head, embed_tokens, experts, self_conditioning and router, and transformers turns
that into modules_to_not_convert, so every skipped module was budgeted at 4 bits while
it materializes in compute dtype. For a MoE checkpoint the experts are most of the
weights. The config is now built before the plan and the load reuses that same object.

Passing the real config rather than a generic skip list matters for the 8bit branch,
which deliberately has no skip list; injecting one there would over-size and could
refuse a load that fits.
danielhanchen added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Aug 16, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

danielhanchen and others added 2 commits August 16, 2026 10:12
…the repo config

The planner only receives model_name and rebuilds the repo's own config, so any load
that overrides that config gets a map for a module tree it will not have.

text_only is the reachable case. It swaps in the text sub-config and loads the decoder
alone, so the plan describes the whole VLM and names model.language_model.layers.N while
the load creates model.layers.N. On a Gemma 3 4B that is 444 of 445 weights arriving with
no device, and transformers raises "doesn't have any device set" mid-load. Transformers
4.57 no longer pre-flights the map through accelerate's check_device_map, so there is no
friendly error first.

num_labels is the same failure from the other side: the load builds a sequence
classification head whose score replaces the lm_head the plan named, and accelerate
refuses the map for giving score.weight no device.

Both now decline planning and fall back to sequential, matching how the resolver already
handles vLLM, full finetuning and distributed launches. Passing the effective config to
the planner is not an option: plan_device_map_for_pretrained takes only a repo name and
builds the config itself.

The class comparison is on model classes rather than auto classes, since
AutoModelForVision2Seq and AutoModelForImageTextToText are distinct objects that resolve
to the same VLM. It fails open: an unknown class vetoes nothing.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

danielhanchen added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Aug 16, 2026
…sk head

Last commit vetoed a class-divergent plan in vision.py, but loader.py only delegates to
FastModel for 8bit, full finetuning and QAT. A num_labels load of a llama, mistral, gemma,
gemma2, qwen2 or qwen3 repo stays on the optimized path, where the planner sized the
repo's causal LM and the load then built AutoModelForSequenceClassification. That model
has a score head and no lm_head, so accelerate's dispatch_model refuses the map with
"does not give any device for the following parameters: score.weight".

The veto does not fail open here, unlike the vision path. A num_labels load is a
classification load by construction and the planner's own class resolution can never
produce a sequence classification class, so an unknown class still declines.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 16, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 16, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 16, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 16, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 16, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 16, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 16, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Aug 25, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 9dd2d7f43f

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

…d skip list

Three from review:

max_memory now replaces the measured budget rather than overlaying onto it. The
keys of a mapping the caller wrote are the devices they will let the load use --
accelerate's _init_infer_auto_device_map takes devices = list(max_memory.keys())
and get_max_memory never widens a supplied mapping -- so {0: ..., 1: ...} on a
four-GPU host was leaving the planner free to place weights on the two cards they
had reserved for another workload. Devices we cannot measure (cpu, disk) survive.

FastSentenceTransformer stripped the default's marker with str(), which also
turned an explicit dict placement into the text "{'': 0, 'model': 1}".
unmarked_device_map touches the marker and nothing else.

llama.py declines to plan a prequantized bitsandbytes checkpoint of a mamba hybrid
whose bundled skip list lacks the exclusions the load adds. merge_quantization_configs
overlays loading attributes for GPTQ/AWQ/AutoRound/FbgemmFp8/CompressedTensors/Mxfp4
and never for bitsandbytes, so such a checkpoint is always sized by the list in its
own config.json and no argument here can correct it; the mamba stacks are GiBs of
error. The other unbundled entries reachable on this loader are MoE routers, which
top out near 70 MiB on Qwen3-235B-A22B, inside the planner's 256 MiB safety margin.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 25, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 25, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 25, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 25, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 25, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 25, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 25, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 25, 2026
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Aug 25, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep it up!

Reviewed commit: eb22d83949

ℹ️ 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 and docstring text only, AST-verified against HEAD. Also drops a stale copy
of the max_memory rationale in loader_utils that the earlier fix left behind above
its replacement.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

mem_get_info was called for every visible device before the caller's device set was
applied, so a card withheld for another workload got a CUDA context initialised on it
anyway, and a withheld card that refuses (Exclusive_Process, ECC, MIG parent) dropped
the whole plan to sequential over a device this load was never going to touch --
sequential being the placement that then OOMs.

The device set is now read before probing. A set with fewer than two GPUs is not a
multi-GPU plan, so it returns sequential without asking the planner or touching a card.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 25, 2026
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Aug 25, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep them coming!

Reviewed commit: 64814e1e9e

ℹ️ 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 text only, AST-verified.
@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: e084873225

ℹ️ 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
danielhanchen merged commit ac600e8 into main Aug 25, 2026
40 checks passed
@danielhanchen
danielhanchen deleted the glimmer-loader-quant-metadata-and-device-map branch August 25, 2026 04:46
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