Views
No views yet
1from vllm import LLM, SamplingParams
2from vllm.assets.image import ImageAsset
3from transformers import AutoProcessor
4
5# Define model name once
6model_name = "RedHatAI/gemma-3-1b-it-quantized.w4a16"
7
8# Load image and processor
9image = ImageAsset("cherry_blossom").pil_image.convert("RGB")
10processor = AutoProcessor.from_pretrained(model_name, trust_remote_code=True)
11
12# Build multimodal prompt
13chat = [
14 {"role": "user", "content": [{"type": "image"}, {"type": "text", "text": "What is the content of this image?"}]},
15 {"role": "assistant", "content": []}
16]
17prompt = processor.apply_chat_template(chat, add_generation_prompt=True)
18
19# Initialize model
20llm = LLM(model=model_name, trust_remote_code=True)
21
22# Run inference
23inputs = {"prompt": prompt, "multi_modal_data": {"image": [image]}}
24outputs = llm.generate(inputs, SamplingParams(temperature=0.2, max_tokens=64))
25
26# Display result
27print("RESPONSE:", outputs[0].outputs[0].text)1import base64
2from io import BytesIO
3import torch
4from datasets import load_dataset
5from transformers import AutoProcessor, Gemma3ForConditionalGeneration
6from llmcompressor.modifiers.quantization import GPTQModifier
7from llmcompressor.transformers import oneshot
8
9
10# Load model.
11model_id = "google/gemma-3-1b-it"
12model = Gemma3ForConditionalGeneration.from_pretrained(
13 model_id,
14 device_map="auto",
15 torch_dtype="auto",
16)
17processor = AutoProcessor.from_pretrained(model_id, trust_remote_code=True)
18
19# Oneshot arguments
20DATASET_ID = "neuralmagic/calibration"
21DATASET_SPLIT = {"LLM": "train[:1024]"}
22NUM_CALIBRATION_SAMPLES = 1024
23MAX_SEQUENCE_LENGTH = 2048
24
25# Load dataset and preprocess.
26ds = load_dataset(DATASET_ID, split=DATASET_SPLIT)
27ds = ds.shuffle(seed=42)
28
29dampening_frac=0.05
30
31def data_collator(batch):
32 assert len(batch) == 1, "Only batch size of 1 is supported for calibration"
33 item = batch[0]
34 collated = {}
35 import torch
36
37
38 for key, value in item.items():
39 if isinstance(value, torch.Tensor):
40 collated[key] = value.unsqueeze(0)
41 elif isinstance(value, list) and isinstance(value[0][0], int):
42 # Handle tokenized inputs like input_ids, attention_mask
43 collated[key] = torch.tensor(value)
44 elif isinstance(value, list) and isinstance(value[0][0], float):
45 # Handle possible float sequences
46 collated[key] = torch.tensor(value)
47 elif isinstance(value, list) and isinstance(value[0][0], torch.Tensor):
48 # Handle batched image data (e.g., pixel_values as [C, H, W])
49 collated[key] = torch.stack(value) # -> [1, C, H, W]
50 elif isinstance(value, torch.Tensor):
51 collated[key] = value
52 else:
53 print(f"[WARN] Unrecognized type in collator for key={key}, type={type(value)}")
54
55 return collated
56
57
58
59# Recipe
60recipe = [
61 GPTQModifier(
62 targets="Linear",
63 ignore=["re:.*lm_head.*", "re:.*embed_tokens.*", "re:vision_tower.*", "re:multi_modal_projector.*"],
64 sequential_update=True,
65 sequential_targets=["Gemma3DecoderLayer"],
66 dampening_frac=dampening_frac,
67 config_groups={
68 "group_0": {
69 "targets": ["Linear"],
70 "weights": {
71 "num_bits": 4,
72 "group_size": 128,
73 "type": "int",
74 "symmetric": False,
75 "strategy": "group",
76 "actorder": "weight",
77 },
78 },
79 },
80 )
81]
82
83
84SAVE_DIR=f"{model_id.split('/')[1]}-quantized.w4a16"
85
86# Perform oneshot
87oneshot(
88 model=model,
89 tokenizer=model_id,
90 dataset=ds,
91 recipe=recipe,
92 max_seq_length=MAX_SEQUENCE_LENGTH,
93 num_calibration_samples=NUM_CALIBRATION_SAMPLES,
94 trust_remote_code_model=True,
95 data_collator=data_collator,
96 output_dir=SAVE_DIR
97)lm_eval \
--model vllm \
--model_args pretrained="<model_name>",dtype=auto,add_bos_token=True,max_model_len=4096,tensor_parallel_size=<n>,gpu_memory_utilization=0.8,enable_chunked_prefill=True,trust_remote_code=True,enforce_eager=True \
--tasks openllm \
--batch_size auto| Category | Metric | google/gemma-3-1b-it | RedHatAI/gemma-3-1b-it-quantized.w4a16 | Recovery (%) |
|---|---|---|---|---|
| OpenLLM V1 | ARC Challenge | 36.86% | 33.96% | 92.13% |
| GSM8K | 25.17% | 22.14% | 87.95% | |
| Hellaswag | 56.03% | 53.62% | 95.70% | |
| MMLU | 39.99% | 37.00% | 92.52% | |
| Truthfulqa (mc2) | 38.54% | 39.94% | 103.64% | |
| Winogrande | 58.88% | 57.54% | 97.72% | |
| Average Score | 42.58% | 40.70% | 95.59% |