pdnhan's picture
Upload Arcee-VyLinh int4 ONNX with Android, iOS and Python code
6f60ae1 verified
Raw History Blame Contribute Delete
16.8 kB
#!/usr/bin/env python3
"""Writes the model card for out/<size>/repo, adds the Android, iOS and Python code, and uploads it to a public
Hugging Face repo, pdnhan/<name>-mobile (see MODELS).
Run export.py and validate.py first (the card quotes out/<size>/validation.json), and the Kotlin and Swift checks
(kotlin/, swift/check/run.sh). Needs a Hugging Face token with write access (hf auth login).
Usage:
.venv/bin/python -I publish.py [--size 1.5B VyLinh-3B] [--owner pdnhan] [--dry-run]
"""
import argparse
import hashlib
import json
import shutil
import sys
from pathlib import Path
from string import Template
from huggingface_hub import HfApi
sys.path.insert(0, str(Path(__file__).resolve().parent)) # -I drops the script's own directory
from common import HERE, SIZES, out_dir # noqa: E402
SCRIPTS = ("export.py", "asr_hyps.py", "validate.py", "publish.py", "common.py", "qwen_refine.py", "README.md")
# The 1.5B model is Apache 2.0, the license of the original Qwen2.5-1.5B-Instruct model.
LICENSES = {
"1.5B": "license: apache-2.0\nlicense_link: https://huggingface.co/Qwen/Qwen2.5-1.5B-Instruct/blob/main/LICENSE",
"VyLinh-3B": "license: apache-2.0\nlicense_link: https://huggingface.co/arcee-ai/Arcee-VyLinh",
}
LICENSE_TEXT = {
"1.5B": "Apache 2.0, the license of the original model (see [`LICENSE`](LICENSE)); the code in this repo is "
"shared under the same license.",
# The license Arcee AI publishes Arcee-VyLinh under.
"VyLinh-3B": "Apache 2.0, the license [Arcee AI](https://huggingface.co/arcee-ai) publishes "
"[arcee-ai/Arcee-VyLinh](https://huggingface.co/arcee-ai/Arcee-VyLinh) under (see [`LICENSE`](LICENSE)); "
"the code in this repo is shared under the same license.",
}
# Per model: the Hugging Face repo it comes from, the name of the published repo (pdnhan/<name>-mobile), the
# card's base_model list, extra tags and who the credit goes to.
MODELS = {
"1.5B": {
"source": "Qwen/Qwen2.5-1.5B-Instruct",
"name": "Qwen2.5-1.5B-Instruct",
"base_models": "base_model: Qwen/Qwen2.5-1.5B-Instruct",
"tags": "",
"credit": "All credit for the model goes to the [Qwen team](https://huggingface.co/Qwen) (Built with Qwen).",
},
"VyLinh-3B": {
"source": "arcee-ai/Arcee-VyLinh",
"name": "Arcee-VyLinh",
"base_models": "base_model:\n- arcee-ai/Arcee-VyLinh",
"tags": "- vylinh\n",
"credit": "All credit for the model goes to [Arcee AI](https://huggingface.co/arcee-ai), "
"[qnguyen3](https://huggingface.co/qnguyen3) and the [Qwen team](https://huggingface.co/Qwen) "
"(Built with Qwen).",
},
}
CARD = Template("""---
$license
language:
- vi
- en
- zh
- multilingual
$base_models
pipeline_tag: text-generation
library_name: onnxruntime
tags:
- qwen2.5
$extra_tags- onnx
- int4
- android
- ios
- on-device
- speech-recognition-post-processing
- punctuation-restoration
- vietnamese
---
# $name for mobile (ONNX, int4)
[$source](https://huggingface.co/$source) converted to a 4-bit ONNX model
that [ONNX Runtime](https://onnxruntime.ai) runs on **Android** and **iOS**, with ready-to-use Kotlin and Swift
code: the Qwen tokenizer, the generation loop with a KV cache, and a **speech-transcript refiner** for Vietnamese.
The refiner turns raw speech-recognition output (for example [PhoWhisper](https://huggingface.co/vinai/PhoWhisper-small))
into clean written text: it adds punctuation and capitals, fixes misheard words from context, removes fillers and
stutters, writes numbers in digits, dates as day/month/year (`20/11/2026`) and units as symbols (`5 kg`), and writes
spoken lists as bullet points. It is what the Thì Thầm app runs after PhoWhisper.
| Transcript | Refined |
|---|---|
$examples
The weights are those of the original model; only the format and the precision differ.
## Files
| File | What | Size | SHA-256 |
|---|---|---|---|
$files
Mobile apps download `onnx/model.onnx`, `onnx/model.onnx.data`, `onnx/genai_config.json`, `vocab.txt` and
`merges.txt` (about $app_mb MB in total) and use the code in [`android/`](android) or [`ios/`](ios).
- `onnx/model.onnx` + `onnx/model.onnx.data`: built with the
[ONNX Runtime GenAI model builder](https://github.com/microsoft/onnxruntime-genai) (`-p int4 -e cpu`):
`GroupQueryAttention` with a KV cache, 4-bit `MatMulNBits` (symmetric, blocks of 32, `accuracy_level` 4) and the
tied embedding as a 4-bit `GatherBlockQuantized` shared with the LM head, which only computes the last
position's logits. Plain ONNX Runtime (1.22 or newer; tested with 1.31.1) runs it; the folder also works as is
with ONNX Runtime GenAI.
- `vocab.txt`: the byte-level BPE vocabulary, one token per line, line number = token id (special tokens included).
- `merges.txt`: the BPE merges, one `a b` pair per line, by rank.
- `onnx/tokenizer.json`, `onnx/tokenizer_config.json`, `onnx/chat_template.jinja`: the original tokenizer files,
for Python and ONNX Runtime GenAI.
## Model interface
| | Name | Type | Shape |
|---|---|---|---|
| input | `input_ids` | int64 | `[batch, tokens]` |
| input | `attention_mask` | int64 | `[batch, past + tokens]`: 1 for every token so far |
| input | `past_key_values.{0..$last_layer}.key` / `.value` | float32 | `[batch, $kv_heads, past, $head_size]` (`past` = 0 for the first run) |
| output | `logits` | float32 | `[batch, 1, 151936]`: next-token scores after the last input token |
| output | `present.{0..$last_layer}.key` / `.value` | float32 | `[batch, $kv_heads, past + tokens, $head_size]`: the next run's `past_key_values` |
## Accuracy of the refiner
On $transcripts PhoWhisper transcripts of [FLEURS](https://huggingface.co/datasets/google/fleurs) Vietnamese test
clips (the first 150 clips, transcribed by the int8 PhoWhisper tiny and small models of
[pdnhan/PhoWhisper-small-mobile](https://huggingface.co/pdnhan/PhoWhisper-small-mobile) and its siblings),
against the original transcriptions:
| Recognizer | Word error rate of the transcript | after the refiner |
|---|---|---|
$wer_rows
Word error rate is measured case- and punctuation-insensitively; FLEURS writes numbers as both digits and words,
so a number the refiner writes in digits can count as an error. Punctuation (`. , ? ! :` on the words both texts
share): precision $precision, recall $recall, F1 **$f1**. Time per transcript on an x86 desktop CPU (8 threads):
$seconds s; phones are several times slower.
The tokenizer gives the same ids as Hugging Face `tokenizers` on all $tok_texts test texts, and the prompt is
token for token the model's own chat template. The Kotlin code (JVM, ONNX Runtime 1.31.1) and the Swift code give
the same text as the Python reference on the test cases.
## How the refiner works
[`python/qwen_refine.py`](python/qwen_refine.py) is the readable reference (numpy, onnxruntime and `regex`); the
Kotlin and Swift code follow it step by step.
1. **Tokenizer**: NFC, Qwen2's pre-tokenizer regex, byte-level BPE. Special tokens are never parsed from the
transcript: the prompt inserts their ids, so a transcript cannot start a new chat turn.
2. **Numbers**: spoken numbers of two or more words are written in digits (`hai nghìn không trăm hai mươi sáu`
→ `2026`), then dates, decimals, percentages, units and phone numbers the Vietnamese way (`ngày 20/11/2026`,
`tháng 4/2025`, `3,2`, `20%`, `12 km`, `0912345678`, `2 phòng`), only where the words can mean nothing else. A
small model adds numbers up wrong far more often than it copies digits.
3. **Prompt**: a system message and four example turns (fillers, a spoken list with a decimal and a unit, a
question with a date that must not be answered, misheard words and a percentage, unknown names kept). They are
the same for every transcript, so their KV cache is computed once when the model loads.
4. **Decoding**: greedy, until `<|im_end|>`, at most 1.5 × the transcript's tokens + 32.
5. **Merge**: small models reword, drop words and "correct" names they do not know. The output is aligned word by
word with the transcript (longest common subsequence) and only trusted edits are kept: punctuation, capitals,
line breaks and bullets; fillers (`ờ`, `ừm`, …), stutters (`tôi tôi`) and list markers (`thứ hai là`) left
out; a word replaced by a similar-sounding one (`hà lội` → `Hà Nội`, `thể giục` → `thể dục`: gi/d/r, tr/ch
and x/s count as the same sound, then at most one letter apart, two when both words are long, ignoring tone
marks); a spoken number written in digits with the same value, Vietnamese style
(`2.300.000`, `3,5`, `20%` for `phần trăm`, `0912345678`, `ngày 20/11/2026`, `tháng 4/2025`); a spoken unit
written as its symbol right after a number (`ki lô gam` → `kg`, `mét vuông` → `m²`, `độ c` → `°C`). Anything
else is undone with the transcript's own words, and when less than half of them come through (the model
answered instead of correcting) the transcript is kept as it is. Last, hesitation sounds the model kept (`ờ`, `ừm`) are left out
and a yes/no question the model closed with a full stop
(`có … không`, `được không`, `đã … chưa`) gets a question mark.
## Android (Kotlin)
Copy [`android/QwenRefiner.kt`](android/QwenRefiner.kt) into the app. It uses only the Kotlin standard library
and the ONNX Runtime Java API.
```kotlin
// build.gradle.kts: implementation("com.microsoft.onnxruntime:onnxruntime-android:1.22.0") or newer
// dir: a directory with vocab.txt, merges.txt, onnx/genai_config.json, onnx/model.onnx, onnx/model.onnx.data
val refiner = QwenRefiner.load(dir, threads = 4) // keep one instance: loading takes a few seconds
val text = refiner.refine("thủ tướng phạm minh chính đã tiếp bộ trưởng nông nghiệp mỹ tại hà lội vào sáng nay")
// "Thủ tướng Phạm Minh Chính đã tiếp Bộ trưởng Nông nghiệp Mỹ tại Hà Nội vào sáng nay."
```
Call `refine` off the main thread. The model needs about $ram_gb GB of RAM while it runs.
## iOS (Swift)
Add the Swift package in [`ios/`](ios) (it depends on
[onnxruntime-swift-package-manager](https://github.com/microsoft/onnxruntime-swift-package-manager)), or copy
`ios/Sources/QwenRefiner/*.swift` into an app that already uses ONNX Runtime (SPM module `OnnxRuntimeBindings` or
CocoaPods `onnxruntime-objc`, 1.22 or newer).
```swift
import QwenRefiner
let refiner = try QwenRefiner(directory: dir, threads: 4)
let text = try refiner.refine("thủ tướng phạm minh chính đã tiếp bộ trưởng nông nghiệp mỹ tại hà lội vào sáng nay")
```
The Swift code was compiled and checked on Linux (Swift 6.0) against a stand-in for the ONNX Runtime module that
replays the Python reference's generated tokens, not yet on an iPhone.
## Python
```python
from huggingface_hub import snapshot_download
import sys
repo = snapshot_download("$repo_id")
sys.path.insert(0, f"{repo}/python")
from qwen_refine import Refiner # numpy, onnxruntime>=1.22, regex
refiner = Refiner(repo)
print(refiner.refine("bạn có biết mấy giờ rồi không")) # Bạn có biết mấy giờ rồi không?
```
## How it was made
The scripts are in [`scripts/`](scripts): `export.py` runs the ONNX Runtime GenAI model builder and writes the
tokenizer files, `asr_hyps.py` transcribes the FLEURS clips with PhoWhisper, `validate.py` checks the tokenizer and
the prompt and measures the table above. The Kotlin and Swift checks are in `scripts/kotlin` and
`scripts/swift-check`.
## License and credit
Changes by ITGRATE Vietnam: the original weights were converted to ONNX and quantized to 4-bit (int4); nothing else in the model was changed. $license_text $credit
FLEURS (CC BY 4.0) and PhoWhisper (BSD-3-Clause) were used for evaluation only.
""")
DESCRIPTIONS = {
"onnx/model.onnx": "int4 model graph",
"onnx/model.onnx.data": "int4 weights",
"onnx/genai_config.json": "model settings",
"vocab.txt": "tokenizer vocabulary",
"merges.txt": "tokenizer merges",
"onnx/tokenizer.json": "tokenizer for Python",
}
APP_FILES = ("onnx/model.onnx", "onnx/model.onnx.data", "onnx/genai_config.json", "vocab.txt", "merges.txt")
def sha256(path: Path) -> str:
digest = hashlib.sha256()
with open(path, "rb") as f:
for chunk in iter(lambda: f.read(1 << 20), b""):
digest.update(chunk)
return digest.hexdigest()
def file_rows(repo: Path) -> str:
rows = []
for name, what in DESCRIPTIONS.items():
size = (repo / name).stat().st_size
size = f"{size / 1e6:,.1f} MB" if size >= 1e6 else f"{size / 1e3:,.1f} kB"
rows.append(f"| `{name}` | {what} | {size} | `{sha256(repo / name)}` |")
return "\n".join(rows)
def copy_code(repo: Path) -> None:
"""Android, iOS and Python code, and the scripts that made and checked the files."""
for name in ("android", "ios", "python", "scripts"):
shutil.rmtree(repo / name, ignore_errors=True)
(repo / "android").mkdir()
shutil.copy2(HERE / "kotlin/src/main/kotlin/QwenRefiner.kt", repo / "android/QwenRefiner.kt")
shutil.copytree(HERE / "swift", repo / "ios", ignore=shutil.ignore_patterns("check", ".build"))
(repo / "python").mkdir()
shutil.copy2(HERE / "qwen_refine.py", repo / "python/qwen_refine.py")
(repo / "scripts").mkdir()
for name in SCRIPTS:
shutil.copy2(HERE / name, repo / "scripts" / name)
shutil.copytree(HERE / "kotlin", repo / "scripts/kotlin", ignore=shutil.ignore_patterns("build", ".gradle", ".kotlin"))
shutil.copytree(HERE / "swift/check", repo / "scripts/swift-check")
def table_cell(text: str) -> str:
return text.replace("|", "\\|").replace("\n", "<br>")
def write_card(size: str, repo: Path, repo_id: str) -> None:
report = json.loads((out_dir(size).parent / "validation.json").read_text(encoding="utf-8"))
decoder = json.loads((repo / "onnx/genai_config.json").read_text())["model"]["decoder"]
names = {"tiny": "PhoWhisper tiny (int8)", "small": "PhoWhisper small (int8)"}
wer_rows = "\n".join(
f"| {names.get(asr, asr)} | {w['wer_before']:.1%} | {w['wer_after']:.1%} |" for asr, w in report["wer"].items()
)
examples = "\n".join(
f"| {table_cell(e['input'])} | {table_cell(e['output'])} |" for e in report["examples"][:6]
)
weights = (repo / "onnx/model.onnx.data").stat().st_size
(repo / "README.md").write_text(
CARD.substitute(
license=LICENSES[size],
license_text=LICENSE_TEXT[size],
name=MODELS[size]["name"],
source=MODELS[size]["source"],
base_models=MODELS[size]["base_models"],
credit=MODELS[size]["credit"],
extra_tags=MODELS[size]["tags"],
repo_id=repo_id,
examples=examples,
files=file_rows(repo),
app_mb=round(sum((repo / f).stat().st_size for f in APP_FILES) / 1e6),
last_layer=decoder["num_hidden_layers"] - 1,
kv_heads=decoder["num_key_value_heads"],
head_size=decoder["head_size"],
transcripts=report["transcripts"],
wer_rows=wer_rows,
precision=f"{report['punctuation']['precision']:.2f}",
recall=f"{report['punctuation']['recall']:.2f}",
f1=f"{report['punctuation']['f1']:.2f}",
seconds=report["seconds_per_transcript"],
tok_texts=report["tokenizer"]["texts"],
ram_gb=f"{weights * 1.3 / 1e9:.1f}",
),
encoding="utf-8",
)
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--size", choices=SIZES, nargs="+", default=list(SIZES))
parser.add_argument("--owner", default="pdnhan")
parser.add_argument("--dry-run", action="store_true", help="write README.md and copy the code only")
args = parser.parse_args()
api = HfApi()
for size in args.size:
repo = out_dir(size)
if not (repo.parent / "validation.json").exists():
sys.exit(f"error: run validate.py --size {size} first")
name = MODELS[size]["name"]
repo_id = f"{args.owner}/{name}-mobile"
copy_code(repo)
write_card(size, repo, repo_id)
print(f"wrote {repo / 'README.md'}")
if args.dry_run:
continue
api.create_repo(repo_id, repo_type="model", private=False, exist_ok=True)
api.upload_folder(repo_id=repo_id, repo_type="model", folder_path=repo, ignore_patterns=[".cache/**"],
commit_message=f"Upload {name} int4 ONNX with Android, iOS and Python code")
print(f"published https://huggingface.co/{repo_id}")
if __name__ == "__main__":
main()