Skip to content

Fixes to XPU offloading during training - #9534

Merged
danielhanchen merged 12 commits into
unslothai:mainfrom
ChowChowSonic:main
Sep 22, 2026
Merged

danielhanchen merged 12 commits into
unslothai:mainfrom
ChowChowSonic:main

Conversation

@ChowChowSonic

@ChowChowSonic ChowChowSonic commented Aug 22, 2026 •

Copy link
Copy Markdown
Contributor

Closes #9524

@danielhanchen

Copy link
Copy Markdown
Member

Confirmed both image trainers still pick device and weight dtype with a CUDA-only rule (diffusion_dit_trainer.py:1874, diffusion_h3_trainer.py:522), so the 4-bit transformer lands off-device on XPU; mark it ready for review when you are happy with it and we will take a look.

@ChowChowSonic
ChowChowSonic marked this pull request as ready for review August 25, 2026 13:25
@ChowChowSonic

Copy link
Copy Markdown
Contributor Author

hey @danielhanchen, thanks for looking into this for me!
I've marked the PR as ready for review since you're reporting the issue as being on the same lines I did.

@ChowChowSonic

Copy link
Copy Markdown
Contributor Author

hey @danielhanchen, sorry for taking so long with this, things have been busy on my end. I would say that the PR is just about ready for a merge whenever you're available to look it over.

Thanks again!

@danielhanchen

Copy link
Copy Markdown
Member

Confirmed the CUDA-only device and dtype rule is still there in diffusion_dit_trainer.py and diffusion_h3_trainer.py, and this puts the 4-bit transformer on the right device via device_map, which matches the failure in #9524. Will get this reviewed.

Follow-up to the XPU device selection in this PR. The selection is right, and
a differential over both trainers confirms an XPU box now binds device="xpu"
with bf16 where it previously bound "cpu" while the bitsandbytes quantizer had
already placed the 4-bit transformer on xpu:0. Four things around it needed
fixing.

The bf16 guard was not a guard. torch.xpu.is_bf16_supported() takes
including_emulation and defaults it to True, then short-circuits before reading
has_bfloat16_conversions, so the bare call answers True for every available
XPU. That is the same emulation trap native_bf16_supported() exists to avoid on
the CUDA side, so an emulation-only XPU was accepted into a bf16-throughout
loop. native_bf16_supported_xpu() now asks for the native answer explicitly and
falls back to the no-argument form on a torch that predates the parameter.

The DiT trainer never got the empty_cache mirror the H3 trainer got. Both
sites sit immediately before the multi-GB transformer load, one after the text
encoders are freed and one after the VAE, so on an XPU box that memory stayed
resident for the load that follows. Both boundaries now clear the selected
accelerator.

An uninitialised XPU driver killed the run. torch.xpu.is_available() raising
propagated out of the trainer, where the same probe in
dit_accelerator_missing_reason is guarded per accelerator. The selection moves
into a shared resolve_train_device() that guards each probe and keeps CUDA
first, so a box carrying both trains where it always did.

A bf16 XPU run recorded its precision as "no". effective_mixed_precision still
keyed the flow families on torch.cuda.is_available() while the loops bind bf16
on any accelerator, so identity_for_config mislabelled every XPU checkpoint and
a later resume could be refused as a precision mismatch. It now resolves the
device the same way the loops do.

tests/test_diffusion_xpu_training.py covers the decision table with a bare fake
torch.xpu that carries only the attributes each case names, so a missing-API
case cannot pass on an auto-created attribute. Reverting any one of the four
fixes fails it. CPU-only, no Intel hardware required.

