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.

7.5 KB
Raw Blame
# Auto-generated by .github/workflows/consolidated-tests-ci.yml. Aggressive CUDA spoof for the consolidated CPU-only CI
# GPU-less spoof extending tests/conftest.py. Import before unsloth, unsloth_zoo and transformers.
# Only no-op or value-returning patches, except dropping pin_memory=True.

from __future__ import annotations

import sys
import types
from typing import Any


def apply() -> None:
    """Apply the spoof. Idempotent: calling again has no effect."""
    import torch

    if getattr(torch.cuda, "_unsloth_consolidated_spoof", False):
        return

    # Import bitsandbytes before the spoof flips is_available(), or its CUDA backend import fails
    # with a non-ImportError on a CPU-only wheel.
    try:
        import bitsandbytes  # noqa: F401
    except Exception:
        pass

    torch.cuda.is_available = lambda: True
    torch.cuda.device_count = lambda: 1
    torch.cuda.current_device = lambda: 0
    torch.cuda.is_initialized = lambda: True
    torch.cuda.set_device = lambda *a, **k: None
    torch.cuda.synchronize = lambda *a, **k: None
    torch.cuda.empty_cache = lambda *a, **k: None
    torch.cuda.get_device_name = lambda *a, **k: "NVIDIA A100-SPOOFED"
    torch.cuda.get_device_capability = lambda *a, **k: (8, 0)
    torch.cuda.is_bf16_supported = lambda *a, **k: True
    torch.cuda._is_in_bad_fork = lambda *a, **k: False  # type: ignore[attr-defined]

    # unsloth/kernels/utils.py reads _cuda_getCurrentRawStream at import. CPU-only wheels lack it,
    # and a CUDA wheel on a runner with no driver has it but raises (a notebook install cell that
    # pulls vLLM brings in such a wheel). 0 is the default stream; a working handle is kept.
    _raw_stream = getattr(torch._C, "_cuda_getCurrentRawStream", None)
    try:
        _raw_stream_works = _raw_stream is not None and _raw_stream(0) is not None
    except Exception:
        _raw_stream_works = False
    if not _raw_stream_works:
        torch._C._cuda_getCurrentRawStream = lambda index = 0: 0  # type: ignore[attr-defined]

    class _Props:
        name = "NVIDIA A100-SPOOFED"
        major = 8
        minor = 0
        total_memory = 80 * 1024**3
        multi_processor_count = 108
        is_integrated = False
        is_multi_gpu_board = False

    torch.cuda.get_device_properties = lambda *a, **k: _Props()  # type: ignore[assignment]

    class _CudaRt:
        @staticmethod
        def cudaMemGetInfo(device: int = 0):
            # Nonzero free: zero reads as an exhausted card and the fused loss raises instead of chunking.
            return (60 * 1024**3, 80 * 1024**3)

        @staticmethod
        def cudaGetDeviceCount(*_a, **_k):
            return 0

        @staticmethod
        def cudaSetDevice(*_a, **_k):
            return 0

    torch.cuda.cudart = lambda: _CudaRt()  # type: ignore[assignment]

    try:
        import torch.cuda.memory as _cuda_memory  # type: ignore

        _cuda_memory.mem_get_info = lambda *a, **k: (60 * 1024**3, 80 * 1024**3)
        _cuda_memory.memory_stats = lambda *a, **k: {}
        _cuda_memory.memory_allocated = lambda *a, **k: 0
        _cuda_memory.max_memory_allocated = lambda *a, **k: 0
        _cuda_memory.memory_reserved = lambda *a, **k: 0
        _cuda_memory.max_memory_reserved = lambda *a, **k: 0
        _cuda_memory.reset_peak_memory_stats = lambda *a, **k: None
    except Exception:
        pass

    nvtx_stub = types.ModuleType("torch.cuda.nvtx")
    nvtx_stub.range_push = lambda *a, **k: None  # type: ignore[attr-defined]
    nvtx_stub.range_pop = lambda *a, **k: None  # type: ignore[attr-defined]
    nvtx_stub.mark = lambda *a, **k: None  # type: ignore[attr-defined]
    sys.modules.setdefault("torch.cuda.nvtx", nvtx_stub)
    torch.cuda.nvtx = nvtx_stub  # type: ignore[attr-defined]

    # torch.manual_seed calls cuda.manual_seed_all, so routing back would recurse. No-op them.
    torch.cuda.manual_seed = lambda *a, **k: None  # type: ignore[assignment]
    torch.cuda.manual_seed_all = lambda *a, **k: None  # type: ignore[assignment]
    # Do not route through torch.{get,set}_rng_state, which touch the CPU RNG.
    import torch as _t

    _empty_rng_state = _t.empty(0, dtype = _t.uint8)
    torch.cuda.get_rng_state = lambda *a, **k: _empty_rng_state.clone()  # type: ignore[assignment]
    torch.cuda.set_rng_state = lambda *a, **k: None  # type: ignore[assignment]
    torch.cuda.get_rng_state_all = lambda *a, **k: [_empty_rng_state.clone()]  # type: ignore[attr-defined]
    torch.cuda.set_rng_state_all = lambda *a, **k: None  # type: ignore[attr-defined]
    torch.cuda.initial_seed = lambda *a, **k: 0  # type: ignore[assignment]
    torch.cuda.seed = lambda *a, **k: None  # type: ignore[assignment]
    torch.cuda.seed_all = lambda *a, **k: None  # type: ignore[assignment]

    class _NoopStream:
        def __init__(self, *a, **k): ...
        def __enter__(self):
            return self

        def __exit__(self, *a):
            return False

        def synchronize(self, *a, **k): ...
        def wait_stream(self, *a, **k): ...
        def query(self):
            return True

    class _NoopEvent:
        def __init__(self, *a, **k): ...
        def record(self, *a, **k): ...
        def wait(self, *a, **k): ...
        def query(self):
            return True

        def synchronize(self, *a, **k): ...
        def elapsed_time(self, *a, **k):
            return 0.0

    torch.cuda.Stream = _NoopStream  # type: ignore[assignment]
    torch.cuda.Event = _NoopEvent  # type: ignore[assignment]
    torch.cuda.stream = lambda s: s if s is not None else _NoopStream()  # type: ignore[assignment]
    torch.cuda.current_stream = lambda *a, **k: _NoopStream()  # type: ignore[assignment]
    torch.cuda.default_stream = lambda *a, **k: _NoopStream()  # type: ignore[assignment]

    # pin_memory=True raises on a CPU-only build; strip the kwarg.
    for _name in (
        "empty",
        "zeros",
        "ones",
        "empty_like",
        "zeros_like",
        "ones_like",
        "rand",
        "randn",
        "randint",
    ):
        _orig = getattr(torch, _name, None)
        if _orig is None:
            continue

        def _wrap(
            *args: Any,
            _orig = _orig,
            **kwargs: Any,
        ):
            kwargs.pop("pin_memory", None)
            return _orig(*args, **kwargs)

        setattr(torch, _name, _wrap)

    if hasattr(torch.Tensor, "pin_memory"):
        torch.Tensor.pin_memory = lambda self, *a, **k: self  # type: ignore[assignment]
    if hasattr(torch.Tensor, "is_pinned"):
        torch.Tensor.is_pinned = lambda self, *a, **k: False  # type: ignore[assignment]

    try:
        import torch.cuda.amp  # type: ignore
    except Exception:
        cuda_amp = types.ModuleType("torch.cuda.amp")

        class _StubScaler:
            def __init__(self, *a, **k): ...
            def scale(self, x):
                return x

            def step(self, opt):
                opt.step()

            def update(self, *a, **k): ...
            def unscale_(self, *a, **k): ...
            def get_scale(self):
                return 1.0

            def is_enabled(self):
                return False

            def state_dict(self):
                return {}

            def load_state_dict(self, *a, **k): ...

        cuda_amp.GradScaler = _StubScaler  # type: ignore[attr-defined]
        sys.modules.setdefault("torch.cuda.amp", cuda_amp)
        torch.cuda.amp = cuda_amp  # type: ignore[attr-defined]

    torch.cuda._unsloth_consolidated_spoof = True  # type: ignore[attr-defined]


if __name__ == "__main__":
    apply()
    print("CUDA spoof applied.")