Views
No views yet
kimi-k3-tiny-random.
Routed expert w1/w2/w3 stay plain BF16 weights; there is no MXFP4 packing
and no quantization_config.moonshotai/Kimi-K3:| Structural feature | Original K3 | This tiny model |
|---|---|---|
| Attention cycle | 3 KDA + 1 MLA per group | Same |
| Ending | Final layer is MLA | Same |
| KDA : MLA ratio | 69:24 (~3:1) | 12:5 (~3:1) |
| Total layers | 93 | 17 (4 groups + final MLA) |
| FFN layout | Layer 0 Dense MLP, others MoE | Same |
| MoE routing | top-16, 2 shared experts, group=1 | Same |
| Routed experts | 896 | 64 |
| AttnRes checkpoint | Every 12 layers (3 groups) | Every 8 layers (2 groups), proportionally scaled |
| KDA kernel params | num_heads=96, head_dim=128, conv=4, gate_lower_bound=-5 | heads 96 -> 8; per-head dims same |
| MLA kernel params | 96 heads, q/kv LoRA ranks 1536/512, nope/rope/v head dims | heads 96 -> 8, q rank 1536 -> 256, kv rank stays 512; kernel dims same |
| MoE quantization | Only routed expert w1/w2/w3 MXFP4 | None (full BF16) |
| Expert linear dims | moe_intermediate=3072, routed_hidden=3584 | moe_intermediate=32, routed_hidden=32 |
| Vision head_dim | 32 | Same |
| MTP | None | None |
| File path | Size |
|---|---|
| model.safetensors | 31.9MB |
1import numpy as np
2import torch
3from PIL import Image
4from transformers import AutoModel, AutoProcessor
5
6model_id = "yujiepan/kimi-k3-bf16-tiny-random"
7processor = AutoProcessor.from_pretrained(model_id, trust_remote_code=True)
8model = AutoModel.from_pretrained(
9 model_id,
10 dtype=torch.bfloat16,
11 device_map='cuda',
12 trust_remote_code=True,
13 attn_implementation='eager',
14).eval()
15image = Image.fromarray(np.random.default_rng(42).integers(0, 256, (56, 56, 3), dtype=np.uint8))
16tools = [{
17 'type': 'function',
18 'function': {
19 'name': 'get_image_size',
20 'description': 'Return the width and height of an image.',
21 'parameters': {
22 'type': 'object',
23 'properties': {
24 'image_index': {'type': 'integer', 'description': 'Zero-based image index.'},
25 },
26 'required': ['image_index'],
27 },
28 },
29}]
30messages = [{
31 'role': 'user',
32 'content': [
33 {'type': 'image', 'image': image},
34 {'type': 'text', 'text': 'Use the available tool to get this image size.'},
35 ],
36}]
37inputs = processor(
38 messages=messages,
39 tools=tools,
40 tool_choice='required',
41 return_tensors='pt',
42).to(model.device)
43with torch.no_grad():
44 outputs = model.generate(**inputs, max_new_tokens=32)
45generated_ids = outputs.sequences if hasattr(outputs, 'sequences') else outputs
46print(processor.decode(generated_ids[0].detach().cpu().tolist()))1import json
2from pathlib import Path
3
4import accelerate
5import torch
6from huggingface_hub import file_exists, hf_hub_download, list_repo_files
7from safetensors.torch import load_file, save_file
8from transformers import AutoConfig, AutoModel, GenerationConfig, set_seed
9
10source_model_id = "moonshotai/Kimi-K3"
11save_folder = "/tmp/yujiepan/kimi-k3-bf16-tiny-random" # pyright: ignore[reportUnusedExpression] # codegen marker
12
13Path(save_folder).mkdir(parents=True, exist_ok=True)
14suffixes = ['.json', '.py', '.model', '.jinja']
15for filename in list_repo_files(
16 source_model_id,
17 repo_type='model',
18 revision=source_revision,
19):
20 if any(filename.endswith(suffix) for suffix in suffixes) and not filename.endswith('.index.json'):
21 hf_hub_download(
22 repo_id=source_model_id,
23 filename=filename,
24 repo_type='model',
25 revision=source_revision,
26 local_dir=save_folder,
27 )
28
29def replace_file(filepath, replacements):
30 with open(filepath, 'r', encoding='utf-8') as f:
31 code = f.read()
32 for old_string, new_string in replacements:
33 if old_string not in code:
34 if new_string in code:
35 continue
36 raise ValueError(f'Expected code was not found in {filepath}: {old_string}')
37 code = code.replace(old_string, new_string)
38 with open(filepath, 'w', encoding='utf-8') as f:
39 f.write(code)
40
41# The upstream reference implementation forces FlashAttention for MLA even
42# when eager attention is requested. Allow the tiny MLA layer to use eager
43# attention without requiring the separate flash-attn package.
44force_flash_code = ''' if getattr(config, "_attn_implementation", None) is not None:
45 if config._attn_implementation != "flash_attention_2":
46 logger.warning_once(
47 f"Ignoring the provided attention implementation {config._attn_implementation}")
48 logger.warning_once("Using flash_attention_2 backend instead.")
49 config._attn_implementation = "flash_attention_2"
50 else:
51 config._attn_implementation = "flash_attention_2"'''
52per_channel_gate_code = ''' g = self.f_b_proj(self.f_a_proj(hidden_states))
53 g = rearrange(g, '... (h d) -> ... h d', d=self.head_dim)
54 beta = self.b_proj(hidden_states).float()'''
55per_channel_gate_compat_code = ''' g = self.f_b_proj(self.f_a_proj(hidden_states))
56 g = rearrange(g, '... (h d) -> ... h d', d=self.head_dim)
57 # The released K3 checkpoint stores per-channel decay shared by all heads.
58 g = self.gate_lower_bound * torch.sigmoid(
59 self.A_log.float().exp().view(1, 1, 1, self.head_dim)
60 * (g.float() + self.dt_bias.float().view(1, 1, self.num_heads, self.head_dim))
61 ).to(g.dtype)
62 beta = self.b_proj(hidden_states).float()'''
63causal_mask_code = ''' causal_mask = create_causal_mask(
64 config=self.config,
65 input_embeds=inputs_embeds,
66 attention_mask=attention_mask,
67 cache_position=cache_position,
68 past_key_values=past_key_values,
69 position_ids=position_ids,
70 )'''
71causal_mask_compat_code = ''' if version.parse(transformers.__version__) >= version.parse("5.0.0"):
72 causal_mask = create_causal_mask(
73 config=self.config,
74 inputs_embeds=inputs_embeds,
75 attention_mask=attention_mask,
76 past_key_values=past_key_values,
77 position_ids=position_ids,
78 )
79 else:
80 causal_mask = create_causal_mask(
81 config=self.config,
82 input_embeds=inputs_embeds,
83 attention_mask=attention_mask,
84 cache_position=cache_position,
85 past_key_values=past_key_values,
86 position_ids=position_ids,
87 )'''
88cache_api_code = ''' def get_mask_sizes(self, cache_position: torch.Tensor, layer_idx: int) -> tuple[int, int]:
89 """
90 Return a tuple (kv_length, kv_offset) corresponding to the length and offset that will be returned for
91 the given layer at `layer_idx`.
92 The masks are then prepared according to the given lengths (kv_length, kv_offset) and patterns for each layer.
93 """
94 kv_offset = 0
95 query_length = cache_position.shape[0]'''
96cache_api_compat_code = ''' def get_query_offset(self, layer_idx: int) -> int:
97 return self.get_seq_length(layer_idx)
98
99def get_mask_sizes(self, cache_position: torch.Tensor | int, layer_idx: int) -> tuple[int, int]:
100 """
101 Return a tuple (kv_length, kv_offset) corresponding to the length and offset that will be returned for
102 the given layer at `layer_idx`.
103 The masks are then prepared according to the given lengths (kv_length, kv_offset) and patterns for each layer.
104 """
105 kv_offset = 0
106 query_length = cache_position if isinstance(cache_position, int) else cache_position.shape[0]'''
107
108replace_file(f'{save_folder}/modeling_kimi_linear.py', [
109 # Transformers 5 compatibility.
110 (
111 'from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel',
112 'from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, OutputRecorder, PreTrainedModel',
113 ),
114 (
115 'from transformers.utils.generic import OutputRecorder, check_model_inputs',
116 'from transformers.utils.generic import check_model_inputs',
117 ),
118 (
119 ' _tied_weights_keys = ["lm_head.weight"]',
120 ''' _tied_weights_keys = (
121 {"lm_head.weight": "model.embed_tokens.weight"}
122 if version.parse(transformers.__version__) >= version.parse("5.0.0")
123 else ["lm_head.weight"]
124)''',
125 ),
126 (causal_mask_code, causal_mask_compat_code),
127 (cache_api_code, cache_api_compat_code),
128 # Allow eager MLA instead of forcing the optional flash-attn package.
129 (
130 force_flash_code,
131 ' config._attn_implementation = getattr(config, "_attn_implementation", "eager")',
132 ),
133 # Fix stale K3 reference code: released shards store A_log as
134 # [head_dim], and the decay is applied per channel across all heads.
135 (
136 ' self.num_heads, dtype=torch.float32).uniform_(1, 16)))',
137 ' self.head_dim, dtype=torch.float32).uniform_(1, 16)))',
138 ),
139 (per_channel_gate_code, per_channel_gate_compat_code),
140 (
141 ''' use_qk_l2norm_in_kernel=True,
142 use_gate_in_kernel=True,
143 use_beta_sigmoid_in_kernel=True,''',
144 ''' use_qk_l2norm_in_kernel=True,
145 use_gate_in_kernel=False,
146 use_beta_sigmoid_in_kernel=True,''',
147 ),
148 (
149 ' safe_gate=self.gate_lower_bound is not None,',
150 ' safe_gate=False,',
151 ),
152])
153replace_file(f'{save_folder}/modeling_kimi_k3.py', [
154 (' def tie_weights(self):', ' def tie_weights(self, *args, **kwargs):'),
155 (" _supports_sdpa = True", " _supports_sdpa = False"),
156 (
157 ' first_layer_past_key_value = past_key_values[0][0][:, :, :, 0]',
158 ''' if hasattr(past_key_values, "key_cache"):
159 first_key_cache = next(
160 key_cache for key_cache in past_key_values.key_cache if key_cache is not None
161 )
162 first_layer_past_key_value = first_key_cache[:, :, :, 0]
163 else:
164 first_layer_past_key_value = past_key_values[0][0][:, :, :, 0]''',
165 ),
166])
167
168with open(f'{save_folder}/config.json', encoding='utf-8') as f:
169 config_json = json.load(f)
170
171# Pure BF16: drop all quantization metadata (no MXFP4 / no quant_method).
172config_json['text_config'].pop('quantization_config', None)
173config_json.pop('quantization_config', None)
174
175# Preserve the kernel-sensitive dims from upstream: KDA head_dim=128,
176# MLA kv_lora_rank=512, qk_nope=128, qk_rope=64, v=128, conv kernel=4.
177# vLLM's Kimi fused MLA decode kernel requires latent KV rank 512 and
178# cache/query head size 512 + 64 = 576, so only shrink head count and
179# q_lora_rank; q_b_proj still drops 54MB->0.75MB.
180# Keep the upstream cadence: four 4-layer groups plus the final MLA layer.
181# One attention-residual checkpoint every two groups (block_size=8), so
182# block boundaries land on layers 0, 8, 16 (0-based).
183# Without MXFP4, expert linear dims no longer need group_size=32 / TP
184# padding floors; shrink moe_intermediate_size and routed_expert_hidden_size
185# so BF16 experts stay small (target total checkpoint <= ~150MB).
186config_json['text_config'].update({
187 'attn_res_block_size': 8,
188 'first_k_dense_replace': 1,
189 'hidden_size': 8,
190 'intermediate_size': 32,
191 'kv_lora_rank': 512,
192 'moe_intermediate_size': 32,
193 'num_attention_heads': 8,
194 'num_experts': 64,
195 'num_hidden_layers': 17,
196 'num_key_value_heads': 8,
197 'q_lora_rank': 256,
198 'routed_expert_hidden_size': 32,
199 '_attn_implementation': 'eager',
200})
201config_json['text_config']['linear_attn_config'].update({
202 'full_attn_layers': [4, 8, 12, 16, 17],
203 'kda_layers': [1, 2, 3, 5, 6, 7, 9, 10, 11, 13, 14, 15],
204 'num_heads': 8,
205})
206config_json['vision_config'].update({
207 '_attn_implementation': 'eager',
208 'init_pos_emb_height': 8,
209 'init_pos_emb_width': 8,
210 'mm_hidden_size': 64,
211 'qkv_hidden_size': 64,
212 'text_hidden_size': 8,
213 'vt_hidden_size': 64,
214 'vt_intermediate_size': 128,
215 # Vision attention head size = qkv_hidden_size / heads = 64 / 2 = 32.
216 'vt_num_attention_heads': 2,
217 'vt_num_hidden_layers': 2,
218})
219with open(f'{save_folder}/config.json', 'w', encoding='utf-8') as f:
220 json.dump(config_json, f, indent=2)
221
222config = AutoConfig.from_pretrained(save_folder, trust_remote_code=True)
223print(config)
224torch.set_default_dtype(torch.bfloat16)
225model = AutoModel.from_config(
226 config,
227 trust_remote_code=True,
228 attn_implementation='eager',
229)
230torch.set_default_dtype(torch.float32)
231if file_exists(
232 filename='generation_config.json',
233 repo_id=source_model_id,
234 repo_type='model',
235 revision=source_revision,
236):
237 model.generation_config = GenerationConfig.from_pretrained(
238 source_model_id,
239 trust_remote_code=True,
240 revision=source_revision,
241 )
242set_seed(42)
243model = model.cpu()
244num_params = sum(p.numel() for p in model.parameters())
245with torch.no_grad():
246 for name, parameter in sorted(model.named_parameters()):
247 torch.nn.init.normal_(parameter, 0, 0.1)
248 print(name, parameter.shape, parameter.dtype, f'{parameter.numel() / num_params:.2%}')
249model.save_pretrained(save_folder)
250
251# Match the official checkpoint schema for non-quantized tensors: keep
252# KDA / MoE gate bias buffers in float32.
253model_path = Path(save_folder) / 'model.safetensors'
254state_dict = load_file(str(model_path))
255for name in list(state_dict):
256 if name.endswith((
257 '.block_sparse_moe.gate.e_score_correction_bias',
258 '.self_attn.A_log',
259 '.self_attn.dt_bias',
260 '.self_attn.k_conv1d.weight',
261 '.self_attn.o_norm.weight',
262 '.self_attn.q_conv1d.weight',
263 '.self_attn.v_conv1d.weight',
264 )):
265 state_dict[name] = state_dict[name].float()
266dtype_counts = {
267 dtype: sum(tensor.dtype == dtype for tensor in state_dict.values())
268 for dtype in (torch.bfloat16, torch.float32, torch.uint8)
269}
270text_cfg = config_json['text_config']
271num_moe_layers = text_cfg['num_hidden_layers'] - text_cfg['first_k_dense_replace']
272num_kda_layers = len(text_cfg['linear_attn_config']['kda_layers'])
273expected_f32 = num_moe_layers + num_kda_layers * 6
274assert dtype_counts == {
275 torch.bfloat16: len(state_dict) - expected_f32,
276 torch.float32: expected_f32,
277 torch.uint8: 0,
278}, dtype_counts
279assert not any('mtp' in name.lower() for name in state_dict)
280total_bytes = sum(t.numel() * t.element_size() for t in state_dict.values())
281print(f'Total checkpoint size: {total_bytes / 1024**2:.2f} MB')
282assert total_bytes / 1024**2 <= 150, total_bytes / 1024**2
283print('Top 20 keys with largest storage size:')
284for name, tensor in sorted(state_dict.items(), key=lambda x: x[1].numel() * x[1].element_size(), reverse=True)[:20]:
285 print(f'{name}: {tensor.numel()} elements, {tensor.numel() * tensor.element_size() / 1024**2:.2f} MB')
286save_file(state_dict, str(model_path), metadata={'format': 'pt'})1KimiK3ForConditionalGeneration(
2 (vision_tower): MoonViT3dPretrainedModel(
3 (patch_embed): MoonVision3dPatchEmbed(
4 (proj): Conv2d(3, 64, kernel_size=(14, 14), stride=(14, 14), bias=False)
5 (pos_emb): Learnable2DInterpPosEmbDivided_fixed()
6 )
7 (encoder): MoonViT3dEncoder(
8 (rope_2d): Rope2DPosEmbRepeated(dim=32, max_height=512, max_width=512, theta_base=10000)
9 (blocks): ModuleList(
10 (0-1): 2 x MoonViTEncoderLayer(
11 (norm0): RMSNorm((64,), eps=None, elementwise_affine=True)
12 (norm1): RMSNorm((64,), eps=None, elementwise_affine=True)
13 (mlp): MLP2(
14 (fc0): Linear(in_features=64, out_features=128, bias=False)
15 (fc1): Linear(in_features=128, out_features=64, bias=False)
16 (activation): GELUTanh()
17 )
18 (wqkv): Linear(in_features=64, out_features=192, bias=False)
19 (wo): Linear(in_features=64, out_features=64, bias=False)
20 )
21 )
22 (final_layernorm): RMSNorm((64,), eps=None, elementwise_affine=True)
23 )
24 )
25 (mm_projector): PatchMergerMLPV2(
26 (proj): Sequential(
27 (0): Linear(in_features=256, out_features=256, bias=False)
28 (1): GELU(approximate='none')
29 (2): Linear(in_features=256, out_features=8, bias=False)
30 )
31 (post_norm): RMSNorm((8,), eps=1e-05, elementwise_affine=True)
32 )
33 (language_model): KimiLinearForCausalLM(
34 (model): KimiLinearModel(
35 (embed_tokens): Embedding(163840, 8, padding_idx=163839)
36 (layers): ModuleList(
37 (0): KimiDecoderLayer(
38 (self_attn): KimiDeltaAttention(
39 (q_proj): Linear(in_features=8, out_features=1024, bias=False)
40 (k_proj): Linear(in_features=8, out_features=1024, bias=False)
41 (v_proj): Linear(in_features=8, out_features=1024, bias=False)
42 (q_conv1d): ShortConvolution(1024, 1024, kernel_size=(4,), stride=(1,), padding=(3,), groups=1024, bias=False, activation=silu, backend=triton)
43 (k_conv1d): ShortConvolution(1024, 1024, kernel_size=(4,), stride=(1,), padding=(3,), groups=1024, bias=False, activation=silu, backend=triton)
44 (v_conv1d): ShortConvolution(1024, 1024, kernel_size=(4,), stride=(1,), padding=(3,), groups=1024, bias=False, activation=silu, backend=triton)
45 (f_a_proj): Linear(in_features=8, out_features=128, bias=False)
46 (f_b_proj): Linear(in_features=128, out_features=1024, bias=False)
47 (b_proj): Linear(in_features=8, out_features=8, bias=False)
48 (g_proj): Linear(in_features=8, out_features=1024, bias=False)
49 (o_norm): FusedRMSNormGated(128, eps=1e-05, activation=sigmoid)
50 (o_proj): Linear(in_features=1024, out_features=8, bias=False)
51 )
52 (mlp): KimiMLP(
53 (gate_proj): Linear(in_features=8, out_features=32, bias=False)
54 (up_proj): Linear(in_features=8, out_features=32, bias=False)
55 (down_proj): Linear(in_features=32, out_features=8, bias=False)
56 (act_fn): SituAndMul()
57 )
58 (input_layernorm): KimiRMSNorm()
59 (post_attention_layernorm): KimiRMSNorm()
60 (self_attention_res_norm): KimiRMSNorm()
61 (mlp_res_norm): KimiRMSNorm()
62 (self_attention_res_proj): Linear(in_features=8, out_features=1, bias=False)
63 (mlp_res_proj): Linear(in_features=8, out_features=1, bias=False)
64 )
65 (1-2): 2 x KimiDecoderLayer(
66 (self_attn): KimiDeltaAttention(
67 (q_proj): Linear(in_features=8, out_features=1024, bias=False)
68 (k_proj): Linear(in_features=8, out_features=1024, bias=False)
69 (v_proj): Linear(in_features=8, out_features=1024, bias=False)
70 (q_conv1d): ShortConvolution(1024, 1024, kernel_size=(4,), stride=(1,), padding=(3,), groups=1024, bias=False, activation=silu, backend=triton)
71 (k_conv1d): ShortConvolution(1024, 1024, kernel_size=(4,), stride=(1,), padding=(3,), groups=1024, bias=False, activation=silu, backend=triton)
72 (v_conv1d): ShortConvolution(1024, 1024, kernel_size=(4,), stride=(1,), padding=(3,), groups=1024, bias=False, activation=silu, backend=triton)
73 (f_a_proj): Linear(in_features=8, out_features=128, bias=False)
74 (f_b_proj): Linear(in_features=128, out_features=1024, bias=False)
75 (b_proj): Linear(in_features=8, out_features=8, bias=False)
76 (g_proj): Linear(in_features=8, out_features=1024, bias=False)
77 (o_norm): FusedRMSNormGated(128, eps=1e-05, activation=sigmoid)
78 (o_proj): Linear(in_features=1024, out_features=8, bias=False)
79 )
80 (block_sparse_moe): KimiSparseMoeBlock(
81 (experts): ModuleList(
82 (0-63): 64 x KimiBlockSparseMLP(
83 (w1): Linear(in_features=32, out_features=32, bias=False)
84 (w2): Linear(in_features=32, out_features=32, bias=False)
85 (w3): Linear(in_features=32, out_features=32, bias=False)
86 (act_fn): SituAndMul()
87 )
88 )
89 (gate): KimiMoEGate()
90 (shared_experts): KimiMLP(
91 (gate_proj): Linear(in_features=8, out_features=64, bias=False)
92 (up_proj): Linear(in_features=8, out_features=64, bias=False)
93 (down_proj): Linear(in_features=64, out_features=8, bias=False)
94 (act_fn): SituAndMul()
95 )
96 (routed_expert_down_proj): Linear(in_features=8, out_features=32, bias=False)
97 (routed_expert_up_proj): Linear(in_features=32, out_features=8, bias=False)
98 (routed_expert_norm): KimiRMSNorm()
99 )
100 (input_layernorm): KimiRMSNorm()
101 (post_attention_layernorm): KimiRMSNorm()
102 (self_attention_res_norm): KimiRMSNorm()
103 (mlp_res_norm): KimiRMSNorm()
104 (self_attention_res_proj): Linear(in_features=8, out_features=1, bias=False)
105 (mlp_res_proj): Linear(in_features=8, out_features=1, bias=False)
106 )
107 (3): KimiDecoderLayer(
108 (self_attn): KimiMLAAttention(
109 (q_a_proj): Linear(in_features=8, out_features=256, bias=False)
110 (q_a_layernorm): KimiRMSNorm()
111 (q_b_proj): Linear(in_features=256, out_features=1536, bias=False)
112 (kv_a_proj_with_mqa): Linear(in_features=8, out_features=576, bias=False)
113 (kv_a_layernorm): KimiRMSNorm()
114 (kv_b_proj): Linear(in_features=512, out_features=2048, bias=False)
115 (o_proj): Linear(in_features=1024, out_features=8, bias=False)
116 (g_proj): Linear(in_features=8, out_features=1024, bias=False)
117 )
118 (block_sparse_moe): KimiSparseMoeBlock(
119 (experts): ModuleList(
120 (0-63): 64 x KimiBlockSparseMLP(
121 (w1): Linear(in_features=32, out_features=32, bias=False)
122 (w2): Linear(in_features=32, out_features=32, bias=False)
123 (w3): Linear(in_features=32, out_features=32, bias=False)
124 (act_fn): SituAndMul()
125 )
126 )
127 (gate): KimiMoEGate()
128 (shared_experts): KimiMLP(
129 (gate_proj): Linear(in_features=8, out_features=64, bias=False)
130 (up_proj): Linear(in_features=8, out_features=64, bias=False)
131 (down_proj): Linear(in_features=64, out_features=8, bias=False)
132 (act_fn): SituAndMul()
133 )
134 (routed_expert_down_proj): Linear(in_features=8, out_features=32, bias=False)
135 (routed_expert_up_proj): Linear(in_features=32, out_features=8, bias=False)
136 (routed_expert_norm): KimiRMSNorm()
137 )
138 (input_layernorm): KimiRMSNorm()
139 (post_attention_layernorm): KimiRMSNorm()
140 (self_attention_res_norm): KimiRMSNorm()
141 (mlp_res_norm): KimiRMSNorm()
142 (self_attention_res_proj): Linear(in_features=8, out_features=1, bias=False)
143 (mlp_res_proj): Linear(in_features=8, out_features=1, bias=False)
144 )
145 (4-6): 3 x KimiDecoderLayer(
146 (self_attn): KimiDeltaAttention(
147 (q_proj): Linear(in_features=8, out_features=1024, bias=False)
148 (k_proj): Linear(in_features=8, out_features=1024, bias=False)
149 (v_proj): Linear(in_features=8, out_features=1024, bias=False)
150 (q_conv1d): ShortConvolution(1024, 1024, kernel_size=(4,), stride=(1,), padding=(3,), groups=1024, bias=False, activation=silu, backend=triton)
151 (k_conv1d): ShortConvolution(1024, 1024, kernel_size=(4,), stride=(1,), padding=(3,), groups=1024, bias=False, activation=silu, backend=triton)
152 (v_conv1d): ShortConvolution(1024, 1024, kernel_size=(4,), stride=(1,), padding=(3,), groups=1024, bias=False, activation=silu, backend=triton)
153 (f_a_proj): Linear(in_features=8, out_features=128, bias=False)
154 (f_b_proj): Linear(in_features=128, out_features=1024, bias=False)
155 (b_proj): Linear(in_features=8, out_features=8, bias=False)
156 (g_proj): Linear(in_features=8, out_features=1024, bias=False)
157 (o_norm): FusedRMSNormGated(128, eps=1e-05, activation=sigmoid)
158 (o_proj): Linear(in_features=1024, out_features=8, bias=False)
159 )
160 (block_sparse_moe): KimiSparseMoeBlock(
161 (experts): ModuleList(
162 (0-63): 64 x KimiBlockSparseMLP(
163 (w1): Linear(in_features=32, out_features=32, bias=False)
164 (w2): Linear(in_features=32, out_features=32, bias=False)
165 (w3): Linear(in_features=32, out_features=32, bias=False)
166 (act_fn): SituAndMul()
167 )
168 )
169 (gate): KimiMoEGate()
170 (shared_experts): KimiMLP(
171 (gate_proj): Linear(in_features=8, out_features=64, bias=False)
172 (up_proj): Linear(in_features=8, out_features=64, bias=False)
173 (down_proj): Linear(in_features=64, out_features=8, bias=False)
174 (act_fn): SituAndMul()
175 )
176 (routed_expert_down_proj): Linear(in_features=8, out_features=32, bias=False)
177 (routed_expert_up_proj): Linear(in_features=32, out_features=8, bias=False)
178 (routed_expert_norm): KimiRMSNorm()
179 )
180 (input_layernorm): KimiRMSNorm()
181 (post_attention_layernorm): KimiRMSNorm()
182 (self_attention_res_norm): KimiRMSNorm()
183 (mlp_res_norm): KimiRMSNorm()
184 (self_attention_res_proj): Linear(in_features=8, out_features=1, bias=False)
185 (mlp_res_proj): Linear(in_features=8, out_features=1, bias=False)
186 )
187 (7): KimiDecoderLayer(
188 (self_attn): KimiMLAAttention(
189 (q_a_proj): Linear(in_features=8, out_features=256, bias=False)
190 (q_a_layernorm): KimiRMSNorm()
191 (q_b_proj): Linear(in_features=256, out_features=1536, bias=False)
192 (kv_a_proj_with_mqa): Linear(in_features=8, out_features=576, bias=False)
193 (kv_a_layernorm): KimiRMSNorm()
194 (kv_b_proj): Linear(in_features=512, out_features=2048, bias=False)
195 (o_proj): Linear(in_features=1024, out_features=8, bias=False)
196 (g_proj): Linear(in_features=8, out_features=1024, bias=False)
197 )
198 (block_sparse_moe): KimiSparseMoeBlock(
199 (experts): ModuleList(
200 (0-63): 64 x KimiBlockSparseMLP(
201 (w1): Linear(in_features=32, out_features=32, bias=False)
202 (w2): Linear(in_features=32, out_features=32, bias=False)
203 (w3): Linear(in_features=32, out_features=32, bias=False)
204 (act_fn): SituAndMul()
205 )
206 )
207 (gate): KimiMoEGate()
208 (shared_experts): KimiMLP(
209 (gate_proj): Linear(in_features=8, out_features=64, bias=False)
210 (up_proj): Linear(in_features=8, out_features=64, bias=False)
211 (down_proj): Linear(in_features=64, out_features=8, bias=False)
212 (act_fn): SituAndMul()
213 )
214 (routed_expert_down_proj): Linear(in_features=8, out_features=32, bias=False)
215 (routed_expert_up_proj): Linear(in_features=32, out_features=8, bias=False)
216 (routed_expert_norm): KimiRMSNorm()
217 )
218 (input_layernorm): KimiRMSNorm()
219 (post_attention_layernorm): KimiRMSNorm()
220 (self_attention_res_norm): KimiRMSNorm()
221 (mlp_res_norm): KimiRMSNorm()
222 (self_attention_res_proj): Linear(in_features=8, out_features=1, bias=False)
223 (mlp_res_proj): Linear(in_features=8, out_features=1, bias=False)
224 )
225 (8-10): 3 x KimiDecoderLayer(
226 (self_attn): KimiDeltaAttention(
227 (q_proj): Linear(in_features=8, out_features=1024, bias=False)
228 (k_proj): Linear(in_features=8, out_features=1024, bias=False)
229 (v_proj): Linear(in_features=8, out_features=1024, bias=False)
230 (q_conv1d): ShortConvolution(1024, 1024, kernel_size=(4,), stride=(1,), padding=(3,), groups=1024, bias=False, activation=silu, backend=triton)
231 (k_conv1d): ShortConvolution(1024, 1024, kernel_size=(4,), stride=(1,), padding=(3,), groups=1024, bias=False, activation=silu, backend=triton)
232 (v_conv1d): ShortConvolution(1024, 1024, kernel_size=(4,), stride=(1,), padding=(3,), groups=1024, bias=False, activation=silu, backend=triton)
233 (f_a_proj): Linear(in_features=8, out_features=128, bias=False)
234 (f_b_proj): Linear(in_features=128, out_features=1024, bias=False)
235 (b_proj): Linear(in_features=8, out_features=8, bias=False)
236 (g_proj): Linear(in_features=8, out_features=1024, bias=False)
237 (o_norm): FusedRMSNormGated(128, eps=1e-05, activation=sigmoid)
238 (o_proj): Linear(in_features=1024, out_features=8, bias=False)
239 )
240 (block_sparse_moe): KimiSparseMoeBlock(
241 (experts): ModuleList(
242 (0-63): 64 x KimiBlockSparseMLP(
243 (w1): Linear(in_features=32, out_features=32, bias=False)
244 (w2): Linear(in_features=32, out_features=32, bias=False)
245 (w3): Linear(in_features=32, out_features=32, bias=False)
246 (act_fn): SituAndMul()
247 )
248 )
249 (gate): KimiMoEGate()
250 (shared_experts): KimiMLP(
251 (gate_proj): Linear(in_features=8, out_features=64, bias=False)
252 (up_proj): Linear(in_features=8, out_features=64, bias=False)
253 (down_proj): Linear(in_features=64, out_features=8, bias=False)
254 (act_fn): SituAndMul()
255 )
256 (routed_expert_down_proj): Linear(in_features=8, out_features=32, bias=False)
257 (routed_expert_up_proj): Linear(in_features=32, out_features=8, bias=False)
258 (routed_expert_norm): KimiRMSNorm()
259 )
260 (input_layernorm): KimiRMSNorm()
261 (post_attention_layernorm): KimiRMSNorm()
262 (self_attention_res_norm): KimiRMSNorm()
263 (mlp_res_norm): KimiRMSNorm()
264 (self_attention_res_proj): Linear(in_features=8, out_features=1, bias=False)
265 (mlp_res_proj): Linear(in_features=8, out_features=1, bias=False)
266 )
267 (11): KimiDecoderLayer(
268 (self_attn): KimiMLAAttention(
269 (q_a_proj): Linear(in_features=8, out_features=256, bias=False)
270 (q_a_layernorm): KimiRMSNorm()
271 (q_b_proj): Linear(in_features=256, out_features=1536, bias=False)
272 (kv_a_proj_with_mqa): Linear(in_features=8, out_features=576, bias=False)
273 (kv_a_layernorm): KimiRMSNorm()
274 (kv_b_proj): Linear(in_features=512, out_features=2048, bias=False)
275 (o_proj): Linear(in_features=1024, out_features=8, bias=False)
276 (g_proj): Linear(in_features=8, out_features=1024, bias=False)
277 )
278 (block_sparse_moe): KimiSparseMoeBlock(
279 (experts): ModuleList(
280 (0-63): 64 x KimiBlockSparseMLP(
281 (w1): Linear(in_features=32, out_features=32, bias=False)
282 (w2): Linear(in_features=32, out_features=32, bias=False)
283 (w3): Linear(in_features=32, out_features=32, bias=False)
284 (act_fn): SituAndMul()
285 )
286 )
287 (gate): KimiMoEGate()
288 (shared_experts): KimiMLP(
289 (gate_proj): Linear(in_features=8, out_features=64, bias=False)
290 (up_proj): Linear(in_features=8, out_features=64, bias=False)
291 (down_proj): Linear(in_features=64, out_features=8, bias=False)
292 (act_fn): SituAndMul()
293 )
294 (routed_expert_down_proj): Linear(in_features=8, out_features=32, bias=False)
295 (routed_expert_up_proj): Linear(in_features=32, out_features=8, bias=False)
296 (routed_expert_norm): KimiRMSNorm()
297 )
298 (input_layernorm): KimiRMSNorm()
299 (post_attention_layernorm): KimiRMSNorm()
300 (self_attention_res_norm): KimiRMSNorm()
301 (mlp_res_norm): KimiRMSNorm()
302 (self_attention_res_proj): Linear(in_features=8, out_features=1, bias=False)
303 (mlp_res_proj): Linear(in_features=8, out_features=1, bias=False)
304 )
305 (12-14): 3 x KimiDecoderLayer(
306 (self_attn): KimiDeltaAttention(
307 (q_proj): Linear(in_features=8, out_features=1024, bias=False)
308 (k_proj): Linear(in_features=8, out_features=1024, bias=False)
309 (v_proj): Linear(in_features=8, out_features=1024, bias=False)
310 (q_conv1d): ShortConvolution(1024, 1024, kernel_size=(4,), stride=(1,), padding=(3,), groups=1024, bias=False, activation=silu, backend=triton)
311 (k_conv1d): ShortConvolution(1024, 1024, kernel_size=(4,), stride=(1,), padding=(3,), groups=1024, bias=False, activation=silu, backend=triton)
312 (v_conv1d): ShortConvolution(1024, 1024, kernel_size=(4,), stride=(1,), padding=(3,), groups=1024, bias=False, activation=silu, backend=triton)
313 (f_a_proj): Linear(in_features=8, out_features=128, bias=False)
314 (f_b_proj): Linear(in_features=128, out_features=1024, bias=False)
315 (b_proj): Linear(in_features=8, out_features=8, bias=False)
316 (g_proj): Linear(in_features=8, out_features=1024, bias=False)
317 (o_norm): FusedRMSNormGated(128, eps=1e-05, activation=sigmoid)
318 (o_proj): Linear(in_features=1024, out_features=8, bias=False)
319 )
320 (block_sparse_moe): KimiSparseMoeBlock(
321 (experts): ModuleList(
322 (0-63): 64 x KimiBlockSparseMLP(
323 (w1): Linear(in_features=32, out_features=32, bias=False)
324 (w2): Linear(in_features=32, out_features=32, bias=False)
325 (w3): Linear(in_features=32, out_features=32, bias=False)
326 (act_fn): SituAndMul()
327 )
328 )
329 (gate): KimiMoEGate()
330 (shared_experts): KimiMLP(
331 (gate_proj): Linear(in_features=8, out_features=64, bias=False)
332 (up_proj): Linear(in_features=8, out_features=64, bias=False)
333 (down_proj): Linear(in_features=64, out_features=8, bias=False)
334 (act_fn): SituAndMul()
335 )
336 (routed_expert_down_proj): Linear(in_features=8, out_features=32, bias=False)
337 (routed_expert_up_proj): Linear(in_features=32, out_features=8, bias=False)
338 (routed_expert_norm): KimiRMSNorm()
339 )
340 (input_layernorm): KimiRMSNorm()
341 (post_attention_layernorm): KimiRMSNorm()
342 (self_attention_res_norm): KimiRMSNorm()
343 (mlp_res_norm): KimiRMSNorm()
344 (self_attention_res_proj): Linear(in_features=8, out_features=1, bias=False)
345 (mlp_res_proj): Linear(in_features=8, out_features=1, bias=False)
346 )
347 (15-16): 2 x KimiDecoderLayer(
348 (self_attn): KimiMLAAttention(
349 (q_a_proj): Linear(in_features=8, out_features=256, bias=False)
350 (q_a_layernorm): KimiRMSNorm()
351 (q_b_proj): Linear(in_features=256, out_features=1536, bias=False)
352 (kv_a_proj_with_mqa): Linear(in_features=8, out_features=576, bias=False)
353 (kv_a_layernorm): KimiRMSNorm()
354 (kv_b_proj): Linear(in_features=512, out_features=2048, bias=False)
355 (o_proj): Linear(in_features=1024, out_features=8, bias=False)
356 (g_proj): Linear(in_features=8, out_features=1024, bias=False)
357 )
358 (block_sparse_moe): KimiSparseMoeBlock(
359 (experts): ModuleList(
360 (0-63): 64 x KimiBlockSparseMLP(
361 (w1): Linear(in_features=32, out_features=32, bias=False)
362 (w2): Linear(in_features=32, out_features=32, bias=False)
363 (w3): Linear(in_features=32, out_features=32, bias=False)
364 (act_fn): SituAndMul()
365 )
366 )
367 (gate): KimiMoEGate()
368 (shared_experts): KimiMLP(
369 (gate_proj): Linear(in_features=8, out_features=64, bias=False)
370 (up_proj): Linear(in_features=8, out_features=64, bias=False)
371 (down_proj): Linear(in_features=64, out_features=8, bias=False)
372 (act_fn): SituAndMul()
373 )
374 (routed_expert_down_proj): Linear(in_features=8, out_features=32, bias=False)
375 (routed_expert_up_proj): Linear(in_features=32, out_features=8, bias=False)
376 (routed_expert_norm): KimiRMSNorm()
377 )
378 (input_layernorm): KimiRMSNorm()
379 (post_attention_layernorm): KimiRMSNorm()
380 (self_attention_res_norm): KimiRMSNorm()
381 (mlp_res_norm): KimiRMSNorm()
382 (self_attention_res_proj): Linear(in_features=8, out_features=1, bias=False)
383 (mlp_res_proj): Linear(in_features=8, out_features=1, bias=False)
384 )
385 )
386 (norm): KimiRMSNorm()
387 (output_attn_res_norm): KimiRMSNorm()
388 (output_attn_res_proj): Linear(in_features=8, out_features=1, bias=False)
389 )
390 (lm_head): Linear(in_features=8, out_features=163840, bias=False)
391 )
392)