Skip to content

FSDP2: run GGUF, torchao, OpenVINO and GGML exports on rank 0 instead of refusing them - #15353

Merged
danielhanchen merged 11 commits into
mainfrom
dh/s7-fsdp2-exports
Oct 26, 2026
Merged

danielhanchen merged 11 commits into
mainfrom
dh/s7-fsdp2-exports

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Problem

A notebook script launched as UNSLOTH_FSDP2=1 torchrun --nproc-per-node 2 script.py trains fine, then dies in its export cell:

  • model.save_pretrained_torchao(...) (the Qwen3 0.6B ExecuTorch and QAT notebooks) raised RuntimeError: save_pretrained_torchao does not support a model sharded by FSDP2 on every rank.
  • save_pretrained_gguf and push_to_hub_gguf were refused the same way (FunctionGemma 270M LMStudio has a live GGUF cell).
  • save_pretrained_openvino, push_to_hub_openvino, save_pretrained_ggml and push_to_hub_ggml had no FSDP2 handling at all, so every rank exported its own shards into the same place.

Adapter saves and save_pretrained_merged / push_to_hub_merged already gather the shards to rank 0 (_fsdp2_collective_save). This PR gives the whole-model exports the same treatment.

Fix

_fsdp2_refuses_save is replaced by _fsdp2_export_on_rank0 (unsloth/save.py), backed by fsdp2_export_on_writer (unsloth/models/fsdp2_save.py). Under FSDP2:

  1. Every rank makes the call, as the unmodified script does.
  2. Rank 0 adds up the bytes the gather will leave in its host RAM. If they do not fit, every rank raises before anything is gathered. The message gives the numbers, for example "needs about 18.0 GiB (16.0 GiB of gathered weights + 2.0 GiB headroom), but only 12.3 GiB is available", and suggests the adapter save plus a single-process export. UNSLOTH_FSDP2_EXPORT_SKIP_RAM_CHECK=1 skips the check.
  3. The shards are gathered to rank 0's CPU with the same options save_pretrained_merged uses (merged_save_gather_options(model, "merged_16bit") for a LoRA model, packed 4-bit bytes staged on the CPU). A GGUF LoRA export (save_method = "lora", save_pretrained_ggml) gathers only the adapter. A QAT model saved with save_pretrained_torchao and no LoRA is converted in place, so rank 0 keeps the gathered weights on its GPU when they fit (1 GiB or 10% of the card spare), which is where one GPU converts them. Otherwise it converts on the CPU and prints a line saying so.
  4. Rank 0 alone runs the existing single-process export: the merged 16-bit save, the llama.cpp conversion, the torchao quantization, or the Hub upload.
  5. The other ranks wait on the default store (store.wait, UNSLOTH_FSDP2_SAVE_TIMEOUT, default 7 days). This is not a collective, so a GGUF build that takes many minutes cannot trip the NCCL watchdog.
  6. Every rank returns rank 0's result (save_pretrained_gguf returns its dict of file paths). If rank 0 raises, the other ranks raise Unsloth: save_pretrained_gguf failed on rank 0, the FSDP2 rank that exports: ... instead of carrying on.
  7. Exports that swap submodules in place get them put back afterwards, together with config.quantization_config. torchao's QAT convert replaces every fake-quantized Linear, so without this rank 0 would end up with a different model from the other ranks. The sharded model keeps training after the export.

Nested calls (push_to_hub_gguf calls save_pretrained_gguf) see the gather already active and run directly. TP / PP models are still refused by _model_parallel_refuses_save, which runs first.

Without FSDP2 the wrapper calls fsdp2_units(model), which is the same check the old refusal made, and then the original function. Single-GPU and DDP behaviour is unchanged.

Behaviour difference to note: on one GPU, save_pretrained_torchao on a QAT model leaves the model converted. Under FSDP2 it leaves every rank with the trained, fake-quantized, sharded model. This keeps the ranks consistent with each other.

Tests

tests/test_fsdp2_exports_gloo.py runs 2 gloo ranks on CPU with a small random Qwen3 (3 layers, hidden 64, real Qwen3 tokenizer, LoRA with a random B) and compares against one process:

