Skip to content

DDP: VLM tower sync, Gemma 4 tower LoRA and DPO ref adapter default to find_unused False, bind cuda:LOCAL_RANK at import - #17867

Merged
danielhanchen merged 7 commits into
mainfrom
ddp1-fix
Nov 15, 2026
Merged

danielhanchen merged 7 commits into
mainfrom
ddp1-fix

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

DDP now works for full finetuning and tower LoRA on VLMs, for DPO's reference adapter, and without wasting GPU 0 memory. No user code changes are needed.

What failed on main (tiny Gemma 4 / Qwen2.5-VL, CPU gloo, B200 and Kaggle 2xT4 NCCL)

Case main
Gemma 4 full finetuning, text-only batches Expected to have finished reduction
Gemma 4 full finetuning, mixed text / image batches hangs until timeout
Gemma 4 LoRA with finetune_vision_layers / finetune_audio_layers marked ready twice, then hangs
DPO LoRA (TRL adds a frozen ref adapter) falls back to find_unused_parameters=True, crashes on NCCL
Every rank other than 0 opens a CUDA context on GPU 0 at import unsloth (818 MiB per rank on B200, 150 MiB on T4)

find_unused_parameters=True fails under reentrant checkpointing (marked ready twice). static_graph=True fails as soon as batches alternate between text and images. Neither is a usable default.

Fixes

