Skip to content

Studio: data-parallel DiT LoRA training across GPUs (num_gpus) - #18771

Merged
danielhanchen merged 8 commits into
mainfrom
nov21-train-ddp
Nov 22, 2026
Merged

danielhanchen merged 8 commits into
mainfrom
nov21-train-ddp

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Nov 21, 2026 •

Copy link
Copy Markdown
Member

Studio's DiT LoRA trainer only ever used one GPU, so a second card sat idle during training. This adds an opt-in data-parallel path: set num_gpus and the run trains on that many identical visible CUDA GPUs, one process each. With the default num_gpus=1 nothing changes.

How it works

  • The trainer child is rank 0. It starts ranks 1..N-1 as plain subprocesses (diffusion_ddp.launch), using a TCPStore that listens on 127.0.0.1 only, and NCCL with NCCL_SOCKET_IFNAME=lo unless the user set it. The child is a daemonic multiprocessing process, so it cannot spawn multiprocessing children; plain subprocess.Popen gets the config on stdin.
  • Every rank draws the same global micro-batch from the same seeded streams: sampler order, latent variant picks, noise, timesteps and caption dropout. Each rank then trains its own batch_size slice. So N GPUs at batch b compute exactly the one-GPU run at batch N*b, with the batch split across cards.
  • Without a latent cache, a rank decodes and VAE-encodes only its own images. The skipped images still advance the shared crop / flip stream (from the image header). The posterior sample draws a rank-private generator, so ranks never share one and the shared CUDA stream stays in step.
  • Epoch-based runs count the whole world: 16 images for 1 epoch on 2 GPUs at batch 1 is 8 steps.
  • Resume: before the loop every rank takes rank 0's torch CPU and CUDA generator state (rank 0's saved state is every rank's state, since all ranks draw the same streams). Checkpoints record the GPU count, and a resume at another count is refused like a batch-size change. A bundle from before this counts as 1 GPU.
  • After the micro-steps, one flat fp32 all-reduce averages the LoRA gradients and the step loss, before fp16 unscale and clipping. Compile, the checkpointing budget, OOM reruns and GradScaler all run per rank, unchanged. The replicas stay identical: LoRA init is broadcast once, and an end-of-run checksum is reported.
  • Rank 0 alone emits events, writes checkpoints, previews and the adapter. The other ranks wait at two store gates:
    • until rank 0 has written the conditioning cache, then they read it warm and never load the text encoders;
    • until rank 0 has loaded its base, so the bases load one after another from page cache.
  • Ranks agree on one base precision: the most memory-frugal one any rank's Auto resolved. When the ranks' picks differ (a busier second card), rank 0 warns with every GPU's pick and the base they all train.
  • Stop requests are polled on rank 0 and shared through a 1-element all-reduce per step, so every rank leaves the loop at the same step.
  • A dying rank makes rank 0 emit an error event and exit, instead of hanging in a collective. Ranks exit when their parent goes away.
  • Falls back to one GPU with a warning when:
    • the device is not CUDA;
    • the torch build has no NCCL / RCCL (e.g. Windows);
    • block swap is requested;
    • the cards differ;
    • fewer GPUs are visible than requested (it then trains on the ones it has).
  • train_batch_size is per GPU, and samples_per_second counts the global batch. The complete event gains a multi_gpu block: world_size, allreduce_calls, per-rank steps / peaks / LoRA checksum, params_in_sync.
  • API: DiffusionTrainingStartRequest.num_gpus (1 to 64, default 1). The SDXL and MiniMax-H3 trainers ignore it with a warning.
  • Worker ranks start in the caller's working directory, so relative paths that rank 0 resolved resolve the same way on every rank.

Results (Kaggle 2x T4, fp16 path)

