FILE README.md SHA256 1ab00abbeb10c1a50fc75493258e29c50cf57794afd59967951b74327841646c

1: # Modulated Diffusion: Accelerating Generative Modeling with Modulated Quantization
2: 
3: This repository provides the official implementation of our ICML 2025 paper, [Modulated Diffusion: Accelerating Generative Modeling with Modulated Quantization](https://icml.cc/virtual/2025/poster/43551), along with the pretrained checkpoints and the calibrated dataset used for Q-Diffusion. MoDiff is designed to be compatible with any post-training quantization (PTQ) method, enabling lower activation precision (up to 3 bits) without compromising generation quality. 
4: 
5: ![Example output on LSUN Church dataset](assets/example_church.png)
6: 
7: Our MoDiff scales to Stable Diffusion on text-guided image generation. Here is an example on COCO-MS-2014.
8: 
9: ![Example output on MS-COCO dataset](assets/example_coco.png)
10: 
11: ## Overview
12: Diffusion models have emerged as powerful generative models, but their high computation cost in iterative sampling remains a significant bottleneck. In this work, we present an in-depth and insightful study of state-of-the-art acceleration techniques for diffusion models, including caching and quantization, revealing their limitations in computation error and generation quality. To break these limits, this work introduces Modulated Diffusion (MoDiff), an innovative, rigorous, and principled framework that accelerates generative modeling through modulated quantization and error compensation. MoDiff not only inherents the advantages of existing caching and quantization methods but also serves as a general framework to accelerate all diffusion models. The advantages of MoDiff are supported by solid theoretical insight and analysis. In addition, extensive experiments on CIFAR-10 and LSUN demonstrate that MoDiff significant reduces activation quantization from 8 bits to 3 bits without performance degradation in post-training quantization (PTQ).
13: 
14: ![Method illustration](assets/modiff.png)
15: 
16: ## Usage
17: 
18: ### Installation
19: Clone the MoDiff repository and create a conda environment ` modiff ` with the following commands:
20: 
21: ```
22: git clone https://github.com/WeizhiGao/MoDiff.git
23: cd MoDiff
24: conda env create -f environment.yml
25: conda activate modiff
26: ```
27: 
28: If you encounter errors while installing the environment, please manually install the packages with compatible versions.
29: 
30: ### Pretrained Model Preparation
31: Before the quantization, you need to prepare the pre-trained models with the following instructions:
32: 
33: 1. Specify the model directory and move ` models ` directory there.
34: 
35: 2. For DDIM on CIFAR10, the pre-trained model will be automatically downloaded. You are able to change the saving path in the input args.
36: 
37: 3. For Latent Diffusion and Stable Diffusion experiments, we follow the checkpoints in [latent-diffusion](https://github.com/CompVis/latent-diffusion#model-zoo) and [stable-diffusion](https://github.com/CompVis/stable-diffusion#weights) . We use ` LDM-8 ` for LSUN-Churches, ` LDM-4 ` for LSUN-Bedrooms, and ` sd-v1-1.4 ` for MS-COCO. We provide a script for automatically downloading:
38:     ```
39:     cd <model_path>/models
40:     sh download.sh
41:     ```
42: 
43: 4. Our work targets the activation quantization, and you can use the quantized models weight for any quantization. You should download your quantized model weights to ` quant_models ` directory. We use the checkpoints in [Q-Diffusion](https://github.com/Xiuyu-Li/q-diffusion) and you can download those models from [Google Drive](https://drive.google.com/drive/folders/1ImRbmAvzCsU6AOaXbIeI7-4Gu2_Scc-X).
44: 
45: ### Calibration Dataset Generation
46: If you use dynamic quantization, you can skip this step. For some quantization methods, calibration dataset is required. We provide scipts to generate calibration dataset of CIFAR-10 and LSUN-Churches for MoDiff as follows:
47: 
48: ```
49: # CIFAR10
50: python scripts/sample_diffusion_ddim.py --config configs/cifar10.yml --use_pretrained --timesteps 100 --eta 0 --skip_type quad \
51:  --logdir <logdir> --generate residual --cali_n 256 --cali_st 20 --cali_data_path cali_data/cifar10.pt 
52: 
53: # LSUN-Churches
54: python scripts/sample_diffusion_ldm.py -r <path>/models/ldm/lsun_churches256/model.ckpt --batch_size 32 -c 400 -e 0.0 --seed 42 \
55:  -l <logdir> --generate residual --cali_n 256 --cali_st 20 --cali_data_path cali_data/church.pt 
56: ```
57: 
58: You can apply the script to other datasets. In practice, we only generate 256 data for each timestep, which cost several minutes on one H100 GPU. We also provide well-generated calibration data in [Hugging Face](https://huggingface.co/datasets/Weizhi98/MoDiff/tree/main/cali_data).
59: 
60: ### Post-Training Quantization
61: 1. For dynamic quantization, you do not need the calibration dataset. Reproduce the results of our paper with the following code. You can control the usage of modulated quantization by ` --modulate `, which can allow 3-bit activation as the limit:
62:     ```
63:     # CIFAR10
64:     python scripts/sample_diffusion_ddim.py --config configs/cifar10.yml --use_pretrained --timesteps 100 --eta 0 --skip_type quad --ptq \
65:      --weight_bit 4 --quant_act --act_bit 4 --a_sym --split --resume -l <logdir> --cali_ckpt $path/quant_models/cifar_w4a8_ckpt.pth \
66:      --modulate --quant_mode dynamic --max_images 50000
67: 
68:     # LSUN-Churches
69:     python scripts/sample_diffusion_ldm.py -r $path/models/ldm/lsun_churches256/model.ckpt --batch_size 8 -c 400 -e 0.0 --seed 41 --ptq \
70:      --weight_bit 4 --quant_act --act_bit 4 --resume -l <logdir> --cali_ckpt $path/quant_models/church_w4a8_ckpt.pth \
71:      --modulate --quant_mode dynamic -n 50000
72: 
73:     # LSUN-Bedrooms
74:     python scripts/sample_diffusion_ldm.py -r $path/models/ldm/lsun_beds256/model.ckpt --batch_size 8 -c 200 -e 0.0 --seed 41 --ptq \
75:      --weight_bit 4 --quant_act --act_bit 4 --resume -l <logdir> --cali_ckpt $path/quant_models/bedroom_w4a8_ckpt.pth \
76:      --modulate --quant_mode dynamic -n 50000
77: 
78:     # Text-Guided with Stable Diffusion
79:     python scripts/txt2img.py --prompt "a photograph of an astronaut riding a horse" --plms --cond --n_iter 1 --n_samples 5 --skip_grid --ptq \
80:      --weight_bit 8 --quant_act --act_bit 4 --no_grad_ckpt --split --running_stat --outdir <logdir> \
81:      --ckpt $path/models/stable-diffusion-v1/model.ckpt --resume --cali_ckpt $path/quantized_models/sd_w8a8_ckpt.pth \
82:      --modulate --quant_mode dynamic --act_tensor
83: 
84:     ```
85:     **Note:** You can enable the tensor-wise activation quantization with ` --act_tensor `. For complete text-guided generation results on Stable Diffusion, please download the annotation of [MSCOCO-2014](https://cocodataset.org/#download) and specify `--from-file` augments. You can also download the annotation from [Huggging Face](https://huggingface.co/datasets/Weizhi98/MoDiff/tree/main/annotation/MS-COCO).
86: 
87: 2. For Q-Diffusion, please first prepare the calibration dataset following the last step. We recommend to use the min-max initalization, which is both data-efficient and computation-efficient, resulting in comparable results compared to MSE calibration. You can use only 32 calibrated data for each time steps as follows:
88:     ```
89:     # CIFAR10
90:     python scripts/sample_diffusion_ddim.py --config configs/cifar10.yml --use_pretrained --timesteps 100 --eta 0 --skip_type quad --ptq \
91:      --weight_bit 4 --cali_st 20 --cali_batch_size 32 --cali_n 32 --quant_act --act_bit 4 --a_sym --split \
92:      --cali_data_path $path/cali_data/cifar10.pt -l <logdir> --cali_ckpt $path/quant_models/cifar_w4a8_ckpt.pth --resume_w \
93:      --modulate --quant_mode qdiff --cali_min_max --max_image 50000
94: 
95:     # LSUN-Churches
96:     python scripts/sample_diffusion_ldm.py -r $path/models/ldm/lsun_churches256/model.ckpt --batch_size 8 -c 400 -e 0.0 --seed 42 \
97:      --ptq --weight_bit 4 --cali_st 20 --cali_batch_size 32 --cali_n 32 --quant_act --act_bit 4 \
98:      --cali_data_path $path/cali_data/church.pt -l <logdir> --cali_ckpt $path/quantized_models/church_w4a8_ckpt.pth --resume_w \
99:      --modulate --quant_mode qdiff --cali_min_max -n 50000
100:     ```
101: 
102: 3. For MSE calibration of Q-Diffusion, you can reproduce with the following code:
103:     ```
104:     # CIFAR10
105:     python scripts/sample_diffusion_ddim.py --config configs/cifar10.yml --use_pretrained --timesteps 100 --eta 0 --skip_type quad --ptq \
106:      --weight_bit 4 --cali_st 20 --cali_batch_size 32 --cali_n 256 --quant_act --act_bit 4 --a_sym --split \
107:      --cali_data_path $path/cali_data/cifar10.pt  -l <logdir> --cali_ckpt $path/quant_models/cifar_w4a8_ckpt.pth --resume_w \
108:      --modulate --quant_mode qdiff --max_image 50000
109: 
110:     # LSUN-Churches
111:     python scripts/sample_diffusion_ldm.py -r $path/models/ldm/lsun_churches256/model.ckpt --batch_size 8 -c 400 -e 0.0 --seed 42 \
112:      --ptq --weight_bit 4 --cali_st 20 --cali_batch_size 32 --cali_n 256 --quant_act --act_bit 4 \
113:      --cali_data_path $path/cali_data/church.pt -l logdir> --cali_ckpt $path/quantized_models/church_w4a8_ckpt.pth --resume_w \
114:      --modulate --quant_mode qdiff -n 50000
115:     ```
116:     **Note:** You can tune the calibration learning rate and the outlier penalty with `--cali_lr` and `--out_penalty` for better generation quality.
117: 
118: ### Image Generation
119: You can generate images from the quantized checkpoints. For dynamic quantization, please refer the [Dynamic Quantization](#post-training-quantization). For Q-Diffusion checkpoints, use the following commands to generate images:
120: ```
121: # CIFAR10
122: python scripts/sample_diffusion_ddim.py --config configs/cifar10.yml --use_pretrained --timesteps 100 --eta 0 --skip_type quad --ptq \
123:  --weight_bit 8 --quant_act --act_bit 4 --a_sym --split --resume -l <logdir> --cali_ckpt <ckpt_dir> \
124:  --modulate --quant_mode qdiff --max_images 50000
125: 
126: # LSUN-Churches
127: python scripts/sample_diffusion_ldm.py -r $path/models/ldm/lsun_churches256/model.ckpt --batch_size 64 -c 400 -e 0.0 --seed 41 \
128:  --ptq --weight_bit 4 --quant_act --act_bit 4 --resume -l <logdir> --cali_ckpt <ckpt_dir> \
129:  --modulate --quant_mode qdiff -n 50000 
130: ```
131: 
132: ### Evaluation
133: For the evaluation of IS, FID, sFID, we follow [torch-fidelity](https://github.com/toshas/torch-fidelity) and [guided-diffusion](https://github.com/openai/guided-diffusion). We generate 50,000 images for CIFAR-10 and LSUN datasets. 
134: 
135: 1. Evaluate IS and FID scores with torch-fidelity. Before evlautaion, you need to download the reference datasets. The cifar-10 reference data will be downladed automatically, and you can obtain the LSUN datasets [here](https://github.com/fyu/lsun). Then run the following command to gain the IS score and FID score:
136:     
137:     ```
138:     # CIFAR10
139:     fidelity --gpu 0 --isc --fid --input1 <generated_image_path> --input2 cifar10-train
140: 
141:     # LSUN
142:     fidelity --gpu 0 --fid --input1 <generated_image_path> --input2 <reference_image_path>
143:     ```
144: 2. Evaluate FID and sFID scores with guided-diffusion. Please follow the [requirements](https://github.com/openai/guided-diffusion/blob/main/evaluations/requirements.txt) to install a TensorFlow-based environment. After installing the environment, you need to compress your reference dataset as `.npz` files. We provided the files of CIFAR10 and LSUN datasets in [Hugging Face](https://huggingface.co/datasets/Weizhi98/MoDiff/tree/main/reference_data). For LSUN generation, it defaultly saves the '.npz' files. For the generated'.npz' file of CIFAR-10, you can collect it during sampling or post process the generated '.png' files. Then run the following command to gain the IS score and FID score:
145:     ```
146:     python scripts/evaluate.py <reference_npz_file> <generated_npz_file>
147:     ```
148: 
149: ## Citation
150: If you find this work helpful in your usage, please consider citing our paper:
151: ```
152: @inproceedings{gaomodulated,
153:   title={Modulated Diffusion: Accelerating Generative Modeling with Modulated Quantization},
154:   author={Gao, Weizhi and Hou, Zhichao and Yin, Junqi and Wang, Feiyi and Peng, Linyu and Liu, Xiaorui},
155:   booktitle={Forty-second International Conference on Machine Learning},
156:   month={June},
157:   year={2025}
158: }
159: ```
160: 
161: ## Acknowledgements
162: We appreciate the availability of well-maintained public codebases. Our diffusion model code is developed based on [q-diffusion](https://github.com/Xiuyu-Li/q-diffusion), [ddim](https://github.com/ermongroup/ddim), [latent-diffusion](https://github.com/CompVis/latent-diffusion), and [stable-diffusion](https://github.com/CompVis/latent-diffusion). If you find any bugs in this repo, feel free to contact my through email or put them in [Issues](https://github.com/WeizhiGao/MoDiff/issues).
163: 
164: We thank [DeepSpeed](https://github.com/microsoft/DeepSpeed) for model sizes and BOPS measurements, [torch-fidelity](https://github.com/toshas/torch-fidelity) and [guided-diffusion](https://github.com/openai/guided-diffusion) for IS, FID and sFID evaluation, and [LSUN]((https://github.com/fyu/lsun)) for providing datasets. 

FILE qdiff/quant_layer.py SHA256 7932051590924dabc9c19eb01e19490c3141224ae00cf14dac03a40ca5a19c9a

1: import logging
2: import warnings
3: import torch
4: import torch.nn as nn
5: import torch.nn.functional as F
6: from typing import Union
7: 
8: logger = logging.getLogger(__name__)
9: 
10: 
11: class StraightThrough(nn.Module):
12:     def __init__(self, channel_num: int = 1):
13:         super().__init__()
14: 
15:     def forward(self, input):
16:         return input
17: 
18: 
19: def round_ste(x: torch.Tensor):
20:     """
21:     Implement Straight-Through Estimator for rounding operation.
22:     """
23:     return (x.round() - x).detach() + x
24: 
25: 
26: def lp_loss(pred, tgt, p=2.0, reduction='none'):
27:     """
28:     loss function measured in L_p Norm
29:     """
30:     if reduction == 'none':
31:         return (pred-tgt).abs().pow(p).sum(1).mean()
32:     else:
33:         return (pred-tgt).abs().pow(p).mean()
34: 
35: 
36: class UniformAffineQuantizer(nn.Module):
37:     """
38:     PyTorch Function that can be used for asymmetric quantization (also called uniform affine
39:     quantization). Quantizes its argument in the forward pass, passes the gradient 'straight
40:     through' on the backward pass, ignoring the quantization that occurred.
41:     Based on https://arxiv.org/abs/1806.08342.
42: 
43:     :param n_bits: number of bit for quantization
44:     :param symmetric: if True, the zero_point should always be 0
45:     :param channel_wise: if True, compute scale and zero_point in each channel
46:     :param scale_method: determines the quantization scale and zero point
47:     """
48:     def __init__(self, n_bits: int = 8, symmetric: bool = False, channel_wise: bool = False, scale_method: str = 'max',
49:                  leaf_param: bool = False, always_zero: bool = False, dynamic: bool = False):
50:         super(UniformAffineQuantizer, self).__init__()
51:         self.sym = symmetric
52:         # assert 2 <= n_bits <= 8, 'bitwidth not supported'
53:         self.n_bits = n_bits
54:         self.n_levels = 2 ** self.n_bits if not self.sym else 2 ** (self.n_bits - 1) - 1
55:         self.delta = None
56:         self.zero_point = None
57:         self.inited = False
58:         self.leaf_param = leaf_param
59:         self.channel_wise = channel_wise
60:         self.scale_method = scale_method
61:         self.running_stat = False
62:         self.always_zero = always_zero
63:         if self.leaf_param:
64:             self.x_min, self.x_max = None, None
65:         self.dynamic = dynamic
66: 
67:         # self.print_info = False
68:         # self.count = 0
69: 
70:     def forward(self, x: torch.Tensor):
71: 
72:         if self.inited is False:
73:             if self.leaf_param:
74:                 delta, self.zero_point = self.init_quantization_scale(x, self.channel_wise)
75:                 self.delta = torch.nn.Parameter(delta)
76:                 # self.zero_point = torch.nn.Parameter(self.zero_point)
77:             else:
78:                 self.delta, self.zero_point = self.init_quantization_scale(x, self.channel_wise)
79:             self.inited = True
80: 
81:         if self.dynamic and (self.inited is True):
82:             delta, zero_point = self.init_quantization_scale(x, self.channel_wise)
83:             self.delta = torch.nn.Parameter(delta)
84:             if isinstance(self.zero_point, torch.nn.Parameter):
85:                 self.zero_point = torch.nn.Parameter(zero_point)
86:             else:
87:                 self.zero_point = zero_point
88: 
89:         if self.running_stat:
90:             self.act_momentum_update(x)

134:     def init_quantization_scale(self, x: torch.Tensor, channel_wise: bool = False):
135:         delta, zero_point = None, None
136:         if channel_wise:
137:             if self.scale_method == 'mse:':
138:                 x_clone = x.clone().detach()
139:                 n_channels = x_clone.shape[0]
140:                 if len(x.shape) == 4:
141:                     x_max = x_clone.abs().max(dim=-1)[0].max(dim=-1)[0].max(dim=-1)[0]
142:                 elif len(x.shape) == 3:
143:                     x_max = x_clone.abs().max(dim=-1)[0].max(dim=-1)[0]
144:                 else:
145:                     x_max = x_clone.abs().max(dim=-1)[0]
146:                 delta = x_max.clone()
147:                 zero_point = x_max.clone()
148:                 # determine the scale and zero point channel-by-channel
149:                 for c in range(n_channels):
150:                     delta[c], zero_point[c] = self.init_quantization_scale(x_clone[c], channel_wise=False)
151:                 if len(x.shape) == 4:
152:                     delta = delta.view(-1, 1, 1, 1)
153:                     zero_point = zero_point.view(-1, 1, 1, 1)
154:                 elif len(x.shape) == 3:
155:                     delta = delta.view(-1, 1, 1)
156:                     zero_point = zero_point.view(-1, 1, 1)
157:                 else:
158:                     delta = delta.view(-1, 1)
159:                     zero_point = zero_point.view(-1, 1)
160:             else:
161:                 # For dynamic activation quantization which is more efficient compared with loops
162:                 x_clone = x.clone().detach()
163:                 n_channels = x_clone.shape[0]
164:                 if len(x.shape) == 4:
165:                     x_max = x_clone.max(dim=-1)[0].max(dim=-1)[0].max(dim=-1)[0]
166:                     x_min = x_clone.min(dim=-1)[0].min(dim=-1)[0].min(dim=-1)[0]
167:                 elif len(x.shape) == 3:
168:                     x_max = x_clone.max(dim=-1)[0].max(dim=-1)[0]
169:                     x_min = x_clone.min(dim=-1)[0].min(dim=-1)[0]
170:                 else:
171:                     x_max = x_clone.max(dim=-1)[0]
172:                     x_min = x_clone.min(dim=-1)[0]
173:                 delta = x_max.clone()
174:                 zero_point = x_max.clone()
175:                 x_absmax = torch.maximum((x_min).abs(), x_max)
176:                 if self.sym:
177:                     delta = x_absmax / self.n_levels
178:                 else:
179:                     delta = (x_max - x_min) / (self.n_levels - 1)
180:                 delta[delta<1e-8]=1e-8
181:                 zero_point = (-x_min / delta).round() if not (self.sym or self.always_zero) else torch.zeros_like(delta)
182:                 if len(x.shape) == 4:
183:                     delta = delta.view(-1, 1, 1, 1)
184:                     zero_point = zero_point.view(-1, 1, 1, 1)
185:                 elif len(x.shape) == 3:
186:                     delta = delta.view(-1, 1, 1)
187:                     zero_point = zero_point.view(-1, 1, 1)
188:                 else:
189:                     delta = delta.view(-1, 1)
190:                     zero_point = zero_point.view(-1, 1)
191:         else:
192:             if self.leaf_param:
193:                 self.x_min = x.data.min()
194:                 self.x_max = x.data.max()
195: 
196:             if 'max' in self.scale_method:
197:                 x_min = min(x.min().item(), 0)
198:                 x_max = max(x.max().item(), 0)
199:                 if 'scale' in self.scale_method:
200:                     x_min = x_min * (self.n_bits + 2) / 8
201:                     x_max = x_max * (self.n_bits + 2) / 8
202: 
203:                 x_absmax = max(abs(x_min), x_max)
204:                 if self.sym:
205:                     # x_min, x_max = -x_absmax if x_min < 0 else 0, x_absmax
206:                     delta = x_absmax / self.n_levels
207:                 else:
208:                     delta = float(x.max().item() - x.min().item()) / (self.n_levels - 1)
209:                 if delta < 1e-8:
210:                     # warnings.warn('Quantization range close to zero: [{}, {}]'.format(x_min, x_max))
211:                     delta = 1e-8

290:         self.act_quant_mode = act_quant_mode
291:         self.disable_act_quant = disable_act_quant
292:         # initialize quantizer
293:         self.weight_quantizer = UniformAffineQuantizer(**self.weight_quant_params)
294:         self.act_quantizer = UniformAffineQuantizer(**self.act_quant_params)
295:         self.split = 0
296: 
297:         self.activation_function = StraightThrough()
298:         self.ignore_reconstruction = False
299: 
300:         self.extra_repr = org_module.extra_repr
301: 
302:         # Store intermediate states
303:         self.modulate = modulate
304:         self.a_hat = None
305:         self.o_hat = None
306: 
307:     def forward(self, input: torch.Tensor, split: int = 0):
308:         if split != 0 and self.split != 0:
309:             assert(split == self.split)
310:         elif split != 0:
311:             logger.info(f"split at {split}!")
312:             self.split = split
313:             self.set_split()
314: 
315:         if not self.disable_act_quant and self.use_act_quant:
316:             if self.a_hat == None:
317:                 assert(self.o_hat, None)
318: 
319:             if self.modulate:
320:                 if self.a_hat is None:
321:                     self.a_hat = input.clone().detach()
322:                     # if self.split != 0:
323:                     #     input_0 = self.act_quantizer(input[:, :self.split, :, :])
324:                     #     input_1 = self.act_quantizer_0(input[:, self.split:, :, :])
325:                     #     input = torch.cat([input_0, input_1], dim=1)
326:                     # else:
327:                     #     input = self.act_quantizer(input)
328:                     # self.a_hat = input.clone().detach()
329:                 else:
330:                     input = input - self.a_hat
331:                     if self.split != 0:
332:                         input_0 = self.act_quantizer(input[:, :self.split, :, :])
333:                         input_1 = self.act_quantizer_0(input[:, self.split:, :, :])
334:                         input = torch.cat([input_0, input_1], dim=1)
335:                     else:
336:                         # if self.act_quantizer.delta is not None:
337:                         #     print("uniform", (input.max()-input.min()).item()/15)
338:                         #     print("delta", self.act_quantizer.delta.item())
339:                         input = self.act_quantizer(input)
340:                     self.a_hat = (self.a_hat + input).clone().detach()
341:             else:
342:                 if self.split != 0:
343:                     input_0 = self.act_quantizer(input[:, :self.split, :, :])
344:                     input_1 = self.act_quantizer_0(input[:, self.split:, :, :])
345:                     input = torch.cat([input_0, input_1], dim=1)
346:                 else:
347:                     input = self.act_quantizer(input)
348:         if self.use_weight_quant:
349:             if self.split != 0:
350:                 weight_0 = self.weight_quantizer(self.weight[:, :self.split, ...])
351:                 weight_1 = self.weight_quantizer_0(self.weight[:, self.split:, ...])
352:                 weight = torch.cat([weight_0, weight_1], dim=1)
353:             else:
354:                 weight = self.weight_quantizer(self.weight)
355:             bias = self.bias
356:         else:
357:             weight = self.org_weight
358:             bias = self.org_bias
359:         
360:         if self.modulate and self.use_act_quant:

FILE qdiff/quant_model.py SHA256 d4edeaf905aeaec246a75bfbd9a9345b90a33e2de1b9446a888ea59764ea889f

20:         if hasattr(model, 'image_size'):
21:             self.image_size = model.image_size
22:         self.specials = get_specials(act_quant_params['leaf_param'])
23:         self.quant_module_refactor(self.model, weight_quant_params, act_quant_params)
24:         self.quant_block_refactor(self.model, weight_quant_params, act_quant_params)
25: 
26:     def quant_module_refactor(self, module: nn.Module, weight_quant_params: dict = {}, act_quant_params: dict = {}):
27:         """
28:         Recursively replace the normal layers (conv2D, conv1D, Linear etc.) to QuantModule
29:         :param module: nn.Module with nn.Conv2d, nn.Conv1d, or nn.Linear in its children
30:         :param weight_quant_params: quantization parameters like n_bits for weight quantizer
31:         :param act_quant_params: quantization parameters like n_bits for activation quantizer
32:         """
33:         prev_quantmodule = None
34:         for name, child_module in module.named_children():
35:             if isinstance(child_module, (nn.Conv2d, nn.Conv1d, nn.Linear)): # nn.Conv1d
36:                 setattr(module, name, QuantModule(
37:                     child_module, weight_quant_params, act_quant_params, modulate=self.modulate))
38:                 prev_quantmodule = getattr(module, name)
39: 
40:             elif isinstance(child_module, StraightThrough):
41:                 continue
42: 
43:             else:
44:                 self.quant_module_refactor(child_module, weight_quant_params, act_quant_params)
45: 
46:     def quant_block_refactor(self, module: nn.Module, weight_quant_params: dict = {}, act_quant_params: dict = {}):
47:         for name, child_module in module.named_children():
48:             if type(child_module) in self.specials:
49:                 if self.specials[type(child_module)] in [QuantBasicTransformerBlock, QuantAttnBlock]:
50:                     setattr(module, name, self.specials[type(child_module)](child_module,
51:                         act_quant_params, sm_abit=self.sm_abit))
52:                 elif self.specials[type(child_module)] == QuantSMVMatMul:

FILE scripts/sample_diffusion_ddim.py SHA256 81109f38d4af5498360e072eb694280df86e9b9543a1f49a7a8e4587ea04b0d3

136:                 generated_data = {"xs":xs, "ts":ts}
137:             else:
138:                 raise ValueError
139:             torch.save(generated_data, self.args.cali_data_path)
140:             exit()
141: 
142:         if self.args.ptq:
143:             wq_params = {'n_bits': args.weight_bit, 'channel_wise': True, 'scale_method': 'max'}
144:             aq_params = {
145:                 'n_bits': args.act_bit, 'symmetric': args.a_sym, 'channel_wise': args.act_tensor, 'scale_method': 'max', 
146:                 'leaf_param': args.quant_act, 'dynamic': (args.quant_mode=="dynamic")}
147:             if self.args.resume:
148:                 logger.info('Load with min-max quick initialization')
149:                 wq_params['scale_method'] = 'max'
150:                 aq_params['scale_method'] = 'max'
151:             if self.args.resume_w:
152:                 wq_params['scale_method'] = 'max'
153:             qnn = QuantModel(
154:                 model=model, weight_quant_params=wq_params, act_quant_params=aq_params, 
155:                 sm_abit=self.args.sm_abit, modulate=self.args.modulate)

610:     parser.add_argument("--split", action="store_true",
611:         help="split shortcut connection into two parts"
612:     )
613:     parser.add_argument(
614:         "--verbose", action="store_true",
615:         help="print out info like quantized model arch"
616:     )
617: 
618:     # MoDiff parameters
619:     parser.add_argument("--modulate", action="store_true", help="if apply modulated computing")
620:     parser.add_argument("--act_tensor", action="store_true", help="use tensor-wise activation quantization")
621:     parser.add_argument("--out_penalty", type=float, default=0.0, help="penalty for outliers in calibration")
622:     parser.add_argument("--cali_min_max", action="store_true", help="use min-max of calibration datasets to init scaling")
623:     parser.add_argument("--generate", type=str, default=None, choices=[None, "raw", "residual"], help="generate calibration data")
624: 
625:     return parser
626: 
627: 

FILE scripts/sample_diffusion_ldm.py SHA256 96d6a89a24c66d6f30e47559a0c05098429c4cd8febac4ad3c24e9443ce0a21b

411:         "--dpm", action="store_true",
412:         help="use dpm solver for sampling"
413:     )
414:     parser.add_argument(
415:         "--verbose", action="store_true",
416:         help="print out info like quantized model arch"
417:     )
418: 
419:     # MoDiff parameters
420:     parser.add_argument("--modulate", action="store_true", help="if apply modulated computing")
421:     parser.add_argument("--act_tensor", action="store_true", help="use tensor-wise activation quantization")
422:     parser.add_argument("--out_penalty", type=float, default=0.0, help="penalty for outliers in calibration")
423:     parser.add_argument("--cali_min_max", action="store_true", help="use min-max of calibration datasets to init scaling")
424:     parser.add_argument("--generate", type=str, default=None, choices=[None, "raw", "residual"], help="generate calibration data")
425: 
426:     return parser

544:         exit()
545: 
546:     assert(not opt.cond)
547:     if opt.ptq:
548:         a_scale_method = 'mse' if not opt.a_min_max else 'max'
549:         wq_params = {'n_bits': opt.weight_bit, 'channel_wise': True, 'scale_method': 'mse'}
550:         aq_params = {
551:             'n_bits': opt.act_bit, 'symmetric': opt.a_sym, 'channel_wise': opt.act_tensor, 
552:             'scale_method': a_scale_method, 'leaf_param': opt.quant_act, 'dynamic': (opt.quant_mode=="dynamic")
553:         }
554:         if opt.resume:
555:             logger.info('Load with min-max quick initialization')
556:             wq_params['scale_method'] = 'max'
557:             aq_params['scale_method'] = 'max'
558:         if opt.resume_w:
559:             wq_params['scale_method'] = 'max'
560:         # with model.ema_scope("Quantizing", restore=False):
561:         qnn = QuantModel(
562:             model=model.model.diffusion_model, weight_quant_params=wq_params, act_quant_params=aq_params,
563:             sm_abit=opt.sm_abit, modulate=opt.modulate)
564:         qnn.cuda()
565:         qnn.eval()

PAPER CHANNEL/TENSOR-WISE KEYWORD CONTEXT; lines are layout extraction, not page numbers

540: precisions, demonstrating its ability to significantly reduce           measurements (Sajjadi et al., 2018) in Appendix C.3.
541: activation bit requirements compared to existing methods
542:                                                                         Quantization Methods. We use dynamic channel-wise
543: across multiple datasets. Additionally, we conduct com-
544:                                                                         quantization and Q-Diffusion as the base quantization meth-

546:                                                                         ods and apply MoDiff to both (Dettmers et al., 2022; Li et al.,
547: generated images to assess the effectiveness of MoDiff.
548:                                                                         2023). We also present results using dynamic tensor-wise
549:                                                                         quantization in Appendix D.2. Additionally, we include re-
550: 5.1. Experiment Settings                                                sults with full-precision activation (32 bits), for comparison.

551: Datasets, Models, and Evaluation. We majorly evaluate                   For weight quantization, we adopt the MSE reconstruction
552: the effectiveness of our MoDiff on the CIFAR-10 (32 × 32),              method, following the Q-Diffusion checkpoints. For ac-
553: LSUN-Bedrooms (256 × 256), and LSUN-Church-Outdoor                      tivation quantization, dynamic channel-wise quantization
554: (256 × 256) datasets (Krizhevsky et al., 2009; Yu et al.,               determines the scaling factor based on the channel-wise
555: 2015). For CIFAR-10, we use DDIM models with 100 de-                    min-max range of the input. Due to its dynamic nature,

552: the effectiveness of our MoDiff on the CIFAR-10 (32 × 32),              method, following the Q-Diffusion checkpoints. For ac-
553: LSUN-Bedrooms (256 × 256), and LSUN-Church-Outdoor                      tivation quantization, dynamic channel-wise quantization
554: (256 × 256) datasets (Krizhevsky et al., 2009; Yu et al.,               determines the scaling factor based on the channel-wise
555: 2015). For CIFAR-10, we use DDIM models with 100 de-                    min-max range of the input. Due to its dynamic nature,
556: noising steps (Song et al., 2021a). For the LSUN datasets,              we directly apply MoDiff to this method. In contrast, Q-

605: “W/A”, where “W” represents the weight precision and “A”              datasets and various quantization methods. For both Q-Diff
606: represents the activation precision. We refer to Q-Diffusion          and LCQ, our approach consistently improves their perfor-
607: and dynamic channel-wise quantization as LCQ and Q-Diff,              mance. However, we observe that quantizing activations to
608: respectively. Our implementations based on them are de-               extremely low-bit precision becomes increasingly challeng-
609: noted as LCQ+MoDiff and Q-Diff+MoDiff. We denote                      ing for higher-resolution datasets, even with our method. As

1028: Baselines. For the implementation of baselines, we follow the existing codebase. Specifically, we conduct Q-Diffusion
1029: experiments by directly using their provided code (Li et al., 2023). We also utilize the calibration datasets they provide
1030: to quantize the models at different bit levels. For LCQ, we follow the BRECQ framework and adopt channel-wise
1031: quantization (Li et al., 2021).
1032: MoDiff. For our MoDiff implementation, we incorporate several key techniques:

1050: C.1. Results on Stable Diffusion
1051: To demonstrate that our method generalizes to larger-scale datasets and higher resolutions, we conduct experiments on
1052: MS-COCO 2014 (Lin et al., 2014) using Stable Diffusion v1.4 with DPM solvers(Lu et al., 2022). We apply tensor-wise
1053: dynamic quantization and evaluate the quantized models within the Q-Diffusion framework. A total of 30,000 images are
1054: generated using 50 sampling steps. As shown in Table 7, the resulting FID scores confirm that MoDiff consistently performs

1073: To evaluate the generalizability of MoDiff across different architectures, we conduct experiments on the Diffusion Trans-
1074: former (Peebles & Xie, 2023). Following PTQ4DiT (Wu et al., 2024), we use DiT-XL/2 as the baseline model. The
1075: experiments are performed on the ImageNet 256×256 dataset (Russakovsky et al., 2015) using tensor-wise dynamic quan-
1076: tization. We generate 10,000 images using 50 sampling steps for evaluation. As shown in Table 8, MoDiff consistently
1077: enhances generation quality under low activation bit widths.

1213: 
1214: D.2. Results on Tensor-Wise Quantization
1215: In our main experiments, we present results using dynamic channel-wise quantization (LCQ). In this section, we extend
1216: our analysis to dynamic tensor-wise quantization (LTQ), which is more hardware-friendly. We conduct experiments on
1217: CIFAR-10 using DDIM, while continuing to use Q-Diffusion checkpoints for weight quantization. As shown in Table 14, our

1214: D.2. Results on Tensor-Wise Quantization
1215: In our main experiments, we present results using dynamic channel-wise quantization (LCQ). In this section, we extend
1216: our analysis to dynamic tensor-wise quantization (LTQ), which is more hardware-friendly. We conduct experiments on
1217: CIFAR-10 using DDIM, while continuing to use Q-Diffusion checkpoints for weight quantization. As shown in Table 14, our
1218: MoDiff framework is also effective for LTQ. However, the minimum activation bit-width achievable with LTQ is higher than

1217: CIFAR-10 using DDIM, while continuing to use Q-Diffusion checkpoints for weight quantization. As shown in Table 14, our
1218: MoDiff framework is also effective for LTQ. However, the minimum activation bit-width achievable with LTQ is higher than
1219: that of LCQ. This is because tensor-wise quantization operates on higher-dimensional data, making accurate quantization
1220: more challenging.
1221: 

1222: D.3. Results on More Samplers
1223: In the main paper, we demonstrate that MoDiff generalizes to the DDPM sampler. Here, we further show its applicability
1224: to additional solvers. Specifically, we perform tensor-wise dynamic quantization using DPM-Solver-2 (Lu et al., 2022)
1225: on CIFAR-10 with 20 sampling steps. Additionally, we evaluate MoDiff with the PLMS solver using 50 steps on Stable
1226: Diffusion with the MS-COCO 2014 dataset (Liu et al., 2022). As shown in Table 15 and Table 7, MoDiff consistently

1229: 
1230:                     Modulated Diffusion: Accelerating Generative Modeling with Modulated Quantization
1231: Table 14. The IS, FID, sFID, and GBOPs for CIFAR-10 with DDIM using tensor-wise quantization under different precisions. The best
1232: performance is bolded.
1233:         Methods                 Bits (W/A)      IS ↑   FID ↓     sFID ↓       Bits (W/A)   IS ↑    FID ↓      sFID ↓