robertgshaw2 commited on
Commit
9d40424
1 Parent(s): bd74ab9

Create quantization/apply_gptq_save_marlin.py

Browse files
quantization/apply_gptq_save_marlin.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse, gc, shutil
2
+ from transformers import AutoTokenizer
3
+ from auto_gptq import AutoGPTQForCausalLM, BaseQuantizeConfig
4
+ from datasets import load_dataset
5
+
6
+ parser = argparse.ArgumentParser()
7
+ parser.add_argument("--model-id", type=str)
8
+ parser.add_argument("--save-dir", type=str)
9
+ parser.add_argument("--channelwise", action="store_true")
10
+ parser.add_argument("--num-samples", type=int, default=512)
11
+ parser.add_argument("--max-seq-len", type=int, default=2048)
12
+
13
+
14
+ def preprocess(example):
15
+ return {"text": tokenizer.apply_chat_template(example["messages"], tokenize=False)}
16
+
17
+ if __name__ == "__main__":
18
+ args = parser.parse_args()
19
+
20
+ dataset = load_dataset("HuggingFaceH4/ultrachat_200k", split="train_sft[:5%]")
21
+ tokenizer = AutoTokenizer.from_pretrained(args.model_id)
22
+ ds = dataset.shuffle().select(range(args.num_samples))
23
+ ds = ds.map(preprocess)
24
+
25
+ examples = [
26
+ tokenizer(
27
+ example["text"], padding=False, max_length=args.max_seq_len, truncation=True,
28
+ ) for example in ds
29
+ ]
30
+
31
+ if args.channelwise:
32
+ group_size = -1
33
+ else:
34
+ group_size = 128
35
+
36
+ quantize_config = BaseQuantizeConfig(
37
+ bits=4, # Only support 4 bit
38
+ group_size=group_size, # Set to g=128 or -1 (for channelwise)
39
+ desc_act=False, # Marlin does not suport act_order=True
40
+ model_file_base_name="model" # Name of the model.safetensors when we call save_pretrained
41
+ )
42
+
43
+ model = AutoGPTQForCausalLM.from_pretrained(
44
+ args.model_id,
45
+ quantize_config,
46
+ device_map="auto")
47
+ model.quantize(examples)
48
+
49
+ gptq_save_dir = args.gptq_save_dir
50
+ print(f"Saving gptq model to {gptq_save_dir}")
51
+ model.save_pretrained(gptq_save_dir)
52
+ tokenizer.save_pretrained(gptq_save_dir)
53
+
54
+ del model
55
+ gc.collect()
56
+
57
+ print("Reloading in marlin format")
58
+ gptq_save_dir = "./tmp-gptq"
59
+ marlin_model = AutoGPTQForCausalLM.from_quantized(
60
+ gptq_save_dir,
61
+ use_marlin=True,
62
+ device_map="auto")
63
+
64
+ print("Saving in marlin format")
65
+ marlin_model.save_pretrained(args.marlin_save_dir)
66
+ tokenizer.save_pretrained(args.marlin_save_dir)
67
+
68
+ shutil.rmtree(gptq_save_dir)