Verified on an NVIDIA host: a real bnb-nf4 load plus LoRA attach plus one
optimizer step is unchanged against this PR's parent on parameter and
quant-state placement, dtypes, load and step peak memory, and loss to the last
digit. The XPU kernels themselves remain unverified here; no Intel device is
reachable from CI or this host.
Comment-only. Deletes the four docstrings that restated their own code or
their test's name, drops the section banners, and collapses the remaining
multi-line rationales to one line each, keeping every load-bearing fact: the
is_bf16_supported emulation short-circuit, why the fake torch.xpu must stay a
bare namespace, why the decision is read at the _assert_trusted_base_model cut,
and the identity_for_config resume invariant.

test_diffusion_xpu_training.py 55 comment lines to 31 (26.7 to 16.8 percent).
AST-verified comments, docstrings and whitespace only; 19 tests still pass.
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 22, 2026
…preflight

Two gaps the XPU device selection opened, neither reachable before it.

capture_rng_state and restore_rng_state handled the CPU and CUDA generators
only, but both flow loops draw their per-step noise with randn_like on the
TRAINING device (diffusion_dit_trainer.py:2248), so an XPU run's noise stream
lives in the XPU generator. A resumed run silently continued from a fresh seed.
Mirrors the CUDA block, including its all-or-nothing capture and its per-device
restore; the XPU generator API is a 1:1 mapping of the CUDA one.

bf16_unsupported_reason checked CUDA alone while dit_accelerator_missing_reason
accepts any available XPU, so the start route admitted an emulation-only XPU,
evicted the user's resident models, and only then hit the trainer's own guard.
That ordering is the whole reason this preflight exists.

The probe is tri-state rather than boolean. get_device_properties() raises when
no device is really there, and collapsing that to unsupported made the preflight
refuse nf4 on any host whose XPU cannot be interrogated: a probe failing CLOSED,
caught by test_training_precision_preflight_error. Only a definite no rejects
before eviction; an undeterminable capability is left to the child, which runs
on the device and can ask properly.

Full diffusion selection: 33 failures, all 33 present on main with the same
selection, zero introduced. Reverting either fix or the fail-open rule fails the
new tests.
Recording bf16 for an XPU flow run, two commits ago, removed the accidental
barrier that used to stop a CUDA checkpoint resuming on an XPU box: the two
precisions now match and nothing else in CheckpointIdentity distinguishes the
backends. The restore then looks for torch_xpu_* keys in a bundle holding only
torch_cuda_* ones, finds none, and returns quietly, so the destination device
generator stays freshly seeded and every later latent and noise draw differs
while the resume reports success. Measured: zero set_rng_state calls, no error.

capture_rng_state now records which accelerator its device tensors came from,
and _assert_required_state refuses a known mismatch before teardown, alongside
the missing-stream checks already there for the same reason one level up.

Deliberately not a CheckpointIdentity field: adding one changes the identity of
every checkpoint ever written and would break resumes that work today. A bundle
predating this carries no accelerator key and still resumes, since an unknown
backend is not a mismatch.

Diffusion plus checkpoint selection: 39 failures, all 39 present on main with
the same selection, zero introduced.
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 22, 2026
Comment-only, the closing pass. Collapses the cross-backend resume note and the
tri-state probe docstring, keeping both load-bearing facts: that nothing else
distinguishes the backends because the identity records bf16 for each, and that
an unprobeable XPU must not fail closed. AST-verified comments only.
@danielhanchen

Copy link
Copy Markdown
Member

Review record for #9534, carried over from the mirror it was reviewed on: danielhanchen/unsloth-staging-review#55.

Findings are quoted as posted and attributed to the account that posted them. The reactions shown are the triage recorded on the mirror; none were re-applied here. Commits are named as the mirror's, with this PR's equivalent where one was found.

Round 1 — reviewed mirror 07168bf6a (no equivalent commit found on this PR)

chatgpt-codex-connector[bot] on studio/backend/core/training/diffusion_train_common.py (on the mirror)

@@ -644,6 +645,55 @@ def native_bf16_supported() -> bool:
         return False
 
 
