{"record":{"id":"299ba0f1a40a1c81","repo":"deepfakes/faceswap","slug":"an-unhandled-exception-occurred-initializing-the-d","errorCode":null,"errorMessage":"An unhandled exception occurred initializing the device via Torch Library. Original error: {str(err)}","messagePattern":"An unhandled exception occurred initializing the device via Torch Library\\. Original error: (.+?)","errorType":"exception","errorClass":"FaceswapError","httpStatus":null,"severity":"error","filePath":"lib/gpu_stats/apple_silicon.py","lineNumber":95,"sourceCode":"\n        _METAL_INITIALIZED = True\n\n    def _test_torch(self) -> None:\n        \"\"\"Test that torch can execute correctly.\n\n        Raises\n        ------\n        FaceswapError\n            If the Torch library could not be successfully initialized\n        \"\"\"\n        try:\n            meminfo = torch.mps.driver_allocated_memory()\n            self._log(\"debug\",\n                      f\"Torch initialization test: (mem_info: {meminfo})\")\n        except RuntimeError as err:\n            msg = (\"An unhandled exception occurred initializing the device via Torch \"\n                   f\"Library. Original error: {str(err)}\")\n            raise FaceswapError(msg) from err\n\n    def _get_device_count(self) -> int:\n        \"\"\"Detect the number of SoCs attached to the system.\n\n        Returns\n        -------\n        The total number of SoCs available\n        \"\"\"\n        retval = len(self._mps_devices)\n        self._log(\"debug\", f\"GPU Device count: {retval}\")\n        return retval\n\n    def _get_handles(self) -> list:\n        \"\"\"Obtain the device handles for all available Apple Silicon SoCs.\n\n        Notes\n        -----\n        Apple SoC does not use handles, so return a list of indices corresponding to found","sourceCodeStart":77,"sourceCodeEnd":113,"githubUrl":"https://github.com/deepfakes/faceswap/blob/f530cb7508ae670f6474f8a7d9c4df94705cf96b/lib/gpu_stats/apple_silicon.py#L77-L113","documentation":"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.","triggerScenarios":"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).","commonSituations":" 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.","solutions":["Confirm outside Faceswap: run `nvidia-smi` — if it fails, fix drivers first","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","For NoPermission: run with adequate privileges or correct udev/container device permissions","If drivers are fine and you don't need GPU stats, run with --cpu to bypass NVML"],"exampleFix":"# before\npython faceswap.py --nvidia train ...  # NVMLError_DriverNotLoaded\n\n# after\nsudo apt purge '*nvidia*' && sudo reboot\n# reinstall driver per your distro, verify, then:\nnvidia-smi  # must succeed\npython faceswap.py --nvidia train ...\n# container case:\ndocker run --gpus all ...","handlingStrategy":"try-catch","validationCode":"def mps_usable():\n    import torch\n    return (hasattr(torch.backends, \"mps\")\n            and torch.backends.mps.is_available()\n            and hasattr(torch, \"mps\"))\n\nassert mps_usable(), \"MPS stack broken - reinstall torch before using --apple-silicon\"","typeGuard":"def torch_mps_ok() -> bool:\n    \"\"\"True when the torch MPS backend answers a driver query.\"\"\"\n    try:\n        import torch\n        torch.mps.driver_allocated_memory()\n        return True\n    except (RuntimeError, AttributeError, ImportError):\n        return False","tryCatchPattern":"from lib.utils import FaceswapError\ntry:\n    stats = AppleSiliconStats()  # or launch with --apple-silicon\nexcept FaceswapError as err:\n    if \"Torch Library\" in str(err):\n        run_with_cpu_fallback()  # equivalent of --cpu\n    else:\n        raise","preventionTips":["Pin a torch version known-good for your macOS/Metal combo","Test torch.backends.mps.is_available() in env setup scripts","Keep a --cpu fallback path in automation for MPS breakage"],"tags":["faceswap","nvidia","nvml","driver","gpu","environment"],"backgroundTag":null,"analyzedSha":"f530cb7508ae670f6474f8a7d9c4df94705cf96b","analyzedAt":"2026-08-15T02:59:26.626Z","schemaVersion":2},"datasetVersion":"2026-08-15T17:31:12.345Z"}