diff --git a/PROJECT_KNOWLEDGE.md b/PROJECT_KNOWLEDGE.md index c6ee923..5c8ae3d 100644 --- a/PROJECT_KNOWLEDGE.md +++ b/PROJECT_KNOWLEDGE.md @@ -315,3 +315,32 @@ run directories preserving relative symlinks. Process interruption may leave an unreferenced record or temporary directory, never a partial current generation. This local POSIX-filesystem contract does not promise power-loss durability or network-filesystem transaction semantics. + +## Explicit Whisper execution policy + +Whisper remains the transcription engine. The new backend policy supports CPU, +Vulkan and Auto independently of model/language/thread settings. CPU uses +`--no-gpu`; Vulkan requires selected hardware-backend diagnostics; Auto warns +and records a single forced-CPU retry for missing evidence or recognized backend +failures, while unrelated failures are not retried. The parser targets the +pinned `978113305b2ead22249b881deafa131dc8884911` CLI diagnostic format. Software +Vulkan is rejected. Existing transcript output formats remain unchanged. + +Transcription metadata records execution backend and executable/model checksums; +per-attempt logs and diagnostics survive failures. The build and benchmark +scripts described in `docs/whisper-vulkan.md` preserve the CPU installation and +never invoke Ollama. Actual R9700 validation requires host device access and is +not established by a successful compile alone. + + +## Independent Ollama/Whisper concurrency and memory diagnostics + +Lab does not coordinate Ollama's native queue with the Whisper subprocess. +Confirmed Vulkan device OOM, host OOM, unspecified OOM and GPU allocation errors +are distinguished. Whisper Auto can retain device-OOM evidence after one CPU +retry; explicit Vulkan fails clearly. Ollama memory failures are surfaced without +retries. Pipeline metadata includes a memory classification when available. +The opt-in concurrency benchmark uses qwen3.8:27b with num_ctx=32768; compares +serial, two-request parallel and parallel-plus-Whisper cases; and captures +read-only resource telemetry. It does not modify server settings, models, power +limits or existing meeting artifacts, and adds no production scheduler. diff --git a/README.md b/README.md index f42c0a1..e12af9b 100644 --- a/README.md +++ b/README.md @@ -290,3 +290,16 @@ run directories preserving relative symlinks. Process interruption may leave an unreferenced record or temporary directory, never a partial current generation. This local POSIX-filesystem contract does not promise power-loss durability or network-filesystem transaction semantics. + +Whisper execution can be selected explicitly with `--whisper-backend cpu|vulkan|auto` +on the transcription and MVP CLIs, or `MvpMeetingConfig.whisper_backend` in the +Python API. CPU forces GPU execution off; Vulkan requires hardware execution +proof; Auto reports any CPU fallback. See [Vulkan configuration and validation](docs/whisper-vulkan.md) +for the separate pinned build, diagnostics, benchmarking and rollback procedure. + + +The opt-in `scripts/benchmark_gpu_concurrency.py` measures two concurrent +qwen3.8:27b requests alongside strict Vulkan transcription, preserving the +32768-token context and reporting memory failures. Ollama and Whisper retain +independent execution; no global GPU lock is added. See `docs/whisper-vulkan.md` +and the paired Assistant's `docs/gpu-concurrency.md` for controlled validation. diff --git a/docs/whisper-vulkan.md b/docs/whisper-vulkan.md new file mode 100644 index 0000000..569e31e --- /dev/null +++ b/docs/whisper-vulkan.md @@ -0,0 +1,118 @@ +# Explicit Whisper CPU and Vulkan execution + +Meeting Lab retains whisper.cpp, large-v3-turbo, the canonical audio preparation, +and all language, thread, flash-attention and JSON-output parameters. Transcription acceleration needs no ROCm or GPU power changes. The separate +fertigungski concurrency policy changes only Ollama resident/parallel limits. + +`transcribe_audio(..., backend=...)`, `MvpMeetingConfig.whisper_backend`, and +`--whisper-backend` on both transcription/MVP CLIs support: + +- `cpu`: always pass `--no-gpu`, including when using a Vulkan-capable binary. +- `vulkan`: require successful inference and diagnostics identifying a selected + Vulkan backend and hardware device. Enumeration alone, failed initialization, + software renderers, and missing diagnostic evidence fail clearly. +- `auto` (portable default): attempt Vulkan; if successful execution lacks hardware + evidence, or a recognized Vulkan/backend failure occurs, retry once with + `--no-gpu`. Emit a warning and record the reason. Unrelated inference/model + failures are not retried. CPU fallback uses the selected binary's CPU backend. + +This policy is deliberately tied to the pinned CLI's diagnostic format. If a +future CLI changes its logs, explicit Vulkan fails closed and auto reports CPU +fallback. Runtime evidence establishes backend initialization and completed +inference, not that every operation ran on the GPU. Host validation must also +observe Radeon utilization. + +Each attempt preserves its command, exit status and combined output in +`backend_diagnostics.json` and `whisper_attempt_N.log`. Failed runs also retain +these diagnostics. Successful `runtime_metadata.json` retains the existing +`backend: whisper.cpp` field and adds requested/actual backend, device name, +fallback reason, executable path/checksum and model checksum. Transcript formats +are unchanged. Attempt commands contain a temporary output prefix that is removed +at completion; the original JSON is preserved as `whisper_raw.json`. + +## Reproducible separate host build + +Run from the Meeting Lab checkout with normal host write/device access: + +```bash +python3 scripts/build_whisper_vulkan.py --source /opt/whisper.cpp --jobs 4 +``` + +The script refuses a dirty source tree, a revision other than +`978113305b2ead22249b881deafa131dc8884911`, or an existing `build-vulkan` +directory. It creates `/opt/whisper.cpp/build-vulkan` with: + +```text +CMAKE_BUILD_TYPE=Release +GGML_VULKAN=ON +GGML_CPU=ON +GGML_HIP=OFF +GGML_CUDA=OFF +WHISPER_BUILD_TESTS=OFF +WHISPER_BUILD_SERVER=OFF +``` + +It records compiler/CMake versions, source status/diff, build commands/logs, +CPU/Vulkan CMake caches, and SHA256 values. Original CPU binary, cache and model +checksums are checked again after building. It never installs packages or alters +the original `build` directory or model. Do not copy just the new executable: +its companion shared libraries must remain with it. + +The observed Debian prerequisites are build-essential, CMake, Vulkan development +files/loader, Mesa Vulkan drivers, glslc and SPIR-V headers. They are already +installed on fertigungski. The build uses host CPU tuning; rebuild on another host +rather than assuming the resulting binary is portable. + +## Hardware validation and benchmark + +Check `vulkaninfo --summary` on the host: it must expose the Radeon AI PRO R9700, +not only llvmpipe. Check device permissions and library resolution. Run a fresh +benchmark outside all existing meeting runs: + +```bash +python3 scripts/benchmark_whisper_backends.py /opt/whisper.cpp/samples/jfk.wav \ + --model /opt/whisper.cpp/models/ggml-large-v3-turbo.bin \ + --cpu-executable /opt/whisper.cpp/build/bin/whisper-cli \ + --vulkan-executable /opt/whisper.cpp/build-vulkan/bin/whisper-cli \ + --language en --threads 4 --repeats 3 \ + --output-dir /tmp/whisper-r9700-benchmark-001 +``` + +The benchmark refuses an existing output directory. It uses identical audio, +model, language, threads and decoding parameters; creates only transcription +artifacts; and makes no LLM calls. Its JSON records timing, real-time factor, +actual backend, device and failures. The first run includes possible cold-start +costs. Never claim GPU speedup from forced-CPU or software Vulkan results. + +Observe utilization, peak VRAM, power and temperature using existing host tools. +Repeat on reviewed German/English clips, checking WER/CER, names, numbers, +omissions, repetition and timestamps. Verify explicit CPU, explicit unavailable +Vulkan and auto fallback. Test contention with resident Ollama models without +changing Ollama configuration or power limits. Keep the model unchanged; GPU +floating-point differences can affect decoding and diarization alignment. + +## Rollback + +Select `cpu` and `/opt/whisper.cpp/build/bin/whisper-cli`. Keep the same model. +The separate Vulkan build can remain unused; no service restart or package +rollback is required for this configuration change. Existing artifacts remain +unchanged. Apply paired Assistant/Lab revisions together. + + +## GPU memory failures and concurrent load + +Transcription metadata additionally records `gpu_out_of_memory_detected` and +`memory_error_kind`. A confirmed Vulkan device OOM fails explicit Vulkan or +triggers the documented Auto CPU retry, retaining its OOM evidence. Host or +unqualified memory errors are not silently treated as GPU OOM. Ollama HTTP/JSON +memory errors are classified and surfaced without retrying LLM generation. + +`scripts/benchmark_gpu_concurrency.py` measures serial and parallel workloads +using two qwen3.8:27b requests with 32768-token contexts and strict Vulkan Whisper. +It performs six generation requests and two transcriptions in a new directory, +records independent request windows and read-only VRAM/utilization/power/thermal +and Ollama `/api/ps` samples, and stops after a failed case. Supply representative +canonical audio and two complete protocol prompts within the 29000 estimated +input-token budget. No shared production GPU lock or scheduler is introduced. +See the paired Assistant's `docs/gpu-concurrency.md` for the host service policy, +benchmark command, server-side overlap verification and rollback procedure. diff --git a/scripts/benchmark_gpu_concurrency.py b/scripts/benchmark_gpu_concurrency.py new file mode 100755 index 0000000..3f4b141 --- /dev/null +++ b/scripts/benchmark_gpu_concurrency.py @@ -0,0 +1,167 @@ +#!/usr/bin/env python3 +"""Benchmark two qwen3.8:27b requests alongside strict Vulkan Whisper.""" + +from __future__ import annotations + +import argparse +import json +import sys +import wave +from collections.abc import Callable +from pathlib import Path +from typing import Any + +REPO_ROOT = Path(__file__).resolve().parents[1] +if str(REPO_ROOT) not in sys.path: + sys.path.insert(0, str(REPO_ROOT)) + +from src.meeting_lab.benchmarking.concurrency import run_load_case +from src.meeting_lab.llm.ollama import generate_once, require_model +from src.meeting_lab.protocol.generate_direct_protocol import estimate_input_tokens +from src.meeting_lab.transcription.backend import file_sha256 +from src.meeting_lab.transcription.whisper import transcribe_audio + +MODEL = "qwen3.8:27b" +CONTEXT = 32768 + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument( + "audio", type=Path, help="Fresh canonical WAV for a realistic Whisper workload" + ) + parser.add_argument( + "--prompt-file", + type=Path, + required=True, + help="Complete realistic protocol prompt", + ) + parser.add_argument( + "--second-prompt-file", type=Path, help="Defaults to reusing the first prompt" + ) + parser.add_argument("--whisper-model", type=Path, required=True) + parser.add_argument("--whisper-executable", required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--endpoint", default="http://127.0.0.1:11434") + parser.add_argument("--language", default="de") + parser.add_argument("--threads", default="auto") + parser.add_argument("--timeout", type=int, default=3600) + args = parser.parse_args() + paths = [args.prompt_file, args.second_prompt_file or args.prompt_file] + prompts = [path.read_text(encoding="utf-8") for path in paths] + if any( + not prompt.strip() or estimate_input_tokens(prompt) > 29000 + for prompt in prompts + ): + parser.error( + "Prompts must be non-empty and within the 29,000 estimated input-token budget" + ) + with wave.open(str(args.audio), "rb") as audio: + if (audio.getnchannels(), audio.getframerate(), audio.getsampwidth()) != ( + 1, + 16000, + 2, + ): + parser.error("Audio must be canonical mono 16 kHz PCM16 WAV") + duration = audio.getnframes() / audio.getframerate() + args.output_dir.mkdir(parents=True, exist_ok=False) + report = { + "model": MODEL, + "num_ctx": CONTEXT, + "llm_request_count_planned": 6, + "whisper_request_count_planned": 2, + "audio_duration_seconds": duration, + "audio_sha256": file_sha256(args.audio), + "whisper_model_sha256": file_sha256(args.whisper_model), + "prompts": [ + { + "sha256": file_sha256(path), + "estimated_tokens": estimate_input_tokens(prompt), + } + for path, prompt in zip(paths, prompts, strict=True) + ], + "server_policy_expected": { + "OLLAMA_MAX_LOADED_MODELS": 1, + "OLLAMA_NUM_PARALLEL": 2, + }, + "cases": {}, + } + result_file = args.output_dir / "concurrency.json" + + def save() -> None: + result_file.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + + save() + try: + require_model(args.endpoint, MODEL) + except Exception as exc: # noqa: BLE001 + report["blocked"] = str(exc) + save() + return 1 + + def jobs( + case: str, include_whisper: bool + ) -> dict[str, Callable[[], dict[str, Any]]]: + folder = args.output_dir / case + folder.mkdir() + + def llm(index: int) -> dict[str, Any]: + generated = generate_once( + args.endpoint, + MODEL, + prompts[index], + timeout=args.timeout, + num_ctx=CONTEXT, + num_predict=8192, + ) + (folder / f"ollama-{index + 1}.json").write_text( + json.dumps(generated.raw_response, indent=2) + "\n" + ) + return { + "runtime_seconds": generated.client_wall_time_seconds, + "model": MODEL, + "num_ctx": CONTEXT, + "prompt_eval_count": generated.raw_response.get("prompt_eval_count"), + "eval_count": generated.raw_response.get("eval_count"), + "total_duration_ns": generated.raw_response.get("total_duration"), + "load_duration_ns": generated.raw_response.get("load_duration"), + "prompt_eval_duration_ns": generated.raw_response.get("prompt_eval_duration"), + "eval_duration_ns": generated.raw_response.get("eval_duration"), + } + + calls = {"ollama-1": lambda: llm(0), "ollama-2": lambda: llm(1)} + if include_whisper: + + def whisper() -> dict[str, Any]: + result = transcribe_audio( + args.audio, + args.whisper_model, + folder / "whisper", + args.language, + executable=args.whisper_executable, + threads=args.threads, + backend="vulkan", + ) + return json.loads(result.runtime_metadata.read_text()) + + calls["whisper"] = whisper + return calls + + for case, parallel, include_whisper in [ + ("serial_baseline", False, True), + ("ollama_parallel", True, False), + ("ollama_and_whisper", True, True), + ]: + report["cases"][case] = run_load_case( + jobs(case, include_whisper), parallel=parallel, endpoint=args.endpoint + ) + save() + if any(job["status"] == "failed" for job in report["cases"][case]["jobs"]): + print(f"Benchmark failed in {case}; diagnostics: {result_file}") + return 1 + print(result_file) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/benchmark_whisper_backends.py b/scripts/benchmark_whisper_backends.py new file mode 100755 index 0000000..897ab6e --- /dev/null +++ b/scripts/benchmark_whisper_backends.py @@ -0,0 +1,95 @@ +#!/usr/bin/env python3 +"""Compare CPU/Vulkan on one canonical WAV without generating a protocol.""" + +from __future__ import annotations + +import argparse +import json +import sys +import wave +from pathlib import Path + +REPO_ROOT = Path(__file__).resolve().parents[1] +if str(REPO_ROOT) not in sys.path: + sys.path.insert(0, str(REPO_ROOT)) + +from src.meeting_lab.transcription.backend import file_sha256 +from src.meeting_lab.transcription.whisper import ( + TranscriptionError, + transcribe_audio, +) + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("audio", type=Path) + parser.add_argument("--model", type=Path, required=True) + parser.add_argument("--cpu-executable", required=True) + parser.add_argument("--vulkan-executable", required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--language", default="en") + parser.add_argument("--threads", default="auto") + parser.add_argument("--repeats", type=int, default=3) + args = parser.parse_args() + if args.repeats < 1: + parser.error("--repeats must be positive") + with wave.open(str(args.audio), "rb") as source: + if (source.getnchannels(), source.getframerate(), source.getsampwidth()) != ( + 1, + 16000, + 2, + ): + parser.error("Input must be mono 16 kHz PCM16 WAV") + duration = source.getnframes() / source.getframerate() + args.output_dir.mkdir(parents=True, exist_ok=False) + report = { + "audio_sha256": file_sha256(args.audio), + "model_sha256": file_sha256(args.model), + "audio_duration_seconds": duration, + "language": args.language, + "threads": args.threads, + "runs": [], + "errors": [], + "notes": "First run per backend is cold-start candidate; later runs are warm candidates.", + } + for mode, executable in [ + ("cpu", args.cpu_executable), + ("vulkan", args.vulkan_executable), + ]: + for index in range(args.repeats): + output = args.output_dir / f"{mode}-{index + 1}" + try: + result = transcribe_audio( + args.audio, + args.model, + output, + args.language, + executable=executable, + threads=args.threads, + backend=mode, + ) + metadata = json.loads(result.runtime_metadata.read_text()) + report["runs"].append( + { + "backend": mode, + "iteration": index + 1, + "runtime_seconds": result.runtime_seconds, + "rtf": result.runtime_seconds / duration, + "device_name": metadata["device_name"], + "actual_backend": metadata["actual_backend"], + "output": str(output.resolve()), + } + ) + except TranscriptionError as exc: + report["errors"].append({"backend": mode, "error": str(exc)}) + break + finally: + (args.output_dir / "benchmark.json").write_text( + json.dumps(report, indent=2) + "\n" + ) + print(args.output_dir / "benchmark.json") + return 1 if report["errors"] else 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/build_whisper_vulkan.py b/scripts/build_whisper_vulkan.py new file mode 100755 index 0000000..a63976d --- /dev/null +++ b/scripts/build_whisper_vulkan.py @@ -0,0 +1,107 @@ +#!/usr/bin/env python3 +"""Build the pinned Vulkan CLI separately, preserving the CPU installation.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import subprocess +from pathlib import Path + +PINNED_REVISION = "978113305b2ead22249b881deafa131dc8884911" +FLAGS = [ + "-DCMAKE_BUILD_TYPE=Release", + "-DGGML_VULKAN=ON", + "-DGGML_CPU=ON", + "-DGGML_HIP=OFF", + "-DGGML_CUDA=OFF", + "-DWHISPER_BUILD_TESTS=OFF", + "-DWHISPER_BUILD_SERVER=OFF", +] + + +def 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 capture(*command: str) -> str: + return subprocess.check_output(command, text=True) + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--source", type=Path, default=Path("/opt/whisper.cpp")) + parser.add_argument("--jobs", type=int, default=4) + args = parser.parse_args() + source = args.source.resolve() + if args.jobs < 1: + parser.error("--jobs must be positive") + revision = capture("git", "-C", str(source), "rev-parse", "HEAD").strip() + changes = capture("git", "-C", str(source), "diff", "HEAD", "--binary") + status = capture("git", "-C", str(source), "status", "--porcelain=v1") + if revision != PINNED_REVISION or changes or status: + parser.error( + "Source must be the clean pinned revision; refusing an unrecorded build." + ) + build = source / "build-vulkan" + model = source / "models/ggml-large-v3-turbo.bin" + protected = [ + model, + source / "build/bin/whisper-cli", + source / "build/CMakeCache.txt", + ] + before = {str(path): sha256(path) for path in protected} + build.mkdir(exist_ok=False) + provenance = build / "provenance" + provenance.mkdir() + configure = ["cmake", "-S", str(source), "-B", str(build), *FLAGS] + compile_command = [ + "cmake", + "--build", + str(build), + "--target", + "whisper-cli", + "-j", + str(args.jobs), + ] + manifest = { + "source_revision": revision, + "source_status": status, + "protected_sha256": before, + "configure": configure, + "build": compile_command, + "compiler": capture("c++", "--version"), + "cmake": capture("cmake", "--version"), + } + (provenance / "baseline.json").write_text(json.dumps(manifest, indent=2) + "\n") + (provenance / "source.patch").write_text(changes) + (provenance / "cpu-CMakeCache.txt").write_bytes(protected[2].read_bytes()) + try: + for command, name in [ + (configure, "configure.log"), + (compile_command, "build.log"), + ]: + with (provenance / name).open("w") as log: + subprocess.run( + command, stdout=log, stderr=subprocess.STDOUT, check=True + ) + (provenance / "vulkan-CMakeCache.txt").write_bytes( + (build / "CMakeCache.txt").read_bytes() + ) + manifest["vulkan_binary_sha256"] = sha256(build / "bin/whisper-cli") + finally: + after = {str(path): sha256(path) for path in protected} + manifest["protected_sha256_after"] = after + (provenance / "baseline.json").write_text(json.dumps(manifest, indent=2) + "\n") + if before != after: + raise RuntimeError("Protected CPU installation/model changed during build.") + print(f"Built {build / 'bin/whisper-cli'}; GPU validation is still required.") + + +if __name__ == "__main__": + main() diff --git a/scripts/run_mvp_meeting.py b/scripts/run_mvp_meeting.py index 9c36f7d..d645879 100644 --- a/scripts/run_mvp_meeting.py +++ b/scripts/run_mvp_meeting.py @@ -82,6 +82,7 @@ def parse_args(argv: list[str] | None = None) -> argparse.Namespace: default=[], help="Additional docker argument; repeat and use = for values beginning with --.", ) + parser.add_argument("--whisper-backend", choices=("cpu", "vulkan", "auto"), default="auto") return parser.parse_args(argv) @@ -96,6 +97,7 @@ def config_from_args(args: argparse.Namespace) -> MvpMeetingConfig: output_root=args.output_root, language=args.language, threads=args.threads, + whisper_backend=args.whisper_backend, model=args.model, ollama_endpoint=args.ollama_endpoint, protocol_safe_input_token_budget=args.protocol_safe_input_token_budget, diff --git a/scripts/transcribe_meeting.py b/scripts/transcribe_meeting.py index e096cdc..92f48a4 100644 --- a/scripts/transcribe_meeting.py +++ b/scripts/transcribe_meeting.py @@ -25,6 +25,7 @@ def parse_args(argv: list[str] | None = None) -> argparse.Namespace: parser.add_argument("--language", default="auto", help="Language code or 'auto' (default: auto).") parser.add_argument("--threads", default="auto", help="Thread count or 'auto' for physical CPU cores (default: auto).") parser.add_argument("--whisper-executable", default="whisper-cli", help="whisper.cpp CLI executable (default: whisper-cli).") + parser.add_argument("--whisper-backend", choices=("cpu", "vulkan", "auto"), default="auto") return parser.parse_args(argv) @@ -38,6 +39,7 @@ def main(argv: list[str] | None = None) -> int: args.language, executable=args.whisper_executable, threads=args.threads, + backend=args.whisper_backend, ) except TranscriptionError as exc: print(f"Error: {exc}") diff --git a/src/meeting_lab/benchmarking/__init__.py b/src/meeting_lab/benchmarking/__init__.py new file mode 100644 index 0000000..1be7868 --- /dev/null +++ b/src/meeting_lab/benchmarking/__init__.py @@ -0,0 +1 @@ +"""Controlled, opt-in runtime benchmarks; no production scheduling.""" diff --git a/src/meeting_lab/benchmarking/concurrency.py b/src/meeting_lab/benchmarking/concurrency.py new file mode 100644 index 0000000..ffeed61 --- /dev/null +++ b/src/meeting_lab/benchmarking/concurrency.py @@ -0,0 +1,118 @@ +"""Measure independent inference jobs and read-only AMD resource telemetry.""" + +from __future__ import annotations + +import time +from collections.abc import Callable, Mapping +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path +from threading import Event, Thread +from typing import Any + +import requests + +from ..runtime_errors import memory_error_kind + + +def gpu_snapshot(root: Path = Path("/sys/class/drm")) -> list[dict[str, Any]]: + """Read existing sysfs counters; never adjust device settings.""" + devices = [] + for card in sorted(root.glob("card[0-9]*")): + if "-" in card.name: + continue + device = card / "device" + try: + if (device / "vendor").read_text().strip() != "0x1002": + continue + except OSError: + continue + values: dict[str, Any] = {"card": card.name} + paths = list(device.glob("mem_info_vram_*")) + [device / "gpu_busy_percent"] + paths += list(device.glob("hwmon/hwmon*/power1_average")) + paths += list(device.glob("hwmon/hwmon*/temp1_input")) + for path in paths: + try: + values[path.name] = int(path.read_text().strip()) + except (OSError, ValueError): + continue + devices.append(values) + return devices + + +def run_load_case( + jobs: Mapping[str, Callable[[], dict[str, Any]]], + *, + parallel: bool, + endpoint: str | None = None, + sampler: Callable[[], list[dict[str, Any]]] = gpu_snapshot, + sample_interval: float = 1.0, +) -> dict[str, Any]: + """Launch only this benchmark's jobs; preserve failures and measured overlap.""" + stop = Event() + samples = [] + origin = time.perf_counter() + + def sample() -> None: + while not stop.is_set(): + row: dict[str, Any] = { + "seconds": time.perf_counter() - origin, + "gpu": sampler(), + } + if endpoint: + try: + response = requests.get(endpoint.rstrip("/") + "/api/ps", timeout=2) + response.raise_for_status() + row["ollama_ps"] = response.json() + except (requests.RequestException, ValueError) as exc: + row["ollama_ps_error"] = str(exc) + samples.append(row) + stop.wait(sample_interval) + + def execute(name: str, call: Callable[[], dict[str, Any]]) -> dict[str, Any]: + start = time.perf_counter() - origin + try: + result = {"status": "ok", "result": call()} + except Exception as exc: # noqa: BLE001 + result = { + "status": "failed", + "error_type": type(exc).__name__, + "error": str(exc), + "memory_error_kind": getattr( + exc, "memory_error_kind", memory_error_kind(str(exc)) + ), + } + end = time.perf_counter() - origin + return { + "job": name, + "start_seconds": start, + "end_seconds": end, + "runtime_seconds": end - start, + **result, + } + + monitoring = Thread(target=sample, daemon=True) + monitoring.start() + try: + if parallel: + with ThreadPoolExecutor(max_workers=len(jobs)) as workers: + futures = [ + workers.submit(execute, name, call) for name, call in jobs.items() + ] + results = [future.result() for future in futures] + else: + results = [execute(name, call) for name, call in jobs.items()] + finally: + stop.set() + monitoring.join() + overlap = max( + 0.0, + min(item["end_seconds"] for item in results) + - max(item["start_seconds"] for item in results), + ) + return { + "parallel": parallel, + "jobs": results, + "resource_samples": samples, + "all_request_windows_overlap_seconds": overlap, + "notes": "Request-window overlap does not prove server-side parallel execution; check Ollama logs.", + } diff --git a/src/meeting_lab/llm/ollama.py b/src/meeting_lab/llm/ollama.py index 9c2ef0a..4e28a13 100644 --- a/src/meeting_lab/llm/ollama.py +++ b/src/meeting_lab/llm/ollama.py @@ -8,6 +8,7 @@ from typing import Any import requests +from ..runtime_errors import memory_error_kind DEFAULT_ENDPOINT = "http://127.0.0.1:11434" @@ -16,6 +17,19 @@ class OllamaError(RuntimeError): """Raised when Ollama cannot safely complete the requested operation.""" +class OllamaMemoryError(OllamaError): + """An inference memory failure reported by the Ollama server.""" + + def __init__(self, kind: str, detail: str) -> None: + self.memory_error_kind = kind + label = ( + "GPU out of memory" + if kind == "gpu_out_of_memory" + else f"memory failure ({kind})" + ) + super().__init__(f"Ollama {label}: {detail}") + + @dataclass(frozen=True) class OllamaGeneration: raw_response: dict[str, Any] @@ -39,7 +53,9 @@ def require_model(endpoint: str, model: str, timeout: int = 10) -> dict[str, Any response.raise_for_status() data = response.json() except (requests.RequestException, ValueError) as exc: - raise OllamaError(f"Ollama endpoint is not reachable at {base_url}: {exc}") from exc + raise OllamaError( + f"Ollama endpoint is not reachable at {base_url}: {exc}" + ) from exc models = data.get("models") if isinstance(data, dict) else None if not isinstance(models, list): @@ -85,6 +101,13 @@ def generate_once( response.raise_for_status() data = response.json() except requests.RequestException as exc: + error_response = getattr(exc, "response", None) + detail = str(exc) + if error_response is not None: + detail += " " + error_response.text + kind = memory_error_kind(detail) + if kind: + raise OllamaMemoryError(kind, detail) from exc raise OllamaError(f"Ollama generation request failed: {exc}") from exc except ValueError as exc: raise OllamaError("Ollama generation response is not valid JSON.") from exc @@ -92,6 +115,12 @@ def generate_once( if not isinstance(data, dict): raise OllamaError("Ollama generation response must be a JSON object.") + error = data.get("error") + if isinstance(error, str): + kind = memory_error_kind(error) + if kind: + raise OllamaMemoryError(kind, error) + raise OllamaError(f"Ollama generation request failed: {error}") text = data.get("response") if not isinstance(text, str): raise OllamaError("Ollama generation response has no string 'response' field.") diff --git a/src/meeting_lab/orchestration/mvp.py b/src/meeting_lab/orchestration/mvp.py index 8cb05b7..a81f709 100644 --- a/src/meeting_lab/orchestration/mvp.py +++ b/src/meeting_lab/orchestration/mvp.py @@ -29,6 +29,7 @@ from src.meeting_lab.models.meeting_context import ( write_meeting_context, ) from src.meeting_lab.progress import ProgressEvent, ProgressSink, ProgressStatus +from src.meeting_lab.runtime_errors import memory_error_kind from src.meeting_lab.protocol.history import persist_protocol_generation from src.meeting_lab.protocol.generate_direct_protocol import ( DEFAULT_MODEL, @@ -66,6 +67,7 @@ class MvpMeetingConfig: diarization_container_image: str | None = None diarization_container_args: Sequence[str] = () stop_after_diarization: bool = False + whisper_backend: str = "auto" @dataclass(frozen=True) @@ -211,6 +213,8 @@ def _effective_context(value: ContextInput | None) -> MeetingContext | None: def _validate_inputs( config: MvpMeetingConfig, meeting_context: MeetingContext | None ) -> None: + if config.whisper_backend not in ("cpu", "vulkan", "auto"): + raise ValueError(f"Unsupported Whisper backend: {config.whisper_backend}") if not config.audio_file.is_file(): raise FileNotFoundError(f"Audio file does not exist: {config.audio_file}") if not config.whisper_model.is_file(): @@ -314,6 +318,7 @@ def run_mvp_meeting( "transcript_output": str(transcript_path.resolve()), "protocol_output": str(protocol_path.resolve()), "whisper_model": str(config.whisper_model.resolve()), + "whisper_backend_requested": config.whisper_backend, "model": config.model, "ollama_endpoint": config.ollama_endpoint, "status": "running", @@ -398,7 +403,16 @@ def run_mvp_meeting( config.language, executable=config.whisper_executable, threads=config.threads, + backend=config.whisper_backend, ) + transcription_metadata = json.loads(transcription.runtime_metadata.read_text(encoding="utf-8")) + metadata["transcription_backend"] = { + key: transcription_metadata.get(key) + for key in ( + "requested_backend", "actual_backend", "device_name", "fallback_reason", + "gpu_out_of_memory_detected", "memory_error_kind", + ) + } stage_runtimes["whisper"] = round(time.perf_counter() - stage_started, 3) _emit(progress_sink, "transcription", "completed", overall_started) @@ -496,6 +510,7 @@ def run_mvp_meeting( "stage": metadata_stage, "type": type(exc).__name__, "message": str(exc), + "memory_error_kind": getattr(exc, "memory_error_kind", memory_error_kind(str(exc))), } protocol_path = None _emit( diff --git a/src/meeting_lab/runtime_errors.py b/src/meeting_lab/runtime_errors.py new file mode 100644 index 0000000..3b30b11 --- /dev/null +++ b/src/meeting_lab/runtime_errors.py @@ -0,0 +1,33 @@ +"""Classify explicit inference memory failures without guessing their cause.""" + +from __future__ import annotations + +import re + + +def memory_error_kind(message: str) -> str | None: + """Separate confirmed device OOM from host OOM and allocation failures.""" + if re.search( + r"VK_ERROR_OUT_OF_DEVICE_MEMORY|ErrorOutOfDeviceMemory|OutOfDeviceMemoryError|" + r"(?:CUDA|HIP|GPU|VRAM)[^\n]{0,100}out of memory|" + r"out of (?:device|gpu) memory|not enough (?:free )?(?:VRAM|GPU memory)", + message, + re.IGNORECASE, + ): + return "gpu_out_of_memory" + if re.search( + r"VK_ERROR_OUT_OF_HOST_MEMORY|ErrorOutOfHostMemory|host out of memory", + message, + re.IGNORECASE, + ): + return "host_out_of_memory" + if re.search(r"out of memory|std::bad_alloc", message, re.IGNORECASE): + return "out_of_memory" + if re.search( + r"(?:failed|unable) to allocate[^\n]*(?:Vulkan|CUDA|HIP|GPU)|" + r"(?:Vulkan|CUDA|HIP|GPU)[^\n]*(?:allocation failed|failed to allocate)", + message, + re.IGNORECASE, + ): + return "gpu_allocation_failure" + return None diff --git a/src/meeting_lab/transcription/backend.py b/src/meeting_lab/transcription/backend.py new file mode 100644 index 0000000..2559061 --- /dev/null +++ b/src/meeting_lab/transcription/backend.py @@ -0,0 +1,173 @@ +"""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 diff --git a/src/meeting_lab/transcription/whisper.py b/src/meeting_lab/transcription/whisper.py index 5e795c2..40f98a9 100644 --- a/src/meeting_lab/transcription/whisper.py +++ b/src/meeting_lab/transcription/whisper.py @@ -10,11 +10,19 @@ import shutil import subprocess import tempfile import time +from collections.abc import Callable, Sequence from dataclasses import dataclass from datetime import datetime, timezone from pathlib import Path -from typing import Any, Callable, Sequence +from typing import Any +from .backend import ( + BACKEND_MODES, + BackendError, + executable_provenance, + execute_whisper, + file_sha256, +) BACKEND = "whisper.cpp" RAW_FILENAME = "whisper_raw.json" @@ -197,6 +205,7 @@ def transcribe_audio( *, executable: str = "whisper-cli", threads: str | int = DEFAULT_THREADS, + backend: str = "auto", thread_detector: Callable[[], int] = physical_core_count, runner: Callable[..., subprocess.CompletedProcess[str]] = subprocess.run, monotonic: Callable[[], float] = time.monotonic, @@ -216,6 +225,8 @@ def transcribe_audio( raise TranscriptionError("Whisper executable must be a non-empty string.") if output_dir.exists() and not output_dir.is_dir(): raise TranscriptionError(f"Output directory path is not a directory: {output_dir}") + if backend not in BACKEND_MODES: + raise TranscriptionError(f"Unsupported Whisper backend: {backend}") thread_count = resolve_threads(threads, thread_detector) output_dir.mkdir(parents=True, exist_ok=True) @@ -235,19 +246,16 @@ def transcribe_audio( "-oj", "-of", str(temporary_prefix), ) - try: - completed = runner(command, check=False, capture_output=True, text=True) - except OSError as exc: - raise TranscriptionError(f"Could not start {BACKEND}: {exc}") from exc - runtime_seconds = monotonic() - started temporary_raw = temporary_prefix.with_suffix(".json") + try: + diagnostics = execute_whisper(command, backend, temporary_raw, output_dir, runner) + except BackendError as exc: + if temporary_raw.is_file(): + shutil.copyfile(temporary_raw, raw_output) + raise TranscriptionError(str(exc)) from exc + runtime_seconds = monotonic() - started if temporary_raw.is_file(): shutil.copyfile(temporary_raw, raw_output) - if completed.returncode != 0: - detail = completed.stderr.strip() or completed.stdout.strip() or "no diagnostic output" - raise TranscriptionError( - f"{BACKEND} failed with exit code {completed.returncode}: {detail}" - ) if not raw_output.is_file(): raise TranscriptionError(f"{BACKEND} completed without producing JSON output.") @@ -263,6 +271,15 @@ def transcribe_audio( "input_file": str(audio_path.resolve()), "model": str(model_path.resolve()), "backend": BACKEND, + "requested_backend": backend, + "actual_backend": diagnostics["actual_backend"], + "device_name": diagnostics["device_name"], + "fallback_reason": diagnostics["fallback_reason"], + "gpu_out_of_memory_detected": diagnostics["gpu_out_of_memory_detected"], + "memory_error_kind": diagnostics["memory_error_kind"], + "backend_diagnostics": "backend_diagnostics.json", + "executable_provenance": executable_provenance(executable), + "model_sha256": file_sha256(model_path), "whisper_executable": executable, "language": language.strip(), "threads": thread_count, diff --git a/tests/test_gpu_concurrency.py b/tests/test_gpu_concurrency.py new file mode 100644 index 0000000..880614d --- /dev/null +++ b/tests/test_gpu_concurrency.py @@ -0,0 +1,174 @@ +"""GPU failures are reported; independent benchmark jobs are not serialized.""" + +import json +import subprocess +import tempfile +import unittest +from pathlib import Path +from threading import Barrier +from unittest.mock import Mock, patch + +import requests + +from src.meeting_lab.benchmarking.concurrency import gpu_snapshot, run_load_case +from src.meeting_lab.llm.ollama import OllamaError, OllamaMemoryError, generate_once +from src.meeting_lab.runtime_errors import memory_error_kind +from src.meeting_lab.transcription.whisper import TranscriptionError, transcribe_audio + + +class MemoryFailureTests(unittest.TestCase): + def test_device_and_host_memory_errors_are_distinguished(self): + self.assertEqual( + memory_error_kind("VK_ERROR_OUT_OF_DEVICE_MEMORY"), "gpu_out_of_memory" + ) + self.assertEqual( + memory_error_kind("vk::OutOfDeviceMemoryError"), "gpu_out_of_memory" + ) + self.assertEqual( + memory_error_kind("VK_ERROR_OUT_OF_HOST_MEMORY"), "host_out_of_memory" + ) + self.assertEqual(memory_error_kind("out of memory"), "out_of_memory") + self.assertEqual( + memory_error_kind("failed to allocate Vulkan0 buffer"), + "gpu_allocation_failure", + ) + self.assertIsNone(memory_error_kind("server overloaded")) + + def test_ollama_http_oom_is_reported_without_retry(self): + response = Mock(text="Vulkan: ErrorOutOfDeviceMemory") + error = requests.HTTPError("500 Server Error", response=response) + with patch( + "src.meeting_lab.llm.ollama.requests.post", side_effect=error + ) as call, self.assertRaisesRegex(OllamaMemoryError, "GPU out of memory"): + generate_once( + "http://localhost:11434", + "qwen3.8:27b", + "prompt", + timeout=10, + num_ctx=32768, + num_predict=8192, + ) + self.assertEqual(call.call_count, 1) + self.assertEqual(call.call_args.kwargs["json"]["options"]["num_ctx"], 32768) + + def test_ollama_json_oom_is_reported_without_retry(self): + response = Mock() + response.json.return_value = {"error": "GPU out of memory"} + with patch( + "src.meeting_lab.llm.ollama.requests.post", return_value=response + ) as call, self.assertRaises(OllamaMemoryError): + generate_once( + "http://localhost:11434", + "qwen3.8:27b", + "prompt", + timeout=10, + num_ctx=32768, + num_predict=8192, + ) + self.assertEqual(call.call_count, 1) + + def test_overload_is_not_mislabeled_as_gpu_oom(self): + response = Mock(text="server overloaded") + with patch( + "src.meeting_lab.llm.ollama.requests.post", + side_effect=requests.HTTPError("503", response=response), + ), self.assertRaises(OllamaError) as caught: + generate_once( + "http://localhost:11434", + "qwen3.8:27b", + "prompt", + timeout=10, + num_ctx=32768, + num_predict=8192, + ) + self.assertNotIsInstance(caught.exception, OllamaMemoryError) + + def test_whisper_oom_is_recorded_even_after_cpu_fallback(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + audio, model = root / "audio.wav", root / "model.bin" + audio.write_bytes(b"audio") + model.write_bytes(b"model") + calls = [] + + def runner(command, **kwargs): + calls.append(command) + if len(calls) == 1: + return subprocess.CompletedProcess( + command, 1, "", "VK_ERROR_OUT_OF_DEVICE_MEMORY" + ) + raw = Path(command[command.index("-of") + 1]).with_suffix(".json") + raw.write_text(json.dumps({"transcription": []})) + return subprocess.CompletedProcess(command, 0, "", "") + + with self.assertWarnsRegex(RuntimeWarning, "GPU out of memory"): + result = transcribe_audio( + audio, model, root / "out", runner=runner, backend="auto" + ) + metadata = json.loads(result.runtime_metadata.read_text()) + self.assertTrue(metadata["gpu_out_of_memory_detected"]) + self.assertEqual(metadata["actual_backend"], "cpu") + self.assertEqual(metadata["memory_error_kind"], "gpu_out_of_memory") + self.assertIn("--no-gpu", calls[-1]) + + def test_explicit_vulkan_oom_fails_without_cpu_retry(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + audio, model = root / "audio.wav", root / "model.bin" + audio.write_bytes(b"audio") + model.write_bytes(b"model") + runner = Mock( + return_value=subprocess.CompletedProcess( + [], 1, "", "VK_ERROR_OUT_OF_DEVICE_MEMORY" + ) + ) + with self.assertRaisesRegex(TranscriptionError, "GPU out of memory"): + transcribe_audio( + audio, model, root / "out", runner=runner, backend="vulkan" + ) + self.assertEqual(runner.call_count, 1) + metadata = json.loads((root / "out/backend_diagnostics.json").read_text()) + self.assertTrue(metadata["gpu_out_of_memory_detected"]) + + +class ConcurrentBenchmarkTests(unittest.TestCase): + def test_three_jobs_can_overlap_and_failures_are_retained(self): + barrier = Barrier(3, timeout=2) + + def call(): + barrier.wait() + return {"ok": True} + + def oom(): + barrier.wait() + raise OllamaMemoryError("gpu_out_of_memory", "test") + + report = run_load_case( + {"ollama-1": call, "ollama-2": oom, "whisper": call}, + parallel=True, + sampler=list, + sample_interval=0.01, + ) + statuses = [row["status"] for row in report["jobs"]] + self.assertEqual(statuses, ["ok", "failed", "ok"]) + self.assertEqual(report["jobs"][1]["memory_error_kind"], "gpu_out_of_memory") + self.assertGreater(report["all_request_windows_overlap_seconds"], 0) + self.assertTrue(report["resource_samples"]) + + def test_serial_case_does_not_claim_overlap(self): + report = run_load_case( + {"a": dict, "b": dict}, parallel=False, sampler=list + ) + self.assertEqual(report["all_request_windows_overlap_seconds"], 0) + + def test_gpu_telemetry_reads_only_amd_counters(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + device = root / "card0/device" + device.mkdir(parents=True) + (device / "vendor").write_text("0x1002") + (device / "mem_info_vram_used").write_text("123456") + (device / "gpu_busy_percent").write_text("80") + rows = gpu_snapshot(root) + self.assertEqual(rows[0]["mem_info_vram_used"], 123456) + self.assertEqual(rows[0]["gpu_busy_percent"], 80) diff --git a/tests/test_mvp_orchestrator.py b/tests/test_mvp_orchestrator.py index 6d1aa6b..b30033e 100644 --- a/tests/test_mvp_orchestrator.py +++ b/tests/test_mvp_orchestrator.py @@ -51,6 +51,7 @@ def fake_transcribe( *, executable: str, threads: str | int, + backend: str = "auto", ) -> TranscriptionResult: output_dir.mkdir(parents=True, exist_ok=True) raw = output_dir / "whisper_raw.json" diff --git a/tests/test_whisper_backend.py b/tests/test_whisper_backend.py new file mode 100644 index 0000000..880131f --- /dev/null +++ b/tests/test_whisper_backend.py @@ -0,0 +1,220 @@ +"""Regression checks for execution evidence and explicit fallback policy.""" + +import json +import subprocess +import tempfile +import unittest +from pathlib import Path + +from src.meeting_lab.transcription.whisper import TranscriptionError, transcribe_audio + +GPU_LOG = ( + "ggml_vulkan: 0 = AMD Radeon AI PRO R9700 (RADV) | uma: 0\n" + "whisper_backend_init_gpu: using Vulkan0 backend\n" +) +RAW = {"transcription": [{"offsets": {"from": 0, "to": 1000}, "text": "Hello"}]} + + +class BackendTests(unittest.TestCase): + def run_case(self, backend, logs): + temporary = tempfile.TemporaryDirectory() + self.addCleanup(temporary.cleanup) + root = Path(temporary.name) + audio, model = root / "audio.wav", root / "model.bin" + audio.write_bytes(b"audio") + model.write_bytes(b"model") + commands = [] + + def runner(command, **kwargs): + commands.append(command) + code, log = logs[len(commands) - 1] + Path(command[command.index("-of") + 1]).with_suffix(".json").write_text( + json.dumps(RAW), encoding="utf-8" + ) + return subprocess.CompletedProcess(command, code, stdout="", stderr=log) + + return ( + root, + commands, + lambda: transcribe_audio( + audio, + model, + root / "out", + "en", + backend=backend, + runner=runner, + thread_detector=lambda: 2, + ), + ) + + def test_cpu_disables_gpu_and_preserves_parameters(self): + _root, commands, run = self.run_case("cpu", [(0, "")]) + result = run() + self.assertIn("--no-gpu", commands[0]) + self.assertIn("-fa", commands[0]) + self.assertEqual(commands[0][commands[0].index("-l") + 1], "en") + metadata = json.loads(result.runtime_metadata.read_text()) + self.assertEqual(metadata["actual_backend"], "cpu") + self.assertIsNone(metadata["fallback_reason"]) + self.assertEqual( + json.loads(result.transcript_json.read_text())["text"], "Hello" + ) + + def test_verified_vulkan_and_provenance(self): + root, commands, run = self.run_case("vulkan", [(0, GPU_LOG)]) + metadata = json.loads(run().runtime_metadata.read_text()) + self.assertEqual(metadata["actual_backend"], "vulkan") + self.assertEqual(metadata["device_name"], "AMD Radeon AI PRO R9700") + self.assertEqual(len(metadata["model_sha256"]), 64) + self.assertNotIn("--no-gpu", commands[0]) + self.assertTrue((root / "out/whisper_attempt_1.log").is_file()) + + def test_enumeration_without_selection_fails(self): + root, commands, run = self.run_case("vulkan", [(0, GPU_LOG.splitlines()[0])]) + with self.assertRaisesRegex( + TranscriptionError, "Vulkan acceleration unavailable" + ): + run() + self.assertEqual(len(commands), 1) + self.assertIsNone( + json.loads((root / "out/backend_diagnostics.json").read_text())[ + "actual_backend" + ] + ) + + def test_software_vulkan_is_rejected(self): + _root, _commands, run = self.run_case( + "vulkan", [(0, GPU_LOG.replace("AMD Radeon AI PRO R9700", "llvmpipe"))] + ) + with self.assertRaises(TranscriptionError): + run() + + def test_failed_initialization_is_rejected(self): + _root, _commands, run = self.run_case( + "vulkan", [(0, GPU_LOG + "failed to initialize Vulkan0 backend")] + ) + with self.assertRaises(TranscriptionError): + run() + + def test_auto_fallback_is_reported_and_forces_cpu(self): + _root, commands, run = self.run_case("auto", [(0, "no GPU found"), (0, "")]) + with self.assertWarnsRegex(RuntimeWarning, "fallback to CPU"): + metadata = json.loads(run().runtime_metadata.read_text()) + self.assertEqual(metadata["actual_backend"], "cpu") + self.assertTrue(metadata["fallback_reason"]) + self.assertIn("--no-gpu", commands[1]) + + def test_auto_vulkan_error_retries_cpu(self): + _root, commands, run = self.run_case( + "auto", [(1, GPU_LOG + "VK_ERROR_DEVICE_LOST"), (0, "")] + ) + with self.assertWarns(RuntimeWarning): + run() + self.assertEqual(len(commands), 2) + + def test_auto_does_not_retry_unrelated_failure(self): + _root, commands, run = self.run_case("auto", [(7, "invalid model")]) + with self.assertRaisesRegex(TranscriptionError, "exit code 7"): + run() + self.assertEqual(len(commands), 1) + + def test_cpu_fallback_failure_is_preserved(self): + _root, commands, run = self.run_case( + "auto", [(0, "no GPU found"), (9, "CPU failure")] + ) + with ( + self.assertWarns(RuntimeWarning), + self.assertRaisesRegex(TranscriptionError, "exit code 9"), + ): + run() + self.assertEqual(len(commands), 2) + + def test_auto_successful_vulkan_does_not_retry(self): + _root, commands, run = self.run_case("auto", [(0, GPU_LOG)]) + self.assertEqual( + json.loads(run().runtime_metadata.read_text())["actual_backend"], "vulkan" + ) + self.assertEqual(len(commands), 1) + + def test_invalid_backend_fails_before_execution(self): + _root, commands, run = self.run_case("hip", []) + with self.assertRaisesRegex(TranscriptionError, "Unsupported Whisper backend"): + run() + self.assertEqual(commands, []) + + +class BackendConfigurationTests(unittest.TestCase): + def test_cli_and_mvp_backend_selection(self): + from scripts.run_mvp_meeting import config_from_args, parse_args + from scripts.transcribe_meeting import parse_args as parse_transcription + + for backend in ("cpu", "vulkan", "auto"): + args = parse_args( + [ + "audio.wav", + "--whisper-model", + "model.bin", + "--whisper-backend", + backend, + ] + ) + self.assertEqual(config_from_args(args).whisper_backend, backend) + transcription = parse_transcription( + [ + "audio.wav", + "--model", + "model.bin", + "--output-dir", + "out", + "--whisper-backend", + backend, + ] + ) + self.assertEqual(transcription.whisper_backend, backend) + + +class BackendFailureArtifactTests(unittest.TestCase): + def test_auto_cannot_reuse_json_from_failed_gpu_attempt(self): + with tempfile.TemporaryDirectory() as temporary: + root = Path(temporary) + audio, model = root / "audio.wav", root / "model.bin" + audio.write_bytes(b"audio") + model.write_bytes(b"model") + calls = [] + + def runner(command, **kwargs): + calls.append(command) + raw = Path(command[command.index("-of") + 1]).with_suffix(".json") + if len(calls) == 1: + raw.write_text(json.dumps(RAW)) + return subprocess.CompletedProcess( + command, 1, "", "VK_ERROR_DEVICE_LOST" + ) + return subprocess.CompletedProcess(command, 0, "", "") + + with ( + self.assertWarns(RuntimeWarning), + self.assertRaisesRegex(TranscriptionError, "without producing JSON"), + ): + transcribe_audio( + audio, model, root / "out", backend="auto", runner=runner + ) + self.assertFalse((root / "out/whisper_raw.json").exists()) + + def test_start_error_persists_diagnostics_without_retry(self): + with tempfile.TemporaryDirectory() as temporary: + root = Path(temporary) + audio, model = root / "audio.wav", root / "model.bin" + audio.write_bytes(b"audio") + model.write_bytes(b"model") + + def runner(command, **kwargs): + raise FileNotFoundError("executable missing") + + with self.assertRaisesRegex( + TranscriptionError, "Could not start whisper.cpp" + ): + transcribe_audio(audio, model, root / "out", runner=runner) + diagnostic = json.loads((root / "out/backend_diagnostics.json").read_text()) + self.assertIsNone(diagnostic["actual_backend"]) + self.assertEqual(diagnostic["error"], "executable missing")