Views
No views yet
1from vllm.assets.image import ImageAsset
2from vllm import LLM, SamplingParams
3
4# prepare model
5llm = LLM(
6 model="neuralmagic/Phi-3-vision-128k-instruct-W4A16-G128",
7 trust_remote_code=True,
8 max_model_len=4096,
9 max_num_seqs=2,
10)
11
12# prepare inputs
13question = "What is the content of this image?"
14inputs = {
15 "prompt": f"<|user|>\n<|image_1|>\n{question}<|end|>\n<|assistant|>\n",
16 "multi_modal_data": {
17 "image": ImageAsset("cherry_blossom").pil_image.convert("RGB")
18 },
19}
20
21# generate response
22print("========== SAMPLE GENERATION ==============")
23outputs = llm.generate(inputs, SamplingParams(temperature=0.2, max_tokens=64))
24print(f"PROMPT : {outputs[0].prompt}")
25print(f"RESPONSE: {outputs[0].outputs[0].text}")
26print("==========================================")1import torch
2from datasets import load_dataset
3from transformers import AutoModelForCausalLM, AutoProcessor
4
5from llmcompressor.modifiers.quantization import GPTQModifier
6from llmcompressor.transformers import oneshot
7
8# Load model.
9model_id = "microsoft/Phi-3-vision-128k-instruct"
10model = AutoModelForCausalLM.from_pretrained(
11 model_id,
12 device_map="auto",
13 torch_dtype="auto",
14 trust_remote_code=True,
15 _attn_implementation="eager",
16)
17processor = AutoProcessor.from_pretrained(model_id, trust_remote_code=True)
18processor.chat_template = processor.tokenizer.chat_template
19
20# Calibration dataset arguments
21DATASET_ID = "lmms-lab/flickr30k"
22DATASET_SPLIT = "test[:512]"
23NUM_CALIBRATION_SAMPLES = 512
24MAX_SEQUENCE_LENGTH = 2048
25
26# Load dataset and preprocess.
27ds = load_dataset(DATASET_ID, split=DATASET_SPLIT)
28ds = ds.shuffle(seed=42).select(range(NUM_CALIBRATION_SAMPLES))
29
30# Apply chat template and tokenize inputs.
31def preprocess_and_tokenize(example):
32 messages = [{"role": "user", "content": "<|image_1|>\nWhat does the image show?"}]
33 text = processor.apply_chat_template(
34 messages,
35 add_generation_prompt=True,
36 )
37 images = example["image"]
38
39 return processor(
40 text=text,
41 images=images,
42 padding=False,
43 max_length=MAX_SEQUENCE_LENGTH,
44 truncation=True,
45 )
46
47ds = ds.map(preprocess_and_tokenize, writer_batch_size=1, remove_columns=ds.column_names)
48
49# Define a oneshot data collator for multimodal inputs.
50def data_collator(batch):
51 assert len(batch) == 1
52 return {key: torch.tensor(value) for key, value in batch[0].items()}
53
54
55# Recipe
56recipe = GPTQModifier(
57 targets="Linear",
58 scheme="W4A16",
59 sequential_targets=["Phi3DecoderLayer"],
60 ignore=["lm_head", "re:model.vision_embed_tokens.*"],
61)
62
63# Perform oneshot
64SAVE_DIR = model_id.split("/")[1] + "-W4A16-G128"
65
66oneshot(
67 model=model,
68 processor=processor,
69 dataset=ds,
70 recipe=recipe,
71 max_seq_length=MAX_SEQUENCE_LENGTH,
72 num_calibration_samples=NUM_CALIBRATION_SAMPLES,
73 trust_remote_code_model=True,
74 data_collator=data_collator,
75 output_dir=SAVE_DIR
76)