import torchfrom datasets import load_datasetfrom transformers import AutoModelForCausalLM, AutoProcessor from llmcompressor.modifiers.quantization import GPTQModifierfrom llmcompressor.transformers import oneshot # Load model.model_id = "microsoft/Phi-3-vision-128k-instruct"model = AutoModelForCausalLM.from_pretrained( model_id, device_map="auto", torch_dtype="auto", trust_remote_code=True, _attn_implementation="eager",)processor = AutoProcessor.from_pretrained(model_id, trust_remote_code=True)processor.chat_template = processor.tokenizer.chat_template # Calibration dataset argumentsDATASET_ID = "lmms-lab/flickr30k"DATASET_SPLIT = "test[:512]"NUM_CALIBRATION_SAMPLES = 512MAX_SEQUENCE_LENGTH = 2048 # Load dataset and preprocess.ds = load_dataset(DATASET_ID, split=DATASET_SPLIT)ds = ds.shuffle(seed=42).select(range(NUM_CALIBRATION_SAMPLES)) # Apply chat template and tokenize inputs.def preprocess_and_tokenize(example): messages = [{"role": "user", "content": "<|image_1|>\nWhat does the image show?"}] text = processor.apply_chat_template( messages, add_generation_prompt=True, ) images = example["image"] return processor( text=text, images=images, padding=False, max_length=MAX_SEQUENCE_LENGTH, truncation=True, ) ds = ds.map(preprocess_and_tokenize, writer_batch_size=1, remove_columns=ds.column_names) # Define a oneshot data collator for multimodal inputs.def data_collator(batch): assert len(batch) == 1 return {key: torch.tensor(value) for key, value in batch[0].items()} # Reciperecipe = GPTQModifier( targets="Linear", scheme="W4A16", sequential_targets=["Phi3DecoderLayer"], ignore=["lm_head", "re:model.vision_embed_tokens.*"],) # Perform oneshotSAVE_DIR = model_id.split("/")[1] + "-W4A16-G128" oneshot( model=model, processor=processor, dataset=ds, recipe=recipe, max_seq_length=MAX_SEQUENCE_LENGTH, num_calibration_samples=NUM_CALIBRATION_SAMPLES, trust_remote_code_model=True, data_collator=data_collator, output_dir=SAVE_DIR)