PTQ-Level Efficiency, QAT-Level Accuracy | 训练后量化的效率,量化感知训练的精度
remove non-essential requirements (#1103)
Heng Guo36749155bf17
diff --git a/auto_round/__main__.py b/auto_round/__main__.pyindex 496be3da1..c468f716d 100644--- a/auto_round/__main__.py+++ b/auto_round/__main__.py@@ -470,6 +470,13 @@ def tune(args):if args.eval_bs is None:args.eval_bs = "auto"from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer+ from transformers.utils.versions import require_version++ if args.tasks is not None:+ require_version(+ "lm_eval>=0.4.2",+ "lm-eval is required for evaluation, please install it with `pip install 'lm-eval>=0.4.2'`",+ )from auto_round.utils import detect_device, get_library_version, loggerdiff --git a/auto_round/compressors/base.py b/auto_round/compressors/base.pyindex 8bf788c24..54d656b29 100644--- a/auto_round/compressors/base.py+++ b/auto_round/compressors/base.py@@ -739,7 +739,15 @@ class BaseCompressor(object):elif format_ != "fake":has_besides_gguf = Trueif has_gguf and has_besides_gguf:- raise ValueError("Gguf format is not compatible with other formats, please choose only one of them")+ raise ValueError("GGUF format is not compatible with other formats, please choose only one of them")+ if has_gguf:+ from transformers.utils.versions import require_version++ require_version(+ "sentencepiece",+ "GGUF format requires SentencePiece to be installed. "+ "Please install it with `pip install sentencepiece`",+ )if has_gguf and self.iters != 0 and self.bits != 3 and not self.enable_alg_ext:logger.warning("`iters=0` is recommended when exporting to current GGUF format"diff --git a/auto_round/compressors/diffusion/eval.py b/auto_round/compressors/diffusion/eval.pyindex 5baed978b..226054f4f 100644--- a/auto_round/compressors/diffusion/eval.py+++ b/auto_round/compressors/diffusion/eval.py@@ -17,7 +17,6 @@ import osimport numpy as npimport torch-from PIL import Imagefrom tqdm import tqdmfrom auto_round.compressors.diffusion.dataset import get_diffusion_dataloader@@ -25,6 +24,7 @@ from auto_round.utils import LazyImportmetrics = LazyImport("torchmetrics.multimodal")reward = LazyImport("ImageReward")+Image = LazyImport("PIL.Image")def compute_clip(prompts, images, device: str = "cuda"):@@ -107,6 +107,6 @@ def diffusion_eval(for metric in metrics:result.update(metric_map[metric](prompt_list, image_list, pipe.device))- import tabulate+ import tabulate # pylint: disable=E0401print(tabulate.tabulate(result.items(), tablefmt="grid"))diff --git a/auto_round/compressors/mllm/compressor.py b/auto_round/compressors/mllm/compressor.pyindex 6379ac341..c6808eeb0 100644--- a/auto_round/compressors/mllm/compressor.py+++ b/auto_round/compressors/mllm/compressor.py@@ -12,6 +12,7 @@# See the License for the specific language governing permissions and# limitations under the License.+import importlib.utilimport tracebackfrom copy import deepcopyfrom typing import Union@@ -182,6 +183,13 @@ class MLLMCompressor(BaseCompressor):self.model = modelquant_nontext_module = self._check_quant_nontext(layer_config, quant_nontext_module)+ if quant_nontext_module:+ from transformers.utils.versions import require_version++ require_version(+ "pillow",+ "pillow is required for quantizing non-text modules, please install it with `pip install pillow`",+ )all_blocks = get_block_names(model, quant_nontext_module)self.quant_block_list = find_matching_blocks(model, all_blocks, to_quant_block_names)if to_quant_block_names is None:diff --git a/auto_round/compressors/mllm/eval.py b/auto_round/compressors/mllm/eval.pyindex d9e7bdeaf..339bb0fd7 100644--- a/auto_round/compressors/mllm/eval.py+++ b/auto_round/compressors/mllm/eval.py@@ -317,7 +317,7 @@ def mllm_eval(if len(eval_results) < len(eval_results.columns):eval_results = eval_results.Ttry:- import tabulate+ import tabulate # pylint: disable=E0401logger.info("\n" + tabulate.tabulate(eval_results))except:diff --git a/auto_round/compressors/mllm/utils.py b/auto_round/compressors/mllm/utils.pyindex 39256f704..e8535666c 100644--- a/auto_round/compressors/mllm/utils.py+++ b/auto_round/compressors/mllm/utils.py@@ -19,7 +19,7 @@ import requestsfrom auto_round.utils import LazyImportPIL = LazyImport("PIL")-from PIL import Image # pylint: disable=E0401+Image = LazyImport("PIL.Image")VISUAL_KEYS = ["thinker",diff --git a/auto_round/eval/eval_cli.py b/auto_round/eval/eval_cli.pyindex 66cebf71d..0e31209ad 100644--- a/auto_round/eval/eval_cli.py+++ b/auto_round/eval/eval_cli.py@@ -12,9 +12,12 @@# See the License for the specific language governing permissions and# limitations under the License.import argparse+import importlib.utilimport osimport time+from transformers.utils.versions import require_version+from auto_round.utils import (clear_memory,get_device_and_parallelism,@@ -141,6 +144,10 @@ def _eval_init(tasks, model_path, device, disable_trust_remote_code=False, dtypedef eval(args):+ require_version(+ "lm_eval>=0.4.2", "lm-eval is required for evaluation, please install it with `pip install 'lm-eval>=0.4.2'`"+ )+if args.eval_backend == "vllm":assert isinstance(args.model, str), "vllm evaluation only supports model name or path."eval_with_vllm(args)@@ -231,14 +238,18 @@ def eval_task_by_task(mllm=False,add_bos_token=False,):+ require_version(+ "lm_eval>=0.4.2", "lm-eval is required for evaluation, please install it with `pip install 'lm-eval>=0.4.2'`"+ )+set_cuda_visible_devices(device)device_str, parallelism = get_device_and_parallelism(device)# load after _eval_int in order to make sure import torch after set CUDA_VISIBLE_DEVICESimport traceback- from lm_eval import simple_evaluate as lm_simple_evaluate # pylint: disable=E0611- from lm_eval.models.huggingface import HFLM+ from lm_eval import simple_evaluate as lm_simple_evaluate # pylint: disable=E0401+ from lm_eval.models.huggingface import HFLM # pylint: disable=E0401from transformers import AutoModelForCausalLM, AutoTokenizerfrom auto_round.utils import logger@@ -277,7 +288,7 @@ def eval_task_by_task(if batch_size is None or batch_size == "auto":logger.warning("hf-multimodal models does not support auto currently, reset eval_bs to 16")batch_size = 16- from lm_eval.models.hf_vlms import HFMultimodalLM+ from lm_eval.models.hf_vlms import HFMultimodalLM # pylint: disable=E0401hflm = HFMultimodalLM(pretrained=model,@@ -306,7 +317,7 @@ def eval_task_by_task(if isinstance(tasks, str):tasks = tasks.replace(" ", "").split(",")- from lm_eval.utils import make_table # pylint: disable=E0611+ from lm_eval.utils import make_table # pylint: disable=E0401res_all = {}res_keys = ["results", "versions", "n-shot", "higher_is_better"]diff --git a/auto_round/eval/evaluation.py b/auto_round/eval/evaluation.pyindex 515357e2d..90f489ccf 100644--- a/auto_round/eval/evaluation.py+++ b/auto_round/eval/evaluation.py@@ -15,13 +15,13 @@import osfrom typing import Optional, Union-from lm_eval import simple_evaluate as lm_simple_evaluate # pylint: disable=E0611+from lm_eval import simple_evaluate as lm_simple_evaluate # pylint: disable=E0401from auto_round.logger import loggeros.environ["TOKENIZERS_PARALLELISM"] = "false"-from lm_eval.models.huggingface import HFLM+from lm_eval.models.huggingface import HFLM # pylint: disable=E0401def simple_evaluate_user_model(@@ -36,7 +36,7 @@ def simple_evaluate_user_model(**kwargs):if mllm:- from lm_eval.models.hf_vlms import HFMultimodalLM+ from lm_eval.models.hf_vlms import HFMultimodalLM # pylint: disable=E0401if batch_size is None or batch_size == "auto":logger.warning("hf-multimodal models does not support auto currently, reset eval_bs to 16")diff --git a/auto_round/export/export_to_gguf/convert_hf_to_gguf.py b/auto_round/export/export_to_gguf/convert_hf_to_gguf.pyindex c7c327f1b..b823580ce 100644--- a/auto_round/export/export_to_gguf/convert_hf_to_gguf.py+++ b/auto_round/export/export_to_gguf/convert_hf_to_gguf.py@@ -1232,7 +1232,7 @@ class TextModel(ModelBase):special_vocab.add_to_gguf(self.gguf_writer)def _create_vocab_sentencepiece(self):- from sentencepiece import SentencePieceProcessor+ from sentencepiece import SentencePieceProcessor # pylint: disable=E0401tokenizer_path = self.dir_model / "tokenizer.model"@@ -4243,7 +4243,7 @@ class Phi3MiniModel(TextModel):if tokenizer_class == "GPT2Tokenizer":return self._set_vocab_gpt2()- from sentencepiece import SentencePieceProcessor+ from sentencepiece import SentencePieceProcessor # pylint: disable=E0401tokenizer_path = self.dir_model / "tokenizer.model"@@ -4730,8 +4730,8 @@ class InternLM2Model(TextModel):# Copy from _set_vocab_sentencepiece, The only difference is that we will treat the character# \x00 specially and convert it into an emoji character to prevent it from being mistakenly# recognized as an empty string in C++.- from sentencepiece import SentencePieceProcessor- from sentencepiece import sentencepiece_model_pb2 as model+ from sentencepiece import SentencePieceProcessor # pylint: disable=E0401+ from sentencepiece import sentencepiece_model_pb2 as model # pylint: disable=E0401tokenizer_path = self.dir_model / "tokenizer.model"@@ -5064,8 +5064,8 @@ class BertModel(TextModel):# to avoid TypeError: Descriptors cannot be created directly# exception when importing sentencepiece_model_pb2os.environ["PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION"] = "python"- from sentencepiece import SentencePieceProcessor- from sentencepiece import sentencepiece_model_pb2 as model+ from sentencepiece import SentencePieceProcessor # pylint: disable=E0401+ from sentencepiece import sentencepiece_model_pb2 as model # pylint: disable=E0401tokenizer_path = self.dir_model / "sentencepiece.bpe.model"@@ -6756,7 +6756,7 @@ class ArcticModel(TextModel):# The reason for using a custom implementation here is that the# snowflake-arctic-instruct model redefined tokens 31998 and 31999 from# tokenizer.model and used them as BOS and EOS instead of adding new tokens.- from sentencepiece import SentencePieceProcessor+ from sentencepiece import SentencePieceProcessor # pylint: disable=E0401tokenizer_path = self.dir_model / "tokenizer.model"@@ -7246,8 +7246,8 @@ class T5Model(TextModel):# to avoid TypeError: Descriptors cannot be created directly# exception when importing sentencepiece_model_pb2os.environ["PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION"] = "python"- from sentencepiece import SentencePieceProcessor- from sentencepiece import sentencepiece_model_pb2 as model+ from sentencepiece import SentencePieceProcessor # pylint: disable=E0401+ from sentencepiece import sentencepiece_model_pb2 as model # pylint: disable=E0401tokenizer_path = self.dir_model / "tokenizer.model"@@ -7381,8 +7381,8 @@ class T5EncoderModel(TextModel):# to avoid TypeError: Descriptors cannot be created directly# exception when importing sentencepiece_model_pb2os.environ["PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION"] = "python"- from sentencepiece import SentencePieceProcessor- from sentencepiece import sentencepiece_model_pb2 as model+ from sentencepiece import SentencePieceProcessor # pylint: disable=E0401+ from sentencepiece import sentencepiece_model_pb2 as model # pylint: disable=E0401tokenizer_path = self.dir_model / "tokenizer.model"diff --git a/auto_round/utils/model.py b/auto_round/utils/model.pyindex 1c2fc7987..20cbc3934 100644--- a/auto_round/utils/model.py+++ b/auto_round/utils/model.py@@ -240,6 +240,20 @@ def download_hf_model(repo_id, cache_dir=None, repo_type=None, revision=None):return model_path+def _check_accelerate_version():+ from auto_round.utils.common import get_library_version++ accelerate_version = get_library_version("accelerate")+ from packaging.version import Version++ if Version(accelerate_version) > Version("1.5.1") and Version(accelerate_version) < Version("1.10.0"):+ logger.warning(+ f"Detected accelerate version {accelerate_version}. "+ "Versions between 1.5.1 and 1.10.0 may cause high RAM usage during model loading. "+ "It is recommended to upgrade to version 1.10.0 or above."+ )++def llm_load_model(pretrained_model_name_or_path: str,platform: str = "hf",@@ -254,6 +268,9 @@ def llm_load_model(], "current only support hf or model_scope platform to load pretrained model."if platform.lower() == "model_scope" and not envs.AR_USE_MODELSCOPE:envs.set_config(AR_USE_MODELSCOPE=True)++ _check_accelerate_version()+if platform == "model_scope":from modelscope import AutoModel, AutoModelForCausalLM, AutoTokenizer # pylint: disable=E0401else:@@ -336,6 +353,8 @@ def mllm_load_model():from auto_round.special_model_handler import MISTRAL_3_2_MODELS+ _check_accelerate_version()+assert platform.lower() in ["hf","model_scope",@@ -485,6 +504,8 @@ def diffusion_load_model(from auto_round.utils.common import LazyImportfrom auto_round.utils.device import get_device_and_parallelism+ _check_accelerate_version()+if platform != "hf":raise NotImplementedError(f"auto_round current only support hf as platform for diffusion model, but get {platform}"diff --git a/requirements.txt b/requirements.txtindex 2c9f8ac53..4f348bfdc 100644--- a/requirements.txt+++ b/requirements.txt@@ -1,13 +1,10 @@# 1.5.1<accelerate<1.10.0 may cause potentially high RAM usage; versions 1.10.0 or above are recommended.acceleratedatasets-py-cpuinfo-sentencepiecenumpy-tqdm-packaging-pillow-torch-transformers>=4.38+# packaging # for python version <= 3.9+py-cpuinfothreadpoolctl-lm-eval>=0.4.2,<0.5\ No newline at end of file+torch+tqdm+transformers>=4.38\ No newline at end of filediff --git a/test/test_cpu/requirements.txt b/test/test_cpu/requirements.txtindex d6f2c49d6..302574935 100644--- a/test/test_cpu/requirements.txt+++ b/test/test_cpu/requirements.txt@@ -1,8 +1,11 @@addictmodelscopegguf+sentencepiecetorchvisionparameterized+pillownumba#TODO: (yiliu30) replace it with the release version-llmcompressor @ git+https://github.com/vllm-project/llm-compressor.git@7b28d78\ No newline at end of file+llmcompressor @ git+https://github.com/vllm-project/llm-compressor.git@7b28d78+lm_eval\ No newline at end of file