Repository navigation
Studio: data-parallel DiT LoRA training across GPUs (num_gpus) - #18771
Conversation
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.
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. |
…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.
|
@codex review |
There was a problem hiding this comment.
💡 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) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
|
The lint reds come from this PR's new
(The |
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]
|
@codex review |
There was a problem hiding this comment.
💡 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".
| train_steps = resolve_train_steps( | ||
| replace(cfg, train_batch_size = max(1, cfg.train_batch_size) * max(1, world)), |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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(), |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
… rank 0 resolved relative paths [skip ci]
|
@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". |
…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]
…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.
… 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).
…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.
…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.
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_gpusand the run trains on that many identical visible CUDA GPUs, one process each. With the defaultnum_gpus=1nothing changes.How it works
diffusion_ddp.launch), using aTCPStorethat listens on 127.0.0.1 only, and NCCL withNCCL_SOCKET_IFNAME=lounless the user set it. The child is a daemonic multiprocessing process, so it cannot spawn multiprocessing children; plainsubprocess.Popengets the config on stdin.batch_sizeslice. So N GPUs at batch b compute exactly the one-GPU run at batch N*b, with the batch split across cards.train_batch_sizeis per GPU, andsamples_per_secondcounts the global batch. Thecompleteevent gains amulti_gpublock:world_size,allreduce_calls, per-rank steps / peaks / LoRA checksum,params_in_sync.DiffusionTrainingStartRequest.num_gpus(1 to 64, default 1). The SDXL and MiniMax-H3 trainers ignore it with a warning.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.
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):
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:
params_in_syncis true in every run.Follow-up smoke (2x T4, head 08af459):
/proc/net/tcp{,6}andss -ltnp.NCCL_SOCKET_IFNAMEwasloon every rank.Resume on 2x T4 (stop-and-save at 8, resume to 15, against two uninterrupted 15-step runs):
World 1 is unchanged: this PR at
num_gpus=1sits 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:plan_worldfallbacks: CPU, no NCCL, block swap (config and env), mismatched cards, one card, more GPUs requested than visible;num_gpusvalidation and the API field;allcloseadapters and per-step losses). Rank 0 and rank 1 adapters aretorch.equal. Rank 1 loaded no conditioners (it read rank 0's cache warm). Rank 1 wrote no output;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;sync_rngcontinues rank 0's stream on diverged ranks; a checkpoint resumes only at its GPU count (legacy bundles read as 1 GPU);NCCL_SOCKET_IFNAMEdefaults toloand 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
num_gpusby itself; it stays opt-in.