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