ZygAI-DS / docs /FORMAT.md
ZygAI's picture
ZygAI DS release (bbae783)
d8fd1d0 verified
|
Raw History Blame Contribute Delete
9.13 kB

ZYM model file format (.zym), version 1

One container format for every ZygAI DS model. The DS app reads it with ds-app/source/engine/zym.c; the PC tools write it with training/zym.py.

  • All integers are little-endian (the DS's ARM9 and x86 PCs are both LE).
  • Every section starts on a 4-byte boundary, and every array inside a section is 4-byte aligned. The DS loads the whole file into one malloc buffer and points straight into it, with no copying or unpacking.
  • The file carries a CRC-32 (same as zlib.crc32), so a flaky SD card or a bad copy is caught at load time instead of producing garbage.

File header (64 bytes)

Offset Type Field Notes
0 char[4] magic "ZYGM"
4 u16 version 1
6 u16 model_type 1 char n-gram, 2 char GRU, 3 BPE transformer
8 u32 file_size total bytes; detects truncated copies
12 u32 crc32 CRC-32 of bytes [64, file_size)
16 u16 section_count 1..64
18 u16 header_size 64
20 u32 ram_hint extra runtime RAM the model needs (bytes)
24 char[24] name display name, ASCII, NUL-padded (≤ 23 chars)
48 u8[16] reserved zero

Section table (at offset 64, section_count × 16 bytes)

Offset Type Field
0 char[4] tag
4 u32 offset (from file start, multiple of 4)
8 u32 size (unpadded)
12 u32 reserved

Unknown tags are ignored, so new sections can be added without breaking old apps.

VOCB: vocabulary (character models)

Required for model types 1 and 2. Token models (type 3) have a TOKN section instead.

u16 n_symbols        1..127
u16 reserved
u8  ascii[n_symbols] ASCII code of symbol i (sorted ascending by the trainer)

The vocabulary must contain ' ' and '\n'. Typed characters map to symbols as follows: an exact match wins, then the other letter case, then space. zym_engine_encode() and zym.encode() implement this identically.

META: training metadata (optional)

key=value\n lines in ASCII, e.g. order=24, corpus_sha1=…. Mostly informational. The app reads two keys:

  • default_temp=0.70: the temperature step selected when the model loads (the nearest of the app's steps; L/R still change it).
  • style=story: the model continues text instead of answering. The prompt is fed as the start of a story (no Q:/A: wrapper) and may be empty.

NGRM: character n-gram tree (model_type 1)

A reversed-context tree (a suffix tree of contexts, read backwards):

  • Each node is a context, meaning the last k characters. The root is the empty context (k = 0).
  • The child of context "bc" via symbol 'a' is context "abc", so walking from the root follows the text backwards from the most recent character.
  • Each node stores the distribution of the next character after that context.

Inference walks backwards through the recent characters as far as the tree allows and samples from the deepest node it reaches (longest-match backoff). The tree is suffix-closed, so the walk never has to backtrack.

u8  order            max context length
u8  q_bits           8
u16 flags            0
u32 n_nodes          (N)
u32 n_entries        (E)
u32 reserved
u32 child_off[N+1]   children of node i are nodes child_off[i] .. child_off[i+1]-1
u32 entry_off[N+1]   entries of node i are entry_off[i] .. entry_off[i+1]-1
u8  node_sym[N]      symbol on the edge into node i (root: 0), padded to 4
u8  entry_sym[E]     next-symbol id,                          padded to 4
u8  entry_q[E]       quantized count, 1..255

Nodes are stored breadth-first, and each level is sorted by (parent index, symbol). That is what makes the children of a node contiguous and sorted, so the DS finds a child by binary search. child_off[0] = 1, child_off[N] = N, and every node has at least one entry.

Quantization: within a node, q = max(1, round(255 · count / max_count)), so the most frequent next character always has q = 255.

Pruning (train_ngram.py):

  1. Keep a context only if it occurred at least min_count times and its shorter suffix was kept.
  2. Lossless: drop a leaf whose quantized distribution equals its parent's. Sampling at the parent is then identical. This removes ~90 % of the nodes of an order-24 model.
  3. If the file is still larger than --max-bytes, raise min_count until it fits.

Sampling with temperature T, integers only:

w(q)   = 65536 · (q/255)^(1/T)
       = exp2neg_q16( ((LOG2_Q16[255] - LOG2_Q16[q]) · round(256/T)) >> 8 )
r      = (xorshift32() · Σw) >> 32
pick the first entry where r < cumulative w

LOG2_Q16 and EXP2NEG_Q16 (with linear interpolation) are fixed tables, generated into ds-app/source/engine/zym_tables.h from training/zym.py, so the PC reference and the DS produce bit-identical text for the same seed (verified by tools/test_crosscheck.py).

GRU1: character GRU (model_type 2)

Specified in PHASE2.md.

TOKN: BPE tokenizer (model_type 3)

u16 n_tokens          = vocab size of LLM1
u16 bos, eos          stop tokens (generation ends when one is sampled)
u16 byte_base         token of byte 0x00 (256 byte tokens follow), 0xFFFF = none
u16 flags             bit 0: add a " " token before non-empty text
u16 max_display
u16 n_sorted
u16 reserved
u32 blob_size
i32 score[n_tokens]           merge priority (higher merges first)
u32 piece_off[n_tokens + 1]   into blob: exact bytes used to match text
u32 disp_off[n_tokens + 1]    into blob: ASCII text shown for the token
u16 sorted[n_sorted]          token ids sorted by piece bytes (binary search),
                              padded to 4 bytes; specials are left out
u8  blob[blob_size]

Encoding (zym_llama_encode(), Tokenizer.encode()): BOS, then the optional " " token, then one token per byte (its single-character piece, else the byte token). Then repeatedly merge the adjacent pair whose concatenated pieces are a token with the highest score (first pair on ties), until no pair is a token. This is the llama2.c rule.

LLM1: Llama-family transformer (model_type 3)

Pre-norm decoder (RMSNorm, attention with RoPE and grouped key/value heads, SwiGLU FFN), the llama2.c architecture. All integer; the reference is training/llama_ref.py, the DS code ds-app/source/engine/llama.c.

u16 dim, hidden, n_layers, n_heads, n_kv_heads, vocab, seq_len
u16 flags                 bit 0: separate classifier (else tied to the embedding)
u8  act_frac = 16, mult_shift = 24, rope_frac = 30, reserved
u32 att_scale             round(65536 / sqrt(head_size))
u64 eps_q48               round(rms_eps * 2^48)
i32 rope[seq_len][head_size / 2][2]       cos, sin of pos * 10000^(-2j/head_size), Q30
mat emb [vocab][dim]
per layer:
    i32 rms_att[dim]  mat wq [dim][dim]  mat wk [kv][dim]  mat wv [kv][dim]
    mat wo [dim][dim] i32 rms_ffn[dim]   mat w1 [hidden][dim]
    mat w3 [hidden][dim]  mat w2 [dim][hidden]
i32 rms_final[dim]
mat cls [vocab][dim]      only if flags bit 0

mat [rows][cols] is i8 w[rows][cols] followed by i32 mult[rows], with mult = round(row_scale * 2^24). dim and hidden are multiples of 8 (hidden is zero-padded), kv = n_kv_heads * head_size.

Arithmetic, per token:

  • Activations are int32 Q16. Before a matrix-vector product the input is shifted right by the smallest e that makes it fit int16; then out = (dot(w, u) * mult) >> (24 - e).
  • RMSNorm works on that int16 copy with an integer square root and one division per vector.
  • Attention scores go to the log2 domain and through the same 2^-x table as sampling; the weights are normalised with one reciprocal per head.
  • silu(x) = x * sigmoid(x) uses the GRU's sigmoid table.
  • Results are saturated to int32 and q/k to ±(2^27 − 1), so the C int64 arithmetic can never overflow.

Generation protocol (all model types)

reset state
chat mode: feed "\n\nQ: " + prompt + "\nA:"     free mode: feed prompt
repeat up to max_tokens:
    s = sample(state, rng, temperature); feed(s); output s
    chat mode: stop after '\n'

Token models (type 3): feed BOS + the prompt tokens, then sample tokens until BOS/EOS, max_tokens or a full context, and output each token's display text (one leading space is dropped right after BOS, like llama2.c). max_tokens counts tokens, not characters.

The RNG is xorshift32 (x ^= x<<13; x ^= x>>17; x ^= x<<5), and seed 0 is replaced by 0x9E3779B9.