Skip to content

Commit 55cfa1b

Browse files
Add Idefics3/SmolVLM quant support via traceable class (#1095)
SUMMARY: Adding a traceable Idefics3 class following the new [guide](https://github.com/vllm-project/llm-compressor/blob/main/src/llmcompressor/transformers/tracing/GUIDE.md) to allow W4A16 quants of Idefics3 and SmolVLM (which share the same architecture). Idefics3 seems to require a max_sequence_length of 4096 and I copied the example from the Phi 3 Vision example as the dataset loading approach from the Llava example led to OOM on 64 GB RAM. TEST PLAN: Tested on A100 with Idefics3 @512 samples and on a 4060 Ti with SmolVLM @128 samples. --------- Co-authored-by: Kyle Sayers <[email protected]>
1 parent 08c4c91 commit 55cfa1b

File tree

3 files changed

+545
-0
lines changed

3 files changed

+545
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,117 @@
1+
import requests
2+
import torch
3+
from datasets import load_dataset
4+
from PIL import Image
5+
from transformers import AutoProcessor
6+
7+
from llmcompressor.modifiers.quantization import GPTQModifier
8+
from llmcompressor.transformers import oneshot
9+
from llmcompressor.transformers.tracing import TraceableIdefics3ForConditionalGeneration
10+
11+
# Load model.
12+
model_id = "HuggingFaceM4/Idefics3-8B-Llama3" # or "HuggingFaceTB/SmolVLM-Instruct"
13+
model = TraceableIdefics3ForConditionalGeneration.from_pretrained(
14+
model_id, device_map="auto", torch_dtype="auto"
15+
)
16+
processor = AutoProcessor.from_pretrained(model_id, trust_remote_code=True)
17+
18+
# Oneshot arguments
19+
DATASET_ID = "lmms-lab/flickr30k"
20+
DATASET_SPLIT = "test[:512]"
21+
NUM_CALIBRATION_SAMPLES = 512
22+
MAX_SEQUENCE_LENGTH = 4096 # Seems to be required here
23+
24+
25+
# Define a oneshot data collator for multimodal inputs.
26+
def data_collator(batch):
27+
assert len(batch) == 1
28+
return {key: torch.tensor(value) for key, value in batch[0].items()}
29+
30+
31+
# Recipe
32+
recipe = [
33+
GPTQModifier(
34+
targets="Linear",
35+
scheme="W4A16",
36+
sequential_targets=["LlamaDecoderLayer"],
37+
ignore=["re:.*lm_head", "re:model.vision_model.*", "re:model.connector.*"],
38+
),
39+
]
40+
41+
# Load dataset and preprocess.
42+
ds = load_dataset(DATASET_ID, split=DATASET_SPLIT)
43+
ds = ds.shuffle(seed=42).select(range(NUM_CALIBRATION_SAMPLES))
44+
45+
46+
# Apply chat template
47+
def preprocess(example):
48+
messages = [
49+
{
50+
"role": "user",
51+
"content": [
52+
{"type": "text", "text": "What does the image show?"},
53+
{"type": "image"},
54+
],
55+
}
56+
]
57+
return {
58+
"text": processor.apply_chat_template(
59+
messages,
60+
add_generation_prompt=True,
61+
),
62+
"images": example["image"],
63+
}
64+
65+
66+
ds = ds.map(preprocess)
67+
68+
69+
# Tokenize inputs.
70+
def tokenize(sample):
71+
return processor(
72+
text=sample["text"],
73+
images=sample["images"],
74+
padding=False,
75+
max_length=MAX_SEQUENCE_LENGTH,
76+
truncation=True,
77+
)
78+
79+
80+
# avoid errors with writer_batch_size
81+
ds = ds.map(tokenize, writer_batch_size=1, remove_columns=ds.column_names)
82+
83+
# Perform oneshot
84+
oneshot(
85+
model=model,
86+
dataset=ds,
87+
recipe=recipe,
88+
max_seq_length=MAX_SEQUENCE_LENGTH,
89+
num_calibration_samples=NUM_CALIBRATION_SAMPLES,
90+
trust_remote_code_model=True,
91+
data_collator=data_collator,
92+
)
93+
94+
# Confirm generations of the quantized model look sane.
95+
print("========== SAMPLE GENERATION ==============")
96+
messages = [
97+
{
98+
"role": "user",
99+
"content": [
100+
{"type": "text", "text": "Please describe the animal in this image\n"},
101+
{"type": "image"},
102+
],
103+
},
104+
]
105+
prompt = processor.apply_chat_template(messages, add_generation_prompt=True)
106+
image_url = "http://images.cocodataset.org/train2017/000000231895.jpg"
107+
raw_image = Image.open(requests.get(image_url, stream=True).raw)
108+
109+
inputs = processor(images=raw_image, text=prompt, return_tensors="pt").to("cuda")
110+
output = model.generate(**inputs, max_new_tokens=100)
111+
print(processor.decode(output[0], skip_special_tokens=True))
112+
print("==========================================")
113+
114+
# Save to disk compressed.
115+
SAVE_DIR = model_id.split("/")[1] + "-W4A16-G128"
116+
model.save_pretrained(SAVE_DIR, save_compressed=True)
117+
processor.save_pretrained(SAVE_DIR)

src/llmcompressor/transformers/tracing/__init__.py

+4
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,13 @@
77
from .qwen2_vl import (
88
Qwen2VLForConditionalGeneration as TraceableQwen2VLForConditionalGeneration,
99
)
10+
from .idefics3 import (
11+
Idefics3ForConditionalGeneration as TraceableIdefics3ForConditionalGeneration
12+
)
1013

1114
__all__ = [
1215
"TraceableLlavaForConditionalGeneration",
1316
"TraceableMllamaForConditionalGeneration",
1417
"TraceableQwen2VLForConditionalGeneration",
18+
"TraceableIdefics3ForConditionalGeneration"
1519
]

0 commit comments

Comments
 (0)