Skip to content

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

enable backup pile dataset loading (#417)

WeiweiZhang1a9b5ae4fbb2c
diff --git a/.azure-pipelines/scripts/ut/run_ut.sh b/.azure-pipelines/scripts/ut/run_ut.sh
index 411730c16..e2abf25e2 100644
--- a/.azure-pipelines/scripts/ut/run_ut.sh
+++ b/.azure-pipelines/scripts/ut/run_ut.sh
@@ -4,6 +4,7 @@ set -xe
# install requirements
echo "set up UT env..."
pip install pytest-cov pytest-html
+pip install -r /auto-round/test/requirements.txt
pip list
cd /auto-round/test || exit 1
diff --git a/auto_round/backend.py b/auto_round/backend.py
index c4e59bf68..07e19427c 100644
--- a/auto_round/backend.py
+++ b/auto_round/backend.py
@@ -137,7 +137,7 @@ BackendInfos['gptq:cuda'] = BackendInfo(device=["cuda"], sym=[True, False],
packing_format="triton_zp+-1",
bits=[2, 3, 4, 8], group_size=None,
priority=1, feature_checks=[feature_multiply_checker_32],
- alias=["auto_round:auto_gptq:cuda,auto_gptq:cuda, auto_round:gptq:cuda"],
+ alias=["auto_round:auto_gptq:cuda","auto_gptq:cuda","auto_round:gptq:cuda"],
convertable_format=["triton_zp+-1"],
requirements=["auto-gptq>=0.7.1"]
)
@@ -554,3 +554,4 @@ def get_layer_backend(device, backend, orig_backend, bits, group_size, sym, in_f
reverse=True)
return supported_backends[0]
+
diff --git a/auto_round/calib_dataset.py b/auto_round/calib_dataset.py
index e2376fef0..1fd8a5cd0 100644
--- a/auto_round/calib_dataset.py
+++ b/auto_round/calib_dataset.py
@@ -17,10 +17,8 @@ import random
import torch
from datasets import IterableDataset
-
-torch.use_deterministic_algorithms(True, warn_only=True)
from torch.utils.data import DataLoader
-
+import sys
from .utils import is_local_path, logger
CALIB_DATASETS = {}
@@ -102,9 +100,49 @@ def get_pile_dataset(tokenizer, seqlen, dataset_name="NeelNanda/pile-10k", split
from datasets import load_dataset
split = "train"
+
tokenizer_function = get_tokenizer_function(tokenizer, seqlen, apply_chat_template=apply_chat_template)
+ try:
+ calib_dataset = load_dataset(dataset_name, split=split)
+ except Exception as e:
+ logger.error(f"Failed to load the dataset: {e}." \
+ "Consider using a backup dataset by `pip install modelscope`" \
+ " and set '--dataset swift/pile-val-backup' in AutoRound API.")
+ sys.exit(1)
+ calib_dataset = calib_dataset.shuffle(seed=seed)
+ calib_dataset = calib_dataset.map(tokenizer_function, batched=True)
- calib_dataset = load_dataset(dataset_name, split=split)
+ return calib_dataset
+
+
+@register_dataset("swift/pile-val-backup")
+def get_pile_val_dataset(tokenizer, seqlen, dataset_name="swift/pile-val-backup", split=None, seed=42,
+ apply_chat_template=False):
+ """Returns a dataloader for the specified dataset and split.
+
+ Args:
+ tokenizer: The tokenizer to be used for tokenization.
+ seqlen: The maximum sequence length.
+ data_name: The name of the dataset.
+ split: The data split to be used (e.g., "train", "test", "validation").
+ seed: The random seed for shuffling the dataset.
+ apply_chat_template: Whether to apply chat template in tokenization.
+
+ Returns:
+ A dataloader for the specified dataset and split, using the provided tokenizer and sequence length.
+ """
+ from datasets import load_dataset
+
+ split = "validation"
+
+ tokenizer_function = get_tokenizer_function(tokenizer, seqlen, apply_chat_template=apply_chat_template)
+ from transformers.utils.versions import require_version
+ require_version("modelscope", "Loading 'swift/pile-val-backup' dataset requires modelscope to be installed, " \
+ "`pip install modelscope`")
+ from modelscope import MsDataset # pylint: disable=E0401
+ calib_dataset = MsDataset.load('swift/pile-val-backup',
+ 'default', split=split).to_iterable_dataset() #, use_streaming=True
+ calib_dataset = calib_dataset.take(10000)
calib_dataset = calib_dataset.shuffle(seed=seed)
calib_dataset = calib_dataset.map(tokenizer_function, batched=True)
@@ -601,3 +639,4 @@ def get_dataloader(
calib_dataloader = DataLoader(dataset_final, batch_size=bs, shuffle=False, collate_fn=collate_batch)
return calib_dataloader
+
diff --git a/auto_round/script/llm.py b/auto_round/script/llm.py
index 7dfe86e94..ea6284774 100644
--- a/auto_round/script/llm.py
+++ b/auto_round/script/llm.py
@@ -28,10 +28,9 @@
import os
import re
import argparse
-
+os.environ["CUBLAS_WORKSPACE_CONFIG"] = ":4096:8"
from auto_round.utils import detect_device, get_fp_layer_names
-
class BasicArgumentParser(argparse.ArgumentParser):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
@@ -158,6 +157,9 @@ class BasicArgumentParser(argparse.ArgumentParser):
self.add_argument("--disable_act_dynamic", action='store_true',
help="activation static quantization")
+
+ self.add_argument("--disable_deterministic_algorithms", action='store_true',
+ help="disable torch deterministic algorithms.")
self.add_argument("--device_map", default=None, type=str,
help="device_map for block in tuning phase")
@@ -331,7 +333,7 @@ def tune(args):
if "marlin" in args.format and args.asym is True:
assert False, "marlin backend only supports sym quantization, please remove --asym"
- ##must set this before import torch
+ ## must set this before import torch
devices = args.device.replace(" ", "").split(',')
use_auto_mapping = False
if all(s.isdigit() for s in devices):
@@ -357,10 +359,12 @@ def tune(args):
elif args.device == "auto":
use_auto_mapping = True
- os.environ["CUBLAS_WORKSPACE_CONFIG"] = ":4096:8"
-
import torch
- torch.use_deterministic_algorithms(True, warn_only=True)
+ if not args.disable_deterministic_algorithms:
+ torch.use_deterministic_algorithms(True, warn_only=True)
+ print("'torch.use_deterministic_algorithms' is turned on by default for reproducibility, "\
+ "and can be turned off by setting the '--disable_deterministic_algorithms' parameter.")
+
model_name = args.model
if model_name[-1] == "/":
@@ -489,6 +493,7 @@ def tune(args):
if not awq_supported:
logger.warning(f"The AutoAWQ format may not be supported due to {info}")
+
autoround = round(
model, tokenizer, args.bits, args.group_size, sym=not args.asym, batch_size=args.batch_size,
dataset=args.dataset, seqlen=seqlen, nblocks=args.nblocks, iters=args.iters, lr=args.lr,
diff --git a/auto_round/script/mllm.py b/auto_round/script/mllm.py
index 883cb9a6a..f7c30e8d1 100644
--- a/auto_round/script/mllm.py
+++ b/auto_round/script/mllm.py
@@ -16,17 +16,12 @@ import os
import sys
import argparse
import json
-
-import torch
import transformers
-
-os.environ["CUBLAS_WORKSPACE_CONFIG"] = ":4096:8"
-torch.use_deterministic_algorithms(True, warn_only=True)
from transformers import AutoModelForCausalLM, AutoTokenizer, AutoConfig, AutoProcessor
from auto_round.utils import detect_device, get_fp_layer_names
from auto_round.utils import logger
-
+os.environ["CUBLAS_WORKSPACE_CONFIG"] = ":4096:8"
class BasicArgumentParser(argparse.ArgumentParser):
def __init__(self, *args, **kwargs):
@@ -141,6 +136,9 @@ class BasicArgumentParser(argparse.ArgumentParser):
self.add_argument("--enable_torch_compile", default=None, type=bool,
help="whether to enable torch compile")
+
+ self.add_argument("--disable_deterministic_algorithms", action='store_true',
+ help="disable torch deterministic algorithms.")
## ======================= VLM =======================
self.add_argument("--quant_nontext_module", action='store_true',
@@ -236,7 +234,7 @@ def setup_lmeval_parser():
def tune(args):
if args.format is None:
args.format = "auto_round"
- supported_formats = ["auto_round", "auto_round:auto_gptq", "auto_round:auto_awq", "auto_awq"]
+ supported_formats = ["auto_round", "auto_round:auto_gptq", "auto_round:auto_awq", "auto_awq", "fake"]
if not args.quant_nontext_module:
supported_formats.extend(["auto_gptq", "auto_gptq:marlin"])
@@ -249,7 +247,8 @@ def tune(args):
if model_name[-1] == "/":
model_name = model_name[:-1]
logger.info(f"start to quantize {model_name}")
-
+
+ ## must set this before import torch
devices = args.device.replace(" ", "").split(',')
use_auto_mapping = False
@@ -276,6 +275,11 @@ def tune(args):
elif args.device == "auto":
use_auto_mapping = True
+ import torch
+ if not args.disable_deterministic_algorithms:
+ torch.use_deterministic_algorithms(True, warn_only=True)
+ print("'torch.use_deterministic_algorithms' is turned on by default for reproducibility, "\
+ "and can be turned off by setting the '--disable_deterministic_algorithms' parameter.")
device_str = detect_device(devices[0])
torch_dtype = "auto"
@@ -532,3 +536,4 @@ def lmms_eval(args):
apply_chat_template=False,
)
return results
+
diff --git a/test/requirements.txt b/test/requirements.txt
new file mode 100644
index 000000000..3b0b45391
--- /dev/null
+++ b/test/requirements.txt
@@ -0,0 +1,2 @@
+addict
+modelscope
diff --git a/test/test_calib_dataset.py b/test/test_calib_dataset.py
index 291d535c3..cfa368bbc 100644
--- a/test/test_calib_dataset.py
+++ b/test/test_calib_dataset.py
@@ -88,6 +88,14 @@ class TestLocalCalibDataset(unittest.TestCase):
self.model, self.tokenizer, bits=bits, group_size=group_size, sym=sym, iters=2, seqlen=128, dataset=dataset
)
autoround.quantize()
+
+ def test_pile_val_backup_dataset(self):
+ dataset = "swift/pile-val-backup"
+ bits, group_size, sym = 4, 128, True
+ autoround = AutoRound(
+ self.model, self.tokenizer, bits=bits, group_size=group_size, sym=sym, iters=2, seqlen=128, dataset=dataset
+ )
+ autoround.quantize()
@classmethod
def tearDownClass(self):
@@ -97,3 +105,4 @@ class TestLocalCalibDataset(unittest.TestCase):
if __name__ == "__main__":
unittest.main()
+