Skip to content

PTQ-Level Efficiency, QAT-Level Accuracy | 训练后量化的效率,量化感知训练的精度

enhancement of code and readme

wenhuach21b0c169a13383
diff --git a/README.md b/README.md
index bac07de97..3b73b5331 100644
--- a/README.md
+++ b/README.md
@@ -31,8 +31,50 @@ Install the necessary dependencies with the following command:
```bash
pip install -r requirements.txt
```
+## Uasage
+```python
+from auto_round import AutoRound
+model_name = "facebook/opt-125m"
+
+model = AutoModelForCausalLM.from_pretrained(
+ model_name, low_cpu_mem_usage=True, torch_dtype="auto", trust_remote_code=True
+ )
+tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
+autoround = round(model, tokenizer, num_bits=4, group_size=128, scheme="asym")
+fake_qdq_model = autoround.quantize()
+
+## export to gpu
+# packed_folder = "./tmp_autoround_packed"
+# autoround.export_to_autogptq("packed_folder")
-## Usage
+```
+### Detailed Hyperparameters
+- `model`: The PyTorch model to be quantized.
+- `tokenizer`: An optional tokenizer for processing input data. If none is provided, a dataloader must be supplied.
+- `bits (int)`: Number of bits for quantization (default is 4).
+- `group_size (int)`: Size of the quantization group (default is 128).
+- `scheme (str)`: The quantization scheme (symmetric/asymmetric) to be used (default is "asymmetric").
+- `use_quant_input (bool)`: Whether to use the output of the previous quantized block as the input for the current block (default is True).
+- `enable_minmax_tuning (bool)`: Whether to enable weight min-max tuning (default is True).
+- `iters (int)`: Number of tuning iterations (default is 200).
+- `lr (float)`: The learning rate for rounding value (default is 0.005).
+- `minmax_lr (float)`: The learning rate for min-max tuning (default is None).
+- `n_samples (int)`: Number of samples for tuning (default is 512).
+- `seqlen (int)`: Data length of the sequence for tuning.
+- `bs (int)`: Batch size for training (default is 8).
+- `amp (bool)`: Whether to use automatic mixed precision (default is True).
+- `n_blocks (int)`: Packing several blocks as one for tuning together (default is 1).
+- `gradient_accumulate_steps (int)`: Number of gradient accumulation steps (default is 1).
+- `low_gpu_mem_usage (bool)`: Whether to save GPU memory at the cost of a little tuning time (default is True).
+- `dataset_name (str)`: The default dataset name for tuning (default is "NeelNanda/pile-10k").
+- `dataset_split (str)`: The split of the dataset to be used for tuning (default is "train").
+- `dataloader`: The dataloader for tuning data.
+- `weight_config (dict)`: Configuration for weight quantization (default is an empty dictionary), mainly for mixed bits or mixed precision.
+- `device`: The device to be used for tuning (default is "cuda:0").
+
+
+
+### Examples
cd to examples folder, install lm-eval to run the evaluation
```bash
pip install -r requirements.txt
@@ -40,18 +82,18 @@ pip install -r requirements.txt
- **Default Settings:**
```bash
-CUDA_VISIBLE_DEVICES=0 python3 main.py --model_name facebook/opt-125m --amp --num_bits 4 --group_size -1 --enable_minmax_tuning --use_quant_input
+CUDA_VISIBLE_DEVICES=0 python3 main.py --model_name facebook/opt-125m --amp --bits 4 --group_size -1 --enable_minmax_tuning --use_quant_input
```
- **Reduced GPU Memory Usage and Adjusted Training Batch Size:**
```bash
-CUDA_VISIBLE_DEVICES=0 python3 main.py --model_name facebook/opt-125m --amp --num_bits 4 --group_size -1 --low_gpu_mem_usage --train_bs 1 --gradient_accumulate_steps 8
+CUDA_VISIBLE_DEVICES=0 python3 main.py --model_name facebook/opt-125m --amp --bits 4 --group_size -1 --low_gpu_mem_usage --train_bs 1 --gradient_accumulate_steps 8
```
- **Utilizing the AdamW Optimizer:**
Include the flag `--adam`. Note that AdamW may be less effective than Sign gradient descent in many scenarios.
- **Running the Original SignRound:**
```bash
-CUDA_VISIBLE_DEVICES=0 python3 main.py --model_name facebook/opt-125m --amp --num_bits 4 --group_size -1 --iters 400 --lr 0.0025 --minmax_lr 0.0025
+CUDA_VISIBLE_DEVICES=0 python3 main.py --model_name facebook/opt-125m --amp --bits 4 --group_size -1 --iters 400 --lr 0.0025 --minmax_lr 0.0025
```
`--enable_minmax_tuning` is strongly recommended
@@ -71,6 +113,20 @@ We are working on exporting the quantized model to HF format
Cpu kernel will be supported soon
## Validated Models
+
+[//]: # ()
+[//]: # (| W4G128 | MMLU | Lamb. | Hella. | Wino. | Piqa | Truth. | Open. | Boolq | RTE | ARC-e | ARC-c. | AVG. |)
+
+[//]: # (|-----------------------------|------|-------|--------|-------|------|--------|-------|-------|-----|-------|--------|------|)
+
+[//]: # (| | | | | | | | | | | | | |)
+
+[//]: # (| mistralai/Mixtral-8x7B-v0.1 | | | | | | | | | | | | |)
+
+[//]: # (|-----------------------------|------|-------|--------|-------|------|--------|-------|-------|-----|-------|--------|------|)
+
+[//]: # (| microsoft/phi-2 | | | | | | | | | | | | |)
+
For a fair comparison, we utilized 512 samples from Pile-10k for all methods during calibration. Due to memory constraints, we maintained the original sequence length of 512 for AWQ, while for GPTQ and our approach, a sequence length of 2048 is used. We have enalbed act-order and true-seqential in GPTQ, and the notation GPTQ* indicates that we adjusted the random seed or data preprocessing to address issues related to the non-positive definite Hessian matrix or other issues.
![](./figs/W4G-1.png)
![](./figs/W4G128.png)
diff --git a/auto_round/autoround.py b/auto_round/autoround.py
index 8d314bde7..4e95388da 100644
--- a/auto_round/autoround.py
+++ b/auto_round/autoround.py
@@ -46,6 +46,7 @@ def quant_weight_asym(weight, num_bits=4, v=0, min_scale=0, max_scale=0):
Quantized and dequantized weight, scale, zero-point
"""
maxq = torch.tensor(2 ** num_bits - 1)
+ ##zeros = torch.zeros(weight.shape[0], device=weight.device, dtype=weight.dtype)##force scale to fp16
zeros = torch.zeros(weight.shape[0], device=weight.device)
if isinstance(min_scale, torch.Tensor):
wmin_tmp = torch.minimum(weight.min(1)[0], zeros)
@@ -900,7 +901,7 @@ class AutoRound(object):
Args:
model: The PyTorch model to be quantized.
- tokenizer: An optional tokenizer for processing input data.
+ tokenizer: An optional tokenizer for processing input data. If none, a dataloader must be provided.
bits (int): Number of bits for quantization (default is 4).
group_size (int): Size of the quantization group (default is 128).
scheme (str): The quantization scheme to be used (default is "asym").
@@ -918,7 +919,7 @@ class AutoRound(object):
enable_full_range (bool): Whether to enable full range quantization (default is False).
bs (int): Batch size for training (default is 8).
amp (bool): Whether to use automatic mixed precision (default is True).
- device: The device to be used for training (default is "cuda:0").
+ device: The device to be used for tuning (default is "cuda:0").
lr_scheduler: The learning rate scheduler to be used.
dataloader: The dataloader for input data (to be supported in future).
dataset_name (str): The default dataset name (default is "NeelNanda/pile-10k").
@@ -1334,7 +1335,7 @@ class AutoRound(object):
for i in range(0, len(block_names), n_blocks):
if n_blocks == 1:
n = block_names[i]
- logger.info(n)
+ logger.info(f"quantizing {i}/{len(block_names)}, {n}")
m = get_module(model, n)
else:
names = block_names[i: i + n_blocks]
@@ -1366,17 +1367,25 @@ class AutoRound(object):
Export the model to autogptq format to easily leverage cuda kernel
"""
model = copy.deepcopy(self.model.to("cpu")) ##TODO avoid this deepcopy
- quantizers = {}
- for key in self.weight_config:
- info = self.weight_config[key]
- if info["bits"] > 8:
- continue
- quantizers[key] = (None, info['scale'], info['zp'], info['g_idx'])
+
from auto_gptq.modeling._utils import pack_model
if self.bits == 3:
+ quantizers = {}
+ for key in self.weight_config:
+ info = self.weight_config[key]
+ if info["bits"] > 8:
+ continue
+ quantizers[key] = (None, info['scale'], info['zp'], info['g_idx'])
pack_model(model, quantizers, self.bits, self.group_size, use_cuda_fp16=True, desc_act=False,
force_layer_back_to_cpu=True)
else:
+ quantizers = {}
+ for key in self.weight_config:
+ info = self.weight_config[key]
+ if info["bits"] > 8:
+ continue
+ quantizers[key] = (None, info['scale'].to(torch.float32), info['zp'].to(torch.float32), info['g_idx'])
+
pack_model(model, quantizers, self.bits, self.group_size, use_cuda_fp16=True, desc_act=False,
force_layer_back_to_cpu=True, use_triton=True)
from auto_round.export import save_quantized_to_autogptq
@@ -1441,7 +1450,7 @@ class AutoRound(object):
end_time = time.time()
cost_time = end_time - start_time
logger.info(f"quantization tuning time {cost_time}")
- self.export_to_autogptq("test_export")
+ ##self.export_to_autogptq("test_export")
return self.model, self.weight_config
diff --git a/auto_round/export.py b/auto_round/export.py
index f73948b61..ac44f1e38 100644
--- a/auto_round/export.py
+++ b/auto_round/export.py
@@ -44,9 +44,10 @@ from safetensors.torch import save_file as safe_save
from os.path import join, isfile, isdir
-def save_quantized_to_autogptq(model, save_dir: str, bits=4, group_size=128, sym=False, iters=200, lr=5e-3, minmax_lr=5e-3,
- enable_minmax_tuning=True, use_quant_input=True, use_safetensors: bool = True,
- safetensors_metadata: Optional[Dict[str, str]] = None):
+def save_quantized_to_autogptq(model, save_dir: str, bits=4, group_size=128, sym=False, iters=200, lr=5e-3,
+ minmax_lr=5e-3,
+ enable_minmax_tuning=True, use_quant_input=True, use_safetensors: bool = True,
+ safetensors_metadata: Optional[Dict[str, str]] = None):
"""save quantized model and configs to local disk"""
os.makedirs(save_dir, exist_ok=True)
model.to("cpu")
@@ -103,8 +104,9 @@ def save_quantized_to_autogptq(model, save_dir: str, bits=4, group_size=128, sym
model.config.save_pretrained(save_dir)
from auto_gptq.modeling._base import BaseQuantizeConfig
- quantization_config = BaseQuantizeConfig(bits=bits,group_size=group_size, desc_act=False, sym=sym, true_sequential=False, static_groups=False,
- model_file_base_name=model_base_name)
+ quantization_config = BaseQuantizeConfig(bits=bits, group_size=group_size, desc_act=False, sym=sym,
+ true_sequential=False, static_groups=False,
+ model_file_base_name=model_base_name)
quantization_config.model_file_base_name = model_base_name
quantization_config.save_pretrained(save_dir)
diff --git a/examples/main.py b/examples/main.py
index 937f0341f..98429dd54 100644
--- a/examples/main.py
+++ b/examples/main.py
@@ -27,7 +27,7 @@ if __name__ == '__main__':
"--model_name", default="/models/opt-125m"
)
- parser.add_argument("--num_bits", default=4, type=int,
+ parser.add_argument("--bits", default=4, type=int,
help="number of bits")
parser.add_argument("--group_size", default=128, type=int,
@@ -155,7 +155,7 @@ if __name__ == '__main__':
seqlen = min(seqlen, tokenizer.model_max_length)
args.seqlen = seqlen
- excel_name = f"{model_name}_{args.num_bits}_{args.group_size}"
+ excel_name = f"{model_name}_{args.bits}_{args.group_size}"
if args.eval_fp16_baseline:
if not args.low_gpu_mem_usage:
model = model.to(cuda_device)
@@ -168,7 +168,7 @@ if __name__ == '__main__':
# if args.iters <= 0:
# print("eval rtn", flush=True)
# excel_name += "_rtn.xlsx"
- # q_dq_weight(model, num_bits=args.num_bits, group_size=args.group_size)
+ # q_dq_weight(model, bits=args.bits, group_size=args.group_size)
# if not args.low_gpu_mem_usage:
# model = model.to(cuda_device)
# eval_model(output_dir=args.output_dir, model=model, tokenizer=tokenizer, tasks=args.tasks, \
@@ -186,7 +186,7 @@ if __name__ == '__main__':
if args.adam:
round = AutoAdamRound
- autoround = round(model, tokenizer, args.num_bits, args.group_size, scheme, bs=args.train_bs,
+ autoround = round(model, tokenizer, args.bits, args.group_size, scheme, bs=args.train_bs,
seqlen=seqlen, n_blocks=args.n_blocks, iters=args.iters, lr=args.lr,
minmax_lr=args.minmax_lr, use_quant_input=args.use_quant_input,
amp=args.amp, n_samples=args.n_samples, low_gpu_mem_usage=args.low_gpu_mem_usage, seed=args.seed, gradient_accumulate_steps=args.gradient_accumulate_steps) ##TODO args pass
@@ -194,7 +194,7 @@ if __name__ == '__main__':
torch.cuda.empty_cache()
model.eval()
- output_dir = args.output_dir + "_" + args.model_name.split('/')[-1] + f"_w{args.num_bits}_g{args.group_size}"
+ output_dir = args.output_dir + "_" + args.model_name.split('/')[-1] + f"_w{args.bits}_g{args.group_size}"
# model.to(cuda_device)
# eval_model(model, model_name, tokenizer, tasks=args.tasks, eval_bs=args.eval_bs)