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 AutoProcessor, AutoModelForVision2Seq
8
9os.environ["HF_HUB_ENABLE_HF_TRANSFER"] = "1"
10MODEL_ID = "HiTZ/Latxa-Qwen3-VL-2B-Instruct"
11
12# Load model.
13model = AutoModelForVision2Seq.from_pretrained(MODEL_ID, torch_dtype="auto")
14processor = AutoProcessor.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": processor.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 processor.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="FP8_DYNAMIC", 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
72
73print("\n\n")
74print("========== SAMPLE GENERATION ==============")
75dispatch_for_generation(model)
76messages = [
77 {
78 "role": "user",
79 "content": [
80 {
81 "type": "image",
82 "url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/p-blog/candy.JPG",
83 },
84 {"type": "text", "text": "What animal is on the candy?"},
85 ],
86 },
87]
88inputs = processor.apply_chat_template(
89 messages,
90 add_generation_prompt=True,
91 tokenize=True,
92 return_dict=True,
93 return_tensors="pt",
94).to(model.device)
95
96# output = model.generate(**inputs, max_new_tokens=40)
97# print(processor.decode(output[0][inputs["input_ids"].shape[-1] :]))
98print("==========================================\n\n")
99
100
101# Save to disk in compressed-tensors format.
102SAVE_DIR = MODEL_ID.rstrip("/").split("/")[-1] + "-w8a8_fp8"
103model.save_pretrained(SAVE_DIR, save_compressed=True)
104processor.save_pretrained(SAVE_DIR)
105
106
107model.push_to_hub("Iker/" + SAVE_DIR)
108processor.push_to_hub("Iker/" + SAVE_DIR)