Skip to content

studio: shard export checkpoint loads across all visible GPUs - #7215

Merged
danielhanchen merged 24 commits into
unslothai:mainfrom
hakanbaysal:fix/studio-export-multi-gpu-device-map
Jul 26, 2026
Merged

danielhanchen merged 24 commits into
unslothai:mainfrom
hakanbaysal:fix/studio-export-multi-gpu-device-map

Conversation

@hakanbaysal

Copy link
Copy Markdown
Contributor

Export checkpoint loading always used unsloth's from_pretrained default of
device_map="sequential", which stacks the whole model on GPU0. On a multi-GPU
host this OOMs GPU0 while the other GPUs sit empty, so a GGUF export that would
comfortably fit across the machine fails with CUDA out of memory (#7053).

Add _multi_gpu_device_map_kwargs(): when the CUDA/ROCm host exposes more than
one visible GPU and get_device_map resolves to "balanced" (the same policy the
inference loader already uses), pass device_map="balanced" to every
from_pretrained in load_checkpoint. In every other case -- single GPU, CPU,
MLX, or any probe failure -- it returns {} so the loader default is untouched.

Fixes #7053

Export checkpoint loading always used unsloth's from_pretrained default of
device_map="sequential", which stacks the whole model on GPU0. On a multi-GPU
host this OOMs GPU0 while the other GPUs sit empty, so a GGUF export that would
comfortably fit across the machine fails with CUDA out of memory (unslothai#7053).

Add _multi_gpu_device_map_kwargs(): when the CUDA/ROCm host exposes more than
one visible GPU and get_device_map resolves to "balanced" (the same policy the
inference loader already uses), pass device_map="balanced" to every
from_pretrained in load_checkpoint. In every other case -- single GPU, CPU,
MLX, or any probe failure -- it returns {} so the loader default is untouched.

Fixes unslothai#7053
@gemini-code-assist

Copy link
Copy Markdown
Contributor

Caution

The consumer version of Gemini Code Assist on GitHub has been sunset. All code review activity has officially ceased.

@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: 1212a0023d

ℹ️ 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 studio/backend/core/export/export.py Resolved
Comment thread studio/backend/core/export/export.py Resolved
hakanbaysal and others added 3 commits July 17, 2026 23:40
…re quantize

Two review fixes on the multi-GPU export sharding:

1. UUID/MIG CUDA_VISIBLE_DEVICES masks resolve to no numeric ids, so the
   len(visible) > 1 gate skipped get_device_map entirely and large exports on
   those hosts still stacked onto GPU0. An empty id list now routes to
   get_device_map(None), whose visible-count fallback exists for exactly this
   case; a genuinely GPU-less host still resolves "sequential" and keeps the
   loader default.

2. The compressed (FP8/NVFP4) export freed GPU memory before its llm-compressor
   subprocess only for single-device models -- a plain .to("cpu") is invalid on
   an accelerate-dispatched model, so a multi-GPU-sharded checkpoint stayed
   resident on every GPU while the subprocess loaded a second copy. The release
   is factored into _offload_model_for_quantize_subprocess /
   _restore_model_after_quantize_subprocess: dispatched all-GPU shards get their
   accelerate hooks removed, move to CPU, and are re-dispatched over the
   recorded hf_device_map afterwards. Maps with cpu/disk targets (already
   offloading) and quantized models are left alone, as before.

@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: f9cb55fd2f

ℹ️ 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/save.py Resolved
Comment thread studio/backend/core/export/export.py Resolved
hakanbaysal and others added 3 commits July 18, 2026 06:13
…ffload fails

Two review fixes on the multi-GPU export path:

1. The LoRA-merge save path budgeted every merged tensor against GPU0
   (get_device_properties(0) + unqualified memory_allocated()). A merged tensor
   lives on the GPU of its source layer, so for a model sharded across GPUs
   (the device_map="balanced" this PR enables) GPU1+ could OOM as their weights
   accumulated while only GPU0's headroom was checked. Budget against W's own
   device via a per-device cache; single-GPU behavior is unchanged (W on GPU0).

2. _offload_model_for_quantize_subprocess removed the accelerate hooks and then
   moved a dispatched model to CPU; if that move raised (host RAM too small for
   the sharded checkpoint) the model was left hookless and half-moved, breaking
   later exports in the same worker. It now re-dispatches (or, for the
   single-device path, moves back) on a failed move before aborting the offload.

@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: 1c95d50a3d

ℹ️ 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 studio/backend/core/export/export.py Resolved
The portable torchao FP8/INT8 export freed the in-memory model only when every
parameter sat on one device, then reloaded a second copy with
device_map="auto". A checkpoint loaded through the new multi-GPU export map is
accelerate-dispatched across several GPUs, so that single-device gate never
fired and the original stayed resident on every GPU during the reload -- an OOM
for exactly the models large enough to have needed the sharded load.

It now uses the same _offload_model_for_quantize_subprocess /
_restore_model_after_quantize_subprocess pair as the compressed export, which
removes the accelerate hooks, moves to CPU, and re-dispatches over the recorded
hf_device_map afterwards. Those helpers are extended to XPU as well, since
torchao also runs on Intel GPUs and the path they replace covered both.

@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: a94677c31f

ℹ️ 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/save.py Resolved
Comment thread unsloth/save.py Resolved
hakanbaysal and others added 4 commits July 19, 2026 21:32
… reloads

Two cases the release helper skipped outright, both of which leave GPU memory
held while the compressed subprocess or the torchao device_map="auto" reload
allocates a second copy:

- Quantized models. ExportBackend.load_checkpoint loads 4-bit by DEFAULT, so the
  common Studio export hit the is_loaded_in_4bit guard and kept a quantized shard
  on every visible GPU. They are now attempted like any other model: transformers
  refuses .to() for some bitsandbytes builds, but that refusal raises before
  anything moves, so the existing recovery path restores the model and returns
  None -- best-effort where the stack allows it, old behaviour where it does not.

- Maps that spill to CPU. Any non-GPU target disqualified the whole model even
  though the GPU-mapped modules were still resident and are exactly what needs
  reclaiming. A cpu spill is safe to move (those weights are already in host RAM)
  and is now released; only disk/meta targets are still skipped, because
  accelerate keeps those parameters off the model and moving would try to
  materialize the whole checkpoint. An all-CPU map is skipped as a no-op.
…Ms (unslothai#7215)

The dispatch branch of _offload_model_for_quantize_subprocess never ran for a
PEFT model: the wrapper proxies _hf_hook, so remove_hook_from_submodules raised
AttributeError and the bare except returned None. Studio always loads adapters,
so the new balanced map turned the offload off (0 percent freed against 91.8 on
the sequential path it replaces).

- resolve the real dispatch root before removing or replaying hooks
- snapshot and replay hooks, tensor placements and instance forwards; a plain
  re-dispatch rebuilds hooks against the post-PEFT tree (395 to 1379) and drops
  the fused kernels accelerate captured into _old_forward before unsloth patched
- drop the accelerator side of tied_params_map so the offload actually frees
- pass skip_keys on the fallback dispatch_model
- log the swallowed exception instead of returning None silently
- guard _unsloth_save_torchao_with_given_config like its two siblings
- retry the export load once on the loader default when the balanced map OOMs,
  which happens when a training or chat job already owns the other GPUs

Measured on 4x B200 with Qwen3-0.6B: 89.9 percent freed bf16 and 79.7 percent
4bit under balanced, logits bit-identical, hooks and placements restored
exactly, 184 Params4bit round-tripped unchanged including nested state2.
@danielhanchen

Copy link
Copy Markdown
Member

Thanks for this, the core change is right and I confirmed the issue it targets is real.

Reproduced #7053 on a 4x B200 box: with GPU0 capped and the other three free, the old sequential default dies with CUDA out of memory. Tried to allocate 1.09 GiB and balanced loads fine. Before the change 100 percent of the checkpoint sat on GPU0 at 1.22 GB peak; after it splits 25/29/29/16 with 0.36 GB peak. Merged safetensors come out byte-identical and the GGUF is bit-identical across all 310 tensors.

I pushed 8b6b4ca to this branch rather than leave it as review notes, since a couple of the problems only show up when you actually run the new path.

What the follow-up commit fixes

The offload was a silent no-op on exactly the configuration this PR introduces. _offload_model_for_quantize_subprocess calls remove_hook_from_submodules(model), and a PEFT wrapper proxies unknown attributes to the model it wraps. So hasattr(peft_model, "_hf_hook") is true, delattr then fails, and accelerate raises AttributeError before removing a single hook. The bare except Exception: return None swallowed it and logged nothing. Studio always loads an adapter, so under the new balanced map nothing was freed at all:

load hooks VRAM freed
bf16, sequential (the path this replaces) 0 91.8 percent
bf16, balanced (the new path) 397 0 percent
4bit, sequential 0 83.9 percent
4bit, balanced 397 0 percent

Repairing that naively costs the fused kernels. accelerate restores module.forward = module._old_forward when a hook comes off, and _old_forward is whatever the forward was when the hook was first attached, which is before unsloth patches the module. One remove and re-add cycle therefore reverts apply_lora_mlp_swiglu to stock Qwen3MLP.forward on all 28 MLPs, permanently. The logits move by up to 0.5 on a scale of 19 and the top-5 order changes. I bisected it: the hook cycle alone reproduces it with no device move, all 703 parameters and buffers are bit-identical afterwards, and two consecutive forwards on an untouched model agree exactly. So the commit snapshots the hook objects, the tensor placements and the instance forwards, and replays them verbatim.

Also in the commit:

  • resolve the real dispatch root, since hf_device_map keys are relative to the inner module, not the wrapper
  • drop the accelerator side of accelerate's tied_params_map after the move, otherwise holding the hooks pins a GPU copy of the tied embedding (0.31 GB of 1.24 GB here) and the offload frees far less than it should
  • pass skip_keys on the fallback dispatch_model; without it all 397 hooks came back with skip_keys=None where the model declares ["past_key_values"]
  • log the swallowed exception instead of returning None silently, which is why this survived four review rounds
  • guard _unsloth_save_torchao_with_given_config the same way as its two siblings
  • retry the export load once on the loader default when the balanced map OOMs

That last one is a behaviour regression worth calling out. routes/export.py deliberately refuses to tear down a running training or chat job, and balanced budgets from the free memory read before this process opens its own CUDA context on each GPU. With a trainer holding GPUs 1 to 3 down to 900 MB free, sequential loads and exports fine but balanced fails with CUDA out of memory ... GPU 3 ... 14.06 MiB is free. The retry restores the old outcome without giving up the sharding when the GPUs are actually free.

Verification

check before after
PEFT + balanced, bf16 VRAM freed 0 percent 89.9 percent
PEFT + balanced, 4bit VRAM freed 0 percent 79.7 percent
logits after offload and restore shifted bit-identical
device map, param and buffer devices, tied groups, hook execution devices n/a restored exactly
hook count 397 to 397 397 to 397
184 Params4bit incl. nested state2 n/a bit-identical
single-GPU and sequential paths 91.8 / 83.9 percent unchanged
export while a trainer holds the other GPUs at 900 MB free fails succeeds
multi-GPU sharding with GPUs free 4-way split unchanged
10 alternating success and failure cycles n/a hooks, devices and logits stable, 0.0 GB VRAM drift
host RAM failure injected mid-offload n/a returns cleanly, hooks and placements preserved
test suites 15 + 9 20 + 9

Five regression tests were added for the new behaviour, including one that pins the _old_forward problem so it cannot come back.

Compatibility

Checked the hardware matrix with one spoofed subprocess per cell over [Linux, WSL, Windows, macOS] x [NVIDIA, ROCm, XPU, CPU, MLX], 22 cells. balanced is only produced for multi-GPU NVIDIA and multi-GPU ROCm; single-GPU, XPU, CPU-only and both macOS variants keep the loader default untouched, and no non-CUDA cell touches a CUDA property or memory API. Two cases simply do not engage the fix rather than regressing: CUDA_VISIBLE_DEVICES unset with no nvidia-smi available, and a stale single-GPU HIP_VISIBLE_DEVICES or ROCR_VISIBLE_DEVICES on an NVIDIA host.

Dependency floors and ceiling were checked in separate venvs: transformers 4.51.3 through 5.5.0, accelerate 0.34.1, peft 0.18.0, bitsandbytes 0.45.5, 0.47.0 and 0.50.0. dispatch_model accepts device_map, skip_keys and force_hooks at every version, and device_map="balanced" is still valid at transformers 5.5.0, where the validation just moved to integrations/accelerate.py.

Cross-platform and Playwright runs are going through a staging repo so they do not sit in the org queue. I will report back when they finish.

@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: 8b6b4ca0b5

ℹ️ 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/save.py Outdated
Comment on lines +4566 to +4567
finally:
_restore_model_after_quantize_subprocess(model, model_restore)

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 Delay restoring the original until the quantized copy is released

For save_pretrained_torchao(..., torchao_config=...) on CUDA/XPU, from_pretrained(device_map="auto") leaves quantized_model resident on the accelerator, but this finally immediately restores the full original model before the quantized copy is saved or deleted. A large model that only fits after the new offload will therefore OOM during restoration; that exception is swallowed by the restore helper, so the export can report success while the caller's model is left partially moved and unusable. Keep the original offloaded through saving and releasing quantized_model, and restore it from an outer finally afterward.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Good catch, that was mine and it was wrong. The finally fired as soon as from_pretrained returned, so the original came back onto the accelerator while quantized_model was still resident and still being saved, which defeats the offload on exactly the models that needed it. The restore helper also warns rather than raises, so a failure there would have been invisible.

Fixed in a58f108: the restore now sits in an outer finally that covers the save and the del quantized_model, with a cache clear before it. That matches what _unsloth_save_torchao and _unsloth_save_compressed_tensors already do.

Comment thread unsloth/save.py
Comment on lines +4704 to +4705
for name, hook in hooks:
add_hook_to_module(root.get_submodule(name) if name else root, hook)

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 Retie shared parameters after replaying dispatch hooks

For an Accelerate-dispatched model with tied input/output embeddings, moving to CPU changes the tensors' data pointers and the preceding cache cleanup removes their accelerator entries. Re-adding each hook here consequently materializes separate parameters for the formerly shared weights, and unlike dispatch_model, this replay never reties them. After a compressed or torchao export, subsequent training can update the two weights independently and restoration consumes duplicate VRAM; preserve the tied groups and retie them after all hooks and placements are restored.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Correct, and reproduced. On a Llama with tie_word_embeddings=True dispatched over two GPUs, one offload and restore cycle gave lm_head.weight its own storage: the embedding was duplicated in VRAM and an update to embed_tokens.weight no longer reached lm_head.weight (0.978656 against -0.021344).

Root cause is as described. The CPU round trip repoints every tensor, tied_params_map is keyed on the pre-move pointer, and the replay then materialises independent parameters.

Fixed in a58f108. The snapshot now records tied groups by storage pointer and re-ties them after all placements are restored. One detail worth noting for anyone reading the diff: it has to enumerate with named_parameters(remove_duplicate=False), because the default hides one half of every tied pair, which is precisely the half that needs re-tying. The stale accelerator entries in tied_params_map are dropped afterwards so the pre-retie tensors are not pinned.

After the fix: tie preserved, no extra storages, a live CUDA storage census identical before and after (39 storages, 8.817 MiB both sides), updates propagate again, and logits bit-identical. A regression test pins it.

…etie shared weights (unslothai#7215)

Two follow-ups from review of 8b6b4ca.

_unsloth_save_torchao_with_given_config restored the original inside a finally
that ran as soon as from_pretrained returned, so the original and the quantized
copy were both resident while the copy was still being saved. The restore now
sits in an outer finally that covers saving and releasing quantized_model, which
is what the two sibling paths already do.

The dispatch replay did not preserve tied embeddings. A CPU round trip repoints
every tensor and accelerate's tied_params_map is keyed on the old pointer, so
replaying the hooks produced two independent parameters. Reproduced on a tied
Llama: lm_head picked up its own storage, the embedding was duplicated in VRAM,
and an update to one no longer reached the other. The snapshot now records tied
groups (named_parameters(remove_duplicate=False), since the default hides one
half of every pair) and re-ties them after placements are restored.

Verified: tie preserved, no extra storages, live CUDA storage census identical
before and after, updates propagate again, logits bit-identical, and the 4 GPU
invariants unchanged at 89.9 percent freed bf16 and 79.7 percent 4bit.
@danielhanchen

Copy link
Copy Markdown
Member

@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

Here are some automated review suggestions for this pull request.

Reviewed commit: a58f1086bf

ℹ️ 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/save.py
Comment on lines +4687 to +4689
for name, tensor in named:
groups.setdefault(tensor.untyped_storage().data_ptr(), []).append(name)
ties = [names for names in groups.values() if len(names) > 1]

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 Exclude meta tensors from tied-weight groups

When an hf_device_map contains a CPU-offloaded module, Accelerate represents its parameters as meta tensors, whose storage pointers are all zero. This groups every such parameter together as if it were tied; during _restore_dispatch_state, _share_tensor then replaces unrelated parameters—potentially with different shapes—with the first parameter in the group, corrupting the restored in-memory model after export. Ignore meta/zero-pointer tensors when constructing ties and rely on the hooks' weight maps to restore them.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Correct, and this one was a corruption bug, not just a waste. Reproduced with a balanced map that spills two blocks to CPU: 18 parameters land on meta, all report storage pointer 0, and they collapsed into a single group holding shapes 64x64, 32x64 and 128x64. The retie step would have overwritten every one of them with the first.

Fixed in c423701: meta and null-pointer tensors are excluded when the groups are built, and _share_tensor now checks shape as well as device before replacing anything. Same repro afterwards: 18 meta parameters, 0 tie groups. A regression test pins it.

Comment thread unsloth/save.py
f"Unsloth: could not snapshot the accelerate dispatch "
f"({type(snap_exc).__name__}: {snap_exc}); re-dispatching on restore."
)
remove_hook_from_submodules(root)

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 Restore Accelerate's device-movement guards

For a dispatched base model, Accelerate's remove_hook_from_submodules also deletes the instance-level to, cuda, xpu, and related wrappers installed by dispatch_model, but the snapshot restoration only reinstalls hooks, forwards, and tensor placements. Consequently, after a successful quantized export, a later model.to(...) or model.cuda(...) uses the raw module method while the restored hooks and hf_device_map still target the old devices, which can incorrectly move or OOM a sharded/offloaded model. Preserve these wrapped methods in the snapshot or reinstall the dispatch movement guards during restoration.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Correct. remove_hook_from_module pops _accelerate_added_attributes, which is ["to", "cuda", "npu", "xpu", "mlu", "sdaa", "musa"], so the replay left the raw nn.Module methods in place while the restored hooks and hf_device_map still described a sharded model.

Fixed in c423701: the snapshot records those instance attributes alongside forward and _old_forward and replays them. The list is read from accelerate.hooks._accelerate_added_attributes when available so it tracks upstream, with the current names as a fallback.

Comment thread studio/backend/core/export/export.py Outdated
# GPU, so when a training or chat job already owns the others (which
# routes/export.py deliberately allows) the shard can OOM where the pre-#7053
# single-device load succeeded. Fall back once before giving up.
if _device_map_override is None and _is_oom_error(e) and _multi_gpu_device_map_kwargs():

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 Retry balanced bitsandbytes CPU-spill failures

With the default load_in_4bit=True, a concurrent job occupying secondary GPUs can make Accelerate's balanced calculation place modules on CPU or disk even when GPU0 alone still has enough space for the old sequential load. Transformers' bitsandbytes quantizer rejects that placement with a ValueError saying modules were dispatched to CPU/disk, not an OOM exception or an “out of memory” message, so _is_oom_error(e) is false and the intended single-device fallback is skipped. Recognize this placement failure as retryable before returning the load error.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Correct, and I confirmed the exact path. transformers/quantizers/quantizer_bnb_4bit.py:128 raises a plain ValueError reading "Some modules are dispatched on the CPU or the disk...", with no memory wording anywhere in it, so _is_oom_error returned False and the fallback never fired. That is the common case rather than an exotic one, since Studio defaults to load_in_4bit=True and a busy secondary GPU is exactly when balanced starts spilling.

Fixed in c423701 with an explicit _is_cpu_spill_rejection predicate, ORed into the retry condition. A regression test asserts the bnb ValueError is retryable while an unrelated RuntimeError is not.

Comment thread unsloth/save.py Outdated
)
tokenizer.save_pretrained(torchao_save_directory, token = token)

del quantized_model

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 Release the quantized copy on exceptional exits

If the quantized model loads successfully but save_pretrained, push_to_hub, or the tokenizer save then raises, execution skips this del, while the finally block tries to restore the original model with quantized_model still resident. For models that only loaded the quantized copy because the original was offloaded, this recreates the exact two-model OOM the change is intended to avoid and leaves the original on CPU after the restore failure is swallowed. Delete any initialized quantized copy in the finally block before collecting caches and restoring the original.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Correct. The del sat at the end of the try, so a failure in save_pretrained, push_to_hub or the tokenizer save skipped it and the finally restored the original with the quantized copy still resident, which is the two-model residency the change exists to avoid.

Fixed in c423701: the copy is dropped at the top of the finally, before the cache clear and the restore. A regression test asserts the ordering inside that block.

danielhanchen and others added 2 commits July 26, 2026 08:02
…retry CPU spills (unslothai#7215)

Four follow-ups from review of a58f108.

Meta tensors all report storage pointer 0, and accelerate parks every
CPU-offloaded parameter on meta, so grouping by pointer collapsed them into one
fake tied group. Reproduced with a balanced map that spills two blocks to CPU:
18 meta parameters in a single group with shapes 64x64, 32x64 and 128x64, which
the retie step would have overwritten with the first one. Meta and null-pointer
tensors are now skipped, and the retie also checks shape.

remove_hook_from_submodules deletes the to/cuda/xpu wrappers dispatch_model
installs to stop a caller moving an offloaded model. The snapshot now records
and replays those alongside forward and _old_forward.

The single-device retry only matched OOM, but a balanced map that spills to CPU
is refused by bitsandbytes with a plain ValueError saying modules were dispatched
to the CPU or the disk (transformers quantizers/quantizer_bnb_4bit.py:128), with
no memory wording. That is now retryable too, which matters because Studio loads
4-bit by default and busy secondary GPUs are exactly when balanced spills.

The torchao path dropped the quantized copy at the end of the try, so a failure
in save_pretrained left it resident while the original was restored. The del
moved into the finally, ahead of the restore.

Four regression tests added; suites now 25 and 9.
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Jul 26, 2026

@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: 85a0612da3

ℹ️ 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/save.py
Comment on lines +1162 to 1164
elif W.device.type != "cuda":
# Already off-GPU (offloaded layer): keeping it costs no VRAM.
state_dict[name] = W

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 Spill merged CPU weights instead of retaining them

When a balanced device map offloads layers to CPU, merging a LoRA creates new tensors for those layers while the original CPU weights remain resident. This branch retains every merged tensor in state_dict without consulting the previously computed RAM budget, so large CPU-spilled checkpoints can accumulate nearly another copy of their offloaded weights and exhaust host RAM; route these tensors through the disk fallback unless they fit an explicit RAM budget.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Declining this one. Three reasons, in order of weight:

  1. The RAM budget you want consulted does not exist. It is commented out directly below this branch, upstream, with # [TODO] Saving to RAM seems to leak memory???. Re-enabling a spill path that upstream deliberately disabled is not something this PR should do on the side.

  2. It is not a regression. Pre-PR the line was if (torch.cuda.memory_allocated() + W.nbytes) < max_vram, where max_vram is GPU0 capacity. For a CPU tensor that comparison is nonsense but almost always true, so CPU weights were retained then too. The only case it changed is when GPU0 happened to be full, where the old code spilled a CPU tensor to disk because a GPU was busy. The new elif just makes the existing behaviour explicit and drops that.

  3. This is unsloth_save_model, which no Studio export path reaches. Studio goes through unsloth_generic_save -> merge_and_overwrite_lora, which streams the base weights from the checkpoint shards on disk and never builds this state_dict. I confirmed that with coverage earlier in this review.

Comment thread unsloth/save.py
Comment on lines +4705 to +4707
for name, tensor in named:
if tensor.device.type == "meta":
continue

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 Preserve ties between meta-device parameters

For an accelerate map containing CPU-offloaded modules, genuinely tied parameters such as input embeddings and the LM head are both represented by the same meta Parameter when this snapshot is taken. Skipping every meta tensor therefore omits that real tie; hook removal materializes separate parameters, and _restore_dispatch_state never reties them, leaving the restored model with duplicated, independently mutable weights. Track meta ties by object identity rather than their zero storage pointer.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I built the repro for this and it does not hold, so I am leaving the meta skip in place.

Tied Llama (tie_word_embeddings=True), asserted lm_head.weight is model.embed_tokens.weight before dispatch, then dispatched with both offloaded to cpu. After dispatch_model:

  • same_object_before: false

accelerate does not keep a tied pair as one shared Parameter when it offloads. AlignDevicesHook.init_hook calls set_module_tensor_to_device(module, name, "meta") per module, so each side gets its own meta placeholder and the real values move into the weights_map. Identity finds nothing that the pointer did not: the snapshot records ties_found: [] either way.

Nothing is lost by skipping them. The round trip returns the pair to exactly the state it was in (both meta, same distinct objects, same devices, round_trip_faithful: true), and the real weights live in accelerate offload storage that the offload/restore never touches.

Keying meta tensors by id() would therefore only add a branch that provably never fires on this accelerate version, so I would rather not carry it. Happy to revisit with a case where a tied pair does survive offloading as one object.

@@ -405,6 +484,7 @@ def load_checkpoint(
trust_remote_code = trust_remote_code,

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 Retry full-precision loads that spill modules to CPU

On a multi-GPU host with a busy secondary GPU and load_in_4bit=False, device_map="balanced" can successfully return a model whose hf_device_map contains CPU-offloaded modules, so neither exception-based retry runs. Accelerate leaves those module parameters on meta, but the merged-save path later reads them directly in _merge_lora rather than invoking their hooks, causing the export to fail on meta/device-mismatched operations or serialize data-less tensors; detect an accepted CPU spill and retry the single-device loader when GPU0 could hold the previous sequential load.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Good catch, and it is worse than the 4-bit case: with load_in_4bit=False nothing raises at all, so neither branch of the retry ever sees it.

Reproduced on 4x B200 against a merged (non-PEFT) checkpoint loaded with a map that offloads 8 layers:

  • load succeeds, hf_device_map keeps 8 cpu entries, 88 parameters stay on meta
  • the export then dies in safetensors: NotImplementedError: Cannot copy out of meta tensor; no data!

Worth noting why only merged checkpoints hit this: for a LoRA checkpoint PEFT re-dispatches after attaching the adapter, which materialises everything and clears the offload. I traced a base load that came back with 8 cpu entries and the final PEFT model had 0 cpu entries and 0 meta parameters, so the adapter path was already safe by accident.

Fixed in 79e6b97 by inspecting the resulting map instead of waiting for an exception. _cpu_offloaded_modules() counts cpu/disk targets and the load raises _CpuSpillRetry, which joins the existing out-of-block retry. Scoped to if _device_map_kw so a single-GPU host, which has no second placement to retry onto, behaves exactly as before.

After the fix, same checkpoint and same map: retry fires, model lands on GPU0 with 0 meta parameters, export is 310/310 tensors bit-identical to the source. With the real balanced resolver on the same 4-GPU host there is no spurious retry (1 map resolution, sharded across 0-3, 0 cpu entries, export still bit-identical). Covered by 5 new tests in test_export_multi_gpu_device_map.py.

Comment thread unsloth/save.py
Comment on lines +4590 to +4591
quantized_model = None
del quantized_model

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 Clear failed quantization tracebacks before restoring

If from_pretrained or save_pretrained raises, the active exception traceback still retains the callee frame and its partially built or fully loaded quantized model, so deleting only this local variable does not release its accelerator tensors. The immediately following restore can therefore OOM and leave the original model on CPU; once the exception propagates and its traceback is released, no restoration is retried, poisoning subsequent export attempts in the same session.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Agreed, and this is the same trap that broke the first version of the export.py retry, so I should have caught it here too. Setting the local to None does not release the copy while the exception is still propagating, because the traceback keeps the frames that built it alive.

Fixed in 79e6b97: the finally block now clears the in-flight traceback frames before the restore.

_exc = sys.exc_info()[1]
if _exc is not None:
    traceback.clear_frames(_exc.__traceback__)

Added a test that pins the mechanism rather than the text: it runs the same try/finally shape with a weakref to an object held only by the failing callee frame, asserts the object survives without clear_frames and is collected with it.

Comment thread unsloth/save.py
Comment on lines +1132 to +1135
if dev.type != "cuda":
return None
idx = dev.index if dev.index is not None else torch.cuda.current_device()
if idx not in _max_vram_by_device:

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 Account for external allocations in VRAM budgets

On the busy multi-GPU hosts this change is designed to support, total_memory * maximum_memory_usage is not an available-memory budget: torch.cuda.memory_allocated(W.device) only counts this process and ignores training or inference jobs using the same GPU. A balanced load can correctly place a small shard based on current free memory, but the merge then accumulates tensors up to a fraction of total VRAM and OOMs well before this threshold on a busy secondary GPU; derive each budget from mem_get_info or otherwise include allocations from other processes.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

The observation about the formula is fair, but it is not something this PR introduced and I do not want to change it here.

git show $(git merge-base HEAD origin/main):unsloth/save.py at this function:

max_vram = int(torch.cuda.get_device_properties(0).total_memory * maximum_memory_usage)
...
if (torch.cuda.memory_allocated() + W.nbytes) < max_vram:

Same total_memory * ratio, same memory_allocated(). The PR changed which device is budgeted, not how the budget is derived, so the external-allocation blind spot is pre-existing upstream behaviour that this diff carries over unchanged.

Switching to mem_get_info would also redefine a public parameter. maximum_memory_usage is a documented argument on save_pretrained_merged, push_to_hub_merged and friends (defaults 0.75 / 0.85 / 0.9) and it means a fraction of capacity everywhere it is used, including the host RAM budget a few lines up at max_ram = int(max(0, max_ram) * maximum_memory_usage). Making the GPU side mean a fraction of free memory would give the same argument two meanings and silently change the effective budget for every existing caller.

Worth doing, but as its own change against unsloth_save_model with its own testing, not folded into a Studio multi-GPU export fix.

@danielhanchen

Copy link
Copy Markdown
Member

@codex review

danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Jul 26, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 6818e73d63

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

Copy link
Copy Markdown
Member

@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

Here are some automated review suggestions for this pull request.

Reviewed commit: 31de15046a

ℹ️ 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/save.py
Comment on lines 5443 to +5444
finally:
if model_dev is not None:
try:
model.to(model_dev)
except Exception:
logger.warning_once(
"Unsloth: could not restore the model to its original device after torchao "
"export; it may remain on CPU."
)
_restore_model_after_quantize_subprocess(model, model_restore)

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 Release the quantized copy before restoring the original model

If from_pretrained, processor loading, or either save_pretrained call raises after allocating the quantized model, the live local/traceback still retains that GPU-resident copy when this finally restores the original multi-GPU shards. The restore can therefore OOM and leave the Studio model partially restored or on CPU; this file's other torchao path explicitly deletes the copy and clears the traceback before restoring, and this path needs equivalent failure cleanup.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Correct, and I missed it when I fixed the sibling path. quantized_model is assigned at save.py:5385 and deleted at 5396, but the finally at 5443 runs the restore, so anything raising in between (the reload, the processor load, either save_pretrained) leaves the copy resident through both the live local and the traceback frames.

Fixed in 3f4ebd4 with the same treatment the other path already had: null the local, clear the in-flight traceback frames, three gc/empty_cache rounds (CUDA and XPU), and only then restore.

Added a test asserting both torchao paths do this, so the two cannot drift apart again.

Comment thread unsloth/save.py
Comment on lines +4815 to +4816
else:
tensor.data = tensor.data.to(want)

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 Restore parameter gradients with their weights

When a dispatched model is exported while trainable adapter parameters still have gradients, model.to("cpu") moves both their data and gradients to CPU, but this replay moves only tensor.data back to the original accelerator. This path specifically handles LoRA tensors added after dispatch, so resuming training after export leaves CUDA/XPU parameters with CPU gradients and the next optimizer step can fail with a device mismatch; move any existing tensor.grad back to want as part of the restore.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Real bug, thanks. The symptom is worse than described though, so the suggested fix would not have worked, and it is worth recording why.

Gradients are not left on CPU. They are destroyed outright. I instrumented the round trip on a 2-GPU dispatched model with a trainable parameter added after dispatch:

after backward                     id= 20816 dev=cuda:1  grad=cuda:1
after remove_hook_from_submodules  id= 20816 dev=cuda:1  grad=cuda:1
after model.to("cpu")              id= 20816 dev=cpu     grad=cpu
after re-adding hooks              id= 11248 dev=cuda:1  grad=None
after placement loop               id= 11248 dev=cuda:1  grad=None

The parameter object id changes when the hooks go back on: add_hook_to_module runs init_hook, which calls set_module_tensor_to_device, which constructs a fresh nn.Parameter. The gradient is gone before the placement loop is reached, so moving tensor.grad there would have found nothing to move.

Fixed in 3f4ebd4 by recording gradients in the snapshot and reattaching them after the hooks are back, on whatever device the weight ended up on.

Verified on 2x B200, same fixture: grad_survived true, grad back on cuda:1 with its sum unchanged at 1024.0, no device mismatch, and a real optimizer.step() now succeeds where it previously had no gradient at all. Covered by a unit test that simulates the init_hook parameter swap.

Comment on lines +98 to +100
if len(visible) > 1:
device_map = get_device_map(visible)
elif not visible:

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 Reserve merge headroom in the balanced device map

For a near-capacity 4-bit LoRA checkpoint, device_map="balanced" may fill each visible GPU with model shards without reserving space for export-time dequantization. unsloth.save._merge_lora materializes each layer in float32 before the new per-device budget check runs, so a checkpoint that loads successfully can OOM during the merge even though loading it on a roomier GPU with the previous sequential policy would have exported successfully; provide per-device max_memory headroom for the largest merge temporary or retry the export with the single-device policy.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Measured this one and it comes out the other way round: balanced leaves MORE merge headroom than the old policy, not less.

4-bit LoRA checkpoint on 4x B200, balanced vs sequential, same fixture and same merge:

balanced sequential
peak on GPU0 407.2 MB 982.9 MB
min free after load 104864 MB 104272 MB

Sequential stacks the whole model on GPU0 and then merges there too, so GPU0 carries both the shards and every float32 temporary. Balanced spreads the shards, and because each merged tensor is built on the device of its source layer the temporaries spread with them: peak per GPU drops to roughly 40 percent, and the tightest GPU ends up 592 MB better off. Reserving headroom would be solving a problem that the sharding already relieves.

Separately, the function cited is not on this path. I spied both merge entry points during a real Studio-style export:

unsloth_save_merge_lora: 0
zoo_merge_and_overwrite: 1

unsloth.save._merge_lora and its per-device budget are in unsloth_save_model, which no Studio export reaches; unsloth_generic_save goes to merge_and_overwrite_lora, which streams base weights from the checkpoint shards on disk.

@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Can't wait for the next one!

Reviewed commit: 3f4ebd428b

ℹ️ 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 to danielhanchen/unsloth-staging-2 that referenced this pull request Jul 26, 2026
@danielhanchen
danielhanchen merged commit e7d047a into unslothai:main Jul 26, 2026
48 of 50 checks passed

@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: 20d81f0e8d

ℹ️ 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/save.py
Comment on lines +4794 to +4795
for name, hook in hooks:
add_hook_to_module(root.get_submodule(name) if name else root, hook)

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 Preserve Parameter identity when replaying dispatch hooks

When an Accelerate-dispatched LoRA model is exported after its optimizer has been created and training later resumes, add_hook_to_module runs each hook's initializer, which recreates hooked parameters while moving the CPU-offloaded weights back. The snapshot now restores gradients onto those new objects, but the optimizer's parameter groups still reference the old CPU parameters, so later optimizer steps either update detached weights or fail on device-mismatched state. Preserve and rebind the original Parameter objects rather than restoring only their gradients.

Useful? React with 👍 / 👎.

Comment thread unsloth/save.py
Comment on lines +4709 to +4711
ptr = tensor.untyped_storage().data_ptr()
if ptr:
groups.setdefault(ptr, []).append(name)

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 Distinguish packed tensor views from tied weights

For dispatched models with packed weights, such as equal-shaped MoE expert parameters registered as different slices of one backing allocation, untyped_storage().data_ptr() returns the same base address for every slice even though their storage offsets differ. This groups all experts as tied, and the later shape/device-only check replaces every follower with the first expert after export, silently making distinct experts identical. Identify exact aliases by object identity or include storage offset, shape, and stride in the grouping key.

Useful? React with 👍 / 👎.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Unsloth Studio GGUF export uses only GPU0 and ignores multiple GPUs during checkpoint loading

3 participants