Skip to content

torchrun: plain Trainer DDP find_unused default, FSDP2-collective SentenceTransformer save - #15324

Merged
danielhanchen merged 4 commits into
mainfrom
dh/s7-torchrun-plain-trainer-st-save
Oct 26, 2026
Merged

danielhanchen merged 4 commits into
mainfrom
dh/s7-torchrun-plain-trainer-st-save

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Two fixes so unmodified notebook scripts run under torchrun --nproc-per-node 2 (Kaggle T4x2).

1. Plain transformers.Trainer under DDP: "marked as ready twice"

Orpheus TTS (and the other notebooks that train a LoRA model with the plain Trainer) failed on the first backward under DDP:

RuntimeError: Expected to mark a variable ready only once ...
Parameter at index 386 with name base_model.model.model.layers.27.mlp.gate_proj.lora_A.default.weight has been marked as ready twice.

Cause: ddp_find_unused_parameters is None, the model is a PeftModel (not a PreTrainedModel), so transformers passes find_unused_parameters=True to DDP. With reentrant gradient checkpointing the checkpointed forward runs without grad, DDP marks every LoRA weight unused, then the recompute marks them again. Unsloth already picks False for this case (unsloth_default_ddp_find_unused_parameters in _ddp_defaults.py), but only the generated TRL trainers call it (rl.py), not the patched Trainer.__init__.

Fix: the patched Trainer.__init__ (_utils.py) calls the same default before the original __init__, so plain Trainer, Seq2SeqTrainer and any other subclass get it. It runs before __init__ because transformers 5 builds the DDP kwargs inside __init__ (4.x builds them in _wrap_model). The helper is unchanged: it only fills a value the user left as None, only under a distributed launch with gradient checkpointing on, and only for a single plain LoRA adapter on a decoder-only causal LM (MoE, towers, modules_to_save, embedding / lm_head adapters, encoder-decoder models are left to transformers). An explicit ddp_find_unused_parameters is kept. TRL trainers call it twice now; the second call re-decides to the same value.

2. FastSentenceTransformer save_pretrained under native FSDP2

With UNSLOTH_FSDP2=1 torchrun, the sentence-transformer notebooks trained fine but crashed in model.save_pretrained(...):

RuntimeError: Attempted to access the data pointer on an invalid python storage.

Cause: SentenceTransformer.save reads the DTensor shards directly (through the Transformer module and PeftModel.save_pretrained), on every rank, into the same folder. The causal LM saves are collective (_fsdp2_collective_save / fsdp2_gathered), the sentence-transformer save was not.

Fix (sentence_transformer.py): FastSentenceTransformer.from_pretrained / get_peft_model wrap SentenceTransformer.save (behind save_pretrained and SentenceTransformerTrainer._save) once. For a model FSDP2 does not shard it is a pass-through. For a sharded one every rank calls it, fsdp2_gathered gathers the weights to rank 0, rank 0 writes, the other ranks return None and wait for the write. Two details keep the folder identical to a one-process save:

  • The model card's usage snippet runs model.encode, and a forward of a sharded model is collective. It is now run on every rank before the gather (whole weights via native_fsdp2_unsharded, since older sentence-transformers' encode calls self.forward and skips the root unit's hooks), and the writer's card reuses the result. Without this, sentence-transformers 6.x hangs in the save (rank 0 alone in an all-gather), and 5.x writes a card without the similarity output.
  • The card prints the architecture, so FSDP2's FSDP<Name> classes are named as their plain classes while rank 0 writes.

