Views
No views yet
1# Python 3.10.x or above
2pip3 install -v "gptqmodel>=2.2.0" --no-build-isolation
31python3 gptqmodel_quantize.py /path/to/Qwen2.5-VL-7B-Instruct/ /path/to/Qwen2.5-VL-7B-Instruct-gptqmodel-int8 8
21# gptqmodel_quantize.py
2
3import fire
4from datasets import load_dataset
5
6from gptqmodel import GPTQModel, QuantizeConfig
7from gptqmodel.models.definitions.base_qwen2_vl import BaseQwen2VLGPTQ
8
9os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
10os.environ["PYTORCH_CUDA_ALLOC_CONF"] = "expandable_segments:True"
11os.environ["PYTHONUTF8"]="1"
12
13def format_qwen2_vl_dataset(image, assistant):
14 return [
15 {
16 "role": "user",
17 "content": [
18 {"type": "image", "image": image},
19 {"type": "text", "text": "generate a caption for this image"},
20 ],
21 },
22 {"role": "assistant", "content": assistant},
23 ]
24
25
26def prepare_dataset(format_func, n_sample: int = 20) -> list[list[dict]]:
27 from datasets import load_dataset
28
29 dataset = load_dataset(
30 "laion/220k-GPT4Vision-captions-from-LIVIS", split=f"train[:{n_sample}]"
31 )
32 return [
33 format_func(sample["url"], sample["caption"])
34 for sample in dataset
35 ]
36
37
38def get_calib_dataset(model):
39 if isinstance(model, BaseQwen2VLGPTQ):
40 return prepare_dataset(format_qwen2_vl_dataset, n_sample=256)
41 raise NotImplementedError(f"Unsupported MODEL: {model.__class__}")
42
43
44def quantize(model_path: str,
45 output_path: str,
46 bit: int):
47 quant_config = QuantizeConfig(bits=bit, group_size=128)
48
49 model = GPTQModel.load(model_path, quant_config)
50 calibration_dataset = get_calib_dataset(model)
51
52 # increase `batch_size` to match gpu/vram specs to speed up quantization
53 model.quantize(calibration_dataset, batch_size=8)
54
55 model.save(output_path)
56
57 # test post-quant inference
58 model = GPTQModel.load(output_path)
59 result = model.generate("Uncovering deep insights begins with")[0] # tokens
60 print(model.tokenizer.decode(result)) # string output
61
62
63if __name__ == "__main__":
64 fire.Fire(quantize)
65