Release frozen D512 ONNX weights under MIT
Browse filesIncludes the cleaned ONNX model, vocabulary, inference manifest, MIT license, and model card with CPU inference examples.
Files changed (5)
- LICENSEAdded+21
- README.mdAdded+129
- manifest.jsonAdded+44
- model.onnxAdded+3
- vocab.jsonAdded
123456789101112131415161718192021MIT License
Copyright (c) 2026 Funmula Corp Limited
Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in allcopies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, 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 THESOFTWARE.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129---license: mitlanguage:- zhlibrary_name: onnxruntimetags:- onnx- bopomofo- zhuyin- input-method- 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 json
import numpy as npimport onnxruntime as ortfrom huggingface_hub import snapshot_download
path = 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"])
def syllable(s): base = s[:-1] if s[-1] in TONES else s return BASES[base], TONES.get(s[-1], 1)
def 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] * n tones = [0] * len(head) + [t for _, t in sounds] + [0] * n types = [0] * len(head) + [1] * n + [0] + [2] * (n - 1) L = len(ids) row = lambda x: np.array([x], dtype=np.int64) feeds = {"ids": row(ids), "bases": row(bases), "tones": row(tones), "types": row(types), "positions": row(list(range(L))), "mask": np.tril(np.ones((L, L), dtype=bool))[None, None], "proj_pos": np.arange(out, L, dtype=np.int64), "target_node": row(list(range(n))), "target_ids": row([x - 6 for x in cand])} return float(session.run(["scores"], feeds)[0][0])
def score(context, reading, candidate): s = log_prob(context, reading, candidate) last = reading[-1] base = last[:-1] if last[-1] in TONES else last if base in NEUTRAL and last[-1] != "˙": # 最後一個音節另以輕聲評分,取較大者 s = max(s, log_prob(context, reading[:-1] + [base + "˙"], candidate)) return s
def 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: return 0 fused = [e + w * s for e, s in zip(engine_scores, neural)] best = max(range(len(fused)), key=fused.__getitem__) return best if best != 0 and fused[best] - fused[0] > tau else 0
def rank(context, reading, candidates): # 沒有輸入法引擎時:只用模型分數排序同音候選,最可能的在前。 return sorted(candidates, key=lambda c: score(context, reading, c), reverse=True)
print(rank("下週就是", ["ㄑㄧˊ", "ㄓㄨㄥ", "ㄎㄠˇ"], ["其中考", "期中考"])) # ['期中考', '其中考']print(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` 多列),分數與逐一評分相同1234567891011121314151617181920212223242526272829303132333435363738394041424344{ "schema": "zuin-sequence-runtime-v1", "context_policy": "confirmed_left_64", "allow_partial": true, "dictionary_sha256": "517e6c8bb5cbb145c0554edc3cc91c2b55fc753dd42e11194d83f6b0e119aea3", "weight": 2.0, "margin": 0.0, "files": { "model.onnx": "71af1f0e77b2752cc71cbc04bf19c8e8f2e765662246f766e65a2822bab4e66e", "vocab.json": "556dffaffbf4c05211a846dcee55ef735cea68c5754f9bffcc6f9588124172b3" }, "spec": { "kind": "decoder", "hidden": 512, "layers": 8, "heads": 8, "intermediate": 768 }, "limits": { "min_syllables": 2, "max_syllables": 32, "max_candidates": 16, "context_runes": 64, "correction": "whole_case_fallback", "unknown_candidate_character": "whole_case_fallback", "text_mode": "single_syllable_with_confirmed_context" }, "hint_gap": 2.0, "text_weight": 2.0, "text_margin": 1.0, "neutral_tolerant_last": [ "ㄅㄚ", "ㄇㄚ", "ㄋㄜ", "ㄌㄚ", "ㄌㄨㄛ", "ㄓㄜ", "ㄚ", "ㄛ", "ㄧㄚ", "ㄧㄝ" ], "neutral_expand_penalty": 4.0}123version https://git-lfs.github.com/spec/v1oid sha256:71af1f0e77b2752cc71cbc04bf19c8e8f2e765662246f766e65a2822bab4e66esize 130723134LICENSEAdded+21
README.mdAdded+129
manifest.jsonAdded+44
model.onnxAdded+3
vocab.jsonAdded