Views
No views yet
1python -m vllm.entrypoints.openai.api_server \
2 --tensor-parallel-size 2 \
3 --model yujiepan/deepseek-v3.1-tiny-random \
4 --trust-remote-code \
5 --speculative-config='{"method": "deepseek_mtp", "num_speculative_tokens": 1}' 1import torch
2import transformers
3
4model_id = "yujiepan/deepseek-v3.1-tiny-random"
5pipe = transformers.pipelines.pipeline(
6 'text-generation',
7 model=model_id,
8 trust_remote_code=True,
9 device_map='cuda',
10 torch_dtype=torch.bfloat16,
11)
12r = pipe.model(torch.tensor([[1, 2, 3]], dtype=torch.int64).cuda(), attention_mask=None, use_cache=False)
13print(r)1import json
2from copy import deepcopy
3from pathlib import Path
4
5import accelerate
6import torch
7import torch.nn as nn
8from huggingface_hub import file_exists, hf_hub_download
9from transformers import (
10 AutoConfig,
11 AutoModelForCausalLM,
12 AutoProcessor,
13 AutoTokenizer,
14 GenerationConfig,
15 set_seed,
16)
17from transformers.models.glm4_moe.modeling_glm4_moe import Glm4MoeRMSNorm
18source_model_id = "deepseek-ai/DeepSeek-V3.1"
19save_folder = "/tmp/yujiepan/deepseek-v3.1-tiny-random"
20
21Path(save_folder).mkdir(parents=True, exist_ok=True)
22tokenizer = AutoTokenizer.from_pretrained(source_model_id, trust_remote_code=True)
23tokenizer.save_pretrained(save_folder)
24
25with open(hf_hub_download(source_model_id, filename='config.json', repo_type='model', cache_dir='/tmp/'), 'r', encoding='utf-8') as f:
26 config_json = json.load(f)
27for k, v in config_json['auto_map'].items():
28 config_json['auto_map'][k] = f'{source_model_id}--{v}'
29config_json.update({
30 'first_k_dense_replace': 1,
31 'num_hidden_layers': 2,
32 'hidden_size': 8,
33 'intermediate_size': 64,
34 'kv_lora_rank': 384,
35 'moe_intermediate_size': 64,
36 'n_routed_experts': 32,
37 'n_shared_experts': 1,
38 'num_attention_heads': 4,
39 'num_experts_per_tok': 8,
40 'num_key_value_heads': 4,
41 'q_lora_rank': 32,
42 'qk_nope_head_dim': 64,
43 'qk_rope_head_dim': 192, # vllm mla kernel supports 576 only, FA supports head dim <= 256
44 'v_head_dim': 64,
45 'tie_word_embeddings': False,
46})
47del config_json['quantization_config']
48with open(f"{save_folder}/config.json", "w", encoding='utf-8') as f:
49 json.dump(config_json, f, indent=2)
50
51config = AutoConfig.from_pretrained(
52 save_folder,
53 trust_remote_code=True,
54)
55print(config)
56torch.set_default_dtype(torch.bfloat16)
57model = AutoModelForCausalLM.from_config(config, trust_remote_code=True)
58
59if file_exists(filename="generation_config.json", repo_id=source_model_id, repo_type='model'):
60 model.generation_config = GenerationConfig.from_pretrained(
61 source_model_id, trust_remote_code=True,
62 )
63
64class SharedHead(nn.Module):
65 def __init__(self, config) -> None:
66 super().__init__()
67 from transformers.models.glm4_moe.modeling_glm4_moe import Glm4MoeRMSNorm
68 self.norm = Glm4MoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
69
70last_extra_layer = model.model.layers[0].__class__(config, layer_idx=config.num_hidden_layers)
71last_extra_layer.enorm = Glm4MoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
72last_extra_layer.hnorm = Glm4MoeRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
73last_extra_layer.eh_proj = nn.Linear(config.hidden_size * 2, config.hidden_size, bias=False)
74last_extra_layer.shared_head = SharedHead(config=config)
75model.model.layers.append(last_extra_layer)
76
77torch.set_default_dtype(torch.float32)
78set_seed(42)
79model = model.cpu() # cpu is more stable for random initialization across machines
80with torch.no_grad():
81 for name, p in sorted(model.named_parameters()):
82 torch.nn.init.normal_(p, 0, 0.1)
83 print(name, p.shape)
84
85last_extra_layer.shared_head.head = deepcopy(model.get_output_embeddings())
86last_extra_layer.embed_tokens = deepcopy(model.get_input_embeddings())
87model.save_pretrained(save_folder)
88with open(f"{save_folder}/config.json", "r", encoding='utf-8') as f:
89 config_json = json.load(f)
90 config_json['auto_map'] = {k: v.split('--')[-1] for k, v in config_json['auto_map'].items()}
91with open(f"{save_folder}/config.json", "w", encoding='utf-8') as f:
92 json.dump(config_json, f, indent=2)
93hf_hub_download(source_model_id, filename='modeling_deepseek.py', repo_type='model',
94 local_dir=save_folder, local_dir_use_symlinks=False, cache_dir='/tmp/')
95with open(f'{save_folder}/modeling_deepseek.py', 'r', encoding='utf-8') as f:
96 codes = f.read()
97codes = codes.replace(
98 "past_length = past_key_values.seen_tokens",
99 "past_length = past_key_values.seen_tokens if hasattr(past_key_values, 'seen_tokens') else past_key_values.get_seq_length() # fix cache api deprecation"
100)
101codes = codes.replace(
102 "max_cache_length = past_key_values.get_max_length()",
103 "max_cache_length = past_key_values.get_max_length() if hasattr(past_key_values, 'get_max_length') else past_key_values.get_max_cache_shape() # fix cache api deprecation"
104)
105codes = codes.replace(
106 "past_key_value.get_usable_length(",
107 "getattr(past_key_value, 'get_usable_length', lambda *args, **kwargs: past_key_value.get_seq_length())("
108)
109codes = codes.replace(
110 "past_key_values.get_usable_length(",
111 "getattr(past_key_values, 'get_usable_length', lambda *args, **kwargs: past_key_values.get_seq_length())("
112)
113with open(f'{save_folder}/modeling_deepseek.py', 'w', encoding='utf-8') as f:
114 f.write(codes)1DeepseekV3ForCausalLM(
2 (model): DeepseekV3Model(
3 (embed_tokens): Embedding(129280, 8)
4 (layers): ModuleList(
5 (0): DeepseekV3DecoderLayer(
6 (self_attn): DeepseekV3Attention(
7 (q_a_proj): Linear(in_features=8, out_features=32, bias=False)
8 (q_a_layernorm): DeepseekV3RMSNorm()
9 (q_b_proj): Linear(in_features=32, out_features=1024, bias=False)
10 (kv_a_proj_with_mqa): Linear(in_features=8, out_features=576, bias=False)
11 (kv_a_layernorm): DeepseekV3RMSNorm()
12 (kv_b_proj): Linear(in_features=384, out_features=512, bias=False)
13 (o_proj): Linear(in_features=256, out_features=8, bias=False)
14 (rotary_emb): DeepseekV3YarnRotaryEmbedding()
15 )
16 (mlp): DeepseekV3MLP(
17 (gate_proj): Linear(in_features=8, out_features=64, bias=False)
18 (up_proj): Linear(in_features=8, out_features=64, bias=False)
19 (down_proj): Linear(in_features=64, out_features=8, bias=False)
20 (act_fn): SiLU()
21 )
22 (input_layernorm): DeepseekV3RMSNorm()
23 (post_attention_layernorm): DeepseekV3RMSNorm()
24 )
25 (1): DeepseekV3DecoderLayer(
26 (self_attn): DeepseekV3Attention(
27 (q_a_proj): Linear(in_features=8, out_features=32, bias=False)
28 (q_a_layernorm): DeepseekV3RMSNorm()
29 (q_b_proj): Linear(in_features=32, out_features=1024, bias=False)
30 (kv_a_proj_with_mqa): Linear(in_features=8, out_features=576, bias=False)
31 (kv_a_layernorm): DeepseekV3RMSNorm()
32 (kv_b_proj): Linear(in_features=384, out_features=512, bias=False)
33 (o_proj): Linear(in_features=256, out_features=8, bias=False)
34 (rotary_emb): DeepseekV3YarnRotaryEmbedding()
35 )
36 (mlp): DeepseekV3MoE(
37 (experts): ModuleList(
38 (0-31): 32 x DeepseekV3MLP(
39 (gate_proj): Linear(in_features=8, out_features=64, bias=False)
40 (up_proj): Linear(in_features=8, out_features=64, bias=False)
41 (down_proj): Linear(in_features=64, out_features=8, bias=False)
42 (act_fn): SiLU()
43 )
44 )
45 (gate): MoEGate()
46 (shared_experts): DeepseekV3MLP(
47 (gate_proj): Linear(in_features=8, out_features=64, bias=False)
48 (up_proj): Linear(in_features=8, out_features=64, bias=False)
49 (down_proj): Linear(in_features=64, out_features=8, bias=False)
50 (act_fn): SiLU()
51 )
52 )
53 (input_layernorm): DeepseekV3RMSNorm()
54 (post_attention_layernorm): DeepseekV3RMSNorm()
55 )
56 (2): DeepseekV3DecoderLayer(
57 (self_attn): DeepseekV3Attention(
58 (q_a_proj): Linear(in_features=8, out_features=32, bias=False)
59 (q_a_layernorm): DeepseekV3RMSNorm()
60 (q_b_proj): Linear(in_features=32, out_features=1024, bias=False)
61 (kv_a_proj_with_mqa): Linear(in_features=8, out_features=576, bias=False)
62 (kv_a_layernorm): DeepseekV3RMSNorm()
63 (kv_b_proj): Linear(in_features=384, out_features=512, bias=False)
64 (o_proj): Linear(in_features=256, out_features=8, bias=False)
65 (rotary_emb): DeepseekV3YarnRotaryEmbedding()
66 )
67 (mlp): DeepseekV3MoE(
68 (experts): ModuleList(
69 (0-31): 32 x DeepseekV3MLP(
70 (gate_proj): Linear(in_features=8, out_features=64, bias=False)
71 (up_proj): Linear(in_features=8, out_features=64, bias=False)
72 (down_proj): Linear(in_features=64, out_features=8, bias=False)
73 (act_fn): SiLU()
74 )
75 )
76 (gate): MoEGate()
77 (shared_experts): DeepseekV3MLP(
78 (gate_proj): Linear(in_features=8, out_features=64, bias=False)
79 (up_proj): Linear(in_features=8, out_features=64, bias=False)
80 (down_proj): Linear(in_features=64, out_features=8, bias=False)
81 (act_fn): SiLU()
82 )
83 )
84 (input_layernorm): DeepseekV3RMSNorm()
85 (post_attention_layernorm): DeepseekV3RMSNorm()
86 (enorm): Glm4MoeRMSNorm((8,), eps=1e-06)
87 (hnorm): Glm4MoeRMSNorm((8,), eps=1e-06)
88 (eh_proj): Linear(in_features=16, out_features=8, bias=False)
89 (shared_head): SharedHead(
90 (norm): Glm4MoeRMSNorm((8,), eps=1e-06)
91 (head): Linear(in_features=8, out_features=129280, bias=False)
92 )
93 (embed_tokens): Embedding(129280, 8)
94 )
95 )
96 (norm): DeepseekV3RMSNorm()
97 )
98 (lm_head): Linear(in_features=8, out_features=129280, bias=False)
99)