Skip to content

Machine and Engines

hifuku.system tells which of the three engines can run on the machine, and on what device. hifuku info prints the same information. An engine that cannot run is a normal state of a machine, so each function returns a status and none raises.

EngineStatus dataclass

Whether one engine can run on this machine.

note is one line: the device the engine runs on, or why it cannot run. software is true for a WebGPU adapter that runs the kernels on the CPU, which is slower than the CPU engine.

Source code in src/hifuku/system.py
@dataclasses.dataclass(frozen=True)
class EngineStatus:
    """Whether one engine can run on this machine.

    ``note`` is one line: the device the engine runs on, or why it cannot run.
    ``software`` is true for a WebGPU adapter that runs the kernels on the CPU,
    which is slower than the CPU engine.
    """

    name: str
    usable: bool
    note: str
    software: bool = False

cpu_status

cpu_status() -> EngineStatus

The CPU engine, which runs on every machine. The note names the CPU.

Source code in src/hifuku/system.py
def cpu_status() -> EngineStatus:
    """The CPU engine, which runs on every machine.  The note names the CPU."""
    return EngineStatus("cpu", True, cpu_model())

cuda_status

cuda_status() -> EngineStatus

The CUDA engine. It can run when numba finds an NVIDIA GPU and its driver. The note names the GPU and its compute capability.

Source code in src/hifuku/system.py
def cuda_status() -> EngineStatus:
    """The CUDA engine.  It can run when numba finds an NVIDIA GPU and its
    driver.  The note names the GPU and its compute capability."""
    try:
        from numba import cuda
        present = cuda.is_available()
    except Exception as exc:  # noqa: BLE001 - numba.cuda can fail to load
        return EngineStatus("cuda", False, f"numba.cuda does not load ({exc})")
    if not present:
        return EngineStatus("cuda", False,
                            "needs an NVIDIA GPU and its driver, and found none")
    try:
        dev = cuda.get_current_device()
        name = dev.name.decode() if isinstance(dev.name, bytes) else str(dev.name)
        return EngineStatus("cuda", True,
                            f"{name} (compute {'%d.%d' % dev.compute_capability})")
    except Exception:  # noqa: BLE001 - present, but the device does not open
        return EngineStatus("cuda", True, "an NVIDIA GPU")

wgsl_status

wgsl_status() -> EngineStatus

The WGSL engine. It can run when wgpu is installed and WebGPU finds an adapter. The note names the adapter and its graphics API, for example Metal. An adapter that runs in software on the CPU sets software.

Source code in src/hifuku/system.py
def wgsl_status() -> EngineStatus:
    """The WGSL engine.  It can run when wgpu is installed and WebGPU finds an
    adapter.  The note names the adapter and its graphics API, for example
    Metal.  An adapter that runs in software on the CPU sets ``software``."""
    if not _wgpu_installed():
        return EngineStatus("wgsl", False, "needs wgpu, which is not installed; "
                                           "install it with pip install 'hifuku[wgsl]'")
    try:
        from hifuku.wgsl import device
        info = device.default_device().adapter.info
    except Exception as exc:  # noqa: BLE001 - no adapter of any kind
        return EngineStatus("wgsl", False, f"found no WebGPU adapter ({exc})")
    where = f"{info['device']} through {info['backend_type']}"
    if info["adapter_type"] == "CPU":
        return EngineStatus("wgsl", True, f"{where}, in software on the CPU, "
                                          f"which is slower than the cpu engine",
                            software=True)
    return EngineStatus("wgsl", True, where)

auto_engine

auto_engine() -> EngineStatus

The engine of --device auto: CUDA, then a hardware WebGPU adapter, then the CPU.

Source code in src/hifuku/system.py
def auto_engine() -> EngineStatus:
    """The engine of ``--device auto``: CUDA, then a hardware WebGPU adapter,
    then the CPU."""
    cuda = cuda_status()
    if cuda.usable:
        return cuda
    wgsl = wgsl_status()
    if wgsl.usable and not wgsl.software:
        return wgsl
    return cpu_status()

report

report() -> str

The text of hifuku info: the host, each engine and the packages.

Source code in src/hifuku/system.py
def report() -> str:
    """The text of ``hifuku info``: the host, each engine and the packages."""
    memory = memory_bytes()
    host = f"{platform.platform()}; {cpu_model()}, {os.cpu_count()} cores"
    if memory:
        host += f", {memory / 2**30:.1f} GiB"
    engines = [cpu_status(), cuda_status(), wgsl_status()]
    chosen = auto_engine()
    packages = []
    for name in ("numpy", "numba", "h5py", "polars", "dendropy", "wgpu"):
        version = _version(name)
        if name == "h5py" and version != "not installed":
            try:
                import h5py
                version += f" (HDF5 {h5py.version.hdf5_version})"
            except Exception:  # noqa: BLE001 - reported as installed only
                pass
        packages.append(f"{name} {version}")
    lines = [f"hifuku {_version('hifuku')}",
             f"Python {platform.python_version()} at {sys.executable}",
             host, "", "Engines:"]
    for e in engines:
        state = "available" if e.usable else "not available"
        lines.append(f"  {e.name:<5} {state}: {e.note}")
    lines += ["", f"hifuku run and hifuku survey use the {chosen.name} engine "
                  f"(--device auto).", "", "Packages: " + ", ".join(packages)]
    return "\n".join(lines)

cpu_model

cpu_model() -> str

The name of the host CPU, or the machine type when no name is found.

Source code in src/hifuku/system.py
def cpu_model() -> str:
    """The name of the host CPU, or the machine type when no name is found."""
    try:
        for line in pathlib.Path("/proc/cpuinfo").read_text().splitlines():
            if line.startswith(("model name", "Model", "Hardware")):
                return line.split(":", 1)[1].strip()
    except OSError:
        pass
    # ARM Linux names no model in /proc/cpuinfo; lscpu reads it from the part
    # numbers, one name per core type.
    try:
        out = subprocess.run(["lscpu"], capture_output=True, text=True, timeout=5,
                             env={**os.environ, "LC_ALL": "C"})
        names = [line.split(":", 1)[1].strip() for line in out.stdout.splitlines()
                 if line.strip().startswith("Model name")]
        if names:
            return " + ".join(dict.fromkeys(names))
    except (OSError, subprocess.SubprocessError):
        pass
    try:
        out = subprocess.run(["sysctl", "-n", "machdep.cpu.brand_string"],
                             capture_output=True, text=True, timeout=5)
        if out.returncode == 0 and out.stdout.strip():
            return out.stdout.strip()
    except (OSError, subprocess.SubprocessError):
        pass
    return platform.processor() or platform.machine()

memory_bytes

memory_bytes() -> int | None

The physical memory of the host, or None where the OS does not say.

Source code in src/hifuku/system.py
def memory_bytes() -> int | None:
    """The physical memory of the host, or None where the OS does not say."""
    try:
        return os.sysconf("SC_PAGE_SIZE") * os.sysconf("SC_PHYS_PAGES")
    except (ValueError, OSError, AttributeError):
        return None