Views
No views yet
1import os
2
3from datasets import load_dataset
4from llmcompressor import oneshot
5from llmcompressor.modifiers.quantization import QuantizationModifier
6from llmcompressor.utils import dispatch_for_generation
7from transformers import AutoModelForCausalLM, AutoTokenizer
8
9os.environ["HF_HUB_ENABLE_HF_TRANSFER"] = "1"
10MODEL_ID = "HiTZ/Latxa-Llama-3.1-8B-Instruct"
11
12# Load model.
13model = AutoModelForCausalLM.from_pretrained(MODEL_ID, torch_dtype="auto")
14tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
15
16
17DATASET_ID = "Iker/calibration-dataset"
18DATASET_SPLIT = "train"
19
20# Select number of samples. 512 samples is a good place to start.
21# Increasing the number of samples can improve accuracy.
22NUM_CALIBRATION_SAMPLES = 2048
23MAX_SEQUENCE_LENGTH = 8192
24
25# Load dataset and preprocess.
26ds = load_dataset(DATASET_ID, split="train")
27ds = ds.shuffle(seed=42)
28ds = ds.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 and scheme.
57# In this case, we:
58# * quantize the weights to fp4 with per group 16 via ptq
59# * calibrate a global_scale for activations, which will be used to
60# quantize activations to fp4 on the fly
61recipe = QuantizationModifier(targets="Linear", scheme="NVFP4", ignore=["lm_head"])
62
63# Apply quantization.
64oneshot(
65 model=model,
66 dataset=ds,
67 recipe=recipe,
68 max_seq_length=MAX_SEQUENCE_LENGTH,
69 num_calibration_samples=NUM_CALIBRATION_SAMPLES,
70)
71
72print("\n\n")
73print("========== SAMPLE GENERATION ==============")
74dispatch_for_generation(model)
75model_input = tokenizer.apply_chat_template(
76 [{"role": "user", "content": "Who are you?"}],
77 tokenize=True,
78 return_tensors="pt",
79)
80output = model.generate(model_input.to(model.device), max_new_tokens=100, temperature=0.6, do_sample=True)
81print(tokenizer.decode(output[0]))
82print("==========================================\n\n")
83
84
85# Save to disk in compressed-tensors format.
86SAVE_DIR = MODEL_ID.rstrip("/").split("/")[-1] + "-w4a4_nvfp4"
87model.save_pretrained(SAVE_DIR, save_compressed=True)
88tokenizer.save_pretrained(SAVE_DIR)
89
90
91model.push_to_hub("Iker/Latxa-Llama-3.1-8B-Instruct-w4a4_nvfp4")
92tokenizer.push_to_hub("Iker/Latxa-Llama-3.1-8B-Instruct-w4a4_nvfp4")