Views
No views yet
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, group_size=32 | Same |
| Vision head_dim | 32 | Same |
| MTP | None | None |
| File path | Size |
|---|---|
| model.safetensors | 133.5MB |
1# Tested on NVIDIA H20. If you run into issues, please open an issue.
2VLLM_ENABLE_K3_LATENT_MOE_TAIL_FUSION=1 \
3FLASHINFER_DISABLE_VERSION_CHECK=1 \
4VLLM_ENABLE_CUDA_COMPATIBILITY=1 \
5VLLM_CUDA_COMPATIBILITY_PATH=/usr/local/cuda/compat \
6vllm serve yujiepan/kimi-k3-tiny-random \
7 --trust-remote-code \
8 --tensor-parallel-size 2 \
9 --load-format safetensors \
10 --moe-backend marlin \
11 --gpu-memory-utilization 0.70 \
12 --compilation-config '{"cudagraph_mode":"FULL","cudagraph_capture_sizes":[1,2,4,8],"max_cudagraph_capture_size":8}'1# Not verified yet; this mirrors the vLLM-tested parallelism and backend choices.
2python3 -m sglang.launch_server \
3 --model-path yujiepan/kimi-k3-tiny-random \
4 --trust-remote-code \
5 --tp-size 2 \
6 --ep-size 2 \
7 --moe-runner-backend marlin \
8 --decode-attention-backend flashmla \
9 --mamba-full-memory-ratio 0.45 \
10 --mem-fraction-static 0.70 \
11 --cuda-graph-max-bs 81import numpy as np
2import torch
3from PIL import Image
4from transformers import AutoModel, AutoProcessor
5
6model_id = "yujiepan/kimi-k3-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-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
171quantization_config = config_json['text_config'].pop('quantization_config')
172# Upstream declares every Linear as a target, but the released shards and
173# community loaders agree that only routed expert w1/w2/w3 are MXFP4.
174# Narrow only the scope; preserve format, 4-bit float encoding,
175# group_size=32, U8 E8M0 scales, symmetry, and all other strategy fields.
176quantization_config['config_groups']['group_0']['targets'] = [
177 're:.*block_sparse_moe\\.experts\\.\\d+\\.(w1|w2|w3)$'
178]
179
180# Preserve the kernel-sensitive dims from upstream: KDA head_dim=128,
181# MLA kv_lora_rank=512, qk_nope=128, qk_rope=64, v=128, conv kernel=4.
182# vLLM's Kimi fused MLA decode kernel requires latent KV rank 512 and
183# cache/query head size 512 + 64 = 576, so only shrink head count and
184# q_lora_rank; q_b_proj still drops 54MB->0.75MB.
185# Keep the upstream cadence: four 4-layer groups plus the final MLA layer.
186# One attention-residual checkpoint every two groups (block_size=8), so
187# block boundaries land on layers 0, 8, 16 (0-based).
188# MXFP4 only targets routed expert w1/w2/w3, whose input dims are
189# routed_expert_hidden_size / moe_intermediate_size, so those two must stay
190# divisible by group_size=32; hidden_size itself is never quantized and can
191# shrink to 8. Inference engines pad MXFP4 buffers (sglang/vllm round the
192# per-partition intermediate up to 128 and hidden up to 256, packing 2
193# codes per byte along hidden) and their weight loaders only tolerate
194# padding along the shard dim, so keep intermediate >= 256 (128 per
195# partition at TP2) and routed_expert_hidden_size >= 256.
196config_json['text_config'].update({
197 'attn_res_block_size': 8,
198 'first_k_dense_replace': 1,
199 'hidden_size': 8,
200 'intermediate_size': 32,
201 'kv_lora_rank': 512,
202 'moe_intermediate_size': 256,
203 'num_attention_heads': 8,
204 'num_experts': 64,
205 'num_hidden_layers': 17,
206 'num_key_value_heads': 8,
207 'q_lora_rank': 256,
208 'routed_expert_hidden_size': 256,
209 '_attn_implementation': 'eager',
210})
211config_json['text_config']['linear_attn_config'].update({
212 'full_attn_layers': [4, 8, 12, 16, 17],
213 'kda_layers': [1, 2, 3, 5, 6, 7, 9, 10, 11, 13, 14, 15],
214 'num_heads': 8,
215})
216config_json['vision_config'].update({
217 '_attn_implementation': 'eager',
218 'init_pos_emb_height': 8,
219 'init_pos_emb_width': 8,
220 'mm_hidden_size': 64,
221 'qkv_hidden_size': 64,
222 'text_hidden_size': 8,
223 'vt_hidden_size': 64,
224 'vt_intermediate_size': 128,
225 # Vision attention head size = qkv_hidden_size / heads = 64 / 2 = 32.
226 'vt_num_attention_heads': 2,
227 'vt_num_hidden_layers': 2,
228})
229with open(f'{save_folder}/config.json', 'w', encoding='utf-8') as f:
230 json.dump(config_json, f, indent=2)
231
232config = AutoConfig.from_pretrained(save_folder, trust_remote_code=True)
233print(config)
234torch.set_default_dtype(torch.bfloat16)
235model = AutoModel.from_config(
236 config,
237 trust_remote_code=True,
238 attn_implementation='eager',
239)
240torch.set_default_dtype(torch.float32)
241if file_exists(
242 filename='generation_config.json',
243 repo_id=source_model_id,
244 repo_type='model',
245 revision=source_revision,
246):
247 model.generation_config = GenerationConfig.from_pretrained(
248 source_model_id,
249 trust_remote_code=True,
250 revision=source_revision,
251 )
252set_seed(42)
253model = model.cpu()
254num_params = sum(p.numel() for p in model.parameters())
255with torch.no_grad():
256 for name, parameter in sorted(model.named_parameters()):
257 torch.nn.init.normal_(parameter, 0, 0.1)
258 print(name, parameter.shape, parameter.dtype, f'{parameter.numel() / num_params:.2%}')
259model.save_pretrained(save_folder)
260
261# Match the official checkpoint schema: routed experts are native MXFP4
262# (two values per U8 byte, one E8M0 scale per group of 32 values).
263model_path = Path(save_folder) / 'model.safetensors'
264state_dict = load_file(str(model_path))
265fp4_boundaries = torch.tensor([0.25, 0.75, 1.25, 1.75, 2.5, 3.5, 5.0])
266for name in list(state_dict):
267 if '.block_sparse_moe.experts.' in name and name.endswith('.weight'):
268 weight = state_dict.pop(name).float()
269 out_features, in_features = weight.shape
270 assert in_features % 32 == 0
271 packed_name = name.removesuffix('.weight') + '.weight_packed'
272 scale_name = name.removesuffix('.weight') + '.weight_scale'
273 blocks = weight.view(out_features, in_features // 32, 32)
274 # E2M1 represents magnitudes {0, .5, 1, 1.5, 2, 3, 4, 6}.
275 # E8M0 stores the shared power-of-two scale as exponent + bias 127.
276 scale_exponents = torch.round(
277 torch.log2(blocks.abs().amax(dim=-1).clamp_min(torch.finfo(torch.float32).tiny) / 6)
278 ).clamp(-126, 127)
279 scales = torch.pow(2.0, scale_exponents)
280 normalized = (blocks / scales.unsqueeze(-1)).clamp(-6, 6)
281 codes = torch.bucketize(normalized.abs(), fp4_boundaries)
282 codes += normalized.signbit() * 8
283 codes = codes.view(out_features, in_features)
284 state_dict[packed_name] = (
285 codes[:, ::2] | (codes[:, 1::2] << 4)
286 ).to(torch.uint8)
287 state_dict[scale_name] = (scale_exponents + 127).to(torch.uint8)
288 elif name.endswith((
289 '.block_sparse_moe.gate.e_score_correction_bias',
290 '.self_attn.A_log',
291 '.self_attn.dt_bias',
292 '.self_attn.k_conv1d.weight',
293 '.self_attn.o_norm.weight',
294 '.self_attn.q_conv1d.weight',
295 '.self_attn.v_conv1d.weight',
296 )):
297 state_dict[name] = state_dict[name].float()
298dtype_counts = {
299 dtype: sum(tensor.dtype == dtype for tensor in state_dict.values())
300 for dtype in (torch.bfloat16, torch.float32, torch.uint8)
301}
302# Derive the expected schema from the config instead of hardcoding counts:
303# each MoE layer has num_experts × (w1|w2|w3) × (packed, scale) U8 tensors,
304# and F32 tensors are per-MoE e_score_correction_bias plus per-KDA A_log,
305# dt_bias, o_norm, and k/q/v conv1d weights.
306text_cfg = config_json['text_config']
307num_moe_layers = text_cfg['num_hidden_layers'] - text_cfg['first_k_dense_replace']
308num_kda_layers = len(text_cfg['linear_attn_config']['kda_layers'])
309expected_uint8 = num_moe_layers * text_cfg['num_experts'] * 3 * 2
310expected_f32 = num_moe_layers + num_kda_layers * 6
311assert dtype_counts == {
312 torch.bfloat16: len(state_dict) - expected_uint8 - expected_f32,
313 torch.float32: expected_f32,
314 torch.uint8: expected_uint8,
315}
316assert not any('mtp' in name.lower() for name in state_dict)
317print('Top 20 keys with largest storage size:')
318for name, tensor in sorted(state_dict.items(), key=lambda x: x[1].numel() * x[1].element_size(), reverse=True)[:20]:
319 print(f'{name}: {tensor.numel()} elements, {tensor.numel() * tensor.element_size() / 1024**2:.2f} MB')
320save_file(state_dict, str(model_path), metadata={'format': 'pt'})
321
322with open(f'{save_folder}/config.json', encoding='utf-8') as f:
323 saved_config = json.load(f)
324saved_config['quantization_config'] = quantization_config
325saved_config['text_config']['quantization_config'] = quantization_config
326with open(f'{save_folder}/config.json', 'w', encoding='utf-8') as f:
327 json.dump(saved_config, f, indent=2)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=256, out_features=256, bias=False)
84 (w2): Linear(in_features=256, out_features=256, bias=False)
85 (w3): Linear(in_features=256, out_features=256, bias=False)
86 (act_fn): SituAndMul()
87 )
88 )
89 (gate): KimiMoEGate()
90 (shared_experts): KimiMLP(
91 (gate_proj): Linear(in_features=8, out_features=512, bias=False)
92 (up_proj): Linear(in_features=8, out_features=512, bias=False)
93 (down_proj): Linear(in_features=512, out_features=8, bias=False)
94 (act_fn): SituAndMul()
95 )
96 (routed_expert_down_proj): Linear(in_features=8, out_features=256, bias=False)
97 (routed_expert_up_proj): Linear(in_features=256, 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=256, out_features=256, bias=False)
122 (w2): Linear(in_features=256, out_features=256, bias=False)
123 (w3): Linear(in_features=256, out_features=256, bias=False)
124 (act_fn): SituAndMul()
125 )
126 )
127 (gate): KimiMoEGate()
128 (shared_experts): KimiMLP(
129 (gate_proj): Linear(in_features=8, out_features=512, bias=False)
130 (up_proj): Linear(in_features=8, out_features=512, bias=False)
131 (down_proj): Linear(in_features=512, out_features=8, bias=False)
132 (act_fn): SituAndMul()
133 )
134 (routed_expert_down_proj): Linear(in_features=8, out_features=256, bias=False)
135 (routed_expert_up_proj): Linear(in_features=256, 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=256, out_features=256, bias=False)
164 (w2): Linear(in_features=256, out_features=256, bias=False)
165 (w3): Linear(in_features=256, out_features=256, bias=False)
166 (act_fn): SituAndMul()
167 )
168 )
169 (gate): KimiMoEGate()
170 (shared_experts): KimiMLP(
171 (gate_proj): Linear(in_features=8, out_features=512, bias=False)
172 (up_proj): Linear(in_features=8, out_features=512, bias=False)
173 (down_proj): Linear(in_features=512, out_features=8, bias=False)
174 (act_fn): SituAndMul()
175 )
176 (routed_expert_down_proj): Linear(in_features=8, out_features=256, bias=False)
177 (routed_expert_up_proj): Linear(in_features=256, 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=256, out_features=256, bias=False)
202 (w2): Linear(in_features=256, out_features=256, bias=False)
203 (w3): Linear(in_features=256, out_features=256, bias=False)
204 (act_fn): SituAndMul()
205 )
206 )
207 (gate): KimiMoEGate()
208 (shared_experts): KimiMLP(
209 (gate_proj): Linear(in_features=8, out_features=512, bias=False)
210 (up_proj): Linear(in_features=8, out_features=512, bias=False)
211 (down_proj): Linear(in_features=512, out_features=8, bias=False)
212 (act_fn): SituAndMul()
213 )
214 (routed_expert_down_proj): Linear(in_features=8, out_features=256, bias=False)
215 (routed_expert_up_proj): Linear(in_features=256, 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=256, out_features=256, bias=False)
244 (w2): Linear(in_features=256, out_features=256, bias=False)
245 (w3): Linear(in_features=256, out_features=256, bias=False)
246 (act_fn): SituAndMul()
247 )
248 )
249 (gate): KimiMoEGate()
250 (shared_experts): KimiMLP(
251 (gate_proj): Linear(in_features=8, out_features=512, bias=False)
252 (up_proj): Linear(in_features=8, out_features=512, bias=False)
253 (down_proj): Linear(in_features=512, out_features=8, bias=False)
254 (act_fn): SituAndMul()
255 )
256 (routed_expert_down_proj): Linear(in_features=8, out_features=256, bias=False)
257 (routed_expert_up_proj): Linear(in_features=256, 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=256, out_features=256, bias=False)
282 (w2): Linear(in_features=256, out_features=256, bias=False)
283 (w3): Linear(in_features=256, out_features=256, bias=False)
284 (act_fn): SituAndMul()
285 )
286 )
287 (gate): KimiMoEGate()
288 (shared_experts): KimiMLP(
289 (gate_proj): Linear(in_features=8, out_features=512, bias=False)
290 (up_proj): Linear(in_features=8, out_features=512, bias=False)
291 (down_proj): Linear(in_features=512, out_features=8, bias=False)
292 (act_fn): SituAndMul()
293 )
294 (routed_expert_down_proj): Linear(in_features=8, out_features=256, bias=False)
295 (routed_expert_up_proj): Linear(in_features=256, 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=256, out_features=256, bias=False)
324 (w2): Linear(in_features=256, out_features=256, bias=False)
325 (w3): Linear(in_features=256, out_features=256, bias=False)
326 (act_fn): SituAndMul()
327 )
328 )
329 (gate): KimiMoEGate()
330 (shared_experts): KimiMLP(
331 (gate_proj): Linear(in_features=8, out_features=512, bias=False)
332 (up_proj): Linear(in_features=8, out_features=512, bias=False)
333 (down_proj): Linear(in_features=512, out_features=8, bias=False)
334 (act_fn): SituAndMul()
335 )
336 (routed_expert_down_proj): Linear(in_features=8, out_features=256, bias=False)
337 (routed_expert_up_proj): Linear(in_features=256, 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=256, out_features=256, bias=False)
362 (w2): Linear(in_features=256, out_features=256, bias=False)
363 (w3): Linear(in_features=256, out_features=256, bias=False)
364 (act_fn): SituAndMul()
365 )
366 )
367 (gate): KimiMoEGate()
368 (shared_experts): KimiMLP(
369 (gate_proj): Linear(in_features=8, out_features=512, bias=False)
370 (up_proj): Linear(in_features=8, out_features=512, bias=False)
371 (down_proj): Linear(in_features=512, out_features=8, bias=False)
372 (act_fn): SituAndMul()
373 )
374 (routed_expert_down_proj): Linear(in_features=8, out_features=256, bias=False)
375 (routed_expert_up_proj): Linear(in_features=256, 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)