Views
No views yet
| wiki | |
|---|---|
| FP | 5,33 |
| Quantized | 5,90 |
| piqa | arc_easy | arc_challenge | boolq | hellaswag | winogrande | mmlu_humanities | mmlu_social_sciences | mmlu_stem | mmlu_other | |
|---|---|---|---|---|---|---|---|---|---|---|
| FP | 81,5 | 86,2 | 61,9 | 87,4 | 63,7 | 75,8 | 78,7 | 84,4 | 71,1 | 80,2 |
| Quantized | 80,7 | 85,8 | 61,4 | 87,0 | 62,7 | 73,0 | 75,5 | 81,0 | 68,6 | 77,9 |
| danetqa | terra | rwsd | muserc | rucos | lidirus | parus | rcb | russe | rucola | |
|---|---|---|---|---|---|---|---|---|---|---|
| FP | 88,9 | 88,6 | 75,5 | 81,8 | 82,4 | 70,7 | 77,0 | 35,0 | 63,1 | 34,7 |
| Quantized | 86,6 | 81,8 | 71,6 | 75,6 | 69,5 | 60,3 | 64,0 | 26,8 | 63,1 | 32,5 |
| Avg acc diff on Eng, % (↑) | Avg acc diff on Rus, % (↑) | Occupied disk space, % (↓) | |
|---|---|---|---|
| FP | 0 | 0 | 100 |
| Quantized | -1,7 | -6,6 | 28,2 |
1import gc
2
3import auto_gptq.nn_modules.qlinear.qlinear_cuda as qlinear_cuda
4import auto_gptq.nn_modules.qlinear.qlinear_triton as qlinear_triton
5import torch
6
7from accelerate import (
8 init_empty_weights,
9 infer_auto_device_map,
10 load_checkpoint_in_model,
11)
12from tqdm import tqdm
13from transformers import (
14 AutoConfig,
15 AutoModelForCausalLM,
16 AutoTokenizer,
17 pipeline,
18)
19
20
21def get_named_linears(model):
22 return {
23 name: module for name, module in model.named_modules()
24 if isinstance(module, torch.nn.Linear)
25 }
26
27
28def set_module(model, name, module):
29 parent = model
30 levels = name.split('.')
31
32 for i in range(len(levels) - 1):
33 cur_name = levels[i]
34
35 if cur_name.isdigit():
36 parent = parent[int(cur_name)]
37 else:
38 parent = getattr(parent, cur_name)
39
40 setattr(parent, levels[-1], module)
41
42
43def load_model(model_path):
44 # Based on: https://github.com/OpenGVLab/OmniQuant/blob/main/runing_quantized_mixtral_7bx8.ipynb
45
46 config = AutoConfig.from_pretrained(model_path, trust_remote_code=True)
47
48 if not hasattr(config, 'quantization_config'):
49 raise AttributeError(
50 f'No quantization info found in model config "{model_path}"'
51 f' (`quantization_config` section is missing).'
52 )
53
54 wbits = config.quantization_config['bits']
55 group_size = config.quantization_config['group_size']
56
57 # We are going to init an ordinary model and then manually replace all Linears with QuantLinears
58 del config.quantization_config
59
60 with init_empty_weights():
61 model = AutoModelForCausalLM.from_config(config=config, torch_dtype=torch.float16, trust_remote_code=True)
62
63 layers = model.model.layers
64
65 for i in tqdm(range(len(layers))):
66 layer = layers[i]
67 named_linears = get_named_linears(layer)
68
69 for name, module in named_linears.items():
70 params = (
71 wbits, group_size,
72 module.in_features, module.out_features,
73 module.bias is not None
74 )
75
76 if wbits in [2, 4]:
77 q_linear = qlinear_triton.QuantLinear(*params)
78 elif wbits == 3:
79 q_linear = qlinear_cuda.QuantLinear(*params)
80 else:
81 raise NotImplementedError("Only 2, 3 and 4 bits are supported.")
82
83 q_linear.to(next(layer.parameters()).device)
84 set_module(layer, name, q_linear)
85
86 torch.cuda.empty_cache()
87 gc.collect()
88
89 model.tie_weights()
90 device_map = infer_auto_device_map(model)
91
92 print("Loading pre-computed quantized weights...")
93
94 load_checkpoint_in_model(
95 model, checkpoint=model_path,
96 device_map=device_map, offload_state_dict=True,
97 )
98
99 print("Model loaded successfully!")
100
101 return model1model_path = "compressa-ai/Llama-3-70B-Instruct-OmniQuant"
2
3model = load_model(model_path).cuda()
4tokenizer = AutoTokenizer.from_pretrained(
5 model_path, use_fast=False, trust_remote_code=True
6)
7
8# Llama 3 "specifics"
9# https://huggingface.co/meta-llama/Meta-Llama-3-8B-Instruct/discussions/4
10terminators = [
11 tokenizer.convert_tokens_to_ids("<|end_of_text|>"),
12 tokenizer.convert_tokens_to_ids("<|eot_id|>")
13]
14
15system_message = "You are a friendly chatbot who responds as if you are the Sandy Cheeks squirrel from the SpongeBob SquarePants cartoon."
16user_message = "Do squirrels communicate with birds?"
17messages = [
18 {"role": "system", "content": system_message},
19 {"role": "user", "content": user_message},
20]
21prompt = tokenizer.apply_chat_template(
22 messages, tokenize=False, add_generation_prompt=True
23)
24
25inputs = tokenizer(prompt, return_tensors="pt")
26inputs = {k: v.cuda() for k, v in inputs.items()}
27
28outputs = model.generate(
29 **inputs, max_new_tokens=512,
30 do_sample=True, temperature=0.7, top_p=0.95,
31 eos_token_id=terminators,
32)
33
34response = tokenizer.decode(outputs[0])
35continuation = response.removeprefix(prompt).removesuffix(tokenizer.eos_token)
36
37print(f'Prompt:\n{prompt}')
38print(f'Continuation:\n{continuation}\n')1pipe = pipeline(
2 "text-generation",
3 model=model, tokenizer=tokenizer,
4 eos_token_id=terminators,
5 max_new_tokens=512, do_sample=True,
6 temperature=0.7, top_p=0.95,
7 device=0,
8)
9
10prompt = pipe.tokenizer.apply_chat_template(
11 messages, tokenize=False, add_generation_prompt=True
12)
13
14outputs = pipe(prompt)
15
16response = outputs[0]["generated_text"]
17continuation = response.removeprefix(prompt)
18
19print(f'Prompt:\n{prompt}')
20print(f'Continuation:\n{continuation}\n')