Views
No views yet
1import time
2from datasets import load_dataset
3from transformers import AutoTokenizer
4from rich import print
5from llmcompressor.modifiers.quantization import GPTQModifier
6from llmcompressor.transformers import SparseAutoModelForCausalLM, oneshot
7
8# Select model and load it.
9MODEL_ID = "Unbabel/TowerInstruct-7B-v0.1"
10model = SparseAutoModelForCausalLM.from_pretrained(
11 MODEL_ID,
12 device_map="auto",
13 torch_dtype="auto",
14)
15tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
16
17# Select calibration dataset.
18DATASET_ID = "HuggingFaceH4/ultrachat_200k"
19DATASET_SPLIT = "train_sft"
20
21# Select number of samples. 512 samples is a good place to start.
22# Increasing the number of samples can improve accuracy.
23NUM_CALIBRATION_SAMPLES = 512
24MAX_SEQUENCE_LENGTH = 2048
25
26# Load dataset and preprocess.
27ds = load_dataset(DATASET_ID, split=DATASET_SPLIT)
28ds = ds.shuffle(seed=42).select(range(NUM_CALIBRATION_SAMPLES))
29
30
31def preprocess(example):
32 return {
33 "text": tokenizer.apply_chat_template(
34 example["messages"],
35 tokenize=False,
36 )
37 }
38
39
40ds = ds.map(preprocess)
41
42
43# Tokenize inputs.
44def tokenize(sample):
45 return tokenizer(
46 sample["text"],
47 padding=False,
48 max_length=MAX_SEQUENCE_LENGTH,
49 truncation=True,
50 add_special_tokens=False,
51 )
52
53
54ds = ds.map(tokenize, remove_columns=ds.column_names)
55
56# Configure the quantization algorithm to run.
57# * quantize the weights to 4 bit with GPTQ with a group size 128
58# Note: to reduce GPU memory use `sequential_update=False`
59recipe = GPTQModifier(targets="Linear", scheme="W4A16", ignore=["lm_head"])
60print(recipe)
61
62# Apply algorithms.
63oneshot(
64 model=model,
65 dataset=ds,
66 recipe=recipe,
67 max_seq_length=MAX_SEQUENCE_LENGTH,
68 num_calibration_samples=NUM_CALIBRATION_SAMPLES,
69)
70
71# Confirm generations of the quantized model look sane and measure generation time.
72print("\n\n")
73print("========== SAMPLE GENERATION ==============")
74input_text = "Translate the following text from Portuguese into English.\nPortuguese: Um grupo de investigadores lançou um novo modelo para tarefas relacionadas com tradução.\nEnglish:"
75input_ids = tokenizer(input_text, return_tensors="pt").input_ids.to("cuda")
76
77start_time = time.time()
78
79output = model.generate(input_ids, max_new_tokens=100)
80
81end_time = time.time()
82generation_time = end_time - start_time
83
84print(tokenizer.decode(output[0]))
85print(f"Generation time: {generation_time:.2f} seconds")
86print("==========================================\n\n")
87
88# Save to disk compressed.
89SAVE_DIR = MODEL_ID.split("/")[1] + "-W4A16-G128"
90model.save_pretrained(SAVE_DIR, save_compressed=True)
91tokenizer.save_pretrained(SAVE_DIR)