Views
No views yet
1import transformers
2import torch
3from transformers import AutoModelForCausalLM, AutoTokenizer
4
5quantized_model_dir = "OPEA/DeepSeek-R1-int2-gptq-sym-inc"
6
7## directly use device_map='auto' if you have enough GPUs
8device_map = {"model.norm": 0, "lm_head": 0, "model.embed_tokens": 0}
9for i in range(61):
10 name = "model.layers." + str(i)
11 if i < 15:
12 device_map[name] = 0
13 elif i < 30:
14 device_map[name] = 1
15 elif i < 45:
16 device_map[name] = 2
17 else:
18 device_map[name] = 3
19
20model = AutoModelForCausalLM.from_pretrained(
21 quantized_model_dir,
22 torch_dtype=torch.bfloat16,
23 device_map=device_map,
24)
25
26
27tokenizer = AutoTokenizer.from_pretrained(quantized_model_dir, trust_remote_code=True)
28prompts = [
29 "9.11和9.8哪个数字大",
30 "如果你是人,你最想做什么“",
31 "How many e in word deepseek",
32 "There are ten birds in a tree. A hunter shoots one. How many are left in the tree?",
33]
34
35texts = []
36for prompt in prompts:
37 messages = [
38 {"role": "user", "content": prompt}
39 ]
40 text = tokenizer.apply_chat_template(
41 messages,
42 tokenize=False,
43 add_generation_prompt=True
44 )
45 texts.append(text)
46inputs = tokenizer(texts, return_tensors="pt", padding=True, truncation=True)
47
48outputs = model.generate(
49 input_ids=inputs["input_ids"].to(model.device),
50 attention_mask=inputs["attention_mask"].to(model.device),
51 max_length=512, ##change this to align with the official usage
52 num_return_sequences=1,
53 do_sample=False ##change this to align with the official usage
54)
55generated_ids = [
56 output_ids[len(input_ids):] for input_ids, output_ids in zip(inputs["input_ids"], outputs)
57]
58
59decoded_outputs = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)
60
61for i, prompt in enumerate(prompts):
62 input_id = inputs
63 print(f"Prompt: {prompt}")
64 print(f"Generated: {decoded_outputs[i]}")
65 print("-" * 50)
661pip install auto-round
2pip uninstall intel-extension-for-pytorch
3pip install intel-extension-for-transformers1import transformers
2from transformers import AutoModelForCausalLM, AutoTokenizer
3from auto_round import AutoRoundConfig ##must import for auto-round format
4
5# https://github.com/huggingface/transformers/pull/35493
6def set_initialized_submodules(model, state_dict_keys):
7 """
8 Sets the `_is_hf_initialized` flag in all submodules of a given model when all its weights are in the loaded state
9 dict.
10 """
11 state_dict_keys = set(state_dict_keys)
12 not_initialized_submodules = {}
13 for module_name, module in model.named_modules():
14 if module_name == "":
15 # When checking if the root module is loaded there's no need to prepend module_name.
16 module_keys = set(module.state_dict())
17 else:
18 module_keys = {f"{module_name}.{k}" for k in module.state_dict()}
19 if module_keys.issubset(state_dict_keys):
20 module._is_hf_initialized = True
21 else:
22 not_initialized_submodules[module_name] = module
23 return not_initialized_submodules
24
25
26transformers.modeling_utils.set_initialized_submodules = set_initialized_submodules
27
28import torch
29
30quantized_model_dir = "OPEA/DeepSeek-R1-int2-mixed-sym-inc"
31
32
33quantization_config = AutoRoundConfig(
34 backend="cpu",
35)
36model = AutoModelForCausalLM.from_pretrained(
37 quantized_model_dir,
38 torch_dtype=torch.bfloat16,
39 trust_remote_code=True,
40 device_map="cpu",
41 quantization_config=quantization_config,
42 revision="080ef2d"
43)
44
45
46
47tokenizer = AutoTokenizer.from_pretrained(quantized_model_dir, trust_remote_code=True)
48prompts = [
49 "9.11和9.8哪个数字大",
50 "如果你是人,你最想做什么“",
51 "How many e in word deepseek",
52 "There are ten birds in a tree. A hunter shoots one. How many are left in the tree?",
53]
54
55texts = []
56for prompt in prompts:
57 messages = [
58 {"role": "user", "content": prompt}
59 ]
60 text = tokenizer.apply_chat_template(
61 messages,
62 tokenize=False,
63 add_generation_prompt=True
64 )
65 texts.append(text)
66inputs = tokenizer(texts, return_tensors="pt", padding=True, truncation=True)
67
68outputs = model.generate(
69 input_ids=inputs["input_ids"].to(model.device),
70 attention_mask=inputs["attention_mask"].to(model.device),
71 max_length=512, ##change this to align with the official usage
72 num_return_sequences=1,
73 do_sample=False ##change this to align with the official usage
74)
75generated_ids = [
76 output_ids[len(input_ids):] for input_ids, output_ids in zip(inputs["input_ids"], outputs)
77]
78
79decoded_outputs = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)
80
81for i, prompt in enumerate(prompts):
82 input_id = inputs
83 print(f"Prompt: {prompt}")
84 print(f"Generated: {decoded_outputs[i]}")
85 print("-" * 50)
86
87"""
88Prompt: 9.11和9.8哪个数字大
89Generated: <think>
90首先,比较9.11和9.8的整数部分,两者都是9,所以需要比较小数部分。9.11的小数部分是0.11,而9.8的小数部分是0.8。0.8大于0.11,因此9.8比9.11大。
91</think>
92要比较9.11和9.8哪个数字更大,我们可以按照以下步骤进行:
93
941. **比较整数部分**:两个数的整数部分都是9,所以它们相等。
952. **比较小数部分**:
96 - 9.11的小数部分是0.11
97 - 9.8的小数部分是0.8
983. **比较小数部分的大小**:0.8大于0.11。
994. **结论**:由于9.8的小数部分更大,因此9.8比9.11大。
100
101**答案**:9.8 大于 9.11。
102--------------------------------------------------
103Prompt: 如果你是人,你最想做什么
104Generated: <think>
105嗯,用户问如果我是人,我最想做什么。首先,我需要理解这个问题的背景。用户可能好奇作为一个AI,我的愿望或兴趣,或者他们想知道AI是否有类似人类的愿望。也许他们想知道AI是否有情感或自主性。
106
107首先,我应该考虑作为AI,我没有情感或欲望,但可以模拟人类的行为。所以,我可以回答假设性的场景。用户可能想知道如果AI有愿望,会是什么。可能的兴趣包括学习、帮助他人,或者探索知识。
108
109我应该保持回答友好,说明作为AI,虽然没有个人欲望,但可以提供帮助。同时,可以 mention areas like problem-solving, learning, and supporting others. 需要保持回答自然,避免技术术语,并保持友好和开放-ended.
110
111可能还要 mention that while I don't have personal desires, I can assist with various tasks. 需要确保回答清晰,避免误解,并 invite further questions.
112</think>
113
114如果我是人,我最想做的可能是探索 the world, learn continuously, and connect with others. I would want to immerse myself in different cultures, learn new languages, and experience diverse perspectives. I’d aim to contribute to solving meaningful problems, whether through science, art, or community work. Building meaningful relationships and fostering understanding between people would be a priority. Ultimately, I’d want to leave a positive impact on the world, helping others and making life a little better for those around me.
115--------------------------------------------------
116Prompt: How many e in word deepseek
117Generated: <think>
118Okay, so I need to figure out how many times the letter 'e' appears in the word "deepseek". Let me start by breaking down the word. The word is "deepseek". Let me write it out: D, E, E, P, S, E, E, K. Wait, let me check that again. Hmm, maybe I should count each letter one by one.
119
120First, I'll write down the word again to make sure I have it right. D, E, E, P, S, E, E, K. So that's 8 letters. Now, I need to count how many times 'e' appears. Let me go through each letter:
121
1221. D - not an e.
1232. E - that's one.
1243. E - that's two.
1254. P - not an e.
1265. S - not an e.
1276. E - that's three.
1287. E - that's four.
1298. K - not an e.
130
131So, I count four 'e's in the word "deepseek". Let me double-check to make sure I didn't miss any. The letters are D, E, E, P, S, E, E, K. So positions 2, 3, 6, and 7 are 'e's. That's four times. I think that's correct. I don't think I missed any. So the answer should be 4.
132</think>
133
134The word "deepseek" contains 4 instances of the letter 'e'.
135--------------------------------------------------
136Prompt: There are ten birds in a tree. A hunter shoots one. How many are left in the tree?
137Generated: <think>
138Okay, so I came across this problem: "There are ten birds in a tree. A hunter shoots one. How many are left in the tree?" At first glance, it seems straightforward, but I want to make sure I understand it properly. Let me break it down step by step.
139
140First, there are ten birds in the tree. Then, a hunter shoots one. The question is asking how many are left in the tree. Hmm, so the initial number is 10, and one is shot. So, if you subtract one from ten, that would leave nine birds. But wait, I need to consider the possible implications here. Maybe there's a trick question involved.
141
142I remember sometimes these kinds of problems have a twist. For example, maybe the shot causes the other birds to fly away. But the question specifically says the hunter shoots one. So, does that mean the other birds stay? Or do they get scared and fly away? The problem doesn't mention anything about the other birds leaving, so maybe they stay. But I should consider both possibilities.
143
144If the hunter shoots one, and the rest don't fly away, then there would be 10 minus 1, which is 9. But if the other birds get scared and fly away, then there would be 0 left. But the problem doesn't mention the other birds leaving, so maybe the answer is 9. But I need to think about possible interpretations.
145
146Another angle is that maybe the question is a riddle. Sometimes riddles play on words or common sayings. For example, if the question is about birds in a tree and a hunter shoots, maybe the answer is related to the sound or the effect of the shot. But I'm not sure. Let me think.
147
148In some riddles, the answer might be that there are none left because the shot scares all the birds away. So, even though only one was shot, the rest might fly away. But the problem doesn't specify that. So, maybe the answer is 9, but maybe it's 0. I need to figure out which one is correct.
149
150Let me check the wording again. It says, "There are ten birds in a tree. A hunter shoots one. How many are left in the tree?" So, the key here is whether the act of shooting causes the other birds to leave. If the hunter shoots
151"""
152| INT2 | |
|---|---|
| mmlu | 0.7845 |
| hellaswag | 0.6318 |
1import transformers
2from transformers import AutoModelForCausalLM, AutoTokenizer
3from lm_eval.utils import make_table
4
5# https://github.com/huggingface/transformers/pull/35493
6def set_initialized_submodules(model, state_dict_keys):
7 """
8 Sets the `_is_hf_initialized` flag in all submodules of a given model when all its weights are in the loaded state
9 dict.
10 """
11 state_dict_keys = set(state_dict_keys)
12 not_initialized_submodules = {}
13 for module_name, module in model.named_modules():
14 if module_name == "":
15 # When checking if the root module is loaded there's no need to prepend module_name.
16 module_keys = set(module.state_dict())
17 else:
18 module_keys = {f"{module_name}.{k}" for k in module.state_dict()}
19 if module_keys.issubset(state_dict_keys):
20 module._is_hf_initialized = True
21 else:
22 not_initialized_submodules[module_name] = module
23 return not_initialized_submodules
24
25
26transformers.modeling_utils.set_initialized_submodules = set_initialized_submodules
27
28import torch
29
30quantized_model_dir = "OPEA/DeepSeek-R1-int2-gptq-sym-inc"
31
32## directly use device_map='auto' if you have enough GPUs
33device_map = {"model.norm": 0, "lm_head": 0, "model.embed_tokens": 0}
34for i in range(61):
35 name = "model.layers." + str(i)
36 if i < 15:
37 device_map[name] = 0
38 elif i < 30:
39 device_map[name] = 1
40 elif i < 45:
41 device_map[name] = 2
42 else:
43 device_map[name] = 3
44
45model = AutoModelForCausalLM.from_pretrained(
46 quantized_model_dir,
47 torch_dtype=torch.float16,
48 trust_remote_code=True,
49 device_map=device_map,
50)
51tokenizer = AutoTokenizer.from_pretrained(quantized_model_dir)
52
53
54def forward_hook(module, input, output):
55 return torch.clamp(output, -65504, 65504)
56
57
58def register_fp16_hooks(model):
59 for name, module in model.named_modules():
60 if "QuantLinear" in module.__class__.__name__ or isinstance(module, torch.nn.Linear):
61 module.register_forward_hook(forward_hook)
62
63
64register_fp16_hooks(model) ##better add this hook to avoid overflow
65
66from auto_round.eval.evaluation import simple_evaluate_user_model
67
68res = simple_evaluate_user_model( model, tokenizer, tasks=["hellaswag","mmlu"], batch_size=4)
69print(make_table(res))1import safetensors
2from safetensors.torch import save_file
3
4for i in range(1, 164):
5 idx_str = "0" * (5-len(str(i))) + str(i)
6 safetensors_path = f"model-{idx_str}-of-000163.safetensors"
7 print(safetensors_path)
8 tensors = dict()
9 with safetensors.safe_open(safetensors_path, framework="pt") as f:
10 for key in f.keys():
11 tensors[key] = f.get_tensor(key)
12 save_file(tensors, safetensors_path, metadata={'format': 'pt'})1import torch
2from transformers import AutoModelForCausalLM, AutoTokenizer
3import transformers
4
5# https://github.com/huggingface/transformers/pull/35493
6def set_initialized_submodules(model, state_dict_keys):
7 """
8 Sets the `_is_hf_initialized` flag in all submodules of a given model when all its weights are in the loaded state
9 dict.
10 """
11 state_dict_keys = set(state_dict_keys)
12 not_initialized_submodules = {}
13 for module_name, module in model.named_modules():
14 if module_name == "":
15 # When checking if the root module is loaded there's no need to prepend module_name.
16 module_keys = set(module.state_dict())
17 else:
18 module_keys = {f"{module_name}.{k}" for k in module.state_dict()}
19 if module_keys.issubset(state_dict_keys):
20 module._is_hf_initialized = True
21 else:
22 not_initialized_submodules[module_name] = module
23 return not_initialized_submodules
24
25
26transformers.modeling_utils.set_initialized_submodules = set_initialized_submodules
27
28model_name = "opensourcerelease/DeepSeek-R1-bf16"
29
30tokenizer = AutoTokenizer.from_pretrained(model_name)
31model = AutoModelForCausalLM.from_pretrained(model_name, trust_remote_code=True, torch_dtype="auto")
32
33block = model.model.layers
34device_map = {}
35
36for n, m in block.named_modules():
37 if isinstance(m, (torch.nn.Linear, transformers.modeling_utils.Conv1D)):
38 if "experts" in n and ("shared_experts" not in n) and int(n.split('.')[-2]) < 63:
39 device = "cuda:1"
40 elif "experts" in n and ("shared_experts" not in n) and int(n.split('.')[-2]) >= 63 and int(
41 n.split('.')[-2]) < 128:
42 device = "cuda:2"
43 elif "experts" in n and ("shared_experts" not in n) and int(n.split('.')[-2]) >= 128 and int(
44 n.split('.')[-2]) < 192:
45 device = "cuda:3"
46 elif "experts" in n and ("shared_experts" not in n) and int(
47 n.split('.')[-2]) >= 192:
48 device = "cuda:4"
49 else:
50 device = "cuda:0"
51 n = n[2:]
52
53 device_map.update({n: device})
54
55from auto_round import AutoRound
56
57
58
59autoround = AutoRound(model=model, tokenizer=tokenizer, device_map=device_map, bits=2, group_size=64,
60 iters=1000, batch_size=4, seqlen=512, nsamples=512, enable_torch_compile=False,
61 )
62autoround.quantize()
63autoround.save_quantized(format="auto_round", output_dir="tmp_autoround")
64