Repository navigation
FSDP2: run GGUF, torchao, OpenVINO and GGML exports on rank 0 instead of refusing them - #15353
Conversation
… 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.
… GPU placement dispatch
|
@codex review |
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 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".
| for name, param in model.named_parameters(): | ||
| if id(param) in seen or not isinstance(param, DTensor): | ||
| continue |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
|
@codex review |
|
Codex Review: Didn't find any major issues. You're on a roll. 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". |
…model only fits the CPU; cgroup-aware host RAM check; offloaded shards use the mesh device [skip ci]
|
Follow-up from a deeper check of the CPU fallback in the QAT torchao export (ee358a5):
New gloo cases: @codex review |
There was a problem hiding this comment.
💡 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".
| 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) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
|
@codex review |
There was a problem hiding this comment.
💡 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".
| need = _gathered_host_bytes(model, offload_to_cpu = True, offload_4bit = True) | ||
| if need + max(_GIB, total // 10) > free: |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
|
@codex review |
|
Codex Review: Didn't find any major issues. 🎉 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". |
|
@codex review |
There was a problem hiding this comment.
💡 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".
| 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) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
…by-module convert [skip ci]
|
@codex review |
|
Codex Review: Didn't find any major issues. Can't wait for the next one! 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". |
## 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`.
Problem
A notebook script launched as
UNSLOTH_FSDP2=1 torchrun --nproc-per-node 2 script.pytrains fine, then dies in its export cell:model.save_pretrained_torchao(...)(the Qwen3 0.6B ExecuTorch and QAT notebooks) raisedRuntimeError: save_pretrained_torchao does not support a model sharded by FSDP2on every rank.save_pretrained_ggufandpush_to_hub_ggufwere refused the same way (FunctionGemma 270M LMStudio has a live GGUF cell).save_pretrained_openvino,push_to_hub_openvino,save_pretrained_ggmlandpush_to_hub_ggmlhad 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_mergedalready gather the shards to rank 0 (_fsdp2_collective_save). This PR gives the whole-model exports the same treatment.Fix
_fsdp2_refuses_saveis replaced by_fsdp2_export_on_rank0(unsloth/save.py), backed byfsdp2_export_on_writer(unsloth/models/fsdp2_save.py). Under FSDP2:UNSLOTH_FSDP2_EXPORT_SKIP_RAM_CHECK=1skips the check.save_pretrained_mergeduses (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 withsave_pretrained_torchaoand 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.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.save_pretrained_ggufreturns its dict of file paths). If rank 0 raises, the other ranks raiseUnsloth: save_pretrained_gguf failed on rank 0, the FSDP2 rank that exports: ...instead of carrying on.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_ggufcallssave_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_torchaoon 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.pyruns 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:save_pretrained_mergedmerged_16bit, tensors equal to one processsave_pretrained_gguf(converter stubbed): rank 0 alone converts, its 16-bit input equals one process, both ranks return the same dict, shards restoredpush_to_hub_gguf(converter andHfApistubbed): only rank 0 calls the Hubsave_pretrained_torchaoLoRA +Int8WeightOnlyConfig,-torchaotensors equal one processsave_pretrained_torchaofull model QATphone-deployment(the ExecuTorch recipe), tensors equal one process, sharded model trains afterwardstests/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):test_fsdp2_save_gloo.py::test_merge_offload_keeps_4bit_adapters_after_an_eval_forward, isNo module named 'bitsandbytes'and fails the same way on baseOn 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.
save_pretrained_torchao: refused (training passed, losses 0.843 / 0.931 / 0.775)Qwen3-0.6B-int8-int4-unsloth/written by rank 0save_pretrained_ggufQ8_0, real llama.cpp converter)save_pretrained_gguf: refusedfunctiongemma-270m-it.Q8_0.ggufwritten by rank 0Exported files compared with one GPU. A copy of each script with
learning_rate = 0.0makes both runs export the same weights; nothing else in the script changes:functiongemma_finetune/model.safetensors(the 16-bit merge GGUF starts from)functiongemma-270m-it.Q8_0.gguffunctiongemma_lora/adapter_model.safetensorsQwen3-0.6B-int8-int4-unsloth/pytorch_model.bin, converted on rank 0's GPU (this PR)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
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.learning_rate = 0.0copy was run on the GPU placement commit.