|
| 1 | +import json |
| 2 | +import os |
| 3 | + |
| 4 | +import requests |
| 5 | +import torch |
| 6 | +from PIL import Image |
| 7 | +from transformers import AutoProcessor, Mistral3ForConditionalGeneration |
| 8 | + |
| 9 | +from llmcompressor import oneshot |
| 10 | +from llmcompressor.modifiers.quantization import GPTQModifier |
| 11 | + |
| 12 | +# Load model. |
| 13 | +model_id = "mistralai/Mistral-Small-3.1-24B-Instruct-2503" |
| 14 | +model = Mistral3ForConditionalGeneration.from_pretrained( |
| 15 | + model_id, device_map="auto", torch_dtype="auto" |
| 16 | +) |
| 17 | +processor = AutoProcessor.from_pretrained(model_id, trust_remote_code=True) |
| 18 | + |
| 19 | +# Use a custom calibration chat template, rather than the overly-verbose default |
| 20 | +file_path = os.path.join(os.path.dirname(__file__), "mistral3_chat_template.json") |
| 21 | +with open(file_path, "r") as file: |
| 22 | + processor.chat_template = json.load(file)["chat_template"] |
| 23 | + |
| 24 | +# Oneshot arguments |
| 25 | +DATASET_ID = "flickr30k" |
| 26 | +DATASET_SPLIT = "test" |
| 27 | +NUM_CALIBRATION_SAMPLES = 512 |
| 28 | +MAX_SEQUENCE_LENGTH = 2048 |
| 29 | + |
| 30 | + |
| 31 | +# Define a oneshot data collator for multimodal inputs. |
| 32 | +def data_collator(batch): |
| 33 | + assert len(batch) == 1 |
| 34 | + return { |
| 35 | + key: torch.tensor(value) |
| 36 | + if key != "pixel_values" |
| 37 | + else torch.tensor(value, dtype=model.dtype) |
| 38 | + for key, value in batch[0].items() |
| 39 | + } |
| 40 | + |
| 41 | + |
| 42 | +# Recipe |
| 43 | +recipe = [ |
| 44 | + GPTQModifier( |
| 45 | + targets="Linear", |
| 46 | + scheme="W4A16", |
| 47 | + sequential_targets=["MistralDecoderLayer"], |
| 48 | + ignore=["re:.*lm_head", "re:vision_tower.*", "re:multi_modal_projector.*"], |
| 49 | + ), |
| 50 | +] |
| 51 | + |
| 52 | +# Perform oneshot |
| 53 | +oneshot( |
| 54 | + model=model, |
| 55 | + tokenizer=model_id, |
| 56 | + dataset=DATASET_ID, |
| 57 | + splits={"calibration": f"{DATASET_SPLIT}[:{NUM_CALIBRATION_SAMPLES}]"}, |
| 58 | + recipe=recipe, |
| 59 | + max_seq_length=MAX_SEQUENCE_LENGTH, |
| 60 | + num_calibration_samples=NUM_CALIBRATION_SAMPLES, |
| 61 | + trust_remote_code_model=True, |
| 62 | + data_collator=data_collator, |
| 63 | +) |
| 64 | + |
| 65 | +# Confirm generations of the quantized model look sane. |
| 66 | +print("========== SAMPLE GENERATION ==============") |
| 67 | +messages = [ |
| 68 | + { |
| 69 | + "role": "user", |
| 70 | + "content": [ |
| 71 | + {"type": "text", "text": "Please describe the animal in this image\n"}, |
| 72 | + {"type": "image"}, |
| 73 | + ], |
| 74 | + }, |
| 75 | +] |
| 76 | +prompt = processor.apply_chat_template(messages, add_generation_prompt=True) |
| 77 | +image_url = "http://images.cocodataset.org/train2017/000000231895.jpg" |
| 78 | +raw_image = Image.open(requests.get(image_url, stream=True).raw) |
| 79 | + |
| 80 | +inputs = processor(images=raw_image, text=prompt, return_tensors="pt").to("cuda") |
| 81 | +inputs["pixel_values"] = inputs["pixel_values"].to(model.dtype) # fix dtype |
| 82 | +output = model.generate(**inputs, max_new_tokens=100) |
| 83 | +print(processor.decode(output[0], skip_special_tokens=True)) |
| 84 | +print("==========================================") |
| 85 | + |
| 86 | +# Save to disk compressed. |
| 87 | +SAVE_DIR = model_id.split("/")[1] + "-W4A16-G128" |
| 88 | +model.save_pretrained(SAVE_DIR, save_compressed=True) |
| 89 | +processor.save_pretrained(SAVE_DIR) |
0 commit comments