Skip to content

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

fix several regressions including lm-head quantization, 3bit asym torch backend,etc (#796)

Wenhua Cheng08d6b9e74b1c
diff --git a/auto_round/autoround.py b/auto_round/autoround.py
index e02891b29..1934c5298 100644
--- a/auto_round/autoround.py
+++ b/auto_round/autoround.py
@@ -18,7 +18,7 @@ import re
import sys
import time
import traceback
-from dataclasses import asdict
+from dataclasses import asdict, fields
from typing import Any, Callable, Union
import accelerate
@@ -177,7 +177,7 @@ class AutoRound(object):
disable_opt_rtn (bool, optional): Disable RTN-mode optimization (iters=0). Defaults to False.
enable_alg_ext (bool, optional): Enable algorithm extension (primarily for INT2). Defaults to False.
**kwargs: Backward compatible options:
- - enable_alg_ext, lr, lr_scheduler, sampler, not_use_best_mse, dynamic_max_gap,
+ - enable_alg_ext, quant_lm_head, lr, lr_scheduler, sampler, not_use_best_mse, dynamic_max_gap,
super_group_size, super_bits, scale_dtype ("fp16" etc.),
nblocks, low_cpu_mem_usage, to_quant_block_names,
enable_norm_bias_tuning, enable_quanted_input,
@@ -226,9 +226,7 @@ class AutoRound(object):
disable_deterministic_algorithms = kwargs.pop("disable_deterministic_algorithms", False)
static_kv_dtype = kwargs.pop("static_kv_dtype", None)
device = kwargs.pop("device", None)
- if device is not None:
- logger.warning("`device` is deprecated, please use `device_map` instead")
-
+ self.quant_lm_head = kwargs.pop("quant_lm_head", False)
self.vlm = kwargs.pop("vlm") if "vlm" in kwargs else False
# Scale factor for RAM usage per parameter.
self.mem_per_param_scale = kwargs.pop("mem_per_param_scale", None)
@@ -236,6 +234,14 @@ class AutoRound(object):
if kwargs:
logger.warning(f"unrecognized keys {list(kwargs.keys())} were passed. Please check them.")
+ if not disable_deterministic_algorithms:
+ if "CUBLAS_WORKSPACE_CONFIG" not in os.environ:
+ os.environ["CUBLAS_WORKSPACE_CONFIG"] = ":4096:8"
+ torch.use_deterministic_algorithms(True, warn_only=False)
+
+ if device is not None:
+ logger.warning("`device` is deprecated, please use `device_map` instead")
+
if device_map is None:
device_map = 0
@@ -269,11 +275,6 @@ class AutoRound(object):
self.device_map = None
self._set_device_map_in_blocks(self.device_map)
- if not disable_deterministic_algorithms:
- if "CUBLAS_WORKSPACE_CONFIG" not in os.environ:
- os.environ["CUBLAS_WORKSPACE_CONFIG"] = ":4096:8"
- torch.use_deterministic_algorithms(True, warn_only=False)
-
# Model related
self.quantized = False
if isinstance(model, str):
@@ -296,31 +297,7 @@ class AutoRound(object):
self.tokenizer = tokenizer
self.shared_cache_keys = get_shared_keys(self.model)
- # Some other quantization configs
- self.layer_config = {} if layer_config is None else layer_config
- # Check and convert to dict
- for key, item in self.layer_config.items():
- if isinstance(item, str):
- item = asdict(preset_name_to_scheme(item.upper()))
- self.layer_config[key] = item
-
- if isinstance(item, QuantizationScheme):
- config = asdict(item)
- tmp_keys = copy.deepcopy(list(config.keys()))
- for tmp_key in tmp_keys: ## Pop None value to be overridden
- if config[tmp_key] is None:
- config.pop(tmp_key)
- self.layer_config[key] = config
- elif isinstance(item, dict):
- item_keys = item.keys()
- expected_keys = list(QuantizationScheme.__annotations__.keys())
- if item_keys not in expected_keys:
- for item_key in item_keys:
- if item_key not in expected_keys:
- raise ValueError(
- f"the key {item_key} in layer_config for layer {key} is invalid,"
- f" only {expected_keys} are supported"
- )
+ self._parse_layer_config(layer_config) # must place after model init
self.to_quant_block_names = to_quant_block_names
@@ -410,33 +387,58 @@ class AutoRound(object):
import habana_frameworks.torch.core as htcore # pylint: disable=E0401
import habana_frameworks.torch.hpu as hthpu # pylint: disable=E0401]
- self.serialization_keys = [
- "bits",
- "group_size",
- "sym",
- "data_type",
- "enable_quanted_input",
- "enable_minmax_tuning",
- "seqlen",
- "batch_size",
- "scale_dtype",
- "lr",
- "minmax_lr",
- "gradient_accumulate_steps",
- "iters",
- "amp",
- "nsamples",
- "low_gpu_mem_usage",
- "to_quant_block_names",
- "enable_norm_bias_tuning",
- "act_bits",
- "act_group_size",
- "act_sym",
- "act_dynamic",
- "act_data_type",
- "super_bits",
- "super_group_size",
- ]
+ def _parse_layer_config(self, layer_config: dict[str, Union[str, dict, QuantizationScheme]]) -> None:
+ """Parse and set the layer-wise quantization configuration."""
+ # Some other quantization configs
+ self.layer_config = {} if layer_config is None else layer_config
+ scheme_keys = [f.name for f in fields(QuantizationScheme)]
+ for key, item in self.layer_config.items():
+ if isinstance(item, str):
+ item = asdict(preset_name_to_scheme(item.upper()))
+ self.layer_config[key] = item
+
+ if isinstance(item, QuantizationScheme):
+ config = asdict(item)
+ tmp_keys = copy.deepcopy(list(config.keys()))
+ for tmp_key in tmp_keys: ## Pop None value to be overridden
+ if config[tmp_key] is None:
+ config.pop(tmp_key)
+ self.layer_config[key] = config
+ elif isinstance(item, dict):
+ item_keys = item.keys()
+ if item_keys not in scheme_keys:
+ for item_key in item_keys:
+ if item_key not in scheme_keys:
+ raise ValueError(
+ f"the key {item_key} in layer_config for layer {key} is invalid,"
+ f" only {scheme_keys} are supported"
+ )
+
+ if not self.quant_lm_head or (isinstance(self.scheme, str) and self.scheme.lower().startswith("gguf")):
+ return
+ for n, _ in self.model.named_modules():
+ lm_head_layer_name = n
+
+ if (
+ hasattr(self.model, "config")
+ and self.model.config.tie_word_embeddings
+ and hasattr(self.model, "_tied_weights_keys")
+ ):
+ tied_keys = self.model._tied_weights_keys
+ for item in tied_keys:
+ if lm_head_layer_name in item: # TODO extend to encoder-decoder layer, seq classification model
+ self.quant_lm_head = False
+ logger.warning(
+ "reset `quant_lm_head` to `False` as quantizing lm_head with tied weights has not been "
+ "supported currently"
+ )
+ break
+
+ lm_head_layer_config = self.layer_config[lm_head_layer_name] if lm_head_layer_name in self.layer_config else {}
+
+ for key in scheme_keys:
+ if key not in lm_head_layer_config:
+ lm_head_layer_config[key] = getattr(self, key)
def _parse_and_set_scheme(self, scheme: Union[str, dict, QuantizationScheme], kwargs) -> None:
"""Parse and set the quantization scheme."""
@@ -448,20 +450,7 @@ class AutoRound(object):
scheme = scheme.upper()
self.scheme = scheme
scheme = asdict(preset_name_to_scheme(scheme))
-
- scheme_keys = (
- "bits",
- "group_size",
- "sym",
- "data_type",
- "act_bits",
- "act_group_size",
- "act_sym",
- "act_data_type",
- "act_dynamic",
- "super_bits",
- "super_group_size",
- )
+ scheme_keys = [f.name for f in fields(QuantizationScheme)]
for key in scheme_keys:
if key in kwargs and kwargs[key] is not None:
setattr(self, key, kwargs[key])
@@ -797,11 +786,27 @@ class AutoRound(object):
Returns:
list: A list of validated and updated formats.
"""
- _gguf_args_check(self, format, model_type=ModelType.TEXT)
- if self.vlm:
- _gguf_args_check(self, format, model_type=ModelType.MMPROJ)
+
+ # Remove duplicates from formats list
+ def remove_duplicates(lst):
+ seen = set()
+ return [x for x in lst if not (x in seen or seen.add(x))]
formats = format.replace("q*_", f"q{self.bits}_").replace(" ", "").split(",")
+ formats = remove_duplicates(formats) # need the keep origin order
+
+ if isinstance(self.scheme, str) and self.scheme.lower().startswith("gguf"):
+ for i in range(len(formats)):
+ if formats[i] != "fake" and formats[i] != self.scheme.lower().startswith("gguf"):
+ logger.warning(
+ f"reset format {formats[i]} to {self.scheme.lower()} "
+ f"since scheme {self.scheme} can only be exported to format {self.scheme.lower()}"
+ )
+ formats[i] = self.scheme.lower()
+
+ _gguf_args_check(self, formats, model_type=ModelType.TEXT)
+ if self.vlm:
+ _gguf_args_check(self, formats, model_type=ModelType.MMPROJ)
for format_ in formats:
if format_ not in SUPPORTED_FORMATS:
@@ -859,11 +864,6 @@ class AutoRound(object):
if (is_nv_fp(self.data_type) or is_mx_fp(self.data_type)) and format != "fake":
logger.warning(f"nv_fp and mx_fp dtypes are not supported for export format: {format}")
- # Remove duplicates from formats list
- def remove_duplicates(lst):
- seen = set()
- return [x for x in lst if not (x in seen or seen.add(x))]
-
formats = remove_duplicates(formats)
for i in range(len(formats)):
formats[i] = self._check_supported_format(formats[i])
@@ -3060,11 +3060,37 @@ class AutoRound(object):
)
if "awq" in format and not self.bits == 4:
raise ValueError("The AWQ format only supports W4 quantization ")
-
+ serialization_keys = [
+ "bits",
+ "group_size",
+ "sym",
+ "data_type",
+ "enable_quanted_input",
+ "enable_minmax_tuning",
+ "seqlen",
+ "batch_size",
+ "scale_dtype",
+ "lr",
+ "minmax_lr",
+ "gradient_accumulate_steps",
+ "iters",
+ "amp",
+ "nsamples",
+ "low_gpu_mem_usage",
+ "to_quant_block_names",
+ "enable_norm_bias_tuning",
+ "act_bits",
+ "act_group_size",
+ "act_sym",
+ "act_dynamic",
+ "act_data_type",
+ "super_bits",
+ "super_group_size",
+ ]
if isinstance(self.dataset, str):
- self.serialization_keys.append("dataset")
+ serialization_keys.append("dataset")
serialization_dict = {}
- for key in self.serialization_keys:
+ for key in serialization_keys:
serialization_dict[key] = getattr(self, key)
from .version import __version__
@@ -3072,7 +3098,7 @@ class AutoRound(object):
if "scale_dtype" in serialization_dict.keys():
serialization_dict["scale_dtype"] = str(serialization_dict["scale_dtype"])
- compressed_model = save_quantized_as_format( ##TODO refine the code
+ compressed_model = save_quantized_as_format( # TODO refine the code
output_dir,
model=self.model,
layer_config=self.layer_config,
diff --git a/auto_round/export/export_to_autogptq/export.py b/auto_round/export/export_to_autogptq/export.py
index c66a893f0..02079c70b 100644
--- a/auto_round/export/export_to_autogptq/export.py
+++ b/auto_round/export/export_to_autogptq/export.py
@@ -70,10 +70,11 @@ def pack_layer(name, model, backend, device=None):
if name == "lm_head": ##dese not support lm-head
return
layer = get_module(model, name)
- orig_device = layer.weight.device
- if not isinstance(layer, SUPPORTED_LAYER_TYPES): ##already packed
+
+ if not isinstance(layer, SUPPORTED_LAYER_TYPES): # already packed
return
+ orig_device = layer.weight.device # must place after 74
bits = layer.bits
if bits > 8:
return
diff --git a/auto_round/inference/convert_model.py b/auto_round/inference/convert_model.py
index bd6dde836..3454e422d 100644
--- a/auto_round/inference/convert_model.py
+++ b/auto_round/inference/convert_model.py
@@ -366,7 +366,7 @@ def _replace_by_quant_layers(module: nn.Module, layer_configs, target_backend, t
if not layer_backend:
raise ValueError(f"No compatible backend found for layer {layer_name} with config {config}")
- logger.debug(f"{layer_name}: {layer_backend} backend is used") ##TODO delete
+ logger.debug(f"{layer_name}: {layer_backend} backend is used") # TODO delete
# Create and replace layer
new_layer = _create_quant_layer(layer, layer_backend, config, in_features, out_features)
diff --git a/auto_round/script/llm.py b/auto_round/script/llm.py
index 9f7319157..11cdb42ad 100644
--- a/auto_round/script/llm.py
+++ b/auto_round/script/llm.py
@@ -516,24 +516,7 @@ def tune(args):
# TODO gptq could support some mixed precision config
logger.warning(f"mixed precision exporting does not support {format} currently")
- lm_head_layer_name = "lm_head"
- for n, _ in model.named_modules():
- lm_head_layer_name = n
if args.quant_lm_head:
- config = AutoConfig.from_pretrained(model_name, trust_remote_code=not args.disable_trust_remote_code)
- if config.tie_word_embeddings and hasattr(model, "_tied_weights_keys"):
- tied_keys = model._tied_weights_keys
- for item in tied_keys:
- if lm_head_layer_name in item: # TODO extend to encoder-decoder layer, seq classification model
- args.quant_lm_head = False
- logger.warning(
- "reset `quant_lm_head` to `False` as quantizing lm_head with tied weights has not been "
- "supported currently"
- )
- break
-
- if args.quant_lm_head:
- layer_config[lm_head_layer_name] = {"bits": args.bits, "act_bits": args.act_bits}
for format in formats:
if "auto_round" not in format and "fake" not in format:
auto_round_formats = [s for s in SUPPORTED_FORMATS if s.startswith("auto_round")]
diff --git a/auto_round/script/mllm.py b/auto_round/script/mllm.py
index 26053a02c..162b2ee54 100644
--- a/auto_round/script/mllm.py
+++ b/auto_round/script/mllm.py
@@ -397,23 +397,7 @@ def tune(args):
##TODO gptq, awq could support some mixed precision config
logger.warning(f"mixed precision exporting does not support {format} currently")
- lm_head_layer_name = "lm_head"
- for n, _ in model.named_modules():
- lm_head_layer_name = n
if args.quant_lm_head:
- config = AutoConfig.from_pretrained(model_name, trust_remote_code=not args.disable_trust_remote_code)
- if config.tie_word_embeddings and hasattr(model, "_tied_weights_keys"):
- tied_keys = model._tied_weights_keys
- for item in tied_keys:
- if lm_head_layer_name in item: ##TODO extend to encoder-decoder layer, seq classification model
- args.quant_lm_head = False
- print(
- "warning, disable quant_lm_head as quantizing lm_head with tied weights has not been "
- "supported currently"
- )
- break
- if args.quant_lm_head:
- layer_config[lm_head_layer_name] = {"bits": args.bits, "act_bits": args.act_bits}
for format in formats:
if "auto_round" not in format and "fake" not in format:
auto_round_formats = [s for s in SUPPORTED_FORMATS if s.startswith("auto_round")]
diff --git a/auto_round/utils.py b/auto_round/utils.py
index d019420a0..2561a20cb 100644
--- a/auto_round/utils.py
+++ b/auto_round/utils.py
@@ -1230,18 +1230,12 @@ def get_gguf_architecture(dir_model, model_type=ModelType.TEXT):
return model_class
-def _gguf_args_check(args_or_ar, format_str=None, model_type=ModelType.TEXT):
+def _gguf_args_check(args_or_ar, formats: list[str] = None, model_type=ModelType.TEXT):
import argparse
from auto_round.export.export_to_gguf.convert import download_convert_file
from auto_round.utils import logger
- if format_str is None:
- args_or_ar.format = args_or_ar.format.replace("q*_", f"q{args_or_ar.bits}_")
- format_str = args_or_ar.format
- else:
- format_str = format_str.replace("q*_", f"q{args_or_ar.bits}_")
- formats = format_str.lower().replace(" ", "").split(",")
formats = sorted(formats, key=lambda x: len(x))
export_gguf = False
for f in formats:
diff --git a/auto_round_extension/torch/qlinear_torch.py b/auto_round_extension/torch/qlinear_torch.py
index a7e40277f..22d91a973 100644
--- a/auto_round_extension/torch/qlinear_torch.py
+++ b/auto_round_extension/torch/qlinear_torch.py
@@ -224,7 +224,7 @@ class QuantLinear(nn.Module):
col += 1
qzeros[:, col] |= (zeros[:, i] >> 2) & 1
i += 1
- # packed_zeros = (zeros[:, i: i + 10]).to(dtype=torch.int32)
+ packed_zeros = (zeros[:, i : i + 10]).to(dtype=torch.int32)
shifts = torch.arange(0, 10).to(device) * self.bits + 1
shifted = packed_zeros << shifts
qzeros[:, col] |= shifted.sum(dim=-1)
@@ -233,7 +233,7 @@ class QuantLinear(nn.Module):
col += 1
qzeros[:, col] |= (zeros[:, i] >> 1) & 0x3
i += 1
- # packed_zeros = (zeros[:, i: i + 10]).to(dtype=torch.int32)
+ packed_zeros = (zeros[:, i : i + 10]).to(dtype=torch.int32)
shifts = torch.arange(0, 10).to(device) * self.bits + 2
shifted = packed_zeros << shifts
qzeros[:, col] |= shifted.sum(dim=-1)
diff --git a/docs/mxnv_acc.md b/docs/mxnv_acc.md
index 539028811..cb764fa58 100644
--- a/docs/mxnv_acc.md
+++ b/docs/mxnv_acc.md
@@ -12,4 +12,4 @@ We evaluated using a fake model since we currently have no access to devices for
|-------------------|----------------------|--------------------|---------|-----------|
| RTN | 0.68756 | 0.6906 | 0.72962 | 0.71636 |
| AutoRound | 0.69184 | 0.69728 | 0.73058 | 0.73062 |
-| AutoRound+alg_ext | 0.69648 | 0.6989 | 0.7318 | |
\ No newline at end of file
+| AutoRound+alg_ext | 0.69648 | 0.6989 | 0.7318 | 0.72948 |
\ No newline at end of file
diff --git a/test/test_cpu/test_autoround.py b/test/test_cpu/test_autoround.py
index a82abef00..ea53aaf94 100644
--- a/test/test_cpu/test_autoround.py
+++ b/test/test_cpu/test_autoround.py
@@ -278,7 +278,7 @@ class TestAutoRound(unittest.TestCase):
)
autoround.quantize()
- def test_lm_head(self):
+ def test_lm_head_layer_config_way(self):
bits, group_size, sym = 4, -1, False
layer_config = {"lm_head": {"data_type": "int"}}
autoround = AutoRound(
@@ -368,7 +368,7 @@ class TestAutoRound(unittest.TestCase):
tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
bits, group_size, sym = 4, 128, True
- autoround = AutoRound(model, tokenizer, bits=bits, group_size=group_size, sym=sym, iters=1, nsamples=1)
+ autoround = AutoRound(model, tokenizer, bits=bits, group_size=group_size, sym=sym, iters=0, nsamples=1)
quantized_model_path = self.save_folder
autoround.quantize_and_save(output_dir=quantized_model_path, format="auto_round")
model = AutoModelForCausalLM.from_pretrained(
@@ -672,6 +672,11 @@ class TestAutoRound(unittest.TestCase):
layer_config = {"model.decoder.layers.2.self_attn": {"bit": 2}} # should be bits
ar = AutoRound("facebook/opt-125m", scheme="W3A16", nsamples=1, iters=1, layer_config=layer_config)
+ def test_quant_lm_head(self):
+ model_name = "Qwen/Qwen3-8B"
+ ar = AutoRound(model_name, quant_lm_head=True, iters=1, nsamples=1, seqlen=32)
+ ar.quantize()
+
if __name__ == "__main__":
unittest.main()
diff --git a/test/test_cpu/test_autoround_acc.py b/test/test_cpu/test_autoround_acc.py
index 1a3ca5018..5c79d71b2 100644
--- a/test/test_cpu/test_autoround_acc.py
+++ b/test/test_cpu/test_autoround_acc.py
@@ -3,6 +3,8 @@ import shutil
import sys
import unittest
+from auto_round.eval.evaluation import simple_evaluate
+
sys.path.insert(0, "../..")
from math import isclose
@@ -26,24 +28,23 @@ class LLMDataLoader:
class TestAutoRound(unittest.TestCase):
@classmethod
def setUpClass(self):
- self.model_name = "hf-internal-testing/tiny-random-GPTJForCausalLM"
- self.model = AutoModelForCausalLM.from_pretrained(
- self.model_name, torch_dtype=torch.float32, trust_remote_code=True
- )
- self.tokenizer = AutoTokenizer.from_pretrained(self.model_name, trust_remote_code=True)
self.llm_dataloader = LLMDataLoader()
+ self.save_dir = "./saved"
@classmethod
def tearDownClass(self):
- shutil.rmtree("./saved", ignore_errors=True)
+ shutil.rmtree(self.save_dir, ignore_errors=True)
shutil.rmtree("runs", ignore_errors=True)
def test_default_acc(self):
+ model_name = "hf-internal-testing/tiny-random-GPTJForCausalLM"
+ model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype=torch.float32, trust_remote_code=True)
+ tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
bits, group_size, sym = 4, 128, True
inp = torch.ones([1, 10], dtype=torch.long)
autoround = AutoRound(
- self.model,
- self.tokenizer,
+ model,
+ tokenizer,
bits=bits,
device="cpu",
group_size=group_size,
@@ -53,15 +54,13 @@ class TestAutoRound(unittest.TestCase):
dataset=self.llm_dataloader,
)
autoround.quantize()
- out0 = self.model(inp)
+ out0 = model(inp)
print(f"out0 = {float(out0[0][0][0][0])}")
- model_tmp = AutoModelForCausalLM.from_pretrained(
- self.model_name, torch_dtype=torch.float32, trust_remote_code=True
- )
+ model_tmp = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype=torch.float32, trust_remote_code=True)
autoround_1 = AutoRound(
model_tmp,
- self.tokenizer,
+ tokenizer,
bits=bits,
group_size=group_size,
sym=sym,
@@ -76,6 +75,20 @@ class TestAutoRound(unittest.TestCase):
assert out0[0].equal(out1[0])
self.assertTrue(isclose(float(out0[0][0][0][0]), -0.021002087742090225, rel_tol=5e-04))
+ def test_3bits_asym_autoround(self):
+ model_name = "facebook/opt-125m"
+
+ bits, sym = 3, False
+ autoround = AutoRound(model_name, bits=bits, sym=sym, iters=0)
+ autoround.quantize_and_save(self.save_dir, format="auto_round", inplace=False)
+ model_args = f"pretrained={self.save_dir}"
+ res = simple_evaluate(model="hf", model_args=model_args, tasks="lambada_openai", batch_size="auto", limit=10)
+
+ accuracy = res["results"]["lambada_openai"]["acc,none"]
+ print(f"accuracy = {accuracy}")
+ assert accuracy > 0.15
+ shutil.rmtree(self.save_dir, ignore_errors=True)
+
if __name__ == "__main__":
unittest.main()
diff --git a/test/test_cpu/test_basic_usage.py b/test/test_cpu/test_cli_usage.py
similarity index 97%
rename from test/test_cpu/test_basic_usage.py
rename to test/test_cpu/test_cli_usage.py
index ad9e9b56c..1eed6d30e 100644
--- a/test/test_cpu/test_basic_usage.py
+++ b/test/test_cpu/test_cli_usage.py
@@ -19,13 +19,13 @@ class TestAutoRoundCmd(unittest.TestCase):
def test_auto_round_cmd(self):
python_path = sys.executable
- ##test llm script
+ # Test llm script
res = os.system(f"cd ../.. && {python_path} -m auto_round -h")
if res > 0 or res == -1:
assert False, "cmd line test fail, please have a check"
res = os.system(
- f"cd ../.. && {python_path} -m auto_round --model 'facebook/opt-125m' --seqlen 32 --iter 2 --nsamples 1 --format auto_gptq,auto_round --output_dir ./saved --tasks piqa"
+ f"cd ../.. && {python_path} -m auto_round --model 'facebook/opt-125m' --seqlen 32 --iter 2 --nsamples 1 --format auto_gptq,auto_round --output_dir ./saved --tasks piqa"
)
if res > 0 or res == -1:
assert False, "cmd line test fail, please have a check"
diff --git a/test/test_cpu/test_export.py b/test/test_cpu/test_export.py
index 536cd338a..5cf516935 100644
--- a/test/test_cpu/test_export.py
+++ b/test/test_cpu/test_export.py
@@ -37,9 +37,9 @@ class TestAutoRound(unittest.TestCase):
def test_autogptq_format(self):
for group_size in [-1, 32, 128]:
bits, sym = 4, False
+ model_name = "facebook/opt-125m"
autoround = AutoRound(
- self.model,
- self.tokenizer,
+ model=model_name,
bits=bits,
group_size=group_size,
sym=sym,
@@ -48,9 +48,8 @@ class TestAutoRound(unittest.TestCase):
dataset=self.llm_dataloader,
)
- autoround.quantize()
quantized_model_path = "./saved"
- autoround.save_quantized(output_dir=quantized_model_path, inplace=False, format="auto_gptq")
+ autoround.quantize_and_save(output_dir=quantized_model_path, format="auto_gptq")
if group_size == -1:
shutil.rmtree("./saved", ignore_errors=True)
@@ -68,9 +67,9 @@ class TestAutoRound(unittest.TestCase):
def test_autoround_format(self):
for group_size in [-1, 32, 128]:
bits, sym = 4, True
+ model_name = "facebook/opt-125m"
autoround = AutoRound(
- self.model,
- self.tokenizer,
+ model=model_name,
bits=bits,
group_size=group_size,
sym=sym,
@@ -78,9 +77,8 @@ class TestAutoRound(unittest.TestCase):
seqlen=2,
dataset=self.llm_dataloader,
)
- autoround.quantize()
quantized_model_path = "./saved"
- autoround.save_quantized(output_dir=quantized_model_path, inplace=False, format="auto_round")
+ autoround.quantize_and_save(output_dir=quantized_model_path, format="auto_round")
if group_size == -1:
shutil.rmtree("./saved", ignore_errors=True)
@@ -95,9 +93,9 @@ class TestAutoRound(unittest.TestCase):
def test_autoround_awq_format(self):
for group_size in [-1, 32, 128]:
bits, sym = 4, False
+ model_name = "facebook/opt-125m"
autoround = AutoRound(
- self.model,
- self.tokenizer,
+ model=model_name,
bits=bits,
group_size=group_size,
sym=sym,
@@ -105,10 +103,9 @@ class TestAutoRound(unittest.TestCase):
seqlen=2,
dataset=self.llm_dataloader,
)
- autoround.quantize()
quantized_model_path = "./saved"
- autoround.save_quantized(output_dir=quantized_model_path, inplace=False, format="auto_round:auto_awq")
+ autoround.quantize_and_save(output_dir=quantized_model_path, format="auto_round:auto_awq")
# quantization_config = AutoRoundConfig(
# backend="cpu"