mrchatgpt's picture
Initial commit of buddi-asr source
f4931e8 verified
Raw History Blame Contribute Delete
6.83 kB
"""Merge PEFT adapters and create a checksummed whisper.cpp artifact."""
from __future__ import annotations
import hashlib
import json
import re
import shutil
import subprocess
import sys
from pathlib import Path
from typing import Any
from buddi_asr.errors import ManifestError, OptionalDependencyError
SUPPORTED_QUANTIZATIONS = {"none", "q4_0", "q5_0", "q5_1", "q8_0"}
def _sha256(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as handle:
for chunk in iter(lambda: handle.read(1024 * 1024), b""):
digest.update(chunk)
return digest.hexdigest()
def merge_lora_adapter(
base_model: str,
adapter_dir: str | Path,
output_dir: str | Path,
) -> dict[str, Any]:
try:
import torch
from peft import PeftModel
from transformers import WhisperForConditionalGeneration, WhisperProcessor
except ImportError as exc:
raise OptionalDependencyError(
"Merging LoRA requires: python -m pip install -e '.[train]'"
) from exc
adapter_path = Path(adapter_dir).resolve()
destination = Path(output_dir).resolve()
if not (adapter_path / "adapter_config.json").is_file():
raise ManifestError(f"LoRA adapter_config.json not found in {adapter_path}")
if destination.exists() and any(destination.iterdir()):
raise ManifestError(f"Merge output directory must be empty: {destination}")
destination.mkdir(parents=True, exist_ok=True)
model = WhisperForConditionalGeneration.from_pretrained(
base_model, torch_dtype=torch.float32, low_cpu_mem_usage=True
)
peft_model = PeftModel.from_pretrained(model, adapter_path)
merged = peft_model.merge_and_unload(safe_merge=True)
merged.config.use_cache = True
merged.save_pretrained(destination, safe_serialization=True)
try:
processor = WhisperProcessor.from_pretrained(adapter_path)
except OSError:
processor = WhisperProcessor.from_pretrained(base_model)
processor.save_pretrained(destination)
return {
"base_model": base_model,
"adapter": str(adapter_path),
"merged_model": str(destination),
}
def _find_quantizer(whisper_cpp: Path) -> Path | None:
candidates = (
whisper_cpp / "build/bin/quantize",
whisper_cpp / "build/bin/whisper-quantize",
whisper_cpp / "build/bin/Release/quantize",
whisper_cpp / "build/bin/Release/whisper-quantize",
)
return next((path for path in candidates if path.is_file()), None)
def export_whisper_cpp(
model_dir: str | Path,
whisper_cpp_dir: str | Path,
openai_whisper_dir: str | Path,
output_dir: str | Path,
*,
name: str = "buddi-asr-tiny-argulf-v1",
quantization: str = "q5_0",
build_if_needed: bool = False,
) -> dict[str, Any]:
model_path = Path(model_dir).resolve()
whisper_cpp = Path(whisper_cpp_dir).resolve()
openai_whisper = Path(openai_whisper_dir).resolve()
destination = Path(output_dir).resolve()
if quantization not in SUPPORTED_QUANTIZATIONS:
raise ManifestError(
"Unsupported quantization; choose: " + ", ".join(sorted(SUPPORTED_QUANTIZATIONS))
)
safe_name = re.sub(r"[^a-zA-Z0-9._-]+", "-", name).strip("-.")
if not safe_name:
raise ManifestError("Artifact name contains no safe filename characters")
if (model_path / "adapter_config.json").exists():
raise ManifestError("Export needs a merged/full model; run merge-lora first")
required_model_files = ("config.json", "vocab.json", "added_tokens.json")
missing_model = [name_ for name_ in required_model_files if not (model_path / name_).is_file()]
if missing_model:
raise ManifestError(
f"Model directory is not a complete Whisper export; missing: {', '.join(missing_model)}"
)
converter = whisper_cpp / "models/convert-h5-to-ggml.py"
if not converter.is_file():
raise ManifestError(f"whisper.cpp converter not found: {converter}")
if not (openai_whisper / "whisper/assets/mel_filters.npz").is_file():
raise ManifestError(
"OpenAI Whisper checkout must contain whisper/assets/mel_filters.npz: "
f"{openai_whisper}"
)
destination.mkdir(parents=True, exist_ok=True)
final_suffix = "f16" if quantization == "none" else quantization
final_model = destination / f"{safe_name}-{final_suffix}.bin"
if final_model.exists():
raise ManifestError(f"Refusing to overwrite existing artifact: {final_model}")
conversion_dir = destination / f".{safe_name}-conversion"
if conversion_dir.exists():
raise ManifestError(f"Stale conversion directory exists; inspect and remove it: {conversion_dir}")
conversion_dir.mkdir()
try:
subprocess.run(
[
sys.executable,
str(converter),
str(model_path),
str(openai_whisper),
str(conversion_dir),
],
check=True,
)
f16_model = conversion_dir / "ggml-model.bin"
if not f16_model.is_file():
raise ManifestError(f"Converter did not create expected file: {f16_model}")
if quantization == "none":
shutil.move(f16_model, final_model)
else:
quantizer = _find_quantizer(whisper_cpp)
if quantizer is None and build_if_needed:
subprocess.run(["cmake", "-B", "build"], cwd=whisper_cpp, check=True)
subprocess.run(
["cmake", "--build", "build", "-j", "--config", "Release"],
cwd=whisper_cpp,
check=True,
)
quantizer = _find_quantizer(whisper_cpp)
if quantizer is None:
raise ManifestError(
"whisper.cpp quantizer is not built. Run cmake -B build && "
"cmake --build build -j --config Release, or pass --build-if-needed"
)
subprocess.run(
[str(quantizer), str(f16_model), str(final_model), quantization], check=True
)
finally:
if conversion_dir.exists():
shutil.rmtree(conversion_dir)
artifact = {
"name": safe_name,
"format": "whisper.cpp-ggml",
"quantization": quantization,
"file": str(final_model),
"size_bytes": final_model.stat().st_size,
"sha256": _sha256(final_model),
"source_model_name": model_path.name,
}
metadata_path = destination / f"{safe_name}-{final_suffix}.json"
metadata_path.write_text(
json.dumps(artifact, ensure_ascii=False, indent=2, sort_keys=True) + "\n",
encoding="utf-8",
)
artifact["metadata"] = str(metadata_path)
return artifact