PTQ-Level Efficiency, QAT-Level Accuracy | 训练后量化的效率,量化感知训练的精度
fix evaluation device bug, relate to issue 413 (#419)
Heng Guo22315cc5c585
diff --git a/auto_round/low_cpu_mem/utils.py b/auto_round/low_cpu_mem/utils.pyindex 6f579118b..3cb481a3b 100644--- a/auto_round/low_cpu_mem/utils.py+++ b/auto_round/low_cpu_mem/utils.py@@ -31,6 +31,7 @@ from transformers import AutoConfig, AutoModelForCausalLMfrom transformers.models.auto.auto_factory import _BaseAutoModelClassfrom .load import load+from auto_round.utils import detect_devicelogging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(filename)s L%(lineno)d: %(message)s")logger = logging.getLogger("low_cpu_mem_tools")@@ -433,13 +434,14 @@ def convert_model(empty_model, saved_path=LWQ_WORKSPACE):def load_model_with_hooks(pretrained_model_name_or_path,cls=AutoModelForCausalLM,- device="cpu",+ device=None,clean_weight=True,saved_path=None,**kwargs):if saved_path is None:logger.warning(f"saved_path is not set, use default working space: {LWQ_WORKSPACE}")saved_path = LWQ_WORKSPACE+ device = detect_device(device)empty_model = load_empty_model(pretrained_model_name_or_path, cls=cls, saved_path=saved_path, **kwargs)register_weight_hooks(empty_model, empty_model.path, device, clean_weight, saved_path)return empty_modeldiff --git a/auto_round/script/llm.py b/auto_round/script/llm.pyindex ea6284774..2779a229f 100644--- a/auto_round/script/llm.py+++ b/auto_round/script/llm.py@@ -28,181 +28,188 @@import osimport reimport argparse+from auto_round.utils import get_fp_layer_names, set_cuda_visible_devices, clear_memory+os.environ["CUBLAS_WORKSPACE_CONFIG"] = ":4096:8"-from auto_round.utils import detect_device, get_fp_layer_namesclass BasicArgumentParser(argparse.ArgumentParser):+def __init__(self, *args, **kwargs):super().__init__(*args, **kwargs)- self.add_argument("--model", "--model_name", "--model_name_or_path", default="facebook/opt-125m",- help="model name or path")+ self.add_argument(+ "--model", "--model_name", "--model_name_or_path", 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('--eval', action='store_true', help="whether to use eval only mode")- self.add_argument("--bits", default=4, type=int,- help="number of weight bits")+ self.add_argument("--bits", default=4, type=int, help="number of weight bits")- self.add_argument("--eval_bs", default=None, type=int,- help="batch size in evaluation")+ self.add_argument("--eval_bs", default=None, type=int, help="batch size in evaluation")- self.add_argument("--device", "--devices", default="0", type=str,- help="the device to be used for tuning. "- "Currently, device settings support CPU, GPU, and HPU."- "The default is set to cuda:0,"- "allowing for automatic detection and switch to HPU or CPU."- "set --device 0,1,2 to use multiple cards.")+ self.add_argument(+ "--device",+ "--devices",+ default="0",+ type=str,+ help="the device to be used for tuning. "+ "Currently, device settings support CPU, GPU, and HPU."+ "The default is set to cuda:0,"+ "allowing for automatic detection and switch to HPU or CPU."+ "set --device 0,1,2 to use multiple cards.")- self.add_argument("--asym", action='store_true',- help="whether to use asym quantization")+ self.add_argument("--asym", action='store_true', help="whether to use asym quantization")- self.add_argument("--dataset", default="NeelNanda/pile-10k", type=str,- help="the dataset for quantization training")+ self.add_argument(+ "--dataset", default="NeelNanda/pile-10k", type=str, help="the dataset for quantization training")- 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(+ "--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(+ "--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="random seed")+ self.add_argument("--seed", default=42, type=int, help="random seed")- self.add_argument("--adam", action='store_true',- help="whether to use adam optimizer instead of SignSGD")+ self.add_argument("--adam", action='store_true', help="whether to use adam optimizer instead of SignSGD")- self.add_argument("--gradient_accumulate_steps", default=1, type=int,- help="gradient accumulate steps")+ self.add_argument("--gradient_accumulate_steps", default=1, type=int, help="gradient accumulate steps")- self.add_argument("--nblocks", default=1, type=int,- help="how many blocks to tune together")+ self.add_argument("--nblocks", default=1, type=int, help="how many blocks to tune together")- self.add_argument("--low_gpu_mem_usage", action='store_true',- help="offload intermediate features to cpu")+ self.add_argument("--low_gpu_mem_usage", action='store_true', help="offload intermediate features to cpu")- self.add_argument("--format", default="auto_round", type=str,- help="the format to save the model"- )+ self.add_argument("--format", default="auto_round", type=str, help="the format to save the model")- self.add_argument("--data_type", "--dtype", default='int',- help="data type for tuning, 'int', 'mx_fp' and etc")+ self.add_argument("--data_type", "--dtype", default='int', help="data type for tuning, 'int', 'mx_fp' and etc")- self.add_argument("--scale_dtype", default='fp16', choices=["fp16", "float16",- "bf16", "bfloat16", "fp32", "float32"],- help="scale data type to use for quantization")+ self.add_argument(+ "--scale_dtype",+ default='fp16',+ choices=["fp16", "float16", "bf16", "bfloat16", "fp32", "float32"],+ help="scale data type to use for quantization")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")- self.add_argument("--output_dir", default="./tmp_autoround", type=str,- help="the directory to save quantized model")+ self.add_argument(+ "--output_dir", default="./tmp_autoround", type=str, help="the directory to save quantized model")- self.add_argument("--disable_eval", action='store_true',- help="whether to do lm-eval evaluation after tuning")+ 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_amp", action='store_true', help="disable amp")- self.add_argument("--disable_minmax_tuning", action='store_true',- help="whether to disable enable weight minmax tuning")+ self.add_argument(+ "--disable_minmax_tuning", action='store_true', help="whether to disable enable weight minmax tuning")- self.add_argument("--enable_norm_bias_tuning", action='store_true',- help="whether to enable norm bias tuning")+ self.add_argument("--enable_norm_bias_tuning", action='store_true', help="whether to 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_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(+ "--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="whether to quant lm_head")+ self.add_argument("--quant_lm_head", action='store_true', help="whether to quant lm_head")- self.add_argument("--low_cpu_mem_mode", default=0, type=int, choices=[0, 1, 2],- 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_mode",+ default=0,+ type=int,+ choices=[0, 1, 2],+ 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="temporary work space to store the temporary files "- "when using low cpu memory mode. Will remove after tuning.")+ self.add_argument(+ "--low_cpu_mem_tmp_dir",+ default=None,+ type=str,+ help="temporary 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, choices=["fp16", "float16",- "bf16", "bfloat16", "fp32", "float32"],- help="force to convert the dtype, some backends supports fp16 dtype better")+ self.add_argument(+ "--model_dtype",+ default=None,+ type=str,+ choices=["fp16", "float16", "bf16", "bfloat16", "fp32", "float32"],+ help="force to convert the dtype, some backends supports fp16 dtype better")- self.add_argument("--act_bits", default=16, type=int,- help="activation bits")+ self.add_argument("--act_bits", default=16, type=int, help="activation bits")- self.add_argument("--fp_layers", default="", type=str,- help="list of Layer names to maintain original data type")+ self.add_argument(+ "--fp_layers", default="", type=str, help="list of Layer names to maintain original data type")- self.add_argument("--not_use_best_mse", action='store_true',- help="whether to use the iter of best mes loss in the tuning phase")+ self.add_argument(+ "--not_use_best_mse",+ action='store_true',+ help="whether to use the iter of best mes loss in the tuning phase")- self.add_argument("--to_quant_block_names", default=None, type=str,- help="Names of quantitative blocks, please use commas to separate them.")+ self.add_argument(+ "--to_quant_block_names",+ default=None,+ type=str,+ help="Names of quantitative blocks, please use commas to separate them.")- self.add_argument("--enable_torch_compile", default=None, type=bool,- help="whether to enable torch compile")+ self.add_argument("--enable_torch_compile", default=None, type=bool, help="whether to enable torch compile")- self.add_argument("--act_data_type", default=None, type=str,- help="activation data type")+ self.add_argument("--act_data_type", default=None, type=str, help="activation data type")- self.add_argument("--disable_act_dynamic", action='store_true',- help="activation static quantization")+ 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")+ self.add_argument("--device_map", default=None, type=str, help="device_map for block in tuning phase")class EvalArgumentParser(argparse.ArgumentParser):+def __init__(self, *args, **kwargs):super().__init__(*args, **kwargs)- self.add_argument("--model", "--model_name", "--model_name_or_path", default="facebook/opt-125m",- help="model name or path")- self.add_argument("--device", "--devices", default="0", type=str,- help="the device to be used for tuning. "- "Currently, device settings support CPU, GPU, and HPU."- "The default is set to cuda:0,"- "allowing for automatic detection and switch to HPU or CPU."- "set --device 0,1,2 to use multiple cards.")+ self.add_argument(+ "--model", "--model_name", "--model_name_or_path", default="facebook/opt-125m", help="model name or path")+ self.add_argument(+ "--device",+ "--devices",+ default="0",+ type=str,+ help="the device to be used for tuning. "+ "Currently, device settings support CPU, GPU, and HPU."+ "The default is set to cuda:0,"+ "allowing for automatic detection and switch to HPU or CPU."+ "set --device 0,1,2 to use multiple cards.")self.add_argument("--tasks",default="lambada_openai,hellaswag,winogrande,piqa,mmlu,wikitext,truthfulqa_mc1," \"openbookqa,boolq,arc_easy,arc_challenge",help="lm-eval tasks")- self.add_argument("--disable_trust_remote_code", action='store_true',- help="whether to disable trust_remote_code")- self.add_argument("--eval_bs", "--bs", "--batch_size", default=None, type=int,- help="batch size in evaluation")+ self.add_argument(+ "--disable_trust_remote_code", action='store_true', help="whether to disable trust_remote_code")+ self.add_argument("--eval_bs", "--bs", "--batch_size", default=None, type=int, help="batch size in evaluation")def setup_parser():parser = BasicArgumentParser()- parser.add_argument("--group_size", default=128, type=int,- help="group size")+ parser.add_argument("--group_size", default=128, type=int, help="group size")- parser.add_argument("--batch_size", "--train_bs", "--bs", default=8, type=int,- help="train batch size")+ parser.add_argument("--batch_size", "--train_bs", "--bs", default=8, type=int, help="train batch size")- parser.add_argument("--iters", "--iter", default=200, type=int,- help="iteration to tune each block")+ parser.add_argument("--iters", "--iter", default=200, type=int, help="iteration to tune each block")- parser.add_argument("--seqlen", "--seq_len", default=2048, type=int,- help="sequence length of the calibration samples")+ parser.add_argument(+ "--seqlen", "--seq_len", default=2048, type=int, help="sequence length of the calibration samples")- parser.add_argument("--nsamples", default=128, type=int,- help="number of samples")+ parser.add_argument("--nsamples", "--nsample", default=128, type=int, help="number of samples")args = parser.parse_args()return args@@ -211,20 +218,16 @@ def setup_parser():def setup_best_parser():parser = BasicArgumentParser()- parser.add_argument("--group_size", default=128, type=int,- help="group size")+ parser.add_argument("--group_size", default=128, type=int, help="group size")- parser.add_argument("--batch_size", "--train_bs", "--bs", default=8, type=int,- help="train batch size")+ parser.add_argument("--batch_size", "--train_bs", "--bs", default=8, type=int, help="train batch size")- parser.add_argument("--iters", "--iter", default=1000, type=int,- help="iterations to tune each block")+ parser.add_argument("--iters", "--iter", default=1000, type=int, help="iterations to tune each block")- parser.add_argument("--seqlen", "--seq_len", default=2048, type=int,- help="sequence length of the calibration samples")+ parser.add_argument(+ "--seqlen", "--seq_len", default=2048, type=int, help="sequence length of the calibration samples")- parser.add_argument("--nsamples", default=512, type=int,- help="number of samples")+ parser.add_argument("--nsamples", "--nsample", default=512, type=int, help="number of samples")args = parser.parse_args()args.low_gpu_mem_usage = True@@ -235,20 +238,16 @@ def setup_best_parser():def setup_fast_parser():parser = BasicArgumentParser()- parser.add_argument("--group_size", default=128, type=int,- help="group size")+ parser.add_argument("--group_size", default=128, type=int, help="group size")- parser.add_argument("--batch_size", "--train_bs", "--bs", default=4, type=int,- help="train batch size")+ parser.add_argument("--batch_size", "--train_bs", "--bs", default=4, type=int, help="train batch size")- parser.add_argument("--iters", default=200, type=int,- help="iterations to tune each block")+ parser.add_argument("--iters", default=200, type=int, help="iterations to tune each block")- parser.add_argument("--seqlen", "--seq_len", default=512, type=int,- help="sequence length of the calibration samples")+ parser.add_argument(+ "--seqlen", "--seq_len", default=512, type=int, help="sequence length of the calibration samples")- parser.add_argument("--nsamples", default=128, type=int,- help="number of samples")+ parser.add_argument("--nsamples", "--nsample", default=128, type=int, help="number of samples")args = parser.parse_args()@@ -291,12 +290,14 @@ def _gguf_args_check(args):setattr(args, k, v)if len(unsupport_list) > 0:if len(formats) > 1:- logger.error(f"format {format} not support for {', '.join(unsupport_list)},"- f" please reset to {', '.join(reset_list)}, and retry")+ logger.error(+ f"format {format} not support for {', '.join(unsupport_list)},"+ f" please reset to {', '.join(reset_list)}, and retry")exit(-1)else:- logger.error(f"format {format} not support for {', '.join(unsupport_list)},"- f" reset to {', '.join(reset_list)}.")+ logger.error(+ f"format {format} not support for {', '.join(unsupport_list)},"+ f" reset to {', '.join(reset_list)}.")logger.info(f"export format {format}, sym = {not args.asym}, group_size = {args.group_size}")return args@@ -306,18 +307,18 @@ def tune(args):import transformersfrom transformers import AutoModelForCausalLM, AutoTokenizer, AutoModel, AutoConfig, AutoProcessor- from lm_eval.utils import make_table # pylint: disable=E0401from auto_round import AutoRoundConfig- from auto_round.eval.evaluation import simple_evaluatefrom auto_round.utils import detect_device, get_library_version, detect_device_countfrom auto_round.utils import loggertasks = args.tasksif args.format is None:args.format = "auto_round"- supported_formats = ["auto_round", "auto_gptq", "auto_awq", "auto_round:auto_gptq", "auto_round:auto_awq",- "auto_gptq:marlin", "gguf:q4_0", "gguf:q4_1", "itrex", "itrex_xpu", "fake"]+ supported_formats = [+ "auto_round", "auto_gptq", "auto_awq", "auto_round:auto_gptq", "auto_round:auto_awq", "auto_gptq:marlin",+ "gguf:q4_0", "gguf:q4_1", "itrex", "itrex_xpu", "fake"+ ]formats = args.format.lower().replace(' ', '').split(",")for format in formats:if format not in supported_formats:@@ -333,31 +334,8 @@ 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- devices = args.device.replace(" ", "").split(',')- use_auto_mapping = False- if all(s.isdigit() for s in devices):- if "CUDA_VISIBLE_DEVICES" in os.environ:- current_visible_devices = os.environ["CUDA_VISIBLE_DEVICES"]- current_visible_devices = current_visible_devices.split(',')- indices = [int(device) for device in devices]- try:- pick_device = [current_visible_devices[i] for i in indices]- except:- raise ValueError(- "Invalid '--device' value: It must be smaller than the number of available devices. "- "For example, with CUDA_VISIBLE_DEVICES=4,5, "- "--device 0,1 is valid, but --device 4,5 is not supported.")- visible_devices = ','.join(pick_device)- os.environ["CUDA_VISIBLE_DEVICES"] = visible_devices- else:- os.environ["CUDA_VISIBLE_DEVICES"] = args.device- args.device = ",".join(map(str, range(len(devices))))- devices = args.device.replace(" ", "").split(',')- if len(devices) > 1: ##for 70B model on single card, use auto will cause some layer offload to cpu- use_auto_mapping = True- elif args.device == "auto":- use_auto_mapping = True+ ##must set this before import torch+ device_str, use_auto_mapping = set_cuda_visible_devices(args.device)import torchif not args.disable_deterministic_algorithms:@@ -370,9 +348,8 @@ def tune(args):if model_name[-1] == "/":model_name = model_name[:-1]logger.info(f"start to quantize {model_name}")- device_str = detect_device(devices[0])torch_dtype = "auto"- if "hpu" in device_str:+ if device_str is not None and "hpu" in device_str:torch_dtype = torch.bfloat16is_glm = bool(re.search("chatglm", model_name.lower()))@@ -393,8 +370,7 @@ def tune(args):clean_weight=True,saved_path=args.low_cpu_mem_tmp_dir,torch_dtype=torch_dtype,- trust_remote_code=not args.disable_trust_remote_code- )+ 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_modellow_cpu_mem_usage = True@@ -404,13 +380,14 @@ def tune(args):device=device_str,saved_path=args.low_cpu_mem_tmp_dir,torch_dtype=torch_dtype,- trust_remote_code=not args.disable_trust_remote_code- )+ trust_remote_code=not args.disable_trust_remote_code)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, device_map="auto" if use_auto_mapping else None- )+ model_name,+ low_cpu_mem_usage=True,+ torch_dtype=torch_dtype,+ trust_remote_code=not args.disable_trust_remote_code,+ device_map="auto" if use_auto_mapping else None)from auto_round import AutoRound, AutoRoundAdam@@ -456,8 +433,7 @@ def tune(args):for name in not_quantize_layer_names:layer_config[name] = {"bits": 16}if len(not_quantize_layer_names) > 0:- logger.info(- f"{not_quantize_layer_names} will not be quantized.")+ logger.info(f"{not_quantize_layer_names} will not be quantized.")for format in formats:if "auto_round" not in format and "fake" not in format and "awq" not in format:##TODO gptq could support some mixed precision config@@ -488,24 +464,44 @@ def tune(args):if "auto_awq" in args.format:from auto_round.utils import check_awq_gemm_compatibility- awq_supported, info = check_awq_gemm_compatibility(model, args.bits, args.group_size, not args.asym,- layer_config)+ awq_supported, info = check_awq_gemm_compatibility(+ model, args.bits, args.group_size, not args.asym, layer_config)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,- 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,- to_quant_block_names=args.to_quant_block_names, enable_torch_compile=args.enable_torch_compile,- act_data_type=args.act_data_type, act_dynamic=not args.disable_act_dynamic,+ 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,+ to_quant_block_names=args.to_quant_block_names,+ enable_torch_compile=args.enable_torch_compile,+ act_data_type=args.act_data_type,+ act_dynamic=not args.disable_act_dynamic,device_map=args.device_map)model, _ = autoround.quantize()model_name = args.model.rstrip("/")@@ -514,8 +510,7 @@ def tune(args):shutil.rmtree(args.low_cpu_mem_tmp_dir, ignore_errors=True)model.eval()- if "cpu" not in device_str:- torch.cuda.empty_cache()+ clear_memory()if model_name.split('/')[-1].strip('.') == "":export_dir = os.path.join(args.output_dir, f"w{args.bits}g{args.group_size}")@@ -543,10 +538,12 @@ def tune(args):tasks = tasks.split(',')if not args.disable_eval and eval_folder is not None:+ from lm_eval.utils import make_table # pylint: disable=E0401+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}"+ tasks, model_args, device_str = _eval_init(args.tasks, eval_folder, args.device, 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@@ -554,92 +551,53 @@ def tune(args):dispatch_model(model, model.hf_device_map)user_model = modelelse:- user_model = model.to(device_str)+ user_model = model #.to(device_str)if args.eval_bs is None or args.eval_bs == "auto":args.eval_bs = 16from auto_round.eval.evaluation import simple_evaluate_user_model- res = simple_evaluate_user_model(user_model, tokenizer, tasks=tasks, batch_size=args.eval_bs)+ res = simple_evaluate_user_model(+ user_model, tokenizer, tasks=tasks, batch_size=args.eval_bs, device=device_str)else:- if use_auto_mapping:- model_args += ",parallelize=True"- res = simple_evaluate(model="hf", model_args=model_args,- tasks=tasks,- batch_size=args.eval_bs)+ from auto_round.eval.evaluation import simple_evaluate+ res = simple_evaluate(+ model="hf", model_args=model_args, tasks=tasks, device=device_str, batch_size=args.eval_bs)print(make_table(res))-def _eval_init(args):- devices = args.device.replace(" ", "").split(',')- parallelism = False-- if all(s.isdigit() for s in devices):- if "CUDA_VISIBLE_DEVICES" in os.environ:- current_visible_devices = os.environ["CUDA_VISIBLE_DEVICES"]- current_visible_devices = current_visible_devices.split(',')- indices = [int(device) for device in devices]- try:- pick_device = [current_visible_devices[i] for i in indices]- except:- raise ValueError(- "Invalid '--device' value: It must be smaller than the number of available devices. "- "For example, with CUDA_VISIBLE_DEVICES=4,5, "- "--device 0,1 is valid, but --device 4,5 is not supported.")- visible_devices = ','.join(pick_device)- os.environ["CUDA_VISIBLE_DEVICES"] = visible_devices- else:- os.environ["CUDA_VISIBLE_DEVICES"] = args.device- args.device = ",".join(map(str, range(len(devices))))- devices = args.device.replace(" ", "").split(',')- if len(devices) > 1:- parallelism = True- device_str = None- elif args.device == "auto":- device_str = None- parallelism = True- else:- device_str = detect_device(args.device.replace(" ", ""))-- model_args = f"pretrained={args.model},trust_remote_code={not args.disable_trust_remote_code}"+def _eval_init(tasks, model_path, device, disable_trust_remote_code=False):+ device_str, parallelism = set_cuda_visible_devices(device)+ model_args = f"pretrained={model_path},trust_remote_code={disable_trust_remote_code}"if parallelism:model_args += ",parallelize=True"- tasks = args.tasks- if isinstance(args.tasks, str):- tasks = args.tasks.split(',')-+ if isinstance(tasks, str):+ tasks = tasks.split(',')return tasks, model_args, device_strdef eval(args):- from auto_round.eval.evaluation import simple_evaluate+ tasks, model_args, device_str = _eval_init(args.tasks, args.model, args.device, args.disable_trust_remote_code)- tasks, model_args, device_str = _eval_init(args)+ # load after _eval_int in order to make sure import torch after set CUDA_VISBILE_DEVICES+ from auto_round.eval.evaluation import simple_evaluate- res = simple_evaluate(- model="hf",- model_args=model_args,- tasks=tasks,- device=device_str,- batch_size=args.eval_bs)+ 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=E0401print(make_table(res))def eval_sequence(args):+ tasks, model_args, device_str = _eval_init(args.tasks, args.model, args.device, args.disable_trust_remote_code)++ # load after _eval_int in order to make sure import torch after set CUDA_VISBILE_DEVICESfrom auto_round.eval.evaluation import simple_evaluate- tasks, model_args, device_str = _eval_init(args)from lm_eval.utils import make_table # pylint: disable=E0401res_all = {}res_keys = ["results", "versions", "n-shot", "higher_is_better"]for task in tasks:- res = simple_evaluate(- model="hf",- model_args=model_args,- tasks=task,- device=device_str,- batch_size=args.eval_bs)+ res = simple_evaluate(model="hf", model_args=model_args, tasks=task, device=device_str, batch_size=args.eval_bs)if not res_all:res_all = reselse:diff --git a/auto_round/script/mllm.py b/auto_round/script/mllm.pyindex f7c30e8d1..a7c597f4a 100644--- a/auto_round/script/mllm.py+++ b/auto_round/script/mllm.py@@ -15,173 +15,195 @@import osimport sysimport argparse-import json-import transformers-from transformers import AutoModelForCausalLM, AutoTokenizer, AutoConfig, AutoProcessor-from auto_round.utils import detect_device, get_fp_layer_names-from auto_round.utils import logger+from auto_round.utils import clear_memory, get_fp_layer_names, set_cuda_visible_devices, logger+os.environ["CUBLAS_WORKSPACE_CONFIG"] = ":4096:8"+class BasicArgumentParser(argparse.ArgumentParser):+def __init__(self, *args, **kwargs):super().__init__(*args, **kwargs)- self.add_argument("--model", "--model_name", "--model_name_or_path",- default="Qwen/Qwen2-VL-2B-Instruct",- help="model name or path")+ self.add_argument(+ "--model",+ "--model_name",+ "--model_name_or_path",+ default="Qwen/Qwen2-VL-2B-Instruct",+ help="model name or path")- self.add_argument('--eval', action='store_true',- help="whether to use eval only mode.")+ self.add_argument('--eval', action='store_true', help="whether to use eval only mode.")++ self.add_argument("--bits", default=4, type=int, help="weight bits")- self.add_argument("--bits", default=4, type=int,- help="weight bits")+ self.add_argument("--eval_bs", default=None, type=int, help="batch size in evaluation")- self.add_argument("--eval_bs", default=None, type=int,- help="batch size in evaluation")+ self.add_argument(+ "--device",+ "--devices",+ default="0",+ type=str,+ help="the device to be used for tuning. "+ "Currently, device settings support CPU, GPU, and HPU."+ "The default is set to cuda:0,"+ "allowing for automatic detection and switch to HPU or CPU."+ "set --device 0,1,2 to use multiple cards.")- self.add_argument("--device", "--devices", default="0", type=str,- help="the device to be used for tuning. "- "Currently, device settings support CPU, GPU, and HPU."- "The default is set to cuda:0,"- "allowing for automatic detection and switch to HPU or CPU."- "set --device 0,1,2 to use multiple cards.")+ self.add_argument("--asym", action='store_true', help="whether to use asym quantization")- self.add_argument("--asym", action='store_true',- help="whether to use asym quantization")+ self.add_argument(+ "--dataset",+ type=str,+ default=None,+ help="the dataset for quantization training."+ " current support NeelNanda/pile-10k,liuhaotian/llava_conv_58k,"+ "liuhaotian/llava_instruct_80k,liuhaotian/llava_instruct_150k"+ "It can be a custom one. Default is NeelNanda/pile-10k")- self.add_argument("--dataset", type=str, default=None,- help="the dataset for quantization training."- " current support NeelNanda/pile-10k,liuhaotian/llava_conv_58k,"- "liuhaotian/llava_instruct_80k,liuhaotian/llava_instruct_150k"- "It can be a custom one. Default is NeelNanda/pile-10k")+ 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("--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("--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="random seed")- self.add_argument("--seed", default=42, type=int,- help="random seed")+ self.add_argument("--adam", action='store_true', help="whether to use adam optimizer instead of SignSGD")- self.add_argument("--adam", action='store_true',- help="whether to use adam optimizer instead of SignSGD")+ self.add_argument("--gradient_accumulate_steps", default=1, type=int, help="gradient accumulate steps")- self.add_argument("--gradient_accumulate_steps", default=1, type=int,- help="gradient accumulate steps")+ self.add_argument("--nblocks", default=1, type=int, help="how many blocks to tune together")- self.add_argument("--nblocks", default=1, type=int,- help="how many blocks to tune together")+ self.add_argument("--low_gpu_mem_usage", action='store_true', help="offload intermediate features to cpu")- self.add_argument("--low_gpu_mem_usage", action='store_true',- help="offload intermediate features to cpu")+ self.add_argument("--format", default="auto_round", type=str, help="the format to save the model")- self.add_argument("--format", default="auto_round", type=str,- help="the format to save the model"- )+ self.add_argument("--data_type", "--dtype", default='int', help="data type for tuning, 'int', 'mx_fp' and etc")- self.add_argument("--data_type", "--dtype", default='int',- help="data type for tuning, 'int', 'mx_fp' and etc")+ self.add_argument(+ "--scale_dtype",+ default='fp16',+ choices=["fp16", "float16", "bf16", "bfloat16", "fp32", "float32"],+ help="scale data type to use for quantization")- self.add_argument("--scale_dtype", default='fp16', choices=["fp16", "float16",- "bf16", "bfloat16", "fp32", "float32"],- help="scale data type to use for quantization")+ self.add_argument(+ "--output_dir", default="./tmp_autoround", type=str, help="the directory to save quantized model")- self.add_argument("--output_dir", default="./tmp_autoround", type=str,- help="the directory to save quantized model")+ self.add_argument("--disable_amp", action='store_true', help="disable amp")- 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("--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("--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_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("--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="whether to quant lm_head")- self.add_argument("--quant_lm_head", action='store_true',- help="whether to quant lm_head")+ self.add_argument(+ "--low_cpu_mem_mode",+ default=0,+ type=int,+ choices=[0, 1, 2],+ 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_mode", default=0, type=int, choices=[0, 1, 2],- 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="temporary work space to store the temporary files "+ "when using low cpu memory mode. Will remove after tuning.")- self.add_argument("--low_cpu_mem_tmp_dir", default=None, type=str,- help="temporary 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,+ choices=["fp16", "float16", "bf16", "bfloat16", "fp32", "float32"],+ help="force to convert the dtype, some backends supports fp16 dtype better")- self.add_argument("--model_dtype", default=None, type=str, choices=["fp16", "float16",- "bf16", "bfloat16", "fp32", "float32"],- 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("--act_bits", default=32, type=int,- help="activation bits")+ self.add_argument("--fp_layers", default="", type=str, help="layers to maintain original data type")- self.add_argument("--fp_layers", default="", type=str,- help="layers to maintain original data type")+ self.add_argument(+ "--not_use_best_mse",+ action='store_true',+ help="whether to use the iter of best mes loss in the tuning phase")- self.add_argument("--not_use_best_mse", action='store_true',- help="whether to use the iter of best mes loss in the tuning phase")-- self.add_argument("--enable_torch_compile", default=None, type=bool,- help="whether to enable torch compile")+ 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',- help="whether to quantize non-text module, e.g. vision component")-- self.add_argument("--extra_data_dir", default=None, 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, "- "and if not find, will automatic download.")-- self.add_argument("--template", default=None, type=str,- help="the template for building training dataset. It can be a custom one.")-- self.add_argument("--truncation", action="store_true",- help="whether to truncate sequences at the maximum length."- " Default True for pile and False for llava dataset.")-- self.add_argument("--to_quant_block_names", default=None, type=str,- help="Names of quantitative blocks, please use commas to separate them.")-- self.add_argument("--device_map", default=None, type=str,- help="device_map for block in tuning phase")+ self.add_argument(+ "--quant_nontext_module",+ action='store_true',+ help="whether to quantize non-text module, e.g. vision component")++ self.add_argument(+ "--extra_data_dir",+ default=None,+ 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, "+ "and if not find, will automatic download.")++ self.add_argument(+ "--template",+ default=None,+ type=str,+ help="the template for building training dataset. It can be a custom one.")++ self.add_argument(+ "--truncation",+ action="store_true",+ help="whether to truncate sequences at the maximum length."+ " Default True for pile and False for llava dataset.")++ self.add_argument(+ "--to_quant_block_names",+ default=None,+ type=str,+ help="Names of quantitative blocks, please use commas to separate them.")++ self.add_argument("--device_map", default=None, type=str, help="device_map for block in tuning phase")def setup_parser():parser = BasicArgumentParser()- parser.add_argument("--group_size", default=128, type=int,- help="group size")+ parser.add_argument("--group_size", default=128, type=int, help="group size")- parser.add_argument("--batch_size", "--train_bs", "--bs", default=8, type=int,- help="train batch size")+ parser.add_argument("--batch_size", "--train_bs", "--bs", default=8, type=int, help="train batch size")- parser.add_argument("--iters", "--iter", default=200, type=int,- help=" iters")+ parser.add_argument("--iters", "--iter", default=200, type=int, help=" iters")- parser.add_argument("--seqlen", "--seq_len", default=None, type=int,- help="sequence length, default 2048 for text-only, 512 for liuhaotian/llava")+ parser.add_argument(+ "--seqlen",+ "--seq_len",+ default=None,+ type=int,+ help="sequence length, default 2048 for text-only, 512 for liuhaotian/llava")- parser.add_argument("--nsamples", default=128, type=int,- help="number of samples")+ parser.add_argument("--nsamples", "--nsample", default=128, type=int, help="number of samples")args = parser.parse_args()return args@@ -189,49 +211,72 @@ def setup_parser():def setup_lmeval_parser():parser = argparse.ArgumentParser()- parser.add_argument("--model", "--model_name", "--model_name_or_path",- help="model name or path")- parser.add_argument("--tasks", type=str,- default="MMBench_DEV_EN_V11,ScienceQA_VAL,TextVQA_VAL,POPE",- help="eval tasks for VLMEvalKit.")+ parser.add_argument("--model", "--model_name", "--model_name_or_path", help="model name or path")+ parser.add_argument(+ "--device",+ "--devices",+ default="0",+ type=str,+ help="the device to be used for tuning. "+ "Currently, device settings support CPU, GPU, and HPU."+ "The default is set to cuda:0,"+ "allowing for automatic detection and switch to HPU or CPU."+ "set --device 0,1,2 to use multiple cards.")+ parser.add_argument(+ "--tasks",+ type=str,+ default="MMBench_DEV_EN_V11,ScienceQA_VAL,TextVQA_VAL,POPE",+ help="eval tasks for VLMEvalKit.")# Args that only apply to Video Dataset- parser.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.")- parser.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")- parser.add_argument("--fps", type=float, default=-1,- help="set the fps for a video.")+ parser.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.")+ parser.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")+ parser.add_argument("--fps", type=float, default=-1, help="set the fps for a video.")# Work Dir# Infer + Eval or Infer Only- parser.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.")- parser.add_argument('--eval_data_dir', type=str, default=None,- help='path for VLMEvalKit to store the eval data. Default will store in ~/LMUData')+ parser.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.")+ parser.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 LLMsparser.add_argument('--retry', type=int, default=None, help='retry numbers for API VLMs')# Explicitly Set the Judge Model- parser.add_argument('--judge', type=str, default=None,- help="whether is a judge model.")+ parser.add_argument('--judge', type=str, default=None, help="whether is a judge model.")# Logging Utils- parser.add_argument('--verbose', action='store_true',- help="whether to display verbose information.")+ parser.add_argument('--verbose', action='store_true', help="whether to display verbose information.")# Configuration for Resume# Ignore: will not rerun failed VLM inference- parser.add_argument('--ignore', action='store_true',- help='ignore failed indices. ')+ parser.add_argument('--ignore', action='store_true', help='ignore failed indices. ')# Rerun: will remove all evaluation temp files- parser.add_argument('--rerun', action='store_true',- help="if true, will remove all evaluation temp files and rerun.")- parser.add_argument("--output_dir", default="./eval_result", type=str,- help="the directory to save quantized model")+ parser.add_argument(+ '--rerun', action='store_true', help="if true, will remove all evaluation temp files and rerun.")+ parser.add_argument("--output_dir", default="./eval_result", type=str, help="the directory to save quantized model")args = parser.parse_args()return argsdef tune(args):+ import transformers++ from transformers import AutoModelForCausalLM, AutoTokenizer, AutoConfig, AutoProcessor+ from lm_eval.utils import make_table # pylint: disable=E0401+if args.format is None:args.format = "auto_round"supported_formats = ["auto_round", "auto_round:auto_gptq", "auto_round:auto_awq", "auto_awq", "fake"]@@ -243,47 +288,21 @@ def tune(args):if format not in supported_formats:raise ValueError(f"{format} is not supported, we only support {supported_formats}")- model_name = args.model- 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-- if all(s.isdigit() for s in devices):- if "CUDA_VISIBLE_DEVICES" in os.environ:- current_visible_devices = os.environ["CUDA_VISIBLE_DEVICES"]- current_visible_devices = current_visible_devices.split(',')- indices = [int(device) for device in devices]- try:- pick_device = [current_visible_devices[i] for i in indices]- except:- raise ValueError(- "Invalid '--device' value: It must be smaller than the number of available devices. "- "For example, with CUDA_VISIBLE_DEVICES=4,5, "- "--device 0,1 is valid, but --device 4,5 is not supported.")- visible_devices = ','.join(pick_device)- os.environ["CUDA_VISIBLE_DEVICES"] = visible_devices- else:- os.environ["CUDA_VISIBLE_DEVICES"] = args.device- args.device = ",".join(map(str, range(len(devices))))- devices = args.device.replace(" ", "").split(',')- if len(devices) > 1:- use_auto_mapping = True ##for 70B model on single card, use auto will cause some layer offload to cpu- elif args.device == "auto":- use_auto_mapping = True+ ##must set this before import torch+ device_str, use_auto_mapping = set_cuda_visible_devices(args.device)import torchif 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])+ model_name = args.model+ if model_name[-1] == "/":+ model_name = model_name[:-1]+ logger.info(f"start to quantize {model_name}")torch_dtype = "auto"- if "hpu" in device_str:+ if device_str is not None and "hpu" in device_str:torch_dtype = torch.bfloat16# load_model@@ -293,7 +312,9 @@ def tune(args):processor = DeepseekVLV2Processor.from_pretrained(model_name)tokenizer = processor.tokenizermodel: DeepseekVLV2ForCausalLM = AutoModelForCausalLM.from_pretrained(- model_name, trust_remote_code=not args.disable_trust_remote_code, torch_dtype=torch_dtype,+ model_name,+ trust_remote_code=not args.disable_trust_remote_code,+ torch_dtype=torch_dtype,device_map="auto" if use_auto_mapping else None)model_type = "deepseek_vl_v2"else:@@ -301,8 +322,7 @@ def tune(args):if "llava" in model_name and config.architectures[0] != "LlavaForConditionalGeneration":from llava.model.builder import load_pretrained_model # pylint: disable=E0401tokenizer, model, image_processor, _ = load_pretrained_model(- model_name, model_base=None, model_name=model_name,- torch_dtype=torch_dtype)+ model_name, model_base=None, model_name=model_name, torch_dtype=torch_dtype)model_type = "llava"else:tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=not args.disable_trust_remote_code)@@ -321,7 +341,9 @@ def tune(args):cls = AutoModelForCausalLMmodel = cls.from_pretrained(- model_name, trust_remote_code=not args.disable_trust_remote_code, torch_dtype=torch_dtype,+ model_name,+ trust_remote_code=not args.disable_trust_remote_code,+ torch_dtype=torch_dtype,device_map="auto" if use_auto_mapping else None)if "cogvlm2" in model_name:model.config.model_type = "cogvlm2"@@ -349,8 +371,7 @@ def tune(args):for name in not_quantize_layer_names:layer_config[name] = {"bits": 16}if len(not_quantize_layer_names) > 0:- logger.info(- f"{not_quantize_layer_names} will not be quantized.")+ logger.info(f"{not_quantize_layer_names} will not be quantized.")for format in formats:if "auto_round" not in format and "fake" not in format and "awq" not in format:##TODO gptq could support some mixed precision config@@ -365,8 +386,7 @@ def tune(args):for fp_layer in fp_layers:if fp_layer in n:layer_config[n] = {"bits": 16}- logger.info(- f"{n} will not be quantized.")+ logger.info(f"{n} will not be quantized.")if len(layer_config) > 0:for format in formats:if "auto_round" not in format and "fake" not in format:@@ -403,36 +423,58 @@ def tune(args):f"{format} is not supported for lm-head quantization, please change to {auto_round_formats}")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")+ print(+ f"warning, low_gpu_mem_usage=False is strongly recommended if the whole model could be loaded to "+ f"gpu")if "--truncation" not in sys.argv:args.truncation = Noneif "auto_awq" in args.format:from auto_round.utils import check_awq_gemm_compatibility- awq_supported, info = check_awq_gemm_compatibility(model, args.bits, args.group_size, not args.asym,- layer_config)+ awq_supported, info = check_awq_gemm_compatibility(+ model, args.bits, args.group_size, not args.asym, layer_config)if not awq_supported:logger.warning(f"The AutoAWQ format may not be supported due to {info}")- autoround = round(model, tokenizer, processor=processor, image_processor=image_processor, 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=args.seqlen, nblocks=args.nblocks,- iters=args.iters, lr=args.lr, minmax_lr=args.minmax_lr, amp=not args.disable_amp,- enable_quanted_input=not args.disable_quanted_input, truncation=args.truncation,- 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, template=args.template,- 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,- to_quant_block_names=args.to_quant_block_names, enable_torch_compile=args.enable_torch_compile,- device_map=args.device_map)+ autoround = round(+ model,+ tokenizer,+ processor=processor,+ image_processor=image_processor,+ 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=args.seqlen,+ nblocks=args.nblocks,+ iters=args.iters,+ lr=args.lr,+ minmax_lr=args.minmax_lr,+ amp=not args.disable_amp,+ enable_quanted_input=not args.disable_quanted_input,+ truncation=args.truncation,+ 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,+ template=args.template,+ 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,+ to_quant_block_names=args.to_quant_block_names,+ enable_torch_compile=args.enable_torch_compile,+ device_map=args.device_map)model, _ = autoround.quantize()model.eval()- if args.device != "cpu":- torch.cuda.empty_cache()+ clear_memory()if model_name.split('/')[-1].strip('.') == "":export_dir = os.path.join(args.output_dir, f"w{args.bits}g{args.group_size}")@@ -446,11 +488,13 @@ def tune(args):safe_serialization = Trueif "phi3_v" in model_type:safe_serialization = False- autoround.save_quantized(- eval_folder, format=format_, inplace=inplace, safe_serialization=safe_serialization)+ autoround.save_quantized(eval_folder, format=format_, inplace=inplace, safe_serialization=safe_serialization)def eval(args):+ device_str, parallelism = set_cuda_visible_devices(args.device)+ if parallelism:+ os.environ['AUTO_SPLIT'] = '1'if isinstance(args.tasks, str):args.tasks = args.tasks.replace(' ', '').split(',')from auto_round.mllm import mllm_eval@@ -466,21 +510,18 @@ def eval(args):judge=args.judge,verbose=args.verbose,mode=args.mode,- ignore=args.ignore- )+ ignore=args.ignore)def setup_lmms_parser():parser = argparse.ArgumentParser()- parser.add_argument("--model", "--model_name", "--model_name_or_path",- help="model name or path")+ parser.add_argument("--model", "--model_name", "--model_name_or_path", help="model name or path")parser.add_argument("--tasks",default="pope,textvqa_val,scienceqa,mmbench_en",help="To get full list of tasks, use the command lmms-eval --tasks list",)- parser.add_argument("--output_dir", default="./eval_result", type=str,- help="the directory to save quantized model")+ parser.add_argument("--output_dir", default="./eval_result", type=str, help="the directory to save quantized model")parser.add_argument("--num_fewshot",type=int,@@ -505,22 +546,29 @@ def setup_lmms_parser():)parser.add_argument("--device",+ "--devices",+ default="0",type=str,- default=None,- help="Device to use (e.g. cuda, cuda:0, cpu)",- )+ help="the device to be used for tuning. "+ "Currently, device settings support CPU, GPU, and HPU."+ "The default is set to cuda:0,"+ "allowing for automatic detection and switch to HPU or CPU."+ "set --device 0,1,2 to use multiple cards.")parser.add_argument("--limit",type=float,default=None,- help="Limit the number of examples per task. " "If <1, limit is a percentage of the total"- " number of examples.",+ help="Limit the number of examples per task. "+ "If <1, limit is a percentage of the total"+ " number of examples.",)args = parser.parse_args()return argsdef lmms_eval(args):+ device_str, parallelism = set_cuda_visible_devices(args.device)+from auto_round.mllm import lmms_evalresults = lmms_eval(@@ -531,7 +579,7 @@ def lmms_eval(args):limit=args.limit,batch_size=args.batch_size,max_batch_size=args.max_batch_size,- device=args.device,+ device=device_str,use_cache=None,apply_chat_template=False,)diff --git a/auto_round/utils.py b/auto_round/utils.pyindex a182a53ec..1511c81e0 100644--- a/auto_round/utils.py+++ b/auto_round/utils.py@@ -18,6 +18,7 @@ import osimport sysimport subprocessfrom collections import UserDict+from typing import Union, Optionalimport re# for cpu usageimport cpuinfo@@ -1158,3 +1159,36 @@ def check_awq_gemm_compatibility(model, bits, group_size, sym, layer_configs=Nonreturn False, f"Layer {layer_name} out_features is not multiple of 32 // bits"return True, ""+++def set_cuda_visible_devices(device):+ devices = device.replace(" ", "").split(',')+ parallelism = False+ if all(s.isdigit() for s in devices):+ if "CUDA_VISIBLE_DEVICES" in os.environ:+ current_visible_devices = os.environ["CUDA_VISIBLE_DEVICES"]+ current_visible_devices = current_visible_devices.split(',')+ indices = [int(device) for device in devices]+ try:+ pick_device = [current_visible_devices[i] for i in indices]+ except:+ raise ValueError(+ "Invalid '--device' value: It must be smaller than the number of available devices."+ " For example, with CUDA_VISIBLE_DEVICES=4,5, "+ "--device 0,1 is valid, but --device 4,5 is not supported.")+ visible_devices = ','.join(pick_device)+ os.environ["CUDA_VISIBLE_DEVICES"] = visible_devices+ else:+ os.environ["CUDA_VISIBLE_DEVICES"] = device+ device = ",".join(map(str, range(len(devices))))+ devices = device.replace(" ", "").split(',')+ if len(devices) > 1: ##for 70B model on single card, use auto will cause some layer offload to cpu+ parallelism = True+ device_str = None+ elif device == "auto":+ device_str = None+ parallelism = True+ else:+ device_str = detect_device(device.replace(" ", ""))+ return device_str, parallelism+\ No newline at end of file