Skip to content

Stop the CPU fake-train tests from spoofing torch for the whole session - #8259

Merged
danielhanchen merged 1 commit into
unslothai:mainfrom
danielhanchen:fix/version-compat-torch-global-leak
Aug 9, 2026
Merged

danielhanchen merged 1 commit into
unslothai:mainfrom
danielhanchen:fix/version-compat-torch-global-leak

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

The leak

tests/version_compat/test_trl_fake_train_cpu.py makes the process pretend it has no GPU, and it does so with plain module-level statements:

  • torch.compile = _eager_compile
  • torch.accelerator.is_available = lambda *a, **k: False
  • torch.cuda.is_current_stream_capturing = lambda *a, **k: False
  • a loop over ("empty", "zeros", "ones", "full", "tensor", "arange", "randn", ...) that rewrites any device = "cuda" request to CPU, plus torch.Tensor.to and torch.Tensor.cuda

None of it is restored. pytest imports every selected file during collection, so merely selecting this file is enough: from that point on the whole process is a fake CPU box. tests/version_compat/test_trl_padding_free_max_length.py does the same for torch.compile and torch.accelerator.is_available.

Evidence

On a GPU box, on current main:

CUDA_VISIBLE_DEVICES=6 python3 -B -m pytest tests/version_compat tests/test_grpo_autocast_per_trainer.py -q -p no:randomly
1 failed, 1691 passed, 213 skipped
FAILED tests/test_grpo_autocast_per_trainer.py::test_an_outer_autocast_is_inherited_rather_than_overridden

The same test passes when run alone. The giveaway is in the failure output: the tensors print with no device='cuda:0', so torch.randn(4, 4, device = "cuda") returned a CPU tensor, the CUDA autocast never applied, and the matmul stayed float32.

E  assert torch.float32 is torch.bfloat16
E   +  where torch.float32 = (tensor([[-0.6225,  1.0247, ...]]) @ tensor([[-0.6225,  1.0247, ...]])).dtype

Why CI never caught it

CI runners have no GPU. torch.cuda.is_available() is False there, every GPU test skips, and the suite stays green. The damage is entirely to local GPU verification, where a test that should fail can pass vacuously.

Blast radius, measured

27 files under tests/ gate on CUDA or allocate with device = "cuda". Note that @pytest.mark.skipif(not torch.cuda.is_available(), ...) is evaluated at collection time, before the leak, so those tests are selected to run and then silently get CPU tensors.

Measured on this box against main, over the GPU-touching files that need no large download:

# the GPU files alone
106 passed, 3 skipped

# the same files with test_trl_fake_train_cpu.py collected first
8 failed, 101 passed, 3 skipped
  tests/test_offload_embedding_hooks.py  (4 tests)
  tests/test_uma_safetensors_load.py     (2 tests)
  tests/utils/test_batched_leftpad_generation_gpu.py
  tests/test_grpo_autocast_per_trainer.py

So it is not one test: it is 8 tests across 4 files in that sample alone, and every one of them was a false pass rather than a hard error until the assertions happened to catch it.

In a plain pytest tests/ run the exposure is smaller, since tests/version_compat sorts near the end of collection. It bites when a subset is run in the order given on the command line, which is exactly how GPU verification is done locally.

Nothing else under tests/ patches torch globally at import time. tests/test_float32_no_fp16_autocast.py swaps torch.cuda inside a helper and restores it in a finally; tests/test_device_helpers.py builds a fake torch module rather than mutating the real one.

The fix

The patches move into module-scoped autouse fixtures driven by pytest.MonkeyPatch.context(), which undoes every one of them at module teardown. _require_stack (and patched_sft in the padding-free module) reuse the same MonkeyPatch, so the re-application of the eager torch.compile after import unsloth, and torch._dynamo.config.disable, are unwound too.

Why this over the alternatives:

  • Process isolation. The strongest guarantee, but the repo has no convention for it: pytest-forked is not a dependency, and both version-compat-ci.yml jobs deliberately run these modules together in one process (the daily sweep runs the whole directory in one). Adding a dependency plus a CI-invocation change to fix a test-hygiene bug is a lot of moving parts, and it would not stop the next module from doing the same thing.
  • Save and restore at import time. No new dependency, but it has to enumerate every patched name by hand, including the whole allocator loop, and the next patch added to the file silently escapes it. It also leaves the spoof in place for anything collected between import and the module's own tests.
  • Confine the patches to the tests that need them. The comments say the spoof has to precede certain imports, so I checked whether that constraint is real: nothing at module scope imports unsloth or trl. Both modules do all of that inside fixtures and test bodies, and conftest.py has already imported unsloth before any of this runs. A module-scoped fixture is therefore in place strictly before the first thing that cares, and pytest.MonkeyPatch removes the enumeration problem because the undo list builds itself.

