Repository navigation
Keep the real quantization skip list on save, and add an opt-in multi-GPU device map - #8968
Conversation
…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.
There was a problem hiding this comment.
💡 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".
| token = token, | ||
| trust_remote_code = trust_remote_code, | ||
| revision = revision, |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
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.
…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.
…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.
…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.
|
@codex review |
|
Codex Review: Didn't find any major issues. Swish! 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". |
…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.
|
Codex Review: Didn't find any major issues. Keep it up! 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". |
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.
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.
|
Codex Review: Didn't find any major issues. Keep them coming! 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". |
Comment text only, AST-verified.
|
Codex Review: Didn't find any major issues. Swish! 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". |
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.pystamps a syntheticquantization_configontomodel.configwithllm_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
Noneover 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-4bittoday:Every per-layer entry is gone. Same on
unsloth/Muse-Glimmer-30B-unsloth-bnb-4bit, whose five entries becomeNone.Fixed by reading the list off the loaded config instead of writing
None.Noneand[]stay distinct:Nonemeans 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
Linear4bitversus 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_pretrainedplans 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 ofmem_get_infoarithmetic to use it.That is now:
device_map_planner_kwargsis not optional polish. The planner's defaultretained_rows = 0models 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=1upgrades 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), underfast_inference(vLLM owns placement), underfull_finetuning, on a non-CUDA backend, and on fewer than two GPUs. A planner that returnsNoneor raises falls back too, since a model that loads the old way beats one that will not load.DeviceMapInfeasibleis 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.pyandvision.py, not inloader.py. The mapper can still substitute the repo higher up (a-bnb-4bitname resolving to its 16-bit twin, or theBAD_MAPPINGSrewrites), 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:
and on 2 x 8 GB it raises
DeviceMapInfeasiblewith the per-device numbers rather than placing something that will OOM.Follow-ups in this PR
device_map = "unsloth"was resolved inllama.pyandvision.pybut not on the diffusionroute:
FastModeldispatches diffusion models beforeFastBaseModelruns, so the stringreached transformers, which turns an unknown
device_mapintotorch.device("unsloth")andraises.
FastDiffusionModelnow resolves it at the leaf as well, and_dispatch_diffusionforwards
device_map_planner_kwargs, which is a named parameter and so was never in**kwargs.vision.pyalso planned against the default branch while the load used_revision. A plansized 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.pycovers both: every leaf loader resolves before itloads, and each planner call gets the same ref the weights do.
Tests
tests/test_bnb_checkpoint_skip_modules.pyandtests/test_unsloth_device_map_optin.py, 32 tests, no GPU needed. Both extract the functions withastso 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-4bitshipsllm_int8_skip_modules: nullbecause it quantized everything, so filling thatnullin makes transformers buildmulti_modal_projectoras a denseLinear[4096, 7680]against a packed[15728640, 1]tensor and the load dies inload_state_dict. Second, that the saved config matches the load, includingNoneversus[].The device-map file is mostly about what must not change: five existing
device_mapvalues 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:
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-Instructandunsloth/Qwen3-0.6B-unsloth-bnb-4biton both, giving identical module topology and identical peak VRAM against main.