HelloSun commited on
Commit
91b306a
·
verified ·
1 Parent(s): 2dd5fb1

Add quantize_int4.py

Browse files
Files changed (1) hide show
  1. quantize_int4.py +79 -0
quantize_int4.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """NNCF weight-only INT4 quantization of the OpenVINO FP16 SDXL pipeline.
2
+
3
+ unet (the transformer) + text_encoder -> weight-only INT4 (asymmetric, group 128)
4
+ all remaining components -> default weight-only INT8
5
+
6
+ Usage:
7
+ python quantize_int4.py \
8
+ --model_path /home/user/app/juggernaut-xi-v11-ov-fp16 \
9
+ --output_path /home/user/app/juggernaut-xi-v11-ov-int4
10
+ """
11
+
12
+ import argparse
13
+ import shutil
14
+ import time
15
+ from pathlib import Path
16
+
17
+ from optimum.intel import OVConfig, OVDiffusionPipeline, OVQuantizer
18
+ from optimum.intel.openvino import (
19
+ OVPipelineQuantizationConfig,
20
+ OVWeightQuantizationConfig,
21
+ )
22
+
23
+
24
+ def main() -> None:
25
+ parser = argparse.ArgumentParser()
26
+ parser.add_argument(
27
+ "--model_path",
28
+ type=str,
29
+ default="/home/user/app/juggernaut-xi-v11-ov-fp16",
30
+ help="OpenVINO FP16 pipeline exported with optimum-cli",
31
+ )
32
+ parser.add_argument(
33
+ "--output_path",
34
+ type=str,
35
+ default="/home/user/app/juggernaut-xi-v11-ov-int4",
36
+ help="Destination folder for the INT4 pipeline",
37
+ )
38
+ args = parser.parse_args()
39
+
40
+ model_path = Path(args.model_path)
41
+ output_path = Path(args.output_path)
42
+ if output_path.exists():
43
+ shutil.rmtree(output_path)
44
+ output_path.mkdir(parents=True, exist_ok=True)
45
+
46
+ int4 = dict(
47
+ bits=4,
48
+ sym=False,
49
+ group_size=128,
50
+ group_size_fallback="adjust",
51
+ ratio=1.0,
52
+ )
53
+ quantization_configs = {
54
+ # in an OVDiffusionPipeline the UNet is the transformer component
55
+ "unet": OVWeightQuantizationConfig(**int4),
56
+ "text_encoder": OVWeightQuantizationConfig(**int4),
57
+ }
58
+ default_config = OVWeightQuantizationConfig(bits=8)
59
+
60
+ quantization_config = OVPipelineQuantizationConfig(
61
+ quantization_configs=quantization_configs,
62
+ default_config=default_config,
63
+ )
64
+ ov_config = OVConfig(quantization_config=quantization_config)
65
+
66
+ print(f"loading FP16 pipeline from {model_path} ...", flush=True)
67
+ t0 = time.perf_counter()
68
+ model = OVDiffusionPipeline.from_pretrained(str(model_path), device="CPU")
69
+ print(f"loaded in {time.perf_counter() - t0:.1f}s", flush=True)
70
+
71
+ quantizer = OVQuantizer(model=model)
72
+ t0 = time.perf_counter()
73
+ quantizer.quantize(ov_config=ov_config, save_directory=str(output_path))
74
+ print(f"quantization took {time.perf_counter() - t0:.1f}s", flush=True)
75
+ print(f"INT4 pipeline saved to {output_path}")
76
+
77
+
78
+ if __name__ == "__main__":
79
+ main()