Add Vulkan Whisper backend and GPU concurrency tooling

This commit is contained in:
admin committed 2026-10-12 15:19:12 +02:00
1 parent 405fa6cdf4
commit b3f8baa7ca
18 files changed
+1326 -12

No files matched your search

+167
View File
@@ -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())
+95
View File
@@ -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())
+107
View File
@@ -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()
+2
View File
@@ -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,
+2
View File
@@ -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}")