+def resolve_train_device() -> str:
+    """The device a flow-matching trainer will actually run on: CUDA first, then Intel XPU, else
+    CPU. CUDA keeps priority so a box carrying both trains where it always did.
+
+    Every probe is guarded individually, the same way ``dit_accelerator_missing_reason`` guards
+    them: a torch build that exposes an accelerator module whose ``is_available()`` raises (an
+    uninitialised driver) must fall through to the next candidate, not kill the run. Shared so the
+    two flow trainers and the precision the run RECORDS cannot disagree about the answer."""
+    import torch  # noqa: PLC0415 -- keep the import list light for the training subprocess
+
+    def _probe(module) -> bool:
+        try:
+            fn = getattr(module, "is_available", None)
+            return bool(fn()) if callable(fn) else False
+        except Exception:  # noqa: BLE001 -- probe failure -> this accelerator is not usable
+            return False
+
+    if _probe(getattr(torch, "cuda", None)):
+        return "cuda"
+    if _probe(getattr(torch, "xpu", None)):
+        return "xpu"

P1 Badge Save and restore XPU RNG state for resumable runs

When an XPU DiT run is checkpointed and resumed, this new branch executes training on XPU, but capture_rng_state and restore_rng_state in diffusion_checkpoint.py only handle CPU and CUDA generators. The loop draws latent samples and training noise with torch.randn_like on the XPU, so a resumed run silently continues from a different random stream than an uninterrupted run, undermining reproducibility and changing results. Capture and restore each XPU generator just as the checkpoint code does for CUDA.

Useful? React with 👍 / 👎.

Accepted on the mirror

Reply from shimmyshimmer:

Confirmed and fixed in 7603729. capture_rng_state saved torch_cpu plus per-device torch_cuda_i only, and both flow loops draw their per-step noise with randn_like on the training device (diffusion_dit_trainer.py:2248, and _sample_cached_latents at :1743), so on XPU that stream lives in the XPU generator and a resume restarted it from a fresh seed. Mirrored the CUDA block, keeping its all-or-nothing capture and its per-device restore rather than set_rng_state_all, for the reason the existing comment gives. The XPU generator frontend is documented as a 1:1 mapping of the CUDA one (https://docs.pytorch.org/docs/stable/generated/torch.xpu.get_rng_state_all.html, https://docs.pytorch.org/docs/stable/generated/torch.xpu.set_rng_state_all.html). Pinned by test_an_xpu_run_captures_and_restores_its_own_noise_generator, which fails if the capture branch is removed.

chatgpt-codex-connector[bot] on studio/backend/core/training/diffusion_dit_trainer.py (on the mirror)

@@ -1853,15 +1856,23 @@ def _check_stop() -> bool:
             save_on_stop = False
         return True
 
-    device = "cuda" if torch.cuda.is_available() else "cpu"
+    device = resolve_train_device()
+    # The flow-matching + 4-bit path is bf16 throughout (fp32 on a CPU-only box, to keep import/unit tests
+    # architecture-agnostic).
     # Fail fast on pre-Ampere CUDA, gating on NATIVE bf16 (capability major >= 8), since is_bf16_supported() counts
-    # emulation.
+    # emulation. An XPU device without native bf16 is refused the same way, via the XPU helper that asks for the
+    # native answer explicitly.
     if device == "cuda" and not native_bf16_supported():
         raise ValueError(
             "This trainer requires a bfloat16-capable GPU (Ampere or newer); "
             "this CUDA device does not support bf16."
         )
-    weight_dtype = torch.bfloat16 if device == "cuda" else torch.float32
+    if device == "xpu" and not native_bf16_supported_xpu():
+        raise ValueError(
+            "This trainer requires a bfloat16-capable GPU; this XPU device does not "
+            "support bf16 natively."
+        )

P2 Badge Mirror the XPU BF16 check in the parent preflight

On an available XPU that lacks native BF16, this new child-side guard rejects the run, but training_precision_preflight_error still reaches bf16_unsupported_reason, which checks only CUDA, while dit_accelerator_missing_reason accepts any available XPU. Consequently the start route accepts the request and evicts resident models before the child immediately fails. Apply native_bf16_supported_xpu() in the shared preflight so this configuration is rejected before teardown.

Useful? React with 👍 / 👎.

Accepted on the mirror

Reply from shimmyshimmer:

Confirmed and fixed in 7603729. routes/training.py:3042 says it outright: the child-side checks fire after eviction, which is what this preflight exists to prevent. bf16_unsupported_reason gated on torch.cuda.is_available() while dit_accelerator_missing_reason admits any available XPU, so the route accepted the start, tore down the resident models, and only then hit the new guard.

One correction to the shape of the fix. Applying native_bf16_supported_xpu() directly in the preflight is wrong: torch.xpu.is_bf16_supported(including_emulation=False) reads get_device_properties(), which raises when no device is really there, so an unprobeable XPU collapsed to unsupported and the preflight refused nf4 on hosts that train fine. Your own suite caught it, test_diffusion_base_precision.py::test_training_precision_preflight_error, which pins that a non-CUDA accelerator still passes for nf4 and auto. The probe is now tri-state: only a definite no rejects before eviction, an undeterminable capability is left to the child, which runs on the device and can ask properly. The child keeps the strict reading, matching native_bf16_supported on the CUDA side.

Round 2 — reviewed mirror b96582cd4 (no equivalent commit found on this PR)

chatgpt-codex-connector[bot] (on the mirror)

Codex Review: Didn't find any major issues. Swish!

Reviewed commit: b96582cd48

No triage reaction was recorded on the mirror

Round 3 — reviewed mirror b34abb48b (no equivalent commit found on this PR)

chatgpt-codex-connector[bot] on studio/backend/core/training/diffusion_checkpoint.py (on the mirror)

@@ -685,10 +693,28 @@ def restore_rng_state(
                 if state is None:
                     continue
                 torch.cuda.set_rng_state(state.cpu().to(torch.uint8), i)
+        elif _xpu_available():
+            # Per device for the same reason as CUDA above: set_rng_state_all needs one state per visible device.
+            for i in range(torch.xpu.device_count()):
+                state = tensors.get(f"torch_xpu_{i}")
+                if state is None:
+                    continue

P2 Badge Reject resumes across CUDA and XPU backends

When a checkpoint is moved between CUDA and XPU hosts, effective_mixed_precision records both runs as bf16, so the identity preflight accepts the resume, but this branch only looks for torch_xpu_* keys while a CUDA checkpoint contains only torch_cuda_* keys (and the reverse direction has the symmetric problem). Although the new XPU keys fix same-backend resume, a cross-backend resume therefore silently leaves the destination generator freshly seeded, changing every subsequent latent/noise draw while reporting a successful resume; record the accelerator backend in the checkpoint identity or explicitly reject this transition.

Useful? React with 👍 / 👎.

Accepted on the mirror

Reply from shimmyshimmer:

Confirmed and fixed in 9a9930e. Reproduced it rather than reasoned about it: capture on this CUDA box yields tensor keys ['torch_cpu', 'torch_cuda_0'], and restoring that bundle with the host spoofed to XPU makes zero xpu.set_rng_state calls and raises nothing. You are also right about the cause being mine: recording bf16 for XPU two commits earlier removed the accidental barrier, since CheckpointIdentity carries no backend and the precisions now match.

Fixed at the preflight rather than in the identity. capture_rng_state records which accelerator its device tensors came from, and _assert_required_state refuses a known mismatch before teardown, next to the missing-stream checks that exist for the same reason one level up. Adding a CheckpointIdentity field, the other option you offered, would change the identity of every checkpoint ever written and break resumes that work today; a bundle predating this carries no accelerator key and still resumes, because an unknown backend is not a mismatch.

Pinned by test_a_checkpoint_cannot_silently_resume_across_accelerator_backends, which covers all three: same backend accepted, known mismatch refused, legacy bundle still accepted. Removing either the preflight check or the capture field fails it.

Round 4 — reviewed mirror 758cbcf04 (no equivalent commit found on this PR)

chatgpt-codex-connector[bot] (on the mirror)

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

Reviewed commit: 758cbcf04c

No triage reaction was recorded on the mirror

Verdict

The round converged at mirror 758cbcf04 (no equivalent commit found on this PR).

This is the review as it stood at that commit. Anything pushed to this PR afterwards was not part of it.

@danielhanchen
danielhanchen merged commit fac17ac into unslothai:main Sep 22, 2026
1 check was pending
danielhanchen added a commit that referenced this pull request Sep 22, 2026
#11450 landed on main as one squashed commit, so GitHub retargeted this PR to
main and the merge no longer recognised the base commits this branch already
carried. Three conflicts, all of the same shape: this branch adds a block where
main has none, so HEAD wins in each. The rest of import_fixes.py auto merged,
which matters because main moved on separately, and the resolution keeps that
work: nothing in main's copy of any of the three files is missing here.

The part the merge got wrong on its own: main carries the quant_state check at
_gpu_init.py:110 with its `del` at 123, and this branch moved the call below
the repair with its own `del`. Auto merge kept both, which is not merely the
duplicate warning #11452 already fixed once, it is a NameError on `import
unsloth`, since the second `del` deletes a name the first already removed.
`test_the_check_is_called_once_and_after_the_repair` catches the duplicate call
that causes it. Resolved to one call, after the repair, and one `del`.

Verified after resolving: no duplicate top-level definitions, 106 passed and 4
skipped across the three suites, and 24 passed with 1 skipped in a venv holding
only pytest and packaging.

test_formatter_fixed_point reports studio/backend/tests/test_diffusion_xpu_training.py
and tests/test_omni_auto_class_resolution.py as not fixed points. Both arrived
from main today, in #9534 and #11467, and the same test fails on main itself at
b7aca55, so they are pre-existing and not touched here.
shaojun pushed a commit to shaojun/unsloth that referenced this pull request Sep 29, 2026
* Fixes to XPU offloading during training

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Fixed related issue of cache not being cleared on XPU

* Studio: harden the XPU training path for the DiT and H3 trainers

Follow-up to the XPU device selection in this PR. The selection is right, and
a differential over both trainers confirms an XPU box now binds device="xpu"
with bf16 where it previously bound "cpu" while the bitsandbytes quantizer had
already placed the 4-bit transformer on xpu:0. Four things around it needed
fixing.

The bf16 guard was not a guard. torch.xpu.is_bf16_supported() takes
including_emulation and defaults it to True, then short-circuits before reading
has_bfloat16_conversions, so the bare call answers True for every available
XPU. That is the same emulation trap native_bf16_supported() exists to avoid on
the CUDA side, so an emulation-only XPU was accepted into a bf16-throughout
loop. native_bf16_supported_xpu() now asks for the native answer explicitly and
falls back to the no-argument form on a torch that predates the parameter.

The DiT trainer never got the empty_cache mirror the H3 trainer got. Both
sites sit immediately before the multi-GB transformer load, one after the text
encoders are freed and one after the VAE, so on an XPU box that memory stayed
resident for the load that follows. Both boundaries now clear the selected
accelerator.

An uninitialised XPU driver killed the run. torch.xpu.is_available() raising
propagated out of the trainer, where the same probe in
dit_accelerator_missing_reason is guarded per accelerator. The selection moves
into a shared resolve_train_device() that guards each probe and keeps CUDA
first, so a box carrying both trains where it always did.

A bf16 XPU run recorded its precision as "no". effective_mixed_precision still
keyed the flow families on torch.cuda.is_available() while the loops bind bf16
on any accelerator, so identity_for_config mislabelled every XPU checkpoint and
a later resume could be refused as a precision mismatch. It now resolves the
device the same way the loops do.

tests/test_diffusion_xpu_training.py covers the decision table with a bare fake
torch.xpu that carries only the attributes each case names, so a missing-API
case cannot pass on an auto-created attribute. Reverting any one of the four
fixes fails it. CPU-only, no Intel hardware required.

Verified on an NVIDIA host: a real bnb-nf4 load plus LoRA attach plus one
optimizer step is unchanged against this PR's parent on parameter and
quant-state placement, dtypes, load and step peak memory, and loss to the last
digit. The XPU kernels themselves remain unverified here; no Intel device is
reachable from CI or this host.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Studio: tighten the comments added by the XPU training work

Comment-only. Deletes the four docstrings that restated their own code or
their test's name, drops the section banners, and collapses the remaining
multi-line rationales to one line each, keeping every load-bearing fact: the
is_bf16_supported emulation short-circuit, why the fake torch.xpu must stay a
bare namespace, why the decision is read at the _assert_trusted_base_model cut,
and the identity_for_config resume invariant.

test_diffusion_xpu_training.py 55 comment lines to 31 (26.7 to 16.8 percent).
AST-verified comments, docstrings and whitespace only; 19 tests still pass.

* Studio: carry the XPU training path into resume and the pre-eviction preflight

Two gaps the XPU device selection opened, neither reachable before it.

capture_rng_state and restore_rng_state handled the CPU and CUDA generators
only, but both flow loops draw their per-step noise with randn_like on the
TRAINING device (diffusion_dit_trainer.py:2248), so an XPU run's noise stream
lives in the XPU generator. A resumed run silently continued from a fresh seed.
Mirrors the CUDA block, including its all-or-nothing capture and its per-device
restore; the XPU generator API is a 1:1 mapping of the CUDA one.

bf16_unsupported_reason checked CUDA alone while dit_accelerator_missing_reason
accepts any available XPU, so the start route admitted an emulation-only XPU,
evicted the user's resident models, and only then hit the trainer's own guard.
That ordering is the whole reason this preflight exists.

The probe is tri-state rather than boolean. get_device_properties() raises when
no device is really there, and collapsing that to unsupported made the preflight
refuse nf4 on any host whose XPU cannot be interrogated: a probe failing CLOSED,
caught by test_training_precision_preflight_error. Only a definite no rejects
before eviction; an undeterminable capability is left to the child, which runs
on the device and can ask properly.

Full diffusion selection: 33 failures, all 33 present on main with the same
selection, zero introduced. Reverting either fix or the fail-open rule fails the
new tests.

* Studio: refuse a resume whose RNG state belongs to another accelerator

Recording bf16 for an XPU flow run, two commits ago, removed the accidental
barrier that used to stop a CUDA checkpoint resuming on an XPU box: the two
precisions now match and nothing else in CheckpointIdentity distinguishes the
backends. The restore then looks for torch_xpu_* keys in a bundle holding only
torch_cuda_* ones, finds none, and returns quietly, so the destination device
generator stays freshly seeded and every later latent and noise draw differs
while the resume reports success. Measured: zero set_rng_state calls, no error.

capture_rng_state now records which accelerator its device tensors came from,
and _assert_required_state refuses a known mismatch before teardown, alongside
the missing-stream checks already there for the same reason one level up.

Deliberately not a CheckpointIdentity field: adding one changes the identity of
every checkpoint ever written and would break resumes that work today. A bundle
predating this carries no accelerator key and still resumes, since an unknown
backend is not a mismatch.

Diffusion plus checkpoint selection: 39 failures, all 39 present on main with
the same selection, zero introduced.

* Studio: tighten the comments added during review

Comment-only, the closing pass. Collapses the cross-backend resume note and the
tri-state probe docstring, keeping both load-bearing facts: that nothing else
distinguishes the backends because the identity records bf16 for each, and that
an unprobeable XPU must not fail closed. AST-verified comments only.

---------

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

[Bug] qLora training on XPU Fails due to tensor (off)loading issue

2 participants