Setup: FLUX.2-klein-base-4B with an nf4 base (the T4 fp16 path), 512 px, LoRA r16, lr 1e-4, 100 steps, tarot set (16 train images, 4 held out). Base is origin/main 8b7cde7. Each arm is a fresh process on the same VM. Held-out MSE uses fixed noise at sigma 0.25 / 0.5 / 0.75.

arm GPUs x batch s/step (median) samples/s held-out MSE @100 mean loss peak alloc per rank GiB
main, 1 GPU 1 x 2 4.591 / 4.588 (A/A) 0.436 0.76449 / 0.76497 0.71843 / 0.71847 9.93
this PR, 1 GPU 1 x 2 4.588 0.436 0.76488 0.71847 9.93
this PR, 1 GPU 1 x 1 2.005 0.499 0.76590 0.71253 9.97
this PR, 2 GPUs, seed 0 2 x 1 2.018 / 2.012 (A/A) 0.991 / 0.994 0.76482 / 0.76488 0.71845 / 0.71849 9.97, 9.97
this PR, 1 GPU, seed 1 1 x 2 4.589 0.436 0.76440 0.72660 9.93
this PR, 2 GPUs, seed 1 2 x 1 2.017 0.991 0.76455 0.72662 9.97, 9.97

Throughput: at the same global batch of 2, two T4s train 2.27x the samples per second of one T4. Against one T4's fastest setting (batch 1), the gain is 1.99x. The all-reduce costs 0.6% per step (2.018 vs 2.005 s).

Parity at the same seed and global batch (2 x 1 vs 1 x 2):

comparison per-step loss diff, mean per-step loss diff, max held-out MSE diff
A/A: main vs main 0.00021 0.0017 0.00047
2 x 1 vs 1 x 2, seed 0 0.00021 0.0015 0.00006
2 x 1 vs 1 x 2, seed 1 0.00020 0.0011 0.00015

Both parity rows sit inside the A/A spread, and the per-step diffs equal what two identical single-GPU runs already show. The seed spread of held-out MSE is 0.00048.

Engagement:

  • 100 all-reduces per 100 steps.
  • Both ranks ran 100 steps.
  • params_in_sync is true in every run.
  • Both cards stayed busy (NVML mean over the whole arm, load included: 63% / 63%).

Follow-up smoke (2x T4, head 08af459):

  • Multi-GPU without a latent cache trains, with 6 all-reduces, replicas in sync and the same per-step losses as the cached run.
  • Every socket the run opened listened on 127.0.0.1 or ::1, sampled every 5 s from /proc/net/tcp{,6} and ss -ltnp.
  • NCCL_SOCKET_IFNAME was lo on every rank.

Resume on 2x T4 (stop-and-save at 8, resume to 15, against two uninterrupted 15-step runs):

  • Max per-step loss diff: 3.5e-4, against 3.9e-4 between the two uninterrupted runs.
  • LoRA max abs diff: 1.5e-3, against 1.7e-3.
  • Held-out MSE at 15: 0.770310 resumed, against 0.770360 / 0.770304 uninterrupted.
  • Resuming that 2-GPU checkpoint on 1 GPU is refused before the model loads: "This checkpoint was trained with a different GPU count (2 vs 1)".
  • With GPU 1 mostly held by another process and base_precision auto, both ranks picked and loaded nf4 and no warning fired (the T4 fp16 path pins nf4).

World 1 is unchanged: this PR at num_gpus=1 sits within main's own A/A, at 4.588 vs 4.591 s/step and the same loss class.

Tests

