Views
No views yet
1
2import os
3
4from datasets import load_dataset
5from llmcompressor import oneshot
6from llmcompressor.modifiers.quantization import QuantizationModifier
7from llmcompressor.utils import dispatch_for_generation
8from transformers import AutoModelForCausalLM, AutoTokenizer
9
10os.environ["HF_HUB_ENABLE_HF_TRANSFER"] = "1"
11MODEL_ID = "HiTZ/Latxa-Llama-3.1-70B-Instruct"
12
13# Load model.
14model = AutoModelForCausalLM.from_pretrained(MODEL_ID, torch_dtype="auto")
15tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
16
17
18DATASET_ID = "Iker/calibration-dataset"
19DATASET_SPLIT = "train"
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 = 2048
24MAX_SEQUENCE_LENGTH = 8192
25
26# Load dataset and preprocess.
27ds = load_dataset(DATASET_ID, split="train")
28ds = ds.shuffle(seed=42)
29ds = ds.select(range(NUM_CALIBRATION_SAMPLES))
30
31
32def preprocess(example):
33 return {
34 "text": tokenizer.apply_chat_template(
35 example["messages"],
36 tokenize=False,
37 )
38 }
39
40
41ds = ds.map(preprocess)
42
43
44# Tokenize inputs.
45def tokenize(sample):
46 return tokenizer(
47 sample["text"],
48 padding=False,
49 max_length=MAX_SEQUENCE_LENGTH,
50 truncation=True,
51 add_special_tokens=False,
52 )
53
54
55ds = ds.map(tokenize, remove_columns=ds.column_names)
56
57# Configure the quantization algorithm and scheme.
58# In this case, we:
59# * quantize the weights to fp4 with per group 16 via ptq
60# * calibrate a global_scale for activations, which will be used to
61# quantize activations to fp4 on the fly
62recipe = QuantizationModifier(targets="Linear", scheme="FP8_DYNAMIC", ignore=["lm_head"])
63
64# Apply quantization.
65oneshot(
66 model=model,
67 dataset=ds,
68 recipe=recipe,
69 max_seq_length=MAX_SEQUENCE_LENGTH,
70 num_calibration_samples=NUM_CALIBRATION_SAMPLES,
71)
72
73print("\n\n")
74print("========== SAMPLE GENERATION ==============")
75dispatch_for_generation(model)
76model_input = tokenizer.apply_chat_template(
77 [{"role": "user", "content": "Who are you?"}],
78 tokenize=True,
79 return_tensors="pt",
80)
81#output = model.generate(model_input.to(model.device), max_new_tokens=100, temperature=0.6, do_sample=True)
82#print(tokenizer.decode(output[0]))
83print("==========================================\n\n")
84
85
86# Save to disk in compressed-tensors format.
87SAVE_DIR = MODEL_ID.rstrip("/").split("/")[-1] + "-w8a8_fp8"
88model.save_pretrained(SAVE_DIR, save_compressed=True)
89tokenizer.save_pretrained(SAVE_DIR)
90
91
92model.push_to_hub("Iker/Latxa-Llama-3.1-70B-Instruct-w8a8_fp8")
93tokenizer.push_to_hub("Iker/Latxa-Llama-3.1-70B-Instruct-w8a8_fp8")
94