Skip to content

Studio: scale the SDXL loss in fp16 and keep image LoRA training off devices it cannot use - #13278

Merged
danielhanchen merged 4 commits into
mainfrom
studio-diffusion-device-hardening
Oct 13, 2026
Merged

danielhanchen merged 4 commits into
mainfrom
studio-diffusion-device-hardening

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 11, 2026 •

Copy link
Copy Markdown
Member

Refs #10590

Three device-specific problems in image LoRA training, found while checking every training feature across GPU classes.

1. SDXL in fp16 trained on underflowed gradients

SDXL falls back to an fp16 UNet on GPUs without native bf16 (T4 and RTX 20 on Colab and Kaggle, V100, AMD RDNA2) and when fp16 is requested. The LoRA weights are fp32, but the backward pass runs through the fp16 UNet with no loss scaling, so small gradients flush to zero. The trainer now uses torch.amp.GradScaler, enabled only when the UNet is fp16; bf16 and fp32 runs take the exact same path as before (the scaler is a no-op when disabled). An fp16 overflow step is skipped by the scaler: its non-finite grad norm is not reported to the chart and the LR schedule does not advance for it. The scaler state is saved with each checkpoint and restored on resume, so a resumed fp16 run keeps its loss scale instead of restarting at 65536.

Tiny SDXL pipe, 1024 px, 6 steps, same seed, against an fp32 reference:

Run grad norm, steps 1 to 6 vs fp32
fp32 reference 0.00311, 0.00291, 0.00314, 0.00270, 0.00285, 0.00302
fp16, main 0.00325, 0.00390, 0.00423, 0.00386, 0.00391, 0.00421 +34% from step 2, FAIL
fp16, this PR 0.00311, 0.00291, 0.00314, 0.00270, 0.00284, 0.00302 PASS
fp32, this PR identical to the reference PASS

