|
| 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) |
0 commit comments