The native FSDP2 Trainer.save_model hook (fsdp2_native.py) gathers for a SentenceTransformer too (its trainer's _save ignores a state_dict and calls save_pretrained), so checkpoints and trainer.save_model() write the same files.

save.py is not touched.

Tests

New CPU tests, 2 gloo ranks, tiny random models built in the test:

  • tests/python/test_plain_trainer_ddp_gc.py: LoRA Llama with reentrant checkpointing armed on the model, plain Trainer and Seq2SeqTrainer, 2 steps under DDP. Head: trains, DDP built with find_unused_parameters=False, both ranks log the same losses. An explicit ddp_find_unused_parameters=True is kept (and still fails, as before).
  • tests/python/test_sentence_transformer_fsdp2_save.py: BERT LoRA SentenceTransformer sharded with native FSDP2, forward and backward, then save_pretrained on both ranks and Trainer.save_model through the native hook. Both folders equal a one-process save byte for byte (adapter, configs, tokenizer, README with the usage snippet output); rank 1 returns None; the shards are restored afterwards.
test base (merge base) head
plain Trainer / Seq2SeqTrainer DDP, transformers 5.17.0 FAIL "Expected to mark a variable ready only once" PASS
plain Trainer / Seq2SeqTrainer DDP, transformers 4.57.6 + TRL 0.22.2 FAIL same PASS
explicit ddp_find_unused_parameters=True kept PASS PASS
FSDP2 ST save, sentence-transformers 5.1.2 (tf 5.17.0 and 4.57.6) FAIL "invalid python storage" PASS, byte-equal
FSDP2 ST save, sentence-transformers 6.2.0 FAIL "invalid python storage" PASS, byte-equal

Existing related tests pass on head: test_ddp_find_unused_default.py, test_ddp_comm_defaults.py, test_fsdp2_native_trainer_ckpt_gloo.py, test_fsdp2_native_trainer_init_any_loader_gloo.py, test_cold_import_order.py, test_st_save_merged_signature.py, test_st_modules_json_trust_gate.py, tests/python/test_sentence_transformer_ddp_gc.py.

GPU: the notebooks' python_scripts on Kaggle T4x2 (torch 2.9.0, transformers 4.57.6, TRL 0.22.2, sentence-transformers 6.2.0), max_steps = 3, same zoo for both arms:

script mode base head
Orpheus_(3B)-TTS torchrun DDP FAIL at trainer.train() (marked as ready twice) PASS, losses 4.551 / 4.613 / 4.482
Orpheus_(3B)-TTS FSDP2 PASS PASS
All_MiniLM_L6_v2 FSDP2 FAIL at model.save_pretrained (invalid python storage) PASS
All_MiniLM_L6_v2 torchrun DDP PASS PASS
Gemma3_(270M) SFT (unchanged path) DDP and FSDP2 PASS PASS, same losses

Not covered

  • The default stays None for plain-Trainer notebooks whose model the helper does not classify as a plain dense LoRA causal LM (Whisper and other encoder-decoder speech models, Sesame CSM, Deepseek OCR and other vision models). Those keep transformers' find_unused_parameters=True and were not run under DDP here.
  • SentenceTransformer.push_to_hub, save_pretrained_merged, GGUF and torchao exports under FSDP2 are unchanged by this PR.

…tenceTransformer save

Plain transformers Trainer (and Seq2SeqTrainer, other subclasses) now gets the same
DDP find_unused_parameters default the generated TRL trainers already apply, before
Trainer.__init__ builds the DDP kwargs. A LoRA model with reentrant gradient
checkpointing no longer fails the first backward with "marked as ready twice".
An explicit ddp_find_unused_parameters is kept.

SentenceTransformer.save is collective under native FSDP2: every rank calls it, the
shards are gathered to rank 0, which writes; the other ranks return None. The native
Trainer.save_model hook gathers for a SentenceTransformer too. The saved folder equals
a one-process save byte for byte.
@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-26T06:39:51.017843Z 31c6353 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.

@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: 31c635351d

ℹ️ 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 e0a8f07 into main Oct 26, 2026
@danielhanchen
danielhanchen deleted the dh/s7-torchrun-plain-trainer-st-save branch October 26, 2026 08:56
shimmyshimmer pushed a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Oct 26, 2026
… torchrun) (unslothai#15359)

Targets main (follows unslothai#15324, merged as e0a8f07).

## Problem

`torchrun --nproc-per-node 2` on the DeepSeek-OCR notebook fails on the
first backward, on main and on unslothai#15324 alike:

```
torch.utils.checkpoint.CheckpointError: torch.utils.checkpoint: A different number of tensors was saved during the original forward and recomputation.
Number of tensors saved during forward: 50
Number of tensors saved during recomputation: 49.
```

One GPU and `UNSLOTH_FSDP2=1` train fine.

## Cause

Under DDP, Unsloth checkpoints VLMs non-reentrantly (`vision.py`,
`vlm_gradient_checkpointing_reentrant()`), and every decoder block is
compiled as one region (`_block_compile.py`). When a block is called
inside `DDP.forward`, dynamo hands its graph to DDPOptimizer
(`torch._dynamo.config.optimize_ddp`), which splits it at gradient
bucket boundaries. The checkpoint recompute runs from backward, outside
`DDP.forward`, where dynamo compiles without DDPOptimizer. A block
compiled whole in the recompute does not save the same tensors as the
split forward, so the checkpoint's count check fails.

Evidence on one Kaggle T4x2 kernel, same script, same install: default
fails as above; `torch._dynamo.config.optimize_ddp = False` before
`trainer.train()` trains (losses 3.3576, 3.7844, 3.9564);
`UNSLOTH_BLOCK_COMPILE=0` also trains. Forcing non-reentrant
checkpointing in a single process trains, so the split is the DDP-only
ingredient.

## Fix

`_block_compile.py`: while a DDP module is active and `optimize_ddp` is
on, the block call runs under `torch._dynamo.config.patch(optimize_ddp =
False)`. Each block is already its own compiled region, so its gradients
still reach DDP's buckets block by block. Nothing changes for a single
process, FSDP2, a user's own `torch.compile` of the DDP module, or the
global setting.

## Tests

`tests/python/test_block_compile_ddp_no_split.py`: two CPU gloo ranks, a
Llama with layers above DDP's 1 MB first bucket, block compile
installed, non-reentrant checkpointing, DDP with
`find_unused_parameters=True` and `bucket_cap_mb=1`. It counts
DDPOptimizer calls on decoder block graphs, checks every layer ran its
compiled region and that both ranks hold the same gradients.

| tree | result |
|---|---|
| main before this change (unslothai#15324 head 31c6353) | fails: one
DDPOptimizer split per block graph (`[70]`) |
| this branch | passes (torch 2.13.0 and 2.10.0) |

`tests/test_block_compile.py`: same results as on unslothai#15324 (43 passed, 6
skipped; `test_sm_count_is_read_outside_the_trace` fails on both trees).

## Notebook runs (Kaggle T4x2, torch 2.9.0, transformers 4.57.6, 3
steps)

| notebook | mode | unslothai#15324 head | this branch |
|---|---|---|---|
| Deepseek_OCR_(3B) | single GPU | trains | trains (first two losses
equal to main, third within 1e-3; main against itself varies by 3e-4) |
| Deepseek_OCR_(3B) | DDP 2 ranks | CheckpointError 50 vs 49 | trains, 3
steps |
| Deepseek_OCR_(3B) | FSDP2 2 ranks | trains | trains |
| Llasa_TTS_(1B), Whisper, Sesame_CSM_(1B), Spark_TTS_(0_5B),
bert_classification | DDP 2 ranks | trains | trains (Llasa, CSM, Spark
losses bitwise equal to unslothai#15324; Whisper within 4e-4; bert's notebook
split is unseeded) |

## Not fixed here

- DeepSeek-OCR-2 under DDP still fails after this change, now with
`Recomputed values for the following tensors have different metadata` (a
`[2, 287, 10, 128]` tensor saved, `[2, 10, 287, 128]` recomputed). It
reproduces in one process when non-reentrant checkpointing is forced,
and `UNSLOTH_BLOCK_COMPILE=0` trains, so it is a block compile plus
non-reentrant checkpoint issue of its own. Workaround until then:
`UNSLOTH_BLOCK_COMPILE=0` under torchrun.
- Multi-node and non-T4 GPUs were not run.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
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