Views
No views yet
| File path | Size |
|---|---|
| model.safetensors | 7.3MB |
1import numpy as np
2import torch
3from PIL import Image
4from transformers import AutoModelForMultimodalLM, AutoProcessor
5
6model_id = "tiny-random/inkling"
7processor = AutoProcessor.from_pretrained(model_id)
8model = AutoModelForMultimodalLM.from_pretrained(
9 model_id,
10 dtype=torch.bfloat16,
11 device_map="cuda" if torch.cuda.is_available() else "cpu",
12)
13
14# Synthetic multimodal inputs — no network fetch.
15image = Image.fromarray(np.random.randint(0, 255, (80, 80, 3), dtype=np.uint8))
16sampling_rate = processor.feature_extractor.sampling_rate
17t = np.linspace(0, 0.2, int(sampling_rate * 0.2), endpoint=False)
18audio = (0.1 * np.sin(2 * np.pi * 440 * t)).astype(np.float32)
19
20messages = [
21 {
22 "role": "user",
23 "content": [
24 {"type": "image", "image": image},
25 {"type": "audio", "audio": audio},
26 {"type": "text", "text": "Describe the image and audio briefly."},
27 ],
28 },
29]
30inputs = processor.apply_chat_template(
31 messages,
32 add_generation_prompt=True,
33 tokenize=True,
34 return_dict=True,
35 return_tensors="pt",
36 reasoning_effort="none",
37 processor_kwargs={"sampling_rate": sampling_rate},
38).to(model.device, dtype=model.dtype)
39input_len = inputs["input_ids"].shape[-1]
40outputs = model.generate(**inputs, max_new_tokens=16)
41print(processor.decode(outputs[0], skip_special_tokens=False))1import json
2from pathlib import Path
3
4import torch
5from huggingface_hub import file_exists, hf_hub_download
6from safetensors.torch import load_file, save_file
7from transformers import (
8 AutoConfig,
9 AutoProcessor,
10 GenerationConfig,
11 InklingForConditionalGeneration,
12 set_seed,
13)
14
15source_model_id = "thinkingmachines/Inkling"
16save_folder = "/tmp/tiny-random/inkling"
17
18processor = AutoProcessor.from_pretrained(source_model_id)
19processor.save_pretrained(save_folder)
20
21with open(hf_hub_download(source_model_id, filename='config.json', repo_type='model'), 'r', encoding='utf-8') as f:
22 config_json = json.load(f)
23
24# Only shrink size-critical dims. Keep kernel-sensitive knobs (d_rel, rel_extent,
25# sliding_window_size, num_experts_per_tok, n_shared_experts, ...) as upstream.
26hidden_size = 8
27num_mtp_layers = 1
28config_json['text_config'].update({
29 'hidden_size': hidden_size,
30 'num_hidden_layers': 2,
31 'num_attention_heads': 8,
32 'num_key_value_heads': 4,
33 'head_dim': 32,
34 'swa_num_attention_heads': 8,
35 'swa_num_key_value_heads': 4,
36 'swa_head_dim': 32,
37 'local_layer_ids': [0], # keep 1 sliding + 1 global with 2 layers
38 'dense_mlp_idx': 1, # 1 dense + 1 sparse
39 'dense_intermediate_size': 32,
40 'intermediate_size': 32,
41 'moe_intermediate_size': 32,
42})
43config_json['vision_config'].update({
44 'decoder_dmodel': hidden_size,
45 'n_layers': 2,
46})
47config_json['audio_config'].update({
48 'decoder_dmodel': hidden_size,
49})
50config_json['mtp_config'].update({
51 'num_nextn_predict_layers': num_mtp_layers,
52 'local_layer_ids': [0],
53})
54
55with open(f"{save_folder}/config.json", "w", encoding='utf-8') as f:
56 json.dump(config_json, f, indent=2)
57
58config = AutoConfig.from_pretrained(save_folder)
59print(config)
60torch.set_default_dtype(torch.bfloat16)
61model = InklingForConditionalGeneration(config)
62torch.set_default_dtype(torch.float32)
63if file_exists(filename="generation_config.json", repo_id=source_model_id, repo_type='model'):
64 model.generation_config = GenerationConfig.from_pretrained(
65 source_model_id, trust_remote_code=True,
66 )
67set_seed(42)
68model = model.cpu()
69num_params = sum(p.numel() for p in model.parameters())
70with torch.no_grad():
71 for name, p in sorted(model.named_parameters()):
72 torch.nn.init.normal_(p, 0, 0.2)
73 print(name, p.shape, f'{p.numel() / num_params:.2%}', f'{p.numel() * p.element_size() / 1024**2:.2f}MB')
74# Upstream MoE gate bias / global_scale are F32; sconv stays BF16 in the checkpoint.
75for name, module in model.named_modules():
76 if hasattr(module, "e_score_correction_bias"):
77 module.e_score_correction_bias = torch.nn.Parameter(
78 module.e_score_correction_bias.detach().float()
79 )
80 if name.endswith(".mlp.gate") and hasattr(module, "global_scale"):
81 module.global_scale = torch.nn.Parameter(module.global_scale.detach().float())
82model.save_pretrained(save_folder)
83
84# HF ignores `model.mtp.*` on main load; write them with original checkpoint naming.
85set_seed(42)
86path = Path(save_folder) / "model.safetensors"
87state = load_file(str(path))
88dense_prefix = "model.llm.layers.0." # MTP blocks are dense
89dense_keys = {k: v for k, v in state.items() if k.startswith(dense_prefix)}
90for i in range(num_mtp_layers):
91 block_prefix = f"model.mtp.layers.{i}.transformer_block."
92 for src_key, tensor in dense_keys.items():
93 dst_key = block_prefix + src_key[len(dense_prefix):]
94 state[dst_key] = torch.empty_like(tensor)
95 torch.nn.init.normal_(state[dst_key], 0, 0.2)
96 print(dst_key, tuple(state[dst_key].shape))
97 for name, shape in (
98 (f"model.mtp.layers.{i}.embed_norm.weight", (hidden_size,)),
99 (f"model.mtp.layers.{i}.hidden_norm.weight", (hidden_size,)),
100 (f"model.mtp.layers.{i}.input_proj.weight", (hidden_size, hidden_size * 2)),
101 ):
102 state[name] = torch.empty(shape, dtype=torch.bfloat16)
103 torch.nn.init.normal_(state[name], 0, 0.2)
104 print(name, shape)
105# Keep checkpoint key dtypes aligned even if save_pretrained downcasts.
106for key, tensor in list(state.items()):
107 if key.endswith(".mlp.gate.bias") or key.endswith(".mlp.gate.global_scale"):
108 state[key] = tensor.float()
109save_file(state, str(path))1InklingForConditionalGeneration(
2 (model): InklingModel(
3 (language_model): InklingTextModel(
4 (embed_tokens): Embedding(201024, 8)
5 (layers): ModuleList(
6 (0): InklingDecoderLayer(
7 (self_attn): InklingAttention(
8 (q_proj): Linear(in_features=8, out_features=256, bias=False)
9 (k_proj): Linear(in_features=8, out_features=128, bias=False)
10 (v_proj): Linear(in_features=8, out_features=128, bias=False)
11 (r_proj): Linear(in_features=8, out_features=128, bias=False)
12 (o_proj): Linear(in_features=256, out_features=8, bias=False)
13 (k_sconv): InklingShortConvolution(
14 (conv1d): Conv1d(128, 128, kernel_size=(4,), stride=(1,), padding=(3,), groups=128, bias=False)
15 )
16 (v_sconv): InklingShortConvolution(
17 (conv1d): Conv1d(128, 128, kernel_size=(4,), stride=(1,), padding=(3,), groups=128, bias=False)
18 )
19 (q_norm): InklingRMSNorm((32,), eps=1e-06)
20 (k_norm): InklingRMSNorm((32,), eps=1e-06)
21 (rel_logits_proj): InklingRelativeLogits()
22 )
23 (mlp): InklingMLP(
24 (gate_proj): Linear(in_features=8, out_features=32, bias=False)
25 (up_proj): Linear(in_features=8, out_features=32, bias=False)
26 (down_proj): Linear(in_features=32, out_features=8, bias=False)
27 (act_fn): SiLUActivation()
28 )
29 (input_layernorm): InklingRMSNorm((8,), eps=1e-06)
30 (post_attention_layernorm): InklingRMSNorm((8,), eps=1e-06)
31 (attn_sconv): InklingShortConvolution(
32 (conv1d): Conv1d(8, 8, kernel_size=(4,), stride=(1,), padding=(3,), groups=8, bias=False)
33 )
34 (mlp_sconv): InklingShortConvolution(
35 (conv1d): Conv1d(8, 8, kernel_size=(4,), stride=(1,), padding=(3,), groups=8, bias=False)
36 )
37 )
38 (1): InklingDecoderLayer(
39 (self_attn): InklingAttention(
40 (q_proj): Linear(in_features=8, out_features=256, bias=False)
41 (k_proj): Linear(in_features=8, out_features=128, bias=False)
42 (v_proj): Linear(in_features=8, out_features=128, bias=False)
43 (r_proj): Linear(in_features=8, out_features=128, bias=False)
44 (o_proj): Linear(in_features=256, out_features=8, bias=False)
45 (k_sconv): InklingShortConvolution(
46 (conv1d): Conv1d(128, 128, kernel_size=(4,), stride=(1,), padding=(3,), groups=128, bias=False)
47 )
48 (v_sconv): InklingShortConvolution(
49 (conv1d): Conv1d(128, 128, kernel_size=(4,), stride=(1,), padding=(3,), groups=128, bias=False)
50 )
51 (q_norm): InklingRMSNorm((32,), eps=1e-06)
52 (k_norm): InklingRMSNorm((32,), eps=1e-06)
53 (rel_logits_proj): InklingRelativeLogits()
54 )
55 (mlp): InklingMoE(
56 (gate): InklingTopkRouter()
57 (experts): InklingExperts(
58 (act_fn): SiLUActivation()
59 )
60 (shared_experts): InklingSharedExperts(
61 (act_fn): SiLUActivation()
62 )
63 )
64 (input_layernorm): InklingRMSNorm((8,), eps=1e-06)
65 (post_attention_layernorm): InklingRMSNorm((8,), eps=1e-06)
66 (attn_sconv): InklingShortConvolution(
67 (conv1d): Conv1d(8, 8, kernel_size=(4,), stride=(1,), padding=(3,), groups=8, bias=False)
68 )
69 (mlp_sconv): InklingShortConvolution(
70 (conv1d): Conv1d(8, 8, kernel_size=(4,), stride=(1,), padding=(3,), groups=8, bias=False)
71 )
72 )
73 )
74 (norm): InklingRMSNorm((8,), eps=1e-06)
75 (embed_norm): InklingRMSNorm((8,), eps=1e-06)
76 )
77 (audio_tower): InklingAudioModel(
78 (embed_audio_tokens): InklingAudioModelEmbeddings(
79 (embed_audio_tokens): Embedding(1280, 8)
80 )
81 (norm): InklingRMSNorm((8,), eps=1e-06)
82 )
83 (vision_tower): InklingVisionModel(
84 (encoder_layers): ModuleList(
85 (0): InklingVisionEncoderLayer(
86 (projection): Linear(in_features=300, out_features=320, bias=False)
87 (layer_norm): InklingRMSNorm((320,), eps=1e-06)
88 )
89 (1): InklingVisionEncoderLayer(
90 (projection): Linear(in_features=10240, out_features=8, bias=False)
91 )
92 )
93 (final_norm): InklingRMSNorm((8,), eps=1e-06)
94 )
95 )
96 (lm_head): Linear(in_features=8, out_features=201024, bias=False)
97)