Skip to content

fix(grpo): autocast with DEVICE_TYPE_TORCH instead of a pinned "cuda" - #11461

Merged
danielhanchen merged 5 commits into
unslothai:mainfrom
li-lizhe:fix/grpo-autocast-device-type
Sep 22, 2026
Merged

danielhanchen merged 5 commits into
unslothai:mainfrom
li-lizhe:fix/grpo-autocast-device-type

Conversation

@li-lizhe

Copy link
Copy Markdown
Contributor

What

GRPO's autocast blocks pin device_type = "cuda", and the generated trainer's preamble in unsloth/models/rl.py imports DEVICE_TYPE but not DEVICE_TYPE_TORCH — the constant that exists precisely for torch.amp.autocast ("HIP fails for autocast ... use CUDA instead") and that llama.py / vision.py already pass.

torch.amp.autocast with a device_type that does not match the accelerator is inert rather than loud (pytorch#165730): it emits

UserWarning: CUDA is not available or torch_xla is imported. Disabling autocast.

and the block becomes a no-op. On Ascend NPU (and Intel XPU) that means GRPO's forward runs in float32 against the bf16/fp16 dtype _unsloth_grpo_autocast latched, so both the memory saving and the numerics the helper was written for silently never apply.

Changes

  • unsloth/models/rl.py — the generated trainer's preamble now also imports DEVICE_TYPE_TORCH (it is already the module the generated cache gets DEVICE_TYPE from).
  • unsloth/models/rl_replacements.py — the 6 live autocast sites now pass DEVICE_TYPE_TORCH: the injected header in grpo_trainer__prepare_inputs, the default of _unsloth_grpo_autocast_kwargs, and the four blocks in grpo_trainer__get_per_token_logps_and_entropies (_pg_run_forward / _pk_hidden / _pk_autocast / _pk_pixels). The unreachable branch in grpo_trainer__get_per_token_logps that already reached for DEVICE_TYPE is kept consistent — DEVICE_TYPE is "hip" on ROCm, which is not an autocast device type, so it would have dropped autocast there too.
  • tests/ — test_grpo_autocast_disabled.py and test_grpo_autocast_per_trainer.py exec the injected snippet in a bare namespace, so they now supply DEVICE_TYPE_TORCH exactly the way the generated trainer's preamble does (the same thing _fast_generate in the latter file already does for the vision snippet). Two regression tests are added in the file's existing style: one asserts no torch.amp.autocast(...) call in rl_replacements.py pins device_type = "cuda", the other asserts the generated trainer's preamble imports the constant.

DEVICE_TYPE_TORCH is "cuda" on CUDA and ROCm, "npu" on Ascend, "xpu" on Intel, "mps" on MLX. On a CPU-only run device_type.py still reports "cuda", so nothing changes for the existing CPU CI path.

Verification

Ascend 910B4 (torch 2.15.0.dev+cpu + torch_npu 2.15.0.dev, torch.npu.is_available() == True), same tensor, same kwargs:

before — pinned device_type = "cuda":

UserWarning: CUDA is not available or torch_xla is imported. Disabling autocast.
torch.is_autocast_enabled("npu") -> False
(x @ x).dtype                   -> torch.float32

after — DEVICE_TYPE_TORCH (resolves to "npu"):

torch.is_autocast_enabled("npu") -> True
(x @ x).dtype                   -> torch.bfloat16

The repo's own suites on that host:
python -m pytest --noconftest -q tests/test_grpo_autocast_disabled.py tests/test_grpo_autocast_per_trainer.py → 50 passed, 1 skipped.
The two new tests are red on the pre-fix source (2 failed, naming all 6 pinned call sites) and green after.

Not tested: an end-to-end GRPOTrainer.train() on NPU — this box is a single-card 910B4 without a GRPO-ready model/tokenizer checkout, so the check above is at the torch.amp level plus the repo's source-level suites. The Intel XPU and MLX paths are untested (no such hardware here); they are handled by the same constant that llama.py and vision.py already use for autocast.

torch.amp.autocast with a device_type that does not match the accelerator is
inert rather than loud (pytorch#165730): it warns "Disabling autocast" and the
block becomes a no-op. GRPO's autocast blocks pinned device_type = "cuda", so
on Ascend NPU and Intel XPU autocast silently dropped and the forward ran in
float32 against the bf16/fp16 dtype _unsloth_grpo_autocast had latched.

The generated trainer's preamble already imports unsloth's device constants,
so hand it DEVICE_TYPE_TORCH -- "cuda" on CUDA and ROCm, "npu" on Ascend,
"xpu" on Intel, "mps" on MLX -- the way llama.py and vision.py already do.
DEVICE_TYPE is not usable here because it stays "hip" on ROCm, which is not a
valid autocast device_type either.

Verified on an Ascend 910B4 (torch 2.15.0.dev + torch_npu 2.15.0.dev):
torch.is_autocast_enabled("npu") is False and x @ x stays float32 before,
True and bfloat16 after. tests/test_grpo_autocast_{disabled,per_trainer}.py:
50 passed, 1 skipped on that host.
@danielhanchen

Copy link
Copy Markdown
Member

Confirmed the autocast sites in unsloth/models/rl_replacements.py still pin device_type to cuda, and DEVICE_TYPE, which is hip on ROCm, at the _get_per_token_logps site, so the latched dtype quietly does nothing off CUDA, and the added DEVICE_TYPE_TORCH import in rl.py's preamble is needed for the injected header to resolve. Will get this reviewed.

@danielhanchen danielhanchen self-assigned this Sep 22, 2026
danielhanchen and others added 2 commits September 22, 2026 10:29
…his branch

The autocast blocks in grpo_trainer__get_per_token_logps_and_entropies now read
DEVICE_TYPE_TORCH, which the generated trainer gets from rl.py's preamble. Three
test files landed on main after this branch was cut and exec the same block in a
bare namespace, so merging left them raising

  NameError: name 'DEVICE_TYPE_TORCH' is not defined

at exec time, 17 failures across test_grpo_padded_raw_logits.py,
test_grpo_packed_raw_logits_nograd.py and test_grpo_hidden_states_signal.py.

Supply the name the way the preamble does, matching what the two autocast suites
in this branch already do. test_block_free_variables_are_all_stubbed derives its
expectation from the block source, so it follows from the same line.
@shimmyshimmer

shimmyshimmer commented Sep 22, 2026 •

Copy link
Copy Markdown
Member

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

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 954a938cb9 (this PR's 20c9f142c)

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

Codex Review: Didn't find any major issues. Keep it up!

Reviewed commit: 954a938cb9

No triage reaction was recorded on the mirror

Verdict

The round converged at mirror 954a938cb9 (this PR's 20c9f142c).

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

Re-pointing the _get_per_token_logps autocast site to DEVICE_TYPE_TORCH left
DEVICE_TYPE imported here and referenced nowhere, which the import-hoist lint
flags as a blocker:

  [BLOCKER] HOISTED-IMPORT-UNUSED 'DEVICE_TYPE' was used before, now unused
  (references re-pointed)

Nothing reads DEVICE_TYPE from this module, and the generated trainer takes it
from the preamble in rl.py, which is unchanged, so the emitted
UnslothGRPOTrainer.py still binds both names.
shimmyshimmer pushed a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Sep 22, 2026
@danielhanchen
danielhanchen merged commit 5f2136a into unslothai:main Sep 22, 2026
30 of 31 checks passed
shaojun pushed a commit to shaojun/unsloth that referenced this pull request Sep 29, 2026
…unslothai#11461)

* fix(grpo): autocast with DEVICE_TYPE_TORCH instead of a pinned "cuda"

torch.amp.autocast with a device_type that does not match the accelerator is
inert rather than loud (pytorch#165730): it warns "Disabling autocast" and the
block becomes a no-op. GRPO's autocast blocks pinned device_type = "cuda", so
on Ascend NPU and Intel XPU autocast silently dropped and the forward ran in
float32 against the bf16/fp16 dtype _unsloth_grpo_autocast had latched.

The generated trainer's preamble already imports unsloth's device constants,
so hand it DEVICE_TYPE_TORCH -- "cuda" on CUDA and ROCm, "npu" on Ascend,
"xpu" on Intel, "mps" on MLX -- the way llama.py and vision.py already do.
DEVICE_TYPE is not usable here because it stays "hip" on ROCm, which is not a
valid autocast device_type either.

Verified on an Ascend 910B4 (torch 2.15.0.dev + torch_npu 2.15.0.dev):
torch.is_autocast_enabled("npu") is False and x @ x stays float32 before,
True and bfloat16 after. tests/test_grpo_autocast_{disabled,per_trainer}.py:
50 passed, 1 skipped on that host.

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

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

* Stub DEVICE_TYPE_TORCH in the three GRPO exec harnesses added since this branch

The autocast blocks in grpo_trainer__get_per_token_logps_and_entropies now read
DEVICE_TYPE_TORCH, which the generated trainer gets from rl.py's preamble. Three
test files landed on main after this branch was cut and exec the same block in a
bare namespace, so merging left them raising

  NameError: name 'DEVICE_TYPE_TORCH' is not defined

at exec time, 17 failures across test_grpo_padded_raw_logits.py,
test_grpo_packed_raw_logits_nograd.py and test_grpo_hidden_states_signal.py.

Supply the name the way the preamble does, matching what the two autocast suites
in this branch already do. test_block_free_variables_are_all_stubbed derives its
expectation from the block source, so it follows from the same line.

* Drop the now-unused DEVICE_TYPE import from rl_replacements

Re-pointing the _get_per_token_logps autocast site to DEVICE_TYPE_TORCH left
DEVICE_TYPE imported here and referenced nowhere, which the import-hoist lint
flags as a blocker:

  [BLOCKER] HOISTED-IMPORT-UNUSED 'DEVICE_TYPE' was used before, now unused
  (references re-pointed)

Nothing reads DEVICE_TYPE from this module, and the generated trainer takes it
from the preamble in rl.py, which is unchanged, so the emitted
UnslothGRPOTrainer.py still binds both names.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Daniel Han <[email protected]>
Co-authored-by: danielhanchen <[email protected]>
This was referenced Oct 8, 2026
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.

3 participants