_zoo_aggressive_cuda_spoof.apply() stays at module scope. It is a shared harness (five modules plus the shims generated by consolidated-tests-ci.yml), it is deliberately idempotent and one-way, and it is not restorable in practice since unsloth_zoo.device_type caches the spoofed answer permanently at import. It leaks separately, and on this box it is what still makes test_batched_leftpad_generation_gpu.py fail after the fake-train module: the spoof reports capability (8, 0) on a B200, so Triton compiles an SM80 kernel and gets "no kernel image is available for execution on the device". That is a distinct mechanism from the one fixed here and is left alone on purpose.

Regression test

tests/version_compat/test_import_leaves_torch_globals_alone.py, in two halves:

  • a subprocess that imports both modules exactly as collection does, then checks torch.compile, torch.Tensor.to, torch.Tensor.cuda and torch.accelerator.is_available are the same objects as before, and, when a real GPU is present, that torch.randn(4, 4, device = "cuda") and .to("cuda") still land on CUDA. It runs on a GPU-less runner too, where the identity checks alone still catch the leak.
  • a static check that no module in tests/version_compat assigns to a torch attribute (or setattrs one) at import time, so a new module cannot reintroduce this.

Both fail on the parent commit and pass here:

# on main, with the new file dropped in
2 failed
E  AssertionError: FAILURES:torch.compile was replaced|torch.Tensor.to was replaced|
   torch.Tensor.cuda was replaced|torch.accelerator.is_available was replaced|
   torch.randn(device = "cuda") returned a CPU tensor|Tensor.to("cuda") returned a CPU tensor
E  AssertionError: patch torch from a fixture instead ...:
   ['test_trl_fake_train_cpu.py:71 torch.compile', ..., 'test_trl_padding_free_max_length.py:56 torch.accelerator.is_available']

# with the fix
2 passed

Verification

pytest tests/version_compat tests/test_grpo_autocast_per_trainer.py   1694 passed, 213 skipped   (was 1 failed, 1691 passed)
pytest tests/version_compat                                           1660 passed, 213 skipped
pytest tests/test_grpo_autocast_per_trainer.py                          34 passed

and the blast-radius sample goes from 8 failed / 101 passed to 1 failed / 108 passed, the remaining one being the separate capability spoof described above.

The fake-CPU environment those tests exist for is unchanged: tests/version_compat passes in full on its own, and the three real trainer.train() canaries still run the whole loop on CPU. torch 2.6 compatibility is preserved, torch.accelerator is still reached only under hasattr.

tests/version_compat/test_trl_fake_train_cpu.py and
test_trl_padding_free_max_length.py replace torch.compile, make
torch.accelerator.is_available answer False, and rewrite every
device = "cuda" allocation to CPU, all at module import time and with no
teardown. pytest imports every selected file during collection, so a GPU
test running later in the same process gets CPU tensors out of
torch.randn(..., device = "cuda"): its CUDA autocast never applies and it
passes without testing anything.

Move the patches into module-scoped autouse fixtures driven by
pytest.MonkeyPatch, which undoes them at module teardown. They still land
before the module imports unsloth and generates a trainer, which is the
only reason they sat at import time.

Add tests/version_compat/test_import_leaves_torch_globals_alone.py: a
subprocess that imports both modules and checks torch.compile,
torch.Tensor.to/.cuda, torch.accelerator.is_available and a real
device = "cuda" allocation, plus a static check that no module in the
directory assigns to a torch attribute at import time.
@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: 86ae3a1842

ℹ️ 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
danielhanchen merged commit 29fa2f7 into unslothai:main Aug 9, 2026
24 of 28 checks passed
danielhanchen added a commit that referenced this pull request Aug 9, 2026
…on (#8259)

tests/version_compat/test_trl_fake_train_cpu.py and
test_trl_padding_free_max_length.py replace torch.compile, make
torch.accelerator.is_available answer False, and rewrite every
device = "cuda" allocation to CPU, all at module import time and with no
teardown. pytest imports every selected file during collection, so a GPU
test running later in the same process gets CPU tensors out of
torch.randn(..., device = "cuda"): its CUDA autocast never applies and it
passes without testing anything.

Move the patches into module-scoped autouse fixtures driven by
pytest.MonkeyPatch, which undoes them at module teardown. They still land
before the module imports unsloth and generates a trainer, which is the
only reason they sat at import time.

Add tests/version_compat/test_import_leaves_torch_globals_alone.py: a
subprocess that imports both modules and checks torch.compile,
torch.Tensor.to/.cuda, torch.accelerator.is_available and a real
device = "cuda" allocation, plus a static check that no module in the
directory assigns to a torch attribute at import time.
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