Skip to content

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

[Experimental Feature]support for common hf multimodel (#276)

n1ck-guoe643212582d1
diff --git a/README.md b/README.md
index a7597134f..2b31a85c0 100644
--- a/README.md
+++ b/README.md
@@ -4,7 +4,7 @@ AutoRound
===========================
<h3> Advanced Quantization Algorithm for LLMs</h3>
-[![python](https://img.shields.io/badge/python-3.8%2B-blue)](https://github.com/intel/auto-round)
+[![python](https://img.shields.io/badge/python-3.9%2B-blue)](https://github.com/intel/auto-round)
[![version](https://img.shields.io/badge/release-0.3.1-green)](https://github.com/intel/auto-round)
[![license](https://img.shields.io/badge/license-Apache%202-blue)](https://github.com/intel/auto-round/blob/main/LICENSE)
---
diff --git a/auto_round/__init__.py b/auto_round/__init__.py
index 0f00cf352..c8de3ea93 100644
--- a/auto_round/__init__.py
+++ b/auto_round/__init__.py
@@ -11,6 +11,7 @@
# 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.
-from .autoround import AutoRound, AutoAdamRound, AutoOPTRound
+from .autoround import AutoRound, AutoRoundAdam, AutoRoundOPT
+from .mllm import AutoRoundMLLM
from .auto_quantizer import AutoHfQuantizer,AutoRoundConfig
from .version import __version__
\ No newline at end of file
diff --git a/auto_round/__main__.py b/auto_round/__main__.py
index 29c73231d..340d457ef 100644
--- a/auto_round/__main__.py
+++ b/auto_round/__main__.py
@@ -21,7 +21,7 @@ import transformers
os.environ["CUBLAS_WORKSPACE_CONFIG"] = ":4096:8"
torch.use_deterministic_algorithms(True, warn_only=True)
-from transformers import AutoModelForCausalLM, AutoTokenizer, AutoModel
+from transformers import AutoModelForCausalLM, AutoTokenizer, AutoModel, AutoConfig, AutoProcessor
from lm_eval.utils import make_table # pylint: disable=E0401
from auto_round import AutoRoundConfig
@@ -29,134 +29,196 @@ from auto_round.eval.evaluation import simple_evaluate
from auto_round.utils import detect_device, get_library_version, detect_device_count
from auto_round.utils import logger
+class BasicArgumentParser(argparse.ArgumentParser):
+ def __init__(self, *args, **kwargs):
+ super().__init__( *args, **kwargs)
+ self.add_argument("--model", default="facebook/opt-125m", help="model name or path")
-def setup_parser():
- parser = argparse.ArgumentParser()
+ self.add_argument('--eval', action='store_true',
+ help="whether to use eval only mode.")
- parser.add_argument(
- "--model", default="facebook/opt-125m"
- )
+ self.add_argument("--bits", default=4, type=int,
+ help="number of bits")
- parser.add_argument('--eval', action='store_true',
- help="whether to use eval only mode.")
+ self.add_argument("--eval_bs", default=None, type=int,
+ help="eval batch size")
- parser.add_argument("--bits", default=4, type=int,
- help="number of bits")
+ self.add_argument("--device", default="auto", type=str,
+ help="The device to be used for tuning. The default is set to auto/None,"
+ "allowing for automatic detection."
+ " Currently, device settings support CPU, GPU, and HPU.")
+
+ self.add_argument("--asym", action='store_true',
+ help=" asym quantization")
- parser.add_argument("--group_size", default=128, type=int,
- help="group size")
+ self.add_argument("--dataset", default="NeelNanda/pile-10k", type=str,
+ help="The dataset for quantization training. It can be a custom one.")
- parser.add_argument("--batch_size", default=8, type=int,
- help="train batch size")
+ self.add_argument("--lr", default=None, type=float,
+ help="learning rate, if None, it will be set to 1.0/iters automatically")
- parser.add_argument("--eval_bs", default=None, type=int,
- help="eval batch size")
+ self.add_argument("--minmax_lr", default=None, type=float,
+ help="minmax learning rate, if None,it will beset to be the same with lr")
- parser.add_argument("--device", default="auto", type=str,
- help="The device to be used for tuning. The default is set to auto/None,"
- "allowing for automatic detection. Currently, device settings support CPU, GPU, and HPU.")
+ self.add_argument("--seed", default=42, type=int,
+ help="seed")
- parser.add_argument("--asym", action='store_true',
- help=" asym quantization")
+ self.add_argument("--adam", action='store_true',
+ help="adam")
+
+ self.add_argument("--gradient_accumulate_steps", default=1, type=int, help="gradient accumulate steps")
- parser.add_argument("--iters", default=200, type=int,
- help=" iters")
+ self.add_argument("--nblocks", default=1, type=int, help="num of blocks to tune together")
- parser.add_argument("--dataset", default="NeelNanda/pile-10k", type=str,
- help="The dataset for quantization training. It can be a custom one.")
+ self.add_argument("--low_gpu_mem_usage", action='store_true',
+ help="lower gpu memory usage but 50-100% slower")
+
+ self.add_argument("--format", default=None, type=str,
+ help="The format in which to save the model. "
+ "The options are 'auto_round', 'auto_round:gptq','auto_round:awq',"
+ " 'auto_gptq', 'auto_awq', 'itrex', 'itrex_xpu' and 'fake'."
+ "default to 'auto_round."
+ )
- parser.add_argument("--lr", default=None, type=float,
- help="learning rate, if None, it will be set to 1.0/iters automatically")
+ self.add_argument("--data_type", default='int',
+ help="data type for tuning, 'int', 'mx_fp' and etc.")
- parser.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("--scale_dtype", default='fp16',
+ help="which scale data type to use for quantization, 'fp16', 'fp32' or 'bf16'.")
- parser.add_argument("--seed", default=42, type=int,
- help="seed")
+ self.add_argument("--tasks",
+ default="lambada_openai,hellaswag,winogrande,piqa,mmlu,wikitext,truthfulqa_mc1," \
+ "truthfulqa_mc2,openbookqa,boolq,rte,arc_easy,arc_challenge",
+ help="lm-eval tasks for lm_eval version 0.4")
- parser.add_argument("--adam", action='store_true',
- help="adam")
+ self.add_argument("--output_dir", default="./tmp_autoround", type=str,
+ help="Where to store the final model.")
- parser.add_argument("--seqlen", default=2048, type=int,
- help="sequence length")
+ self.add_argument("--disable_eval", action='store_true',
+ help="Whether to do lm-eval evaluation after tuning.")
- parser.add_argument("--gradient_accumulate_steps", default=1, type=int, help="gradient accumulate steps")
+ self.add_argument("--disable_amp", action='store_true',
+ help="disable amp")
- parser.add_argument("--nblocks", default=1, type=int, help="num of blocks to tune together")
+ self.add_argument("--disable_minmax_tuning", action='store_true',
+ help="whether disable enable weight minmax tuning")
- parser.add_argument("--nsamples", default=128, type=int,
- help="number of samples")
+ self.add_argument("--enable_norm_bias_tuning", action='store_true',
+ help="whether enable norm bias tuning")
- parser.add_argument("--low_gpu_mem_usage", action='store_true',
- help="lower gpu memory but 50%-100% slower")
+ self.add_argument("--disable_trust_remote_code", action='store_true',
+ help="Whether to disable trust_remote_code")
- parser.add_argument("--format", default=None, type=str,
- help="The format in which to save the model. "
- "The options are 'auto_round', 'auto_round:gptq','auto_round:awq',"
- " 'auto_gptq', 'auto_awq', 'itrex', 'itrex_xpu' and 'fake'."
- "default to 'auto_round."
- )
+ self.add_argument("--disable_quanted_input", action='store_true',
+ help="whether to disuse the output of quantized block to tune the next block")
- parser.add_argument("--data_type", default='int',
- help="data type for tuning, 'int', 'mx_fp' and etc.")
+ self.add_argument("--quant_lm_head", action='store_true',
+ help="quant_lm_head")
- parser.add_argument("--scale_dtype", default='fp16',
- help="which scale data type to use for quantization, 'fp16', 'fp32' or 'bf16'.")
+ self.add_argument("--low_cpu_mem_mode", default=0, type=int,
+ help="Choose which low cpu memory mode to use. "
+ "Can significantly reduce cpu memory footprint but cost more time."
+ "1 means choose block-wise mode, load the weights of each block"
+ " from disk when tuning and release the memory of the block after tuning."
+ "2 means choose layer-wise mode, load the weights of each layer from disk when tuning,"
+ " minimum memory consumption and also slowest running speed."
+ "others means not use low cpu memory. Default to 0, not use low cpu memory.")
- parser.add_argument("--tasks",
- default="lambada_openai,hellaswag,winogrande,piqa,mmlu,wikitext,truthfulqa_mc1," \
- "truthfulqa_mc2,openbookqa,boolq,rte,arc_easy,arc_challenge",
- help="lm-eval tasks for lm_eval version 0.4")
+ self.add_argument("--low_cpu_mem_tmp_dir", default=None, type=str,
+ help="temp work space to store the temporary files "
+ "when using low cpu memory mode. Will remove after tuning.")
- parser.add_argument("--output_dir", default="./tmp_autoround", type=str,
- help="Where to store the final model.")
+ self.add_argument("--model_dtype", default=None, type=str,
+ help="force to convert the dtype, some backends supports fp16 dtype better")
- parser.add_argument("--disable_eval", action='store_true',
- help="Whether to do lm-eval evaluation after tuning.")
+ self.add_argument("--act_bits", default=32, type=int,
+ help="activation bits")
- parser.add_argument("--disable_amp", action='store_true',
- help="disable amp")
+ self.add_argument("--fp_layers_list", default="", type=str,
+ help="List of Layers to maintain original data type")
- parser.add_argument("--disable_minmax_tuning", action='store_true',
- help="whether disable enable weight minmax tuning")
+ ## ======================= VLM =======================
+ self.add_argument("--mllm", action='store_true',
+ help="To determine whether use multimodel-llm mode.")
- parser.add_argument("--enable_norm_bias_tuning", action='store_true',
- help="whether enable norm bias tuning")
+ self.add_argument("--quant_vision", action='store_true',
+ help="To determine whether the quantization should handle vision component.")
- parser.add_argument("--disable_trust_remote_code", action='store_true',
- help="Whether to disable trust_remote_code")
+ self.add_argument("--extra_data_dir", default="", type=str,
+ help="Dataset dir for storing images/audio/videos. "
+ "Can be a dir path or multiple dir path with format as "
+ "'image=path_to_image,video=path_to_video,audio=path_to_audio'"
+ "By default, it will search in the relative path.")
+
+ self.add_argument("--template", default=None, type=str,
+ help="The template for building training dataset. It can be a custom one.")
- parser.add_argument("--disable_quanted_input", action='store_true',
- help="whether to disuse the output of quantized block to tune the next block")
- parser.add_argument("--quant_lm_head", action='store_true',
- help="quant_lm_head")
+def setup_parser():
+ parser = BasicArgumentParser()
- parser.add_argument("--low_cpu_mem_mode", default=0, type=int,
- help="Choose which low cpu memory mode to use. "
- "Can significantly reduce cpu memory footprint but cost more time."
- "1 means choose block-wise mode, load the weights of each block"
- " from disk when tuning and release the memory of the block after tuning."
- "2 means choose layer-wise mode, load the weights of each layer from disk when tuning,"
- " minimum memory consumption and also slowest running speed."
- "others means not use low cpu memory. Default to 0, not use low cpu memory.")
+ parser.add_argument("--group_size", default=128, type=int,
+ help="group size")
- parser.add_argument("--low_cpu_mem_tmp_dir", default=None, type=str,
- help="temp work space to store the temporary files "
- "when using low cpu memory mode. Will remove after tuning.")
+ parser.add_argument("--batch_size", default=8, type=int,
+ help="train batch size")
- parser.add_argument("--model_dtype", default=None, type=str,
- help="force to convert the dtype, some backends supports fp16 dtype better")
+ parser.add_argument("--iters", default=200, type=int,
+ help=" iters")
- parser.add_argument("--act_bits", default=32, type=int,
- help="activation bits")
+ parser.add_argument("--seqlen", default=2048, type=int,
+ help="sequence length")
- parser.add_argument("--fp_layers_list", default="", type=str,
- help="List of Layers to maintain original data type")
+ parser.add_argument("--nsamples", default=128, type=int,
+ help="number of samples")
args = parser.parse_args()
return args
+def setup_best_parser():
+ parser = BasicArgumentParser()
+
+ parser.add_argument("--group_size", default=128, type=int,
+ help="group size")
+
+ parser.add_argument("--batch_size", default=8, type=int,
+ help="train batch size")
+
+ parser.add_argument("--iters", default=1000, type=int,
+ help=" iters")
+
+ parser.add_argument("--seqlen", default=2048, type=int,
+ help="sequence length")
+
+ parser.add_argument("--nsamples", default=512, type=int,
+ help="number of samples")
+
+ args = parser.parse_args()
+ args.low_gpu_mem_usage = True
+
+ return args
+
+def setup_fast_parser():
+ parser = BasicArgumentParser()
+
+ parser.add_argument("--group_size", default=128, type=int,
+ help="group size")
+
+ parser.add_argument("--batch_size", default=4, type=int,
+ help="train batch size")
+
+ parser.add_argument("--iters", default=200, type=int,
+ help=" iters")
+
+ parser.add_argument("--seqlen", default=512, type=int,
+ help="sequence length")
+
+ parser.add_argument("--nsamples", default=128, type=int,
+ help="number of samples")
+
+ args = parser.parse_args()
+
+ return args
def tune(args):
tasks = args.tasks
@@ -182,7 +244,11 @@ def tune(args):
is_glm = bool(re.search("chatglm", model_name.lower()))
low_cpu_mem_usage = False
+
+ tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=not args.disable_trust_remote_code)
+
model_cls = AutoModel if is_glm else AutoModelForCausalLM
+
if args.low_cpu_mem_tmp_dir is None:
args.low_cpu_mem_tmp_dir = os.path.join(args.output_dir, "low_cpu_mem_tmp")
if args.low_cpu_mem_mode == 2:
@@ -219,7 +285,7 @@ def tune(args):
trust_remote_code=not args.disable_trust_remote_code
)
- from auto_round import AutoRound, AutoAdamRound
+ from auto_round import AutoRound, AutoRoundAdam
model = model.eval()
# align with GPTQ to eval ppl
@@ -236,7 +302,6 @@ def tune(args):
if args.model_dtype == "bfloat16" or args.model_dtype == "bfp16":
model = model.to(torch.bfloat16)
- tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=not args.disable_trust_remote_code)
if hasattr(tokenizer, "model_max_length"):
if tokenizer.model_max_length < seqlen:
@@ -250,7 +315,7 @@ def tune(args):
round = AutoRound
if args.adam:
- round = AutoAdamRound
+ round = AutoRoundAdam
layer_config = {}
for n, m in model.named_modules():
@@ -273,7 +338,6 @@ def tune(args):
for n, _ in model.named_modules():
lm_head_layer_name = n
if args.quant_lm_head:
- from transformers import AutoConfig
config = AutoConfig.from_pretrained(model_name, trust_remote_code=not args.disable_trust_remote_code)
if config.tie_word_embeddings and hasattr(model, "_tied_weights_keys"):
tied_keys = model._tied_weights_keys
@@ -365,15 +429,138 @@ def eval(args):
print(make_table(res))
+def tune_mllm(args):
+ if args.format is None:
+ args.format = "auto_round"
+
+ if "auto_gptq" in args.format and args.asym is True:
+ print(
+ "warning: The auto_gptq kernel has issues with asymmetric quantization. "
+ "It is recommended to use sym quantization or --format='auto_round'")
+
+ if "marlin" in args.format and args.asym is True:
+ assert False, "marlin backend only supports sym quantization, please remove --asym"
+
+ model_name = args.model
+ if model_name[-1] == "/":
+ model_name = model_name[:-1]
+ logger.info(f"start to quantize {model_name}")
+
+
+ device_str = detect_device(args.device)
+ torch_dtype = "auto"
+ if "hpu" in device_str:
+ torch_dtype = torch.bfloat16
+
+ torch.manual_seed(1234)
+
+ # load_model
+ config = AutoConfig.from_pretrained(model_name, trust_remote_code=not args.disable_trust_remote_code)
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
+ processor = AutoProcessor.from_pretrained(model_name, trust_remote_code=not args.disable_trust_remote_code)
+ tokenizer.processor = processor
+ model_type = config.model_type
+ if "qwen2_vl" in model_type:
+ from transformers import Qwen2VLForConditionalGeneration
+ cls = Qwen2VLForConditionalGeneration
+ elif "mllama" in model_type:
+ from transformers import MllamaForConditionalGeneration
+ cls = MllamaForConditionalGeneration
+ else:
+ cls = AutoModelForCausalLM
+ model = cls.from_pretrained(
+ model_name,trust_remote_code=not args.disable_trust_remote_code, torch_dtype=torch_dtype)
+
+ if "cogvlm2" in model_name:
+ model.config.model_type = "cogvlm2"
+
+ from auto_round import AutoRoundMLLM
+
+ model = model.eval()
+ seqlen = args.seqlen
+
+ round = AutoRoundMLLM
+ layer_config = {}
+ for n, m in model.named_modules():
+ if isinstance(m, torch.nn.Linear) or isinstance(m, transformers.modeling_utils.Conv1D):
+ if m.weight.shape[0] % 32 != 0 or m.weight.shape[1] % 32 != 0:
+ layer_config[n] = {"bits": 32}
+ logger.info(
+ f"{n} will not be quantized due to its shape not being divisible by 32,"
+ " resulting in an exporting issue to autogptq")
+ lm_head_layer_name = "lm_head"
+ for n, _ in model.named_modules():
+ lm_head_layer_name = n
+ if args.quant_lm_head:
+ config = AutoConfig.from_pretrained(model_name, trust_remote_code=not args.disable_trust_remote_code)
+ if config.tie_word_embeddings and hasattr(model, "_tied_weights_keys"):
+ tied_keys = model._tied_weights_keys
+ for item in tied_keys:
+ if lm_head_layer_name in item: ##TODO extend to encoder-decoder layer, seq classification model
+ args.quant_lm_head = False
+ print(
+ f"warning, disable quant_lm_head as quantizing lm_head with tied weights has not been "
+ f"supported currently")
+ break
+ if args.quant_lm_head:
+ layer_config[lm_head_layer_name] = {"bits": args.bits}
+ transformers_version = [int(item) for item in transformers.__version__.split('.')[:2]]
+ if transformers_version[0] == 4 and transformers_version[1] < 38:
+ error_message = "Please upgrade transformers>=4.38.0 to support lm-head quantization."
+ raise EnvironmentError(error_message)
+
+ if args.quant_lm_head and args.low_gpu_mem_usage:
+ print(f"warning, low_gpu_mem_usage=False is strongly recommended if the whole model could be loaded to "
+ f"gpu")
+
+ autoround = round(model, tokenizer, dataset=args.dataset, extra_data_dir=args.extra_data_dir,
+ bits=args.bits, group_size=args.group_size, sym=not args.asym,
+ batch_size=args.batch_size, seqlen=seqlen, nblocks=args.nblocks, iters=args.iters,
+ lr=args.lr, minmax_lr=args.minmax_lr, enable_quanted_input=not args.disable_quanted_input,
+ amp=not args.disable_amp, nsamples=args.nsamples, low_gpu_mem_usage=args.low_gpu_mem_usage,
+ device=device_str, seed=args.seed, gradient_accumulate_steps=args.gradient_accumulate_steps,
+ scale_dtype=args.scale_dtype, layer_config=layer_config,
+ enable_minmax_tuning=not args.disable_minmax_tuning, act_bits=args.act_bits,
+ quant_vision=args.quant_vision)
+ model, _ = autoround.quantize()
+
+ model.eval()
+ if args.device != "cpu":
+ torch.cuda.empty_cache()
+
+ export_dir = args.output_dir + "/" + model_name.split('/')[-1] + f"-autoround-w{args.bits}g{args.group_size}"
+
+ format_list = args.format.replace(' ', '').split(',')
+ inplace = False if len(format_list) > 1 else True
+ for format_ in format_list:
+ eval_folder = f'{export_dir}-{format_}'
+ autoround.save_quantized(eval_folder, format=format_, inplace=inplace, processor=processor)
+
+
def run():
args = setup_parser()
if args.eval_bs is None:
args.eval_bs = "auto"
if args.eval:
eval(args)
+ elif args.mllm:
+ tune_mllm(args)
else:
tune(args)
+def run_best():
+ args = setup_best_parser()
+ tune(args)
+
+def run_fast():
+ args = setup_fast_parser()
+ tune(args)
+
+
+def run_mllm():
+ args = setup_parser()
+ tune_mllm(args)
+
if __name__ == '__main__':
run()
diff --git a/auto_round/autoround.py b/auto_round/autoround.py
index 0cb2c3ff4..731974ec1 100644
--- a/auto_round/autoround.py
+++ b/auto_round/autoround.py
@@ -22,6 +22,7 @@ from typing import Optional, Union
from transformers import set_seed
from torch import autocast
from tqdm import tqdm
+import accelerate
from .quantizer import WrapperMultiblock, wrapper_block, unwrapper_block, WrapperLinear, unwrapper_layer, \
WrapperTransformerConv1d
@@ -48,10 +49,9 @@ from .utils import (
get_layer_names_in_block,
mv_module_from_gpu,
unsupport_meta_device, detect_device_count, clear_memory,
+ get_multimodal_block_names,
)
-
from .low_cpu_mem.utils import get_layers_before_block
-import accelerate
class AutoRound(object):
@@ -529,11 +529,10 @@ class AutoRound(object):
for key in data.keys():
data_new[key] = to_device(data[key], self.model.device)
if key == 'images':
- data_new[key] = to_dtype(data[key], self.model.dtype)
+ data_new[key] = to_dtype(data_new[key], self.model.dtype)
input_ids = data_new["input_ids"]
if input_ids.shape[-1] < self.seqlen:
continue
-
try:
if isinstance(data_new, torch.Tensor):
self.model(data_new)
@@ -544,7 +543,7 @@ class AutoRound(object):
except NotImplementedError:
pass
except Exception as error:
- logger.error(error)
+ raise error
total_cnt += input_ids.shape[0] if len(input_ids.shape) > 1 else 1
if total_cnt >= nsamples:
break
@@ -595,18 +594,21 @@ class AutoRound(object):
)
self.model = mv_module_from_gpu(self.model, self.low_cpu_mem_usage)
clear_memory()
- except:
- logger.info("switch to cpu to cache inputs")
- if "lm_head" in self.layer_config and self.layer_config["lm_head"]["bits"] < 8:
- 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"Otherwise, the process may be significantly slower.")
- self.model = mv_module_from_gpu(self.model, self.low_cpu_mem_usage)
- clear_memory()
- all_inputs = self.cache_inter_data(
- block_names, nsamples, layer_names=layer_names, last_cache_name=last_cache_name
- )
+ 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:
+ 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"Otherwise, the process may be significantly slower.")
+ self.model = mv_module_from_gpu(self.model, self.low_cpu_mem_usage)
+ clear_memory()
+ all_inputs = self.cache_inter_data(
+ block_names, nsamples, layer_names=layer_names, last_cache_name=last_cache_name
+ )
+ else:
+ raise
return all_inputs
@torch.no_grad()
@@ -1330,7 +1332,7 @@ class AutoRound(object):
lr_schedule.step()
-class AutoOPTRound(AutoRound):
+class AutoRoundOPT(AutoRound):
"""Class for automatic rounding-based quantization with optimizers like adamw of a PyTorch model.
Args:
@@ -1413,7 +1415,7 @@ class AutoOPTRound(AutoRound):
optimizer="AdamW",
**kwargs,
):
- super(AutoOPTRound, self).__init__(
+ super(AutoRoundOPT, self).__init__(
model=model,
tokenizer=tokenizer,
bits=bits,
@@ -1493,7 +1495,7 @@ class AutoOPTRound(AutoRound):
htcore.mark_step()
-class AutoAdamRound(AutoOPTRound):
+class AutoRoundAdam(AutoRoundOPT):
"""Class for automatic rounding-based quantization with optimizers like adamw of a PyTorch model.
The default lr has been changed.
@@ -1577,7 +1579,7 @@ class AutoAdamRound(AutoOPTRound):
optimizer="AdamW",
**kwargs,
):
- super(AutoAdamRound, self).__init__(
+ super(AutoRoundAdam, self).__init__(
model=model,
tokenizer=tokenizer,
bits=bits,
diff --git a/auto_round/mllm/README.md b/auto_round/mllm/README.md
new file mode 100644
index 000000000..9060c1689
--- /dev/null
+++ b/auto_round/mllm/README.md
@@ -0,0 +1,49 @@
+# AutoRound for MLLMs
+## API Usage (Gaudi2/CPU/GPU)
+```python
+from auto_round import AutoRoundMLLM
+from transformers import Qwen2VLForConditionalGeneration, AutoProcessor, AutoTokenizer
+
+model_name = "Qwen/Qwen2-VL-2B-Instruct"
+tokenizer = AutoTokenizer.from_pretrained(model_name)
+processor = AutoProcessor.from_pretrained(model_name, trust_remote_code=trust_remote_code)
+tokenizer.processor = processor
+model = Qwen2VLForConditionalGeneration.from_pretrained(
+ model_name, trust_remote_code=True)
+dataset = "/path/to/llava.json"
+extra_data_dir = "/path/to/images/dir"
+
+bits, group_size = 4, 128
+autoround = AutoRoundMLLM(model, tokenizer, bits=bits, group_size=group_size, dataset=dataset, extra_data_dir=extra_data_dir)
+
+autoround.quantize()
+output_dir = "./tmp_autoround"
+autoround.save_quantized(output_dir, format='auto_round', inplace=True)
+```
+
+## Template
+For autoround MLLMs, using Template to customize different operations for different models. User can add a custom chat template through json file as below.
+```json
+{
+ "model_type": "qwen2_vl",
+ "format_user": "<|im_start|>user\n{{content}}<|im_end|>\n",
+ "format_assistant": "<|im_start|>assistant\n{{content}}<|im_end|>\n",
+ "format_system": "<|im_start|>system\n{{content}}<|im_end|>\n",
+ "format_observation": "<|im_start|>tool\n{{content}}<|im_end|>\n<|im_start|>assistant\n",
+ "format_separator": "\n",
+ "default_system": "You are a helpful assistant.",
+ "replace_tokens": ["<image>", "<|vision_start|><|image_pad|><|vision_end|>"],
+ "processor": "qwen2_vl" }
+```
+The special token ```{{content}}``` is a placeholder to tell the preprocessor where to fill in the corresponding dialogue content.
+
+```format_*```: Add specific token to chat content depends on different role names.
+
+For example, the input conversations:<br>
+ ```[{'role': 'user', 'value': '<image>\nWhat are the colors of the bus in the image?'}, {'role': 'assistant', 'value': 'The bus in the image is white and red.'}]```
+
+Using the above template, the input will be converted to the specified format required by Qwen2-vl as below: <br>
+ ```'<|im_start|>system\nYou are a helpful assistant.<|im_end|>\n<|im_start|>user\n<|vision_start|><|image_pad|><|vision_end|>\nWhat are the colors of the bus in the image?<|im_end|>\n<|im_start|>assistant\nThe bus in the image is white and red.<|im_end|>\n<|im_start|>user\nWhat feature can be seen on the back of the bus?<|im_end|>\n<|im_start|>assistant\nThe back of the bus features an advertisement.<|im_end|>\n<|im_start|>user\nIs the bus driving down the street or pulled off to the side?<|im_end|>\n<|im_start|>assistant\nThe bus is driving down the street, which is crowded with people and other vehicles.<|im_end|>\n'```.
+
+## Processor
+Processor is callback interface for calling different processors, such as texts or images processors, for MLLMs. User can define own processor and use registration function to declare. For more information, please refer to the relevant code in ```auto_round/mllm/processor.py```.
\ No newline at end of file
diff --git a/auto_round/mllm/__init__.py b/auto_round/mllm/__init__.py
new file mode 100644
index 000000000..800309207
--- /dev/null
+++ b/auto_round/mllm/__init__.py
@@ -0,0 +1,17 @@
+# Copyright (c) 2024 Intel Corporation
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from .mllm_dataset import get_mllm_dataloader
+from .template import Template, get_template, TEMPLATES
+from .autoround_mllm import AutoRoundMLLM
\ No newline at end of file
diff --git a/auto_round/mllm/autoround_mllm.py b/auto_round/mllm/autoround_mllm.py
new file mode 100644
index 000000000..45e1b57e3
--- /dev/null
+++ b/auto_round/mllm/autoround_mllm.py
@@ -0,0 +1,278 @@
+# Copyright (c) 2024 Intel Corporation
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from typing import Optional, Union
+
+import torch
+
+from ..utils import (
+ logger,
+ to_device,
+ to_dtype,
+ get_multimodal_block_names
+)
+from ..autoround import AutoRound
+from .template import get_template, Template
+from .mllm_dataset import get_mllm_dataloader
+from ..low_cpu_mem.utils import get_layers_before_block
+
+class AutoRoundMLLM(AutoRound):
+ """Class for automatic rounding-based quantization with MLLMs.
+
+ Args:
+ model: The PyTorch model to be quantized.
+ tokenizer: An optional tokenizer for processing input data.
+ bits (int): Number of bits for quantization (default is 4).
+ group_size (int): Size of the quantization group (default is 128).
+ sym (bool): Whether sym to be used (default is True).
+ layer_config (dict): Configuration for weight quantization (default is None).
+ batch_size (int): Batch size for training (default is 8).
+ amp (bool): Whether to use automatic mixed precision (default is True).
+ device: The device to be used for training (default is "auto").
+ lr_scheduler: The learning rate scheduler to be used.
+ dataset: The path or name of the calib dataset.
+ extra_data_dir: The path of extra data such as images, audio and videos.
+ template: The path or name of template used to specify process for different MLLMs.
+ quant_nontext_module: Whether to quantize nontext module.
+ enable_quanted_input (bool): Whether to use quantized input data (default is True).
+ enable_minmax_tuning (bool): Whether to enable min-max tuning (default is True).
+ lr (float): The learning rate (default is 0.005).
+ minmax_lr (float): The learning rate for min-max tuning (default is None).
+ low_gpu_mem_usage (bool): Whether to use low GPU memory (default is False).
+ low_cpu_mem_usage (bool): Whether to use low CPU memory (default is False).
+ iters (int): Number of iterations (default is 200).
+ seqlen (int): Length of the sequence.
+ nsamples (int): Number of samples (default is 128).
+ sampler (str): The sampling method (default is "rand").
+ seed (int): The random seed (default is 42).
+ nblocks (int): Number of blocks (default is 1).
+ gradient_accumulate_steps (int): Number of gradient accumulation steps (default is 1).
+ not_use_best_mse (bool): Whether to use mean squared error (default is False).
+ dynamic_max_gap (int): The dynamic maximum gap (default is -1).
+ data_type (str): The data type to be used (default is "int").
+ scale_dtype (str): The data type of quantization scale to be used (default is "float16"), different kernels
+ have different choices.
+ act_bits (int): Number of bits for activation quantization. Default is 32.
+ act_group_size (int): Group size for activation quantization. Default is None.
+ act_sym (bool): Whether to use symmetric activation quantization. Default is None.
+ act_dynamic (bool): Whether to use dynamic activation quantization. Default is True.
+ quant_block_list (list): A list whose elements are list of block's layer names to be quantized.
+ **kwargs: Additional keyword arguments.
+ """
+ def __init__(
+ self,
+ model,
+ tokenizer,
+ bits: int = 4,
+ group_size: int = 128,
+ sym: bool = False,
+ layer_config: dict = None,
+ batch_size: int = 8,
+ amp: bool = True,
+ device: str = None,
+ lr_scheduler=None,
+ dataset: Union[str, list, tuple, torch.utils.data.DataLoader] = None,
+ extra_data_dir: Union[str, torch.utils.data.DataLoader] = None,
+ template: Union[str, Template] = None,
+ quant_nontext_module: bool = False,
+ enable_quanted_input: bool = True,
+ enable_minmax_tuning: bool = True,
+ lr: float = None,
+ minmax_lr: float = None,
+ low_gpu_mem_usage: bool = False,
+ low_cpu_mem_usage: bool = False,
+ iters: int = 200,
+ seqlen: int = 2048,
+ nsamples: int = 128,
+ sampler: str = "rand",
+ seed: int = 42,
+ nblocks: int = 1,
+ gradient_accumulate_steps: int = 1,
+ not_use_best_mse: bool = False,
+ dynamic_max_gap: int = -1,
+ data_type: str = "int",
+ scale_dtype: str = "fp16",
+ act_bits: int = 32,
+ act_group_size: int = None,
+ act_sym: bool = None,
+ act_dynamic: bool = True,
+ quant_block_list: list = None,
+ enable_norm_bias_tuning: bool = False,
+ **kwargs,
+ ):
+ if quant_block_list is None:
+ quant_block_list = get_multimodal_block_names(model, quant_nontext_module)
+ self.extra_data_dir = extra_data_dir
+ self.quant_nontext_module = quant_nontext_module
+ self.template = template
+ if self.template is None:
+ self.template = get_template(model.config.model_type)
+ assert dataset is not None, "dataset should not be None"
+ if isinstance(dataset, str):
+ dataset = get_mllm_dataloader(self.template, model, tokenizer, dataset, extra_data_dir, seqlen, batch_size)
+
+ super(AutoRoundMLLM, self).__init__(
+ model=model,
+ tokenizer=tokenizer,
+ bits=bits,
+ group_size=group_size,
+ sym=sym,
+ layer_config=layer_config,
+ batch_size=batch_size,
+ amp=amp,
+ device=device,
+ lr_scheduler=lr_scheduler,
+ dataset=dataset,
+ enable_quanted_input=enable_quanted_input,
+ enable_minmax_tuning=enable_minmax_tuning,
+ lr=lr,
+ minmax_lr=minmax_lr,
+ low_gpu_mem_usage=low_gpu_mem_usage,
+ low_cpu_mem_usage=low_cpu_mem_usage,
+ iters=iters,
+ seqlen=seqlen,
+ nsamples=nsamples,
+ sampler=sampler,
+ seed=seed,
+ nblocks=nblocks,
+ gradient_accumulate_steps=gradient_accumulate_steps,
+ not_use_best_mse=not_use_best_mse,
+ dynamic_max_gap=dynamic_max_gap,
+ data_type=data_type,
+ scale_dtype=scale_dtype,
+ act_bits=act_bits,
+ act_group_size=act_group_size,
+ act_sym=act_sym,
+ act_dynamic=act_dynamic,
+ enable_norm_bias_tuning=enable_norm_bias_tuning,
+ quant_block_list=quant_block_list,
+ **kwargs,
+ )
+
+
+ def calib(self, nsamples, bs):
+ """Perform calibration for quantization.
+
+ This method calibrates the model for quantization by processing a specified
+ number of samples from the calibration dataset. It ensures that the data is
+ properly formatted and feeds it to the model. If the number of samples processed
+ is less than the specified number, it logs a warning. If no samples are processed,
+ it logs an error and exits.
+ Args:
+ nsamples (int): The number of samples to use for calibration.
+ bs (int): The number of samples to use for calibration
+ """
+ if isinstance(self.dataset, str):
+ dataset = self.dataset.replace(" ", "")
+ self.dataloader = get_mllm_dataloader(
+ self.template, self.model, self.tokenizer, dataset, self.extra_data_dir, self.seqlen, bs)
+ else:
+ self.dataloader = self.dataset
+ total_cnt = 0
+
+ if self.low_cpu_mem_usage:
+ embed_layers = get_layers_before_block(self.model)
+ for n, m in embed_layers:
+ m = m.to(self.device)
+
+ for data in self.dataloader:
+ if data is None:
+ continue
+ if isinstance(data, torch.Tensor):
+ input_ids = data.to(self.device)
+ data_new = input_ids
+ elif isinstance(data, str):
+ if self.tokenizer is None:
+ logger.error("please provide tokenizer for string input")
+ exit()
+ # data = self.template._encode(data)
+ data = self.template.processor.get_input(
+ self.model,
+ self.tokenizer,
+ text=data,
+ images=None,
+ max_length=self.seqlen,
+ squeeze=False,
+ )
+ data_new = {}
+ for key in data.keys():
+ data_new[key] = data[key].to(self.device)
+ input_ids = data_new["input_ids"]
+ elif isinstance(data, dict) and "text" in data.keys():
+ text = data['text']
+ if isinstance(text, dict):
+ text = [text]
+ input_text = self.template._encode(text)
+ image = None
+ if "image" in data:
+ image = self.template.processor.image_processor(data["image"])
+ data = self.template.processor.get_input(
+ self.model,
+ self.tokenizer,
+ text=input_text,
+ images=image,
+ max_length=self.seqlen,
+ squeeze=False,
+ )
+ data_new = {}
+ for key in data.keys():
+ data_new[key] = to_device(data[key], self.model.device)
+ if key == 'images':
+ data_new[key] = to_dtype(data_new[key], self.model.dtype)
+ input_ids = data_new["input_ids"]
+ elif isinstance(data, tuple) or isinstance(data, list):
+ data_new = data
+ input_ids = data_new[0]
+ else:
+ data_new = {}
+ for key in data.keys():
+ data_new[key] = to_device(data[key], self.model.device)
+ if key == 'images':
+ data_new[key] = to_dtype(data_new[key], self.model.dtype)
+ input_ids = data_new["input_ids"]
+
+ if input_ids.shape[-1] < self.seqlen:
+ continue
+
+ try:
+ if isinstance(data_new, torch.Tensor):
+ self.model(data_new)
+ elif isinstance(data_new, tuple) or isinstance(data_new, list):
+ self.model(*data_new)
+ else:
+ self.model(**data_new)
+ except NotImplementedError:
+ pass
+ except Exception as error:
+ raise error
+ total_cnt += input_ids.shape[0] if len(input_ids.shape) > 1 else 1
+ if total_cnt >= nsamples:
+ break
+ if total_cnt == 0:
+ logger.error(
+ f"no data has been cached, please provide more data with sequence length >={self.seqlen} in the "
+ f"dataset or decease the sequence length"
+ )
+ exit()
+ elif total_cnt < nsamples:
+ logger.warning(
+ f"Insufficient number of samples collected may affect the quantification. "
+ f"Valid samples size:{total_cnt}, Target sample size:{nsamples}"
+ )
+
+ # clean embed weight to save memory
+ if self.low_cpu_mem_usage:
+ for n, m in embed_layers:
+ m = m.to("meta")
+ # torch.cuda.empty_cache()
\ No newline at end of file
diff --git a/auto_round/mllm/mllm_dataset.py b/auto_round/mllm/mllm_dataset.py
new file mode 100644
index 000000000..423d70e0d
--- /dev/null
+++ b/auto_round/mllm/mllm_dataset.py
@@ -0,0 +1,171 @@
+# Copyright (c) 2024 Intel Corporation
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import os
+import json
+from typing import Dict
+
+
+import torch
+from torch.utils.data import Dataset, DataLoader
+
+from .utils import _extract_data_dir
+from .template import Template
+
+
+MLLM_DATASET : Dict[str, Dataset] = {}
+
+def register_dataset(name):
+ """Class decorator to register a DATASET subclass to the registry.
+
+ Decorator function used before a Pattern subclass.
+
+ Args:
+ name: A string. Define the dataset type.
+
+ Returns:
+ cls: The class of register.
+ """
+
+ def register(dataset):
+ MLLM_DATASET[name] = dataset
+ return dataset
+ return register
+
+
+@register_dataset("llava")
+class LlavaDataset(Dataset):
+ """Dataset for supervised fine-tuning."""
+
+ def __init__(
+ self,
+ template,
+ model,
+ tokenzier,
+ dataset_path,
+ extra_data_dir,
+ max_length,
+ padding=True,
+ truncation=True,
+ ) -> None:
+ super().__init__()
+ self.model = model
+ self.model_type = template.model_type
+ self.template = template
+ self.tokenizer = tokenzier
+ self.questions = json.load(open(dataset_path, "r"))
+ self.padding = padding
+ self.truncation = truncation
+ self.extra_data_dir = extra_data_dir
+ self.max_length = max_length
+ self.role_mapping = {"human": "user", "gpt": "assistant"}
+ self.cached_data_dict = {}
+
+
+ def __len__(self):
+ return len(self.questions)
+
+ def __getitem__(self, i) -> Dict[str, torch.Tensor]:
+ if i in self.cached_data_dict:
+ return self.cached_data_dict[i]
+
+ text = self.questions[i]["conversations"]
+ text = self.covert_conversations(text)
+
+ text = self.template._encode(text)
+ if self.extra_data_dir is not None:
+ image_fold = _extract_data_dir(self.extra_data_dir)
+ if isinstance(image_fold, dict):
+ image_fold = image_fold['image']
+ image_path = os.path.join(
+ image_fold, os.path.basename(self.questions[i]["image"]))
+ else:
+ image_path = self.questions[i]["image"]
+ image = self.template.processor.image_processor(image_path)
+
+ ret = self.template.processor.get_input(
+ self.model,
+ self.tokenizer,
+ text=text,
+ images=image,
+ padding=self.padding,
+ truncation=self.truncation,
+ return_tensors="pt",
+ max_length = self.max_length
+ )
+ self.cached_data_dict[i] = ret
+ return ret
+
+ def covert_conversations(self, data):
+ new_data = []
+ for d in data:
+ content = d["value"]
+ for old, new in self.template.replace_tokens:
+ content = content.replace(old, new)
+ new_data.append({
+ "role": self.role_mapping.get(d["from"], d["from"]),
+ "content": content
+ })
+ return new_data
+
+
+def get_mllm_dataloader(
+ template,
+ model,
+ tokenizer,
+ dataset,
+ extra_data_dir,
+ seqlen=512,
+ bs=1,
+ split=None,
+ apply_template=None,
+):
+ """Generate a DataLoader for calibration using specified parameters.
+
+ Args:
+ template (Template): The template to specify process for different mllms.
+ model (Model): The model to quantized.
+ tokenizer (Tokenizer): The tokenizer to use for tokenization.
+ Dataset_name (str): The name or path of the dataset.
+ extra_data_dir (str): The path for extra data such as images, audio or videos.
+ seqlen (int): The exact sequence length. samples < seqlen will be dropped,
+ samples longer than seqlen will be truncated
+ bs (int, optional): The batch size. Defaults to 4.
+ split (str, optional): The data split to use. Defaults to None.
+ apply_template: Whether to apply chat template in tokenization.
+
+ Returns:
+ DataLoader: The DataLoader for the calibrated datasets.
+ """
+ assert isinstance(template, Template)
+
+ if isinstance(dataset, str):
+ if os.path.isfile(dataset):
+ dataset = MLLM_DATASET['llava'](
+ template, model, tokenizer, dataset, extra_data_dir,
+ max_length=min(seqlen, tokenizer.model_max_length))
+ else:
+ from datasets import load_dataset
+ from ..calib_dataset import get_tokenizer_function
+ dataset = load_dataset(dataset, split=split)
+ tokenizer_function = get_tokenizer_function(tokenizer, seqlen, apply_template=apply_template)
+ dataset = dataset.map(tokenizer_function, batched=True)
+
+
+ dataloader_params = {
+ "batch_size": bs,
+ "collate_fn": dataset.template.processor.data_collator
+ }
+
+ return DataLoader(dataset, **dataloader_params)
diff --git a/auto_round/mllm/processor.py b/auto_round/mllm/processor.py
new file mode 100644
index 000000000..eb6305fcf
--- /dev/null
+++ b/auto_round/mllm/processor.py
@@ -0,0 +1,181 @@
+# Copyright (c) 2024 Intel Corporation
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import torch
+from transformers.data.data_collator import default_data_collator
+
+from .utils import fetch_image
+
+PROCESSORS = {}
+
+def regist_processor(name):
+ def register(processor):
+ PROCESSORS[name] = processor
+ return processor
+ return register
+
+@regist_processor("basic")
+class BasicProcessor:
+ def __init__(self):
+ pass
+
+ def get_input(
+ self,
+ model,
+ tokenizer,
+ text,
+ images,
+ padding=True,
+ truncation=True,
+ return_tensors="pt",
+ max_length=None,
+ squeeze=True,
+ **kwargs):
+
+ if max_length:
+ token_length = len(tokenizer(text).input_ids)
+ if token_length < max_length:
+ if tokenizer.pad_token:
+ text += tokenizer.pad_token * (max_length - token_length)
+ else:
+ text = tokenizer.decode(tokenizer(text).input_ids[:max_length])
+
+ ret = tokenizer.processor(
+ text=text,
+ images=images,
+ padding=padding,
+ truncation=truncation,
+ return_tensors=return_tensors,
+ # videos = None
+ )
+ if squeeze:
+ for key in ret:
+ ret[key] = ret[key][0]
+ return ret
+
+ @staticmethod
+ def data_collator(batch):
+ return default_data_collator(batch)
+
+ @staticmethod
+ def image_processor(image_path_or_url):
+ return fetch_image(image_path_or_url)
+
+@regist_processor("qwen2_vl")
+class Qwen2VLProcessor(BasicProcessor):
+ def get_input(
+ self,
+ model,
+ tokenizer,
+ text,
+ images,
+ padding=True,
+ truncation=True,
+ return_tensors="pt",
+ max_length=None,
+ squeeze=True,
+ **kwargs):
+
+ if max_length:
+ token_length = len(tokenizer(text).input_ids)
+ if token_length < max_length:
+ if tokenizer.pad_token:
+ text += tokenizer.pad_token * (max_length - token_length)
+ else:
+ text = tokenizer.decode(tokenizer(text).input_ids[:max_length])
+
+ ret = tokenizer.processor(
+ text=text,
+ images=images,
+ padding=padding,
+ truncation=truncation,
+ return_tensors=return_tensors,
+ # videos = None
+ )
+ if squeeze:
+ for key in ret:
+ if key == "pixel_values":
+ continue
+ ret[key] = ret[key][0]
+ return ret
+
+
+@regist_processor("cogvlm2")
+class CogVLM2Processor(BasicProcessor):
+ def get_input(
+ self, model, tokenizer, text, images, max_length=2048,
+ padding=True, truncation=True, squeeze=True, **kwargs):
+ padding_len = 2303
+ max_length += padding_len
+ input_data = model.build_conversation_input_ids(
+ tokenizer,
+ query=text,
+ history=None,
+ images=[images],
+ template_version='base'
+ )
+ def pad_to_len(unpadded_tensor, pad_to_length, pad_value=0):
+ current_length = len(unpadded_tensor)
+ if current_length >= pad_to_length:
+ if truncation:
+ return unpadded_tensor[:pad_to_length]
+ else:
+ return unpadded_tensor
+ if padding:
+ return torch.cat(
+ (unpadded_tensor,
+ torch.full([pad_to_length - current_length],
+ fill_value=pad_value,
+ dtype=unpadded_tensor.dtype,
+ device=unpadded_tensor.device)), dim=0)
+ else:
+ return unpadded_tensor
+ input_data['input_ids'] = pad_to_len(
+ input_data['input_ids'],
+ max_length,
+ pad_value=128002,
+ )
+ input_data['attention_mask'] = pad_to_len(
+ input_data['attention_mask'],
+ max_length,
+ pad_value=0
+ )
+ input_data['token_type_ids'] = pad_to_len(
+ input_data['token_type_ids'],
+ max_length,
+ pad_value=0
+ )
+ if input_data['labels']:
+ input_data['labels'] = pad_to_len(
+ input_data['labels'],
+ max_length,
+ pad_value=-100
+ )
+ return input_data
+
+ @staticmethod
+ def data_collator(batch):
+ batched_data = {}
+ for key in batch[0].keys():
+ if isinstance(batch[0][key], list):
+ batched_data[key] = [batch_item[key] for batch_item in batch]
+ elif isinstance(batch[0][key], torch.Tensor):
+ batched_data[key] = torch.stack([item[key] for item in batch])
+ # else:
+ # raise ValueError("Unsupported datatype in custom collate_fn")
+ return batched_data
+
+ @staticmethod
+ def image_processor(image_path_or_url):
+ return fetch_image(image_path_or_url).convert('RGB')
\ No newline at end of file
diff --git a/auto_round/mllm/template.py b/auto_round/mllm/template.py
new file mode 100644
index 000000000..3478f1a10
--- /dev/null
+++ b/auto_round/mllm/template.py
@@ -0,0 +1,158 @@
+# Copyright (c) 2024 Intel Corporation
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import os
+import json
+from dataclasses import dataclass
+from typing import Dict, Optional, List, Union, Sequence
+from enum import Enum, unique
+
+from ..utils import logger
+
+
+from .processor import BasicProcessor, PROCESSORS
+
+TEMPLATES: Dict[str, "Template"] = {}
+
+def fill_content(target, **kwargs):
+ for name, value in kwargs.items():
+ target = target.replace("{{" + name + "}}", value, 1)
+ return target
+
+
+@unique
+class Role(str, Enum):
+ USER = "user"
+ ASSISTANT = "assistant"
+ SYSTEM = "system"
+ FUNCTION = "function"
+ OBSERVATION = "observation"
+
+@dataclass
+class Template:
+ model_type: str
+ format_user: str
+ format_assistant: str
+ format_system: str
+ format_function: str
+ format_observation: str
+ format_separator: str
+ default_system: str
+ replace_tokens: List[tuple]
+ processor: "BasicProcessor"
+
+ def _encode(self, sources):
+ """Encodes formatted inputs to pairs of token ids."""
+ element = ""
+ for i, source in enumerate(sources):
+ if i == 0:
+ element += fill_content(self.format_system, content=self.default_system)
+ # if i > 0 and i % 2 ==0:
+ # element += fill_content(self.format_separator)
+
+ if source['role'] == Role.USER.value:
+ element += fill_content(self.format_user, content=source["content"])
+ elif source['role'] == Role.ASSISTANT.value:
+ element += fill_content(self.format_assistant, content=source["content"])
+ elif source['role'] == Role.OBSERVATION.value:
+ element += fill_content(self.format_observation, content=source["content"])
+ elif source['role'] == Role.FUNCTION.value:
+ element += fill_content(self.format_function, content=source["content"])
+ return element
+
+
+def _register_template(
+ model_type: str,
+ format_user: Optional[str] = None,
+ format_assistant: Optional[str] = None,
+ format_system: Optional[str] = None,
+ format_function: Optional[str] = None,
+ format_observation: Optional[str] = None,
+ format_separator: Optional[str] = None,
+ default_system: str = "",
+ replace_tokens: List[tuple] = None,
+ processor: "BasicProcessor" = PROCESSORS["basic"]
+):
+ """Registers a chat template."""
+ template_class = Template
+ default_format_user = "{{content}}"
+ default_format_assistant = "{{content}}"
+ default_format_system = "{{content}}"
+ default_format_function = ""
+ default_format_observation = ""
+ default_format_separator = "\n"
+ TEMPLATES[model_type] = template_class(
+ model_type = model_type,
+ format_user = format_user or default_format_user,
+ format_assistant = format_assistant or default_format_assistant,
+ format_system = format_system or default_format_system,
+ format_function = format_function or default_format_function,
+ format_observation = format_observation or default_format_observation,
+ format_separator = format_separator or default_format_separator,
+ default_system = default_system,
+ replace_tokens = replace_tokens,
+ processor = processor()
+ )
+ return TEMPLATES[model_type]
+
+
+def load_template(path: str):
+ """Load template information from a json file."""
+ data = json.load(open(path, "r"))
+ if "model_type" not in data:
+ data["model_type"] = "user_define"
+ if "replace_tokens" in data and data["replace_tokens"] is not None:
+ assert len(data["replace_tokens"]) % 2 == 0, \
+ "the format of replace_tokens should be [old_tag1, replace_tag1, old_tag2, replace_tag2]"
+ temp = []
+ for i in range(0, len(data["replace_tokens"]), 2):
+ temp.append((data["replace_tokens"][i], data["replace_tokens"][i+1]))
+ data["replace_tokens"] = temp
+ if "processor" in data:
+ assert data["processor"] in PROCESSORS.keys(), \
+ "{} is not supported, current support: {}".format(data["processor"], ",".join(PROCESSORS.keys()))
+ data["processor"] = PROCESSORS[data["processor"]]
+ template = _register_template(
+ **data
+ )
+ return template
+
+
+def _load_preset_template():
+ dir_path = os.path.join(os.path.dirname(__file__), 'templates')
+ for file_name in os.listdir(dir_path):
+ load_template(os.path.join(dir_path, file_name))
+
+_load_preset_template()
+
+
+def get_template(template_or_path: str):
+ """Get template by template name or from a json file.
+
+ Args:
+ template_or_path (str): Template name or a path of the template json file.
+
+ Returns:
+ The Template.
+
+ """
+ if os.path.isfile(template_or_path):
+ template = load_template(template_or_path)
+ else:
+ if template_or_path in TEMPLATES:
+ template = TEMPLATES[template_or_path]
+ else:
+ logger.warning(f"Unable to recognize {template_or_path}, using default template instead.")
+ template = TEMPLATES["default"]
+ return template
\ No newline at end of file
diff --git a/auto_round/mllm/templates/cogvlm2.json b/auto_round/mllm/templates/cogvlm2.json
new file mode 100644
index 000000000..8aa8cfa3e
--- /dev/null
+++ b/auto_round/mllm/templates/cogvlm2.json
@@ -0,0 +1,7 @@
+{
+ "model_type": "cogvlm2",
+ "format_user": "Question: {{content}} ",
+ "format_assistant": "Answer: {{content}}\n",
+ "replace_tokens": ["<image>\n", ""],
+ "processor": "cogvlm2"
+}
\ No newline at end of file
diff --git a/auto_round/mllm/templates/default.json b/auto_round/mllm/templates/default.json
new file mode 100644
index 000000000..c16844529
--- /dev/null
+++ b/auto_round/mllm/templates/default.json
@@ -0,0 +1,12 @@
+{
+ "model_type": "default",
+ "format_user": "{{content}}",
+ "format_assistant": "{{content}}",
+ "format_system": "{{content}}",
+ "format_function": "",
+ "format_observation": "",
+ "format_separator": "\n",
+ "default_system": "You are a helpful assistant.",
+ "replace_tokens": null,
+ "processor": "basic"
+}
\ No newline at end of file
diff --git a/auto_round/mllm/templates/mllama.json b/auto_round/mllm/templates/mllama.json
new file mode 100644
index 000000000..0a31392a2
--- /dev/null
+++ b/auto_round/mllm/templates/mllama.json
@@ -0,0 +1,8 @@
+{
+ "model_type": "mllama",
+ "format_user": "<|start_header_id|>user<|end_header_id|>\n{{content}}<|eot_id|>",
+ "format_assistant": "<|start_header_id|>assistant<|end_header_id|>\n{{content}}<|eot_id|>",
+ "format_system": "<|begin_of_text|><|start_header_id|>system|end_header_id|>\n{{content}}<<eot_id>",
+ "default_system": "You are a helpful assistant.",
+ "replace_tokens": ["<image>", "<|image|>"]
+}
\ No newline at end of file
diff --git a/auto_round/mllm/templates/qwen2_vl.json b/auto_round/mllm/templates/qwen2_vl.json
new file mode 100644
index 000000000..9435d4236
--- /dev/null
+++ b/auto_round/mllm/templates/qwen2_vl.json
@@ -0,0 +1,11 @@
+{
+ "model_type": "qwen2_vl",
+ "format_user": "<|im_start|>user\n{{content}}<|im_end|>\n",
+ "format_assistant": "<|im_start|>assistant\n{{content}}<|im_end|>\n",
+ "format_system": "<|im_start|>system\n{{content}}<|im_end|>\n",
+ "format_observation": "<|im_start|>tool\n{{content}}<|im_end|>\n<|im_start|>assistant\n",
+ "format_separator": "\n",
+ "default_system": "You are a helpful assistant.",
+ "replace_tokens": ["<image>", "<|vision_start|><|image_pad|><|vision_end|>"],
+ "processor": "qwen2_vl"
+}
\ No newline at end of file
diff --git a/auto_round/mllm/utils.py b/auto_round/mllm/utils.py
new file mode 100644
index 000000000..754e351d6
--- /dev/null
+++ b/auto_round/mllm/utils.py
@@ -0,0 +1,42 @@
+# Copyright (c) 2024 Intel Corporation
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import os
+import requests
+
+from PIL import Image # pylint: disable=E0401
+
+
+def _extract_data_dir(dir_path: str):
+ if os.path.isdir(dir_path):
+ return dir_path
+ else:
+ result = {}
+ dir_path = dir_path.split(",")
+ for _path in dir_path:
+ k, v = _path.split('=')
+ if k in ['image', 'video', 'audio']:
+ result[k] = v
+ return result
+
+
+def fetch_image(path_or_url):
+ if os.path.isfile(path_or_url):
+ image_obj = Image.open(path_or_url)
+ elif path_or_url.startswith("http://") or path_or_url.startswith("https://"):
+ image_obj = Image.open(requests.get(path_or_url, stream=True).raw)
+ else:
+ raise TypeError(f"{path_or_url} neither a path or url.")
+
+ return image_obj
\ No newline at end of file
diff --git a/examples/language-modeling/main.py b/examples/language-modeling/main.py
index a72a48bc9..1fb88eec2 100644
--- a/examples/language-modeling/main.py
+++ b/examples/language-modeling/main.py
@@ -246,7 +246,7 @@ if __name__ == '__main__':
)
from auto_round import (AutoRound,
- AutoAdamRound)
+ AutoRoundAdam)
model = model.eval()
@@ -282,7 +282,7 @@ if __name__ == '__main__':
round = AutoRound
if args.adam:
- round = AutoAdamRound
+ round = AutoRoundAdam
layer_config = {}
for n, m in model.named_modules():
diff --git a/examples/multimodal-modeling/Common_model/main.py b/examples/multimodal-modeling/Common_model/main.py
index 7ac7194a4..bb35a8bd5 100644
--- a/examples/multimodal-modeling/Common_model/main.py
+++ b/examples/multimodal-modeling/Common_model/main.py
@@ -451,7 +451,7 @@ if __name__ == '__main__':
dataloader = get_train_dataloader(dataset, model, data_collator=default_collator, train_batch_size=args.train_bs)
from auto_round import (AutoRound,
- AutoAdamRound)
+ AutoRoundAdam)
from auto_round.utils import get_multimodal_block_names
model = model.eval()
@@ -459,7 +459,7 @@ if __name__ == '__main__':
round = AutoRound
if args.adam:
- round = AutoAdamRound
+ round = AutoRoundAdam
layer_config = {}
for n, m in model.named_modules():
diff --git a/examples/multimodal-modeling/Llava/main.py b/examples/multimodal-modeling/Llava/main.py
index 78f7e7466..bf6f57930 100644
--- a/examples/multimodal-modeling/Llava/main.py
+++ b/examples/multimodal-modeling/Llava/main.py
@@ -247,7 +247,7 @@ if __name__ == '__main__':
torch_dtype=torch_dtype)
from auto_round import (AutoRound,
- AutoAdamRound)
+ AutoRoundAdam)
from auto_round.utils import get_multimodal_block_names
model = model.eval()
@@ -304,7 +304,7 @@ if __name__ == '__main__':
round = AutoRound
if args.adam:
- round = AutoAdamRound
+ round = AutoRoundAdam
layer_config = {}
for n, m in model.named_modules():
diff --git a/examples/multimodal-modeling/Phi-3-vision/main.py b/examples/multimodal-modeling/Phi-3-vision/main.py
index 9696b31dc..99f457f8e 100644
--- a/examples/multimodal-modeling/Phi-3-vision/main.py
+++ b/examples/multimodal-modeling/Phi-3-vision/main.py
@@ -337,12 +337,12 @@ if __name__ == '__main__':
dataloader = create_data_loader(dataset, batch_size=args.train_bs, data_collator=data_collator)
from auto_round import (AutoRound,
- AutoAdamRound)
+ AutoRoundAdam)
from auto_round.utils import get_multimodal_block_names
round = AutoRound
if args.adam:
- round = AutoAdamRound
+ round = AutoRoundAdam
layer_config = {}
for n, m in model.named_modules():
diff --git a/requirements.txt b/requirements.txt
index 3c6fecb7b..abd50f03a 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -10,4 +10,5 @@ threadpoolctl
lm-eval>=0.4.2,<=0.4.5
tqdm
packaging
-auto-gptq>=0.7.1
\ No newline at end of file
+auto-gptq>=0.7.1
+pillow
\ No newline at end of file
diff --git a/setup.cfg b/setup.cfg
index 9de8ea928..1afe7e8c6 100644
--- a/setup.cfg
+++ b/setup.cfg
@@ -7,3 +7,9 @@ license_files =
console_scripts =
auto_round = auto_round.__main__:run
auto-round = auto_round.__main__:run
+ auto_round_mllm = auto_round.__main__:run_mllm
+ auto-round-mllm = auto_round.__main__:run_mllm
+ auto-round-fast = auto_round.__main__:run_fast
+ auto_round_fast = auto_round.__main__:run_fast
+ auto-round-best = auto_round.__main__:run_best
+ auto_round_best = auto_round.__main__:run_best
diff --git a/setup.py b/setup.py
index fa8a5c8ae..fac699380 100644
--- a/setup.py
+++ b/setup.py
@@ -190,5 +190,7 @@ if __name__ == "__main__":
"Topic :: Scientific/Engineering :: Artificial Intelligence",
"License :: OSI Approved :: Apache Software License",
],
+ include_package_data=True,
+ package_data={"": ["mllm/templates/*.json"]},
**additional_setup_kwargs
)
diff --git a/test/test_autoopt.py b/test/test_autoopt.py
index 988173c0a..08b1700bd 100644
--- a/test/test_autoopt.py
+++ b/test/test_autoopt.py
@@ -8,7 +8,7 @@ import torch
import transformers
from transformers import AutoModelForCausalLM, AutoTokenizer
-from auto_round import AutoOPTRound, AutoAdamRound
+from auto_round import AutoRoundOPT, AutoRoundAdam
class LLMDataLoader:
@@ -35,7 +35,7 @@ class TestAutoRound(unittest.TestCase):
def test_default(self):
bits, group_size, sym = 4, 128, False
- autoround = AutoOPTRound(
+ autoround = AutoRoundOPT(
self.model,
self.tokenizer,
bits=bits,
@@ -54,7 +54,7 @@ class TestAutoRound(unittest.TestCase):
from auto_round.utils import get_multimodal_block_names
llm_block_names = get_multimodal_block_names(self.model, quant_vision=True)
bits, group_size, sym, batch_size = 4, 128, False, 20
- adamround = AutoAdamRound(
+ adamround = AutoRoundAdam(
self.model,
self.tokenizer,
bits=bits,
diff --git a/test/test_autoround.py b/test/test_autoround.py
index db29bf38d..20e5ea445 100644
--- a/test/test_autoround.py
+++ b/test/test_autoround.py
@@ -288,6 +288,23 @@ class TestAutoRound(unittest.TestCase):
dataset=self.llm_dataloader,
)
autoround.quantize()
+
+ def test_fp32(self):
+ bits, group_size, sym = 4, 128, False
+ model_name = "facebook/opt-125m"
+ model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype=torch.float32, trust_remote_code=True, device_map='auto')
+ autoround = AutoRound(
+ model,
+ self.tokenizer,
+ bits=bits,
+ group_size=group_size,
+ sym=sym,
+ iters=2,
+ seqlen=2,
+ dataset=self.llm_dataloader,
+ amp=False
+ )
+ autoround.quantize()
diff --git a/test/test_mllm.py b/test/test_mllm.py
new file mode 100644
index 000000000..d919f4b0b
--- /dev/null
+++ b/test/test_mllm.py
@@ -0,0 +1,49 @@
+import sys
+import unittest
+
+sys.path.insert(0, "..")
+
+from auto_round import AutoRoundMLLM
+
+from transformers import AutoProcessor, AutoTokenizer, Qwen2VLForConditionalGeneration
+
+
+class FakeDataLoader:
+ def __init__(self):
+ self.batch_size = 1
+
+ self.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.'}],
+ "image": "http://images.cocodataset.org/train2017/000000033471.jpg"
+ }
+
+ def __iter__(self):
+ for i in range(2):
+ yield self.data
+
+class TestAutoRoundMLLM(unittest.TestCase):
+ @classmethod
+ def setUpClass(self):
+ self.model_name = "Qwen/Qwen2-VL-2B-Instruct"
+ self.dataset = FakeDataLoader()
+
+
+ @classmethod
+ def tearDownClass(self):
+ 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)
+ 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)
+ autoround.quantize()
+
+if __name__ == "__main__":
+ unittest.main()