"""Explicit CPU/Vulkan execution policy for the pinned whisper.cpp CLI.""" from __future__ import annotations import hashlib import json import re import shutil import subprocess import warnings from collections.abc import Callable, Sequence from pathlib import Path from ..runtime_errors import memory_error_kind BACKEND_MODES = ("cpu", "vulkan", "auto") class BackendError(RuntimeError): """Whisper failed or did not establish the requested execution backend.""" def file_sha256(path: Path) -> str: digest = hashlib.sha256() with path.open("rb") as handle: for block in iter(lambda: handle.read(1024 * 1024), b""): digest.update(block) return digest.hexdigest() def executable_provenance(executable: str) -> dict[str, str | None]: resolved = shutil.which(executable) return { "path": resolved, "sha256": file_sha256(Path(resolved)) if resolved else None, } def vulkan_device(log: str) -> tuple[str | None, str | None]: """Require selected backend plus hardware identity, not enumeration alone.""" selected = re.search(r"whisper_backend_init_gpu: using (Vulkan\d+) backend", log) if not selected or re.search(r"failed to initialize Vulkan\d+ backend", log): return None, None backend = selected.group(1) index = backend.removeprefix("Vulkan") device = re.search(rf"ggml_vulkan:\s*{index}\s*=\s*(.+?)\s+\(", log) if not device: return None, None name = device.group(1) if re.search(r"llvmpipe|lavapipe|software", name, re.IGNORECASE): return None, None return backend, name def execute_whisper( command: Sequence[str], mode: str, raw_path: Path, output_dir: Path, runner: Callable[..., subprocess.CompletedProcess[str]], ) -> dict[str, object]: """Run inference and persist each attempt; auto retries only backend failures.""" attempts: list[dict[str, object]] = [] diagnostics: dict[str, object] = { "requested_backend": mode, "actual_backend": None, "device_name": None, "fallback_reason": None, "attempts": attempts, "gpu_out_of_memory_detected": False, "memory_error_kind": None, } def persist() -> None: (output_dir / "backend_diagnostics.json").write_text( json.dumps(diagnostics, indent=2) + "\n", encoding="utf-8" ) current = "cpu" if mode == "cpu" else "vulkan" while True: args = list(command) if current == "cpu": args.append("--no-gpu") raw_path.unlink(missing_ok=True) number = len(attempts) + 1 try: completed = runner(args, check=False, capture_output=True, text=True) except OSError as exc: diagnostics["error"] = str(exc) persist() raise BackendError(f"Could not start whisper.cpp: {exc}") from exc log = completed.stdout + "\n" + completed.stderr log_name = f"whisper_attempt_{number}.log" (output_dir / log_name).write_text(log, encoding="utf-8") attempts.append( {"command": args, "returncode": completed.returncode, "log": log_name} ) memory_error = memory_error_kind(log) if memory_error: diagnostics["memory_error_kind"] = memory_error diagnostics["gpu_out_of_memory_detected"] = ( diagnostics["gpu_out_of_memory_detected"] or memory_error == "gpu_out_of_memory" ) attempts[-1]["memory_error_kind"] = memory_error selected, name = vulkan_device(log) backend_failure = bool( re.search( r"no GPU found|No devices found|failed to initialize Vulkan|" r"vk::|Vulkan.*(?:error|failed)|(?:error|failed).*Vulkan|VK_ERROR", log, re.IGNORECASE, ) ) backend_failure = backend_failure or memory_error in ( "gpu_out_of_memory", "gpu_allocation_failure", ) if memory_error in ("host_out_of_memory", "out_of_memory"): backend_failure = False if memory_error and (current == "cpu" or not backend_failure): detail = completed.stderr.strip() or completed.stdout.strip() diagnostics["error"] = memory_error persist() raise BackendError(f"whisper.cpp memory failure ({memory_error}): {detail}") if completed.returncode != 0 and not (current == "vulkan" and backend_failure): detail = ( completed.stderr.strip() or completed.stdout.strip() or "no diagnostic output" ) diagnostics["error"] = detail persist() raise BackendError( f"whisper.cpp failed with exit code {completed.returncode}: {detail}" ) if current == "vulkan" and (not selected or backend_failure): reason = ( "GPU out of memory during Vulkan inference." if memory_error == "gpu_out_of_memory" else "Vulkan hardware execution could not be verified from Whisper diagnostics." ) if mode == "auto" and (completed.returncode == 0 or backend_failure): diagnostics["fallback_reason"] = reason warnings.warn( f"Whisper auto fallback to CPU: {reason}", RuntimeWarning, stacklevel=2, ) current = "cpu" continue diagnostics["error"] = reason persist() detail = completed.stderr.strip() or completed.stdout.strip() raise BackendError( f"Requested Vulkan acceleration unavailable: {reason} {detail}" ) if completed.returncode != 0: detail = ( completed.stderr.strip() or completed.stdout.strip() or "no diagnostic output" ) diagnostics["error"] = detail persist() raise BackendError( f"whisper.cpp failed with exit code {completed.returncode}: {detail}" ) diagnostics["actual_backend"] = current diagnostics["device_name"] = name if current == "vulkan" else None diagnostics["backend_device"] = selected if current == "vulkan" else "CPU" persist() return diagnostics