case base 8ed7abb head
save_pretrained_merged merged_16bit, tensors equal to one process pass (already supported) pass
save_pretrained_gguf (converter stubbed): rank 0 alone converts, its 16-bit input equals one process, both ranks return the same dict, shards restored FAIL (refused) pass
push_to_hub_gguf (converter and HfApi stubbed): only rank 0 calls the Hub FAIL (refused) pass
rank 0 converter raises: rank 1 raises "failed on rank 0" FAIL pass
gathered model too big for host RAM: refused on both ranks with the numbers, nothing written FAIL pass
save_pretrained_torchao LoRA + Int8WeightOnlyConfig, -torchao tensors equal one process FAIL (refused) pass
save_pretrained_torchao full model QAT phone-deployment (the ExecuTorch recipe), tensors equal one process, sharded model trains afterwards FAIL (refused) pass

tests/test_fsdp2_save_coverage.py: the refusal test is replaced. Every export (GGUF, GGUF LoRA, push GGUF, torchao, OpenVINO save / push, GGML save / push) now runs through the rank 0 export with the right gather options. It passes through without FSDP2 and inside a gather already in progress.

Versions (test_fsdp2_exports_gloo.py, test_fsdp2_save_coverage.py, test_fsdp2_save_args.py, test_fsdp2_save_gloo.py):

venv torch transformers result
core 2.13.0 5.17.0 7 / 7 export cases pass, torchao 0.18 cases included
core + overlay 2.13.0 4.57.6 (TRL 0.22.2) 50 passed, 1 skipped
s2_torch210 2.10.0 5.17.0 48 passed, 3 skipped (no torchao)
s2_torch214 2.14.1 5.17.0 39 passed, 11 skipped (no torchao, no bitsandbytes). 1 failure, test_fsdp2_save_gloo.py::test_merge_offload_keeps_4bit_adapters_after_an_eval_forward, is No module named 'bitsandbytes' and fails the same way on base

On base 8ed7abb the new gloo file gives 6 failed and 1 passed. The passing case is merged_16bit, which already worked.

GPU (Kaggle T4 x2, unmodified notebook scripts, 3 training steps)

Every run used torch 2.9.0, transformers 4.57.6, TRL 0.22.2, torchao 0.18.0 and unsloth-zoo main 4dc1114. Base is 8ed7abb; head is this branch.

script base, FSDP2 head, FSDP2 head, one GPU
Qwen3_(0.6B)-Reasoning-Conversational-ExecuTorch FAIL l.300 save_pretrained_torchao: refused (training passed, losses 0.843 / 0.931 / 0.775) PASS, Qwen3-0.6B-int8-int4-unsloth/ written by rank 0 PASS
FunctionGemma_(270M)-LMStudio (live save_pretrained_gguf Q8_0, real llama.cpp converter) FAIL l.704 save_pretrained_gguf: refused PASS, functiongemma-270m-it.Q8_0.gguf written by rank 0 not rerun (A0)

Exported files compared with one GPU. A copy of each script with learning_rate = 0.0 makes both runs export the same weights; nothing else in the script changes:

export FSDP2 vs one GPU
FunctionGemma functiongemma_finetune/model.safetensors (the 16-bit merge GGUF starts from) file sha256 equal, 236 / 236 tensors equal
FunctionGemma functiongemma-270m-it.Q8_0.gguf file sha256 equal, 236 / 236 GGUF tensors equal
FunctionGemma functiongemma_lora/adapter_model.safetensors file sha256 equal
ExecuTorch Qwen3-0.6B-int8-int4-unsloth/pytorch_model.bin, converted on rank 0's GPU (this PR) file sha256 equal, 707 / 707 storages equal

Peak GPU memory sampled during the ExecuTorch FSDP2 run is 13.6 / 13.7 GB on rank 0 / rank 1 in both placements. Gathering on the GPU did not raise the peak; training sets it.

