|
| 1 | +# ******************************************************************************* |
| 2 | +# Copyright 2025 Arm Limited and affiliates. |
| 3 | +# SPDX-License-Identifier: Apache-2.0 |
| 4 | +# |
| 5 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 6 | +# you may not use this file except in compliance with the License. |
| 7 | +# You may obtain a copy of the License at |
| 8 | +# |
| 9 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | +# |
| 11 | +# Unless required by applicable law or agreed to in writing, software |
| 12 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | +# See the License for the specific language governing permissions and |
| 15 | +# limitations under the License. |
| 16 | +# ******************************************************************************* |
| 17 | + |
| 18 | +import argparse |
| 19 | +import requests |
| 20 | +import torch |
| 21 | +from PIL import Image |
| 22 | +from transformers import MllamaForConditionalGeneration, AutoProcessor, GenerationConfig, TextStreamer |
| 23 | +import time |
| 24 | +from torchao.quantization.quant_api import ( |
| 25 | + Int8DynamicActivationIntxWeightConfig, |
| 26 | + quantize_, |
| 27 | +) |
| 28 | +from torchao.dtypes.uintx.packed_linear_int8_dynamic_activation_intx_weight_layout import ( |
| 29 | + PackedLinearInt8DynamicActivationIntxWeightLayout, |
| 30 | + Target, |
| 31 | +) |
| 32 | +from torchao.quantization.granularity import PerGroup, PerAxis |
| 33 | +from torchao.quantization.quant_primitives import MappingType |
| 34 | +import numpy as np |
| 35 | +import os |
| 36 | + |
| 37 | +def main(args): |
| 38 | + |
| 39 | + model_id = "meta-llama/Llama-3.2-11B-Vision-Instruct" |
| 40 | + model = MllamaForConditionalGeneration.from_pretrained( |
| 41 | + model_id, |
| 42 | + torch_dtype=torch.bfloat16 if args.dtype == "bfloat16" else torch.float32, |
| 43 | + ) |
| 44 | + |
| 45 | + if args.quantize: |
| 46 | + layout = PackedLinearInt8DynamicActivationIntxWeightLayout(target=Target.ATEN) |
| 47 | + quantize_( |
| 48 | + model, |
| 49 | + Int8DynamicActivationIntxWeightConfig( |
| 50 | + weight_scale_dtype=torch.float32, |
| 51 | + weight_granularity=PerAxis(0), #PerAxis is also supported |
| 52 | + weight_mapping_type=MappingType.SYMMETRIC_NO_CLIPPING_ERR, # MappingType.SYMMETRIC can also be used but increases error |
| 53 | + layout=layout, |
| 54 | + weight_dtype=torch.int4, |
| 55 | + ), |
| 56 | + ) |
| 57 | + |
| 58 | + processor = AutoProcessor.from_pretrained(model_id) |
| 59 | + image = Image.open(requests.get(args.image_url, stream=True).raw) |
| 60 | + |
| 61 | + messages = [ |
| 62 | + {"role": "user", "content": [ |
| 63 | + {"type": "image"}, |
| 64 | + {"type": "text", "text": args.prompt + os.linesep} |
| 65 | + ]} |
| 66 | + ] |
| 67 | + |
| 68 | + input_text = processor.apply_chat_template(messages, add_generation_prompt=True) |
| 69 | + inputs = processor( |
| 70 | + image, |
| 71 | + input_text, |
| 72 | + add_special_tokens=False, |
| 73 | + return_tensors="pt" |
| 74 | + ).to(model.device) |
| 75 | + |
| 76 | + |
| 77 | + prefill_generation_config = GenerationConfig(do_sample=False, max_new_tokens=1, min_new_tokens=1, temperature=None, top_p=None) |
| 78 | + e2e_generation_config = GenerationConfig(do_sample=False, max_new_tokens=args.num_new_tokens, min_new_tokens=args.num_new_tokens, temperature=None, top_p=None) |
| 79 | + |
| 80 | + print("=" * 100) |
| 81 | + if args.benchmark: |
| 82 | + WARMUP_ITERS = 1 |
| 83 | + BENCHMARK_ITERS = 3 |
| 84 | + |
| 85 | + # prefill |
| 86 | + for _ in range(WARMUP_ITERS): |
| 87 | + model.generate(**inputs, generation_config=prefill_generation_config) |
| 88 | + |
| 89 | + prefill_times = [] |
| 90 | + for _ in range(BENCHMARK_ITERS): |
| 91 | + start_time = time.time() |
| 92 | + model.generate(**inputs, generation_config=prefill_generation_config) |
| 93 | + prefill_times.append(time.time() - start_time) |
| 94 | + |
| 95 | + mean_prefill_times = np.mean(prefill_times) |
| 96 | + print("Prefill Time: ", mean_prefill_times) |
| 97 | + |
| 98 | + # end to end generation |
| 99 | + for _ in range(WARMUP_ITERS): |
| 100 | + model.generate(**inputs, generation_config=e2e_generation_config) |
| 101 | + |
| 102 | + e2e_times = [] |
| 103 | + for _ in range(BENCHMARK_ITERS): |
| 104 | + start_time = time.time() |
| 105 | + model.generate(**inputs, generation_config=e2e_generation_config) |
| 106 | + e2e_times.append(time.time() - start_time) |
| 107 | + |
| 108 | + mean_e2e_times = np.mean(e2e_times) |
| 109 | + print("End to End Time: ", mean_e2e_times) |
| 110 | + print("Decode Throughput: ", args.num_new_tokens / (mean_e2e_times - mean_prefill_times)) |
| 111 | + |
| 112 | + print("Model output:") |
| 113 | + streamer = TextStreamer(processor, skip_special_tokens=True) |
| 114 | + model.generate(**inputs, streamer=streamer, generation_config=e2e_generation_config) |
| 115 | + print("=" * 100) |
| 116 | + |
| 117 | + |
| 118 | +if __name__ == "__main__": |
| 119 | + parser = argparse.ArgumentParser(description="Quantize and Run Benchmark LLM") |
| 120 | + parser.add_argument( |
| 121 | + "--num-new-tokens", |
| 122 | + type=int, |
| 123 | + default=32, |
| 124 | + help="The model will always generate this number of new tokens", |
| 125 | + ) |
| 126 | + parser.add_argument( |
| 127 | + "--prompt", |
| 128 | + type=str, |
| 129 | + default="Describe this image", |
| 130 | + help="Input prompt.", |
| 131 | + ) |
| 132 | + parser.add_argument( |
| 133 | + "--image-url", |
| 134 | + type=str, |
| 135 | + default="https://huggingface.co/datasets/huggingface/documentation-images/resolve/0052a70beed5bf71b92610a43a52df6d286cd5f3/diffusers/rabbit.jpg", |
| 136 | + help="URL to image" |
| 137 | + ) |
| 138 | + parser.add_argument( |
| 139 | + "--benchmark", |
| 140 | + action="store_true", |
| 141 | + help="Run a benchmark, with warmup and multiple iterations" |
| 142 | + ) |
| 143 | + parser.add_argument( |
| 144 | + "--dtype", |
| 145 | + type=str, |
| 146 | + default="bfloat16", |
| 147 | + choices=["bfloat16", "float32"], |
| 148 | + help="Precision to run the model in (or the non-linear layers for quantized model)" |
| 149 | + ) |
| 150 | + parser.add_argument( |
| 151 | + "--quantize", |
| 152 | + action="store_true", |
| 153 | + help="Quantize weights to int4 symmetric channelwise" |
| 154 | + ) |
| 155 | + |
| 156 | + args = parser.parse_args() |
| 157 | + main(args) |
0 commit comments