PTQ-Level Efficiency, QAT-Level Accuracy | 训练后量化的效率,量化感知训练的精度
eval for MLLMs (#296)
n1ck-guo4384914e2894
diff --git a/auto_round/__main__.py b/auto_round/__main__.pyindex 461811d22..839448adb 100644--- a/auto_round/__main__.py+++ b/auto_round/__main__.py@@ -11,557 +11,41 @@# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.--import os-import re-import argparse--import torch-import transformers--os.environ["CUBLAS_WORKSPACE_CONFIG"] = ":4096:8"-torch.use_deterministic_algorithms(True, warn_only=True)-from transformers import AutoModelForCausalLM, AutoTokenizer, AutoModel, AutoConfig, AutoProcessor-from lm_eval.utils import make_table # pylint: disable=E0401--from auto_round import AutoRoundConfig-from auto_round.eval.evaluation import simple_evaluate-from auto_round.utils import detect_device, get_library_version, detect_device_count-from auto_round.utils import logger--class BasicArgumentParser(argparse.ArgumentParser):- def __init__(self, *args, **kwargs):- super().__init__( *args, **kwargs)- self.add_argument("--model", default="facebook/opt-125m", help="model name or path")-- self.add_argument('--eval', action='store_true',- help="whether to use eval only mode.")-- self.add_argument("--bits", default=4, type=int,- help="number of bits")-- self.add_argument("--eval_bs", default=None, type=int,- help="eval batch size")-- self.add_argument("--device", default="auto", type=str,- help="The device to be used for tuning. The default is set to auto/None,"- "allowing for automatic detection."- " Currently, device settings support CPU, GPU, and HPU.")-- self.add_argument("--asym", action='store_true',- help=" asym quantization")-- self.add_argument("--dataset", default="NeelNanda/pile-10k", type=str,- help="The dataset for quantization training. It can be a custom one.")-- self.add_argument("--lr", default=None, type=float,- help="learning rate, if None, it will be set to 1.0/iters automatically")-- self.add_argument("--minmax_lr", default=None, type=float,- help="minmax learning rate, if None,it will beset to be the same with lr")-- self.add_argument("--seed", default=42, type=int,- help="seed")-- self.add_argument("--adam", action='store_true',- help="adam")-- self.add_argument("--gradient_accumulate_steps", default=1, type=int, help="gradient accumulate steps")-- self.add_argument("--nblocks", default=1, type=int, help="num of blocks to tune together")-- self.add_argument("--low_gpu_mem_usage", action='store_true',- help="lower gpu memory usage but 50-100% slower")-- self.add_argument("--format", default=None, type=str,- help="The format in which to save the model. "- "The options are 'auto_round', 'auto_round:gptq','auto_round:awq',"- " 'auto_gptq', 'auto_awq', 'itrex', 'itrex_xpu' and 'fake'."- "default to 'auto_round."- )-- self.add_argument("--data_type", default='int',- help="data type for tuning, 'int', 'mx_fp' and etc.")-- self.add_argument("--scale_dtype", default='fp16',- help="which scale data type to use for quantization, 'fp16', 'fp32' or 'bf16'.")-- self.add_argument("--tasks",- default="lambada_openai,hellaswag,winogrande,piqa,mmlu,wikitext,truthfulqa_mc1," \- "truthfulqa_mc2,openbookqa,boolq,rte,arc_easy,arc_challenge",- help="lm-eval tasks for lm_eval version 0.4")-- self.add_argument("--output_dir", default="./tmp_autoround", type=str,- help="Where to store the final model.")-- self.add_argument("--disable_eval", action='store_true',- help="Whether to do lm-eval evaluation after tuning.")-- self.add_argument("--disable_amp", action='store_true',- help="disable amp")-- self.add_argument("--disable_minmax_tuning", action='store_true',- help="whether disable enable weight minmax tuning")-- self.add_argument("--enable_norm_bias_tuning", action='store_true',- help="whether enable norm bias tuning")-- self.add_argument("--disable_trust_remote_code", action='store_true',- help="Whether to disable trust_remote_code")-- self.add_argument("--disable_quanted_input", action='store_true',- help="whether to disuse the output of quantized block to tune the next block")-- self.add_argument("--quant_lm_head", action='store_true',- help="quant_lm_head")-- self.add_argument("--low_cpu_mem_mode", default=0, type=int,- help="Choose which low cpu memory mode to use. "- "Can significantly reduce cpu memory footprint but cost more time."- "1 means choose block-wise mode, load the weights of each block"- " from disk when tuning and release the memory of the block after tuning."- "2 means choose layer-wise mode, load the weights of each layer from disk when tuning,"- " minimum memory consumption and also slowest running speed."- "others means not use low cpu memory. Default to 0, not use low cpu memory.")-- self.add_argument("--low_cpu_mem_tmp_dir", default=None, type=str,- help="temp work space to store the temporary files "- "when using low cpu memory mode. Will remove after tuning.")-- self.add_argument("--model_dtype", default=None, type=str,- help="force to convert the dtype, some backends supports fp16 dtype better")-- self.add_argument("--act_bits", default=32, type=int,- help="activation bits")-- self.add_argument("--fp_layers_list", default="", type=str,- help="List of Layers to maintain original data type")-- ## ======================= VLM =======================- self.add_argument("--mllm", action='store_true',- help="To determine whether use multimodel-llm mode.")-- self.add_argument("--quant_nontext_module", action='store_true',- help="To determine whether the quantization should handle vision component.")-- self.add_argument("--extra_data_dir", default="", type=str,- help="Dataset dir for storing images/audio/videos. "- "Can be a dir path or multiple dir path with format as "- "'image=path_to_image,video=path_to_video,audio=path_to_audio'"- "By default, it will search in the relative path.")-- self.add_argument("--template", default=None, type=str,- help="The template for building training dataset. It can be a custom one.")---def setup_parser():- parser = BasicArgumentParser()-- parser.add_argument("--group_size", default=128, type=int,- help="group size")-- parser.add_argument("--batch_size", default=8, type=int,- help="train batch size")-- parser.add_argument("--iters", default=200, type=int,- help=" iters")-- parser.add_argument("--seqlen", default=2048, type=int,- help="sequence length")-- parser.add_argument("--nsamples", default=128, type=int,- help="number of samples")-- args = parser.parse_args()- return args--def setup_best_parser():- parser = BasicArgumentParser()-- parser.add_argument("--group_size", default=128, type=int,- help="group size")-- parser.add_argument("--batch_size", default=8, type=int,- help="train batch size")-- parser.add_argument("--iters", default=1000, type=int,- help=" iters")-- parser.add_argument("--seqlen", default=2048, type=int,- help="sequence length")-- parser.add_argument("--nsamples", default=512, type=int,- help="number of samples")-- args = parser.parse_args()- args.low_gpu_mem_usage = True-- return args--def setup_fast_parser():- parser = BasicArgumentParser()-- parser.add_argument("--group_size", default=128, type=int,- help="group size")-- parser.add_argument("--batch_size", default=4, type=int,- help="train batch size")-- parser.add_argument("--iters", default=200, type=int,- help=" iters")-- parser.add_argument("--seqlen", default=512, type=int,- help="sequence length")-- parser.add_argument("--nsamples", default=128, type=int,- help="number of samples")-- args = parser.parse_args()-- return args--def tune(args):- tasks = args.tasks- if args.format is None:- args.format = "auto_round"- if "auto_gptq" in args.format and args.asym is True:- print(- "warning: The auto_gptq kernel has issues with asymmetric quantization. "- "It is recommended to use sym quantization or --format='auto_round'")-- if "marlin" in args.format and args.asym is True:- assert False, "marlin backend only supports sym quantization, please remove --asym"-- model_name = args.model- if model_name[-1] == "/":- model_name = model_name[:-1]- logger.info(f"start to quantize {model_name}")-- device_str = detect_device(args.device)- torch_dtype = "auto"- if "hpu" in device_str:- torch_dtype = torch.bfloat16-- is_glm = bool(re.search("chatglm", model_name.lower()))- low_cpu_mem_usage = False-- tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=not args.disable_trust_remote_code)-- model_cls = AutoModel if is_glm else AutoModelForCausalLM-- if args.low_cpu_mem_tmp_dir is None:- args.low_cpu_mem_tmp_dir = os.path.join(args.output_dir, "low_cpu_mem_tmp")- if args.low_cpu_mem_mode == 2:- from auto_round.low_cpu_mem.utils import load_model_with_hooks- model = load_model_with_hooks(- model_name,- model_cls,- device=device_str,- clean_weight=True,- saved_path=args.low_cpu_mem_tmp_dir,- torch_dtype=torch_dtype,- trust_remote_code=not args.disable_trust_remote_code- )- elif args.low_cpu_mem_mode == 1:- from auto_round.low_cpu_mem.utils import load_empty_model- low_cpu_mem_usage = True- model = load_empty_model(- model_name,- model_cls,- device=device_str,- saved_path=args.low_cpu_mem_tmp_dir,- torch_dtype=torch_dtype,- trust_remote_code=not args.disable_trust_remote_code- )- else:- if detect_device_count() > 1:- model = model_cls.from_pretrained(- model_name, low_cpu_mem_usage=True, torch_dtype=torch_dtype,- trust_remote_code=not args.disable_trust_remote_code, device_map="auto"- )- else:- model = model_cls.from_pretrained(- model_name, low_cpu_mem_usage=True, torch_dtype=torch_dtype,- trust_remote_code=not args.disable_trust_remote_code- )-- from auto_round import AutoRound, AutoRoundAdam-- model = model.eval()- # align with GPTQ to eval ppl- seqlen = args.seqlen- if "opt" in model_name:- seqlen = model.config.max_position_embeddings- model.seqlen = model.config.max_position_embeddings- else:- seqlen = 2048-- if args.model_dtype != None:- if args.model_dtype == "float16" or args.model_dtype == "fp16":- model = model.to(torch.float16)- if args.model_dtype == "bfloat16" or args.model_dtype == "bfp16":- model = model.to(torch.bfloat16)--- if hasattr(tokenizer, "model_max_length"):- if tokenizer.model_max_length < seqlen:- logger.info(- f"change sequence length to {tokenizer.model_max_length} due to the limitation of model_max_length")- seqlen = min(seqlen, tokenizer.model_max_length)- args.seqlen = seqlen-- if "bloom" in model_name:- args.low_gpu_mem_usage = False-- round = AutoRound- if args.adam:- round = AutoRoundAdam-- layer_config = {}- for n, m in model.named_modules():- if isinstance(m, torch.nn.Linear) or isinstance(m, transformers.modeling_utils.Conv1D):- if m.weight.shape[0] % 32 != 0 or m.weight.shape[1] % 32 != 0:- layer_config[n] = {"bits": 32}- logger.info(- f"{n} will not be quantized due to its shape not being divisible by 32,"- " resulting in an exporting issue to autogptq")- fp_layers_list = args.fp_layers_list.split(",")- if bool(fp_layers_list):- for n, m in model.named_modules():- if isinstance(m, torch.nn.Linear) or isinstance(m, transformers.modeling_utils.Conv1D):- name = n.split('.')[-1]- if n in fp_layers_list or name in fp_layers_list:- layer_config[n] = {"bits": 32}- logger.info(- f"{n} will not be quantized.")- 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(- f"reset `quant_lm_head` to `False` as quantizing lm_head with tied weights has not been "- f"supported currently")- break- if args.quant_lm_head:- layer_config[lm_head_layer_name] = {"bits": args.bits}- transformers_version = [int(item) for item in transformers.__version__.split('.')[:2]]- if transformers_version[0] == 4 and transformers_version[1] < 38:- error_message = "Please upgrade transformers>=4.38.0 to support lm-head quantization."- raise EnvironmentError(error_message)-- 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,- minmax_lr=args.minmax_lr, enable_quanted_input=not args.disable_quanted_input,- device=device_str, amp=not args.disable_amp, nsamples=args.nsamples, seed=args.seed,- low_gpu_mem_usage=args.low_gpu_mem_usage, scale_dtype=args.scale_dtype,- gradient_accumulate_steps=args.gradient_accumulate_steps, layer_config=layer_config,- enable_minmax_tuning=not args.disable_minmax_tuning, act_bits=args.act_bits,- low_cpu_mem_usage=low_cpu_mem_usage, data_type=args.data_type,- enable_norm_bias_tuning=args.enable_norm_bias_tuning)- model, _ = autoround.quantize()- model_name = args.model.rstrip("/")- if args.low_cpu_mem_mode == 1 or args.low_cpu_mem_mode == 2:- import shutil- shutil.rmtree(args.low_cpu_mem_tmp_dir, ignore_errors=True)-- model.eval()- if "cpu" not in device_str:- torch.cuda.empty_cache()-- export_dir = args.output_dir + "/" + model_name.split('/')[-1] + f"-w{args.bits}g{args.group_size}"-- format_list = args.format.replace(' ', '').split(',')- inplace = False if len(format_list) > 1 else True- for format_ in format_list:- save_format_ = format_.replace(":", "-")- save_format_ = save_format_.replace("_", "-")- eval_folder = f'{export_dir}-{save_format_}'- autoround.save_quantized(eval_folder, format=format_, inplace=inplace)-- lm_eval_version = get_library_version("lm-eval")-- if isinstance(tasks, str):- tasks = tasks.split(',')-- if not args.disable_eval:- logger.info(f"Using lm-eval version {lm_eval_version}")- model_args = f"pretrained={eval_folder}"- model_args = model_args + f",trust_remote_code={not args.disable_trust_remote_code}"- if args.act_bits <= 8:- if hasattr(model, "hf_device_map") and len(model.hf_device_map) > 1:- from accelerate.big_modeling import dispatch_model-- dispatch_model(model, model.hf_device_map)- user_model = model- else:- user_model = model.to(device_str)- if args.eval_bs == "auto":- args.eval_bs = 16- from auto_round.eval.evaluation import simple_evaluate_user_model- res = simple_evaluate_user_model(user_model, tokenizer, tasks=tasks, batch_size=args.eval_bs)- else:- res = simple_evaluate(model="hf", model_args=model_args,- tasks=tasks,- batch_size=args.eval_bs)- print(make_table(res))---def eval(args):- device_str = detect_device(args.device)- model_args = f"pretrained={args.model},trust_remote_code={not args.disable_trust_remote_code}"- if isinstance(args.tasks, str):- tasks = args.tasks.split(',')- res = simple_evaluate(- model="hf",- model_args=model_args,- tasks=tasks,- device=device_str,- batch_size=args.eval_bs)-- from lm_eval.utils import make_table # pylint: disable=E0401- print(make_table(res))---def tune_mllm(args):- if args.format is None:- args.format = "auto_round"-- if "auto_gptq" in args.format and args.asym is True:- print(- "warning: The auto_gptq kernel has issues with asymmetric quantization. "- "It is recommended to use sym quantization or --format='auto_round'")-- if "marlin" in args.format and args.asym is True:- assert False, "marlin backend only supports sym quantization, please remove --asym"-- model_name = args.model- if model_name[-1] == "/":- model_name = model_name[:-1]- logger.info(f"start to quantize {model_name}")--- device_str = detect_device(args.device)- torch_dtype = "auto"- if "hpu" in device_str:- torch_dtype = torch.bfloat16-- torch.manual_seed(1234)-- # load_model- config = AutoConfig.from_pretrained(model_name, trust_remote_code=not args.disable_trust_remote_code)- tokenizer = AutoTokenizer.from_pretrained(model_name)- processor = AutoProcessor.from_pretrained(model_name, trust_remote_code=not args.disable_trust_remote_code)- tokenizer.processor = processor- model_type = config.model_type- if "qwen2_vl" in model_type:- from transformers import Qwen2VLForConditionalGeneration- cls = Qwen2VLForConditionalGeneration- elif "mllama" in model_type:- from transformers import MllamaForConditionalGeneration- cls = MllamaForConditionalGeneration- else:- cls = AutoModelForCausalLM- model = cls.from_pretrained(- model_name,trust_remote_code=not args.disable_trust_remote_code, torch_dtype=torch_dtype)-- if "cogvlm2" in model_name:- model.config.model_type = "cogvlm2"-- from auto_round import AutoRoundMLLM-- model = model.eval()- seqlen = args.seqlen-- round = AutoRoundMLLM- layer_config = {}- for n, m in model.named_modules():- if isinstance(m, torch.nn.Linear) or isinstance(m, transformers.modeling_utils.Conv1D):- if m.weight.shape[0] % 32 != 0 or m.weight.shape[1] % 32 != 0:- layer_config[n] = {"bits": 32}- logger.info(- f"{n} will not be quantized due to its shape not being divisible by 32,"- " resulting in an exporting issue to autogptq")- 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(- f"warning, disable quant_lm_head as quantizing lm_head with tied weights has not been "- f"supported currently")- break- if args.quant_lm_head:- layer_config[lm_head_layer_name] = {"bits": args.bits}- transformers_version = [int(item) for item in transformers.__version__.split('.')[:2]]- if transformers_version[0] == 4 and transformers_version[1] < 38:- error_message = "Please upgrade transformers>=4.38.0 to support lm-head quantization."- raise EnvironmentError(error_message)-- if args.quant_lm_head and args.low_gpu_mem_usage:- print(f"warning, low_gpu_mem_usage=False is strongly recommended if the whole model could be loaded to "- f"gpu")-- autoround = round(model, tokenizer, dataset=args.dataset, extra_data_dir=args.extra_data_dir,- bits=args.bits, group_size=args.group_size, sym=not args.asym,- batch_size=args.batch_size, seqlen=seqlen, nblocks=args.nblocks, iters=args.iters,- lr=args.lr, minmax_lr=args.minmax_lr, enable_quanted_input=not args.disable_quanted_input,- amp=not args.disable_amp, nsamples=args.nsamples, low_gpu_mem_usage=args.low_gpu_mem_usage,- device=device_str, seed=args.seed, gradient_accumulate_steps=args.gradient_accumulate_steps,- scale_dtype=args.scale_dtype, layer_config=layer_config,- enable_minmax_tuning=not args.disable_minmax_tuning, act_bits=args.act_bits,- quant_nontext_module=args.quant_nontext_module)- model, _ = autoround.quantize()-- model.eval()- if args.device != "cpu":- torch.cuda.empty_cache()-- export_dir = args.output_dir + "/" + model_name.split('/')[-1] + f"-autoround-w{args.bits}g{args.group_size}"-- format_list = args.format.replace(' ', '').split(',')- inplace = False if len(format_list) > 1 else True- for format_ in format_list:- eval_folder = f'{export_dir}-{format_}'- autoround.save_quantized(eval_folder, format=format_, inplace=inplace, processor=processor)-+import sysdef run():+ from .script.llm import setup_parser, tune, evalargs = setup_parser()- if args.eval_bs is None:- args.eval_bs = "auto"if args.eval:eval(args)- elif args.mllm:- tune_mllm(args)else:tune(args)def run_best():+ from .script.llm import setup_best_parser, tuneargs = setup_best_parser()tune(args)def run_fast():+ from .script.llm import setup_fast_parser, tuneargs = setup_fast_parser()tune(args)def run_mllm():+ from .script.mllm import setup_parser, tune, evalargs = setup_parser()- tune_mllm(args)-+ if args.eval:+ eval(args)+ else:+ tune(args)-if __name__ == '__main__':- run()+def switch():+ if "--mllm" in sys.argv:+ sys.argv.remove("--mllm")+ run_mllm()+ else:+ run()+if __name__ == '__main__':+ switch()diff --git a/auto_round/autoround.py b/auto_round/autoround.pyindex 34cf036de..513bde7c5 100644--- a/auto_round/autoround.py+++ b/auto_round/autoround.py@@ -29,7 +29,7 @@ from .special_model_handler import (check_hidden_state_dim,shareable_keywords,special_model_init,reset_params,- skip_keywards_hint+ check_skippable_keywords)from .utils import (CpuInfo,@@ -745,8 +745,8 @@ class AutoRound(object):self.inputs[name][key] = kwargs[key]else:# Parameters not to be cached- if skip_keywards_hint(key):- logger.warning_once(f"Please note that this '{key}' key" \+ if check_skippable_keywords(key):+ logger.warning_once(f"Please note that '{key}' key" \" is not currently used in quantization fine-tuning.")reset_params(self.inputs[name])if name == self.last_cache_name:diff --git a/auto_round/mllm/__init__.py b/auto_round/mllm/__init__.pyindex 800309207..f42a4f485 100644--- a/auto_round/mllm/__init__.py+++ b/auto_round/mllm/__init__.py@@ -14,4 +14,6 @@from .mllm_dataset import get_mllm_dataloaderfrom .template import Template, get_template, TEMPLATES-from .autoround_mllm import AutoRoundMLLM\ No newline at end of file+from .autoround_mllm import AutoRoundMLLM+from ..utils import LazyImport+from .eval import mllm_eval\ No newline at end of filediff --git a/auto_round/mllm/eval.py b/auto_round/mllm/eval.pynew file mode 100644index 000000000..8506b089f--- /dev/null+++ b/auto_round/mllm/eval.py@@ -0,0 +1,274 @@+# Copyright (c) 2024 Intel Corporation+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.++# Copyright 2023 VLMEvalKit Authors.+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.++import os+import json+from functools import partial++import pandas as pd+from ..utils import logger, LazyImport+vlmeval = LazyImport("vlmeval")+++MODEL_TYPE_TO_VLMEVAL_MODEL = {+ #model_name+ "Qwen-VL": dict(cls="QwenVL"),+ "Qwen-VL-Chat": dict(cls="QwenVLChat"),+ "Qwen2-VL": dict(cls="Qwen2VLChat", min_pixels=1280*28*28, max_pixels=16384*28*28),+ "Llama-3.2": dict(cls="llama_vision"),+ "Phi-3-vision": dict(cls="Phi3Vision"),+ "Phi-3.5-vision": dict(cls="Phi3_5Vision"),+ "llava_v1.5": dict(cls="LLaVA"),+ "llava_v1.6": dict(cls="LLaVA_Next"),+ "llava-onevision-qwen2": dict(cls="LLaVA_OneVision"),+ "cogvlm2": dict(cls="CogVlm"),+ "SliME": dict(cls="SliME"),+ "Eagle": dict(cls="Eagle"),+ "Molmo": dict(cls="molmo"),++ # config.model_type+ "qwen2_vl": dict(cls="Qwen2VLChat", min_pixels=1280*28*28, max_pixels=16384*28*28),+ "qwen": dict(cls="QwenVL"),+ "qwen_chat": dict(cls="QwenVLChat"),+ "llava": dict(cls="LLaVA"),+ "llava_next": dict(cls="LLaVA_Next"),+ "phi3_v": dict(cls="Phi3Vision"),+ "mllama": dict(cls="llama_vision"),+}++def mllm_eval(+ pretrained_model_name_or_path: str,+ work_dir: str,+ dataset: list,+ data_store_dir: None,+ pack: bool = False,+ use_subtitle: bool = False,+ fps: float = -1,+ nframe: int = 8,+ rerun: bool = False,+ judge: bool = False,+ verbose: bool = False,+ mode: str = 'all',+ ignore: bool = False+ ):++ try:+ from auto_round import AutoRoundConfig+ except:+ from auto_round.auto_quantizer import AutoHfQuantizer++ model = None+ if data_store_dir is not None:+ os.environ['LMUData'] = data_store_dir++ model_name = pretrained_model_name_or_path+ if "/" in model_name:+ model_name = model_name[:-1] if model_name[-1] == "/" else model_name+ model_name = model_name.split("/")[-1]++ if model_name in MODEL_TYPE_TO_VLMEVAL_MODEL:+ model_type = model_name+ else:+ model_type = None+ split_name = model_name.split("-")+ for i in range(len(split_name), 0, -1):+ tmp = "-".join(split_name[0:i])+ if tmp in MODEL_TYPE_TO_VLMEVAL_MODEL:+ model_type = tmp+ break+ if model_type is None:+ from transformers import AutoConfig+ config = AutoConfig.from_pretrained(pretrained_model_name_or_path, trust_remote_code=True)+ model_type = config.model_type+ if "chat" in model_name.lower():+ model_type += "_chat"++ kwargs = MODEL_TYPE_TO_VLMEVAL_MODEL[model_type]+ kwargs["model_path"] = pretrained_model_name_or_path+ model_cls = kwargs.pop("cls")+ model_cls = getattr(vlmeval.vlm, model_cls)+ vlmeval.config.supported_VLM[model_name] = partial(model_cls, verbose=verbose, **kwargs)++ pred_root = os.path.join(work_dir, model_name)+ os.makedirs(pred_root, exist_ok=True)++ for dataset_name in dataset:+ try:+ dataset_kwargs = {}+ if dataset_name in ['MMLongBench_DOC', 'DUDE', 'DUDE_MINI', 'SLIDEVQA', 'SLIDEVQA_MINI']:+ dataset_kwargs['model'] = model_name+ if dataset_name == 'MMBench-Video':+ dataset_kwargs['pack'] = pack+ if dataset_name == 'Video-MME':+ dataset_kwargs['use_subtitle'] = use_subtitle++ dataset = vlmeval.dataset.build_dataset(dataset_name, **dataset_kwargs)+ if dataset is None:+ logger.error(f'Dataset {dataset_name} is not valid, will be skipped. ')+ continue++ result_file = f'{pred_root}/{model_name}_{dataset_name}.xlsx'+ if fps > 0: # For Video Dataset, set the fps for priority+ if dataset_name == 'MVBench':+ raise ValueError('MVBench does not support fps setting, please transfer to MVBench_MP4!')+ nframe = 0+ if dataset_name in ['MMBench-Video']:+ packstr = 'pack' if pack else 'nopack'+ if nframe > 0:+ result_file = f'{pred_root}/{model_name}_{dataset_name}_{nframe}frame_{packstr}.xlsx'+ else:+ result_file = f'{pred_root}/{model_name}_{dataset_name}_{fps}fps_{packstr}.xlsx'+ elif dataset.MODALITY == 'VIDEO':+ if pack:+ logger.info(f'{dataset_name} not support Pack Mode, directly change to unpack')+ pack = False+ packstr = 'pack' if pack else 'nopack'+ if nframe > 0:+ result_file = f'{pred_root}/{model_name}_{dataset_name}_{nframe}frame_{packstr}.xlsx'+ else:+ result_file = f'{pred_root}/{model_name}_{dataset_name}_{fps}fps_{packstr}.xlsx'+ if dataset_name in ['Video-MME']:+ subtitlestr = 'subs' if use_subtitle else 'nosubs'+ result_file = result_file.replace('.xlsx', f'_{subtitlestr}.xlsx')++ if dataset.TYPE == 'MT':+ result_file = result_file.replace('.xlsx', '.tsv')++ if os.path.exists(result_file) and rerun:+ import re+ pattern = re.compile(f"{model_name}_{dataset_name}_[(openai)|(gpt)|(auxmatch)].*")+ for file_name in os.listdir(pred_root):+ if pattern.match(file_name):+ os.remove(os.path.join(pred_root, file_name))++ if model is None:+ model = model_name # which is only a name++ # Perform the Inference+ if dataset.MODALITY == 'VIDEO':+ model = vlmeval.inference_video.infer_data_job_video(+ model,+ work_dir=pred_root,+ model_name=model_name,+ dataset=dataset,+ nframe=nframe,+ pack=pack,+ verbose=verbose,+ subtitle=use_subtitle,+ fps=fps)+ elif dataset.TYPE == 'MT':+ model = vlmeval.inference_mt.infer_data_job_mt(+ model,+ work_dir=pred_root,+ model_name=model_name,+ dataset=dataset,+ verbose=verbose,+ ignore_failed=ignore)+ else:+ model = vlmeval.inference.infer_data_job(+ model,+ work_dir=pred_root,+ model_name=model_name,+ dataset=dataset,+ verbose=verbose,+ ignore_failed=ignore)++ # Set the judge kwargs first before evaluation or dumping+ judge_kwargs = {+ 'verbose': verbose,+ }+ if judge is not None:+ judge_kwargs['model'] = judge+ else:+ if dataset.TYPE in ['MCQ', 'Y/N'] or vlmeval.smp.listinstr(['MathVerse'], dataset_name):+ judge_kwargs['model'] = 'chatgpt-0125'+ elif vlmeval.smp.listinstr(['MMVet', 'MathVista', 'LLaVABench', 'MMBench-Video', 'MathVision'],+ dataset_name):+ judge_kwargs['model'] = 'gpt-4-turbo'+ elif vlmeval.smp.listinstr(['MMLongBench', 'MMDU', 'DUDE', 'DUDE_MINI', 'SLIDEVQA', 'SLIDEVQA_MINI'],+ dataset_name):+ judge_kwargs['model'] = 'gpt-4o'+ if 'OPENAI_API_KEY_JUDGE' in os.environ and len(os.environ['OPENAI_API_KEY_JUDGE']):+ judge_kwargs['key'] = os.environ['OPENAI_API_KEY_JUDGE']+ if 'OPENAI_API_BASE_JUDGE' in os.environ and len(os.environ['OPENAI_API_BASE_JUDGE']):+ judge_kwargs['api_base'] = os.environ['OPENAI_API_BASE_JUDGE']++ if dataset_name in ['MMMU_TEST']:+ result_json = vlmeval.utils.result_transfer.MMMU_result_transfer(result_file)+ logger.info(f'Transfer MMMU_TEST result to json for official evaluation, '+ f'json file saved in {result_json}') # noqa: E501+ continue+ elif 'MMT-Bench_ALL' in dataset_name:+ submission_file = vlmeval.utils.result_transfer.MMTBench_result_transfer(result_file, **judge_kwargs)+ logger.info(f'Extract options from prediction of MMT-Bench FULL split for official evaluation '+ f'(https://eval.ai/web/challenges/challenge-page/2328/overview), '+ f'submission file saved in {submission_file}') # noqa: E501+ continue+ elif 'MLLMGuard_DS' in dataset_name:+ logger.info('The evaluation of MLLMGuard_DS is not supported yet. ') # noqa: E501+ continue+ elif 'AesBench_TEST' == dataset_name:+ logger.info(f'The results are saved in {result_file}. '+ f'Please send it to the AesBench Team via [email protected].') # noqa: E501+ continue+ elif dataset_name in ['DocVQA_TEST', 'InfoVQA_TEST', 'Q-Bench1_TEST', 'A-Bench_TEST']:+ logger.info(f'{dataset_name} is a test split without ground-truth. '+ 'Thus only the inference part is supported for those datasets. ') # noqa: E501++ if dataset_name in [+ 'MMBench_TEST_CN', 'MMBench_TEST_EN', 'MMBench', 'MMBench_CN',+ 'MMBench_TEST_CN_V11', 'MMBench_TEST_EN_V11', 'MMBench_V11', 'MMBench_CN_V11'+ ]:+ if not vlmeval.smp.MMBenchOfficialServer(dataset_name):+ logger.error(+ f'Can not evaluate {dataset_name} on non-official servers, '+ 'will skip the evaluation. '+ )+ continue++ if mode == 'all':+ eval_results = dataset.evaluate(result_file, **judge_kwargs)+ if eval_results is not None:+ assert isinstance(eval_results, dict) or isinstance(eval_results, pd.DataFrame)+ logger.info(f'The evaluation of model {model_name} x dataset {dataset_name} has finished! ')+ logger.info('Evaluation Results:')+ if isinstance(eval_results, dict):+ logger.info('\n' + json.dumps(eval_results, indent=4))+ elif isinstance(eval_results, pd.DataFrame):+ if len(eval_results) < len(eval_results.columns):+ eval_results = eval_results.T+ try:+ import tabulate+ logger.info('\n' + tabulate.tabulate(eval_results))+ except:+ logger.info(eval_results.to_string())++ except Exception as e:+ logger.exception(f'Model {model_name} x Dataset {dataset_name} combination failed: {e}, '+ 'skipping this combination.')+ continuediff --git a/auto_round/mllm/utils.py b/auto_round/mllm/utils.pyindex 754e351d6..ce3bcae1f 100644--- a/auto_round/mllm/utils.py+++ b/auto_round/mllm/utils.py@@ -15,6 +15,9 @@import osimport requests+from ..utils import LazyImport++PIL = LazyImport("PIL")from PIL import Image # pylint: disable=E0401diff --git a/auto_round/script/__init__.py b/auto_round/script/__init__.pynew file mode 100644index 000000000..e3fdc07b1--- /dev/null+++ b/auto_round/script/__init__.py@@ -0,0 +1,13 @@+# Copyright (c) 2024 Intel Corporation+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.\ No newline at end of filediff --git a/auto_round/script/llm.py b/auto_round/script/llm.pynew file mode 100644index 000000000..2623592d2--- /dev/null+++ b/auto_round/script/llm.py@@ -0,0 +1,431 @@+# Copyright (c) 2024 Intel Corporation+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.++# Copyright (c) 2024 Intel Corporation+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.++import os+import re+import argparse++import torch+import transformers++os.environ["CUBLAS_WORKSPACE_CONFIG"] = ":4096:8"+torch.use_deterministic_algorithms(True, warn_only=True)+from transformers import AutoModelForCausalLM, AutoTokenizer, AutoModel, AutoConfig, AutoProcessor+from lm_eval.utils import make_table # pylint: disable=E0401++from auto_round import AutoRoundConfig+from auto_round.eval.evaluation import simple_evaluate+from auto_round.utils import detect_device, get_library_version, detect_device_count+from auto_round.utils import logger++class BasicArgumentParser(argparse.ArgumentParser):+ def __init__(self, *args, **kwargs):+ super().__init__( *args, **kwargs)+ self.add_argument("--model", default="facebook/opt-125m", help="model name or path")++ self.add_argument('--eval', action='store_true',+ help="whether to use eval only mode.")++ self.add_argument("--bits", default=4, type=int,+ help="number of bits")++ self.add_argument("--eval_bs", default=None, type=int,+ help="eval batch size")++ self.add_argument("--device", default="auto", type=str,+ help="The device to be used for tuning. The default is set to auto/None,"+ "allowing for automatic detection."+ " Currently, device settings support CPU, GPU, and HPU.")++ self.add_argument("--asym", action='store_true',+ help=" asym quantization")++ self.add_argument("--dataset", default="NeelNanda/pile-10k", type=str,+ help="The dataset for quantization training. It can be a custom one.")++ self.add_argument("--lr", default=None, type=float,+ help="learning rate, if None, it will be set to 1.0/iters automatically")++ self.add_argument("--minmax_lr", default=None, type=float,+ help="minmax learning rate, if None,it will beset to be the same with lr")++ self.add_argument("--seed", default=42, type=int,+ help="seed")++ self.add_argument("--adam", action='store_true',+ help="adam")++ self.add_argument("--gradient_accumulate_steps", default=1, type=int, help="gradient accumulate steps")++ self.add_argument("--nblocks", default=1, type=int, help="num of blocks to tune together")++ self.add_argument("--low_gpu_mem_usage", action='store_true',+ help="lower gpu memory usage but 50-100% slower")++ self.add_argument("--format", default=None, type=str,+ help="The format in which to save the model. "+ "The options are 'auto_round', 'auto_round:gptq','auto_round:awq',"+ " 'auto_gptq', 'auto_awq', 'itrex', 'itrex_xpu' and 'fake'."+ "default to 'auto_round."+ )++ self.add_argument("--data_type", default='int',+ help="data type for tuning, 'int', 'mx_fp' and etc.")++ self.add_argument("--scale_dtype", default='fp16',+ help="which scale data type to use for quantization, 'fp16', 'fp32' or 'bf16'.")++ self.add_argument("--tasks",+ default="lambada_openai,hellaswag,winogrande,piqa,mmlu,wikitext,truthfulqa_mc1," \+ "truthfulqa_mc2,openbookqa,boolq,rte,arc_easy,arc_challenge",+ help="lm-eval tasks for lm_eval version 0.4")++ self.add_argument("--output_dir", default="./tmp_autoround", type=str,+ help="Where to store the final model.")++ self.add_argument("--disable_eval", action='store_true',+ help="Whether to do lm-eval evaluation after tuning.")++ self.add_argument("--disable_amp", action='store_true',+ help="disable amp")++ self.add_argument("--disable_minmax_tuning", action='store_true',+ help="whether disable enable weight minmax tuning")++ self.add_argument("--enable_norm_bias_tuning", action='store_true',+ help="whether enable norm bias tuning")++ self.add_argument("--disable_trust_remote_code", action='store_true',+ help="Whether to disable trust_remote_code")++ self.add_argument("--disable_quanted_input", action='store_true',+ help="whether to disuse the output of quantized block to tune the next block")++ self.add_argument("--quant_lm_head", action='store_true',+ help="quant_lm_head")++ self.add_argument("--low_cpu_mem_mode", default=0, type=int,+ help="Choose which low cpu memory mode to use. "+ "Can significantly reduce cpu memory footprint but cost more time."+ "1 means choose block-wise mode, load the weights of each block"+ " from disk when tuning and release the memory of the block after tuning."+ "2 means choose layer-wise mode, load the weights of each layer from disk when tuning,"+ " minimum memory consumption and also slowest running speed."+ "others means not use low cpu memory. Default to 0, not use low cpu memory.")++ self.add_argument("--low_cpu_mem_tmp_dir", default=None, type=str,+ help="temp work space to store the temporary files "+ "when using low cpu memory mode. Will remove after tuning.")++ self.add_argument("--model_dtype", default=None, type=str,+ help="force to convert the dtype, some backends supports fp16 dtype better")++ self.add_argument("--act_bits", default=32, type=int,+ help="activation bits")++ self.add_argument("--fp_layers_list", default="", type=str,+ help="List of Layers to maintain original data type")++ self.add_argument("--not_use_best_mse", action='store_true',+ help="To determine whether the quantization should handle vision component.")+++def setup_parser():+ parser = BasicArgumentParser()++ parser.add_argument("--group_size", default=128, type=int,+ help="group size")++ parser.add_argument("--batch_size", default=8, type=int,+ help="train batch size")++ parser.add_argument("--iters", default=200, type=int,+ help=" iters")++ parser.add_argument("--seqlen", default=2048, type=int,+ help="sequence length")++ parser.add_argument("--nsamples", default=128, type=int,+ help="number of samples")++ args = parser.parse_args()+ return args++def setup_best_parser():+ parser = BasicArgumentParser()++ parser.add_argument("--group_size", default=128, type=int,+ help="group size")++ parser.add_argument("--batch_size", default=8, type=int,+ help="train batch size")++ parser.add_argument("--iters", default=1000, type=int,+ help=" iters")++ parser.add_argument("--seqlen", default=2048, type=int,+ help="sequence length")++ parser.add_argument("--nsamples", default=512, type=int,+ help="number of samples")++ args = parser.parse_args()+ args.low_gpu_mem_usage = True++ return args++def setup_fast_parser():+ parser = BasicArgumentParser()++ parser.add_argument("--group_size", default=128, type=int,+ help="group size")++ parser.add_argument("--batch_size", default=4, type=int,+ help="train batch size")++ parser.add_argument("--iters", default=200, type=int,+ help=" iters")++ parser.add_argument("--seqlen", default=512, type=int,+ help="sequence length")++ parser.add_argument("--nsamples", default=128, type=int,+ help="number of samples")++ args = parser.parse_args()++ return args++def tune(args):+ tasks = args.tasks+ if args.format is None:+ args.format = "auto_round"+ if "auto_gptq" in args.format and args.asym is True:+ print(+ "warning: The auto_gptq kernel has issues with asymmetric quantization. "+ "It is recommended to use sym quantization or --format='auto_round'")++ if "marlin" in args.format and args.asym is True:+ assert False, "marlin backend only supports sym quantization, please remove --asym"++ model_name = args.model+ if model_name[-1] == "/":+ model_name = model_name[:-1]+ logger.info(f"start to quantize {model_name}")++ device_str = detect_device(args.device)+ torch_dtype = "auto"+ if "hpu" in device_str:+ torch_dtype = torch.bfloat16++ is_glm = bool(re.search("chatglm", model_name.lower()))+ low_cpu_mem_usage = False++ tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=not args.disable_trust_remote_code)++ model_cls = AutoModel if is_glm else AutoModelForCausalLM++ if args.low_cpu_mem_tmp_dir is None:+ args.low_cpu_mem_tmp_dir = os.path.join(args.output_dir, "low_cpu_mem_tmp")+ if args.low_cpu_mem_mode == 2:+ from auto_round.low_cpu_mem.utils import load_model_with_hooks+ model = load_model_with_hooks(+ model_name,+ model_cls,+ device=device_str,+ clean_weight=True,+ saved_path=args.low_cpu_mem_tmp_dir,+ torch_dtype=torch_dtype,+ trust_remote_code=not args.disable_trust_remote_code+ )+ elif args.low_cpu_mem_mode == 1:+ from auto_round.low_cpu_mem.utils import load_empty_model+ low_cpu_mem_usage = True+ model = load_empty_model(+ model_name,+ model_cls,+ device=device_str,+ saved_path=args.low_cpu_mem_tmp_dir,+ torch_dtype=torch_dtype,+ trust_remote_code=not args.disable_trust_remote_code+ )+ else:+ if detect_device_count() > 1:+ model = model_cls.from_pretrained(+ model_name, low_cpu_mem_usage=True, torch_dtype=torch_dtype,+ trust_remote_code=not args.disable_trust_remote_code, device_map="auto"+ )+ else:+ model = model_cls.from_pretrained(+ model_name, low_cpu_mem_usage=True, torch_dtype=torch_dtype,+ trust_remote_code=not args.disable_trust_remote_code+ )++ from auto_round import AutoRound, AutoRoundAdam++ model = model.eval()+ # align with GPTQ to eval ppl+ seqlen = args.seqlen+ if "opt" in model_name:+ seqlen = model.config.max_position_embeddings+ model.seqlen = model.config.max_position_embeddings+ else:+ seqlen = 2048++ if args.model_dtype != None:+ if args.model_dtype == "float16" or args.model_dtype == "fp16":+ model = model.to(torch.float16)+ if args.model_dtype == "bfloat16" or args.model_dtype == "bfp16":+ model = model.to(torch.bfloat16)+++ if hasattr(tokenizer, "model_max_length"):+ if tokenizer.model_max_length < seqlen:+ logger.info(+ f"change sequence length to {tokenizer.model_max_length} due to the limitation of model_max_length")+ seqlen = min(seqlen, tokenizer.model_max_length)+ args.seqlen = seqlen++ if "bloom" in model_name:+ args.low_gpu_mem_usage = False++ round = AutoRound+ if args.adam:+ round = AutoRoundAdam++ layer_config = {}+ for n, m in model.named_modules():+ if isinstance(m, torch.nn.Linear) or isinstance(m, transformers.modeling_utils.Conv1D):+ if m.weight.shape[0] % 32 != 0 or m.weight.shape[1] % 32 != 0:+ layer_config[n] = {"bits": 32}+ logger.info(+ f"{n} will not be quantized due to its shape not being divisible by 32,"+ " resulting in an exporting issue to autogptq")+ fp_layers_list = args.fp_layers_list.split(",")+ if bool(fp_layers_list):+ for n, m in model.named_modules():+ if isinstance(m, torch.nn.Linear) or isinstance(m, transformers.modeling_utils.Conv1D):+ name = n.split('.')[-1]+ if n in fp_layers_list or name in fp_layers_list:+ layer_config[n] = {"bits": 32}+ logger.info(+ f"{n} will not be quantized.")+ 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(+ f"reset `quant_lm_head` to `False` as quantizing lm_head with tied weights has not been "+ f"supported currently")+ break+ if args.quant_lm_head:+ layer_config[lm_head_layer_name] = {"bits": args.bits}+ transformers_version = [int(item) for item in transformers.__version__.split('.')[:2]]+ if transformers_version[0] == 4 and transformers_version[1] < 38:+ error_message = "Please upgrade transformers>=4.38.0 to support lm-head quantization."+ raise EnvironmentError(error_message)++ 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,+ minmax_lr=args.minmax_lr, enable_quanted_input=not args.disable_quanted_input,+ device=device_str, amp=not args.disable_amp, nsamples=args.nsamples, seed=args.seed,+ low_gpu_mem_usage=args.low_gpu_mem_usage, scale_dtype=args.scale_dtype,+ gradient_accumulate_steps=args.gradient_accumulate_steps, layer_config=layer_config,+ enable_minmax_tuning=not args.disable_minmax_tuning, act_bits=args.act_bits,+ low_cpu_mem_usage=low_cpu_mem_usage, data_type=args.data_type,+ enable_norm_bias_tuning=args.enable_norm_bias_tuning, not_use_best_mse=args.not_use_best_mse)+ model, _ = autoround.quantize()+ model_name = args.model.rstrip("/")+ if args.low_cpu_mem_mode == 1 or args.low_cpu_mem_mode == 2:+ import shutil+ shutil.rmtree(args.low_cpu_mem_tmp_dir, ignore_errors=True)++ model.eval()+ if "cpu" not in device_str:+ torch.cuda.empty_cache()++ export_dir = args.output_dir + "/" + model_name.split('/')[-1] + f"-w{args.bits}g{args.group_size}"++ format_list = args.format.replace(' ', '').split(',')+ inplace = False if len(format_list) > 1 else True+ for format_ in format_list:+ save_format_ = format_.replace(":", "-")+ save_format_ = save_format_.replace("_", "-")+ eval_folder = f'{export_dir}-{save_format_}'+ autoround.save_quantized(eval_folder, format=format_, inplace=inplace)++ lm_eval_version = get_library_version("lm-eval")++ if isinstance(tasks, str):+ tasks = tasks.split(',')++ if not args.disable_eval:+ logger.info(f"Using lm-eval version {lm_eval_version}")+ model_args = f"pretrained={eval_folder}"+ model_args = model_args + f",trust_remote_code={not args.disable_trust_remote_code}"+ if args.act_bits <= 8:+ if hasattr(model, "hf_device_map") and len(model.hf_device_map) > 1:+ from accelerate.big_modeling import dispatch_model++ dispatch_model(model, model.hf_device_map)+ user_model = model+ else:+ user_model = model.to(device_str)+ if args.eval_bs == "auto":+ args.eval_bs = 16+ from auto_round.eval.evaluation import simple_evaluate_user_model+ res = simple_evaluate_user_model(user_model, tokenizer, tasks=tasks, batch_size=args.eval_bs)+ else:+ res = simple_evaluate(model="hf", model_args=model_args,+ tasks=tasks,+ batch_size=args.eval_bs)+ print(make_table(res))+++def eval(args):+ device_str = detect_device(args.device)+ model_args = f"pretrained={args.model},trust_remote_code={not args.disable_trust_remote_code}"+ if isinstance(args.tasks, str):+ tasks = args.tasks.split(',')+ res = simple_evaluate(+ model="hf",+ model_args=model_args,+ tasks=tasks,+ device=device_str,+ batch_size=args.eval_bs)++ from lm_eval.utils import make_table # pylint: disable=E0401+ print(make_table(res))+diff --git a/auto_round/script/mllm.py b/auto_round/script/mllm.pynew file mode 100644index 000000000..6a79adcd3--- /dev/null+++ b/auto_round/script/mllm.py@@ -0,0 +1,311 @@+# Copyright (c) 2024 Intel Corporation+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.++import os+import argparse++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+from auto_round.utils import logger++class BasicArgumentParser(argparse.ArgumentParser):+ def __init__(self, *args, **kwargs):+ super().__init__( *args, **kwargs)+ self.add_argument("--model", default="facebook/opt-125m", help="model name or path")++ self.add_argument('--eval', action='store_true',+ help="whether to use eval only mode.")++ self.add_argument("--bits", default=4, type=int,+ help="number of bits")++ self.add_argument("--eval_bs", default=None, type=int,+ help="eval batch size")++ self.add_argument("--device", default="auto", type=str,+ help="The device to be used for tuning. The default is set to auto/None,"+ "allowing for automatic detection."+ " Currently, device settings support CPU, GPU, and HPU.")++ self.add_argument("--asym", action='store_true',+ help=" asym quantization")++ self.add_argument("--dataset", required=True, type=str,+ help="The dataset for quantization training. It can be a custom one.")++ self.add_argument("--lr", default=None, type=float,+ help="learning rate, if None, it will be set to 1.0/iters automatically")++ self.add_argument("--minmax_lr", default=None, type=float,+ help="minmax learning rate, if None,it will beset to be the same with lr")++ self.add_argument("--seed", default=42, type=int,+ help="seed")++ self.add_argument("--adam", action='store_true',+ help="adam")++ self.add_argument("--gradient_accumulate_steps", default=1, type=int, help="gradient accumulate steps")++ self.add_argument("--nblocks", default=1, type=int, help="num of blocks to tune together")++ self.add_argument("--low_gpu_mem_usage", action='store_true',+ help="lower gpu memory usage but 50-100% slower")++ self.add_argument("--format", default=None, type=str,+ help="The format in which to save the model. "+ "The options are 'auto_round', 'auto_round:gptq','auto_round:awq',"+ " and 'fake'.default to 'auto_round."+ )++ self.add_argument("--data_type", default='int',+ help="data type for tuning, 'int', 'mx_fp' and etc.")++ self.add_argument("--scale_dtype", default='fp16',+ help="which scale data type to use for quantization, 'fp16', 'fp32' or 'bf16'.")++ self.add_argument("--output_dir", default="./tmp_autoround", type=str,+ help="Where to store the final model.")++ self.add_argument("--disable_amp", action='store_true',+ help="disable amp")++ self.add_argument("--disable_minmax_tuning", action='store_true',+ help="whether disable enable weight minmax tuning")++ self.add_argument("--enable_norm_bias_tuning", action='store_true',+ help="whether enable norm bias tuning")++ self.add_argument("--disable_trust_remote_code", action='store_true',+ help="Whether to disable trust_remote_code")++ self.add_argument("--disable_quanted_input", action='store_true',+ help="whether to disuse the output of quantized block to tune the next block")++ self.add_argument("--quant_lm_head", action='store_true',+ help="quant_lm_head")++ self.add_argument("--low_cpu_mem_mode", default=0, type=int,+ help="Choose which low cpu memory mode to use. "+ "Can significantly reduce cpu memory footprint but cost more time."+ "1 means choose block-wise mode, load the weights of each block"+ " from disk when tuning and release the memory of the block after tuning."+ "2 means choose layer-wise mode, load the weights of each layer from disk when tuning,"+ " minimum memory consumption and also slowest running speed."+ "others means not use low cpu memory. Default to 0, not use low cpu memory.")++ self.add_argument("--low_cpu_mem_tmp_dir", default=None, type=str,+ help="temp work space to store the temporary files "+ "when using low cpu memory mode. Will remove after tuning.")++ self.add_argument("--model_dtype", default=None, type=str,+ help="force to convert the dtype, some backends supports fp16 dtype better")++ self.add_argument("--act_bits", default=32, type=int,+ help="activation bits")++ self.add_argument("--fp_layers_list", default="", type=str,+ help="List of Layers to maintain original data type")++ self.add_argument("--not_use_best_mse", action='store_true',+ help="To determine whether the quantization should handle vision component.")++ ## ======================= VLM =======================+ self.add_argument("--quant_nontext_module", action='store_true',+ help="To determine whether the quantization should handle vision component.")++ self.add_argument("--extra_data_dir", default="", type=str,+ help="Dataset dir for storing images/audio/videos. "+ "Can be a dir path or multiple dir path with format as "+ "'image=path_to_image,video=path_to_video,audio=path_to_audio'"+ "By default, it will search in the relative path.")++ self.add_argument("--template", default=None, type=str,+ help="The template for building training dataset. It can be a custom one.")++ ## ======================= VLM eval=======================+ self.add_argument("--tasks", type=str, default="COCO_VAL",+ help="eval tasks for VLMEvalKit.")+ # Args that only apply to Video Dataset+ self.add_argument("--nframe", type=int, default=8,+ help="The number of frames to sample from a video,"+ " only applicable to the evaluation of video benchmarks.")+ self.add_argument("--pack", action='store_true',+ help="A video may associate with multiple questions, if pack==True,"+ " will ask all questions for a video in a single")+ self.add_argument("--use-subtitle", action='store_true')+ self.add_argument("--fps", type=float, default=-1)+ # Work Dir+ # Infer + Eval or Infer Only+ self.add_argument("--mode", type=str, default='all', choices=['all', 'infer'],+ help="When mode set to 'all', will perform both inference and evaluation;"+ " when set to 'infer' will only perform the inference.")+ self.add_argument('--eval_data_dir', type=str, default=None,+ help='path for VLMEvalKit to store the eval data. Default will store in ~/LMUData')+ # API Kwargs, Apply to API VLMs and Judge API LLMs+ self.add_argument('--retry', type=int, default=None, help='retry numbers for API VLMs')+ # Explicitly Set the Judge Model+ self.add_argument('--judge', type=str, default=None)+ # Logging Utils+ self.add_argument('--verbose', action='store_true')+ # Configuration for Resume+ # Ignore: will not rerun failed VLM inference+ self.add_argument('--ignore', action='store_true', help='Ignore failed indices. ')+ # Rerun: will remove all evaluation temp files+ self.add_argument('--rerun', action='store_true')++def setup_parser():+ parser = BasicArgumentParser()++ parser.add_argument("--group_size", default=128, type=int,+ help="group size")++ parser.add_argument("--batch_size", default=1, type=int,+ help="train batch size")++ parser.add_argument("--iters", default=200, type=int,+ help=" iters")++ parser.add_argument("--seqlen", default=2048, type=int,+ help="sequence length")++ parser.add_argument("--nsamples", default=128, type=int,+ help="number of samples")++ args = parser.parse_args()+ return args++def tune(args):+ if args.format is None:+ args.format = "auto_round"++ model_name = args.model+ if model_name[-1] == "/":+ model_name = model_name[:-1]+ logger.info(f"start to quantize {model_name}")+++ device_str = detect_device(args.device)+ torch_dtype = "auto"+ if "hpu" in device_str:+ torch_dtype = torch.bfloat16++ # load_model+ config = AutoConfig.from_pretrained(model_name, trust_remote_code=not args.disable_trust_remote_code)+ tokenizer = AutoTokenizer.from_pretrained(model_name)+ processor = AutoProcessor.from_pretrained(model_name, trust_remote_code=not args.disable_trust_remote_code)+ tokenizer.processor = processor+ model_type = config.model_type+ if "qwen2_vl" in model_type:+ from transformers import Qwen2VLForConditionalGeneration+ cls = Qwen2VLForConditionalGeneration+ elif "mllama" in model_type:+ from transformers import MllamaForConditionalGeneration+ cls = MllamaForConditionalGeneration+ else:+ cls = AutoModelForCausalLM+ model = cls.from_pretrained(+ model_name,trust_remote_code=not args.disable_trust_remote_code, torch_dtype=torch_dtype)++ if "cogvlm2" in model_name:+ model.config.model_type = "cogvlm2"++ from auto_round import AutoRoundMLLM++ model = model.eval()+ seqlen = args.seqlen++ round = AutoRoundMLLM+ layer_config = {}+ for n, m in model.named_modules():+ if isinstance(m, torch.nn.Linear) or isinstance(m, transformers.modeling_utils.Conv1D):+ if m.weight.shape[0] % 32 != 0 or m.weight.shape[1] % 32 != 0:+ layer_config[n] = {"bits": 32}+ logger.info(+ f"{n} will not be quantized due to its shape not being divisible by 32,"+ " resulting in an exporting issue to autogptq")+ 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(+ f"warning, disable quant_lm_head as quantizing lm_head with tied weights has not been "+ f"supported currently")+ break+ if args.quant_lm_head:+ layer_config[lm_head_layer_name] = {"bits": args.bits}+ transformers_version = [int(item) for item in transformers.__version__.split('.')[:2]]+ if transformers_version[0] == 4 and transformers_version[1] < 38:+ error_message = "Please upgrade transformers>=4.38.0 to support lm-head quantization."+ raise EnvironmentError(error_message)++ if args.quant_lm_head and args.low_gpu_mem_usage:+ print(f"warning, low_gpu_mem_usage=False is strongly recommended if the whole model could be loaded to "+ f"gpu")++ autoround = round(model, tokenizer, dataset=args.dataset, extra_data_dir=args.extra_data_dir,+ bits=args.bits, group_size=args.group_size, sym=not args.asym,+ batch_size=args.batch_size, seqlen=seqlen, nblocks=args.nblocks, iters=args.iters,+ lr=args.lr, minmax_lr=args.minmax_lr, enable_quanted_input=not args.disable_quanted_input,+ amp=not args.disable_amp, nsamples=args.nsamples, low_gpu_mem_usage=args.low_gpu_mem_usage,+ device=device_str, seed=args.seed, gradient_accumulate_steps=args.gradient_accumulate_steps,+ scale_dtype=args.scale_dtype, layer_config=layer_config,+ enable_minmax_tuning=not args.disable_minmax_tuning, act_bits=args.act_bits,+ quant_nontext_module=args.quant_nontext_module, not_use_best_mse=args.not_use_best_mse)+ model, _ = autoround.quantize()++ model.eval()+ if args.device != "cpu":+ torch.cuda.empty_cache()++ export_dir = args.output_dir + "/" + model_name.split('/')[-1] + f"-autoround-w{args.bits}g{args.group_size}"++ format_list = args.format.replace(' ', '').split(',')+ inplace = False if len(format_list) > 1 else True+ for format_ in format_list:+ eval_folder = f'{export_dir}-{format_}'+ autoround.save_quantized(eval_folder, format=format_, inplace=inplace, processor=processor)+++def eval(args):+ if isinstance(args.tasks, str):+ args.tasks = args.tasks.split(',')+ from auto_round.mllm import mllm_eval+ mllm_eval(+ args.model,+ work_dir=args.output_dir,+ data_store_dir=args.eval_data_dir,+ dataset=args.tasks,+ pack=args.pack,+ use_subtitle = args.use_subtitle,+ fps = args.fps,+ nframe = args.nframe,+ rerun = args.rerun,+ judge = args.judge,+ verbose = args.verbose,+ mode = args.mode,+ ignore = args.ignore+ )\ No newline at end of filediff --git a/auto_round/special_model_handler.py b/auto_round/special_model_handler.pyindex 238cf952d..d0f07c3f4 100644--- a/auto_round/special_model_handler.py+++ b/auto_round/special_model_handler.py@@ -99,7 +99,7 @@ def reset_params(inputs):inputs['use_cache'] = False-def skip_keywards_hint(key):+def check_skippable_keywords(key):"""Prints a reminder if a key is not stored during quantization fine-tuning."""