Views
No views yet
1from datasets import load_dataset
2from transformers import AutoModelForCausalLM, AutoTokenizer
3
4from llmcompressor.modifiers.quantization import GPTQModifier
5from llmcompressor.modifiers.obcq import SparseGPTModifier
6from llmcompressor.transformers import oneshot
7
8# Select model and load it.
9#MODEL_ID = "meta-llama/Meta-Llama-3-8B-Instruct"
10MODEL_ID = "nm-testing/llama2.c-stories15M"
11
12model = AutoModelForCausalLM.from_pretrained(
13 MODEL_ID,
14 device_map="auto",
15 torch_dtype="auto",
16)
17tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
18
19# Select calibration dataset.
20DATASET_ID = "ultrachat_200k"
21
22# Select number of samples. 512 samples is a good place to start.
23# Increasing the number of samples can improve accuracy.
24NUM_CALIBRATION_SAMPLES = 512
25MAX_SEQUENCE_LENGTH = 2048
26
27# Configure the quantization algorithm to run.
28# * quantize the weights to 4 bit with GPTQ with a group size 128
29from compressed_tensors.quantization import QuantizationArgs, QuantizationType, QuantizationStrategy
30recipe = [
31 GPTQModifier(
32 config_groups=dict(group_0=dict(
33 targets=[
34 r"re:model.layers.0.self_attn.q_proj",
35 r"re:model.layers.0.self_attn.k_proj",
36 r"re:model.layers.0.self_attn.v_proj",
37 r"re:model.layers.0.self_attn.o_proj",
38 r"re:model.layers.1.self_attn.q_proj",
39 r"re:model.layers.1.self_attn.k_proj",
40 r"re:model.layers.1.self_attn.v_proj",
41 r"re:model.layers.1.self_attn.o_proj",
42 ],
43 weights=QuantizationArgs(
44 num_bits=4,
45 type=QuantizationType.INT,
46 strategy=QuantizationStrategy.TENSOR,
47 symmetric=True,
48 dynamic=False,
49 ignore=["lm_head"]
50 ),
51 )),
52 ),
53 SparseGPTModifier(
54 sparsity=0.5,
55 #mask_structure="2:4",
56 sequential_update=True,
57 targets=[
58 r"re:model.layers.1.self_attn.q_proj",
59 r"re:model.layers.1.self_attn.k_proj",
60 r"re:model.layers.1.self_attn.v_proj",
61 r"re:model.layers.1.self_attn.o_proj",
62 r"re:model.layers.2.self_attn.q_proj",
63 r"re:model.layers.2.self_attn.k_proj",
64 r"re:model.layers.2.self_attn.v_proj",
65 r"re:model.layers.2.self_attn.o_proj",
66 ],
67 ),
68]
69breakpoint()
70
71# Apply algorithms.
72oneshot(
73 model=model,
74 dataset=DATASET_ID,
75 splits={"calibration": f"train_sft[:{MAX_SEQUENCE_LENGTH}]"},
76 recipe=recipe,
77 max_seq_length=MAX_SEQUENCE_LENGTH,
78 num_calibration_samples=NUM_CALIBRATION_SAMPLES,
79)
80
81# Confirm generations of the quantized model look sane.
82print("\n\n")
83print("========== SAMPLE GENERATION ==============")
84input_ids = tokenizer("Hello my name is", return_tensors="pt").input_ids.to("cuda")
85output = model.generate(input_ids, max_new_tokens=100)
86print(tokenizer.decode(output[0]))
87print("==========================================\n\n")
88
89# Save to disk compressed.
90SAVE_DIR = MODEL_ID.split("/")[1] + "-W4A16-G128-unc"
91model.save_pretrained(SAVE_DIR, save_compressed=True)
92tokenizer.save_pretrained(SAVE_DIR)