PTQ-Level Efficiency, QAT-Level Accuracy | 训练后量化的效率,量化感知训练的精度
multiple gpu evaluation/calibration refine (#312)
wenhuach21c5687ba1ce23
diff --git a/README.md b/README.mdindex c6e40235f..d364ba3bb 100644--- a/README.md+++ b/README.md@@ -57,12 +57,12 @@ pip install auto-round### Basic Usage (Gaudi2/CPU/GPU)-A user guide detailing the full list of supported arguments is provided by calling ```auto-round -h``` on the terminal.+[//]: # (A user guide detailing the full list of supported arguments is provided by calling ```auto-round -h``` on the terminal.)Alternatively, you can use ```auto_round``` instead of ```auto-round```. Set the format you want in `format` and-multiple formats exporting has been supported.+multiple formats exporting has been supported. Please check out [step-by-step-instruction](./docs/step_by_step.md) for more details about calibration dataset or evaluation.```bash-CUDA_VISIBLE_DEVICES=0 auto-round \+auto-round \--model facebook/opt-125m \--bits 4 \--group_size 128 \@@ -77,7 +77,7 @@ We provide two recipes for best accuracy and fast running speed with low memory.```bash## best accuracy, 3X slower, low_gpu_mem_usage could save ~20G but ~30% slower-CUDA_VISIBLE_DEVICES=0 auto-round \+auto-round \--model facebook/opt-125m \--bits 4 \--group_size 128 \@@ -89,7 +89,7 @@ CUDA_VISIBLE_DEVICES=0 auto-round \```bash## fast and low memory, 2-3X speedup, slight accuracy drop at W4G128-CUDA_VISIBLE_DEVICES=0 auto-round \+auto-round \--model facebook/opt-125m \--bits 4 \--group_size 128 \diff --git a/auto_round/autoround.py b/auto_round/autoround.pyindex d40218786..86dd36d46 100644--- a/auto_round/autoround.py+++ b/auto_round/autoround.py@@ -264,7 +264,7 @@ class AutoRound(object):Returns:The quantized model and layer configurations."""- # logger.info("cache block input")+if bool(self.quant_block_list):all_blocks = self.quant_block_listelse:@@ -280,10 +280,12 @@ class AutoRound(object):layer_names = self.get_quantized_layer_names_outside_blocks()self.start_time = time.time()all_first_block_names = [block[0] for block in all_blocks]+ logger.info("start calibration")all_inputs = self.try_cache_inter_data_gpucpu(all_first_block_names, self.nsamples, layer_names=layer_names)if hasattr(self.model, "hf_device_map") and len(self.model.hf_device_map) > 1:accelerate.hooks.remove_hook_from_submodules(self.model) ##self.model.hf_device_map has not been changedself.model = mv_module_from_gpu(self.model, self.low_cpu_mem_usage)+ logger.info("calibration done")for block_names in all_blocks:inputs = all_inputs[block_names[0]]all_inputs.pop(block_names[0])@@ -611,10 +613,12 @@ class AutoRound(object):except RuntimeError as e:if "CUDA out of memory" in str(e):logger.info("switch to cpu to cache inputs")- if "lm_head" in self.layer_config and self.layer_config["lm_head"]["bits"] < 8:+ if (("lm_head" in self.layer_config and self.layer_config["lm_head"]["bits"] <= 16) or+ self.__class__.__name__=="AutoRoundMLLM") :logger.warning(f"we strongly recommend using additional CUDA/HPU devices,e.g. "- f"'CUDA_VISIBLE_DEVICES=0,1 python xxx',"- f" for optimal performance during calibration when enabling lm-head quantization. "+ f"set `--device '0,1'` in our cmd line usage or "+ f"load the model with `device_mapping=auto`,"+ f" for optimal performance during calibration "f"Otherwise, the process may be significantly slower.")self.model = mv_module_from_gpu(self.model, self.low_cpu_mem_usage)clear_memory()diff --git a/auto_round/script/llm.py b/auto_round/script/llm.pyindex 292b1162d..faf616eb8 100644--- a/auto_round/script/llm.py+++ b/auto_round/script/llm.py@@ -25,24 +25,8 @@# 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 reimport 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):@@ -59,7 +43,7 @@ class BasicArgumentParser(argparse.ArgumentParser):self.add_argument("--eval_bs", default=None, type=int,help="batch size in evaluation")- self.add_argument("--device", default="auto", type=str,+ self.add_argument("--device", "--devices", default="auto", type=str,help="the device to be used for tuning. The default is set to auto,""allowing for automatic detection.""Currently, device settings support CPU, GPU, and HPU.")@@ -234,7 +218,7 @@ def tune(args):supported_formats = ["auto_round", "auto_gptq", "auto_awq", "auto_round:gptq", "auto_round:auto_gptq","auto_round:auto_gptq:marlin", "auto_round:gptq:marlin", "auto_round:auto_awq","auto_round:awq", "auto_gptq:marlin", "itrex", "iterx_xpu", "fake"]- formats = args.format.replace(' ', '').split(",")+ formats = args.format.replace(' ', '').split(",")for format in formats:if format not in supported_formats:raise ValueError(f"{format} is not supported, we only support {supported_formats}")@@ -247,12 +231,49 @@ 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+ import os+ 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(',')+ use_auto_mapping = True++ import re+ 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+model_name = args.modelif model_name[-1] == "/":model_name = model_name[:-1]logger.info(f"start to quantize {model_name}")-- device_str = detect_device(args.device)+ device_str = detect_device(devices[0])torch_dtype = "auto"if "hpu" in device_str:torch_dtype = torch.bfloat16@@ -289,16 +310,10 @@ def tune(args):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- )+ 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+ )from auto_round import AutoRound, AutoRoundAdam@@ -370,7 +385,6 @@ def tune(args):raise ValueError(f"{format} is not supported for lm-head quantization, please change to {auto_round_formats}")-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,@@ -411,6 +425,7 @@ def tune(args):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:@@ -426,6 +441,8 @@ def tune(args):from auto_round.eval.evaluation import simple_evaluate_user_modelres = simple_evaluate_user_model(user_model, tokenizer, tasks=tasks, batch_size=args.eval_bs)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)@@ -433,8 +450,37 @@ def tune(args):def eval(args):- device_str = detect_device(args.device)+ import os+ 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(',')+ parallelism = True+ device_str = None+++ from auto_round.eval.evaluation import simple_evaluate+model_args = f"pretrained={args.model},trust_remote_code={not args.disable_trust_remote_code}"+ if parallelism:+ model_args += ",parallelize=True"if isinstance(args.tasks, str):tasks = args.tasks.split(',')res = simple_evaluate(diff --git a/auto_round/script/mllm.py b/auto_round/script/mllm.pyindex 6264f9361..4690ccab9 100644--- a/auto_round/script/mllm.py+++ b/auto_round/script/mllm.py@@ -42,7 +42,7 @@ class BasicArgumentParser(argparse.ArgumentParser):self.add_argument("--eval_bs", default=None, type=int,help="batch size in evaluation")- self.add_argument("--device", default="auto", type=str,+ self.add_argument("--device", "--devices", default="auto", type=str,help="the device to be used for tuning. The default is set to auto,""allowing for automatic detection.""Currently, device settings support CPU, GPU, and HPU.")@@ -206,7 +206,7 @@ def tune(args):"auto_round:auto_gptq:marlin", "auto_round:gptq:marlin", "auto_round:auto_awq","auto_round:awq"]if not args.quant_nontext_module:- supported_formats.append("auto_gptq","auto_gptq:marlin")+ supported_formats.extend(["auto_gptq", "auto_gptq:marlin"])formats = args.format.replace(' ', '').split(",")for format in formats:@@ -220,7 +220,31 @@ def tune(args):assert args.dataset is not None, "dataset should not be None."- device_str = detect_device(args.device)+ 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(',')+ use_auto_mapping = True++ device_str = detect_device(devices[0])+torch_dtype = "auto"if "hpu" in device_str:torch_dtype = torch.bfloat16@@ -239,8 +263,10 @@ def tune(args):cls = MllamaForConditionalGenerationelse:cls = AutoModelForCausalLM+model = 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"diff --git a/docs/step_by_step.md b/docs/step_by_step.mdnew file mode 100644index 000000000..e87a15efe--- /dev/null+++ b/docs/step_by_step.md@@ -0,0 +1,217 @@+Step-by-Step+============++This document presents step-by-step instructions for auto-round llm quantization.++# 1 Prerequisite++Install auto-round or install from source++```bash+pip install auto-round+```++## 2. Prepare Calibration Dataset++### Default Dataset++The [NeelNanda/pile-10k](https://huggingface.co/datasets/NeelNanda/pile-10k) in huggingface is adopted as the default+calibration data and will be downloaded automatically from the datasets Hub. To customize a dataset, please kindly+follow our dataset code.+See more about loading [huggingface dataset](https://huggingface.co/docs/datasets/main/en/quickstart)++### Customized Dataset++- Option 1: Pass a local json file path to dataset argument+- Option 2: Register your dataset following the [code](../../auto_round/calib_dataset.py) and pass the new dataset and+ split args to initialize AutoRound object, e.g. autoround=Autoround(dataset="NeelNanda/pile-10k:train", ...)+- Option 3: pass list of string or list of input_ids to dataset.++ ~~~python+ def customized_data():+ ##Important Notice!!! Autoround will drop data < args.seqlen and truncate data to args.seqlen+ data = ["AutoRound is an advanced weight-only quantization algorithm for low-bits LLM inference" * 240]+ data.append("AutoRound is an advanced weight-only quantization algorithm for low-bits LLM inference")+ return data+++ def customized_data_with_tokenizer(tokenizer, seqlen=2048):+ ##Import notice!!! Autoround will drop data < args.seqlen+ data = ["AutoRound is an advanced weight-only quantization algorithm for low-bits LLM inference" * 240]+ data.append("AutoRound is an advanced weight-only quantization algorithm for low-bits LLM inference")+ tokens = []+ for d in data:+ token = tokenizer(d, truncation=True, max_length=seqlen, return_tensors="pt").data+ tokens.append(token)+ return tokens+ ~~~++We support combination of different datasets and parametrization of calibration datasets by using "--dataset ./tmp.json:+concat,NeelNanda/pile-10k:split=train+val:num=256,mbpp:concat=True:num=128:apply_template". Both local calibration file+and huggingface dataset are supported. Through parametrization, users could specify splits of a dataset by setting "+split=split1+split2". A concatenation option could enable users to merge calibration samples, a process commonly used to+enhance calibration reliability. An 'apply_template' option would enable users to apply chat_template to calibration+data before tokenization and is widely used by instruct-models in generation. Please note that samples shorter than+args.seqlen will be dropped when concatenation option is not enabled.+Please use ',' to split datasets, ':' to split parameters of a dataset and '+' to add values for one targeted parameter.+++<br />++## 2. Run Quantization++- **Default Settings:**++ ```bash+ auto-round --model facebook/opt-125m --bits 4 --format "auto_round,auto_gptq" --disble_eval+ ```++- **Reduced GPU Memory Usage:**++ - enable low_gpu_mem_usage(more tuning cost)++ - set "--train_bs 1 --gradient_accumulate_steps 8" (more tuning cost)++ - reduce the train bs to 4(potential accuracy drop)++ - reduce the seqlen to 512 (potential accuracy drop)++ - or combine them+++- **Reduced CPU Memory Usage:**++ - set "--low_cpu_mem_mode 1" to use block-wise mode, load the weights from disk of each block when tuning and+ release the memory of the block after tuning. (more tuning cost)++ - set "--low_cpu_mem_mode 2" to use layer-wise mode, load the weights of each layer from disk when tuning, minimum+ memory consumption and also slowest running speed.+++- **Speedup the tuning:**+ - reduce the seqlen to 512(potential large accuracy drop for some scenarios)++ - reduce the train bs to 4(little accuracy drop. )++ - or combine them+++- **Enable quantized lm-head:**++ Currently only support in AutoRound format inference for this config++ ```bash+ auto-round --model_name facebook/opt-125m --bits 4 --group_size 128 --quant_lm_head --format "auto_round"+ ```++- **Enable marlin kernel:**+ - We support inference repacking for auto_round sym quantized models+ ```python+ from transformers import AutoModelForCausalLM, AutoTokenizer+ from auto_round import AutoRoundConfig+ backend = "cuda_marlin" #supported in auto_round>0.3.1 and 'pip install -v gptqmodel --no-build-isolation')+ quantization_config = AutoRoundConfig(backend=backend)+ quantized_model_path = "./tmp_autoround"+ model = AutoModelForCausalLM.from_pretrained(quantized_model_path,+ device_map=backend.split(':')[0], quantization_config=quantization_config)+ ```+ - To leverage auto-gptq marlin kernel, you need to install auto-gptq from source++ ```bash+ auto-round --model facebook/opt-125m --sym --bits 4 --group_size 128 --format "gptq:marlin"+ ```++- **Utilize the AdamW Optimizer:**++ Include the flag `--adam`. Note that AdamW is less effective than sign gradient descent in many scenarios we tested.+++- **Code generation LLM:**++ We utilized mbpp for calibration, but your own training dataset is highly recommended. Please note that samples with+ seqlen < args.seqlen will be dropped in current version.++ ```bash+ auto-round --model Salesforce/codegen25-7b-multi --bits 4 --dataset "mbpp" --seqlen 128 "+ ```++## 4. Evaluation+### 4.1 Combine evaluation with tuning+ - We leverage lm-eval-harnessing for the evaluation+ ~~~bash+ auto-round --model facebook/opt-125m --bits 4 --format "auto_round,auto_gptq" --tasks mmlu+ ~~~+ The last format will be used in evaluation if multiple formats have been exported.++### 4.2 Eval the Quantized model+- AutoRound format+ For lm-eval-harness, you could just call+ ~~~bash+ auto-round --model="your_model_path" --eval --tasks lambada_openai --eval_bs 16+ ~~~+ Multiple gpu evaluation+ ~~~bash+ auto-round --model="your_model_path" --eval --device 0,1 --tasks lambada_openai --eval_bs 16+ ~~~+ For other evaluation framework, if the framework could support Huggingface models, typically it could support AutoRound format, only you need to do is import the following in the beginning of your code+ ~~~python+ from auto_round import AutoRoundConfig+ ~~~++- AutoGPTQ/AutoAWQ format++ Please refer to their repo and check the evaluation framework's compatibility.+ For lm-eval-harness, you could just call+ ~~~bash+ lm_eval --model hf --model_args pretrained="your_model_path" --device cuda:0 --tasks lambada_openai --batch_size 16+ ~~~+ Multiple gpu evaluation+ ~~~bash+ CUDA_VISIBLE_DEVICES=0,1 lm_eval --model hf --model_args pretrained="your_model_path",parallelize=True --tasks lambada_openai --batch_size 16+ ~~~++## Inference+**CPU**: **auto_round version >0.3.1**, pip install intel-extension-for-pytorch(much higher speed on Intel CPU) or pip+install intel-extension-for-transformers,++**HPU**: docker image with Gaudi Software Stack is recommended. More details can be found+in [Gaudi Guide](https://docs.habana.ai/en/latest/).++**CUDA**: no extra operations for sym quantization, for asym quantization, need to install auto-round from source+### AutoRound format+- The following code will automatically detect device, and typically some error message will remind you to install some extra libraries+ ```python+ from transformers import AutoModelForCausalLM, AutoTokenizer+ from auto_round import AutoRoundConfig ## must import++ quantized_model_path = "./tmp_autoround"+ device="cuda"+ model = AutoModelForCausalLM.from_pretrained(quantized_model_path).to(device)+ tokenizer = AutoTokenizer.from_pretrained(quantized_model_path)+ text = "There is a girl who likes adventure,"+ inputs = tokenizer(text, return_tensors="pt").to(model.device)+ print(tokenizer.decode(model.generate(**inputs, max_new_tokens=50)[0]))+ ```+- To specify device use a different backend++ ```python+ from transformers import AutoModelForCausalLM, AutoTokenizer+ from auto_round import AutoRoundConfig++ backend = "auto" ##cpu, hpu, cuda, cuda:marlin(supported in auto_round>0.3.1 and 'pip install -v gptqmodel --no-build-isolation')+ quantization_config = AutoRoundConfig(+ backend=backend+ )+ quantized_model_path = "./tmp_autoround"+ model = AutoModelForCausalLM.from_pretrained(quantized_model_path,+ device_map=backend.split(':')[0], quantization_config=quantization_config)+ tokenizer = AutoTokenizer.from_pretrained(quantized_model_path)+ text = "There is a girl who likes adventure,"+ inputs = tokenizer(text, return_tensors="pt").to(model.device)+ print(tokenizer.decode(model.generate(**inputs, max_new_tokens=50)[0]))+ ```+++## 6. Known Issues+* Random quantization results in tuning some models+* ChatGlm-V1 is not supported\ No newline at end of filediff --git a/examples/language-modeling/main.py b/examples/language-modeling/main.pyindex bc0309791..503307150 100644--- a/examples/language-modeling/main.py+++ b/examples/language-modeling/main.py@@ -7,26 +7,6 @@ from packaging import versionsys.path.insert(0, '../..')parser = argparse.ArgumentParser()-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--import logging-import warnings-import numexpr--warnings.filterwarnings('ignore', category=DeprecationWarning)-warnings.filterwarnings('ignore', category=FutureWarning)-os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'-dataset_logger = logging.getLogger("datasets")-dataset_logger.disabled = True-numexpr_logger = logging.getLogger("numexpr")-numexpr_logger.disabled = True--os.environ["TOKENIZERS_PARALLELISM"] = "false"if __name__ == '__main__':@@ -46,7 +26,7 @@ if __name__ == '__main__':parser.add_argument("--eval_bs", default=None, type=int,help="eval batch size")- parser.add_argument("--device", default="auto", type=str,+ parser.add_argument("--device", "--devices", 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.")@@ -152,6 +132,9 @@ if __name__ == '__main__':args = parser.parse_args()+ print(+ "Warning, examples/language-modeling/main.py is deprecated, please use auto-round cmd line instead. The file will be deleted in the V0.4.1 release ")+if args.enable_minmax_tuning:print("enable_minmax_tuning is deprecated, it has been set to the default, use disable_minmax_tuning to turn it off")@@ -175,7 +158,47 @@ if __name__ == '__main__':for format in formats:if format not in supported_formats:raise ValueError(f"{format} is not supported, we only support {supported_formats}")+ 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(',')+ use_auto_mapping = True++ 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++ import logging+ import warnings+ import numexpr++ warnings.filterwarnings('ignore', category=DeprecationWarning)+ warnings.filterwarnings('ignore', category=FutureWarning)+ os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'+ dataset_logger = logging.getLogger("datasets")+ dataset_logger.disabled = True+ numexpr_logger = logging.getLogger("numexpr")+ numexpr_logger.disabled = True++ os.environ["TOKENIZERS_PARALLELISM"] = "false"tasks = args.tasksuse_eval_legacy = False@@ -185,9 +208,10 @@ if __name__ == '__main__':model_name = model_name[:-1]print(model_name, flush=True)- from auto_round.utils import detect_device, detect_device_count+ from auto_round.utils import detect_device++ device_str = detect_device(devices[0])- device_str = detect_device(args.device)torch_dtype = "auto"if "hpu" in device_str:torch_dtype = torch.bfloat16@@ -223,16 +247,11 @@ if __name__ == '__main__':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- )++ 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+ )from auto_round import (AutoRound,AutoRoundAdam)@@ -380,6 +399,8 @@ if __name__ == '__main__':model_args = f"pretrained={eval_folder}"model_args = model_args + f",trust_remote_code={not args.disable_trust_remote_code}"+ if use_auto_mapping:+ model_args += ",parallelize=True"user_model = Noneif args.act_bits <= 8:if hasattr(model, "hf_device_map") and len(model.hf_device_map) > 1:diff --git a/examples/language-modeling/scripts/Llama-2-7b-chat-hf.sh b/examples/language-modeling/scripts/Llama-2-7b-chat-hf.shindex a96d03e14..94781f0cf 100644--- a/examples/language-modeling/scripts/Llama-2-7b-chat-hf.sh+++ b/examples/language-modeling/scripts/Llama-2-7b-chat-hf.sh@@ -1,4 +1,5 @@## Due to licensing restrictions, we are unable to release the model. To run the int4 model on GPU, please install transformers==4.32.0, currently the 4.38.1 version has some issues.+## This recipe is outdated, we recommend using the latest recipe for best accuracy in homepagepython3 main.py \--model_name meta-llama/Llama-2-7b-chat-hf \--device 0 \@@ -6,5 +7,5 @@ python3 main.py \--bits 4 \--iters 1000 \--nsamples 512 \---deployment_device 'gpu' \+--format 'auto_round,auto_gptq' \--output_dir "./tmp_autoround"diff --git a/examples/language-modeling/scripts/Meta-Llama-3-8B-Instruct.sh b/examples/language-modeling/scripts/Meta-Llama-3-8B-Instruct.shindex c4e306cc0..57a6ce378 100644--- a/examples/language-modeling/scripts/Meta-Llama-3-8B-Instruct.sh+++ b/examples/language-modeling/scripts/Meta-Llama-3-8B-Instruct.sh@@ -1,3 +1,4 @@+## This recipe is outdated, we recommend using the latest recipe for best accuracy in homepage## quant lm headpython3 main.py \--model_name meta-llama/Meta-Llama-3-8B-Instruct \@@ -7,7 +8,7 @@ python3 main.py \--iters 1000 \--quant_lm_head \--nsamples 512 \---deployment_device 'gpu' \+--format 'auto_round,auto_gptq' \--output_dir "./tmp_autoround"@@ -19,6 +20,6 @@ python3 main.py \--group_size 128 \--bits 4 \--iters 1000 \---deployment_device 'gpu' \+--format 'auto_round,auto_gptq' \--nsamples 512 \--output_dir "./tmp_autoround"\ No newline at end of filediff --git a/examples/language-modeling/scripts/Mistral-7B-Instruct-v0.2.sh b/examples/language-modeling/scripts/Mistral-7B-Instruct-v0.2.shindex 76680b747..aeece3d50 100644--- a/examples/language-modeling/scripts/Mistral-7B-Instruct-v0.2.sh+++ b/examples/language-modeling/scripts/Mistral-7B-Instruct-v0.2.sh@@ -1,3 +1,4 @@+## This recipe is outdated, we recommend using the latest recipe for best accuracy in homepagepython3 main.py \--model_name mistralai/Mistral-7B-Instruct-v0.2 \--device 0 \@@ -5,5 +6,5 @@ python3 main.py \--bits 4 \--iters 1000 \--nsamples 512 \---deployment_device 'gpu' \+--format 'auto_round,auto_gptq' \--output_dir "./tmp_autoround"\ No newline at end of filediff --git a/examples/language-modeling/scripts/Mistral-7B-v0.1.sh b/examples/language-modeling/scripts/Mistral-7B-v0.1.shindex 1071f8db9..4c3f01367 100644--- a/examples/language-modeling/scripts/Mistral-7B-v0.1.sh+++ b/examples/language-modeling/scripts/Mistral-7B-v0.1.sh@@ -1,3 +1,4 @@+## This recipe is outdated, we recommend using the latest recipe for best accuracy in homepagepython3 main.py \--model_name mistralai/Mistral-7B-v0.1 \--device 0 \@@ -5,5 +6,5 @@ python3 main.py \--bits 4 \--iters 1000 \--nsamples 512 \---deployment_device 'gpu' \+--format 'auto_round,auto_gptq' \--output_dir "./tmp_autoround"\ No newline at end of filediff --git a/examples/language-modeling/scripts/Mixtral-8x7B-Instruct-v0.1.sh b/examples/language-modeling/scripts/Mixtral-8x7B-Instruct-v0.1.shindex cd98d5b12..719840058 100644--- a/examples/language-modeling/scripts/Mixtral-8x7B-Instruct-v0.1.sh+++ b/examples/language-modeling/scripts/Mixtral-8x7B-Instruct-v0.1.sh@@ -1,3 +1,4 @@+## This recipe is outdated, we recommend using the latest recipe for best accuracy in homepagepython3 main.py \--model_name mistralai/Mixtral-8x7B-Instruct-v0.1 \--device 0 \@@ -5,5 +6,5 @@ python3 main.py \--bits 4 \--iters 1000 \--nsamples 512 \---deployment_device 'gpu' \+--format 'auto_round,auto_gptq' \--output_dir "./tmp_autoround"\ No newline at end of filediff --git a/examples/language-modeling/scripts/Mixtral-8x7B-v0.1.sh b/examples/language-modeling/scripts/Mixtral-8x7B-v0.1.shindex 185cda732..2557eff5d 100644--- a/examples/language-modeling/scripts/Mixtral-8x7B-v0.1.sh+++ b/examples/language-modeling/scripts/Mixtral-8x7B-v0.1.sh@@ -1,3 +1,4 @@+## This recipe is outdated, we recommend using the latest recipe for best accuracy in homepagepython3 main.py \--model_name mistralai/Mixtral-8x7B-v0.1 \--device 0 \@@ -5,6 +6,6 @@ python3 main.py \--bits 4 \--iters 1000 \--nsamples 512 \---deployment_device 'gpu' \+--format 'auto_round,auto_gptq' \--output_dir "./tmp_autoround" \--disable_quanted_input\ No newline at end of filediff --git a/examples/language-modeling/scripts/Qwen1.5-7B-Chat-asym.sh b/examples/language-modeling/scripts/Qwen1.5-7B-Chat-asym.shindex a9fcebe21..ebfca329f 100644--- a/examples/language-modeling/scripts/Qwen1.5-7B-Chat-asym.sh+++ b/examples/language-modeling/scripts/Qwen1.5-7B-Chat-asym.sh@@ -1,10 +1,11 @@+## This recipe is outdated, we recommend using the latest recipe for best accuracy in homepage## Due to licensing restrictions, we are unable to release the model.python3 main.py \--model_name Qwen/Qwen1.5-7B-Chat \--group_size 128 \--bits 4 \--iters 1000 \---deployment_device 'gpu' \+--format 'auto_round,auto_gptq' \--minmax_lr 2e-3\--nsamples 512diff --git a/examples/language-modeling/scripts/Qwen1.5-7B-Chat-sym.sh b/examples/language-modeling/scripts/Qwen1.5-7B-Chat-sym.shindex 07161e16a..2da700826 100644--- a/examples/language-modeling/scripts/Qwen1.5-7B-Chat-sym.sh+++ b/examples/language-modeling/scripts/Qwen1.5-7B-Chat-sym.sh@@ -1,11 +1,11 @@+## This recipe is outdated, we recommend using the latest recipe for best accuracy in homepage## Due to licensing restrictions, we are unable to release the model.python3 main.py \--model_name Qwen/Qwen1.5-7B-Chat \--bits 4 \--group_size 128 \--iters 200 \---deployment_device gpu \---sym \+--format 'auto_round,auto_gptq' \--nsamples 512 \--minmax_lr 0.01diff --git a/examples/language-modeling/scripts/Yi-6B-Chat.sh b/examples/language-modeling/scripts/Yi-6B-Chat.shindex ce59f1bbe..f66b0efb7 100644--- a/examples/language-modeling/scripts/Yi-6B-Chat.sh+++ b/examples/language-modeling/scripts/Yi-6B-Chat.sh@@ -1,8 +1,11 @@+## This recipe is outdated, we recommend using the latest recipe for best accuracy in homepage## Due to licensing restrictions, we are unable to release the model.python3 main.py \--model_name 01-ai/Yi-6B-Chat \--group_size 128 \--bits 4 \--iters 1000 \---deployment_device 'gpu' \+--format 'auto_round,auto_gptq' \--minmax_lr 2e-3++diff --git a/examples/language-modeling/scripts/baichuan2-7b-chat.sh b/examples/language-modeling/scripts/baichuan2-7b-chat.shindex 74bf14fb6..7425aeca6 100644--- a/examples/language-modeling/scripts/baichuan2-7b-chat.sh+++ b/examples/language-modeling/scripts/baichuan2-7b-chat.sh@@ -1,9 +1,10 @@## Due to licensing restrictions, we are unable to release the model.+## This recipe is outdated, we recommend using the latest recipe for best accuracy in homepagepython3 main.py \--model_name baichuan-inc/Baichuan2-7B-Chat \--group_size 128 \--bits 4 \--iters 1000 \--nsamples 512 \---deployment_device 'gpu' \+--format 'auto_round,auto_gptq' \--minmax_lr 2e-3diff --git a/examples/language-modeling/scripts/bloom-3b.sh b/examples/language-modeling/scripts/bloom-3b.shindex 712d1ae09..64e20cf66 100644--- a/examples/language-modeling/scripts/bloom-3b.sh+++ b/examples/language-modeling/scripts/bloom-3b.sh@@ -1,3 +1,4 @@+## This recipe is outdated, we recommend using the latest recipe for best accuracy in homepagepython3 main.py \--model_name bigscience/bloom-3b \--device 0 \@@ -5,5 +6,5 @@ python3 main.py \--bits 4 \--iters 1000 \--nsamples 512 \---deployment_device 'gpu' \+--format 'auto_round,auto_gptq' \--output_dir "./tmp_autoround"diff --git a/examples/language-modeling/scripts/falcon-7b.sh b/examples/language-modeling/scripts/falcon-7b.shindex adc6b5fba..b99bdc0c0 100644--- a/examples/language-modeling/scripts/falcon-7b.sh+++ b/examples/language-modeling/scripts/falcon-7b.sh@@ -1,3 +1,4 @@+## This recipe is outdated, we recommend using the latest recipe for best accuracy in homepagepython3 main.py \--model_name tiiuae/falcon-7b \--device 0 \@@ -5,6 +6,6 @@ python3 main.py \--bits 4 \--iters 1000 \--nsamples 512 \---deployment_device 'gpu' \+--format 'auto_round,auto_gptq' \--output_dir "./tmp_autoround" \--disable_quanted_input \\ No newline at end of filediff --git a/examples/language-modeling/scripts/gemma-2b.sh b/examples/language-modeling/scripts/gemma-2b.shindex 7bf58bc2a..40de71621 100644--- a/examples/language-modeling/scripts/gemma-2b.sh+++ b/examples/language-modeling/scripts/gemma-2b.sh@@ -1,6 +1,4 @@-git clone https://github.com/intel/auto-round-cd auto-round/examples/language-modeling-pip install -r requirements.txt+## This recipe is outdated, we recommend using the latest recipe for best accuracy in homepagepython3 main.py \--model_name google/gemma-2b \--device 0 \@@ -9,5 +7,5 @@ python3 main.py \--iters 400 \--model_dtype "float16" \--nsamples 512 \---deployment_device 'gpu' \+--format 'auto_round,auto_gptq' \--output_dir "./tmp_autoround"\ No newline at end of filediff --git a/examples/language-modeling/scripts/gemma-7b-it.sh b/examples/language-modeling/scripts/gemma-7b-it.shindex 63e18bcaf..a480ebbd3 100644--- a/examples/language-modeling/scripts/gemma-7b-it.sh+++ b/examples/language-modeling/scripts/gemma-7b-it.sh@@ -1,3 +1,4 @@+## This recipe is outdated, we recommend using the latest recipe for best accuracy in homepagepython3 main.py \--model_name google/gemma-7b-it \--device 0 \@@ -6,6 +7,6 @@ python3 main.py \--iters 1000 \--minmax_lr 2e-3 \--model_dtype "float16" \---deployment_device 'gpu' \+--format 'auto_round,auto_gptq' \--nsamples 512 \--output_dir "./tmp_autoround"\ No newline at end of filediff --git a/examples/language-modeling/scripts/gemma-7b.sh b/examples/language-modeling/scripts/gemma-7b.shindex 37a7b9872..42efb57e9 100644--- a/examples/language-modeling/scripts/gemma-7b.sh+++ b/examples/language-modeling/scripts/gemma-7b.sh@@ -1,3 +1,4 @@+## This recipe is outdated, we recommend using the latest recipe for best accuracy in homepagepython3 main.py \--model_name google/gemma-7b \--device 0 \@@ -6,6 +7,6 @@ python3 main.py \--iters 1000 \--nsamples 512 \--minmax_lr 2e-3 \---deployment_device 'gpu' \+--format 'auto_round,auto_gptq' \--model_dtype "float16" \--output_dir "./tmp_autoround"\ No newline at end of filediff --git a/examples/language-modeling/scripts/gpt-j-6b.sh b/examples/language-modeling/scripts/gpt-j-6b.shindex 99b90a678..0d954ba28 100644--- a/examples/language-modeling/scripts/gpt-j-6b.sh+++ b/examples/language-modeling/scripts/gpt-j-6b.sh@@ -1,3 +1,4 @@+## This recipe is outdated, we recommend using the latest recipe for best accuracy in homepagepython3 main.py \--model_name EleutherAI/gpt-j-6b \--device 0 \@@ -6,5 +7,5 @@ python3 main.py \--iters 1000 \--disable_quanted_input \--nsamples 512 \---deployment_device 'gpu' \+--format 'auto_round,auto_gptq' \--output_dir "./tmp_autoround"diff --git a/examples/language-modeling/scripts/neural-chat-7b-v3-1.sh b/examples/language-modeling/scripts/neural-chat-7b-v3-1.shindex ff3da6570..5d749ea2a 100644--- a/examples/language-modeling/scripts/neural-chat-7b-v3-1.sh+++ b/examples/language-modeling/scripts/neural-chat-7b-v3-1.sh@@ -1,3 +1,4 @@+## This recipe is outdated, we recommend using the latest recipe for best accuracy in homepage## enter to language-modeling foldpython3 main.py \--model_name /models/neural-chat-7b-v3-1 \@@ -7,6 +8,6 @@ python3 main.py \--iters 1000 \--nsamples 512 \--minmax_lr 2e-3 \---deployment_device 'gpu' \+--format 'auto_round,auto_gptq' \--output_dir "./tmp_autoround" \--disable_quanted_input\ No newline at end of filediff --git a/examples/language-modeling/scripts/neural-chat-7b-v3-3.sh b/examples/language-modeling/scripts/neural-chat-7b-v3-3.shindex 378266df5..0906841d0 100644--- a/examples/language-modeling/scripts/neural-chat-7b-v3-3.sh+++ b/examples/language-modeling/scripts/neural-chat-7b-v3-3.sh@@ -1,3 +1,4 @@+## This recipe is outdated, we recommend using the latest recipe for best accuracy in homepagepython3 main.py \--model_name Intel/neural-chat-7b-v3-3 \--device 0 \@@ -6,6 +7,6 @@ python3 main.py \--iters 1000 \--minmax_lr 2e-3 \--nsamples 512 \---deployment_device 'gpu' \+--format 'auto_round,auto_gptq' \--output_dir "./tmp_autoround" \--disable_quanted_input\ No newline at end of filediff --git a/examples/language-modeling/scripts/opt-2.7b.sh b/examples/language-modeling/scripts/opt-2.7b.shindex f7954ece8..9d8cf6708 100644--- a/examples/language-modeling/scripts/opt-2.7b.sh+++ b/examples/language-modeling/scripts/opt-2.7b.sh@@ -1,3 +1,4 @@+## This recipe is outdated, we recommend using the latest recipe for best accuracy in homepagepython3 main.py \--model_name facebook/opt-2.7b \--device 0 \@@ -7,5 +8,5 @@ python3 main.py \--minmax_lr 0.002 \--nsamples 512 \--disable_quanted_input \---deployment_device 'gpu' \+--format 'auto_round,auto_gptq' \--output_dir "./tmp_autoround"diff --git a/examples/language-modeling/scripts/phi-2.sh b/examples/language-modeling/scripts/phi-2.shindex 8b5a1b821..5421373f9 100644--- a/examples/language-modeling/scripts/phi-2.sh+++ b/examples/language-modeling/scripts/phi-2.sh@@ -1,3 +1,4 @@+## This recipe is outdated, we recommend using the latest recipe for best accuracy in homepagepython3 main.py \--model_name microsoft/phi-2 \--device 0 \@@ -6,5 +7,5 @@ python3 main.py \--iters 1000 \--sym \--nsamples 512 \---deployment_device 'gpu' \+--format 'auto_round,auto_gptq' \--output_dir "./tmp_autoround"\ No newline at end of filediff --git a/test/test_basic_usage.py b/test/test_basic_usage.pynew file mode 100644index 000000000..0ee08c9b6--- /dev/null+++ b/test/test_basic_usage.py@@ -0,0 +1,23 @@+import os+import shutil+import sys+import unittest+++class TestAutoRoundCmd(unittest.TestCase):+ @classmethod+ def setUpClass(self):+ pass++ @classmethod+ def tearDownClass(self):+ shutil.rmtree("./saved", ignore_errors=True)+ shutil.rmtree("runs", ignore_errors=True)++ def test_auto_round_cmd(self):+ python_path = sys.executable++ res = os.system(+ f"{python_path} ../auto_round/__main__.py --model 'facebook/opt-125m' --iter 2 --nsamples 1 --format auto_gptq,auto_round --disable_eval --output_dir ./saved")+ if res > 0 or res == -1:+ assert False, "cmd line test fail, please have acheck"diff --git a/test/test_mllm.py b/test/test_mllm.pyindex d919f4b0b..ce8de5593 100644--- a/test/test_mllm.py+++ b/test/test_mllm.py@@ -7,31 +7,38 @@ from auto_round import AutoRoundMLLMfrom transformers import AutoProcessor, AutoTokenizer, Qwen2VLForConditionalGeneration+import shutil+class FakeDataLoader:def __init__(self):self.batch_size = 1self.data = {- "text": [{'role': 'user', 'content': '<|vision_start|><|image_pad|><|vision_end|>\nWhat are the colors of the bus in the image?'}, {'role': 'assistant', 'content': 'The bus in the image is white and red.'}],+ "text": [{'role': 'user',+ 'content': '<|vision_start|><|image_pad|><|vision_end|>\nWhat are the colors of the bus in the image?'},+ {'role': 'assistant', 'content': 'The bus in the image is white and red.'}],"image": "http://images.cocodataset.org/train2017/000000033471.jpg"}-+def __iter__(self):for i in range(2):yield self.data+class TestAutoRoundMLLM(unittest.TestCase):@classmethoddef setUpClass(self):self.model_name = "Qwen/Qwen2-VL-2B-Instruct"self.dataset = FakeDataLoader()-@classmethoddef tearDownClass(self):+ shutil.rmtree("./saved", ignore_errors=True)+ shutil.rmtree("runs", ignore_errors=True)+return super().tearDownClass()-+def test_tune(self):tokenizer = AutoTokenizer.from_pretrained(self.model_name)processor = AutoProcessor.from_pretrained(self.model_name, trust_remote_code=True)@@ -44,6 +51,23 @@ class TestAutoRoundMLLM(unittest.TestCase):nsamples=2,batch_size=1, iters=2, dataset=self.dataset)autoround.quantize()+ autoround.save_quantized("./saved/", format="auto_gptq", inplace=False)+ autoround.save_quantized("./saved/", format="auto_round", inplace=False)++ def test_quant_vision(self): ## bug need to fix+ tokenizer = AutoTokenizer.from_pretrained(self.model_name)+ processor = AutoProcessor.from_pretrained(self.model_name, trust_remote_code=True)+ tokenizer.processor = processor+ model = Qwen2VLForConditionalGeneration.from_pretrained(+ self.model_name, trust_remote_code=True, device_map="auto")+ bits, group_size = 4, 128+ autoround = AutoRoundMLLM(+ model, tokenizer, bits=bits, group_size=group_size,+ nsamples=2,+ batch_size=1, iters=2, dataset=self.dataset, quant_nontext_module=True)+ autoround.quantize()+ autoround.save_quantized("./saved/", format="auto_round", inplace=True)+if __name__ == "__main__":unittest.main()