Lucasgitguy-co's picture
Turbo-Kev Dictate release
20149a3 verified
Raw History Blame Contribute Delete
27.9 kB
"""Build the release folders from out/ and results/, render the three cards from the result files, and check them.
python -m tk.release # -> release/{model,gguf,dataset}, release/release.json, results/cards-check.json
Every number in a card is formatted from results/*.json here; nothing is typed by hand. The check re-renders the
cards from the current results and requires the files on disk to be identical, every file a card names to exist,
and every gate to pass. tk/publish.py refuses to upload unless results/cards-check.json says pass.
"""
from __future__ import annotations
import json
import math
import re
import shutil
import sys
from pathlib import Path
from safetensors import safe_open
from tk import paths
from tk.wer import corpus_wer, n_basic, read_jsonl
NAME = "Turbo-Kev-Dictate"
LIC_DIR = paths.ROOT / "licenses" # Apache-2.0 and CC-BY-4.0 texts
MIT = """MIT License
Copyright (c) 2022 OpenAI
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
LICENSES = { # by set-name prefix
"dis": "Apache-2.0 (amaai-lab/DisfluencySpeech; text from Switchboard-1)",
"fleurs": "CC-BY-4.0 (google/fleurs)",
"long": "CC-BY-4.0 (google/fleurs)",
"vox": "CC0-1.0 (facebook/voxpopuli)",
"ls": "CC-BY-4.0 (LibriSpeech, openslr.org/12)",
"say": "Apache-2.0 (OpenAssistant/oasst2 prompts, spoken by macOS say)",
}
def lic(row: dict, set_name: str | None = None) -> str:
if row.get("license"):
return row["license"]
for key in (set_name, row.get("set"), row.get("id")):
for pre, v in LICENSES.items():
if key and key.startswith(pre):
return v
rid = row.get("id") or "" # text pairs reused from LvW-Dictate carry only source ids
if rid.startswith("oasst-"):
return "Apache-2.0 (OpenAssistant/oasst2 prompts)"
if rid.startswith("en_us-"):
return LICENSES["fleurs"]
if "-PLENARY-" in rid:
return LICENSES["vox"]
raise ValueError(f"no licence for row {row.get('id')} (set {set_name or row.get('set')})")
def f2(x: float) -> str:
return f"{x:.2f}"
def n_params(out: Path) -> dict:
"""Parameters of the dictation model: audio encoder + projector + the language model (Qwen3.5's unused vision
tower and MTP head in text/ are not counted)."""
c = {"audio_tower": 0, "projector": 0, "language_model": 0, "unused_in_text_dir": 0}
files = [out / "model.safetensors", *sorted((out / "text").glob("[!.]*.safetensors"))]
for f in files:
with safe_open(f, "pt") as s:
for k in s.keys():
n = math.prod(s.get_slice(k).get_shape())
if k.startswith("audio_tower."):
c["audio_tower"] += n
elif k.startswith("multi_modal_projector."):
c["projector"] += n
elif k.startswith(("model.language_model.", "lm_head.")):
c["language_model"] += n
else:
c["unused_in_text_dir"] += n
c["total"] = c["audio_tower"] + c["projector"] + c["language_model"]
return c
def examples(root: Path, k: int = 5) -> list[tuple[str, str]]:
"""Real held-out outputs: DisfluencySpeech test clips where the fused model matches the clean transcript and raw
Whisper does not, plus spoken prompts that were transcribed (not answered). Deterministic: ordered by id."""
w = {r["id"]: r for r in read_jsonl(root / "results" / "eval-whisper-rows.jsonl")}
fz = read_jsonl(root / "results" / "eval-fused-rows.jsonl")
good = []
for r in fz:
if r["set"] != "dis-test" or r["id"] not in w or not 8 <= len(r["out"].split()) <= 28:
continue
if corpus_wer([r["transcript_c"]], [r["out"]], n_basic) == 0 < corpus_wer([r["transcript_c"]],
[w[r["id"]]["out"]], n_basic):
good.append((w[r["id"]]["out"], r["out"]))
say = [(w[r["id"]]["out"], r["out"]) for r in fz if r["set"] == "say-test" and r["id"] in w
and corpus_wer([r["target"]], [r["out"]], n_basic) == 0 and r["out"].rstrip().endswith("?")]
return good[: k - 1] + say[:1]
def load(root: Path) -> dict:
R = root / "results"
j = lambda n: json.loads((R / f"{n}.json").read_text())
d = {"whisper": j("eval-whisper")["scores"], "cascade": j("eval-cascade")["scores"],
"fused": j("eval-fused")["scores"], "parity": j("parity-trained"), "quants": j("quants"),
"teacher": j("teacher-quant"), "stats": json.loads((root / "data" / "stats.json").read_text())}
sub = R / "eval-fused-torch-subset.json"
d["torch_subset"] = json.loads(sub.read_text())["scores"] if sub.exists() else None
d["params"] = n_params(root / "out" / "turbo-kev")
d["size"] = f"{d['params']['total'] / 1e9:.1f}B"
d["repos"] = {"model_repo": f"{paths.HF_USER}/{NAME}-{d['size']}", "gguf_repo": f"{paths.HF_USER}/{NAME}-{d['size']}-GGUF",
"data_repo": f"{paths.HF_USER}/turbo-kev-dictate-data"}
d["examples"] = examples(root)
return d
def ship_files(root: Path, d: dict) -> list[tuple[Path, str]]:
"""GGUF files that ship: BF16, every text quant that passed, the f16 mmproj (+ q8_0 if it passed), the bundle."""
G = root / "out" / "turbo-kev-gguf"
q = d["quants"]
fs = [(G / f"{NAME}-BF16.gguf", "text model, BF16 (reference)")]
for name, r in q["text"].items():
if r["pass"]:
rec = " **recommended**" if name == q["text_recommended"] else ""
fs.append((G / f"{NAME}-{name}.gguf", f"text model, {name}{rec}"))
fs.append((G / f"mmproj-{NAME}-f16.gguf", "audio encoder + projector, f16" +
(" **recommended**" if q["mmproj_recommended"] == "f16" else "")))
if q["mmproj"]["q8_0"]["pass"]:
fs.append((G / f"mmproj-{NAME}-q8_0.gguf", "audio encoder + projector, q8_0" +
(" **recommended**" if q["mmproj_recommended"] == "q8_0" else "")))
fs.append((G / q["bundle"]["file"], f"one-file bundle of the recommended pair ({' + '.join(q['recommended_pair'])})"))
return fs
# ------------------------------------------------------------------ cards
def yes(b) -> str:
return "pass" if b else "**FAIL**"
FAILED_OK = __import__("os").environ.get("TK_FAILED_GATE_OK") == "1" # user decision 2026-11-23
def failed_block(d: dict) -> str:
f, w = d["fused"], d["whisper"]
if f.get("pass") is True:
return ""
bad = [k for k, v in f["gates"].items() if not v]
return (f"""> **Release gate: FAILED** ({', '.join(bad)}). On the held-out tests the fused model is worse than plain
> Whisper-turbo on clean read speech (FLEURS {f2(f['G2_fleurs-en-test_wer'])} vs {f2(w['G2_fleurs-en-test_wer'])} WER) and
> on long recordings ({f2(f['G5_long_wer'])} vs {f2(w['G5_long_wer'])}), and it transcribes only {f['G3_prompts_kept_pct']}% of
> dictated questions instead of answering them. It does remove fillers (G1 passes). It is published as-is so the
> result can be inspected; for dictation, Whisper-turbo followed by the text cleanup is the safer choice.
""")
def results_table(d: dict) -> str:
w, c, f = d["whisper"], d["cascade"], d["fused"]
g = f["gates"]
rows = [
("G1 DisfluencySpeech test (250), WER vs clean transcript", "G1_dis_wer_vs_clean", "≥ 25% below raw Whisper",
f"{yes(g['G1'])} ({f2(f['G1_rel_improvement'])}% lower)"),
("G2 FLEURS en test (350), WER", "G2_fleurs-en-test_wer", "≤ raw Whisper + 2.0", yes(g["G2_fleurs-en-test"])),
("G2 LibriSpeech test-clean (300), WER", "G2_ls-clean-300_wer", "≤ raw Whisper + 2.0", yes(g["G2_ls-clean-300"])),
("G3 spoken questions/commands (194), % transcribed not answered", "G3_prompts_kept_pct", "≥ 98%, none 1.3x longer",
yes(g["G3"])),
("G5 long recordings (6 × 75-81 s), WER", "G5_long_wer", "≤ FLEURS WER + 3", yes(g["G5"])),
]
out = ["| Check | raw Whisper-turbo | Whisper → Kev-text (cascade) | **Turbo-Kev-Dictate (fused)** | Rule | Result |",
"|---|---:|---:|---:|---|---|"]
for label, key, rule, res in rows:
cell = lambda s: f2(s[key]) if key in s else "–"
out.append(f"| {label} | {cell(w)} | {cell(c)} | **{cell(f)}** | {rule} | {res} |")
return "\n".join(out)
def quant_table(d: dict) -> str:
q = d["quants"]
out = ["| Text model | Size | G1 dis WER | G2 FLEURS | G2 LibriSpeech | G3 kept | Ships |", "|---|---:|---:|---:|---:|---:|---|"]
b = q["bf16"]
out.append(f"| BF16 | {round((d['root'] / 'out' / 'turbo-kev-gguf' / f'{NAME}-BF16.gguf').stat().st_size / 1e6)} MB | "
f"{f2(b['G1_dis_wer_vs_clean'])} | {f2(b['G2_fleurs-en-test_wer'])} | {f2(b['G2_ls-clean-300_wer'])} | "
f"{d['fused']['G3_prompts_kept_pct']}% | yes |")
for name, r in q["text"].items():
out.append(f"| {name} | {r['size_mb']} MB | {f2(r['G1_dis_wer_vs_clean'])} | {f2(r['G2_fleurs-en-test_wer'])} | "
f"{f2(r['G2_ls-clean-300_wer'])} | {r['G3_prompts_kept_pct']}% | {'yes' if r['pass'] else 'no (fails the rule)'} |")
return "\n".join(out)
def examples_table(d: dict) -> str:
out = ["| raw Whisper-turbo | Turbo-Kev-Dictate |", "|---|---|"]
out += [f"| {a.replace('|', '/')} | {b.replace('|', '/')} |" for a, b in d["examples"]]
return "\n".join(out)
def run_block(d: dict) -> str:
q = d["quants"]
text, mm = q["recommended_pair"]
return f"""```bash
brew install llama.cpp # or a llama.cpp build from ggml-org/llama.cpp
hf download {d['repos']['gguf_repo']} {text} {mm} --local-dir turbo-kev
# speech -> clean text (wav, mp3 or flac)
llama-mtmd-cli -m turbo-kev/{text} --mmproj turbo-kev/{mm} --audio recording.wav -p "Transcribe." --temp 0
# a server (OpenAI-style /v1/chat/completions; send the audio as an input_audio part, then "Transcribe.")
llama-server -m turbo-kev/{text} --mmproj turbo-kev/{mm} --jinja -c 8192 --temp 0
# text mode: send a pasted transcript as the user message (no audio) to the same server, and it comes back cleaned
```"""
def model_card(d: dict) -> str:
p, f, st, par = d["params"], d["fused"], d["stats"], d["parity"]
r = d["repos"]
sub = d["torch_subset"]
sub_line = (f"- A 30-clip subset scored with the PyTorch model directly (not llama.cpp): dis {f2(sub['G1_dis_wer_vs_clean'])}, "
f"FLEURS {f2(sub['G2_fleurs-en-test_wer'])}, prompts kept {sub['G3_prompts_kept_pct']}%.\n") if sub else ""
return f"""---
license: apache-2.0
language:
- en
base_model:
- openai/whisper-large-v3-turbo
- Qwen/Qwen3.5-0.8B-Base
- jaredpalmer/kev-0.8b
pipeline_tag: automatic-speech-recognition
tags:
- dictation
- speech-to-text
- disfluency-removal
- ultravox
- whisper
- qwen3.5
- llama.cpp
datasets:
- {r['data_repo']}
- amaai-lab/DisfluencySpeech
- google/fleurs
- facebook/voxpopuli
---
<div align="center">
# {NAME}-{d['size']}
Speech in, clean text out, in one network: Whisper-large-v3-turbo's encoder hears, Kev-0.8B writes, and the ums,
repeats and false starts are gone. It also cleans a transcript you paste in as text.
[Run it](#run-it) · [Results](#results) · [How it works](#how-it-works) · [Limits](#limits) · [GGUF](https://huggingface.co/{r['gguf_repo']}) · [Data](https://huggingface.co/datasets/{r['data_repo']})
</div>
{failed_block(d)}
Real outputs on held-out test recordings:
{examples_table(d)}
## Run it
The GGUF repository has the files for llama.cpp: a text model and an `mmproj` file (the audio encoder and projector).
llama.cpp needs both; a single merged GGUF does not load (llama.cpp 1.0.0: "wrong number of tensors"), so the
one-file download is a bundle that `gguf_bundle.py unpack` turns back into the pair.
{run_block(d)}
This repository holds the source weights in the Ultravox layout (`config.json` + `model.safetensors` with
`audio_tower.*` and `multi_modal_projector.*`, and the text model in `text/`). llama.cpp's `convert_hf_to_gguf.py`
converts it (`text/` for the text model, the repository root with `--mmproj` for the projector). `text/` also loads
on its own in transformers as a Qwen3.5 model for text-mode cleanup.
## Results
Scored through llama-server on the BF16 text model + f16 mmproj, greedy. WER in %, lower is better.
{results_table(d)}
- G1 counts fillers as words (a model that keeps "uh" loses points); G2 and G5 use Whisper's English normaliser.
- Raw Whisper-turbo is oxide-lab's whisper.cpp q8_0 GGUF with beam 5, the same model that wrote the training
transcripts. The cascade runs this model's text mode on those transcripts.
- Other languages are not supported: on 238 FLEURS clips in 24 other languages the WER is {f2(f['info_multi_wer'])}.
{sub_line}- Parity: the PyTorch pipeline and llama.cpp agree (prompt tokens identical, the same number of audio tokens, projector output cosine ≥ 0.999 on CPU, the same greedy tokens wherever llama.cpp is confident): {yes(par['pass'])}.
GGUF quants are scored with the same checks; see the [GGUF repository](https://huggingface.co/{r['gguf_repo']}).
## How it works
```
audio ─► Whisper-large-v3-turbo encoder (frozen) ─► stack 8 frames ─► SwiGLU projector (trained) ─► Kev-text ─► clean text
30 s windows, 1500 frames each 187 tokens / 30 s ▲
"<system> <user> [audio tokens] Transcribe." ─────┘
```
| Part | Parameters | Trained here | Licence |
|---|---:|---|---|
| Whisper-large-v3-turbo encoder | {p['audio_tower'] / 1e6:.0f}M | no (frozen) | MIT |
| projector (RMSNorm, SwiGLU 10240→4096→2048, RMSNorm, 2048→1024) | {p['projector'] / 1e6:.0f}M | yes, stage 2 | Apache-2.0 |
| Kev-text: Qwen3.5-0.8B-Base + Kev-0.8B LoRA + a cleanup LoRA, merged | {p['language_model'] / 1e6:.0f}M | cleanup LoRA, stage 1 | Apache-2.0 |
| **total** | **{p['total'] / 1e9:.2f}B** | | |
This is the Ultravox recipe (Fixie's ultravox-v0_5 uses the same encoder), so llama.cpp runs it with its existing
Ultravox support. Kev-0.8B is a classifier (a LoRA plus a pointer head on Qwen3.5-0.8B-Base); its LoRA is kept, its
pointer head is not used. Kev's own skill (the `/v1/systemone` classifier) is not part of this model.
1. **Teacher transcripts.** oxide-lab's whisper.cpp q8_0 GGUF of Whisper-large-v3-turbo transcribed every training
clip (q8_0 because smaller quants lost accuracy: {f2(d['teacher']['wer']['q8_0'])} vs q4_k {f2(d['teacher']['wer']['q4_k'])} WER on 149 FLEURS dev clips).
2. **Targets.** DisfluencySpeech: the teacher's own words minus the fillers and restarts the human annotation marks
(only deletions, never words the teacher did not hear). Fluent speech (FLEURS, VoxPopuli, LibriSpeech): the
teacher transcript without bare uh/um. Spoken questions and commands: the question itself, never an answer.
3. **Stage 1, text.** A LoRA (r16) on Kev-merged learns transcript → clean text ({st['text-train']:,} pairs), then is merged.
4. **Stage 2, audio.** Only the projector trains ({st['audio-train']:,} clips, one pass), with the encoder and Kev-text
frozen. Loss: cross-entropy on the clean target plus KL to Kev-text reading the teacher transcript as text, so the
audio path learns to behave like the text path. 5% of the steps use 31-90 s recordings (several windows).
Stage 2 (the projector) was trained on a cloud GPU (Modal); everything else ran on a MacBook Air M4 with 16 GB. The code and every command are in `code/` (start with `code/GUIDE.md`).
## Limits
- English only. Other languages come out as poor English or garbled text.
- Trained on about {st['audio-train']:,} clips, far less audio than Whisper or Ultravox saw: rare words, accents and noisy
recordings are where it loses to plain Whisper first.
- It deletes; it is not meant to rephrase. It can still drop a word that was meant, or keep a filler.
- A dictated question is written down, not answered, in {f['G3_prompts_kept_pct']}% of the held-out prompts.
- llama.cpp cuts audio into 30 s windows and drops a final window shorter than llama.cpp's minimum; very long
recordings are best split at pauses.
## Licence
Apache-2.0 (`LICENSE`) for the projector, the merged text model and the code. The Whisper encoder weights are
OpenAI's, MIT (`LICENSE-whisper-MIT.txt`). Data licences are in `NOTICE` and the dataset card.
"""
def gguf_card(d: dict) -> str:
r, q = d["repos"], d["quants"]
text, mm = q["recommended_pair"]
files = "\n".join(f"| `{p.name}` | {p.stat().st_size / 1e6:,.0f} MB | {role} |" for p, role in ship_files(d["root"], d))
mmq = q["mmproj"]["q8_0"]
return f"""---
license: apache-2.0
language:
- en
base_model:
- {r['model_repo']}
pipeline_tag: automatic-speech-recognition
tags:
- gguf
- llama.cpp
- dictation
- speech-to-text
- ultravox
---
<div align="center">
# {NAME}-{d['size']}-GGUF
GGUF files of [{NAME}-{d['size']}](https://huggingface.co/{r['model_repo']}) for llama.cpp: speech in, clean text out.
</div>
{failed_block(d)}
## Files
| File | Size | What |
|---|---:|---|
{files}
Use one text model **and** one mmproj. The recommended pair is `{text}` + `{mm}`: the smallest that passes the
quant rule below.
## Run it
{run_block(d)}
### The one-file bundle
`{q['bundle']['file']}` holds the recommended pair, byte for byte. llama.cpp cannot load it directly (it needs a text
model and an mmproj; a merged file fails with "wrong number of tensors"), so unpack it first:
```bash
python3 gguf_bundle.py unpack {q['bundle']['file']} -o turbo-kev # standard library only; checks each file's sha256
```
## Quant scores
Each text quant was scored with the f16 mmproj through llama-server on the full test sets. A quant ships {q.get('rule', 'when it passes G1, G2 and G3 and its WERs are within 0.5 points of BF16.')}
Quants were tried from large to small and the search stopped at the first failure.
{quant_table(d)}
The q8_0 mmproj with `{mmq['with']}`: G1 {f2(mmq['G1_dis_wer_vs_clean'])}, FLEURS {f2(mmq['G2_fleurs-en-test_wer'])}, LibriSpeech {f2(mmq['G2_ls-clean-300_wer'])}: {'ships' if mmq['pass'] else 'does not ship (fails the rule)'}.
Gate definitions, the baselines and the limits are in the [main model card](https://huggingface.co/{r['model_repo']}).
## Licence
Apache-2.0 (`LICENSE`); the Whisper encoder inside the mmproj files is OpenAI's, MIT (`LICENSE-whisper-MIT.txt`).
See `NOTICE`.
"""
def dataset_card(d: dict, counts: dict) -> str:
r = d["repos"]
rows = "\n".join(f"| `{k}` | {v:,} |" for k, v in counts.items())
return f"""---
license: other
license_name: mixed-per-row
language:
- en
task_categories:
- automatic-speech-recognition
- text-generation
tags:
- dictation
- disfluency-removal
- asr-post-processing
---
# turbo-kev-dictate-data
The text side of the training and evaluation data of [{NAME}-{d['size']}](https://huggingface.co/{r['model_repo']}):
targets, the Whisper-large-v3-turbo teacher transcripts and every evaluation output. No audio is included; each audio
row names its source clip (`audio` = `<set>/<id>.flac`), which is downloadable from the source dataset.
| File | Rows |
|---|---:|
{rows}
- `text/*.jsonl`: stage-1 pairs, `input` (a transcript) → `target` (the clean text).
- `audio/*.jsonl`: stage-2 rows, `input` is the teacher transcript of the clip, `target` the clean text.
- `teacher/*.jsonl`: oxide-lab whisper.cpp q8_0 Whisper-large-v3-turbo transcripts (`hyp`), beam 5, English.
- `eval/*.jsonl`: the outputs behind every number on the model cards (raw Whisper, cascade, fused, each GGUF quant).
Every target can be reached from its input by deleting words; DisfluencySpeech targets are built from the teacher's
words, not copied from the human transcript (kept in `transcript_c` for scoring). Leak check: no training clip or
text is in any test set.
## Licences
Each row's `license` field names its source: DisfluencySpeech Apache-2.0 (utterance texts from Switchboard-1), FLEURS
CC-BY-4.0, VoxPopuli CC0-1.0, LibriSpeech CC-BY-4.0, OpenAssistant oasst2 Apache-2.0. Teacher transcripts were made
with OpenAI's Whisper-large-v3-turbo (MIT). Our additions are CC-BY-4.0 (`LICENSE-CC-BY-4.0.txt`).
"""
NOTICE = """Turbo-Kev-Dictate
Copyright 2026 Lucas van de Weerd (Lucasgitguy-co)
The projector, the merged text model and the code are Apache-2.0 (LICENSE).
Contains:
openai/whisper-large-v3-turbo encoder weights ...... MIT, Copyright (c) 2022 OpenAI (LICENSE-whisper-MIT.txt)
Qwen/Qwen3.5-0.8B-Base ............................. Apache-2.0 (merged into the text model)
jaredpalmer/kev-0.8b LoRA .......................... Apache-2.0 (merged into the text model; pointer head not used)
Training data (text targets; audio was used for training and is not included):
amaai-lab/DisfluencySpeech ... Apache-2.0 (utterance texts from the Switchboard-1 corpus)
google/fleurs ................ CC-BY-4.0
facebook/voxpopuli ........... CC0-1.0
LibriSpeech (openslr 12) ..... CC-BY-4.0
OpenAssistant/oasst2 ......... Apache-2.0 (prompts; spoken with macOS `say` for training)
Teacher transcripts: oxide-lab/whisper-large-v3-turbo-GGUF (q8_0) through whisper.cpp.
"""
# ------------------------------------------------------------------ build + check
def copy(src: Path, dst: Path) -> None:
dst.parent.mkdir(parents=True, exist_ok=True)
if not dst.exists() or dst.stat().st_size != src.stat().st_size:
shutil.copyfile(src, dst)
def write_jsonl(p: Path, rows: list[dict]) -> int:
p.parent.mkdir(parents=True, exist_ok=True)
p.write_text("".join(json.dumps(r, ensure_ascii=False) + "\n" for r in rows))
return len(rows)
def build(root: Path) -> dict:
d = load(root)
d["root"] = root
rel = root / "release"
out = root / "out" / "turbo-kev"
for sub in ("model", "gguf", "dataset"):
(rel / sub).mkdir(parents=True, exist_ok=True)
lic_files = {"LICENSE": LIC_DIR / "LICENSE-Apache-2.0.txt"}
# model repo
M = rel / "model"
for p in [out / "config.json", out / "model.safetensors", *sorted((out / "text").glob("[!.]*"))]:
copy(p, M / p.relative_to(out))
for pat in ("tk/[!.]*.py", "scripts/[!.]*.py", "tools/tk_embd.cpp", "tests/[!.]*.py", "run.sh", "run_bg.sh",
"GUIDE.md"):
for p in sorted(paths.ROOT.glob(pat)): # the code always comes from this checkout
copy(p, M / "code" / p.relative_to(paths.ROOT))
for p in sorted((root / "results").glob("[!.]*.json")):
copy(p, M / "results" / p.name)
# gguf repo
Gd = rel / "gguf"
keep = {p.name for p, _ in ship_files(root, d)}
for p in Gd.glob("*.gguf"):
if p.name not in keep:
p.unlink()
for p, _ in ship_files(root, d):
copy(p, Gd / p.name)
copy(paths.ROOT / "scripts" / "gguf_bundle.py", Gd / "gguf_bundle.py")
for D in (M, Gd):
copy(lic_files["LICENSE"], D / "LICENSE")
(D / "LICENSE-whisper-MIT.txt").write_text(MIT)
(D / "NOTICE").write_text(NOTICE)
# dataset repo
Ds = rel / "dataset"
counts = {}
for split in ("train", "valid"):
t = read_jsonl(root / "data" / "text" / f"{split}.jsonl")
counts[f"text/{split}.jsonl"] = write_jsonl(Ds / "text" / f"{split}.jsonl", [{**r, "license": lic(r)} for r in t])
a = read_jsonl(root / "data" / f"audio-{split}.jsonl")
counts[f"audio/{split}.jsonl"] = write_jsonl(Ds / "audio" / f"{split}.jsonl",
[{**r, "license": lic(r, r["audio"].split("/")[0])} for r in a])
for p in sorted((root / "data" / "teacher").glob("[!.]*.jsonl")):
counts[f"teacher/{p.name}"] = write_jsonl(Ds / "teacher" / p.name,
[{**r, "license": lic(r, p.stem)} for r in read_jsonl(p)])
for p in sorted((root / "results").glob("eval-*-rows.jsonl")):
counts[f"eval/{p.name}"] = write_jsonl(Ds / "eval" / p.name, read_jsonl(p))
copy(LIC_DIR / "LICENSE-CC-BY-4.0.txt", Ds / "LICENSE-CC-BY-4.0.txt")
d["counts"] = counts
(M / "README.md").write_text(model_card(d))
(Gd / "README.md").write_text(gguf_card(d))
(Ds / "README.md").write_text(dataset_card(d, counts))
(rel / "release.json").write_text(json.dumps({**d["repos"], "params": d["params"], "size": d["size"]}, indent=2))
return d
def check(root: Path, d: dict) -> dict:
rel = root / "release"
problems = []
for sub, text in (("model", model_card(d)), ("gguf", gguf_card(d)), ("dataset", dataset_card(d, d["counts"]))):
card = (rel / sub / "README.md").read_text()
if card != text:
problems.append(f"{sub}/README.md differs from a fresh render of results/")
body = card.split("---", 2)[-1]
for a, b in d["examples"]: # example sentences are speech, not values
body = body.replace(a.replace("|", "/"), "").replace(b.replace("|", "/"), "")
for m in re.findall(r"(?<![A-Za-z])(?:None|nan|inf|TODO)(?![A-Za-z])|[{}]", body):
problems.append(f"{sub}/README.md contains {m!r}")
for p, _ in ship_files(root, d):
q = rel / "gguf" / p.name
if not q.exists() or q.stat().st_size != p.stat().st_size:
problems.append(f"gguf/{p.name} missing or a different size")
for name in d["quants"]["recommended_pair"]:
if not (rel / "gguf" / name).exists():
problems.append(f"recommended {name} not in gguf/")
if len(d["examples"]) < 3:
problems.append(f"only {len(d['examples'])} examples found")
gates = {"eval-fused": d["fused"].get("pass") is True, "parity": d["parity"]["pass"] is True,
"bundle": d["quants"]["bundle"]["unpack_byte_identical"] is True}
for k, v in gates.items():
if v:
continue
if k == "eval-fused" and FAILED_OK and all("Release gate: FAILED" in (rel / sub / "README.md").read_text()
for sub in ("model", "gguf")):
continue # published with the failure stated at the top of both cards
problems.append(f"gate {k} not passed")
for f in ("config.json", "model.safetensors", "text/config.json", "LICENSE", "NOTICE", "code/GUIDE.md"):
if not (rel / "model" / f).exists():
problems.append(f"model/{f} missing")
res = {"pass": not problems, "problems": problems, "gates": gates, "repos": d["repos"], "size": d["size"]}
(root / "results" / "cards-check.json").write_text(json.dumps(res, indent=2))
return res
def main() -> None:
root = Path(sys.argv[1]) if len(sys.argv) > 1 else paths.ROOT
d = build(root)
res = check(root, d)
print(json.dumps(res, indent=1))
if not res["pass"]:
raise SystemExit("cards check failed")
if __name__ == "__main__":
main()