Add Vulkan Whisper backend and GPU concurrency tooling
This commit is contained in:
1 parent
405fa6cdf4
commit
b3f8baa7ca
18 files changed
+1326
-12
No files matched your search
@@ -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)
|
||||
@@ -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"
|
||||
|
||||
@@ -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")
|
||||
Reference in new issue
Block a user