Repository navigation
Stop the CPU fake-train tests from spoofing torch for the whole session - #8259
Merged
danielhanchen merged 1 commit intoAug 9, 2026
Merged
danielhanchen merged 1 commit into
danielhanchen merged 1 commit into
Conversation
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.
Member
Author
|
@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". |
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
The leak
tests/version_compat/test_trl_fake_train_cpu.pymakes the process pretend it has no GPU, and it does so with plain module-level statements:torch.compile = _eager_compiletorch.accelerator.is_available = lambda *a, **k: Falsetorch.cuda.is_current_stream_capturing = lambda *a, **k: False("empty", "zeros", "ones", "full", "tensor", "arange", "randn", ...)that rewrites anydevice = "cuda"request to CPU, plustorch.Tensor.toandtorch.Tensor.cudaNone 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.pydoes the same fortorch.compileandtorch.accelerator.is_available.Evidence
On a GPU box, on current main:
The same test passes when run alone. The giveaway is in the failure output: the tensors print with no
device='cuda:0', sotorch.randn(4, 4, device = "cuda")returned a CPU tensor, the CUDA autocast never applied, and the matmul stayed float32.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 withdevice = "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:
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, sincetests/version_compatsorts 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.pyswapstorch.cudainside a helper and restores it in afinally;tests/test_device_helpers.pybuilds 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(andpatched_sftin the padding-free module) reuse the sameMonkeyPatch, so the re-application of the eagertorch.compileafterimport unsloth, andtorch._dynamo.config.disable, are unwound too.Why this over the alternatives:
pytest-forkedis not a dependency, and bothversion-compat-ci.ymljobs 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.conftest.pyhas already imported unsloth before any of this runs. A module-scoped fixture is therefore in place strictly before the first thing that cares, andpytest.MonkeyPatchremoves 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 byconsolidated-tests-ci.yml), it is deliberately idempotent and one-way, and it is not restorable in practice sinceunsloth_zoo.device_typecaches the spoofed answer permanently at import. It leaks separately, and on this box it is what still makestest_batched_leftpad_generation_gpu.pyfail 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:torch.compile,torch.Tensor.to,torch.Tensor.cudaandtorch.accelerator.is_availableare the same objects as before, and, when a real GPU is present, thattorch.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.tests/version_compatassigns to atorchattribute (orsetattrs one) at import time, so a new module cannot reintroduce this.Both fail on the parent commit and pass here:
Verification
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_compatpasses in full on its own, and the three realtrainer.train()canaries still run the whole loop on CPU. torch 2.6 compatibility is preserved,torch.acceleratoris still reached only underhasattr.