Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

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

Daniel Han29fa2f7eeb5d
diff --git a/tests/version_compat/test_import_leaves_torch_globals_alone.py b/tests/version_compat/test_import_leaves_torch_globals_alone.py
new file mode 100644
index 00000000000..014036d43ed
--- /dev/null
+++ b/tests/version_compat/test_import_leaves_torch_globals_alone.py
@@ -0,0 +1,136 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team.
+"""The CPU-only fake-train modules must not spoof torch for the whole session.
+
+`test_trl_fake_train_cpu.py` and `test_trl_padding_free_max_length.py` pretend
+this process has no GPU: eager `torch.compile`, `torch.accelerator.is_available`
+answering False, and every `device = "cuda"` allocation rewritten to CPU. Done at
+module scope that outlives the module, and 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 having tested anything. CI runners have no GPU, so
+they skip such tests and never notice; local GPU verification is what breaks.
+
+Both checks below fail against the import-time version of those patches.
+"""
+
+from __future__ import annotations
+
+import ast
+import importlib.util
+import subprocess
+import sys
+from pathlib import Path
+
+import pytest
+
+
+_HERE = Path(__file__).resolve().parent
+_GUARDED = ("test_trl_fake_train_cpu.py", "test_trl_padding_free_max_length.py")
+
+# Imported in a subprocess: the whole point is that importing these modules must
+# not touch torch, and doing it in this process would be the damage itself.
+_PROBE = r"""
+import importlib.util, sys
+from pathlib import Path
+
+import torch
+
+before = {
+ "compile": torch.compile,
+ "Tensor.to": torch.Tensor.to,
+ "Tensor.cuda": torch.Tensor.cuda,
+}
+if hasattr(torch, "accelerator"):
+ before["accelerator.is_available"] = torch.accelerator.is_available
+has_cuda = torch.cuda.is_available()
+
+for path in sys.argv[1:]:
+ spec = importlib.util.spec_from_file_location(Path(path).stem, path)
+ module = importlib.util.module_from_spec(spec)
+ sys.modules[spec.name] = module
+ try:
+ spec.loader.exec_module(module)
+ except BaseException as e: # a module-level pytest.skip is not an error here
+ print("skipped %s: %s" % (path, type(e).__name__))
+
+failures = []
+for name, original in before.items():
+ obj = torch
+ for part in name.split(".")[:-1]:
+ obj = getattr(obj, part)
+ if getattr(obj, name.split(".")[-1]) is not original:
+ failures.append("torch.%s was replaced" % name)
+
+if has_cuda:
+ # The allocator rewrite is the one that makes a GPU test pass vacuously.
+ if not torch.randn(4, 4, device = "cuda").is_cuda:
+ failures.append('torch.randn(device = "cuda") returned a CPU tensor')
+ if not torch.zeros(4).to("cuda").is_cuda:
+ failures.append('Tensor.to("cuda") returned a CPU tensor')
+
+print("FAILURES:" + "|".join(failures))
+sys.exit(1 if failures else 0)
+"""
+
+
+def test_importing_the_cpu_modules_leaves_torch_globals_alone():
+ if importlib.util.find_spec("torch") is None:
+ pytest.skip("torch not installed; there is no global state to protect")
+
+ proc = subprocess.run(
+ [sys.executable, "-B", "-c", _PROBE, *[str(_HERE / name) for name in _GUARDED]],
+ capture_output = True,
+ text = True,
+ timeout = 600,
+ )
+ assert proc.returncode == 0, proc.stdout[-4000:] + proc.stderr[-4000:]
+
+
+def _module_level_nodes(node):
+ """Everything that runs on import: loops and try blocks included, function
+ and class bodies excluded, since those only run when something calls them."""
+ for child in ast.iter_child_nodes(node):
+ if isinstance(child, (ast.FunctionDef, ast.AsyncFunctionDef, ast.Lambda, ast.ClassDef)):
+ continue
+ yield child
+ yield from _module_level_nodes(child)
+
+
+def _rooted_at_torch(node):
+ while isinstance(node, ast.Attribute):
+ node = node.value
+ return isinstance(node, ast.Name) and node.id == "torch"
+
+
+def test_no_version_compat_module_patches_torch_at_import_time():
+ """The static half, so a new module cannot reintroduce the leak.
+
+ Cheap and GPU-free, unlike the subprocess above, and it covers every file in
+ the directory rather than the two known offenders.
+ """
+ offenders = []
+ for path in sorted(_HERE.glob("test_*.py")):
+ if path.name == Path(__file__).name:
+ continue
+ for node in _module_level_nodes(ast.parse(path.read_text(encoding = "utf-8"))):
+ targets = []
+ if isinstance(node, ast.Assign):
+ targets = node.targets
+ elif isinstance(node, ast.AnnAssign):
+ targets = [node.target]
+ elif (
+ isinstance(node, ast.Call)
+ and isinstance(node.func, ast.Name)
+ and node.func.id == "setattr"
+ and node.args
+ ):
+ targets = [node.args[0]]
+ for target in targets:
+ if isinstance(target, (ast.Attribute, ast.Name)) and _rooted_at_torch(target):
+ offenders.append(f"{path.name}:{node.lineno} {ast.unparse(target)}")
+
+ assert not offenders, (
+ "patch torch from a fixture instead, so it is undone for the rest of the "
+ f"session: {offenders}"
+ )
diff --git a/tests/version_compat/test_trl_fake_train_cpu.py b/tests/version_compat/test_trl_fake_train_cpu.py
index 2f7b469428d..0162e599ef8 100644
--- a/tests/version_compat/test_trl_fake_train_cpu.py
+++ b/tests/version_compat/test_trl_fake_train_cpu.py
@@ -68,24 +68,6 @@ def _eager_compile(
return lambda fn: fn
-torch.compile = _eager_compile
-
-# Belt-and-suspenders: if any @torch.compile still routes through dynamo, let it
-# fall back to eager instead of crashing, and stop its stream-capture probe from
-# reaching torch.accelerator -> real CUDA on a GPU-less box.
-try:
- import torch._dynamo # noqa: E402
- torch._dynamo.config.suppress_errors = True
-except Exception:
- pass
-if hasattr(torch, "accelerator"):
- torch.accelerator.is_available = lambda *a, **k: False
-
-
-# Redirect any `device="cuda"` tensor allocation / `.to("cuda")` / `.cuda()` to
-# CPU. The aggressive spoof deliberately keeps real allocators, but a fake CPU
-# train needs cuda-targeted ops (e.g. inductor's init_gpu_context does
-# `torch.empty(1, device="cuda")`) to land on CPU instead of erroring.
def _is_cuda_dev(d):
try:
return d is not None and torch.device(d).type == "cuda"
@@ -93,64 +75,103 @@ def _is_cuda_dev(d):
return False
-for _name in (
- "empty",
- "zeros",
- "ones",
- "full",
- "tensor",
- "arange",
- "randn",
- "rand",
- "randint",
- "empty_like",
- "zeros_like",
- "ones_like",
-):
- _orig = getattr(torch, _name, None)
- if _orig is None:
- continue
-
- def _redir(
- *args,
- _orig = _orig,
- **kwargs,
+def _fake_cpu_gpu(mp):
+ """Make this process behave like a GPU-less box, undoably.
+
+ Everything here is a mutation of a global that outlives the module, so it
+ goes through the caller's MonkeyPatch: applied for the duration of this
+ module's tests and reverted afterwards. Applied at import time instead, a
+ GPU test collected from anywhere else in the same session silently gets CPU
+ tensors out of `device = "cuda"` and can pass without testing anything.
+ """
+ mp.setattr(torch, "compile", _eager_compile)
+
+ # Belt-and-suspenders: if any @torch.compile still routes through dynamo,
+ # let it fall back to eager instead of crashing, and stop its stream-capture
+ # probe from reaching torch.accelerator -> real CUDA on a GPU-less box.
+ try:
+ # Aliased: a bare `import torch._dynamo` would rebind `torch` as a local.
+ import torch._dynamo as _dynamo
+ mp.setattr(_dynamo.config, "suppress_errors", True)
+ except Exception:
+ pass
+ # torch.accelerator only exists from torch 2.6 onwards.
+ if hasattr(torch, "accelerator"):
+ mp.setattr(torch.accelerator, "is_available", lambda *a, **k: False)
+
+ # Redirect any `device="cuda"` tensor allocation / `.to("cuda")` / `.cuda()`
+ # to CPU. The aggressive spoof deliberately keeps real allocators, but a fake
+ # CPU train needs cuda-targeted ops (e.g. inductor's init_gpu_context does
+ # `torch.empty(1, device="cuda")`) to land on CPU instead of erroring.
+ for _name in (
+ "empty",
+ "zeros",
+ "ones",
+ "full",
+ "tensor",
+ "arange",
+ "randn",
+ "rand",
+ "randint",
+ "empty_like",
+ "zeros_like",
+ "ones_like",
):
- if _is_cuda_dev(kwargs.get("device")):
- kwargs["device"] = "cpu"
- return _orig(*args, **kwargs)
+ _orig = getattr(torch, _name, None)
+ if _orig is None:
+ continue
+
+ def _redir(
+ *args,
+ _orig = _orig,
+ **kwargs,
+ ):
+ if _is_cuda_dev(kwargs.get("device")):
+ kwargs["device"] = "cpu"
+ return _orig(*args, **kwargs)
- setattr(torch, _name, _redir)
+ mp.setattr(torch, _name, _redir)
-_orig_to = torch.Tensor.to
+ _orig_to = torch.Tensor.to
+ def _to_cpu(self, *args, **kwargs):
+ args = tuple("cpu" if _is_cuda_dev(a) else a for a in args)
+ if _is_cuda_dev(kwargs.get("device")):
+ kwargs["device"] = "cpu"
+ return _orig_to(self, *args, **kwargs)
+
+ mp.setattr(torch.Tensor, "to", _to_cpu)
+ mp.setattr(torch.Tensor, "cuda", lambda self, *a, **k: self)
-def _to_cpu(self, *args, **kwargs):
- args = tuple("cpu" if _is_cuda_dev(a) else a for a in args)
- if _is_cuda_dev(kwargs.get("device")):
- kwargs["device"] = "cpu"
- return _orig_to(self, *args, **kwargs)
+ # Extra CUDA stubs the aggressive spoof lacks, needed to walk a real train():
+ # Adam's _cuda_graph_capture_health_check() probes stream capture.
+ mp.setattr(torch.cuda, "is_current_stream_capturing", lambda *a, **k: False, raising = False)
+ try:
+ import torch.cuda.graphs as _cg
+ mp.setattr(_cg, "_cuda_isCurrentStreamCapturing", lambda *a, **k: False, raising = False)
+ except Exception:
+ pass
+ # A broken libmlx.so in the shared site-packages crashes transformers' Mac-only
+ # is_mlx_array probe on Linux; disable it.
+ try:
+ import transformers.utils.generic as _g
+ mp.setattr(_g, "_is_mlx_available", False, raising = False)
+ except Exception:
+ pass
-torch.Tensor.to = _to_cpu
-torch.Tensor.cuda = lambda self, *a, **k: self
-# Extra CUDA stubs the aggressive spoof lacks, needed to walk a real train():
-# Adam's _cuda_graph_capture_health_check() probes stream capture.
-torch.cuda.is_current_stream_capturing = lambda *a, **k: False
-try:
- import torch.cuda.graphs as _cg # noqa: E402
- _cg._cuda_isCurrentStreamCapturing = lambda *a, **k: False
-except Exception:
- pass
[email protected](scope = "module", autouse = True)
+def _cpu_only_torch():
+ """Hold the GPU-less spoof for this module only.
-# A broken libmlx.so in the shared site-packages crashes transformers' Mac-only
-# is_mlx_array probe on Linux; disable it.
-try:
- import transformers.utils.generic as _g # noqa: E402
- _g._is_mlx_available = False
-except Exception:
- pass
+ Module scoped so it is in place before the per-test `_require_stack` imports
+ unsloth and before any trainer is generated, which is the whole reason the
+ patches used to sit at import time.
+ """
+ with pytest.MonkeyPatch.context() as mp:
+ _fake_cpu_gpu(mp)
+ yield mp
# Dense (non-MoE) tiny model on purpose: MoE models route through Unsloth's
@@ -212,7 +233,7 @@ def _load_plain():
@pytest.fixture(autouse = True)
-def _require_stack():
+def _require_stack(_cpu_only_torch):
global torch # the `import torch._dynamo` below would otherwise shadow it as local
if importlib.util.find_spec("unsloth") is None or importlib.util.find_spec("trl") is None:
pytest.skip("unsloth or trl not installed")
@@ -225,10 +246,11 @@ def _require_stack():
# device, crashing on device props (`gcnArchName`). Re-apply the eager
# passthrough and flip dynamo's call-time kill switch so every @torch.compile
# runs eager regardless of when it was decorated. CPU eager is what we want.
- torch.compile = _eager_compile
+ # Through the module's MonkeyPatch, so both are undone with the rest of it.
+ _cpu_only_torch.setattr(torch, "compile", _eager_compile)
try:
import torch._dynamo # noqa: E402
- torch._dynamo.config.disable = True
+ _cpu_only_torch.setattr(torch._dynamo.config, "disable", True)
except Exception:
pass
diff --git a/tests/version_compat/test_trl_padding_free_max_length.py b/tests/version_compat/test_trl_padding_free_max_length.py
index 564571ead1a..6c1b190fb9b 100644
--- a/tests/version_compat/test_trl_padding_free_max_length.py
+++ b/tests/version_compat/test_trl_padding_free_max_length.py
@@ -51,9 +51,22 @@ def _eager_compile(
return lambda fn: fn
-torch.compile = _eager_compile
-if hasattr(torch, "accelerator"):
- torch.accelerator.is_available = lambda *a, **k: False
[email protected](scope = "module", autouse = True)
+def _cpu_only_torch():
+ """Hold the eager-compile spoof for this module only.
+
+ `torch.compile` and `torch.accelerator.is_available` are process-wide, and
+ nothing here needs them before the module's own tests start, so scope them:
+ left in place at import time they follow the session into any GPU test
+ collected after this file.
+ """
+ with pytest.MonkeyPatch.context() as mp:
+ mp.setattr(torch, "compile", _eager_compile)
+ # torch.accelerator only exists from torch 2.6 onwards.
+ if hasattr(torch, "accelerator"):
+ mp.setattr(torch.accelerator, "is_available", lambda *a, **k: False)
+ yield mp
+
_MODEL = "hf-internal-testing/tiny-random-LlamaForCausalLM"
# Model-level length the trainer resolves from when the user names none.
@@ -63,7 +76,7 @@ _USER_MAX_LENGTH = 64
@pytest.fixture(scope = "module", autouse = True)
-def patched_sft():
+def patched_sft(_cpu_only_torch):
"""Import unsloth, and force both halves of the SFT patch on.
`UNSLOTH_ALLOW_CPU=1` (which CPU-only CI sets) skips both, so ask explicitly,
@@ -73,10 +86,12 @@ def patched_sft():
global torch # the `import torch._dynamo` below would otherwise shadow it
import unsloth # noqa: F401
- torch.compile = _eager_compile
+ # Through the module's MonkeyPatch: `import unsloth` reinstalls the real
+ # torch.compile over the passthrough, and dynamo's kill switch is global too.
+ _cpu_only_torch.setattr(torch, "compile", _eager_compile)
try:
import torch._dynamo
- torch._dynamo.config.disable = True
+ _cpu_only_torch.setattr(torch._dynamo.config, "disable", True)
except Exception:
pass