Image-Text-to-Text
Transformers
Safetensors
kimi_k3
feature-extraction
custom_code
8-bit precision
compressed-tensors
Instructions to use tiny-random/kimi-k3 with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use tiny-random/kimi-k3 with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("image-text-to-text", model="tiny-random/kimi-k3", trust_remote_code=True)# Load model directly from transformers import AutoModel model = AutoModel.from_pretrained("tiny-random/kimi-k3", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use tiny-random/kimi-k3 with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "tiny-random/kimi-k3" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "tiny-random/kimi-k3", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker
docker model run hf.co/tiny-random/kimi-k3
- SGLang
How to use tiny-random/kimi-k3 with SGLang:
Install from pip and serve model
# Install SGLang from pip: pip install sglang # Start the SGLang server: python3 -m sglang.launch_server \ --model-path "tiny-random/kimi-k3" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "tiny-random/kimi-k3", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker images
docker run --gpus all \ --shm-size 32g \ -p 30000:30000 \ -v ~/.cache/huggingface:/root/.cache/huggingface \ --env "HF_TOKEN=<secret>" \ --ipc=host \ lmsysorg/sglang:latest \ python3 -m sglang.launch_server \ --model-path "tiny-random/kimi-k3" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "tiny-random/kimi-k3", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }' - Docker Model Runner
How to use tiny-random/kimi-k3 with Docker Model Runner:
docker model run hf.co/tiny-random/kimi-k3
File size: 41,528 Bytes
6462954 30ed905 6462954 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 | ---
library_name: transformers
base_model:
- moonshotai/Kimi-K3
pipeline_tag: image-text-to-text
---
This tiny model is intended for debugging. It is randomly initialized using the configuration adapted from [moonshotai/Kimi-K3](https://huggingface.co/moonshotai/Kimi-K3).
Note:
- Structural comparison with the original `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 |
- What is shrunk: layer count (93 -> 17), residual width (hidden_size=8),
attention heads (96 -> 8) and MLA q LoRA rank (1536 -> 256). The
kv_lora_rank stays 512 because vLLM's Kimi fused MLA decode kernel requires
cache/query head size 512 + 64 = 576. Per-head dims are unchanged; routed experts (896 -> 64,
still >> top-k=16), expert/MLP intermediate sizes, and vision width/depth.
- The creation of this model was assisted by GPT-5.5 and Kimi-K3.
| File path | Size |
|------|------|
| model.safetensors | 133.5MB |
### Example usage:
- vLLM
```bash
# Tested on NVIDIA H20. If you run into issues, please open an issue.
VLLM_ENABLE_K3_LATENT_MOE_TAIL_FUSION=1 \
FLASHINFER_DISABLE_VERSION_CHECK=1 \
VLLM_ENABLE_CUDA_COMPATIBILITY=1 \
VLLM_CUDA_COMPATIBILITY_PATH=/usr/local/cuda/compat \
vllm serve tiny-random/kimi-k3 \
--trust-remote-code \
--tensor-parallel-size 2 \
--load-format safetensors \
--moe-backend marlin \
--gpu-memory-utilization 0.70 \
--compilation-config '{"cudagraph_mode":"FULL","cudagraph_capture_sizes":[1,2,4,8],"max_cudagraph_capture_size":8}'
```
- SGLang
```bash
# Not verified yet; this mirrors the vLLM-tested parallelism and backend choices.
python3 -m sglang.launch_server \
--model-path tiny-random/kimi-k3 \
--trust-remote-code \
--tp-size 2 \
--ep-size 2 \
--moe-runner-backend marlin \
--decode-attention-backend flashmla \
--mamba-full-memory-ratio 0.45 \
--mem-fraction-static 0.70 \
--cuda-graph-max-bs 8
```
- Transformers
```python
import numpy as np
import torch
from PIL import Image
from transformers import AutoModel, AutoProcessor
model_id = "tiny-random/kimi-k3"
processor = AutoProcessor.from_pretrained(model_id, trust_remote_code=True)
model = AutoModel.from_pretrained(
model_id,
dtype=torch.bfloat16,
device_map='cuda',
trust_remote_code=True,
attn_implementation='eager',
).eval()
image = Image.fromarray(np.random.default_rng(42).integers(0, 256, (56, 56, 3), dtype=np.uint8))
tools = [{
'type': 'function',
'function': {
'name': 'get_image_size',
'description': 'Return the width and height of an image.',
'parameters': {
'type': 'object',
'properties': {
'image_index': {'type': 'integer', 'description': 'Zero-based image index.'},
},
'required': ['image_index'],
},
},
}]
messages = [{
'role': 'user',
'content': [
{'type': 'image', 'image': image},
{'type': 'text', 'text': 'Use the available tool to get this image size.'},
],
}]
inputs = processor(
messages=messages,
tools=tools,
tool_choice='required',
return_tensors='pt',
).to(model.device)
with torch.no_grad():
outputs = model.generate(**inputs, max_new_tokens=32)
generated_ids = outputs.sequences if hasattr(outputs, 'sequences') else outputs
print(processor.decode(generated_ids[0].detach().cpu().tolist()))
```
### Codes to create this repo:
<details><summary>Click to expand</summary>
```python
import json
from pathlib import Path
import accelerate
import torch
from huggingface_hub import file_exists, hf_hub_download, list_repo_files
from safetensors.torch import load_file, save_file
from transformers import AutoConfig, AutoModel, GenerationConfig, set_seed
source_model_id = "moonshotai/Kimi-K3"
save_folder = "/tmp/tiny-random/kimi-k3" # pyright: ignore[reportUnusedExpression] # codegen marker
Path(save_folder).mkdir(parents=True, exist_ok=True)
suffixes = ['.json', '.py', '.model', '.jinja']
for filename in list_repo_files(
source_model_id,
repo_type='model',
revision=source_revision,
):
if any(filename.endswith(suffix) for suffix in suffixes) and not filename.endswith('.index.json'):
hf_hub_download(
repo_id=source_model_id,
filename=filename,
repo_type='model',
revision=source_revision,
local_dir=save_folder,
)
def replace_file(filepath, replacements):
with open(filepath, 'r', encoding='utf-8') as f:
code = f.read()
for old_string, new_string in replacements:
if old_string not in code:
if new_string in code:
continue
raise ValueError(f'Expected code was not found in {filepath}: {old_string}')
code = code.replace(old_string, new_string)
with open(filepath, 'w', encoding='utf-8') as f:
f.write(code)
# The upstream reference implementation forces FlashAttention for MLA even
# when eager attention is requested. Allow the tiny MLA layer to use eager
# attention without requiring the separate flash-attn package.
force_flash_code = ''' if getattr(config, "_attn_implementation", None) is not None:
if config._attn_implementation != "flash_attention_2":
logger.warning_once(
f"Ignoring the provided attention implementation {config._attn_implementation}")
logger.warning_once("Using flash_attention_2 backend instead.")
config._attn_implementation = "flash_attention_2"
else:
config._attn_implementation = "flash_attention_2"'''
per_channel_gate_code = ''' g = self.f_b_proj(self.f_a_proj(hidden_states))
g = rearrange(g, '... (h d) -> ... h d', d=self.head_dim)
beta = self.b_proj(hidden_states).float()'''
per_channel_gate_compat_code = ''' g = self.f_b_proj(self.f_a_proj(hidden_states))
g = rearrange(g, '... (h d) -> ... h d', d=self.head_dim)
# The released K3 checkpoint stores per-channel decay shared by all heads.
g = self.gate_lower_bound * torch.sigmoid(
self.A_log.float().exp().view(1, 1, 1, self.head_dim)
* (g.float() + self.dt_bias.float().view(1, 1, self.num_heads, self.head_dim))
).to(g.dtype)
beta = self.b_proj(hidden_states).float()'''
causal_mask_code = ''' causal_mask = create_causal_mask(
config=self.config,
input_embeds=inputs_embeds,
attention_mask=attention_mask,
cache_position=cache_position,
past_key_values=past_key_values,
position_ids=position_ids,
)'''
causal_mask_compat_code = ''' if version.parse(transformers.__version__) >= version.parse("5.0.0"):
causal_mask = create_causal_mask(
config=self.config,
inputs_embeds=inputs_embeds,
attention_mask=attention_mask,
past_key_values=past_key_values,
position_ids=position_ids,
)
else:
causal_mask = create_causal_mask(
config=self.config,
input_embeds=inputs_embeds,
attention_mask=attention_mask,
cache_position=cache_position,
past_key_values=past_key_values,
position_ids=position_ids,
)'''
cache_api_code = ''' def get_mask_sizes(self, cache_position: torch.Tensor, layer_idx: int) -> tuple[int, int]:
"""
Return a tuple (kv_length, kv_offset) corresponding to the length and offset that will be returned for
the given layer at `layer_idx`.
The masks are then prepared according to the given lengths (kv_length, kv_offset) and patterns for each layer.
"""
kv_offset = 0
query_length = cache_position.shape[0]'''
cache_api_compat_code = ''' def get_query_offset(self, layer_idx: int) -> int:
return self.get_seq_length(layer_idx)
def get_mask_sizes(self, cache_position: torch.Tensor | int, layer_idx: int) -> tuple[int, int]:
"""
Return a tuple (kv_length, kv_offset) corresponding to the length and offset that will be returned for
the given layer at `layer_idx`.
The masks are then prepared according to the given lengths (kv_length, kv_offset) and patterns for each layer.
"""
kv_offset = 0
query_length = cache_position if isinstance(cache_position, int) else cache_position.shape[0]'''
replace_file(f'{save_folder}/modeling_kimi_linear.py', [
# Transformers 5 compatibility.
(
'from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel',
'from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, OutputRecorder, PreTrainedModel',
),
(
'from transformers.utils.generic import OutputRecorder, check_model_inputs',
'from transformers.utils.generic import check_model_inputs',
),
(
' _tied_weights_keys = ["lm_head.weight"]',
''' _tied_weights_keys = (
{"lm_head.weight": "model.embed_tokens.weight"}
if version.parse(transformers.__version__) >= version.parse("5.0.0")
else ["lm_head.weight"]
)''',
),
(causal_mask_code, causal_mask_compat_code),
(cache_api_code, cache_api_compat_code),
# Allow eager MLA instead of forcing the optional flash-attn package.
(
force_flash_code,
' config._attn_implementation = getattr(config, "_attn_implementation", "eager")',
),
# Fix stale K3 reference code: released shards store A_log as
# [head_dim], and the decay is applied per channel across all heads.
(
' self.num_heads, dtype=torch.float32).uniform_(1, 16)))',
' self.head_dim, dtype=torch.float32).uniform_(1, 16)))',
),
(per_channel_gate_code, per_channel_gate_compat_code),
(
''' use_qk_l2norm_in_kernel=True,
use_gate_in_kernel=True,
use_beta_sigmoid_in_kernel=True,''',
''' use_qk_l2norm_in_kernel=True,
use_gate_in_kernel=False,
use_beta_sigmoid_in_kernel=True,''',
),
(
' safe_gate=self.gate_lower_bound is not None,',
' safe_gate=False,',
),
])
replace_file(f'{save_folder}/modeling_kimi_k3.py', [
(' def tie_weights(self):', ' def tie_weights(self, *args, **kwargs):'),
(" _supports_sdpa = True", " _supports_sdpa = False"),
(
' first_layer_past_key_value = past_key_values[0][0][:, :, :, 0]',
''' if hasattr(past_key_values, "key_cache"):
first_key_cache = next(
key_cache for key_cache in past_key_values.key_cache if key_cache is not None
)
first_layer_past_key_value = first_key_cache[:, :, :, 0]
else:
first_layer_past_key_value = past_key_values[0][0][:, :, :, 0]''',
),
])
with open(f'{save_folder}/config.json', encoding='utf-8') as f:
config_json = json.load(f)
quantization_config = config_json['text_config'].pop('quantization_config')
# Upstream declares every Linear as a target, but the released shards and
# community loaders agree that only routed expert w1/w2/w3 are MXFP4.
# Narrow only the scope; preserve format, 4-bit float encoding,
# group_size=32, U8 E8M0 scales, symmetry, and all other strategy fields.
quantization_config['config_groups']['group_0']['targets'] = [
're:.*block_sparse_moe\\.experts\\.\\d+\\.(w1|w2|w3)$'
]
# Preserve the kernel-sensitive dims from upstream: KDA head_dim=128,
# MLA kv_lora_rank=512, qk_nope=128, qk_rope=64, v=128, conv kernel=4.
# vLLM's Kimi fused MLA decode kernel requires latent KV rank 512 and
# cache/query head size 512 + 64 = 576, so only shrink head count and
# q_lora_rank; q_b_proj still drops 54MB->0.75MB.
# Keep the upstream cadence: four 4-layer groups plus the final MLA layer.
# One attention-residual checkpoint every two groups (block_size=8), so
# block boundaries land on layers 0, 8, 16 (0-based).
# MXFP4 only targets routed expert w1/w2/w3, whose input dims are
# routed_expert_hidden_size / moe_intermediate_size, so those two must stay
# divisible by group_size=32; hidden_size itself is never quantized and can
# shrink to 8. Inference engines pad MXFP4 buffers (sglang/vllm round the
# per-partition intermediate up to 128 and hidden up to 256, packing 2
# codes per byte along hidden) and their weight loaders only tolerate
# padding along the shard dim, so keep intermediate >= 256 (128 per
# partition at TP2) and routed_expert_hidden_size >= 256.
config_json['text_config'].update({
'attn_res_block_size': 8,
'first_k_dense_replace': 1,
'hidden_size': 8,
'intermediate_size': 32,
'kv_lora_rank': 512,
'moe_intermediate_size': 256,
'num_attention_heads': 8,
'num_experts': 64,
'num_hidden_layers': 17,
'num_key_value_heads': 8,
'q_lora_rank': 256,
'routed_expert_hidden_size': 256,
'_attn_implementation': 'eager',
})
config_json['text_config']['linear_attn_config'].update({
'full_attn_layers': [4, 8, 12, 16, 17],
'kda_layers': [1, 2, 3, 5, 6, 7, 9, 10, 11, 13, 14, 15],
'num_heads': 8,
})
config_json['vision_config'].update({
'_attn_implementation': 'eager',
'init_pos_emb_height': 8,
'init_pos_emb_width': 8,
'mm_hidden_size': 64,
'qkv_hidden_size': 64,
'text_hidden_size': 8,
'vt_hidden_size': 64,
'vt_intermediate_size': 128,
# Vision attention head size = qkv_hidden_size / heads = 64 / 2 = 32.
'vt_num_attention_heads': 2,
'vt_num_hidden_layers': 2,
})
with open(f'{save_folder}/config.json', 'w', encoding='utf-8') as f:
json.dump(config_json, f, indent=2)
config = AutoConfig.from_pretrained(save_folder, trust_remote_code=True)
print(config)
torch.set_default_dtype(torch.bfloat16)
model = AutoModel.from_config(
config,
trust_remote_code=True,
attn_implementation='eager',
)
torch.set_default_dtype(torch.float32)
if file_exists(
filename='generation_config.json',
repo_id=source_model_id,
repo_type='model',
revision=source_revision,
):
model.generation_config = GenerationConfig.from_pretrained(
source_model_id,
trust_remote_code=True,
revision=source_revision,
)
set_seed(42)
model = model.cpu()
num_params = sum(p.numel() for p in model.parameters())
with torch.no_grad():
for name, parameter in sorted(model.named_parameters()):
torch.nn.init.normal_(parameter, 0, 0.1)
print(name, parameter.shape, parameter.dtype, f'{parameter.numel() / num_params:.2%}')
model.save_pretrained(save_folder)
# Match the official checkpoint schema: routed experts are native MXFP4
# (two values per U8 byte, one E8M0 scale per group of 32 values).
model_path = Path(save_folder) / 'model.safetensors'
state_dict = load_file(str(model_path))
fp4_boundaries = torch.tensor([0.25, 0.75, 1.25, 1.75, 2.5, 3.5, 5.0])
for name in list(state_dict):
if '.block_sparse_moe.experts.' in name and name.endswith('.weight'):
weight = state_dict.pop(name).float()
out_features, in_features = weight.shape
assert in_features % 32 == 0
packed_name = name.removesuffix('.weight') + '.weight_packed'
scale_name = name.removesuffix('.weight') + '.weight_scale'
blocks = weight.view(out_features, in_features // 32, 32)
# E2M1 represents magnitudes {0, .5, 1, 1.5, 2, 3, 4, 6}.
# E8M0 stores the shared power-of-two scale as exponent + bias 127.
scale_exponents = torch.round(
torch.log2(blocks.abs().amax(dim=-1).clamp_min(torch.finfo(torch.float32).tiny) / 6)
).clamp(-126, 127)
scales = torch.pow(2.0, scale_exponents)
normalized = (blocks / scales.unsqueeze(-1)).clamp(-6, 6)
codes = torch.bucketize(normalized.abs(), fp4_boundaries)
codes += normalized.signbit() * 8
codes = codes.view(out_features, in_features)
state_dict[packed_name] = (
codes[:, ::2] | (codes[:, 1::2] << 4)
).to(torch.uint8)
state_dict[scale_name] = (scale_exponents + 127).to(torch.uint8)
elif name.endswith((
'.block_sparse_moe.gate.e_score_correction_bias',
'.self_attn.A_log',
'.self_attn.dt_bias',
'.self_attn.k_conv1d.weight',
'.self_attn.o_norm.weight',
'.self_attn.q_conv1d.weight',
'.self_attn.v_conv1d.weight',
)):
state_dict[name] = state_dict[name].float()
dtype_counts = {
dtype: sum(tensor.dtype == dtype for tensor in state_dict.values())
for dtype in (torch.bfloat16, torch.float32, torch.uint8)
}
# Derive the expected schema from the config instead of hardcoding counts:
# each MoE layer has num_experts × (w1|w2|w3) × (packed, scale) U8 tensors,
# and F32 tensors are per-MoE e_score_correction_bias plus per-KDA A_log,
# dt_bias, o_norm, and k/q/v conv1d weights.
text_cfg = config_json['text_config']
num_moe_layers = text_cfg['num_hidden_layers'] - text_cfg['first_k_dense_replace']
num_kda_layers = len(text_cfg['linear_attn_config']['kda_layers'])
expected_uint8 = num_moe_layers * text_cfg['num_experts'] * 3 * 2
expected_f32 = num_moe_layers + num_kda_layers * 6
assert dtype_counts == {
torch.bfloat16: len(state_dict) - expected_uint8 - expected_f32,
torch.float32: expected_f32,
torch.uint8: expected_uint8,
}
assert not any('mtp' in name.lower() for name in state_dict)
print('Top 20 keys with largest storage size:')
for name, tensor in sorted(state_dict.items(), key=lambda x: x[1].numel() * x[1].element_size(), reverse=True)[:20]:
print(f'{name}: {tensor.numel()} elements, {tensor.numel() * tensor.element_size() / 1024**2:.2f} MB')
save_file(state_dict, str(model_path), metadata={'format': 'pt'})
with open(f'{save_folder}/config.json', encoding='utf-8') as f:
saved_config = json.load(f)
saved_config['quantization_config'] = quantization_config
saved_config['text_config']['quantization_config'] = quantization_config
with open(f'{save_folder}/config.json', 'w', encoding='utf-8') as f:
json.dump(saved_config, f, indent=2)
```
</details>
### Printing the model:
<details><summary>Click to expand</summary>
```text
KimiK3ForConditionalGeneration(
(vision_tower): MoonViT3dPretrainedModel(
(patch_embed): MoonVision3dPatchEmbed(
(proj): Conv2d(3, 64, kernel_size=(14, 14), stride=(14, 14), bias=False)
(pos_emb): Learnable2DInterpPosEmbDivided_fixed()
)
(encoder): MoonViT3dEncoder(
(rope_2d): Rope2DPosEmbRepeated(dim=32, max_height=512, max_width=512, theta_base=10000)
(blocks): ModuleList(
(0-1): 2 x MoonViTEncoderLayer(
(norm0): RMSNorm((64,), eps=None, elementwise_affine=True)
(norm1): RMSNorm((64,), eps=None, elementwise_affine=True)
(mlp): MLP2(
(fc0): Linear(in_features=64, out_features=128, bias=False)
(fc1): Linear(in_features=128, out_features=64, bias=False)
(activation): GELUTanh()
)
(wqkv): Linear(in_features=64, out_features=192, bias=False)
(wo): Linear(in_features=64, out_features=64, bias=False)
)
)
(final_layernorm): RMSNorm((64,), eps=None, elementwise_affine=True)
)
)
(mm_projector): PatchMergerMLPV2(
(proj): Sequential(
(0): Linear(in_features=256, out_features=256, bias=False)
(1): GELU(approximate='none')
(2): Linear(in_features=256, out_features=8, bias=False)
)
(post_norm): RMSNorm((8,), eps=1e-05, elementwise_affine=True)
)
(language_model): KimiLinearForCausalLM(
(model): KimiLinearModel(
(embed_tokens): Embedding(163840, 8, padding_idx=163839)
(layers): ModuleList(
(0): KimiDecoderLayer(
(self_attn): KimiDeltaAttention(
(q_proj): Linear(in_features=8, out_features=1024, bias=False)
(k_proj): Linear(in_features=8, out_features=1024, bias=False)
(v_proj): Linear(in_features=8, out_features=1024, bias=False)
(q_conv1d): ShortConvolution(1024, 1024, kernel_size=(4,), stride=(1,), padding=(3,), groups=1024, bias=False, activation=silu, backend=triton)
(k_conv1d): ShortConvolution(1024, 1024, kernel_size=(4,), stride=(1,), padding=(3,), groups=1024, bias=False, activation=silu, backend=triton)
(v_conv1d): ShortConvolution(1024, 1024, kernel_size=(4,), stride=(1,), padding=(3,), groups=1024, bias=False, activation=silu, backend=triton)
(f_a_proj): Linear(in_features=8, out_features=128, bias=False)
(f_b_proj): Linear(in_features=128, out_features=1024, bias=False)
(b_proj): Linear(in_features=8, out_features=8, bias=False)
(g_proj): Linear(in_features=8, out_features=1024, bias=False)
(o_norm): FusedRMSNormGated(128, eps=1e-05, activation=sigmoid)
(o_proj): Linear(in_features=1024, out_features=8, bias=False)
)
(mlp): KimiMLP(
(gate_proj): Linear(in_features=8, out_features=32, bias=False)
(up_proj): Linear(in_features=8, out_features=32, bias=False)
(down_proj): Linear(in_features=32, out_features=8, bias=False)
(act_fn): SituAndMul()
)
(input_layernorm): KimiRMSNorm()
(post_attention_layernorm): KimiRMSNorm()
(self_attention_res_norm): KimiRMSNorm()
(mlp_res_norm): KimiRMSNorm()
(self_attention_res_proj): Linear(in_features=8, out_features=1, bias=False)
(mlp_res_proj): Linear(in_features=8, out_features=1, bias=False)
)
(1-2): 2 x KimiDecoderLayer(
(self_attn): KimiDeltaAttention(
(q_proj): Linear(in_features=8, out_features=1024, bias=False)
(k_proj): Linear(in_features=8, out_features=1024, bias=False)
(v_proj): Linear(in_features=8, out_features=1024, bias=False)
(q_conv1d): ShortConvolution(1024, 1024, kernel_size=(4,), stride=(1,), padding=(3,), groups=1024, bias=False, activation=silu, backend=triton)
(k_conv1d): ShortConvolution(1024, 1024, kernel_size=(4,), stride=(1,), padding=(3,), groups=1024, bias=False, activation=silu, backend=triton)
(v_conv1d): ShortConvolution(1024, 1024, kernel_size=(4,), stride=(1,), padding=(3,), groups=1024, bias=False, activation=silu, backend=triton)
(f_a_proj): Linear(in_features=8, out_features=128, bias=False)
(f_b_proj): Linear(in_features=128, out_features=1024, bias=False)
(b_proj): Linear(in_features=8, out_features=8, bias=False)
(g_proj): Linear(in_features=8, out_features=1024, bias=False)
(o_norm): FusedRMSNormGated(128, eps=1e-05, activation=sigmoid)
(o_proj): Linear(in_features=1024, out_features=8, bias=False)
)
(block_sparse_moe): KimiSparseMoeBlock(
(experts): ModuleList(
(0-63): 64 x KimiBlockSparseMLP(
(w1): Linear(in_features=256, out_features=256, bias=False)
(w2): Linear(in_features=256, out_features=256, bias=False)
(w3): Linear(in_features=256, out_features=256, bias=False)
(act_fn): SituAndMul()
)
)
(gate): KimiMoEGate()
(shared_experts): KimiMLP(
(gate_proj): Linear(in_features=8, out_features=512, bias=False)
(up_proj): Linear(in_features=8, out_features=512, bias=False)
(down_proj): Linear(in_features=512, out_features=8, bias=False)
(act_fn): SituAndMul()
)
(routed_expert_down_proj): Linear(in_features=8, out_features=256, bias=False)
(routed_expert_up_proj): Linear(in_features=256, out_features=8, bias=False)
(routed_expert_norm): KimiRMSNorm()
)
(input_layernorm): KimiRMSNorm()
(post_attention_layernorm): KimiRMSNorm()
(self_attention_res_norm): KimiRMSNorm()
(mlp_res_norm): KimiRMSNorm()
(self_attention_res_proj): Linear(in_features=8, out_features=1, bias=False)
(mlp_res_proj): Linear(in_features=8, out_features=1, bias=False)
)
(3): KimiDecoderLayer(
(self_attn): KimiMLAAttention(
(q_a_proj): Linear(in_features=8, out_features=256, bias=False)
(q_a_layernorm): KimiRMSNorm()
(q_b_proj): Linear(in_features=256, out_features=1536, bias=False)
(kv_a_proj_with_mqa): Linear(in_features=8, out_features=576, bias=False)
(kv_a_layernorm): KimiRMSNorm()
(kv_b_proj): Linear(in_features=512, out_features=2048, bias=False)
(o_proj): Linear(in_features=1024, out_features=8, bias=False)
(g_proj): Linear(in_features=8, out_features=1024, bias=False)
)
(block_sparse_moe): KimiSparseMoeBlock(
(experts): ModuleList(
(0-63): 64 x KimiBlockSparseMLP(
(w1): Linear(in_features=256, out_features=256, bias=False)
(w2): Linear(in_features=256, out_features=256, bias=False)
(w3): Linear(in_features=256, out_features=256, bias=False)
(act_fn): SituAndMul()
)
)
(gate): KimiMoEGate()
(shared_experts): KimiMLP(
(gate_proj): Linear(in_features=8, out_features=512, bias=False)
(up_proj): Linear(in_features=8, out_features=512, bias=False)
(down_proj): Linear(in_features=512, out_features=8, bias=False)
(act_fn): SituAndMul()
)
(routed_expert_down_proj): Linear(in_features=8, out_features=256, bias=False)
(routed_expert_up_proj): Linear(in_features=256, out_features=8, bias=False)
(routed_expert_norm): KimiRMSNorm()
)
(input_layernorm): KimiRMSNorm()
(post_attention_layernorm): KimiRMSNorm()
(self_attention_res_norm): KimiRMSNorm()
(mlp_res_norm): KimiRMSNorm()
(self_attention_res_proj): Linear(in_features=8, out_features=1, bias=False)
(mlp_res_proj): Linear(in_features=8, out_features=1, bias=False)
)
(4-6): 3 x KimiDecoderLayer(
(self_attn): KimiDeltaAttention(
(q_proj): Linear(in_features=8, out_features=1024, bias=False)
(k_proj): Linear(in_features=8, out_features=1024, bias=False)
(v_proj): Linear(in_features=8, out_features=1024, bias=False)
(q_conv1d): ShortConvolution(1024, 1024, kernel_size=(4,), stride=(1,), padding=(3,), groups=1024, bias=False, activation=silu, backend=triton)
(k_conv1d): ShortConvolution(1024, 1024, kernel_size=(4,), stride=(1,), padding=(3,), groups=1024, bias=False, activation=silu, backend=triton)
(v_conv1d): ShortConvolution(1024, 1024, kernel_size=(4,), stride=(1,), padding=(3,), groups=1024, bias=False, activation=silu, backend=triton)
(f_a_proj): Linear(in_features=8, out_features=128, bias=False)
(f_b_proj): Linear(in_features=128, out_features=1024, bias=False)
(b_proj): Linear(in_features=8, out_features=8, bias=False)
(g_proj): Linear(in_features=8, out_features=1024, bias=False)
(o_norm): FusedRMSNormGated(128, eps=1e-05, activation=sigmoid)
(o_proj): Linear(in_features=1024, out_features=8, bias=False)
)
(block_sparse_moe): KimiSparseMoeBlock(
(experts): ModuleList(
(0-63): 64 x KimiBlockSparseMLP(
(w1): Linear(in_features=256, out_features=256, bias=False)
(w2): Linear(in_features=256, out_features=256, bias=False)
(w3): Linear(in_features=256, out_features=256, bias=False)
(act_fn): SituAndMul()
)
)
(gate): KimiMoEGate()
(shared_experts): KimiMLP(
(gate_proj): Linear(in_features=8, out_features=512, bias=False)
(up_proj): Linear(in_features=8, out_features=512, bias=False)
(down_proj): Linear(in_features=512, out_features=8, bias=False)
(act_fn): SituAndMul()
)
(routed_expert_down_proj): Linear(in_features=8, out_features=256, bias=False)
(routed_expert_up_proj): Linear(in_features=256, out_features=8, bias=False)
(routed_expert_norm): KimiRMSNorm()
)
(input_layernorm): KimiRMSNorm()
(post_attention_layernorm): KimiRMSNorm()
(self_attention_res_norm): KimiRMSNorm()
(mlp_res_norm): KimiRMSNorm()
(self_attention_res_proj): Linear(in_features=8, out_features=1, bias=False)
(mlp_res_proj): Linear(in_features=8, out_features=1, bias=False)
)
(7): KimiDecoderLayer(
(self_attn): KimiMLAAttention(
(q_a_proj): Linear(in_features=8, out_features=256, bias=False)
(q_a_layernorm): KimiRMSNorm()
(q_b_proj): Linear(in_features=256, out_features=1536, bias=False)
(kv_a_proj_with_mqa): Linear(in_features=8, out_features=576, bias=False)
(kv_a_layernorm): KimiRMSNorm()
(kv_b_proj): Linear(in_features=512, out_features=2048, bias=False)
(o_proj): Linear(in_features=1024, out_features=8, bias=False)
(g_proj): Linear(in_features=8, out_features=1024, bias=False)
)
(block_sparse_moe): KimiSparseMoeBlock(
(experts): ModuleList(
(0-63): 64 x KimiBlockSparseMLP(
(w1): Linear(in_features=256, out_features=256, bias=False)
(w2): Linear(in_features=256, out_features=256, bias=False)
(w3): Linear(in_features=256, out_features=256, bias=False)
(act_fn): SituAndMul()
)
)
(gate): KimiMoEGate()
(shared_experts): KimiMLP(
(gate_proj): Linear(in_features=8, out_features=512, bias=False)
(up_proj): Linear(in_features=8, out_features=512, bias=False)
(down_proj): Linear(in_features=512, out_features=8, bias=False)
(act_fn): SituAndMul()
)
(routed_expert_down_proj): Linear(in_features=8, out_features=256, bias=False)
(routed_expert_up_proj): Linear(in_features=256, out_features=8, bias=False)
(routed_expert_norm): KimiRMSNorm()
)
(input_layernorm): KimiRMSNorm()
(post_attention_layernorm): KimiRMSNorm()
(self_attention_res_norm): KimiRMSNorm()
(mlp_res_norm): KimiRMSNorm()
(self_attention_res_proj): Linear(in_features=8, out_features=1, bias=False)
(mlp_res_proj): Linear(in_features=8, out_features=1, bias=False)
)
(8-10): 3 x KimiDecoderLayer(
(self_attn): KimiDeltaAttention(
(q_proj): Linear(in_features=8, out_features=1024, bias=False)
(k_proj): Linear(in_features=8, out_features=1024, bias=False)
(v_proj): Linear(in_features=8, out_features=1024, bias=False)
(q_conv1d): ShortConvolution(1024, 1024, kernel_size=(4,), stride=(1,), padding=(3,), groups=1024, bias=False, activation=silu, backend=triton)
(k_conv1d): ShortConvolution(1024, 1024, kernel_size=(4,), stride=(1,), padding=(3,), groups=1024, bias=False, activation=silu, backend=triton)
(v_conv1d): ShortConvolution(1024, 1024, kernel_size=(4,), stride=(1,), padding=(3,), groups=1024, bias=False, activation=silu, backend=triton)
(f_a_proj): Linear(in_features=8, out_features=128, bias=False)
(f_b_proj): Linear(in_features=128, out_features=1024, bias=False)
(b_proj): Linear(in_features=8, out_features=8, bias=False)
(g_proj): Linear(in_features=8, out_features=1024, bias=False)
(o_norm): FusedRMSNormGated(128, eps=1e-05, activation=sigmoid)
(o_proj): Linear(in_features=1024, out_features=8, bias=False)
)
(block_sparse_moe): KimiSparseMoeBlock(
(experts): ModuleList(
(0-63): 64 x KimiBlockSparseMLP(
(w1): Linear(in_features=256, out_features=256, bias=False)
(w2): Linear(in_features=256, out_features=256, bias=False)
(w3): Linear(in_features=256, out_features=256, bias=False)
(act_fn): SituAndMul()
)
)
(gate): KimiMoEGate()
(shared_experts): KimiMLP(
(gate_proj): Linear(in_features=8, out_features=512, bias=False)
(up_proj): Linear(in_features=8, out_features=512, bias=False)
(down_proj): Linear(in_features=512, out_features=8, bias=False)
(act_fn): SituAndMul()
)
(routed_expert_down_proj): Linear(in_features=8, out_features=256, bias=False)
(routed_expert_up_proj): Linear(in_features=256, out_features=8, bias=False)
(routed_expert_norm): KimiRMSNorm()
)
(input_layernorm): KimiRMSNorm()
(post_attention_layernorm): KimiRMSNorm()
(self_attention_res_norm): KimiRMSNorm()
(mlp_res_norm): KimiRMSNorm()
(self_attention_res_proj): Linear(in_features=8, out_features=1, bias=False)
(mlp_res_proj): Linear(in_features=8, out_features=1, bias=False)
)
(11): KimiDecoderLayer(
(self_attn): KimiMLAAttention(
(q_a_proj): Linear(in_features=8, out_features=256, bias=False)
(q_a_layernorm): KimiRMSNorm()
(q_b_proj): Linear(in_features=256, out_features=1536, bias=False)
(kv_a_proj_with_mqa): Linear(in_features=8, out_features=576, bias=False)
(kv_a_layernorm): KimiRMSNorm()
(kv_b_proj): Linear(in_features=512, out_features=2048, bias=False)
(o_proj): Linear(in_features=1024, out_features=8, bias=False)
(g_proj): Linear(in_features=8, out_features=1024, bias=False)
)
(block_sparse_moe): KimiSparseMoeBlock(
(experts): ModuleList(
(0-63): 64 x KimiBlockSparseMLP(
(w1): Linear(in_features=256, out_features=256, bias=False)
(w2): Linear(in_features=256, out_features=256, bias=False)
(w3): Linear(in_features=256, out_features=256, bias=False)
(act_fn): SituAndMul()
)
)
(gate): KimiMoEGate()
(shared_experts): KimiMLP(
(gate_proj): Linear(in_features=8, out_features=512, bias=False)
(up_proj): Linear(in_features=8, out_features=512, bias=False)
(down_proj): Linear(in_features=512, out_features=8, bias=False)
(act_fn): SituAndMul()
)
(routed_expert_down_proj): Linear(in_features=8, out_features=256, bias=False)
(routed_expert_up_proj): Linear(in_features=256, out_features=8, bias=False)
(routed_expert_norm): KimiRMSNorm()
)
(input_layernorm): KimiRMSNorm()
(post_attention_layernorm): KimiRMSNorm()
(self_attention_res_norm): KimiRMSNorm()
(mlp_res_norm): KimiRMSNorm()
(self_attention_res_proj): Linear(in_features=8, out_features=1, bias=False)
(mlp_res_proj): Linear(in_features=8, out_features=1, bias=False)
)
(12-14): 3 x KimiDecoderLayer(
(self_attn): KimiDeltaAttention(
(q_proj): Linear(in_features=8, out_features=1024, bias=False)
(k_proj): Linear(in_features=8, out_features=1024, bias=False)
(v_proj): Linear(in_features=8, out_features=1024, bias=False)
(q_conv1d): ShortConvolution(1024, 1024, kernel_size=(4,), stride=(1,), padding=(3,), groups=1024, bias=False, activation=silu, backend=triton)
(k_conv1d): ShortConvolution(1024, 1024, kernel_size=(4,), stride=(1,), padding=(3,), groups=1024, bias=False, activation=silu, backend=triton)
(v_conv1d): ShortConvolution(1024, 1024, kernel_size=(4,), stride=(1,), padding=(3,), groups=1024, bias=False, activation=silu, backend=triton)
(f_a_proj): Linear(in_features=8, out_features=128, bias=False)
(f_b_proj): Linear(in_features=128, out_features=1024, bias=False)
(b_proj): Linear(in_features=8, out_features=8, bias=False)
(g_proj): Linear(in_features=8, out_features=1024, bias=False)
(o_norm): FusedRMSNormGated(128, eps=1e-05, activation=sigmoid)
(o_proj): Linear(in_features=1024, out_features=8, bias=False)
)
(block_sparse_moe): KimiSparseMoeBlock(
(experts): ModuleList(
(0-63): 64 x KimiBlockSparseMLP(
(w1): Linear(in_features=256, out_features=256, bias=False)
(w2): Linear(in_features=256, out_features=256, bias=False)
(w3): Linear(in_features=256, out_features=256, bias=False)
(act_fn): SituAndMul()
)
)
(gate): KimiMoEGate()
(shared_experts): KimiMLP(
(gate_proj): Linear(in_features=8, out_features=512, bias=False)
(up_proj): Linear(in_features=8, out_features=512, bias=False)
(down_proj): Linear(in_features=512, out_features=8, bias=False)
(act_fn): SituAndMul()
)
(routed_expert_down_proj): Linear(in_features=8, out_features=256, bias=False)
(routed_expert_up_proj): Linear(in_features=256, out_features=8, bias=False)
(routed_expert_norm): KimiRMSNorm()
)
(input_layernorm): KimiRMSNorm()
(post_attention_layernorm): KimiRMSNorm()
(self_attention_res_norm): KimiRMSNorm()
(mlp_res_norm): KimiRMSNorm()
(self_attention_res_proj): Linear(in_features=8, out_features=1, bias=False)
(mlp_res_proj): Linear(in_features=8, out_features=1, bias=False)
)
(15-16): 2 x KimiDecoderLayer(
(self_attn): KimiMLAAttention(
(q_a_proj): Linear(in_features=8, out_features=256, bias=False)
(q_a_layernorm): KimiRMSNorm()
(q_b_proj): Linear(in_features=256, out_features=1536, bias=False)
(kv_a_proj_with_mqa): Linear(in_features=8, out_features=576, bias=False)
(kv_a_layernorm): KimiRMSNorm()
(kv_b_proj): Linear(in_features=512, out_features=2048, bias=False)
(o_proj): Linear(in_features=1024, out_features=8, bias=False)
(g_proj): Linear(in_features=8, out_features=1024, bias=False)
)
(block_sparse_moe): KimiSparseMoeBlock(
(experts): ModuleList(
(0-63): 64 x KimiBlockSparseMLP(
(w1): Linear(in_features=256, out_features=256, bias=False)
(w2): Linear(in_features=256, out_features=256, bias=False)
(w3): Linear(in_features=256, out_features=256, bias=False)
(act_fn): SituAndMul()
)
)
(gate): KimiMoEGate()
(shared_experts): KimiMLP(
(gate_proj): Linear(in_features=8, out_features=512, bias=False)
(up_proj): Linear(in_features=8, out_features=512, bias=False)
(down_proj): Linear(in_features=512, out_features=8, bias=False)
(act_fn): SituAndMul()
)
(routed_expert_down_proj): Linear(in_features=8, out_features=256, bias=False)
(routed_expert_up_proj): Linear(in_features=256, out_features=8, bias=False)
(routed_expert_norm): KimiRMSNorm()
)
(input_layernorm): KimiRMSNorm()
(post_attention_layernorm): KimiRMSNorm()
(self_attention_res_norm): KimiRMSNorm()
(mlp_res_norm): KimiRMSNorm()
(self_attention_res_proj): Linear(in_features=8, out_features=1, bias=False)
(mlp_res_proj): Linear(in_features=8, out_features=1, bias=False)
)
)
(norm): KimiRMSNorm()
(output_attn_res_norm): KimiRMSNorm()
(output_attn_res_proj): Linear(in_features=8, out_features=1, bias=False)
)
(lm_head): Linear(in_features=8, out_features=163840, bias=False)
)
)
```
</details>
### Test environment:
- einops: 0.9.0.dev0
- fla-core: 0.5.2
- safetensors: 0.8.0
- torch: 2.13.0+cu126
- transformers: 5.15.0.dev0
- triton: 3.7.1
- vllm: 0.1.dev1+g5a3eba034.d20260730.cu126 |