|
| 1 | +from transformers import AutoProcessor, Qwen2_5_VLForConditionalGeneration |
| 2 | + |
| 3 | +from llmcompressor import oneshot |
| 4 | +from llmcompressor.modifiers.quantization import QuantizationModifier |
| 5 | +from llmcompressor.utils import dispatch_for_generation |
| 6 | + |
| 7 | +MODEL_ID = "Qwen/Qwen2.5-VL-7B-Instruct" |
| 8 | + |
| 9 | +# Load model. |
| 10 | +model = Qwen2_5_VLForConditionalGeneration.from_pretrained(MODEL_ID, torch_dtype="auto") |
| 11 | +processor = AutoProcessor.from_pretrained(MODEL_ID) |
| 12 | + |
| 13 | +# Configure the quantization algorithm and scheme. |
| 14 | +# In this case, we: |
| 15 | +# * quantize the weights to fp8 with per channel via ptq |
| 16 | +# * quantize the activations to fp8 with dynamic per token |
| 17 | +recipe = QuantizationModifier( |
| 18 | + targets="Linear", |
| 19 | + scheme="FP8_DYNAMIC", |
| 20 | + ignore=["re:.*lm_head", "re:visual.*"], |
| 21 | +) |
| 22 | + |
| 23 | +# Apply quantization and save to disk in compressed-tensors format. |
| 24 | +oneshot(model=model, recipe=recipe) |
| 25 | + |
| 26 | +# Confirm generations of the quantized model look sane. |
| 27 | +print("========== SAMPLE GENERATION ==============") |
| 28 | +dispatch_for_generation(model) |
| 29 | +input_ids = processor(text="Hello my name is", return_tensors="pt").input_ids.to("cuda") |
| 30 | +output = model.generate(input_ids, max_new_tokens=20) |
| 31 | +print(processor.decode(output[0])) |
| 32 | +print("==========================================") |
| 33 | + |
| 34 | +# Save to disk in compressed-tensors format. |
| 35 | +SAVE_DIR = MODEL_ID.rstrip("/").split("/")[-1] + "-FP8-Dynamic" |
| 36 | +model.save_pretrained(SAVE_DIR, save_compressed=True) |
| 37 | +processor.save_pretrained(SAVE_DIR) |
0 commit comments