Repository navigation
Tokenizer save under DDP / FSDP2: private copy per rank, then move into place - #17862
Conversation
…ove it in Every rank of a DDP or native FSDP2 run saves the tokenizer to the same folder, and Unsloth re-reads tokenizer_config.json right after the transformers save to fix it up. A rank that was truncating the file at that moment made another rank raise JSONDecodeError (5 of 40 concurrent saves on 2xT4 under FSDP2). Use the per-rank private copy + os.replace that tensor parallel tokenizers already use, and push from rank 0 only.
Codex Review Summary: ✅ CompletedThis 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. |
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Lines 9200 to 9204 in 2c528f3
When a DDP/FSDP2 job saves directly into a mounted output directory, this newly enabled path can fail even though the destination is writable. tp_world_save creates its temporary directory beside the destination and then uses os.replace to move files into it; if the destination is a mount point on another filesystem, those moves raise EXDEV. I reproduced this with the existing helper targeting /dev/shm, where a direct save succeeds but the staged save raises Invalid cross-device link. The sibling staging directory also requires write access to the destination's parent, which direct saves did not require. Create the private staging directory within the destination instead so these previously supported DDP/FSDP2 saves continue working.
ℹ️ 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".
…n, so os.replace stays on one filesystem [skip ci]
|
Fixed the staging location finding in the latest commit: |
|
@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". |
[skip ci]
# Conflicts: # unsloth/save.py [skip ci]
…locks (unslothai#17875) GRPO under the FSDP2 sharded layout crashed at its first loss forward with `AttributeError: 'FSDPCommContext' object has no attribute 'all_gather_copy_in_stream'`. The sharded layout is chosen automatically once a model is larger than 40% of one GPU. A 16-bit Qwen3 4B GRPO run on T4s would likely land on it by default. ## Root cause FSDP2 makes whichever sharded unit runs a forward first the root. During the rollout, the model is gathered (`native_fsdp2_unsharded`), and Unsloth's decode loop calls the decoder blocks directly, never the model's top-level forward. A block therefore initialised as its own root, and the next training forward through the real root failed. On CPU the same bug reads "FSDP requires running forward through the root module first". ## Fix `native_fsdp2_unsharded` initialises the real root unit (`_lazy_init_root`) before it gathers. It does nothing once a forward has already gone through the root. ## Results | Check | main | This PR | |---|---|---| | `tests/test_fsdp2_native_unsharded_block_calls_gloo.py` (2 CPU ranks: blocks called inside the gathered context, then one training step) | "already been lazily initialized for layers.0" | passes; loss and grad norm match one process | | Kaggle 2xT4, shrunk `Gemma3_(1B)-GRPO.py`, `UNSLOTH_FSDP2_LAYOUT=sharded` | crashes in training (`all_gather_copy_in_stream`) | fixed: all 4 steps train (with unslothai/unsloth-zoo#2540) | | Kaggle 2xT4, Llama3.2 SFT, sharded layout | passes, loss matches single GPU | | Existing FSDP2 unsharded / units / optimizer re-entry tests: 42 passed, 5 skipped. The same 4 `test_native_fsdp2_units_and_grads[Qwen2_5_VL|Qwen3VL-*]` cases fail on main and with this PR. ## Step-2 hang under the sharded layout (second commit) Under the sharded layout every forward all-gathers, so every rank must run the same number of forwards. GRPO broke that two ways: sequence packing and PrefixGrouper ran their no-grad self-verify forwards only on the rank whose packed length grew, and the padded scoring loop sized its mini batch from each rank's own sequence length. With `TORCH_DISTRIBUTED_DEBUG=DETAIL` the ranks sat in different collectives (rank 0 in a block all-gather, rank 1 already in backward). `_unsloth_grpo_refuse_rank_local_forwards` turns packing and PrefixGrouper off through the existing refusal flags, and the scoring loop agrees its chunk count across ranks (the largest, so no rank forwards more rows than it sized for), only when forwards are collective (`grpo_forwards_are_collective` from unslothai/unsloth-zoo#2540: world > 1 and a unit re-shards after forward). DDP and FSDP2's default fit layout read False and are unchanged; the cost is that GRPO under the sharded layout uses the padded loop instead of packing. Kaggle 2x T4, main vs this PR + unslothai/unsloth-zoo#2540 (+ unslothai#17862 for the tokenizer save at the end of the notebook): | Run | main | This PR | |---|---|---| | Gemma3 1B GRPO, FSDP2 default layout | 4 steps, then rank 1 fails in `tokenizer.save_pretrained` (unslothai#17862) | passes; grad norm [0.9363, 0.6525] identical to main; packing stays on | | Gemma3 1B GRPO, sharded layout | step 1 `AttributeError` | passes, all 4 steps; peak 3032 MiB | | Llama3.2 SFT, default / sharded | max loss diff vs 1 GPU 9e-5 / 6e-5 | 3e-5 / 5e-5 | Both ranks record collective forwards True with packing and PrefixGrouper off under the sharded layout, and False with packing on under the default layout. `tests/test_grpo_collective_forwards_nograd.py` fails without the change and passes with it; all 491 `tests/test_grpo*.py` pass. Merge after unslothai/unsloth-zoo#2540 (without it the new check reads False and behaviour is unchanged).
…oding in test_bind_local_cuda_device (#17892) ## Summary Two repo-wide reds on `main`, both from test files added in the last few merges: 1. `tests/test_ci_repo_cpu_shards.py::TestEveryTestFileLandsInExactlyOneShard::test_no_file_is_dropped_or_run_twice` (`Repo tests (CPU, rest)`): - #17862 added `tests/test_tokenizer_save_ddp_gloo.py`. No shard collects it: `gloo` takes `test_[!fpt]*gloo*`, and `rest` ignores `test_[!f]*gloo*`. It never runs in CI. - #17868 added `tests/test_ddp_push_rank0_gloo.py`. Both `gloo` (`test_[!fpt]*gloo*`) and `rest-2` (`test_[dimsu]*.py`) collect it, so it runs twice, and in `rest-2` without the gloo shard's setup. 2. `tests/test_source_read_encoding.py::test_checked_in_file_reads_name_an_encoding` (`Repo tests (CPU, rest-2)`): #17867's `tests/test_bind_local_cuda_device.py:47` reads `unsloth/__init__.py` with `read_text()` and no encoding. Both new files are correct tests. They only needed a shard home and an explicit encoding. ## Changes - `.github/workflows/studio-backend-ci.yml`: - `gloo` gains `tests/test_t[!p]*gloo*.py`, which covers `test_tokenizer_*`. `test_tp_*` keeps its existing split between `gloo` and `gloo-tp`. - `rest-2` gains `--ignore-glob=tests/test_[dimsu]*gloo*.py`, so a gloo file starting with d/i/m/s/u runs only in `gloo`. - The comment that listed `test_t[!p]*` as an unclaimed name is updated. - `tests/test_bind_local_cuda_device.py`: `read_text(encoding = "utf-8")`. ## Verification `tests/test_ci_repo_cpu_shards.py tests/test_source_read_encoding.py tests/test_bind_local_cuda_device.py`: 38 passed. Removing either workflow line brings back the matching failure: ``` these files are collected by more than one shard: [('tests/test_ddp_push_rank0_gloo.py', ['gloo', 'rest-2'])] these files are collected by no shard, so Repo tests (CPU) no longer runs them: ['tests/test_tokenizer_save_ddp_gloo.py'] ```
…iniMax LoRA sidecar read (#17913) ## Summary Two checks are red on main right now: 1. **`Repo tests (CPU, rest)`: `tests/test_ci_repo_cpu_shards.py::TestEveryGlobRootMatchesAFile::test_no_shard_hands_pytest_an_unexpanded_pattern`** ``` AssertionError: these shard globs match no test file: [('gloo', 'tests/test_t[!p]*gloo*.py')] ``` #17892 added `tests/test_t[!p]*gloo*.py` to the gloo shard so that `tests/test_tokenizer_save_ddp_gloo.py` (from #17862) was collected by some shard. #17882 landed at the same time and renamed that file to `tests/test_local_save_tokenizer_ddp_gloo.py`, which the gloo shard's first glob (`tests/test_[!dfimpstu]*gloo*.py`) already covers. The `test_t[!p]` glob now matches nothing, and an unmatched glob reaches pytest as a literal path. Both PRs were right on their own; together they leave one dead glob. 2. **`(Python 3.13, rest)` and `Repo tests (CPU, rest)`: the text I/O encoding gates** ``` test_text_io_names_its_encoding[diffusion_minimax_h3_image.py] assert not ['diffusion_minimax_h3_image.py:3422: read_text() without encoding'] ``` #17863 added `json.loads(sidecar.read_text())` for the LoRA `adapter_config.json` sidecar. Without an encoding that read uses the locale codepage on Windows. ## Change - `.github/workflows/studio-backend-ci.yml`: remove `tests/test_t[!p]*gloo*.py` from the gloo shard and restore the comment that a `test_t[!p]*` gloo file would be reported as dropped by `tests/test_ci_repo_cpu_shards.py` (with a note on why the glob is not kept for later: an unmatched glob is a missing file to pytest). - `studio/backend/core/inference/diffusion_minimax_h3_image.py`: `sidecar.read_text(encoding = "utf-8")`. JSON is UTF-8, so behaviour on Linux and macOS is unchanged. ## Testing - `tests/test_ci_repo_cpu_shards.py` and `test_text_io_encoding.py::test_text_io_names_its_encoding[diffusion_minimax_h3_image.py]`: 16 passed on this branch, 2 failed on main. - `tests/test_runtime_text_encoding.py` and `studio/backend/tests/test_diffusion_minimax_h3_image.py` pass; `studio/backend/tests/test_text_io_encoding.py` passes for every tracked file.
Under FSDP2, ranks saving the tokenizer into the same folder can crash with
JSONDecodeError.Root cause
Every rank calls
tokenizer.save_pretrainedon the same folder._preserve_sentencepiece_tokenizer_assetsinunsloth/save.pythen re-readstokenizer_config.jsonwithjson.load, while another rank is still truncating that file.On Kaggle 2xT4, 5 of 40 concurrent saves raised under FSDP2. DDP hit 0 of 40, but only by timing.
Fix
When
world_size > 1,unsloth_tokenizer_save_pretrainedtakes the existingtp_world_savepath: each rank writes a private copy, then moves it into place withos.replace. A Hub push goes out from rank 0 only.Results
tests/test_tokenizer_save_ddp_gloo.py(2-rank gloo, forced interleaving)JSONDecodeErroron rank 0