Run frontier MoE models on hardware you already own — pure C, zero deps, experts streamed from disk. Tiny engine, immense model. 🐦
C
tests: restore the tiny token-exact V4 and DSpark oracle
DrewZ68d9f7ce18e3
diff --git a/c/deepseek_v4_tiny/config.json b/c/deepseek_v4_tiny/config.jsonnew file mode 100644index 00000000..c65a4046--- /dev/null+++ b/c/deepseek_v4_tiny/config.json@@ -0,0 +1,63 @@+{+ "architectures": [+ "DeepseekV4ForCausalLM"+ ],+ "model_type": "deepseek_v4",+ "transformers_version": "5.14.1",+ "torch_dtype": "bfloat16",+ "expert_dtype": "fp4",+ "scoring_func": "sqrtsoftplus",+ "topk_method": "noaux_tc",+ "hidden_size": 128,+ "num_hidden_layers": 3,+ "num_attention_heads": 4,+ "num_key_value_heads": 1,+ "head_dim": 32,+ "q_lora_rank": 128,+ "qk_rope_head_dim": 16,+ "o_groups": 1,+ "o_lora_rank": 128,+ "sliding_window": 8,+ "index_n_heads": 2,+ "index_head_dim": 32,+ "index_topk": 2,+ "n_routed_experts": 4,+ "num_experts_per_tok": 2,+ "n_shared_experts": 1,+ "moe_intermediate_size": 128,+ "num_hash_layers": 1,+ "num_nextn_predict_layers": 1,+ "hc_mult": 2,+ "hc_sinkhorn_iters": 3,+ "vocab_size": 128,+ "max_position_embeddings": 128,+ "rms_norm_eps": 1e-06,+ "hc_eps": 1e-06,+ "routed_scaling_factor": 1.5,+ "swiglu_limit": 10.0,+ "rope_theta": 10000.0,+ "compress_rope_theta": 40000.0,+ "compress_ratios": [+ 0,+ 4,+ 8,+ 0+ ],+ "rope_scaling": {+ "type": "yarn",+ "factor": 1.0,+ "original_max_position_embeddings": 128,+ "beta_fast": 32,+ "beta_slow": 1+ },+ "quantization_config": {+ "activation_scheme": "dynamic",+ "fmt": "e4m3",+ "scale_fmt": "ue8m0",+ "quant_method": "fp8",+ "weight_block_size": [+ 128,+ 128+ ]+ }+}diff --git a/c/deepseek_v4_tiny/dspark/config.json b/c/deepseek_v4_tiny/dspark/config.jsonnew file mode 100644index 00000000..5d7fa957--- /dev/null+++ b/c/deepseek_v4_tiny/dspark/config.json@@ -0,0 +1,69 @@+{+ "architectures": [+ "DeepseekV4ForCausalLM"+ ],+ "model_type": "deepseek_v4",+ "transformers_version": "5.14.1",+ "torch_dtype": "bfloat16",+ "expert_dtype": "fp4",+ "scoring_func": "sqrtsoftplus",+ "topk_method": "noaux_tc",+ "hidden_size": 128,+ "num_hidden_layers": 3,+ "num_attention_heads": 4,+ "num_key_value_heads": 1,+ "head_dim": 32,+ "q_lora_rank": 128,+ "qk_rope_head_dim": 16,+ "o_groups": 1,+ "o_lora_rank": 128,+ "sliding_window": 8,+ "index_n_heads": 2,+ "index_head_dim": 32,+ "index_topk": 2,+ "n_routed_experts": 4,+ "num_experts_per_tok": 2,+ "n_shared_experts": 1,+ "moe_intermediate_size": 128,+ "num_hash_layers": 1,+ "num_nextn_predict_layers": 1,+ "hc_mult": 2,+ "hc_sinkhorn_iters": 3,+ "vocab_size": 128,+ "max_position_embeddings": 128,+ "rms_norm_eps": 1e-06,+ "hc_eps": 1e-06,+ "routed_scaling_factor": 1.5,+ "swiglu_limit": 10.0,+ "rope_theta": 10000.0,+ "compress_rope_theta": 40000.0,+ "compress_ratios": [+ 0,+ 4,+ 8,+ 0+ ],+ "rope_scaling": {+ "type": "yarn",+ "factor": 1.0,+ "original_max_position_embeddings": 128,+ "beta_fast": 32,+ "beta_slow": 1+ },+ "quantization_config": {+ "activation_scheme": "dynamic",+ "fmt": "e4m3",+ "scale_fmt": "ue8m0",+ "quant_method": "fp8",+ "weight_block_size": [+ 128,+ 128+ ]+ },+ "dspark_block_size": 2,+ "dspark_noise_token_id": 3,+ "dspark_markov_rank": 16,+ "dspark_target_layer_ids": [+ 1+ ]+}diff --git a/c/deepseek_v4_tiny/dspark/model.safetensors b/c/deepseek_v4_tiny/dspark/model.safetensorsnew file mode 100644index 00000000..5d177f38Binary files /dev/null and b/c/deepseek_v4_tiny/dspark/model.safetensors differdiff --git a/c/deepseek_v4_tiny/dspark/tokenizer.json b/c/deepseek_v4_tiny/dspark/tokenizer.jsonnew file mode 100644index 00000000..54a09a4d--- /dev/null+++ b/c/deepseek_v4_tiny/dspark/tokenizer.json@@ -0,0 +1 @@+{"version":"1.0","truncation":null,"padding":null,"added_tokens":[{"id":0,"content":"<t000>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":1,"content":"<t001>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":2,"content":"<t002>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":3,"content":"<t003>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":4,"content":"<t004>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":5,"content":"<t005>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":6,"content":"<t006>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":7,"content":"<t007>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":8,"content":"<t008>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":9,"content":"<t009>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":10,"content":"<t010>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":11,"content":"<t011>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":12,"content":"<t012>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":13,"content":"<t013>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":14,"content":"<t014>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":15,"content":"<t015>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":16,"content":"<t016>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":17,"content":"<t017>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":18,"content":"<t018>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":19,"content":"<t019>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":20,"content":"<t020>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":21,"content":"<t021>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":22,"content":"<t022>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":23,"content":"<t023>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":24,"content":"<t024>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":25,"content":"<t025>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":26,"content":"<t026>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":27,"content":"<t027>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":28,"content":"<t028>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":29,"content":"<t029>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":30,"content":"<t030>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":31,"content":"<t031>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":32,"content":"<t032>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":33,"content":"<t033>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":34,"content":"<t034>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":35,"content":"<t035>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":36,"content":"<t036>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":37,"content":"<t037>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":38,"content":"<t038>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":39,"content":"<t039>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":40,"content":"<t040>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":41,"content":"<t041>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":42,"content":"<t042>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":43,"content":"<t043>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":44,"content":"<t044>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":45,"content":"<t045>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":46,"content":"<t046>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":47,"content":"<t047>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":48,"content":"<t048>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":49,"content":"<t049>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":50,"content":"<t050>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":51,"content":"<t051>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":52,"content":"<t052>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":53,"content":"<t053>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":54,"content":"<t054>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":55,"content":"<t055>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":56,"content":"<t056>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":57,"content":"<t057>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":58,"content":"<t058>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":59,"content":"<t059>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":60,"content":"<t060>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":61,"content":"<t061>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":62,"content":"<t062>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":63,"content":"<t063>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":64,"content":"<t064>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":65,"content":"<t065>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":66,"content":"<t066>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":67,"content":"<t067>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":68,"content":"<t068>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":69,"content":"<t069>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":70,"content":"<t070>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":71,"content":"<t071>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":72,"content":"<t072>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":73,"content":"<t073>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":74,"content":"<t074>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":75,"content":"<t075>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":76,"content":"<t076>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":77,"content":"<t077>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":78,"content":"<t078>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":79,"content":"<t079>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":80,"content":"<t080>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":81,"content":"<t081>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":82,"content":"<t082>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":83,"content":"<t083>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":84,"content":"<t084>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":85,"content":"<t085>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":86,"content":"<t086>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":87,"content":"<t087>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":88,"content":"<t088>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":89,"content":"<t089>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":90,"content":"<t090>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":91,"content":"<t091>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":92,"content":"<t092>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":93,"content":"<t093>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":94,"content":"<t094>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":95,"content":"<t095>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":96,"content":"<t096>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":97,"content":"<t097>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":98,"content":"<t098>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":99,"content":"<t099>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":100,"content":"<t100>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":101,"content":"<t101>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":102,"content":"<t102>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":103,"content":"<t103>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":104,"content":"<t104>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":105,"content":"<t105>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":106,"content":"<t106>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":107,"content":"<t107>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":108,"content":"<t108>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":109,"content":"<t109>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":110,"content":"<t110>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":111,"content":"<t111>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":112,"content":"<t112>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":113,"content":"<t113>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":114,"content":"<t114>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":115,"content":"<t115>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":116,"content":"<t116>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":117,"content":"<t117>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":118,"content":"<t118>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":119,"content":"<t119>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":120,"content":"<t120>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":121,"content":"<t121>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":122,"content":"<t122>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":123,"content":"<t123>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":124,"content":"<t124>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":125,"content":"<t125>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":126,"content":"<t126>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":127,"content":"<t127>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true}],"normalizer":null,"pre_tokenizer":null,"post_processor":null,"decoder":null,"model":{"type":"BPE","dropout":null,"unk_token":null,"continuing_subword_prefix":"","end_of_word_suffix":"","fuse_unk":false,"byte_fallback":false,"ignore_merges":true,"vocab":{"x":127},"merges":[]}}diff --git a/c/deepseek_v4_tiny/model.safetensors b/c/deepseek_v4_tiny/model.safetensorsnew file mode 100644index 00000000..9abc02a0Binary files /dev/null and b/c/deepseek_v4_tiny/model.safetensors differdiff --git a/c/deepseek_v4_tiny/ref.json b/c/deepseek_v4_tiny/ref.jsonnew file mode 100644index 00000000..2011b5d1--- /dev/null+++ b/c/deepseek_v4_tiny/ref.json@@ -0,0 +1,526 @@+{+ "schema_version": 1,+ "generator_version": "2",+ "seed": 1234,+ "source": "transformers",+ "transformers_version": "5.14.1",+ "torch_version": "2.13.0+cpu",+ "quantization_format": {+ "dense": "E4M3 weight + UE8M0 128x128 scale, dequantized in reference",+ "routed_experts": "packed E2M1 + UE8M0 per-row/per-32 scale, dequantized in reference",+ "bf16": "round-tripped before reference"+ },+ "config_summary": {+ "vocab_size": 128,+ "hidden_size": 128,+ "num_hidden_layers": 3,+ "num_attention_heads": 4,+ "head_dim": 32,+ "q_lora_rank": 128,+ "o_lora_rank": 128,+ "hc_mult": 2,+ "n_routed_experts": 4,+ "num_experts_per_tok": 2,+ "n_shared_experts": 1,+ "moe_intermediate_size": 128,+ "sliding_window": 8,+ "compress_ratios": [+ 0,+ 4,+ 8+ ],+ "index_n_heads": 2,+ "index_head_dim": 32,+ "index_topk": 2,+ "num_nextn_predict_layers": 1+ },+ "prompt_ids_short": [+ 5,+ 7,+ 9,+ 11,+ 13,+ 17,+ 19,+ 23+ ],+ "prompt_ids_compressed": [+ 5,+ 12,+ 19,+ 26,+ 33,+ 40,+ 47,+ 54,+ 61,+ 68,+ 75,+ 82,+ 89,+ 96,+ 6,+ 13,+ 20,+ 27,+ 34,+ 41+ ],+ "prompt_ids_long": [+ 5,+ 16,+ 27,+ 38,+ 49,+ 60,+ 71,+ 82,+ 93,+ 7,+ 18,+ 29,+ 40,+ 51,+ 62,+ 73,+ 84,+ 95,+ 9,+ 20,+ 31,+ 42,+ 53,+ 64,+ 75,+ 86,+ 97,+ 11,+ 22,+ 33,+ 44,+ 55,+ 66,+ 77,+ 88,+ 99,+ 13,+ 24,+ 35,+ 46,+ 57,+ 68,+ 79,+ 90,+ 101,+ 15,+ 26,+ 37,+ 48,+ 59,+ 70,+ 81,+ 92,+ 6,+ 17,+ 28,+ 39,+ 50,+ 61,+ 72,+ 83,+ 94,+ 8,+ 19,+ 30,+ 41,+ 52,+ 63,+ 74,+ 85,+ 96,+ 10+ ],+ "cases": {+ "short": {+ "prompt_ids": [+ 5,+ 7,+ 9,+ 11,+ 13,+ 17,+ 19,+ 23+ ],+ "teacher_forcing_ids": [+ 55,+ 8,+ 10,+ 12,+ 14,+ 18,+ 20,+ 24,+ 25,+ 26,+ 27,+ 28,+ 29,+ 30,+ 31,+ 28+ ],+ "greedy_full_ids": [+ 5,+ 7,+ 9,+ 11,+ 13,+ 17,+ 19,+ 23,+ 24,+ 25,+ 26,+ 27,+ 28,+ 29,+ 30,+ 31+ ],+ "greedy_new_ids": [+ 24,+ 25,+ 26,+ 27,+ 28,+ 29,+ 30,+ 31+ ],+ "max_new_tokens": 8+ },+ "compressed": {+ "prompt_ids": [+ 5,+ 12,+ 19,+ 26,+ 33,+ 40,+ 47,+ 54,+ 61,+ 68,+ 75,+ 82,+ 89,+ 96,+ 6,+ 13,+ 20,+ 27,+ 34,+ 41+ ],+ "teacher_forcing_ids": [+ 55,+ 13,+ 122,+ 27,+ 26,+ 41,+ 48,+ 55,+ 62,+ 69,+ 76,+ 83,+ 90,+ 97,+ 7,+ 14,+ 21,+ 28,+ 35,+ 42,+ 43,+ 44,+ 45,+ 46+ ],+ "greedy_full_ids": [+ 5,+ 12,+ 19,+ 26,+ 33,+ 40,+ 47,+ 54,+ 61,+ 68,+ 75,+ 82,+ 89,+ 96,+ 6,+ 13,+ 20,+ 27,+ 34,+ 41,+ 42,+ 43,+ 44,+ 45+ ],+ "greedy_new_ids": [+ 42,+ 43,+ 44,+ 45+ ],+ "max_new_tokens": 4+ },+ "long": {+ "prompt_ids": [+ 5,+ 16,+ 27,+ 38,+ 49,+ 60,+ 71,+ 82,+ 93,+ 7,+ 18,+ 29,+ 40,+ 51,+ 62,+ 73,+ 84,+ 95,+ 9,+ 20,+ 31,+ 42,+ 53,+ 64,+ 75,+ 86,+ 97,+ 11,+ 22,+ 33,+ 44,+ 55,+ 66,+ 77,+ 88,+ 99,+ 13,+ 24,+ 35,+ 46,+ 57,+ 68,+ 79,+ 90,+ 101,+ 15,+ 26,+ 37,+ 48,+ 59,+ 70,+ 81,+ 92,+ 6,+ 17,+ 28,+ 39,+ 50,+ 61,+ 72,+ 83,+ 94,+ 8,+ 19,+ 30,+ 41,+ 52,+ 63,+ 74,+ 85,+ 96,+ 10+ ],+ "teacher_forcing_ids": [+ 55,+ 114,+ 28,+ 39,+ 50,+ 61,+ 72,+ 83,+ 94,+ 8,+ 19,+ 30,+ 41,+ 52,+ 63,+ 74,+ 85,+ 96,+ 10,+ 21,+ 32,+ 43,+ 54,+ 65,+ 76,+ 87,+ 98,+ 12,+ 23,+ 34,+ 45,+ 56,+ 67,+ 78,+ 89,+ 100,+ 14,+ 25,+ 36,+ 47,+ 58,+ 69,+ 80,+ 91,+ 102,+ 16,+ 27,+ 38,+ 49,+ 60,+ 71,+ 117,+ 93,+ 7,+ 18,+ 29,+ 40,+ 51,+ 62,+ 73,+ 84,+ 95,+ 9,+ 20,+ 31,+ 42,+ 53,+ 64,+ 75,+ 86,+ 97,+ 11,+ 12,+ 13,+ 14,+ 15+ ],+ "greedy_full_ids": [+ 5,+ 16,+ 27,+ 38,+ 49,+ 60,+ 71,+ 82,+ 93,+ 7,+ 18,+ 29,+ 40,+ 51,+ 62,+ 73,+ 84,+ 95,+ 9,+ 20,+ 31,+ 42,+ 53,+ 64,+ 75,+ 86,+ 97,+ 11,+ 22,+ 33,+ 44,+ 55,+ 66,+ 77,+ 88,+ 99,+ 13,+ 24,+ 35,+ 46,+ 57,+ 68,+ 79,+ 90,+ 101,+ 15,+ 26,+ 37,+ 48,+ 59,+ 70,+ 81,+ 92,+ 6,+ 17,+ 28,+ 39,+ 50,+ 61,+ 72,+ 83,+ 94,+ 8,+ 19,+ 30,+ 41,+ 52,+ 63,+ 74,+ 85,+ 96,+ 10,+ 11,+ 12,+ 13,+ 14+ ],+ "greedy_new_ids": [+ 11,+ 12,+ 13,+ 14+ ],+ "max_new_tokens": 4+ }+ }+}diff --git a/c/deepseek_v4_tiny/tokenizer.json b/c/deepseek_v4_tiny/tokenizer.jsonnew file mode 100644index 00000000..54a09a4d--- /dev/null+++ b/c/deepseek_v4_tiny/tokenizer.json@@ -0,0 +1 @@+{"version":"1.0","truncation":null,"padding":null,"added_tokens":[{"id":0,"content":"<t000>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":1,"content":"<t001>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":2,"content":"<t002>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":3,"content":"<t003>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":4,"content":"<t004>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":5,"content":"<t005>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":6,"content":"<t006>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":7,"content":"<t007>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":8,"content":"<t008>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":9,"content":"<t009>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":10,"content":"<t010>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":11,"content":"<t011>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":12,"content":"<t012>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":13,"content":"<t013>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":14,"content":"<t014>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":15,"content":"<t015>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":16,"content":"<t016>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":17,"content":"<t017>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":18,"content":"<t018>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":19,"content":"<t019>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":20,"content":"<t020>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":21,"content":"<t021>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":22,"content":"<t022>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":23,"content":"<t023>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":24,"content":"<t024>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":25,"content":"<t025>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":26,"content":"<t026>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":27,"content":"<t027>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":28,"content":"<t028>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":29,"content":"<t029>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":30,"content":"<t030>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":31,"content":"<t031>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":32,"content":"<t032>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":33,"content":"<t033>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":34,"content":"<t034>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":35,"content":"<t035>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":36,"content":"<t036>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":37,"content":"<t037>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":38,"content":"<t038>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":39,"content":"<t039>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":40,"content":"<t040>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":41,"content":"<t041>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":42,"content":"<t042>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":43,"content":"<t043>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":44,"content":"<t044>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":45,"content":"<t045>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":46,"content":"<t046>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":47,"content":"<t047>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":48,"content":"<t048>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":49,"content":"<t049>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":50,"content":"<t050>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":51,"content":"<t051>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":52,"content":"<t052>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":53,"content":"<t053>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":54,"content":"<t054>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":55,"content":"<t055>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":56,"content":"<t056>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":57,"content":"<t057>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":58,"content":"<t058>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":59,"content":"<t059>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":60,"content":"<t060>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":61,"content":"<t061>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":62,"content":"<t062>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":63,"content":"<t063>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":64,"content":"<t064>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":65,"content":"<t065>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":66,"content":"<t066>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":67,"content":"<t067>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":68,"content":"<t068>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":69,"content":"<t069>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":70,"content":"<t070>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":71,"content":"<t071>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":72,"content":"<t072>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":73,"content":"<t073>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":74,"content":"<t074>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":75,"content":"<t075>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":76,"content":"<t076>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":77,"content":"<t077>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":78,"content":"<t078>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":79,"content":"<t079>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":80,"content":"<t080>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":81,"content":"<t081>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":82,"content":"<t082>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":83,"content":"<t083>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":84,"content":"<t084>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":85,"content":"<t085>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":86,"content":"<t086>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":87,"content":"<t087>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":88,"content":"<t088>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":89,"content":"<t089>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":90,"content":"<t090>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":91,"content":"<t091>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":92,"content":"<t092>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":93,"content":"<t093>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":94,"content":"<t094>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":95,"content":"<t095>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":96,"content":"<t096>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":97,"content":"<t097>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":98,"content":"<t098>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":99,"content":"<t099>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":100,"content":"<t100>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":101,"content":"<t101>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":102,"content":"<t102>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":103,"content":"<t103>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":104,"content":"<t104>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":105,"content":"<t105>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":106,"content":"<t106>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":107,"content":"<t107>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":108,"content":"<t108>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":109,"content":"<t109>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":110,"content":"<t110>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":111,"content":"<t111>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":112,"content":"<t112>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":113,"content":"<t113>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":114,"content":"<t114>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":115,"content":"<t115>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":116,"content":"<t116>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":117,"content":"<t117>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":118,"content":"<t118>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":119,"content":"<t119>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":120,"content":"<t120>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":121,"content":"<t121>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":122,"content":"<t122>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":123,"content":"<t123>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":124,"content":"<t124>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":125,"content":"<t125>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":126,"content":"<t126>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true},{"id":127,"content":"<t127>","single_word":false,"lstrip":false,"rstrip":false,"normalized":false,"special":true}],"normalizer":null,"pre_tokenizer":null,"post_processor":null,"decoder":null,"model":{"type":"BPE","dropout":null,"unk_token":null,"continuing_subword_prefix":"","end_of_word_suffix":"","fuse_unk":false,"byte_fallback":false,"ignore_merges":true,"vocab":{"x":127},"merges":[]}}diff --git a/c/tests/test_deepseek_v4_tiny.py b/c/tests/test_deepseek_v4_tiny.pynew file mode 100644index 00000000..fe11b991--- /dev/null+++ b/c/tests/test_deepseek_v4_tiny.py@@ -0,0 +1,244 @@+#!/usr/bin/env python3+"""Dependency-free token-exact checks for the committed tiny V4 fixture."""++from __future__ import annotations++import argparse+import json+import re+import subprocess+import tempfile+from pathlib import Path+++def run(label: str, command: list[str]) -> subprocess.CompletedProcess[str]:+ result = subprocess.run(+ command,+ text=True,+ encoding="utf-8",+ errors="replace",+ stdout=subprocess.PIPE,+ stderr=subprocess.PIPE,+ timeout=180,+ )+ if result.returncode:+ raise AssertionError(+ f"{label} failed with exit code {result.returncode}\n"+ f"stdout:\n{result.stdout}\nstderr:\n{result.stderr}"+ )+ return result+++def flat_oracle(case: dict[str, object]) -> dict[str, object]:+ return {+ "prompt_ids": case["prompt_ids"],+ "full_ids": case["greedy_full_ids"],+ "tf_pred": case["teacher_forcing_ids"],+ }+++def check_target(+ binary: Path,+ model: Path,+ draft: Path,+ name: str,+ case: dict[str, object],+ temporary: Path,+) -> None:+ oracle = temporary / f"{name}.json"+ oracle.write_text(json.dumps(flat_oracle(case)), encoding="utf-8")+ full = case["greedy_full_ids"]+ generated = case["greedy_new_ids"]+ result = run(+ f"target {name}",+ [+ binary.as_posix(),+ model.as_posix(),+ "--oracle",+ oracle.as_posix(),+ "--teacher-forcing",+ str(len(full)),+ "--greedy",+ str(len(generated)),+ "--draft-model",+ draft.as_posix(),+ ],+ )+ expected_tf = f"{len(full)}/{len(full)} positions"+ expected_greedy = f"{len(generated)}/{len(generated)} tokens"+ if expected_tf not in result.stdout:+ raise AssertionError(f"target {name}: missing exact teacher-forcing result")+ if expected_greedy not in result.stdout:+ raise AssertionError(f"target {name}: missing exact greedy result")+ print(f"PASS target {name}: teacher forcing and greedy token-exact")+++def check_prefix_is_rejected(+ binary: Path, model: Path, draft: Path, case: dict[str, object], temporary: Path+) -> None:+ truncated = flat_oracle(case)+ truncated["full_ids"] = truncated["full_ids"][:-1]+ truncated["tf_pred"] = truncated["tf_pred"][:-1]+ oracle = temporary / "truncated-prefix.json"+ oracle.write_text(json.dumps(truncated), encoding="utf-8")+ result = subprocess.run(+ [+ binary.as_posix(),+ model.as_posix(),+ "--oracle",+ oracle.as_posix(),+ "--teacher-forcing",+ str(len(truncated["full_ids"])),+ "--greedy",+ str(len(case["greedy_new_ids"])),+ "--draft-model",+ draft.as_posix(),+ ],+ text=True,+ encoding="utf-8",+ errors="replace",+ stdout=subprocess.PIPE,+ stderr=subprocess.PIPE,+ timeout=180,+ )+ if result.returncode == 0 or "greedy length mismatch" not in result.stderr:+ raise AssertionError("truncated greedy prefix was not rejected")+ print("PASS target greedy: truncated prefix rejected")+++def token_prompt(ids: list[int]) -> str:+ return "".join(f"<t{token:03d}>" for token in ids)+++def check_session(+ binary: Path,+ model: Path,+ draft: Path,+ name: str,+ case: dict[str, object],+ temporary: Path,+ dspark: bool,+ ordinal: int = 0,+) -> list[int]:+ record = temporary / f"{name}-{'dspark' if dspark else 'target'}-{ordinal}.json"+ command = [+ binary.as_posix(),+ model.as_posix(),+ token_prompt(case["prompt_ids"]),+ "--raw-prompt",+ "--max-tokens",+ str(case["max_new_tokens"]),+ "--record-oracle",+ record.as_posix(),+ "--draft-model",+ draft.as_posix(),+ ]+ if not dspark:+ command.append("--no-dspark")+ result = run(f"session {name} dspark={dspark}", command)+ actual = json.loads(record.read_text(encoding="utf-8"))+ expected_prompt = case["prompt_ids"]+ expected_full = case["greedy_full_ids"]+ if actual.get("prompt_ids") != expected_prompt:+ raise AssertionError(+ f"session {name}: tokenized prompt mismatch: "+ f"expected {expected_prompt}, got {actual.get('prompt_ids')}"+ )+ if actual.get("full_ids") != expected_full:+ raise AssertionError(+ f"session {name} dspark={dspark}: exact output mismatch: "+ f"expected {expected_full}, got {actual.get('full_ids')}"+ )+ stats = re.search(+ r"v4_tokens prompt=(\d+) generated=(\d+).*?"+ r"speculative_rounds=(\d+) proposed=(\d+) accepted=(\d+).*?enabled=(\d+)",+ result.stderr,+ )+ if not stats:+ raise AssertionError(f"session {name}: missing generation statistics")+ prompt_count, generated_count, rounds, proposed, _accepted, enabled = (+ int(value) for value in stats.groups()+ )+ if prompt_count != len(expected_prompt) or generated_count != case["max_new_tokens"]:+ raise AssertionError(+ f"session {name}: length mismatch: prompt={prompt_count} generated={generated_count}"+ )+ if dspark and (enabled != 1 or rounds < 1 or proposed < 1):+ raise AssertionError(+ f"session {name}: DSpark was not exercised: "+ f"enabled={enabled} rounds={rounds} proposed={proposed}"+ )+ if not dspark and (enabled != 0 or rounds or proposed):+ raise AssertionError(+ f"session {name}: drafting was not disabled: "+ f"enabled={enabled} rounds={rounds} proposed={proposed}"+ )+ mode = "DSpark" if dspark else "target session"+ print(f"PASS {mode} {name}: exact IDs and exact length")+ return actual["full_ids"]+++def main() -> int:+ parser = argparse.ArgumentParser()+ parser.add_argument("--binary", type=Path, required=True)+ parser.add_argument("--fixture", type=Path, required=True)+ args = parser.parse_args()++ binary = args.binary.resolve()+ fixture = args.fixture.resolve()+ draft = fixture / "dspark"+ reference = json.loads((fixture / "ref.json").read_text(encoding="utf-8"))+ if reference.get("source") != "transformers":+ raise AssertionError("tiny oracle must come from independent Transformers")+ cases = reference["cases"]++ with tempfile.TemporaryDirectory(prefix="colibri-v4-tiny-") as directory:+ temporary = Path(directory)+ check_target(binary, fixture, draft, "short", cases["short"], temporary)+ check_prefix_is_rejected(binary, fixture, draft, cases["short"], temporary)+ check_target(binary, fixture, draft, "compressed", cases["compressed"], temporary)+ check_target(binary, fixture, draft, "long", cases["long"], temporary)++ # Repeated process-level engine/session lifecycles also validate that+ # drafting is genuinely disabled on the ordinary runtime path.+ for ordinal in range(3):+ check_session(+ binary,+ fixture,+ draft,+ "short",+ cases["short"],+ temporary,+ dspark=False,+ ordinal=ordinal,+ )+ # The 72-token case crosses the target and DSpark 64-token prefill+ # chunk boundary and verifies absolute-position continuity.+ target_long = check_session(+ binary,+ fixture,+ draft,+ "long",+ cases["long"],+ temporary,+ dspark=False,+ )+ dspark_long = check_session(+ binary,+ fixture,+ draft,+ "long",+ cases["long"],+ temporary,+ dspark=True,+ )+ if dspark_long != target_long:+ raise AssertionError("DSpark output differs from target-only output")+ print("PASS DSpark enabled/disabled identity: exact full sequence")++ print("PASS tiny DeepSeek V4 oracle: all checks completed")+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/c/tools/make_deepseek_v4_tiny.py b/c/tools/make_deepseek_v4_tiny.pynew file mode 100644index 00000000..27e6464a--- /dev/null+++ b/c/tools/make_deepseek_v4_tiny.py@@ -0,0 +1,673 @@+#!/usr/bin/env python3+"""Generate the committed tiny DeepSeek V4 + DSpark oracle fixture.++This is a regeneration tool, not a CI dependency. It deliberately requires+PyTorch and a Transformers release that contains the official+DeepseekV4ForCausalLM implementation. Reference tokens always come from that+implementation; there is no C-engine fallback.+"""+from __future__ import annotations++import argparse+import json+import math+import shutil+import struct+from collections import OrderedDict+from pathlib import Path+++SEED = 1234+SCHEMA_VERSION = 1+GENERATOR_VERSION = "2"+VOCAB = 128+HIDDEN = 128+LAYERS = 3+HEADS = 4+HEAD_DIM = 32+Q_RANK = 128+O_GROUPS = 1+O_RANK = 128+EXPERTS = 4+TOPK = 2+MOE = 128+HC = 2+INDEX_HEADS = 2+INDEX_DIM = 32+SLIDING = 8+COMPRESS_RATIOS = [0, 4, 8]+MAX_POSITIONS = 128+DSPARK_STAGES = 1+DSPARK_BLOCK = 2+DSPARK_MARKOV_RANK = 16+DSPARK_TARGET_LAYERS = [1]+DSPARK_NOISE_TOKEN = 3++E2M1 = (+ 0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0,+ 0.0, -0.5, -1.0, -1.5, -2.0, -3.0, -4.0, -6.0,+)+++def require_dependencies():+ try:+ import torch+ import transformers+ from transformers import DeepseekV4Config, DeepseekV4ForCausalLM+ except Exception as exc: # pragma: no cover - regeneration-only diagnostic+ raise SystemExit(+ "DeepSeek V4 tiny generation requires PyTorch and "+ "an official Transformers build with DeepseekV4ForCausalLM"+ ) from exc+ if not hasattr(transformers, "DeepseekV4ForCausalLM"):+ raise SystemExit(+ f"Transformers {transformers.__version__} has no DeepSeek V4 support"+ )+ return torch, transformers, DeepseekV4Config, DeepseekV4ForCausalLM+++def ceil_scale_exponent(maximum: float, limit: float) -> int:+ if maximum <= 0.0:+ return -127+ return max(-127, min(127, math.ceil(math.log2(maximum / limit))))+++def quantize_fp8(torch, value):+ """Production 128x128 E4M3 + UE8M0 block round-trip."""+ value = value.detach().to(torch.float32).contiguous()+ if value.ndim != 2:+ raise ValueError("FP8 tensors must be matrices")+ rows, columns = value.shape+ if columns % 128:+ raise ValueError(f"FP8 contraction dimension must be 128-aligned: {value.shape}")+ quantized = torch.empty_like(value, dtype=torch.float8_e4m3fn)+ scales = torch.empty(+ ((rows + 127) // 128, (columns + 127) // 128),+ dtype=torch.float8_e8m0fnu,+ )+ dequantized = torch.empty_like(value)+ for row in range(0, rows, 128):+ for column in range(0, columns, 128):+ block = value[row : row + 128, column : column + 128]+ exponent = ceil_scale_exponent(float(block.abs().max()), 448.0)+ scale = math.ldexp(1.0, exponent)+ q = (block / scale).clamp(-448.0, 448.0).to(torch.float8_e4m3fn)+ quantized[row : row + 128, column : column + 128] = q+ scales[row // 128, column // 128] = scale+ dequantized[row : row + 128, column : column + 128] = q.float() * scale+ return quantized, scales, dequantized+++def quantize_fp4(torch, value):+ """Production native packed E2M1 + per-row/per-32 UE8M0 round-trip."""+ value = value.detach().to(torch.float32).contiguous()+ if value.ndim != 2:+ raise ValueError("FP4 tensors must be matrices")+ rows, columns = value.shape+ if columns % 128:+ raise ValueError(f"FP4 contraction dimension must be 128-aligned: {value.shape}")+ packed = torch.empty((rows, columns // 2), dtype=torch.uint8)+ scales = torch.empty((rows, columns // 32), dtype=torch.float8_e8m0fnu)+ dequantized = torch.empty_like(value)+ lut = torch.tensor(E2M1, dtype=torch.float32)+ for row in range(rows):+ codes = torch.empty(columns, dtype=torch.uint8)+ for column in range(0, columns, 32):+ block = value[row, column : column + 32]+ exponent = ceil_scale_exponent(float(block.abs().max()), 6.0)+ scale = math.ldexp(1.0, exponent)+ normalized = (block / scale).clamp(-6.0, 6.0)+ code = (normalized[:, None] - lut[None, :]).abs().argmin(dim=1)+ codes[column : column + 32] = code.to(torch.uint8)+ scales[row, column // 32] = scale+ dequantized[row, column : column + 32] = lut[code] * scale+ packed[row] = codes[0::2] | (codes[1::2] << 4)+ # Safetensors must advertise I8, while the runtime treats the bits as packed U8.+ return packed.view(torch.int8), scales, dequantized+++def bf16_round(torch, value):+ return value.detach().to(torch.bfloat16).contiguous().float()+++def tensor_bytes(torch, tensor) -> bytes:+ return tensor.detach().cpu().contiguous().view(torch.uint8).numpy().tobytes()+++def safetensors_dtype(torch, tensor) -> str:+ mapping = {+ torch.float32: "F32",+ torch.bfloat16: "BF16",+ torch.float8_e4m3fn: "F8_E4M3",+ torch.float8_e8m0fnu: "F8_E8M0",+ torch.int64: "I64",+ torch.int8: "I8",+ }+ try:+ return mapping[tensor.dtype]+ except KeyError as exc:+ raise ValueError(f"unsupported safetensors dtype: {tensor.dtype}") from exc+++def write_safetensors(torch, path: Path, tensors: OrderedDict[str, object]) -> None:+ """Write a small standard safetensors file while preserving payload order.++ ExpertStore requires w1/w2/w3 scales to form one contiguous range and the+ three packed weights to form a second contiguous range. Preserving the+ insertion order makes that layout explicit and reproducible.+ """+ header: OrderedDict[str, object] = OrderedDict()+ payloads: list[bytes] = []+ offset = 0+ header["__metadata__"] = {+ "format": "pt",+ "generator": "c/tools/make_deepseek_v4_tiny.py",+ }+ for name, tensor in tensors.items():+ payload = tensor_bytes(torch, tensor)+ header[name] = {+ "dtype": safetensors_dtype(torch, tensor),+ "shape": list(tensor.shape),+ "data_offsets": [offset, offset + len(payload)],+ }+ payloads.append(payload)+ offset += len(payload)+ encoded = json.dumps(header, separators=(",", ":")).encode("utf-8")+ encoded += b" " * ((-len(encoded)) % 8)+ with path.open("wb") as stream:+ stream.write(struct.pack("<Q", len(encoded)))+ stream.write(encoded)+ for payload in payloads:+ stream.write(payload)+++def make_hf_config(DeepseekV4Config):+ return DeepseekV4Config(+ vocab_size=VOCAB,+ hidden_size=HIDDEN,+ moe_intermediate_size=MOE,+ num_hidden_layers=LAYERS,+ num_attention_heads=HEADS,+ num_key_value_heads=1,+ head_dim=HEAD_DIM,+ q_lora_rank=Q_RANK,+ num_experts_per_tok=TOPK,+ n_routed_experts=EXPERTS,+ n_shared_experts=1,+ scoring_func="sqrtsoftplus",+ norm_topk_prob=True,+ routed_scaling_factor=1.5,+ max_position_embeddings=MAX_POSITIONS,+ rope_theta=10000.0,+ layer_types=[+ "sliding_attention",+ "compressed_sparse_attention",+ "heavily_compressed_attention",+ ],+ compress_rates={+ "compressed_sparse_attention": 4,+ "heavily_compressed_attention": 8,+ },+ compress_rope_theta=40000.0,+ hc_mult=HC,+ hc_sinkhorn_iters=3,+ hc_eps=1.0e-6,+ mlp_layer_types=["hash_moe", "moe", "moe"],+ swiglu_limit=10.0,+ sliding_window=SLIDING,+ o_groups=O_GROUPS,+ o_lora_rank=O_RANK,+ index_n_heads=INDEX_HEADS,+ index_head_dim=INDEX_DIM,+ index_topk=2,+ num_nextn_predict_layers=1,+ initializer_range=0.02,+ rms_norm_eps=1.0e-6,+ bos_token_id=0,+ eos_token_id=1,+ tie_word_embeddings=False,+ partial_rotary_factor=0.5,+ rope_parameters={+ "main": {+ "rope_type": "default",+ "rope_theta": 10000.0,+ "partial_rotary_factor": 0.5,+ },+ "compress": {+ "rope_type": "default",+ "rope_theta": 40000.0,+ "partial_rotary_factor": 0.5,+ },+ },+ )+++def make_runtime_config(transformers_version: str, dspark: bool = False) -> dict:+ config = {+ "architectures": ["DeepseekV4ForCausalLM"],+ "model_type": "deepseek_v4",+ "transformers_version": transformers_version,+ "torch_dtype": "bfloat16",+ "expert_dtype": "fp4",+ "scoring_func": "sqrtsoftplus",+ "topk_method": "noaux_tc",+ "hidden_size": HIDDEN,+ "num_hidden_layers": LAYERS,+ "num_attention_heads": HEADS,+ "num_key_value_heads": 1,+ "head_dim": HEAD_DIM,+ "q_lora_rank": Q_RANK,+ "qk_rope_head_dim": HEAD_DIM // 2,+ "o_groups": O_GROUPS,+ "o_lora_rank": O_RANK,+ "sliding_window": SLIDING,+ "index_n_heads": INDEX_HEADS,+ "index_head_dim": INDEX_DIM,+ "index_topk": 2,+ "n_routed_experts": EXPERTS,+ "num_experts_per_tok": TOPK,+ "n_shared_experts": 1,+ "moe_intermediate_size": MOE,+ "num_hash_layers": 1,+ "num_nextn_predict_layers": 1,+ "hc_mult": HC,+ "hc_sinkhorn_iters": 3,+ "vocab_size": VOCAB,+ "max_position_embeddings": MAX_POSITIONS,+ "rms_norm_eps": 1.0e-6,+ "hc_eps": 1.0e-6,+ "routed_scaling_factor": 1.5,+ "swiglu_limit": 10.0,+ "rope_theta": 10000.0,+ "compress_rope_theta": 40000.0,+ "compress_ratios": [*COMPRESS_RATIOS, 0],+ "rope_scaling": {+ "type": "yarn",+ "factor": 1.0,+ "original_max_position_embeddings": MAX_POSITIONS,+ "beta_fast": 32,+ "beta_slow": 1,+ },+ "quantization_config": {+ "activation_scheme": "dynamic",+ "fmt": "e4m3",+ "scale_fmt": "ue8m0",+ "quant_method": "fp8",+ "weight_block_size": [128, 128],+ },+ }+ if dspark:+ config.update(+ dspark_block_size=DSPARK_BLOCK,+ dspark_noise_token_id=DSPARK_NOISE_TOKEN,+ dspark_markov_rank=DSPARK_MARKOV_RANK,+ dspark_target_layer_ids=DSPARK_TARGET_LAYERS,+ )+ return config+++def initialize_router_coverage(torch, model) -> None:+ with torch.no_grad():+ # Tie the output rows to a one-token cyclic shift of the input+ # embeddings. The residual stream therefore has a wide, deterministic+ # top-1 margin instead of relying on accidental near-ties in a random+ # language-model head. Generated IDs still vary at every step, while+ # production activation quantization cannot flip an otherwise fragile+ # oracle result.+ embeddings = model.model.embed_tokens.weight.detach().clone()+ for token in range(VOCAB):+ model.lm_head.weight[(token + 1) % VOCAB].copy_(embeddings[token])+ for layer_id, layer in enumerate(model.model.layers):+ gate = layer.mlp.gate+ values = torch.arange(gate.weight.numel(), dtype=torch.float32)+ gate.weight.copy_((0.025 * torch.sin(values * 0.017 + layer_id)).reshape_as(gate.weight))+ if hasattr(gate, "tid2eid"):+ table = torch.empty((VOCAB, TOPK), dtype=torch.int64)+ for token in range(VOCAB):+ table[token, 0] = (token + layer_id) % EXPERTS+ table[token, 1] = (token * 3 + layer_id + 1) % EXPERTS+ if table[token, 1] == table[token, 0]:+ table[token, 1] = (table[token, 1] + 1) % EXPERTS+ gate.tid2eid.copy_(table)+ if hasattr(gate, "e_score_correction_bias"):+ gate.e_score_correction_bias.copy_(+ torch.linspace(-0.03, 0.03, EXPERTS)+ )+ # EOS is deliberately unattractive so every fixed-length regression is+ # capable of detecting early truncation instead of accepting a prefix.+ model.lm_head.weight[1].zero_()+++def add_target_tensors(torch, model):+ state = model.state_dict()+ output: OrderedDict[str, object] = OrderedDict()++ def add_bf16(name: str, key: str) -> None:+ rounded = bf16_round(torch, state[key])+ state[key].copy_(rounded)+ output[name] = rounded.to(torch.bfloat16)++ def add_f32(name: str, key: str) -> None:+ output[name] = state[key].detach().float().contiguous()++ def add_fp8(name: str, key: str) -> None:+ quantized, scales, dequantized = quantize_fp8(torch, state[key])+ state[key].copy_(dequantized)+ output[name + ".weight"] = quantized+ output[name + ".scale"] = scales++ add_bf16("embed.weight", "model.embed_tokens.weight")+ add_bf16("head.weight", "lm_head.weight")+ add_bf16("norm.weight", "model.norm.weight")+ add_f32("hc_head_fn", "model.hc_head.hc_fn")+ add_f32("hc_head_base", "model.hc_head.hc_base")+ add_f32("hc_head_scale", "model.hc_head.hc_scale")++ for layer_id in range(LAYERS):+ hf = f"model.layers.{layer_id}"+ c = f"layers.{layer_id}"+ add_f32(f"{c}.attn.attn_sink", f"{hf}.self_attn.sinks")+ add_bf16(f"{c}.attn.kv_norm.weight", f"{hf}.self_attn.kv_norm.weight")+ add_bf16(f"{c}.attn.q_norm.weight", f"{hf}.self_attn.q_a_norm.weight")+ add_fp8(f"{c}.attn.wkv", f"{hf}.self_attn.kv_proj.weight")+ add_fp8(f"{c}.attn.wo_a", f"{hf}.self_attn.o_a_proj.weight")+ add_fp8(f"{c}.attn.wo_b", f"{hf}.self_attn.o_b_proj.weight")+ add_fp8(f"{c}.attn.wq_a", f"{hf}.self_attn.q_a_proj.weight")+ add_fp8(f"{c}.attn.wq_b", f"{hf}.self_attn.q_b_proj.weight")+ add_bf16(f"{c}.attn_norm.weight", f"{hf}.input_layernorm.weight")++ if COMPRESS_RATIOS[layer_id]:+ cp = f"{hf}.self_attn.compressor"+ add_f32(f"{c}.attn.compressor.ape", f"{cp}.position_bias")+ add_bf16(f"{c}.attn.compressor.norm.weight", f"{cp}.kv_norm.weight")+ add_bf16(f"{c}.attn.compressor.wgate.weight", f"{cp}.gate_proj.weight")+ add_bf16(f"{c}.attn.compressor.wkv.weight", f"{cp}.kv_proj.weight")+ if COMPRESS_RATIOS[layer_id] == 4:+ ip = f"{cp}.indexer"+ add_f32(f"{c}.attn.indexer.compressor.ape", f"{ip}.position_bias")+ add_bf16(f"{c}.attn.indexer.compressor.norm.weight", f"{ip}.kv_norm.weight")+ add_bf16(f"{c}.attn.indexer.compressor.wgate.weight", f"{ip}.gate_proj.weight")+ add_bf16(f"{c}.attn.indexer.compressor.wkv.weight", f"{ip}.kv_proj.weight")+ add_bf16(f"{c}.attn.indexer.weights_proj.weight", f"{ip}.scorer.weights_proj.weight")+ add_fp8(f"{c}.attn.indexer.wq_b", f"{ip}.q_b_proj.weight")++ add_bf16(f"{c}.ffn.gate.weight", f"{hf}.mlp.gate.weight")+ if layer_id == 0:+ output[f"{c}.ffn.gate.tid2eid"] = state[+ f"{hf}.mlp.gate.tid2eid"+ ].detach().to(torch.int64).contiguous()+ else:+ add_f32(+ f"{c}.ffn.gate.bias",+ f"{hf}.mlp.gate.e_score_correction_bias",+ )+ add_fp8(f"{c}.ffn.shared_experts.w1", f"{hf}.mlp.shared_experts.gate_proj.weight")+ add_fp8(f"{c}.ffn.shared_experts.w2", f"{hf}.mlp.shared_experts.down_proj.weight")+ add_fp8(f"{c}.ffn.shared_experts.w3", f"{hf}.mlp.shared_experts.up_proj.weight")+ add_bf16(f"{c}.ffn_norm.weight", f"{hf}.post_attention_layernorm.weight")+ add_f32(f"{c}.hc_attn_base", f"{hf}.attn_hc.base")+ add_f32(f"{c}.hc_attn_fn", f"{hf}.attn_hc.fn")+ add_f32(f"{c}.hc_attn_scale", f"{hf}.attn_hc.scale")+ add_f32(f"{c}.hc_ffn_base", f"{hf}.ffn_hc.base")+ add_f32(f"{c}.hc_ffn_fn", f"{hf}.ffn_hc.fn")+ add_f32(f"{c}.hc_ffn_scale", f"{hf}.ffn_hc.scale")++ gate_up_key = f"{hf}.mlp.experts.gate_up_proj"+ down_key = f"{hf}.mlp.experts.down_proj"+ for expert in range(EXPERTS):+ matrices = [+ state[gate_up_key][expert, :MOE],+ state[down_key][expert],+ state[gate_up_key][expert, MOE:],+ ]+ names = ("w1", "w2", "w3")+ converted = [quantize_fp4(torch, matrix) for matrix in matrices]+ for matrix, (_, _, dequantized) in zip(matrices, converted):+ matrix.copy_(dequantized)+ # ExpertStore depends on these two contiguous triples.+ for name, (_, scales, _) in zip(names, converted):+ output[f"{c}.ffn.experts.{expert}.{name}.scale"] = scales+ for name, (packed, _, _) in zip(names, converted):+ output[f"{c}.ffn.experts.{expert}.{name}.weight"] = packed+ return output+++def add_dspark_tensors(torch, model):+ """Create one valid production-layout DSpark stage.++ The independent target oracle remains Transformers. DSpark correctness is+ asserted by lossless target verification, so the draft weights may be a+ deterministic reduced stage derived from target layer 2.+ """+ state = model.state_dict()+ output: OrderedDict[str, object] = OrderedDict()++ def put_bf16(name: str, value) -> None:+ output[name] = bf16_round(torch, value).to(torch.bfloat16)++ def put_f32(name: str, value) -> None:+ output[name] = value.detach().float().contiguous()++ def put_fp8(name: str, value) -> None:+ quantized, scales, _ = quantize_fp8(torch, value)+ output[name + ".weight"] = quantized+ output[name + ".scale"] = scales++ put_bf16("embed.weight", state["model.embed_tokens.weight"])+ source = "model.layers.2"+ c = "mtp.0"+ put_f32(f"{c}.attn.attn_sink", state[f"{source}.self_attn.sinks"])+ put_bf16(f"{c}.attn.kv_norm.weight", state[f"{source}.self_attn.kv_norm.weight"])+ put_bf16(f"{c}.attn.q_norm.weight", state[f"{source}.self_attn.q_a_norm.weight"])+ put_fp8(f"{c}.attn.wkv", state[f"{source}.self_attn.kv_proj.weight"])+ put_fp8(f"{c}.attn.wo_a", state[f"{source}.self_attn.o_a_proj.weight"])+ put_fp8(f"{c}.attn.wo_b", state[f"{source}.self_attn.o_b_proj.weight"])+ put_fp8(f"{c}.attn.wq_a", state[f"{source}.self_attn.q_a_proj.weight"])+ put_fp8(f"{c}.attn.wq_b", state[f"{source}.self_attn.q_b_proj.weight"])+ put_bf16(f"{c}.attn_norm.weight", state[f"{source}.input_layernorm.weight"])+ put_bf16(f"{c}.ffn.gate.weight", state[f"{source}.mlp.gate.weight"])+ put_f32(f"{c}.ffn.gate.bias", state[f"{source}.mlp.gate.e_score_correction_bias"])+ put_fp8(f"{c}.ffn.shared_experts.w1", state[f"{source}.mlp.shared_experts.gate_proj.weight"])+ put_fp8(f"{c}.ffn.shared_experts.w2", state[f"{source}.mlp.shared_experts.down_proj.weight"])+ put_fp8(f"{c}.ffn.shared_experts.w3", state[f"{source}.mlp.shared_experts.up_proj.weight"])+ put_bf16(f"{c}.ffn_norm.weight", state[f"{source}.post_attention_layernorm.weight"])+ put_f32(f"{c}.hc_attn_base", state[f"{source}.attn_hc.base"])+ put_f32(f"{c}.hc_attn_fn", state[f"{source}.attn_hc.fn"])+ put_f32(f"{c}.hc_attn_scale", state[f"{source}.attn_hc.scale"])+ put_f32(f"{c}.hc_ffn_base", state[f"{source}.ffn_hc.base"])+ put_f32(f"{c}.hc_ffn_fn", state[f"{source}.ffn_hc.fn"])+ put_f32(f"{c}.hc_ffn_scale", state[f"{source}.ffn_hc.scale"])++ gate_up = state[f"{source}.mlp.experts.gate_up_proj"]+ down = state[f"{source}.mlp.experts.down_proj"]+ for expert in range(EXPERTS):+ matrices = [gate_up[expert, :MOE], down[expert], gate_up[expert, MOE:]]+ names = ("w1", "w2", "w3")+ converted = [quantize_fp4(torch, matrix) for matrix in matrices]+ for name, (_, scales, _) in zip(names, converted):+ output[f"{c}.ffn.experts.{expert}.{name}.scale"] = scales+ for name, (packed, _, _) in zip(names, converted):+ output[f"{c}.ffn.experts.{expert}.{name}.weight"] = packed++ identity = torch.eye(HIDDEN, dtype=torch.float32)+ put_fp8("mtp.0.main_proj", identity)+ put_bf16("mtp.0.main_norm.weight", torch.ones(HIDDEN))+ put_bf16("mtp.0.norm.weight", state["model.norm.weight"])+ put_f32("mtp.0.hc_head_fn", state["model.hc_head.hc_fn"])+ put_f32("mtp.0.hc_head_base", state["model.hc_head.hc_base"])+ put_f32("mtp.0.hc_head_scale", state["model.hc_head.hc_scale"])+ markov = torch.zeros((VOCAB, DSPARK_MARKOV_RANK), dtype=torch.float32)+ put_bf16("mtp.0.markov_head.markov_w1.weight", markov)+ put_bf16("mtp.0.markov_head.markov_w2.weight", markov)+ put_bf16(+ "mtp.0.confidence_head.proj.weight",+ torch.zeros((1, HIDDEN + DSPARK_MARKOV_RANK), dtype=torch.float32),+ )+ return output+++def make_tokenizer() -> dict:+ added = [+ {+ "id": token,+ "content": f"<t{token:03d}>",+ "single_word": False,+ "lstrip": False,+ "rstrip": False,+ "normalized": False,+ "special": True,+ }+ for token in range(VOCAB)+ ]+ return {+ "version": "1.0",+ "truncation": None,+ "padding": None,+ "added_tokens": added,+ "normalizer": None,+ "pre_tokenizer": None,+ "post_processor": None,+ "decoder": None,+ "model": {+ "type": "BPE",+ "dropout": None,+ "unk_token": None,+ "continuing_subword_prefix": "",+ "end_of_word_suffix": "",+ "fuse_unk": False,+ "byte_fallback": False,+ "ignore_merges": True,+ "vocab": {"x": VOCAB - 1},+ "merges": [],+ },+ }+++def greedy_reference(torch, model, prompt: list[int], max_new: int) -> tuple[list[int], list[int]]:+ sequence = list(prompt)+ with torch.no_grad():+ for _ in range(max_new):+ inputs = torch.tensor([sequence], dtype=torch.long)+ logits = model(input_ids=inputs, use_cache=False).logits[0, -1]+ sequence.append(int(logits.argmax()))+ full = torch.tensor([sequence], dtype=torch.long)+ teacher = model(input_ids=full, use_cache=False).logits[0].argmax(-1).tolist()+ generated = sequence[len(prompt) :]+ if len(generated) != max_new or 1 in generated:+ raise RuntimeError(+ f"reference generation truncated or produced EOS: prompt={prompt} generated={generated}"+ )+ return sequence, teacher+++def make_reference(torch, transformers, model) -> dict:+ prompts = {+ "short": [5, 7, 9, 11, 13, 17, 19, 23],+ "compressed": [5 + (index * 7) % 97 for index in range(20)],+ "long": [5 + (index * 11) % 97 for index in range(72)],+ }+ max_new = {"short": 8, "compressed": 4, "long": 4}+ cases = {}+ for name, prompt in prompts.items():+ full, teacher = greedy_reference(torch, model, prompt, max_new[name])+ cases[name] = {+ "prompt_ids": prompt,+ "teacher_forcing_ids": teacher,+ "greedy_full_ids": full,+ "greedy_new_ids": full[len(prompt) :],+ "max_new_tokens": max_new[name],+ }+ return {+ "schema_version": SCHEMA_VERSION,+ "generator_version": GENERATOR_VERSION,+ "seed": SEED,+ "source": "transformers",+ "transformers_version": transformers.__version__,+ "torch_version": torch.__version__,+ "quantization_format": {+ "dense": "E4M3 weight + UE8M0 128x128 scale, dequantized in reference",+ "routed_experts": "packed E2M1 + UE8M0 per-row/per-32 scale, dequantized in reference",+ "bf16": "round-tripped before reference",+ },+ "config_summary": {+ "vocab_size": VOCAB,+ "hidden_size": HIDDEN,+ "num_hidden_layers": LAYERS,+ "num_attention_heads": HEADS,+ "head_dim": HEAD_DIM,+ "q_lora_rank": Q_RANK,+ "o_lora_rank": O_RANK,+ "hc_mult": HC,+ "n_routed_experts": EXPERTS,+ "num_experts_per_tok": TOPK,+ "n_shared_experts": 1,+ "moe_intermediate_size": MOE,+ "sliding_window": SLIDING,+ "compress_ratios": COMPRESS_RATIOS,+ "index_n_heads": INDEX_HEADS,+ "index_head_dim": INDEX_DIM,+ "index_topk": 2,+ "num_nextn_predict_layers": 1,+ },+ "prompt_ids_short": prompts["short"],+ "prompt_ids_compressed": prompts["compressed"],+ "prompt_ids_long": prompts["long"],+ "cases": cases,+ }+++def print_manifest(label: str, tensors: OrderedDict[str, object]) -> None:+ print(f"[{label}] {len(tensors)} tensors")+ for name, tensor in tensors.items():+ print(f" {name}: {list(tensor.shape)} {tensor.dtype}")+++def main() -> int:+ parser = argparse.ArgumentParser(description=__doc__)+ default = Path(__file__).resolve().parents[1] / "deepseek_v4_tiny"+ parser.add_argument("--output", type=Path, default=default)+ parser.add_argument("--force", action="store_true")+ args = parser.parse_args()++ torch, transformers, Config, Model = require_dependencies()+ torch.manual_seed(SEED)+ torch.set_num_threads(1)+ model = Model(make_hf_config(Config)).eval()+ initialize_router_coverage(torch, model)++ target = add_target_tensors(torch, model)+ dspark = add_dspark_tensors(torch, model)+ reference = make_reference(torch, transformers, model)++ output = args.output.resolve()+ if output.exists():+ if not args.force:+ raise SystemExit(f"output exists (use --force): {output}")+ shutil.rmtree(output)+ (output / "dspark").mkdir(parents=True)+ (output / "config.json").write_text(+ json.dumps(make_runtime_config(transformers.__version__), indent=2) + "\n",+ encoding="utf-8",+ )+ (output / "dspark" / "config.json").write_text(+ json.dumps(make_runtime_config(transformers.__version__, dspark=True), indent=2) + "\n",+ encoding="utf-8",+ )+ tokenizer = json.dumps(make_tokenizer(), separators=(",", ":")) + "\n"+ (output / "tokenizer.json").write_text(tokenizer, encoding="utf-8")+ (output / "dspark" / "tokenizer.json").write_text(tokenizer, encoding="utf-8")+ write_safetensors(torch, output / "model.safetensors", target)+ write_safetensors(torch, output / "dspark" / "model.safetensors", dspark)+ (output / "ref.json").write_text(+ json.dumps(reference, indent=2) + "\n", encoding="utf-8"+ )++ print_manifest("target", target)+ print_manifest("dspark", dspark)+ total = sum(path.stat().st_size for path in output.rglob("*") if path.is_file())+ print(f"wrote {output} ({total} bytes, transformers={transformers.__version__})")+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())