Not covered

  • TP / PP exports stay refused. That is separate work.
  • A real llama.cpp GGUF conversion was not run on CPU here. The CPU tests stub the converter; the Kaggle run used the real one.
  • OpenVINO and GGML under FSDP2 are covered only by the dispatch test. Neither was run end to end.
  • FastSentenceTransformer saves are not changed here.
  • The CPU fallback for an in-place QAT convert (a model too big for rank 0's free GPU memory) is not proven to match one GPU. An earlier revision of this branch converted on the CPU, and its ExecuTorch checkpoint differed from the one-GPU file in 396 of 707 storages, all of them linear qdata / scale. A separate check on the same T4 converted the same bf16 Qwen3 0.6B on CPU and on CUDA, and all 707 tensors were equal, so the cause is not the CPU kernels alone. It was not found. The GPU placement is the default whenever the model fits.
  • The unmodified ExecuTorch script was run on the commit before the GPU placement was added. The learning_rate = 0.0 copy was run on the GPU placement commit.

… of refusing them

Under FSDP2 every rank enters the export, the shards are gathered to rank 0's
CPU, rank 0 alone runs the single-process export, and the other ranks wait on
the store (no collective, so a long GGUF build cannot trip a watchdog). Every
rank returns rank 0's result, or raises when rank 0 raised. A gathered model
that does not fit rank 0's host RAM is refused on every rank with the numbers.
Submodules an export swaps in place (torchao QAT convert) are put back, so the
sharded model keeps training. Non-FSDP2 calls are unchanged.
One GPU converts the fake-quantized weights where they sit, on the GPU. Keep the
gathered weights on rank 0's accelerator when they fit there, so the quantized
checkpoint is computed by the same kernels.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 26, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-26T12:09:53.402621Z 082a52d Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector 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.

ℹ️ 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 on lines +506 to +508
for name, param in model.named_parameters():
if id(param) in seen or not isinstance(param, DTensor):
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 Reshard before estimating export memory requirements

When export follows an eval forward that leaves FSDP2 units unsharded, this estimator skips their ordinary parameters because they are not currently DTensors. However, fsdp2_gathered subsequently calls unit.reshard() before gathering, so those weights become DTensors and are included in the actual allocation. This underestimates both the host-RAM check and the accelerator-placement check in gather_on_accelerator_if_it_fits; with a large vocabulary head, the omitted weights can cause an otherwise avoidable host or GPU OOM. Reshard the units on every rank before either estimate, or account for the parameters that will become sharded.

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.

Agreed, fixed in e211ab2691. Both estimates (_gathered_host_bytes for the host RAM check and gather_on_accelerator_if_it_fits for the placement) now reshard the FSDP2 units first, the same way fsdp2_gathered does, so units an eval forward left gathered are counted. New test_export_estimate_counts_units_an_eval_forward_left_gathered (2 gloo ranks): before the fix the estimate after an eval forward was 242112 bytes against 39069504 resharded; now they are equal.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. You're on a roll.

Reviewed commit: 85118630e6

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

Follow-up from a deeper check of the CPU fallback in the QAT torchao export (ee358a5):

  • The CPU-fallback mismatch against one GPU has a cause: torchao computes each scale as max_val / python_float; CUDA evaluates a tensor divided by a CPU scalar as a * (1 / b), the CPU divides. bf16 / fp16 weights always round to the same scale, fp32 weights (a T4 full finetune upcasts fp16 to fp32) do not, which is the 396 / 707 storages seen earlier. The fallback now still gathers to the CPU but converts one module at a time on the GPU and moves it back, so only one layer above the shards sits on the GPU.
  • The host RAM check now also takes the cgroup v2 / v1 memory limit (containers are killed at their limit, not at host RAM).
  • CPU-offloaded shards read the compute device from the mesh instead of taking the CPU convert silently.

New gloo cases: qat_fallback (rank 0 converts module by module, files equal one process) and cgroup (3 GiB left under a 4 GiB limit). Export tests 27 passed.

@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: 018f4f5cf7

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread unsloth/models/fsdp2_save.py Outdated
Comment on lines +561 to +565
for root in (base, "/sys/fs/cgroup/memory"):
limit = read(os.path.join(root, "memory.limit_in_bytes"))
used = read(os.path.join(root, "memory.usage_in_bytes"))
if limit is not None and used is not None and limit < (1 << 60):
left.append(limit - used)

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 Check ancestor limits in the cgroup v1 hierarchy

For a hierarchical cgroup v1 setup where the process belongs to /job/worker but the memory limit is imposed on /job, this checks only the worker and controller root, skipping the limiting parent. If both checked limits are unlimited, _cgroup_available_bytes() returns None despite the parent's finite allowance, so the export RAM check uses host availability and can permit a gather that gets the container OOM-killed. Walk all ancestors and take the smallest remaining allowance, as the v2 branch does, rather than stopping at the first finite leaf limit.

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.

Agreed, fixed in bce971e: the v1 branch now walks every ancestor of the process's memory cgroup, like v2, and takes the smallest remaining allowance. The gloo cgroup case gains a v1 layout with the limit on /job and the process in /job/worker (no limit of its own): 1.5 GiB left, as expected. Export tests 27 passed.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: bce971ede3

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread unsloth/models/fsdp2_save.py Outdated
Comment on lines +624 to +625
need = _gathered_host_bytes(model, offload_to_cpu = True, offload_4bit = True)
if need + max(_GIB, total // 10) > free:

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 Include converted weights in the accelerator placement estimate

For a QAT export near the GPU memory limit, this can select whole-model GPU conversion even though only the gathered, unquantized weights fit. fsdp2_gathered retains every rebuilt parameter in replaced, and _module_tree_kept also retains the original modules, so conversion cannot release those weights as it allocates the quantized replacements. For example, 10 GiB of bf16 weights converted to int4 require roughly another 2.5 GiB before scales and workspace; with 12 GiB free on a 16 GiB card, this check passes despite insufficient conversion memory. Account for the simultaneously live quantized model when choosing placement, or use the existing module-by-module fallback in this case.

Useful? React with 👍 / 👎.

@danielhanchen danielhanchen Oct 26, 2026 •

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.

Agreed, fixed in 622ae0c: the placement check now needs the gathered weights plus half again for their quantized copies (int8 of 16-bit weights is half their size, int4 a quarter), both alive during the convert, plus the existing headroom; otherwise it takes the module-by-module path. Your example (10 GiB gathered, 12 GiB free on a 16 GiB card) now goes module by module. Export tests 28 passed.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 🎉

Reviewed commit: 1991f28daa

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

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 622ae0cab8

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread unsloth/models/_utils.py Outdated
Comment on lines +8732 to +8735
if home is not None:
getattr(parent, child).to(home)
# The replaced module may still be referenced (a kept module tree, a tied weight).
module.to(home)

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 each original tensor to its own device after conversion

When the CPU-gather fallback converts a QAT Linear whose weight is sharded but whose bias is replicated through FSDP2's ignored_params, home is CPU because it comes from the gathered weight. Moving the original module to home also moves its live replicated bias from CUDA to CPU. fsdp2_gathered restores only the replaced DTensor parameters, and _module_tree_kept restores only submodules, so the bias remains on CPU after export while the sharded weight resumes computing on CUDA. Subsequent training on the writer can therefore fail with a device mismatch. Preserve and restore the original devices of individual parameters and buffers instead of moving the entire original module to the gathered weight's device.

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.

Agreed, fixed in 082a52d. Before moving a layer to the GPU for its convert, every parameter and buffer's device is recorded by name; afterwards each tensor of both the converted layer and the replaced one goes back to its own device (a replicated bias stays on the GPU while the gathered weight returns to the CPU), keeping the Parameter object via .data so optimizer state and FSDP2 references stay valid. New gloo case restore_devices; export tests 29 passed.

@danielhanchen

Copy link
Copy Markdown
Member Author

@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: 082a52d3c4

ℹ️ 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 d08984c into main Oct 26, 2026
@danielhanchen
danielhanchen deleted the dh/s7-fsdp2-exports branch October 26, 2026 13:32
danielhanchen added a commit that referenced this pull request Oct 26, 2026
## Problem


`tests/security/test_lint_risky_loaders.py::test_the_tree_matches_the_baseline`
and the `Source lint` risky-loader step fail on main since #15353, so
every PR based on it inherits the failure (#15374 today):

```
1 risky loader call site(s) not in the baseline:
  unsloth/models/fsdp2_save.py:695  [unsafe-deserialize] pickle.loads
```

#15353 added `_share_from_writer`. The export's writer rank pickles a
small result into the job's default c10d store: the RAM refusal string,
or `("ok", run())` / `("error", message)`. The other ranks wait on that
key and unpickle it.

## Product or test

Neither is wrong; the call site just was not recorded. The bytes come
only from a peer rank of the same job, through the job's own c10d store,
under an `unsloth_fsdp2_export_*` key. Anyone who can write that store
already controls the job's collectives. A format change would be a
product change: `run()` returns whatever the export returns, so JSON
would need its own handling for each exporter. The lint's prescribed
path for a trusted input is a reviewed baseline entry, and that is what
this does.

## Fix

- `python scripts/lint_risky_loaders.py --update`, which added exactly
one entry (`unsloth/models/fsdp2_save.py`, `pickle.loads`, `count: 1`)
and changed nothing else.
- Its "REVIEW ME" reason replaced with why the input is trusted.

## Verification

- `python scripts/lint_risky_loaders.py`: `ok: 109 risky loader call
site(s), all recorded` (failed on main).
- `tests/security/test_lint_risky_loaders.py`: 46 passed.
- Sabotage: adding a second `pickle.loads` to `fsdp2_save.py` is still
reported as not in the baseline, because the entry is pinned to `count:
1`.
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.

1 participant