Translate model card and inference comments into English
Browse filesPreserves Traditional Chinese examples, model weights, vocabulary, inference configuration, license, and executable inference logic.
10 unmodified lines1112131415161718192021222324252627282930313233343536373839404142434445464748495 unmodified lines555657585960616263643 unmodified lines6869707172737475767712 unmodified lines909192939495969798991001011024 unmodified lines1071081091101111121131 unmodified line11511611711811912012112212312412512612712812910 unmodified lines- traditional-chinese---# 靈犀注音(0c)D512 選字模型(PF512)注音輸入法的神經選字排序模型。輸入法引擎先給出候選詞,本模型依已確認的前文(最多 64 字)與注音讀音替每個候選算出 log P(候選|前文, 讀音),再和引擎分數合併決定是否改選。這個模型不是獨立的注音轉漢字模型,需要搭配候選來源使用。- 架構:自行訓練的 causal decoder,8 層、hidden 512、8 heads、FFN 768,從零預訓練,再做候選排序微調- 格式:ONNX(opset 18),CPU 推論- 字表:27857 字、416 個注音基底(`vocab.json`)## 檔案| 檔案 | 說明 ||---|---|| `model.onnx` | 評分模型,SHA-256 `71af1f0e77b2752cc71cbc04bf19c8e8f2e765662246f766e65a2822bab4e66e` || `vocab.json` | 特殊 token、字表與注音基底,SHA-256 `556dffaffbf4c05211a846dcee55ef735cea68c5754f9bffcc6f9588124172b3` || `manifest.json` | 操作點、限制與檔案雜湊 |## 安裝需要 Python 3.9 以上,只用 CPU。```shpip install onnxruntime numpy huggingface_hub```第一次執行會從 Hugging Face 下載模型(約 130 MB),之後使用本機快取。## 使用下面是完整程式,存成 `rank.py` 就能執行。讀音每個音節一個字串(`ㄍㄨㄥ`、`ㄩㄢˊ`),候選的字數必須等於音節數。- 只有候選、沒有輸入法引擎:用 `rank()` 依模型分數排序,例如從同音詞裡挑最符合前文的一個。- 已經有輸入法引擎:用 `choose()` 把引擎分數和模型分數合併,只在模型夠有把握時改掉引擎首選。```pythonimport json5 unmodified linespath = snapshot_download("Funmula/0c-sequence-d512")manifest = json.load(open(f"{path}/manifest.json", encoding="utf-8"))vocab = json.load(open(f"{path}/vocab.json", encoding="utf-8"))CHARS = {c: i + 8 for i, c in enumerate(vocab["characters"])} # 0–7 是特殊 token,4 = UNKBASES = {b: i + 2 for i, b in enumerate(vocab["bases"])}TONES = {"ˊ": 2, "ˇ": 3, "ˋ": 4, "˙": 5} # 無聲調符號 = 一聲NEUTRAL = set(manifest.get("neutral_tolerant_last", [])) # 句尾助詞常被打成一聲session = ort.InferenceSession(f"{path}/model.onnx", providers=["CPUExecutionProvider"])3 unmodified linesdef log_prob(context, reading, candidate):# [BOS] 前文 [SEP] 讀音×n [OUT] 候選前 n−1 字;回傳 log P(候選 | 前文, 讀音)。head = [1] + [CHARS.get(c, 4) for c in context[-64:]] + [2]sounds = [syllable(s) for s in reading]cand = [CHARS[c] for c in candidate] # 候選含字表外的字時 KeyError,由呼叫��回退n, out = len(cand), len(head) + len(sounds)ids = head + [0] * n + [3] + cand[:-1]bases = [0] * len(head) + [b for b, _ in sounds] + [0] * n12 unmodified liness = log_prob(context, reading, candidate)last = reading[-1]base = last[:-1] if last[-1] in TONES else lastif base in NEUTRAL and last[-1] != "˙": # 最後一個音節另以輕聲評分,取較大者s = max(s, log_prob(context, reading[:-1] + [base + "˙"], candidate))return sdef choose(context, reading, candidates, engine_scores, w=manifest["weight"], tau=manifest["margin"]):# candidates[0] 是輸入法引擎的首選,engine_scores 是引擎給的 log 分數;回傳要採用的候選索引。try:neural = [score(context, reading, c) for c in candidates]except KeyError:4 unmodified linesdef rank(context, reading, candidates):# 沒有輸入法引擎時:只用模型分數排序同音候選,最可能的在前。return sorted(candidates, key=lambda c: score(context, reading, c), reverse=True)1 unmodified lineprint(rank("", ["ㄐㄧㄣ", "ㄊㄧㄢ", "ㄊㄧㄢ", "ㄑㄧˋ", "ㄏㄣˇ", "ㄏㄠˇ"],["金天天氣很好", "今天天氣很好", "今天天器很好"])) # ['今天天氣很好', ...]# 搭配輸入法引擎:candidates[0] 是引擎首選,模型分數夠高才改選candidates = ["公元", "公園"]print(candidates[choose("今天天氣很好我們去", ["ㄍㄨㄥ", "ㄩㄢˊ"], candidates, [-7.0, -7.5])]) # 公園```## 操作點與限制- 合併分數 = 引擎分數 + w × 模型分數,w = 2;只有最高分候選不是引擎首選、且分差大於 τ = 0 才改選- 音節數 2–32、候選數 ≤ 16;前文只用最後 64 字- 候選含字表外的字時整例不改選- 訓練時的候選來自靈犀注音的詞典(`dictionary_sha256 = 517e6c8bb5cbb145c0554edc3cc91c2b55fc753dd42e11194d83f6b0e119aea3`);換成其他引擎時,w 與 τ 需要依該引擎的分數尺度重新校準- 模型輸入也可以把多個候選的共同前綴合成一棵樹一次評分(`mask` 改為祖先遮罩、`target_node`/`target_ids` 多列),分數與逐一評分相同10 unmodified lines1112131415161718192021222324252627282930313233343536373839404142434445464748495051525 unmodified lines585960616263646566673 unmodified lines717273747576777879808112 unmodified lines9495969798991001011021031041051061074 unmodified lines1121131141151161171181 unmodified line12012112212312412512612712812913013113213313413513613713813910 unmodified lines- traditional-chinese---# 0c D512 Zhuyin Candidate Reranker (PF512)A neural candidate reranker for a Traditional Chinese Zhuyin (Bopomofo) input method.Given confirmed preceding text (up to 64 characters), Zhuyin readings, and supplied candidates,the model computes log P(candidate | context, reading). These scores can be combined with an input-method engine'sscores to decide whether to override its default candidate. A candidate source is required; the model does not generate candidates itself.- Architecture: a dedicated causal Transformer decoder, 8 layers, hidden size 512, 8 attention heads, FFN size 768, pretrained from random initialization and then fine-tuned for candidate ranking- Format: ONNX (opset 18), CPU inference- Vocabulary: 27,857 characters and 416 Zhuyin bases (`vocab.json`)## Files| File | Description ||---|---|| `model.onnx` | Candidate scoring model; SHA-256 `71af1f0e77b2752cc71cbc04bf19c8e8f2e765662246f766e65a2822bab4e66e` || `vocab.json` | Special tokens, character vocabulary, and Zhuyin bases; SHA-256 `556dffaffbf4c05211a846dcee55ef735cea68c5754f9bffcc6f9588124172b3` || `manifest.json` | Operating points, input limits, and file hashes |## InstallationRequires Python 3.9 or later. The examples use CPU inference.```shpip install onnxruntime numpy huggingface_hub```The first run downloads the model from Hugging Face (approximately 130 MB). Subsequent runs use the local cache.## UsageSave the complete example below as `rank.py` and run it. Supply one string per Zhuyin syllable(for example, `ㄍㄨㄥ` and `ㄩㄢˊ`). Each candidate must have exactly one character per syllable.- With supplied candidates only: use `rank()` to order homophonic candidates by model score and find the best match for the context.- With an input-method engine: use `choose()` to combine engine and model scores, overriding the engine default only when the required score margin is met.```pythonimport json5 unmodified linespath = snapshot_download("Funmula/0c-sequence-d512")manifest = json.load(open(f"{path}/manifest.json", encoding="utf-8"))vocab = json.load(open(f"{path}/vocab.json", encoding="utf-8"))CHARS = {c: i + 8 for i, c in enumerate(vocab["characters"])} # IDs 0–7 are special tokens; 4 = UNKBASES = {b: i + 2 for i, b in enumerate(vocab["bases"])}TONES = {"ˊ": 2, "ˇ": 3, "ˋ": 4, "˙": 5} # No tone mark = first toneNEUTRAL = set(manifest.get("neutral_tolerant_last", [])) # Final particles are often typed with first tonesession = ort.InferenceSession(f"{path}/model.onnx", providers=["CPUExecutionProvider"])3 unmodified linesdef log_prob(context, reading, candidate):# [BOS] context [SEP] reading×n [OUT] first n−1 candidate characters.# Return log P(candidate | context, reading).head = [1] + [CHARS.get(c, 4) for c in context[-64:]] + [2]sounds = [syllable(s) for s in reading]cand = [CHARS[c] for c in candidate] # Unknown candidate characters raise KeyError for caller fallbackn, out = len(cand), len(head) + len(sounds)ids = head + [0] * n + [3] + cand[:-1]bases = [0] * len(head) + [b for b, _ in sounds] + [0] * n12 unmodified liness = log_prob(context, reading, candidate)last = reading[-1]base = last[:-1] if last[-1] in TONES else lastif base in NEUTRAL and last[-1] != "˙": # Also score the final syllable with neutral tone and keep the higher scores = max(s, log_prob(context, reading[:-1] + [base + "˙"], candidate))return sdef choose(context, reading, candidates, engine_scores, w=manifest["weight"], tau=manifest["margin"]):# candidates[0] is the engine default; engine_scores are engine log scores.# Return the selected candidate index.try:neural = [score(context, reading, c) for c in candidates]except KeyError:4 unmodified linesdef rank(context, reading, candidates):# Rank supplied homophonic candidates by model score alone, highest first.return sorted(candidates, key=lambda c: score(context, reading, c), reverse=True)1 unmodified lineprint(rank("", ["ㄐㄧㄣ", "ㄊㄧㄢ", "ㄊㄧㄢ", "ㄑㄧˋ", "ㄏㄣˇ", "ㄏㄠˇ"],["金天天氣很好", "今天天氣很好", "今天天器很好"])) # ['今天天氣很好', ...]# With an input-method engine, override candidates[0] only when the fused score warrants it.candidates = ["公元", "公園"]print(candidates[choose("今天天氣很好我們去", ["ㄍㄨㄥ", "ㄩㄢˊ"], candidates, [-7.0, -7.5])]) # 公園```## Operating Points and Limitations- Fused score = engine score + w × model score, with w = 2. Override only if another candidate has the highest score and exceeds the engine default by more than τ = 0.- Supported operating range: 2–32 syllables, at most 16 candidates, and the last 64 context characters.- If any candidate contains a character outside the vocabulary, `choose()` retains the engine default for the entire case.- Training candidates came from the 0c dictionary (`dictionary_sha256 = 517e6c8bb5cbb145c0554edc3cc91c2b55fc753dd42e11194d83f6b0e119aea3`). Calibrate w and τ again when using a different engine's score scale.- Shared candidate prefixes can also be scored together as a tree, using an ancestor attention mask and multiple `target_node`/`target_ids` rows. Scores match individual candidate scoring.## License and Release ScopeModel weights and the accompanying inference examples are released under the MIT license (see `LICENSE`).This release covers this D512 checkpoint only. Training code and training materials are not included.
README.md+43-33