Lucasgitguy-co's picture
Turbo-Kev Dictate release
20149a3 verified
Raw History Blame Contribute Delete
6.86 kB
"""Parity gate: torch pipeline (tk.model + HF text model) vs llama.cpp (tools/tk_embd on the GGUF pair).
python scripts/parity.py --label smoke --out out/smoke --gguf out/smoke-gguf/X-BF16.gguf --mmproj out/smoke-gguf/mmproj-X-f16.gguf
Checks per clip: (1) prompt tokens identical (text before and after the audio), (2) audio token count, (3) projector
output cosine per token >= 0.999 with llama.cpp on CPU and an f32 mmproj (--mmproj-f32; exact reference), (4)
teacher-forced on llama.cpp's greedy tokens (Metal, the shipped mmproj), torch picks the same token at every step
where llama.cpp's top1-top2 margin is > 0.5 (near-ties are allowed to differ). The Metal embedding cosine is reported
too: Metal's encoder is ~1-2% noisier than CPU (measured 2026-11-17: CPU f32 cos min 0.99998, Metal min 0.988 on
silent-padding tokens, same for f16 and f32 mmproj), which is llama.cpp runtime noise, not a pipeline error.
"""
from __future__ import annotations
import argparse
import json
import subprocess
import sys
from pathlib import Path
import numpy as np
import soundfile as sf
import torch
from safetensors.torch import load_file
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from tk import paths # noqa: E402
from tk.model import Projector, load_encoder, encode_audio # noqa: E402
from tk.prompt import render_audio_parts, MARKER # noqa: E402
CLIPS = ["fleurs-en-dev/en_us-1533", "fleurs-en-dev/en_us-1510", "dis-test/dis-test-0000-00000", "long/long-0"]
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--label", required=True)
ap.add_argument("--out", required=True, help="export dir (config.json, model.safetensors, text/)")
ap.add_argument("--gguf", required=True)
ap.add_argument("--mmproj", required=True)
ap.add_argument("--mmproj-f32", required=True)
ap.add_argument("--n-gen", type=int, default=24)
ap.add_argument("--clips", nargs="*", default=CLIPS)
a = ap.parse_args()
dev = "mps"
out = Path(a.out)
from transformers import AutoTokenizer, AutoModelForCausalLM
tok = AutoTokenizer.from_pretrained(out / "text")
lm = AutoModelForCausalLM.from_pretrained(out / "text", dtype=torch.float32).to(dev).eval()
enc = load_encoder(paths.WHISPER, "cpu", torch.float32) # fp32 CPU = exact reference
# llama.cpp keeps the two Whisper conv weights in F16 (converter tensor_force_quant) and ggml_conv_1d runs im2col
# in the kernel's type, so the conv INPUTS (mel, conv1 output) are rounded to fp16. Do the same in the reference;
# without it, fully voiced 30 s windows drift to cosine ~0.99 on a few tokens.
for conv in (enc.conv1, enc.conv2):
conv.register_forward_pre_hook(lambda m, args: (args[0].half().float(),))
sd = load_file(out / "model.safetensors")
proj = Projector(hidden=sd["multi_modal_projector.linear_1.weight"].shape[0]).to(dev).eval()
proj.load_state_dict({k[len("multi_modal_projector."):]: v for k, v in sd.items() if k.startswith("multi_modal_projector.")})
work = paths.RUNS / f"parity-{a.label}"
work.mkdir(parents=True, exist_ok=True)
rows, ok_all = [], True
for c in a.clips:
wav, _ = sf.read(paths.AUDIO / f"{c}.flac", dtype="float32")
stem = work / c.replace("/", "_")
wav.astype(np.float32).tofile(f"{stem}.raw")
pre, post = render_audio_parts("Transcribe.")
Path(f"{stem}.txt").write_text(pre + MARKER + post)
import os
subprocess.run([str(paths.ROOT / "tools/tk_embd"), a.gguf, a.mmproj_f32, f"{stem}.raw", f"{stem}.txt",
f"{stem}-cpu"], check=True, capture_output=True, env={**os.environ, "TK_CPU": "1"})
subprocess.run([str(paths.ROOT / "tools/tk_embd"), a.gguf, a.mmproj, f"{stem}.raw", f"{stem}.txt", str(stem),
str(a.n_gen)], check=True, capture_output=True)
j = json.loads(Path(f"{stem}.json").read_text())
ch = j["chunks"]
mid = ch[1:-1]
assert ch[0]["type"] == "text" and ch[-1]["type"] == "text" and all(c["type"] == "audio" for c in mid), ch
cpp_pre, cpp_aud, cpp_post = ch[0]["tokens"], sum(c["n_tokens"] for c in mid), ch[-1]["tokens"]
cpp_emb = np.fromfile(f"{stem}.audio.f32", dtype=np.float32).reshape(cpp_aud, j["n_embd"])
cpu_emb = np.fromfile(f"{stem}-cpu.audio.f32", dtype=np.float32).reshape(cpp_aud, j["n_embd"])
t_pre = tok(pre, add_special_tokens=False).input_ids
t_post = tok(post, add_special_tokens=False).input_ids
with torch.no_grad():
x = encode_audio(enc, wav, "cpu", torch.float32)
emb = proj.cpu()(x).float()
proj.to(dev)
n_t = emb.shape[0]
emb_c = emb[:cpp_aud].cpu().numpy()
def cosine(u, v):
return (u * v).sum(1) / (np.linalg.norm(u, axis=1) * np.linalg.norm(v, axis=1) + 1e-12)
cos = cosine(emb_c, cpu_emb)
cos_metal = cosine(emb_c, cpp_emb)
# teacher forcing on llama.cpp's greedy tokens
gen = j.get("gen", [])
margin = j.get("margin", [])
E = lm.get_input_embeddings()
with torch.no_grad():
ids_pre = torch.tensor([t_pre], device=dev)
ids_post = torch.tensor([t_post + gen], device=dev)
inp = torch.cat([E(ids_pre), torch.from_numpy(cpp_emb)[None].to(dev), E(ids_post)], 1)
logits = lm(inputs_embeds=inp).logits[0]
start = len(t_pre) + cpp_aud + len(t_post) - 1
pred = logits[start:start + len(gen)].argmax(-1).tolist()
hard = [i for i, m in enumerate(margin) if m > 0.5]
mism = [i for i in hard if pred[i] != gen[i]]
r = {"clip": c, "tokens_pre_equal": t_pre == cpp_pre, "tokens_post_equal": t_post == cpp_post,
"audio_tokens_cpp": cpp_aud, "audio_tokens_torch": n_t, "cos_min": round(float(cos.min()), 5),
"cos_mean": round(float(cos.mean()), 5),
"metal_cos_min": round(float(cos_metal.min()), 5), "metal_cos_mean": round(float(cos_metal.mean()), 5), "gen_len": len(gen), "confident_steps": len(hard),
"confident_mismatch": mism, "use_mrope": j["use_mrope"], "audio_chunks": len(mid),
"cpp_text": tok.decode(gen), "torch_tf_text": tok.decode(pred)}
r["pass"] = bool(r["tokens_pre_equal"] and r["tokens_post_equal"] and cpp_aud == n_t and r["cos_min"] >= 0.999
and not mism)
ok_all &= r["pass"]
rows.append(r)
print(json.dumps(r, ensure_ascii=False), flush=True)
res = {"label": a.label, "pass": ok_all, "gguf": a.gguf, "mmproj": a.mmproj, "mmproj_f32": a.mmproj_f32, "clips": rows}
(paths.RESULTS / f"parity-{a.label}.json").write_text(json.dumps(res, indent=2, ensure_ascii=False))
print("PARITY", "PASS" if ok_all else "FAIL")
if __name__ == "__main__":
sys.exit(main())