Views
No views yet
yujiepan/deepseek-v3-tiny-random.1import os
2from pathlib import Path
3
4import torch
5import transformers
6from huggingface_hub import create_repo, upload_folder
7from transformers import (AutoConfig, AutoModelForCausalLM, AutoTokenizer,
8 GenerationConfig, enable_full_determinism, pipeline,
9 set_seed)
10
11model_id = "deepseek-ai/DeepSeek-V3"
12repo_id = "modularai/deepseek-v3-small-random"
13save_path = f"/home/ubuntu/mock-models/{repo_id}"
14
15deepseek_config = AutoConfig.from_pretrained("deepseek-ai/DeepSeek-V3")
16
17config = AutoConfig.from_pretrained(model_id, trust_remote_code=True)
18config.num_hidden_layers = 2
19config.first_k_dense_replace = 1
20
21# transformers has not supported the customized quantization config
22del config.quantization_config
23
24tokenizer = AutoTokenizer.from_pretrained(model_id, trust_remote_code=True)
25tokenizer.save_pretrained(save_path)
26
27enable_full_determinism(seed=42)
28model = AutoModelForCausalLM.from_config(
29 config, torch_dtype=torch.bfloat16, trust_remote_code=True,
30)
31
32try:
33 model.generation_config = GenerationConfig.from_pretrained(
34 model_id, trust_remote_code=True)
35except:
36 print("No generation config found")
37
38# This fixes the NaN values
39model.model.layers[1].mlp.gate.e_score_correction_bias = torch.nn.Parameter(
40torch.randn_like(
41model.model.layers[1].mlp.gate.e_score_correction_bias) * 1e-2)
42
43num_params = 0
44with torch.no_grad():
45 for name, p in sorted(model.named_parameters()):
46 if 'experts' in name and 'experts.0.' not in name: # avoid printing too much
47 pass
48 else:
49 print(name, p.shape)
50 # torch.nn.init.uniform_(p, -0.2, 0.2)
51 num_params += p.numel()
52print(f"Number of parameters: {num_params / 1e6:.2f}M")
53model.save_pretrained(save_path)
54
55# patch to use official modeling codes
56auto_map = config.auto_map
57import json
58with open(f"{save_path}/config.json", "r") as f:
59 config_json = json.load(f)
60 config_json['auto_map'] = auto_map
61with open(f"{save_path}/config.json", "w") as f:
62 json.dump(config_json, f, indent=2)
63
64! cat {save_path}/config.json
65
66del model
67del tokenizer
68for p in Path(save_path).glob("*.py"):
69 os.remove(p)
70
71os.system(f"ls -alh {save_path}")
72torch.use_deterministic_algorithms(False)