A Chinese / English input-method model of Zhiyi IME in about 10 MB, for phones: 8 ModernBERT layers of width 256 with a 32,000-token vocabulary, weights in 4 bits. It does two things:
你的作业|了吗, "your homework | yet?").It is zhen-mini-next-preview (itself zh-lite-next-preview made small) fine-tuned for mid-text completion; the same file layout and inputs, new weights. A preview: Zhiyi IME does not use it yet. The GitHub release model-zhen-mini-next-preview-1116 has the same files, and its release notes have every test result. All Zhiyi models: https://github.com/dd1000001000/zhiyi_models
| File | |
|---|---|
model.safetensors |
all weights, already 4-bit (10.1 MB): 54 matrices as ggml Q4_0 blocks, the rest F32 |
config.json |
the structure (with encoder.layer_types), prefix_mask, shared_head, compact, choice_only, next_word_decoder, special tokens, sequence settings, ml, next_word (the decoder, rows_are_tokens), vocab_size and q4_0: each 4-bit tensor's [rows, columns] |
next_rows.json |
per token: its piece and text, the mode masks (zh, en_start, en_cont), the end token, characters per token |
tokenizer.json |
the 32k Unigram tokenizer: context, tags, typed text |
tokenizer.candidates.json |
the same with Metaspace prepend_scheme never: candidates, Chinese and English (no leading ▁) |
unified_vocab.json |
the units and letters of the typed slots (its character tables are not used) |
test_vectors.safetensors |
13 word-choice and 12 next-word inputs (4 of them mid-text) with the fp32 PyTorch model's outputs, to check an implementation |
candle_ref/ |
a reference forward pass in Rust (candle 0.11), version 0.7.0: reads the 4-bit file |
onnx/w4/ |
laya.mini.w4.onnx (12.2 MB, word choice and next words in one file: opset 21 + com.microsoft MatMulNBits / GatherBlockQuantized), with both tokenizers and the JSON files |
onnx/slim/ |
the same file in 10.4 MB (laya.mini.w4.onnx: the head's in-projection 4-bit too, scales float16); same inputs and outputs |
example.py |
the quick start below |
LICENSE |
Apache License 2.0 |
Word choice, next words and mid-text with onnx/w4/laya.mini.w4.onnx (the code is in example.py):
pip install onnxruntime tokenizers numpy huggingface_hub
python example.py
D = os.path.join(snapshot_download("zhiyi-ime/zhiyi-zhen-mini", allow_patterns=["onnx/w4/*"]), "onnx", "w4")
tok = Tokenizer.from_file(os.path.join(D, "tokenizer.json")) # context, tags, typed text
ctok = Tokenizer.from_file(os.path.join(D, "tokenizer.candidates.json")) # candidates (no leading ▁)
BOS, EOS, MASK = 2, 1, 4
# 1. Word choice: <bos> context <eos> <mask> x syllables <eos> cand1 cand2 ... <eos>; one score per candidate
# (context mode on the leading block, then key mode on the rest with that cache)
print(choose("今天天气很好,我们去公园", ["san", "bu"], ["散步", "散布", "三部"]))
# 2. Next words: context mode once (cross_k_out / cross_v_out), then is_step in a beam search over the 32k tokens
print(next_words("今天天气很好,我们一起去"))
print(next_words("Thank you very much for your", lang="en"))
print(next_words("我们明天去公", min_chars=1)) # completion: the typed start of the word ends the context
print(next_words("你的作业", right="了吗")) # mid-text: <bos> left <mask> right <eos>
Output (ONNX Runtime 1.24.4, CPU):
[('散步', 2.92...), ('散布', -4.90...), ('三部', -6.74...)]
[('看看', -2.42...), ('学习', -2.76...), ('参加', -2.78...), ('旅游', -3.35...), ('旅行', -3.79...)]
[('support', -3.20...), ('work', -3.28...), ('job', -3.62...), ('inspiration', -3.80...), ('future', -4.06...)]
[('司', -0.90...), ('园', -1.71...), ('路', -2.84...), ('开', -3.00...), ('交', -3.79...)]
[('开始', -3.56...), ('作文', -4.01...), ('记录', -4.05...), ('成功', -4.11...), ('工作', -4.14...)]
The calls build the inputs of test_vectors.safetensors cases 0, next0, next5, next7 and next8 (token for
token); the 4-bit file's words differ a little from the vectors' fp32 ones (next0: the same 5 words, 参加 third
instead of first). Traditional rows add the tag <zh-Hant> after <bos> and the typed text instead of <mask> units
(see "Inputs"). For the slim file, change onnx/w4 to onnx/slim in example.py (the file names are the same).
The bool input is_step picks the branch (an If node runs only that one). Every input has a small default, so ONNX
Runtime lists them as overridable initializers, not as graph inputs (get_overridable_initializers()); feed them by
name and leave out what the branch does not use.
is_step false (the default), word choice: input_ids, unit_ids, past_enc_k / past_enc_v
(8 × 1 × 4 × P × 64), past_choice_k / past_choice_v (1 × 1 × 4 × P × 64) with past_mask, marker_pos →
logits, present_0 … present_3 (the encoder's and the head's keys and values), cross_k_out / cross_v_out.
Context mode (the leading block <bos> … <eos>, no past) gives the cache; key mode (the rest, the cache as the past)
gives the scores, with marker_pos counted from the start of the rest.<bos> context[last 128 tokens] <eos> (mid-text:
<bos> left <mask> right[first 32 tokens] <eos>) with unit ids 0 → cross_k_out, cross_v_out
(2 × 1 × 4 × T × 64), the decoder's cross-attention keys and values. In an input method this is the context pass
word choice already runs, when the contexts are the same.is_step true, one next-word step for N hypotheses: prev (N, the previous token; any value at position 0),
pos (N), dec_past_k / dec_past_v (2 × N × 4 × P × 64) with dec_past_mask (N × P; at position 0 a placeholder
of length 1, false), cross_k / cross_v (2 × N × 4 × T × 64, one copy per hypothesis) with cross_mask (N × T)
→ logits (N × 32,000, one per token), present_0 / present_1 = the decoder's keys and values with this step
appended.Speed (ONNX Runtime 1.24.4, CPU, AMD Ryzen 5 9600X; the search loop around the graph not counted): word choice 4.9 ms
once per context and 2.4 ms a key on 4 threads (9.4 / 3.9 ms on 1), about 40 MB of memory loaded and 50 MB running
(measured on zhen-mini-next-preview's laya.mini.w4.onnx, the same graph); a whole next-word prediction with the slim
file 5.7 ms on 4 threads (12.4 ms on 1), with a right side 5.9 ms (12.6 ms).
One RTX 5070 Ti.
A tensor listed in config.json q4_0 is stored as ggml's Q4_0 blocks: dtype U8, shape rows × (columns / 32 × 18).
Each block of 32 values along a row is 18 bytes: an f16 scale d (little-endian), then 16 bytes q; value j
(0…15) is ((q[j] & 15) − 8) · d, value j + 16 is ((q[j] >> 4) − 8) · d. This is the layout candle's
qtensor_from_ggml(GgmlDType::Q4_0, …) (and llama.cpp) read, so a linear layer runs as a 4-bit matrix product:
use candle_core::quantized::{ggml_file::qtensor_from_ggml, GgmlDType, QMatMul};
let raw = safetensors.load(name, &device)?.flatten_all()?.to_vec1::<u8>()?;
let w = QMatMul::from_qtensor(qtensor_from_ggml(GgmlDType::Q4_0, &raw, vec![rows, cols], &device)?)?;
// w.forward(&x) = x · wᵀ, then add the bias if the layer has one
The 4-bit tensors: every linear weight of the encoder, the head and the decoder, scorer.1, and the two embedding
tables encoder.embeddings.tok_embeddings.weight (32000 × 256) and unit_emb.weight (3833 × 256), whose rows are
unpacked when read. The token table is also the read-out: keep it as a Q4_0 matrix for x · tableᵀ and unpack only
the rows a lookup needs (one copy in memory). Everything else (norms, biases, type_emb, tone_emb, cand_emb,
next.start, next.pos.weight, next.bias, scorer.3) is F32.
Names are the PyTorch ones.
| Tensor | Shape | |
|---|---|---|
encoder.embeddings.tok_embeddings.weight |
32000 × 256 | Q4_0; token id = row |
encoder.embeddings.norm.weight |
256 | LayerNorm, no bias |
encoder.layers.N.attn_norm.weight (N ≥ 1; layer 0 has none) |
256 | |
encoder.layers.N.attn.Wqkv.weight |
768 × 256 | N = 0…7, Q4_0 |
encoder.layers.N.attn.Wo.weight |
256 × 256 | Q4_0 |
encoder.layers.N.mlp_norm.weight |
256 | |
encoder.layers.N.mlp.Wi.weight |
1024 × 256 | Q4_0 |
encoder.layers.N.mlp.Wo.weight |
256 × 512 | Q4_0 |
encoder.final_norm.weight |
256 | |
unit_emb.weight |
3833 × 256 | Q4_0; row 0 = none, 1-3804 the units of unified_vocab.json, 3805-3832 letters |
tone_emb.weight |
6 × 256 | Zhuyin tones: row 0 = none, 1-5 (5 = neutral) |
type_emb.weight |
3 × 256 | row 0 is the one used (word choice and the decoder's memory) |
cand_emb |
256 | added at each candidate's first token |
head.layers.0.* |
one nn.TransformerEncoderLayer (matrices Q4_0) |
|
scorer.0 (LayerNorm), scorer.1 (256 → 256), scorer.3 (256 → 1) |
word choice | |
next.mem_in.0 (256 → 256), next.mem_in.1 (LayerNorm) |
the decoder's memory | |
next.tok_in (256 → 256) |
a token's embedding → the decoder's input | |
next.start |
256 | the input at position 0 |
next.pos.weight |
22 × 256 | learned positions |
next.layers.N.* (N = 0, 1) |
nn.TransformerDecoderLayer: self_attn, multihead_attn (in_proj_weight = q, k, v stacked, 768 × 256), linear1 (256 → 1024), linear2, norm1-norm3 |
|
next.out.0 (LayerNorm), next.out.1 (256 → 256) |
the decoder's output | |
next.bias |
32000 | the read-out's bias, per token |
One sequence at a time (batch 1, no padding; with padding, mask padded keys in every attention).
The prefix mask. Let n be the position of the first <eos> (1) plus one: positions 0 … n−1 are the
leading block. A query inside the block may attend only to keys inside it; a query after it attends to every key
(within the sliding window where the layer has one). This holds in every encoder layer and in the head layer.
x = tok_emb[input_ids] + unit_emb[unit_ids % 3833] + tone_emb[unit_ids / 3833], plus cand_emb at every
position in marker_pos (each candidate's first token), then LayerNorm (encoder.embeddings.norm).h = attn_norm(x) (layer 0: h = x); q, k, v = split(Wqkv h), laid out as (3, heads, 64).x·cos + rotate_half(x)·sin, frequencies
1 / 160000^(2i/64), positions 0, 1, 2, ….config.json encoder.layer_types gives each layer's kind:
layers 0, 2, 4 and 7 attend globally (full_attention), the others only where |i − j| ≤ 64
(sliding_attention).x += Wo(attention); then a, g = split(Wi mlp_norm(x)) (512 each), x += mlp.Wo(gelu(a) · g), with the
exact (erf) GELU.final_norm. No biases anywhere in the encoder.h0 = encoder output + type_emb[0], then head.layers.0 (PyTorch nn.TransformerEncoderLayer,
norm_first=True, 4 heads, feed-forward 1024 with ReLU, LayerNorm eps 1e-5, in_proj_weight = q, k, v stacked;
no final norm), with the prefix mask.p, score = scorer.3(gelu(scorer.1(scorer.0(h0[p])))).
Higher is better.Caching the context. Run the block alone once per context and keep each layer's keys and values (after RoPE)
for its n positions; on each key run only the positions after it (the ONNX file's context and key modes).
<bos> encode(context)[last 128 tokens] <eos> (English: the context's trailing spaces cut
first) with the encoder above (unit ids 0; one prefix block, so the plain mask with the sliding window).
m = LayerNorm(next.mem_in.0(encoder output + type_emb[0])), (T, 256). Each decoder layer's cross-attention keys
and values are m through rows 256-511 and 512-767 of its multihead_attn.in_proj_weight (and bias): compute
them once per context.
Mid-text: <bos> encode(left)[last tokens] <mask> encode(right)[first 32 tokens] <eos>, the whole block at most
130 tokens (the left side gives way): the same encoder pass and memory, the gap marked by <mask> (a context never
holds one: replace <mask> in the text by a space first). Encode the right side on its own; English: cut the left
side's trailing spaces as before.next.start; position j ≥ 1 is next.tok_in(tok_emb[t_j]), t_j the token written
at step j; plus next.pos.weight[j].nn.TransformerDecoderLayer, norm_first=True, 4 heads of 64, LayerNorm eps 1e-5, no
dropout): x += self_attn(norm1(x)) with a causal mask; x += multihead_attn(norm2(x), memory) (all context
positions); x += linear2(relu(linear1(norm3(x)))). Attention scale 1/8.logits = next.out.1(next.out.0(x)) · tok_embᵀ + next.bias over the 32,000 tokens. A cache of each
layer's self-attention keys and values makes a step cost one position.Search (as example.py and candle_ref): beam 8, k = 5 words, at most 6 tokens a word.
zh tokens (Simplified Han) and the end (<eos>, next_rows.json end);
English mode en_start at the first token, then en_cont or the end. The others get −10⁹ before the log-softmax.next_rows.json text_zh / text_en;
English stripped), kept if it has at least 2 characters (completion: 1); hypotheses writing the same text are summed
(log-sum-exp).Token ids are tokenizer.json's, with <bos> (2) as [CLS], <eos> (1) as [SEP], <mask> (4). The context, a tag
and the typed text are encoded with tokenizer.json; candidates with tokenizer.candidates.json (no ▁, English
ones too), each cut to 16 tokens. Encode without special tokens. A Traditional row starts with the tag <zh-Hant> as
plain text; Simplified Chinese and English have no tag. Characters outside the 32k tokens fall back to UTF-8 bytes
(<0x..> tokens).
word choice, Simplified (pinyin) <bos> encode(context)[last 128] <eos> <mask> × typed units <eos> cand(候选1)[:16] cand(候选2)[:16] … <eos>
word choice, Traditional <bos> encode("<zh-Hant>") encode(context)[last 128] <eos> encode(typed text)[:24] <eos> cand(候選1)[:16] … <eos>
word choice, English as Simplified, one <mask> a typed letter (its letter unit)
next word <bos> encode(context)[last 128] <eos>
next word, mid-text <bos> encode(left) <mask> encode(right)[:32] <eos>
marker_pos lists the position of each candidate's first token. Each <mask> of the typed units carries its unit in
unit_ids (unified_vocab.json units: f:san = the full syllable san, p:s = typed only partly); the other
positions have unit 0.
test_vectors.safetensors holds, for word-choice case i = 0…12, i.input_ids, i.unit_ids, i.marker_pos
(int64) and the fp32 PyTorch model's i.logits (cases 0-4 Simplified Chinese, 5-12 the first row of each Traditional
test file); for next-word case nextN, N = 0…11, nextN.input_ids (<bos> context <eos>; cases 8-11 mid-text,
<bos> left <mask> right <eos>), nextN.mode (0 Chinese, 1 English), nextN.min_chars and the fp32 model's 5 words
nextN.text (UTF-8, one word a line) with nextN.logp.
The model alone, not the IME end to end. fp32 = the PyTorch model before rounding; 4-bit ONNX = the slim
onnx/slim/laya.mini.w4.onnx (ONNX Runtime 1.24.4); Q4_0 = this file with candle_ref.
Word choice, first candidate right: every third row of the Simplified Chinese sets and the first 200 rows of each Traditional test file.
| Word choice | fp32 | 4-bit ONNX | Q4_0 (candle_ref) |
Q4_0's best = fp32's |
|---|---|---|---|---|
| Simplified Chinese, words and word pairs (2175) | 87.5% | 87.3% | 87.2% | 97.7% |
| Simplified Chinese, long input (749) | 81.2% | 81.0% | 81.0% | 97.2% |
| Simplified Chinese, IME's real candidates (right word among them) (545) | 89.5% | 88.8% | 88.8% | 98.3% |
| Simplified Chinese homophones with the previous sentence (267) | 93.3% | 92.5% | 92.5% | 98.1% |
| Traditional, pinyin (luna_pinyin) (200) | 83.0% | 81.5% | 81.5% | 97.0% |
| Traditional, Zhuyin (bopomofo_tw) (200) | 85.0% | 86.5% | 86.5% | 97.5% |
| Traditional, Zhuyin (libchewing) (200) | 93.5% | 93.0% | 93.0% | 98.0% |
| Traditional, Jyutping (jyut6ping3) (200) | 85.0% | 85.5% | 85.0% | 97.0% |
| Traditional, Cangjie 5 (200) | 94.0% | 94.0% | 94.0% | 100.0% |
| Traditional, Quick 5 (200) | 90.5% | 93.0% | 92.5% | 97.5% |
| Traditional, Cangjie 3 (200) | 80.5% | 79.0% | 79.0% | 94.0% |
| Traditional, Quick 3 (200) | 73.5% | 74.0% | 74.0% | 97.0% |
Next word: the text's next word first (@1) / among the 5 words (@5), the model alone (no n-gram), beam 8; the first 200 rows of the Chinese and English next-word test sets, the first 100 mid-text rows of each (the rows whose text goes on after the word, that text as the right side) and 100 Chinese words cut after their first characters (completion). Small sets: a row is half a point or a whole one.
| Next word | fp32 | 4-bit ONNX | Q4_0 (candle_ref) |
Q4_0's first word = fp32's |
|---|---|---|---|---|
| Simplified Chinese (200) | 11.0 / 21.5% | 10.0 / 22.0% | 10.0 / 22.0% | 70.5% |
| English (200) | 15.0 / 32.0% | 17.5 / 31.0% | 17.5 / 31.5% | 81.5% |
| Chinese mid-text (100) | 13.0 / 27.0% | 13.0 / 25.0% | 13.0 / 24.0% | 75.0% |
| English mid-text (100) | 18.0 / 37.0% | 13.0 / 38.0% | 13.0 / 37.0% | 81.0% |
| Chinese completion (100) | 42.0 / 62.0% | 42.0 / 63.0% | 42.0 / 63.0% | 86.0% |
The 4-bit file and the 4-bit ONNX graph agree with each other almost row for row; against fp32 they move a few scores (word choice: the same best candidate in 94-100% of rows; on the 13 vectors the same best in 13/13, logits within 1.263; next word: the same first word in 7 of the 12 vectors, 3.8 of the 5 words shared on average).
On the full next-word test sets (PyTorch fp32 before 4 bits; mid-text = the test rows whose text goes on after the word, Chinese 4 characters on median, English 23), against zhen-mini-next-preview:
| @1 / @5 | zhen-mini-next-preview | zhen-mini-next-preview-1116 |
|---|---|---|
| Chinese mid-text | 3.0 / 8.0% | 13.4 / 25.6% |
| English mid-text | 4.1 / 12.2% | 24.4 / 43.0% |
| Chinese next word | 11.1 / 21.6% | 11.4 / 21.9% |
| ... with ng1017 | 12.1 / 24.0% | 12.5 / 24.0% |
| English next word | 19.5 / 36.7% | 19.4 / 36.4% |
| ... with a trigram of the training text | 20.0 / 37.7% | 20.7 / 38.7% |
| Chinese completion | 47.3 / 69.9% | 48.5 / 70.1% |
zhen-mini-next-preview never saw a right side, so the gap confuses it; given the left side only it gets 10.9 / 21.2% (Chinese) and 19.5 / 36.7% (English) of the mid-text rows. The teacher (Qwen3-1.7B-Base's words rescored with the right side) gets 37.7 / 53.7% and 60.6 / 77.3%: a model of this size uses the right side only a little.
On the public neutral word-choice test sets (v2, v3 web, v4 chat, v5 hard; PyTorch fp32 before 4 bits, whole page, first candidate right):
| v2 | v3 | v4 | v5 | |
|---|---|---|---|---|
| zhen-mini-next-preview | 93.38% | 93.21% | 91.25% | 70.65% |
| zhen-mini-next-preview-1116 | 93.63% | 93.37% | 91.31% | 70.65% |
candle_ref (loads the file in about 0.1 s):
cd candle_ref
RUSTFLAGS="-C target-cpu=native" cargo build --release
target/release/zhiyi-ref ../model.safetensors ../test_vectors.safetensors out.safetensors
candle's quantized kernels choose their SIMD code at compile time: build with RUSTFLAGS="-C target-cpu=native" (or
at least x86-64-v3). candle_ref is a reference, not a fast runtime: it runs the whole sequence with the mask (no
cache) and reruns the decoder over each hypothesis' prefix at every step; the outputs are those of the cached runs.
Word choice on the public neutral test sets, each model alone (no engine, no n-gram), against the theoretical compute
to score a row: of the Zhiyi models only the four maintained ones are shown, pumpkin
(zhiyi-ml-pumpkin), Flash
(zhiyi-ml-flash), Mini
(zhiyi-zhen-mini) and Feather
(zhiyi-zhen-feather), each scored with its released ONNX file
(this model: onnx/w4/laya.mini.w4.onnx), so the points can differ a little from the numbers above. The other models (the file of each,
its license and how it is run) and the scoring code: https://github.com/dd1000001000/zhiyi_models/tree/main/comparisons/models
These weights are Zhiyi IME's own work and are licensed under the Apache License 2.0 (LICENSE). The reference
code in candle_ref/ is GPL-3.0-only, like Zhiyi IME (https://github.com/dd1000001000/zhiyi_ime/blob/main/LICENSE).
The upstream parts keep their licenses: the Laya architecture (https://huggingface.co/convaiinnovations/laya)
Apache-2.0, the mmBERT-small encoder and tokenizer (Marone et al., 2025; https://huggingface.co/jhu-clsp/mmBERT-small)
MIT (the 32k tokenizer is a subset of its vocabulary).
Teachers (only their scores and words were used; none of their weights are in these files): Qwen3.5-9B (https://huggingface.co/Qwen/Qwen3.5-9B) fine-tuned with LoRA for word choice (ML-pumpkin-1026's Chinese and English word-choice rows) and Qwen3-1.7B-Base (https://huggingface.co/Qwen/Qwen3-1.7B-Base) for next words, both by the Qwen team (Alibaba Cloud), Apache-2.0. Next-word text: Chinese text of C4 (Raffel et al.) and LCCC, English text of FineWeb (CC-MAIN-2025-26) and C4. These programs and data only produced training rows; none of them is in these files.
onnx/w4/laya.mini.w4.onnx 12 MBonnx/slim/laya.mini.w4.onnx 10 MBmodel.safetensors 10 MBtest_vectors.safetensors 25.6 kBjhu-clsp/mmBERT-small