hkimi / tools /make_tiny_model.py
Ozomozyan's picture
hkimi 0.1.0
68888be verified
Raw History Blame Contribute Delete
14.9 kB
#!/usr/bin/env python3
"""Create a tiny random model in the exact on-disk layout of a Kimi checkpoint.
Same tensor names, dtypes, nesting and packing as the real thing (read off the released
files, see docs/model-facts.md), with every dimension shrunk so the whole pipeline runs
on a laptop CPU in seconds:
kimi_k31 K3.1 Pro layout: latent MoE, MXFP4 experts, SiTU, AttnRes, bounded
KDA gate, gated MLA with a sparse-attention indexer
kimi_k3 K3 layout: the same without the indexer
kimi_linear Kimi-Linear layout: BF16 experts, SiLU, plain residuals
python tools/make_tiny_model.py --family kimi_k31 --out /tmp/tiny-k31
The weights are random, so the model says nothing sensible. It exists to test the engine
against tools/ref_forward.py and to exercise the draft-and-check loop.
"""
import argparse
import base64
import json
import os
import numpy as np
from hk_safetensors import Streamed, bf16_from_f32, mxfp4_dequant, save_file
def build(family, out_dir, seed=0, vocab=512):
rng = np.random.default_rng(seed)
k3 = family in ("kimi_k3", "kimi_k31")
# Sizes. Widths that differ in the real model differ here too (hidden 64, KDA 80, latent 32,
# expert 96, full-attention 56 / 72 / 40, ranks 24 and 20), so that a matrix read with rows and
# columns swapped, or a buffer sized with the wrong width, cannot pass the tests by luck.
d = 64
layers = 9
kda_layers = [1, 2, 3, 5, 6, 7] # 1-based, like the real config
full_layers = [4, 8, 9] # every fourth layer plus the last
kh, kd, conv = 5, 16, 4 # KDA heads, head dim, conv kernel
heads, nope, rope, vdim, kv_rank = 4, 8, 6, 10, 20
q_rank = 24 if k3 else None
n_exp, top_k = 32, 5
n_shared = 2 if k3 else 1
inter = 96 if k3 else 32
latent = 32 if k3 else None
dense_inter = 128
HD = kh * kd
text = {
"model_type": "kimi_linear", "vocab_size": vocab, "hidden_size": d, "intermediate_size": dense_inter,
"num_hidden_layers": layers, "num_attention_heads": heads, "head_dim": kd,
"hidden_act": "situ" if k3 else "silu", "rms_norm_eps": 1e-5,
"bos_token_id": vocab - 16, "eos_token_id": vocab - 15, "pad_token_id": vocab - 1,
"tie_word_embeddings": False, "moe_intermediate_size": inter, "moe_renormalize": True,
"moe_router_activation_func": "sigmoid", "num_experts": n_exp, "num_experts_per_token": top_k,
"num_shared_experts": n_shared, "routed_scaling_factor": 1.0 if k3 else 2.446,
"first_k_dense_replace": 1, "moe_layer_freq": 1, "use_grouped_topk": True, "num_expert_group": 1,
"topk_group": 1, "topk_method": "noaux_tc", "q_lora_rank": q_rank, "kv_lora_rank": kv_rank,
"qk_nope_head_dim": nope, "qk_rope_head_dim": rope, "v_head_dim": vdim, "mla_use_nope": True,
"num_nextn_predict_layers": 0, "max_position_embeddings": 1048576,
"linear_attn_config": {"full_attn_layers": full_layers, "kda_layers": kda_layers, "num_heads": kh,
"head_dim": kd, "short_conv_kernel_size": conv},
}
if k3:
text.update({"activation_situ_beta": 4.0, "activation_situ_linear_beta": 25.0, "mla_use_output_gate": True,
"attn_res_block_size": 4, "routed_expert_hidden_size": latent, "latent_moe_use_norm": True,
"quantization_config": {
"format": "mxfp4-pack-quantized", "quant_method": "compressed-tensors",
"quantization_status": "compressed",
"config_groups": {"group_0": {"targets": ["Linear"], "weights": {
"num_bits": 4, "type": "float", "strategy": "group", "group_size": 32,
"symmetric": True, "scale_dtype": "torch.uint8"}}}}})
text["linear_attn_config"].update({"use_full_rank_gate": True, "gate_lower_bound": -5.0})
if family == "kimi_k31":
text["dsa_config"] = {"dsa_layers": full_layers, "index_topk": 6, "index_head_dim": 12, "index_num_heads": 3,
"index_rope_dim": 0, "index_k_norm_type": "layernorm", "index_topk_freq": 1,
"index_skip_topk_offset": 1}
if k3:
config = {"architectures": ["KimiK31ForConditionalGeneration" if family == "kimi_k31" else "KimiK3ForConditionalGeneration"],
"model_type": family, "media_placeholder_token_id": vocab - 2, "pad_token_id": vocab - 1,
"dtype": "bfloat16", "text_config": text}
P = "language_model."
else:
config = dict(text)
config["architectures"] = ["KimiLinearForCausalLM"]
P = ""
T = {}
def bf(name, shape, std):
T[name] = ("BF16", bf16_from_f32((rng.standard_normal(shape) * std).astype(np.float32)))
def bf_vec(name, n, mean=1.0, std=0.1):
T[name] = ("BF16", bf16_from_f32((mean + rng.standard_normal(n) * std).astype(np.float32)))
def f32(name, arr):
T[name] = ("F32", np.asarray(arr, dtype=np.float32))
def lin(name, rows, cols, gain=1.0):
bf(name, (rows, cols), gain / np.sqrt(cols))
def bf_rows(name, rows, cols, std):
"""Like bf() for a [rows, cols] matrix. A huge one is written piece by piece, never whole in memory."""
if rows * cols <= 1 << 24:
return bf(name, (rows, cols), std)
piece_seed = int(rng.integers(0, 2 ** 31))
def pieces():
r = np.random.default_rng(piece_seed)
for r0 in range(0, rows, 1 << 18):
yield bf16_from_f32((r.standard_normal((min(1 << 18, rows - r0), cols), dtype=np.float32) * np.float32(std)))
T[name] = ("BF16", Streamed((rows, cols), pieces))
bf_rows(P + "model.embed_tokens.weight", vocab, d, 1.0)
in_dim = latent if k3 else d
for L in range(layers):
p = f"{P}model.layers.{L}."
bf_vec(p + "input_layernorm.weight", d)
bf_vec(p + "post_attention_layernorm.weight", d)
if k3:
# AttnRes: a norm weight and a pseudo-query per mixing point. Layer 0 ships its
# pre-attention pair too, although nothing reads it.
for site in ("self_attention", "mlp"):
bf_vec(p + site + "_res_norm.weight", d)
bf(p + site + "_res_proj.weight", (1, d), 0.5)
a = p + "self_attn."
if (L + 1) in kda_layers:
for n in "qkv":
lin(a + n + "_proj.weight", HD, d)
bf(a + n + "_conv1d.weight", (HD, 1, conv), 0.5)
lin(a + "f_a_proj.weight", kd, d)
lin(a + "f_b_proj.weight", HD, kd)
if k3:
alog = np.zeros(kd, dtype=np.float32) # K3 pads A_log to head_dim; only the first `heads` count
alog[:kh] = rng.standard_normal(kh) * 0.3
f32(a + "A_log", alog)
else:
f32(a + "A_log", rng.standard_normal(kh) * 0.3)
f32(a + "dt_bias", rng.standard_normal(HD) * 0.5)
lin(a + "b_proj.weight", kh, d)
if k3:
lin(a + "g_proj.weight", HD, d)
else:
lin(a + "g_a_proj.weight", kd, d)
lin(a + "g_b_proj.weight", HD, kd)
bf_vec(a + "o_norm.weight", kd)
lin(a + "o_proj.weight", d, HD)
else:
qd = nope + rope
if q_rank:
lin(a + "q_a_proj.weight", q_rank, d)
bf_vec(a + "q_a_layernorm.weight", q_rank)
lin(a + "q_b_proj.weight", heads * qd, q_rank, 2.0)
else:
lin(a + "q_proj.weight", heads * qd, d, 2.0)
lin(a + "kv_a_proj_with_mqa.weight", kv_rank + rope, d)
bf_vec(a + "kv_a_layernorm.weight", kv_rank)
lin(a + "kv_b_proj.weight", heads * (nope + vdim), kv_rank, 2.0)
if k3:
lin(a + "g_proj.weight", heads * vdim, d)
lin(a + "o_proj.weight", d, heads * vdim)
if family == "kimi_k31":
ih, idim = 3, 12
lin(a + "indexer.wq_b.weight", ih * idim, q_rank)
lin(a + "indexer.wk.weight", idim, d)
bf_vec(a + "indexer.k_norm.weight", idim)
bf_vec(a + "indexer.k_norm.bias", idim, 0.0, 0.1)
lin(a + "indexer.weights_proj.weight", ih, d)
if L >= 1:
m = p + "block_sparse_moe."
lin(m + "gate.weight", n_exp, d, 3.0)
f32(m + "gate.e_score_correction_bias", rng.standard_normal(n_exp) * 0.05)
if k3:
lin(m + "routed_expert_down_proj.weight", latent, d)
lin(m + "routed_expert_up_proj.weight", d, latent)
bf_vec(m + "routed_expert_norm.weight", latent)
lin(m + "shared_experts.gate_proj.weight", n_shared * inter, d)
lin(m + "shared_experts.up_proj.weight", n_shared * inter, d)
lin(m + "shared_experts.down_proj.weight", d, n_shared * inter)
for e in range(n_exp):
for tag, (r, c) in (("w1", (inter, in_dim)), ("w3", (inter, in_dim)), ("w2", (in_dim, inter))):
base = f"{m}experts.{e}.{tag}"
if k3:
# MXFP4: random 4-bit codes and block exponents around 2^-4 (weights of about 0.1).
T[base + ".weight_packed"] = ("U8", rng.integers(0, 256, (r, c // 2), dtype=np.uint8))
T[base + ".weight_scale"] = ("U8", rng.integers(121, 125, (r, c // 32), dtype=np.uint8))
else:
# Dense BF16 experts whose values are exactly representable in MXFP4, so that
# `hkimi convert --requantize` is lossless and the store can be checked bit for bit.
packed = rng.integers(0, 256, (r, c // 2), dtype=np.uint8)
scale = rng.integers(121, 125, (r, c // 32), dtype=np.uint8)
T[base + ".weight"] = ("BF16", bf16_from_f32(mxfp4_dequant(packed, scale).astype(np.float32)))
else:
lin(p + "mlp.gate_proj.weight", dense_inter, d)
lin(p + "mlp.up_proj.weight", dense_inter, d)
lin(p + "mlp.down_proj.weight", d, dense_inter)
bf_vec(P + "model.norm.weight", d)
if k3:
bf_vec(P + "model.output_attn_res_norm.weight", d)
bf(P + "model.output_attn_res_proj.weight", (1, d), 0.5)
bf_rows(P + "lm_head.weight", vocab, d, 4.0 / np.sqrt(d))
if k3: # a token vision tensor, to check that the converter ignores it
bf("vision_tower.patch_embed.proj.weight", (4, 3), 0.1)
os.makedirs(out_dir, exist_ok=True)
# Two shards, split in the middle of the layer stack, like a real multi-shard checkpoint.
def shard_of(name):
if ".layers." in name:
return 0 if int(name.split(".layers.")[1].split(".")[0]) < 5 else 1
return 0 if "embed" in name else 1
files = ["model-00001-of-00002.safetensors", "model-00002-of-00002.safetensors"]
parts = [{}, {}]
for name, v in T.items():
parts[shard_of(name)][name] = v
for fn, part in zip(files, parts):
save_file(part, os.path.join(out_dir, fn))
weight_map = {name: files[shard_of(name)] for name in T}
json.dump({"metadata": {"total_size": sum(os.path.getsize(os.path.join(out_dir, fn)) for fn in files)}, "weight_map": weight_map},
open(os.path.join(out_dir, "model.safetensors.index.json"), "w"))
json.dump(config, open(os.path.join(out_dir, "config.json"), "w"), indent=1)
if vocab <= 1 << 16:
write_tokenizer(out_dir, vocab, k3) # a huge test vocabulary gets no tokenizer: run it with token ids
return config
CORPUS = ("the quick brown fox jumps over the lazy dog. hello world, this is a tiny tokenizer for tests. "
"Kimi reads the draft and keeps what it would have written. 1234567890 numbers and symbols !? "
"le modele ecrit vite, le vrai Kimi verifie. ") * 4
def write_tokenizer(out_dir, vocab, k3):
"""A real (tiny) tiktoken-style vocabulary: 256 bytes plus merges learned on a few sentences."""
n_special = 16
n_merges = vocab - 256 - n_special
toks = [bytes([b]) for b in range(256)]
words = [list(w.encode()) for w in CORPUS.replace(" ", " \x00").split("\x00")]
words = [[bytes([b]) for b in w] for w in words if w]
for _ in range(n_merges):
counts = {}
for w in words:
for a, b in zip(w, w[1:]):
counts[(a, b)] = counts.get((a, b), 0) + 1
if not counts:
break
(a, b), _ = max(counts.items(), key=lambda kv: (kv[1], kv[0]))
merged = a + b
toks.append(merged)
new_words = []
for w in words:
out, i = [], 0
while i < len(w):
if i + 1 < len(w) and w[i] == a and w[i + 1] == b:
out.append(merged)
i += 2
else:
out.append(w[i])
i += 1
new_words.append(out)
words = new_words
while len(toks) < vocab - n_special: # corpus exhausted: pad with unused two-byte tokens
toks.append(bytes([0xF5, len(toks) % 256]))
with open(os.path.join(out_dir, "tiktoken.model"), "w") as f:
for rank, t in enumerate(toks):
f.write(base64.b64encode(t).decode() + " " + str(rank) + "\n")
if k3:
names = ["[BOS]", "[EOS]", "<|open|>", "<|close|>", "<|sep|>", "<|end_of_msg|>", "<|media_begin|>",
"<|media_content|>", "<|media_end|>"]
else:
names = ["[BOS]", "[EOS]", "<|im_end|>", "<|im_user|>", "<|im_assistant|>", "<|im_system|>", "<|im_middle|>"]
names += [f"<|reserved_{i}|>" for i in range(n_special - len(names) - 1)] + ["[PAD]"]
added = {str(vocab - n_special + i): {"content": n, "special": True} for i, n in enumerate(names)}
json.dump({"added_tokens_decoder": added, "bos_token": "[BOS]", "eos_token": "[EOS]", "pad_token": "[PAD]",
"tokenizer_class": "TikTokenTokenizer"},
open(os.path.join(out_dir, "tokenizer_config.json"), "w"), indent=1)
if __name__ == "__main__":
ap = argparse.ArgumentParser()
ap.add_argument("--family", default="kimi_k31", choices=["kimi_k31", "kimi_k3", "kimi_linear"])
ap.add_argument("--out", required=True)
ap.add_argument("--seed", type=int, default=0)
ap.add_argument("--vocab", type=int, default=512,
help="vocabulary size. 17000000 makes the embedding and the output head larger than 2 GB each, "
"like the real ones: a test of every path that must not count bytes in 32 bits (docs/testing.md)")
a = ap.parse_args()
cfg = build(a.family, a.out, a.seed, a.vocab)
print(f"wrote {a.family} tiny model to {a.out}")