tests/test_diffusion_ddp.py, CPU, gloo, two processes:

  • the all-reduce averages gradients (a missing grad counts as zeros) and the loss; stop flags and the precision agreement;
  • plan_world fallbacks: CPU, no NCCL, block swap (config and env), mismatched cards, one card, more GPUs requested than visible;
  • num_gpus validation and the API field;
  • the real loop on a tiny Qwen-Image-2.1. Two ranks at batch 1 match one process at batch 2 (allclose adapters and per-step losses). Rank 0 and rank 1 adapters are torch.equal. Rank 1 loaded no conditioners (it read rank 0's cache warm). Rank 1 wrote no output;
  • the same loop without a latent cache, random crops on non-square images: each rank decodes and encodes only its own image per step, and the replicas stay torch.equal. Skipping an image advances the crop / flip stream exactly like loading it (EXIF-rotated image included), and the rank-private posterior generator leaves the shared stream untouched;
  • epoch steps with 1 to 3 GPUs; sync_rng continues rank 0's stream on diverged ranks; a checkpoint resumes only at its GPU count (legacy bundles read as 1 GPU); NCCL_SOCKET_IFNAME defaults to lo and keeps a user's value.

Related suites pass: test_diffusion_gc_budget_replay, test_diffusion_dit_trainer*, test_diffusion_dit_fp16_t4, test_diffusion_xpu_training, test_diffusion_lora_trainer, 253 passed. Against main, every new test is new API (absent on main, passing here). No existing test changes outcome.

Not proven here

  • Only 2 GPUs, only T4s, only the fp16 / nf4 path, and only FLUX.2-klein-base-4B. Not run: bf16 cards, compiled training on 2 GPUs, more than 2 GPUs, other families.
  • No real ROCm / RCCL run: no AMD host here has two cards.
  • Previews while multi-GPU are covered by the code path, not by a GPU run.
  • The precision-agreement warning firing on real GPUs: it needs two bf16-capable cards, since a T4 pins nf4 on every rank.
  • No Auto rule picks num_gpus by itself; it stays opt-in.

One process per GPU: the trainer child is rank 0 and starts the other ranks as
subprocesses. Every rank draws the same global micro-batch and trains its own
slice, and one all-reduce averages the LoRA gradients before clipping, so N
GPUs at batch b train the one-GPU batch N*b run. Rank 0 alone writes events,
checkpoints, previews and the adapter; the others read the conditioning warm
and load the base after rank 0. Falls back to one GPU with a warning off CUDA,
without NCCL, with block swap, or on mismatched cards.
A finished rank waited in destroy_process_group for rank 0, which was still
exporting the adapter, until rank 0 killed it two minutes later. Ranks now
exit directly, and rank 0 leaves its group off-thread with a bound.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 21, 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-21T21:25:49.535841Z 49760d7 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.

…in, RNG sync before the loop

- A TCPStore server given only a port listens on every interface; rank 0 now hands it a socket bound to
  127.0.0.1 (legacy backend, the one that accepts a listening fd on torch 2.6 through 2.14). Also removes the
  free-port close/rebind race.
- launch(): if init_process_group raises, stop the started ranks and the watcher before re-raising.
- sync_rng(): every rank continues rank 0's CPU and device generator before the loop. A resume restored each
  card's generator from rank 0's per-device save, where only card 0 had advanced.
@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: d5bfc30312

ℹ️ 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".

compile_watch = _dynamo_compile_counters() if compiled else None
consecutive_skips = 0
# Data parallel: every rank draws the global batch from the same streams and trains its own slice.
draw_size = batch_size * (ddp.world if ddp is not None else 1)

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 Resolve epoch counts using the effective global batch size

When num_epochs > 0 and multiple GPUs are used, run_dit_lora_training() still resolves train_steps through resolve_train_steps() using only the per-GPU train_batch_size, but this loop now consumes batch_size * ddp.world images per micro-step. For example, 16 images, one epoch, and two GPUs at batch 1 resolve to 16 optimizer steps and consume 32 images instead of 16. This multiplies the requested training duration and stretches the learning-rate schedule. Resolve epoch-based steps using the actual world size after fallbacks, including the bucketed-batch calculation.

Useful? React with 👍 / 👎.

@danielhanchen danielhanchen Nov 21, 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.

Thanks, fixed in 3c3123a: the trainer resolves the GPU count first and counts epochs with the per-GPU batch times the world size; the extra ranks receive the final step count (16 images, 1 epoch, 2 GPUs at batch 1 is 8 steps). Covered by test_epoch_steps_count_the_whole_world.

# Skipped on the final step and when stopping, since the stop path writes one at the exact step.
if (
not stop_now
and (ddp is None or ddp.is_main)

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 Preserve worker RNG states in distributed checkpoints

When resuming a multi-GPU checkpoint, saving only rank 0's existing checkpoint payload does not preserve the workers' active CUDA RNG states. capture_rng_state() in diffusion_checkpoint.py captures generators from the calling process, so its torch_cuda_1 state is rank 0's unused GPU-1 generator, not rank 1's advanced training generator. Every worker subsequently calls restore_resume_state(), which restores states by device index; rank 1 therefore resumes with the wrong noise, latent-sampling, and timestep stream. Gather and save each rank's active RNG state, then restore the corresponding state on that rank, so stop/resume remains a deterministic continuation.

Useful? React with 👍 / 👎.

@danielhanchen danielhanchen Nov 21, 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.

Thanks, fixed in c74404a: sync_rng copies rank 0's torch CPU and current-card CUDA generator states to every rank before the loop. Every rank draws the same global batch and noise from identically seeded streams, so rank 0's saved state is each rank's correct state on resume; 3c3123a documents this at the save site, and a test starts two ranks with diverged generators and checks both continue rank 0's stream.

@danielhanchen

danielhanchen commented Nov 21, 2026 •

Copy link
Copy Markdown
Member Author

The lint reds come from this PR's new studio/backend/core/training/diffusion_ddp.py, not from main:

  • workflow-trigger lint, Repo tests (CPU, rest-2) and the risky-loader step of Source lint all report one new risky loader call site, studio/backend/core/training/diffusion_ddp.py:369 [dynamic-import] __import__. Either replace the __import__ with a plain import / importlib.import_module of a fixed name, or run python scripts/lint_risky_loaders.py --update and replace the new entry's "REVIEW ME" reason in scripts/risky_loaders_baseline.json with why it is safe.

(The Would reformat lines in the Source lint log come from the informational whole-repo format scan and are not what fails the job.)

num_epochs resolved train_steps from the per-GPU train_batch_size, while each micro-step consumes
train_batch_size images on every rank: 16 images, 1 epoch, 2 GPUs at batch 1 ran 16 steps over 32 images.
Plan the world (after its fallbacks) before resolving, and resolve with train_batch_size x world; the
started ranks receive the resolved count. Also note at the save site why rank 0's RNG state is every
rank's on resume.

[skip ci]
@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: 3c3123ab4e

ℹ️ 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 +3501 to +3502
train_steps = resolve_train_steps(
replace(cfg, train_batch_size = max(1, cfg.train_batch_size) * max(1, 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 Include the effective global batch size in resume identity

When a checkpoint is resumed with a different GPU count (including a fallback to one GPU), the resume checks still accept it: identity_for_config() records only the per-GPU train_batch_size and does not record num_gpus or the resolved world size. Consequently, a two-GPU checkpoint at batch 1 can resume on one GPU at batch 1 with its existing optimizer moments and sampler state, despite halving the effective batch size; bucketed sampling also discards the restored pending batches when their length no longer matches. Record and validate the effective global batch size so these runs are not silently treated as matching continuations.

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.

Thanks, fixed in 08af459: checkpoints now record the GPU count, and a resume at a different count is refused before the model loads, like a per-GPU batch size change, so the effective global batch cannot change under restored optimizer and sampler state. Older checkpoints count as 1 GPU. On Kaggle 2x T4 a 1-GPU resume of a 2-GPU checkpoint was refused in 9 s, and a 2-GPU stop-at-8 resume-to-15 run matched an uninterrupted run within the run-to-run noise.

],
stdin = subprocess.PIPE,
env = env_r,
cwd = _backend_dir(),

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 Preserve the caller's working directory for worker ranks

When run_dit_lora_training() is called from outside studio/backend with relative paths, rank 0 resolves them successfully but the worker processes resolve the unchanged configuration against this different working directory. For example, a relative data_dir that rank 0 has already discovered fails discovery in worker_main(), aborting the multi-GPU run; relative local model, cache, and resume paths have the same problem. Preserve the caller's working directory (the backend is already added to PYTHONPATH) or absolutize all filesystem paths before serializing the worker configuration.

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.

Thanks, fixed in 49760d7: worker ranks now start in the caller's working directory (the backend still reaches them through PYTHONPATH), so relative data, model, cache and resume paths resolve as they did on rank 0. Covered by test_worker_ranks_start_in_the_callers_directory.

…he GPU count, NCCL on loopback

Without a latent cache every rank decoded and VAE-encoded the whole global batch. Each rank now
decodes and encodes only its own images; the skipped ones advance the shared crop / flip stream
from the image header, noise and timesteps are drawn for the global batch and sliced, and the
posterior sample draws a rank-private generator so the shared stream stays in step.

Checkpoints record the data-parallel GPU count; a resume at another count (half the global batch
on 1 GPU) is refused like a batch-size change. Bundles from before the field read as 1 GPU.

Single-host ranks default NCCL_SOCKET_IFNAME to lo unless the user set it.
Every rank trains the most memory-frugal base any rank resolved, so a busier second card can
turn rank 0's bf16 into nf4 without a word. Rank 0 now emits a warning naming each GPU's pick
and the base every GPU trains.
@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: 49760d7317

ℹ️ 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".

…and the trainer

A 2-GPU batch-1 bundle is refused at preflight on 1 GPU ("different GPU count (2 vs 1)") and
accepted on 2; the route's world-less identity defers; a pre-field bundle reads as 1 GPU. The
trainer hands preflight_resume the world planned after plan_world's fallbacks.

[skip ci]
@danielhanchen
danielhanchen merged commit 5bab321 into main Nov 22, 2026
@danielhanchen
danielhanchen deleted the nov21-train-ddp branch November 22, 2026 01:59
danielhanchen added a commit that referenced this pull request Nov 22, 2026
…DMD diffusers skip, risky loader lint) (#18824)

## Summary

Four checks are red on `main` itself, so every open PR currently
inherits them in the Backend CI shards and the risky loader lint. Each
was reproduced on a clean `main` checkout before fixing.

| Failing check | Introduced by | Which side was wrong | Fix |
|---|---|---|---|
|
`tests/test_diffusion_rocm_tag_detect.py::test_no_diffusion_or_video_gate_reads_version_hip_directly`
| #18793 (`diffusion_regional_compile.py`) and #18792
(`diffusion_vae_strips.py`) | Code. Both new gates read
`torch.version.hip` directly, which the ROCm tag guard exists to forbid
(a CUDA wheel with a stray `hip` attribute, or a ROCm wheel reporting it
differently, takes the wrong branch). | Route both through the shared
`is_rocm_torch(torch)` helper from `rocm_bf16`. Behaviour on CUDA and
ROCm is unchanged. |
|
`tests/test_h3_quantised_offload.py::test_a_streamed_torchao_render_runs_under_no_grad_and_the_rest_keep_inference_mode`
| #18780 added `draft_ctx` to the denoise `with` | Test. The invariant
(the denoise loop enters `grad_ctx` together with its progress context)
still holds; the test pinned one exact spelling of the `with` line. |
Parse the `with` statements and assert `grad_ctx` and `progress_ctx()`
are entered together, regardless of what other contexts join them.
Verified it still fails when `grad_ctx` is dropped from the statement. |
| `tests/test_video_dmd.py::test_dmd_scheduler_reseeds_per_render`,
`::test_renoise_stream_is_independent_of_the_initial_latent_noise` |
#18779 | Test. `make_dmd_scheduler` builds on a diffusers scheduler, but
these two tests only skipped on missing torch, so they error with `No
module named 'diffusers'` in the shard that runs without diffusers. |
`pytest.importorskip("diffusers")`, matching the existing scheduler test
in the same file. |
| `scripts/lint_risky_loaders.py` (`diffusion_ddp.py:440
[dynamic-import] __import__`) | #18771 | Code. The rank bootstrap
imported two fixed modules through `__import__` in a loop. | Import
`utils.native_tls` and `utils.happy_eyeballs` by name, each in its own
`try`, so a failure in one still does not stop the rank or skip the
other. No baseline entry needed. |

## Testing

- `tests/test_diffusion_rocm_tag_detect.py`,
`tests/test_h3_quantised_offload.py`, `tests/test_video_dmd.py`,
`tests/test_diffusion_ddp.py`, `tests/test_diffusion_training.py`, the
native TLS and happy eyeballs suites, and the regional compile and VAE
strip suites: all pass.
- `tests/test_video_dmd.py` with diffusers blocked from import: 26
passed, 7 skipped (previously 2 errors).
- `python scripts/lint_risky_loaders.py`: all call sites recorded.
- Sabotage: restoring either original `torch.version.hip` read makes the
ROCm tag guard fail; restoring the `__import__` loop makes the risky
loader lint fail.
danielhanchen added a commit that referenced this pull request Nov 22, 2026
… red on main) (#18832)

## Summary

`(Python 3.13, diffusion)` in Backend CI is red on `main` (seen on
#18830, merge base `d165f9f64d`):

```
tests/test_diffusion_dit_fp16_t4.py::test_bf16_card_takes_the_bf16_path[flux.2-klein-cap0] (and the rest of the bf16 grid)
core/training/diffusion_dit_trainer.py:3788: in run_dit_lora_training
core/training/diffusion_checkpoint.py:452: in with_world_size
E   TypeError: replace() should be called on dataclass instances
```

#18771 (data-parallel DiT LoRA training) records the resolved GPU count
on the checkpoint identity right after building it, through
`dataclasses.replace`. That is correct: `identity_for_config` always
returns a `CheckpointIdentity`. The test was wrong: `_route` stubbed
`identity_for_config` to return `None`, so the trainer now raises before
reaching the dtype routing the file is about.

## Fix

Drop the `None` stub and let `_route` build the real identity. It only
hashes the config and the one fake caption pair, so it stays cheap and
the test now follows any further identity rewrites without another stub.

## Testing

- `studio/backend/tests/test_diffusion_dit_fp16_t4.py`: 52 passed (21
failed with the stub, on `main` and on the earlier `923e1a0b44` base).
danielhanchen added a commit that referenced this pull request Nov 22, 2026
…d up front (intermittent diffusion-shard timeout) (#18885)

## Summary

`(Python 3.13, diffusion)` fails intermittently on unrelated PRs with
the same test:

```
studio/backend/tests/test_diffusion_ddp.py::test_all_reduce_averages_grads_and_loss_and_flags
tests/test_diffusion_ddp.py:55: in _spawn
    codes = [p.wait(timeout = timeout) for p in procs]
E   Failed: Timeout (>330.0s) from pytest-timeout.
```

It is the failing test in 3 of the last 6 failed Backend CI runs
(`studio-wan-vae-2frame`, `audio-cpp-accelerator-chosen-install`,
`perf/r37-translate-history-memo`) and on #18851 and #18702.

The test (from #18771) spawns two gloo ranks and joins them through a
`TCPStore` on a port that `_port()` found free by binding and closing a
socket in the parent. The port is only bound for real later, by rank 0
in its own process, after torch has imported. Under xdist another worker
can take that port in the meantime. Rank 0 then fails to bind, rank 1
waits out the store's 300 s timeout, and pytest-timeout kills the test
at 330 s. In the failing logs only one of the spawned pairs ever prints
the gloo "connected to 1 peer ranks" lines.

## Fix

The two spawned ranks rendezvous through a `FileStore` in a fresh temp
directory per spawn (same 300 s store timeout), so there is no port to
race for. `diffusion_ddp`'s gate only uses `store.set` / `store.wait`,
which `FileStore` provides. Production code is unchanged; this is the
test harness only.

## Testing

- `studio/backend/tests/test_diffusion_ddp.py`: 22 passed, including the
gradient all-reduce and the two-rank `train` spawns.
danielhanchen added a commit that referenced this pull request Nov 23, 2026
…t, ROCm budgets, DDP precision, block swap (#18967)

Follow-ups for the Studio diffusion training changes in #18770, #18771,
#18782, #18825 and #18869. There is one commit per fix. Each change is
small and has its own kill switch or opt-in.

## Changes

1. **Auto fp8 below 1.15x free VRAM now checks host RAM first
(#18770).** In the 0.9x-1.15x band the fp8 base loads the dense bf16
transformer on the host and then streams it to the card. The nf4 pick it
replaced loads shard by shard onto the device. Example: on a 32 GB
desktop with a 4090 and FLUX.1-dev, roughly 24 GB of bf16 sat in host
RAM. The band now uses the same host-RAM check as the bf16 block-swap
pick (`_auto_swap_host_ram_ok`: 1.3x dense + 4 GiB, and an unreadable
reading counts as no). If the check fails, Auto picks nf4 as before. The
1.15x-1.5x band is unchanged, because the int8 pick it replaced already
loaded host-first.
2. **Below 1.5x, Auto picks fp8 only for measured families (#18770).**
Both lower bands gave fp8 to every family that was not explicitly
denied. Held-out loss was measured only for Z-Image, FLUX.2 klein and
Wan. A new `_AUTO_FP8_MEASURED` set gates those bands, the same way
`_AUTO_FP8_OVER_BF16` already gates the band above 1.5x. FLUX.1,
FLUX.2-dev, FLUX.3 klein, Krea, LTX and the other families keep their
int8 / nf4 picks until someone measures them.
3. **The fp8 layer now gives `_scaled_mm` a row-major activation and
grad_y.** The fp8 codes keep the input's memory layout, and CUDA
`_scaled_mm` rejects a column-major first operand. The flattened input
and the incoming gradient now get `.contiguous()` before quantising.
This is a no-op when they are already contiguous.
4. **The memory budgets stay off on discrete Windows ROCm cards
(#18825).** On Windows ROCm the budgets see the whole card as free, and
WDDM serves an overflow from host RAM instead of raising. The OOM
step-down therefore never fires. The budgets were measured only on a
unified-memory gfx1151. On a discrete (non-APU) Windows ROCm card,
budgeted checkpointing and the dequant cache now stay off. Detection
uses `is_rocm_torch` and `device_is_integrated`.
`UNSLOTH_DIFFUSION_GC_MODE=auto` and `UNSLOTH_DIFFUSION_DEQUANT_CACHE=1`
opt back in explicitly. APUs, Linux ROCm and CUDA are unchanged.
5. **Multi-GPU runs now check the base precision after conversion
(#18770 / #18782 with #18771).** `agree_precision` fixes one pick for
every rank. The fp8 / W8A8 conversion fallbacks, though, run per rank:
bf16, an nf4 reload, or torchao weight-only int8. After the conversions,
every rank now all_gathers one int64 code for the base it actually
trains. If the codes differ, every rank raises a clear error instead of
all-reducing grads from different base numerics.
6. **Block-swap plans are resized after a failed conversion (#18869).**
The swap plan counts every target Linear as 1-byte codes. A layer whose
conversion fails stays bf16, so the plan under-counted it by 2x. If any
conversion failed, an auto plan is now resized from the actual tensors.
Any extra blocks it needs are added to the first plan, and their codes
move to host RAM.
7. **Removed the dead `diffusion_gc_budget._is_rocm` (#18825).** Nothing
called it, and it checked only `torch.version.hip`.
8. **The int8 / fp8 numerics tests now use an fp64 oracle (#18782).**
The old test checked only cosine similarity. It now bounds the relative
L2 error of forward and grad_x against a float64 dense layer:
- int8: bound 2e-2, measured 0.86e-2 (0.45e-2 on the dense path under 17
rows).
   - fp8: bound 6e-2, measured 3.7e-2.

A second check shows that a 5% weight-scale error breaks the bound while
cosine stays near 1.

## Tests

All on CPU and targeted. Each new test was also run against the merge
base `b1caa38f6f`:

| Item | Test | main | this branch |
|---|---|---|---|
| 1 |
`test_diffusion_fp8_auto_stream.py::test_auto_fp8_below_1_15x_needs_host_ram_for_the_bf16_load`
(low / unreadable host RAM keeps nf4) | fails (fp8) | passes |
| 2 |
`test_diffusion_fp8_auto_stream.py::test_auto_fp8_unmeasured_families_keep_the_previous_pick`
(12 cells) | fails | passes |
| 3 | `test_diffusion_frozen_fp8_layout.py` (column-major x,
column-major grad_y, batch-1 transposed input, under the CUDA layout
contract) | fails ("self must be row_major") | passes, bit-identical to
contiguous |
| 4 | `test_diffusion_gc_budget_rocm_windows.py` (discrete Windows ROCm
off; APU, Linux ROCm and CUDA on; explicit opt-in; kill switches) |
fails | passes |
| 5 | `test_diffusion_ddp_effective_precision.py` (mocked process group
on both ranks, plus a real 2-rank gloo run) | fails | passes |
| 6 |
`test_diffusion_block_swap_lowp.py::test_auto_plan_resized_when_a_conversion_fails`
| fails (6 blocks swapped either way) | passes (11 blocks) |
| 8 | `test_diffusion_frozen_int8.py` fp64 bounds | passes (test-only
change) | passes |

Existing tests whose expectations change with item 2, because unmeasured
families now keep int8 / nf4: `test_pick_auto_precision_policy_table`,
`test_resolve_auto_int8_band_gates_on_torchao`,
`test_pick_auto_precision_fp8_band` and
`test_pick_auto_precision_per_family`.

Every touched module's test file, plus every file that exercises
`_resolve_base_precision`, ran on main and on this branch. The failing
test IDs match, apart from the intended changes listed above.

## GPU check (item 3)

NVIDIA L4 (sm89), torch 2.14.1+cu130, K = N = 3072, T = 1024, with a
batch-1 transposed activation and a transposed grad_y:

| Case | main | this branch |
|---|---|---|
| contiguous | ok | ok, bit-identical to main |
| column-major x | `CUBLAS_STATUS_NOT_SUPPORTED` | ok, `torch.equal` to
contiguous for y and grad_x |
| column-major grad_y | `CUBLAS_STATUS_NOT_SUPPORTED` | ok,
`torch.equal` to contiguous |

The forward relative error against fp64 is 3.69e-2 in both arms.

## Not covered here

- Item 1: host-RAM peak for a real 20+ GB family at about 1.0x free VRAM
(a cgroup-limited Auto run). The gate is conservative: a family with a
hosted fp8 file loads straight to the card, so it could keep fp8 on a
low-RAM host but now gets nf4, the pick it had before #18770.
- Item 4: not run on a discrete Radeon card under Windows. The gate
keeps the pre-#18825 behaviour there.
- Item 5: the real multi-GPU trainer loop. The DDP loop tests skip here
because the installed diffusers has no Qwen-Image-2.1. The collective
itself ran on real gloo with 2 ranks.
- Item 6: the resize path has a CPU test only. A conversion failure is
hard to trigger on a real card.
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