On a real Colab Tesla T4 (sm75, no bf16, so Studio's own pick is fp16), same tiny pipe, against fp32 on the same card:

T4 run grad norm, steps 1 to 3 vs fp32
fp32 reference 0.0029, 0.0030
fp16 auto pick, main 0.0035, 0.0042 FAIL from step 1
fp16 compiled, main 0.0036, 0.0044 FAIL from step 1
fp16 auto pick and compiled, this PR matches fp32, losses 1.1543, 1.1437, 0.0048 identical PASS

On a real AMD Radeon 8060S (gfx1151, ROCm), base vs this PR in the same job, against fp32 on the same card:

gfx1151 run grad norm vs fp32, steps 1 to 6
fp16, main +62.7%, +42.1%, -100% (flushed to 0), +17.7%, +40.1%, +38.6%
fp16, this PR 0.0% at every step, losses identical to fp32
bf16 (the card's default), main and this PR within 0.3%, unchanged by the PR

The T4 also refuses DiT training up front on both main and this PR (bf16 capable GPU required), unchanged.

Losses of every passing run agree to 4 decimals. bf16 differs between main and this PR at the 1e-5 level, which is the same as two runs of main (bf16 GPU kernels are not deterministic run to run).

In isolation on the same UNet, the unscaled fp16 path zeroed 27.6% of the LoRA gradient entries (median cosine to fp32 0.67); with scaling none are zeroed (cosine 0.99999).

2. DiT training on Apple Silicon crashed after evicting the loaded model

The DiT accelerator gate accepted MPS, but the flow trainers resolve their device to CUDA, then XPU, else CPU, so on a Mac the run trains on the CPU, and diffusers' bitsandbytes quantizer refuses a CPU device_map for the 4-bit base. The start therefore evicted the resident Images pipeline, downloaded the text encoders, and only then failed in the child. The gate now accepts exactly the accelerators the trainers use (CUDA, which includes ROCm, and XPU) and refuses on MPS-only hosts with a clear message. Nothing that worked before is lost; SDXL training on a Mac is unaffected.

3. SDXL on Intel XPU or Apple MPS silently trained on the CPU

The SDXL trainer only uses CUDA / ROCm; elsewhere it trains in fp32 on the CPU. That stays as is, but a host with an XPU or MPS device it does not use now gets a warning that steps and previews will be slow.

Tests

  • test_diffusion_base_precision.py: MPS alone no longer clears the gate; XPU does.
  • test_diffusion_lora_trainer.py: a stopped CPU run warns when MPS is present and stays quiet on a plain CPU host.
  • test_diffusion_checkpoint_resume.py: the fp16 loss scaler state round trips through the checkpoint.
  • tests/test_diffusion_lora_trainer.py tests/test_diffusion_base_precision.py tests/test_diffusion_xpu_training.py tests/test_diffusion_train_perf.py: 158 passed.

Not proven here: a real RDNA2 card (the gfx1151 run above uses the same fp16 path), Windows ROCm, and a real Mac (the refusal is checked with a spoofed MPS probe).

@danielhanchen danielhanchen self-assigned this Oct 11, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 11, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 11, 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 ⚠️ Failed 2026-10-12T14:52:13.715740Z f527d0e New commits
ℹ️ 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: be568533da

ℹ️ 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 665 to 667
scaler.step(optimizer)
scaler.update()
lr_sched.step()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Keep the scheduler stationary when scaling skips an update

When fp16 gradients overflow, scaler.step(optimizer) deliberately skips the optimizer update, but the unconditional lr_sched.step() still advances warmup/decay and the loop records the iteration as completed. On precisely the unstable fp16 runs this change targets, checkpoints and final progress can therefore claim N steps while the weights received fewer updates and later updates used an LR schedule ahead of the optimizer. Detect whether the scale decreased and avoid advancing optimizer-step-dependent state when the update was skipped.

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 7996d43: the LR schedule only steps when the scaler did not back off (an overflow-skipped update).

lora_params = [p for p in unet.parameters() if p.requires_grad]
optimizer = _make_lora_optimizer(lora_params, cfg.learning_rate)
# A frozen fp16 UNet (pre-Ampere / RDNA2 fallback) underflows the LoRA gradients without loss scaling.
scaler = torch.amp.GradScaler("cuda", enabled = weight_dtype is torch.float16)

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 Persist the dynamic loss-scaler state in resume checkpoints

For an fp16 resume after the scaler has adapted, this newly constructed scaler always restarts at its initial scale and growth tracker because _save_checkpoint and restore_resume_state only persist the model, optimizer, scheduler, sampler, and RNG state. A resumed run can consequently repeat overflows that the original run had already backed off from, or grow the scale at a different point, so it is not a faithful continuation despite restoring the other training state. Save and restore scaler.state_dict() with the checkpoint.

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 7996d43: the scaler state rides in the checkpoint's progress block and is restored on resume; older bundles start a fresh scale.


# A Mac (MPS present, SDXL trains on the CPU) is told why the run is slow; a CPU-only host is not.
assert len(warnings_for(True)) == 1
assert warnings_for(False) == []

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 Force XPU unavailable in the CPU-only warning test

On an XPU-enabled test host, warnings_for(False) still emits the warning because production checks resolve_train_device() == "xpu", while this test only forces CUDA and MPS unavailable. The assertion therefore fails on exactly the Intel accelerator environment the new warning covers; stub torch.xpu.is_available() to False before testing the CPU-only case.

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 7996d43: the test now forces XPU unavailable too.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. You're on a roll.

Reviewed commit: 7996d430de

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

Copy link
Copy Markdown
Member Author

Backend CI (a-k) fails on tests/test_diffusion_lora_trainer.py::test_sdxl_warns_when_an_unused_accelerator_leaves_it_on_the_cpu, a test this PR adds, with ModuleNotFoundError: No module named 'diffusers'. Backend CI does not install diffusers, so the test needs pytest.importorskip("diffusers") or a stub for whatever it imports from it, the way the other tests in that file avoid the real package.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. More of your lovely PRs please.

Reviewed commit: b035b495c8

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant