deepfakes/faceswap · error · FaceswapError

An unhandled exception occurred initializing the device via

Error message

An unhandled exception occurred initializing the device via Torch Library. Original error: {str(err)}

What it means

Nvidia GPU stats plugin (lib/gpu_stats/nvidia.py) initializes PyNVML; this branch catches the specific NVML errors LibraryNotFound, DriverNotLoaded and NoPermission and converts them into a FaceswapError advising a driver reinstall. It means the NVML shared library was found importable but could not talk to a driver.

Source

Thrown at lib/gpu_stats/apple_silicon.py:95

        _METAL_INITIALIZED = True

    def _test_torch(self) -> None:
        """Test that torch can execute correctly.

        Raises
        ------
        FaceswapError
            If the Torch library could not be successfully initialized
        """
        try:
            meminfo = torch.mps.driver_allocated_memory()
            self._log("debug",
                      f"Torch initialization test: (mem_info: {meminfo})")
        except RuntimeError as err:
            msg = ("An unhandled exception occurred initializing the device via Torch "
                   f"Library. Original error: {str(err)}")
            raise FaceswapError(msg) from err

    def _get_device_count(self) -> int:
        """Detect the number of SoCs attached to the system.

        Returns
        -------
        The total number of SoCs available
        """
        retval = len(self._mps_devices)
        self._log("debug", f"GPU Device count: {retval}")
        return retval

    def _get_handles(self) -> list:
        """Obtain the device handles for all available Apple Silicon SoCs.

        Notes
        -----
        Apple SoC does not use handles, so return a list of indices corresponding to found

View on GitHub (pinned to f530cb7508)

Solutions

  1. Confirm outside Faceswap: run `nvidia-smi` — if it fails, fix drivers first
  2. Fully remove and reinstall NVIDIA drivers (purge old packages, reboot, reinstall matching CUDA driver version); on containers run with --gpus all and the nvidia-container-toolkit
  3. For NoPermission: run with adequate privileges or correct udev/container device permissions
  4. If drivers are fine and you don't need GPU stats, run with --cpu to bypass NVML

Example fix

# before
python faceswap.py --nvidia train ...  # NVMLError_DriverNotLoaded

# after
sudo apt purge '*nvidia*' && sudo reboot
# reinstall driver per your distro, verify, then:
nvidia-smi  # must succeed
python faceswap.py --nvidia train ...
# container case:
docker run --gpus all ...
Defensive patterns

Strategy: try-catch

Validate before calling

def mps_usable():
    import torch
    return (hasattr(torch.backends, "mps")
            and torch.backends.mps.is_available()
            and hasattr(torch, "mps"))

assert mps_usable(), "MPS stack broken - reinstall torch before using --apple-silicon"

Type guard

def torch_mps_ok() -> bool:
    """True when the torch MPS backend answers a driver query."""
    try:
        import torch
        torch.mps.driver_allocated_memory()
        return True
    except (RuntimeError, AttributeError, ImportError):
        return False

Try / catch

from lib.utils import FaceswapError
try:
    stats = AppleSiliconStats()  # or launch with --apple-silicon
except FaceswapError as err:
    if "Torch Library" in str(err):
        run_with_cpu_fallback()  # equivalent of --cpu
    else:
        raise

Prevention

When it happens

Trigger: Calling `faceswap.py --nvidia ...` (or GPU auto-detection) when the NVIDIA driver is missing/unloaded, the libnvidia-ml.so version mismatches the installed driver (common after partial driver upgrades), or NVML is blocked by container permissions (no /dev/nvidia* access, missing CAP_SYS_ADMIN).

Common situations: apt/dnf driver upgrade left mismatched userspace libs; NVIDIA driver installed but display manager not restarted / nvidia module not loaded (`nvidia-smi` also fails); Docker without --gpus all; WSL2 without the correct Windows driver; secure enterprise machines where NVML needs root.

Related errors


AI-assisted analysis of deepfakes/faceswap@f530cb7508 (2026-08-15). Data as JSON: /api/errors/299ba0f1a40a1c81. Report an issue: GitHub.