Commit Change
Tower sync With find_unused_parameters=False, trainable vision / audio tower weights stay out of DDP. They are all-reduced after each synced backward, and a weight no rank used keeps grad=None.
Gemma 4 tower LoRA Defaults find_unused_parameters to False, with the towers handled as above.
Frozen second adapter A frozen, inactive adapter (TRL DPO's ref copy) no longer forces True. A trainable second adapter still keeps the default.
Device binding import unsloth makes cuda:LOCAL_RANK current on a torchrun rank before anything touches CUDA.

Language-only LoRA has no trainable tower weights, so nothing is installed for it and it stays on find_unused_parameters=False.

Results

2 ranks vs 1 process, same global batch with gradient accumulation halved:

  • B200, exactly equal (loss, grad norm and final weights):
    • Qwen3 and Llama 3.2 LoRA, QLoRA and full finetuning;
    • packing, padding-free and uneven tokens per rank;
    • save at step 2 and resume.
  • B200, within about 6e-6 on grad norm, inside the A/A spread:
    • Gemma 4 full finetuning on text-only, mixed and vision batches;
    • Gemma 4 LoRA with vision layers;
    • Qwen2.5-VL full finetuning and vision LoRA.
  • Kaggle 2xT4 NCCL, equal to one process: Gemma 4 full finetuning (text-only and mixed), Qwen2.5-VL full finetuning, fp16 GradScaler for Qwen3 LoRA and Llama QLoRA, padding-free with uneven tokens, and DPO.
  • Kaggle 2xT4, Gemma 4 vision LoRA: step-1 grad norm differs by 1.7e-4. There is no repeated-run baseline on T4 to judge that.
  • Flip tests (tests/test_ddp_tower_sync.py, tests/test_ddp_find_unused_default.py, tests/test_bind_local_cuda_device.py): fail on main, 64 pass here.

…ynced backward

Full finetuning Gemma 4 / Gemma 3N under DDP (reentrant checkpointing, so find_unused_parameters cannot
run) failed on any text-only batch: the vision / audio towers got no gradient and DDP stalled with
'Expected to have finished reduction in the prior iteration'. When DDP is built without unused-parameter
search, trainable tower weights are now left out of DDP and all-reduced after each synced backward, keeping
grad = None for a weight no rank used, as DDP(find_unused_parameters = True) does.
…arameters to False

The Gemma 4 vision and audio notebooks adapt the towers too (finetune_vision_layers / finetune_audio_layers),
which kept transformers' True for a PeftModel; under the reentrant checkpointing Gemma 4 uses, True crashed on
the first backward ('Expected to mark a variable ready only once'). The tower adapters are now kept out of
DDP and averaged after each synced backward, so False trains.
…arameters False

TRL's DPOTrainer adds a frozen "ref" copy of the policy adapter after Unsloth's trainer init picked False;
the re-decision in Trainer.__init__ then saw two adapters and fell back to transformers' True, and every
DPO LoRA run under DDP crashed on the first backward ('Expected to mark a variable ready only once'). The
rule now looks at the adapter that owns the trainable tensors and is active.
Every torchrun rank imported Unsloth with cuda:0 current, and the first CUDA call during import opened a
context there: each extra rank held one on GPU 0 for the whole run (818 MiB per rank on a B200, 150 MiB on
a T4), so GPU 0 had less memory than its peers. The rank's own card is now made current first.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 15, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-15T20:06:15.822137Z bb67422 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 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: 203aeaf35a

ℹ️ 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 +392 to +395
DistributedDataParallel._set_params_and_buffers_to_ignore_for_model(
model, ignored + [n for n in names if n not in seen]
)
model._unsloth_ddp_tower_params = params

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 Broadcast tower parameters before excluding them from DDP

When tower parameters differ across ranks at initialization—for example, newly initialized tower adapters created with rank-dependent seeds—this exclusion also removes them from DDP's initial parameter broadcast. The replacement only averages gradients, so applying identical updates preserves the initial parameter differences and silently trains different models on each rank. Explicitly synchronize the excluded parameters from the process-group source rank before training; the new test's identical manual_seed(0) on both ranks masks this regression.

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.

Fixed in the latest commit: when the tower sync is installed, the excluded tower weights are broadcast from the group's rank 0, as DDP does for the parameters it owns. The gloo test now perturbs rank 1's tower before training; without the broadcast it fails, with it both ranks match one process.

Comment thread unsloth/models/_ddp_defaults.py Outdated
Comment on lines +429 to +431
flat = torch._utils._flatten_dense_tensors(grads)
dist.all_reduce(flat, group = group)
flat.div_(world)

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 Divide tower gradients before the low-precision all-reduce

For FP16 tower gradients, summing before dividing can overflow even when the correct average is representable: two ranks each contributing 40000 produce an infinite sum instead of an average of 40000. This is especially relevant because this hook runs immediately after backward, before GradScaler unscales the gradients. Unlike DDP's default pre-divided reduction, this can cause otherwise valid steps to be skipped or introduce infinite updates without a scaler. Pre-divide the gradients or accumulate the reduction in a wider dtype.

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.

Fixed in the same commit: the flat tower gradient is divided by the world size before the all-reduce, matching DDP's pre-divided reduction, so fp16 tower gradients no longer overflow when summed.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Chef's kiss.

Reviewed commit: bb67422474

ℹ️ 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 e9eaf82 into main Nov 15, 2026
@danielhanchen
danielhanchen deleted the ddp1-fix branch November 15, 2026 22:36
danielhanchen added a commit that referenced this pull request Nov 16, 2026
…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']
```
Penguinjanator pushed a commit to Penguinjanator/unsloth that referenced this pull request Nov 16, 2026
…on without Triton, kernel and test gates (unslothai#17882)

Backend CI on main has been red since today's merges. Every failure
traces to one commit; this fixes the unsloth side (the gloo-cp shard
also needs unslothai/unsloth-zoo#2542, since CI installs zoo from main).

| CI shard / test | Cause | Fix |
|---|---|---|
| gloo: `test_qwen4exp_parallel_matches_one_process[pp*]`,
`test_pp_splits_streams_and_runs_the_mixer_last`, all of
`test_frozen_table_pp_gloo.py` | unslothai#17785: transformers 5.17 (the CI pin)
names the Qwen4Exp layer type `qwen_sparse_attention`, 5.22 renamed it
`indexed_attention`; pipeline parallel only accepted the new name, so
every rank raised "hybrid layer stacks" | accept both names in
`_PP_HYBRID_FAMILIES` |
| diffusion (Python 3.13): 13 tests in
`test_diffusion_int8_attention_triton_device.py` | unslothai#17855: `_launch`
read `triton.runtime` while `triton` is `None` on that shard | check
`triton is not None` first |
| rest: `test_every_constexpr_line_has_a_comment` | unslothai#17860: 23
uncommented `tl.constexpr` parameters in `large_head_attention.py` |
comments added; `_tma_tile`'s signature split one parameter per line |
| rest: `test_every_launch_requests_fp_fusion` | unslothai#17860: the `_launch`
helper forwards `enable_fp_fusion` from every caller, but the gate did
not know it is a helper | registered like `layernorm.py`'s |
| rest: `test_no_file_is_dropped_or_run_twice` | unslothai#17868:
`tests/test_ddp_push_rank0_gloo.py` matched both the gloo shard and
rest-2's `test_[dimsu]*.py` | renamed
`tests/test_hub_push_rank0_ddp_gloo.py` |
| rest-2: `test_checked_in_file_reads_name_an_encoding` | unslothai#17867:
`read_text()` without an encoding in
`tests/test_bind_local_cuda_device.py` | `encoding = "utf-8"` |
| rest-2:
`test_sentence_transformer_trainer_checks_the_placement_before_the_deferred_compile[*]`
| unslothai#17859: `patch_train_dataloader` assumed every trainer class has
`get_train_dataloader` | skip the patch when the method is missing |
| rest-2:
`test_router_aux_loss_gradient_survives_unsloth_checkpointing[*]` |
unslothai#17873: the gpu-marked test still runs under CI's `-m 'not server and
not e2e'` | `has_real_accelerator()` skip next to the gpu mark |
| studio: `test_no_skip_guard_reads_a_spoofable_accelerator_probe` |
unslothai#17850: `test_block_cudagraphs_side_grad.py` skipped on
`torch.cuda.is_available()`, which the CUDA spoof fakes | skip on
`has_real_cuda()` |

## Tests

In a venv matching CI (Python 3.12, torch 2.10.0+cpu, transformers
5.17.0, TRL 1.15, PEFT 0.21.3, `UNSLOTH_COMPILE_DISABLE=1`, `-m 'not
server and not e2e'`):

- gloo: `test_qwen4exp_parallel_gloo.py` failed on main, 9 / 9 pass
here; `test_frozen_table_pp_gloo.py` 13 / 13.
- rest / rest-2 / studio: the nine affected files had exactly CI's 9
failures on main; 153 passed / 6 skipped here.
- diffusion: with Triton blocked (as on the Python 3.13 shard), the 13
failures pass here; with Triton present everything passes.

The only non-test code changes are the PP layer-type name, the Triton
`None` check and the Sentence Transformers method check;
`large_head_attention.py` changes are comments only.
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