PTQ-Level Efficiency, QAT-Level Accuracy | 训练后量化的效率,量化感知训练的精度
reduce ram&vram usage for vlm calib stage (#1488)
Weiweibe3871314df1
diff --git a/auto_round/compressors/base.py b/auto_round/compressors/base.pyindex 2efe78914..d56cba25d 100644--- a/auto_round/compressors/base.py+++ b/auto_round/compressors/base.py@@ -98,6 +98,7 @@ from auto_round.utils import (llm_load_model,memory_monitor,mv_module_from_gpu,+ safe_device_move_with_meta_handling,set_amax_for_all_moe_layers,set_module,to_device,@@ -1742,7 +1743,7 @@ class BaseCompressor(object):all_q_inputs = self.try_cache_inter_data_gpucpu(all_first_block_names, self.nsamples, layer_names=layer_names)- self.model = mv_module_from_gpu(self.model)+ self.model = safe_device_move_with_meta_handling(self.model, "cpu")clear_memory(device_list=self.device_list)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 changed@@ -2169,7 +2170,6 @@ class BaseCompressor(object):and len(layer_names) == 0and not self.has_qlayer_outside_blockand (last_cache_name is None or last_cache_name in block_names)- and getattr(self, "mllm", False) is False):# low_gpu_mem_usage or calibrate only the embedding layer, which is also very fast on CPUall_inputs = self.cache_inter_data(block_names, nsamples, layer_names=[], last_cache_name=last_cache_name)@@ -2313,10 +2313,9 @@ class BaseCompressor(object):else:self.model = self.model.to(torch.float32) ##model on cpu- self.last_cache_name = last_cache_name- if last_cache_name is None and len(block_names) + len(layer_names) == 1:- self.last_cache_name = block_names[0] if len(block_names) == 1 else layer_names[0]- # do not set last_cache_name for multimodal models+ self.last_cache_name = self._infer_last_cache_name(block_names, layer_names, last_cache_name)+ self._cache_target_set = set(self.to_cached_layers)+ self._cache_seen_targets = set()calib_bs = self.batch_sizeself.hook_handles = []self._replace_forward()@@ -2324,12 +2323,54 @@ class BaseCompressor(object):self._recover_forward()res = self.inputsdel self.last_cache_name+ del self._cache_target_set+ del self._cache_seen_targetsdel self.to_cached_layersif tmp_dtype is not None:self.model = self.model.to(tmp_dtype)return res+ def _infer_last_cache_name(self, block_names, layer_names=None, requested_last_cache_name=None):+ """The latest required cache layer for early-stop forward.++ If there are multiple cache targets, return ``None`` and let runtime+ hooks stop only after all targets are observed in real forward execution.+ """+ if layer_names is None:+ layer_names = []++ if requested_last_cache_name is not None:+ return requested_last_cache_name++ cache_targets = list(block_names) + list(layer_names)+ if len(cache_targets) == 1:+ return cache_targets[0]++ # return None here to enable the logic in _should_stop_cache_forward+ return None++ def _should_stop_cache_forward(self, name: str) -> bool:+ """Determine whether current forward pass can stop after caching `name`."""+ if name == self.last_cache_name:+ return True++ if self.last_cache_name is not None:+ return False++ if not hasattr(self, "_cache_target_set") or not hasattr(self, "_cache_seen_targets"):+ return False++ if name in self._cache_target_set:+ self._cache_seen_targets.add(name)++ if not self._cache_target_set.issubset(self._cache_seen_targets):+ return False++ # Lock the last cache name after the first full forward pass.+ self.last_cache_name = name+ return True+@torch.no_grad()def _get_block_forward_func(self, name: str) -> Callable:"""Gets the forward function.@@ -2431,7 +2472,8 @@ class BaseCompressor(object):f"Please note that '{key}' key" " is not currently used in quantization fine-tuning.")reset_params(self.inputs[name])- if name == self.last_cache_name:++ if self._should_stop_cache_forward(name):raise NotImplementedErrorelse:if hidden_states is not None:@@ -2458,6 +2500,9 @@ class BaseCompressor(object):else:self.inputs[name] = list(torch.split(input.to("cpu"), 1, dim=0))+ if self._should_stop_cache_forward(name):+ raise NotImplementedError+return cache_input_hookdef _recover_forward(self):diff --git a/auto_round/compressors/mllm/compressor.py b/auto_round/compressors/mllm/compressor.pyindex 165d4f3d3..4dcd35670 100644--- a/auto_round/compressors/mllm/compressor.py+++ b/auto_round/compressors/mllm/compressor.py@@ -135,7 +135,7 @@ class MLLMCompressor(BaseCompressor):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_gpu_mem_usage (bool): Whether to use low GPU memory (default is True).iters (int): Number of iterations (default is 200).seqlen (int): Length of the sequence.nsamples (int): Number of samples (default is 128).@@ -217,9 +217,13 @@ class MLLMCompressor(BaseCompressor):import importlib.utilmissing_libs = []- for require_lib in ["PIL", "torchvision"]:- if importlib.util.find_spec(require_lib) is None:- missing_libs.append(require_lib.replace("PIL", "pillow"))+ required_libs = {+ "pillow": "PIL",+ "torchvision": "torchvision",+ }+ for pip_name, module_name in required_libs.items():+ if importlib.util.find_spec(module_name) is None:+ missing_libs.append(pip_name)if len(missing_libs) > 0:logger.error(f"{', '.join(missing_libs)} are required for quantizing non-text modules,"@@ -372,14 +376,16 @@ class MLLMCompressor(BaseCompressor):)else:self.dataloader = self.dataset- total_cnt = 0+ total_cnt = 0+ calib_kwargs = {"use_cache": False}total = nsamples if not hasattr(self.dataloader, "len") else min(nsamples, len(self.dataloader))with tqdm(range(1, total + 1), desc="cache block inputs") as pbar:for data in self.dataloader:if data is None:pbar.update(1)continue+if isinstance(data, torch.Tensor):input_ids = data.to(self.model.device)data_new = input_ids@@ -387,16 +393,13 @@ class MLLMCompressor(BaseCompressor):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(text=data,images=None,max_length=self.seqlen,squeeze=False,)- data_new = {}- for key in data.keys():- data_new[key] = data[key].to(self.model.device)+ data_new = {k: v.to(self.model.device) for k, v in data.items()}input_ids = data_new["input_ids"]elif isinstance(data, dict) and "text" in data.keys():text = data["text"]@@ -410,41 +413,44 @@ class MLLMCompressor(BaseCompressor):squeeze=False,)data_new = {}- for key in data.keys():- data_new[key] = torch.tensor(data[key])- data_new[key] = to_device(data_new[key], self.model.device)+ for key, value in data.items():+ if isinstance(value, torch.Tensor):+ tensor_value = value+ else:+ tensor_value = torch.as_tensor(value)+ tensor_value = to_device(tensor_value, self.model.device)if key == "images":- data_new[key] = to_dtype(data_new[key], self.model.dtype)+ tensor_value = to_dtype(tensor_value, self.model.dtype)+ data_new[key] = tensor_valueinput_ids = data_new["input_ids"]- elif isinstance(data, tuple) or isinstance(data, list):+ elif isinstance(data, (tuple, list)):data_new = to_device(data, self.model.device)input_ids = data_new[0]else:data_new = {}- for key in data.keys():- data_new[key] = to_device(data[key], self.model.device)+ for key, value in data.items():+ tensor_value = to_device(value, self.model.device)if key in ["images", "pixel_values"]:- data_new[key] = to_dtype(data_new[key], self.model.dtype)- if "input_ids" in data_new:- input_ids = data_new["input_ids"]- else:- input_ids = data_new["inputs_embeds"]+ tensor_value = to_dtype(tensor_value, self.model.dtype)+ data_new[key] = tensor_value+ input_ids = data_new["input_ids"] if "input_ids" in data_new else data_new["inputs_embeds"]if input_ids.shape[-1] < self.seqlen:pbar.update(1)continue+try:if isinstance(data_new, torch.Tensor):- data_new = data_new.to(self.model.device)- self.model(data_new)- elif isinstance(data_new, tuple) or isinstance(data_new, list):- self.model(*data_new)+ self.model(data_new, **calib_kwargs)+ elif isinstance(data_new, (tuple, list)):+ self.model(*data_new, **calib_kwargs)else:- self.model(**data_new)+ self.model(**data_new, **calib_kwargs)except NotImplementedError:passexcept Exception as error:raise error+step = input_ids.shape[0] if len(input_ids.shape) > 1 else 1total_cnt += steppbar.update(step)@@ -472,6 +478,9 @@ class MLLMCompressor(BaseCompressor):if isinstance(v[key], list) and len(v[key]) == total_cnt:self.inputs[k][key] = v[key][:max_len]+ if hasattr(self.dataloader, "dataset") and hasattr(self.dataloader.dataset, "clear_runtime_cache"):+ self.dataloader.dataset.clear_runtime_cache()+# torch.cuda.empty_cache()def save_quantized(self, output_dir=None, format="auto_round", inplace=True, **kwargs):diff --git a/auto_round/compressors/mllm/dataset.py b/auto_round/compressors/mllm/dataset.pyindex cf2941350..e441d764b 100644--- a/auto_round/compressors/mllm/dataset.py+++ b/auto_round/compressors/mllm/dataset.py@@ -14,6 +14,8 @@import jsonimport os+from collections import OrderedDict+from inspect import signaturefrom typing import Dictimport torch@@ -75,6 +77,7 @@ class LlavaDataset(Dataset):padding=True,truncation=True,nsamples=512,+ cache_size=0,) -> None:super().__init__()self.model = model@@ -104,7 +107,8 @@ class LlavaDataset(Dataset):self.truncation = truncationself.extra_data_dir = extra_data_dirself.role_mapping = {"human": "user", "gpt": "assistant"}- self.cached_data_dict = {}+ self.cache_size = max(int(cache_size), 0)+ self.cached_data_dict = OrderedDict() if self.cache_size > 0 else Noneself.image_fold = Noneif extra_data_dir is not None:@@ -149,7 +153,8 @@ class LlavaDataset(Dataset):return len(self.questions)def __getitem__(self, i) -> Dict[str, torch.Tensor]:- if i in self.cached_data_dict:+ if self.cached_data_dict is not None and i in self.cached_data_dict:+ self.cached_data_dict.move_to_end(i)return self.cached_data_dict[i]text = self.questions[i]["conversations"]@@ -177,9 +182,17 @@ class LlavaDataset(Dataset):max_length=max_length,truncation_strategy=truncation_strategy,)- self.cached_data_dict[i] = ret+ if self.cached_data_dict is not None:+ self.cached_data_dict[i] = ret+ self.cached_data_dict.move_to_end(i)+ while len(self.cached_data_dict) > self.cache_size:+ self.cached_data_dict.popitem(last=False)return ret+ def clear_runtime_cache(self):+ if self.cached_data_dict is not None:+ self.cached_data_dict.clear()+def covert_conversations(self, data):new_data = []for d in data:@@ -240,9 +253,15 @@ def get_mllm_dataloader(f" reset to {MLLM_DATASET[dataset].MAX_SUPPORT_SEQLEN}")seqlen = 512- dataset = MLLM_DATASET[dataset](- template, model, tokenizer, dataset, extra_data_dir, seqlen=seqlen, truncation=truncation, nsamples=nsamples- )+ dataset_cls = MLLM_DATASET[dataset]+ dataset_kwargs = {+ "seqlen": seqlen,+ "truncation": truncation,+ "nsamples": nsamples,+ }+ if "cache_size" in signature(dataset_cls.__init__).parameters:+ dataset_kwargs["cache_size"] = int(os.getenv("AR_MLLM_DATASET_CACHE_SIZE", "0"))+ dataset = dataset_cls(template, model, tokenizer, dataset, extra_data_dir, **dataset_kwargs)bs, gradient_accumulate_steps = check_mllm_model_batch(model, batch_size=bs, gradient_accumulate_steps=gradient_accumulate_stepsdiff --git a/auto_round/utils/model.py b/auto_round/utils/model.pyindex f17398fcc..3a04005e8 100644--- a/auto_round/utils/model.py+++ b/auto_round/utils/model.py@@ -1087,6 +1087,50 @@ def mv_module_from_gpu(module):return module.to("cpu")+def safe_device_move_with_meta_handling(+ model,+ target_device="cpu",+ *,+ materialize_meta=None,+ logger=None,+):+ """Move model to target device, handling meta parameters and buffers correctly.+ Skipping module move on target/meta device.++ Args:+ target_device: Target device ('cpu', 'cuda', etc.)+ materialize_meta: Optional callable to materialize meta tensors before movement+ logger: Optional logger for warnings if needed+ """+ target_type = torch.device(target_device).type++ # Materialize meta tensors if handler provided+ if materialize_meta is not None:+ materialize_meta(model)++ meta_count = 0++ # Move parameters+ for p in model.parameters():+ if p.device.type in (target_type, "meta"):+ meta_count += p.device.type == "meta"+ continue+ p.data = p.data.to(target_device)++ # Move buffers+ for m in model.modules():+ for n, b in m._buffers.items():+ if b is None or b.device.type in (target_type, "meta"):+ meta_count += b is not None and b.device.type == "meta"+ continue+ m._buffers[n] = b.to(target_device)++ if meta_count and logger is not None:+ logger.warning(f"{meta_count} tensors still on meta device after movement")++ return model++def is_moe_model(model: torch.nn.Module) -> bool:if hasattr(model, "config") and hasattr(model.config, "to_dict"):for key in model.config.to_dict().keys():diff --git a/test/test_cpu/models/test_mllm.py b/test/test_cpu/models/test_mllm.pyindex 87e140a26..7450cd8ab 100644--- a/test/test_cpu/models/test_mllm.py+++ b/test/test_cpu/models/test_mllm.py@@ -1,9 +1,11 @@+import osimport shutilimport pytest-from transformers import AutoProcessor, AutoTokenizer, Qwen2VLForConditionalGeneration+from transformers import AutoModelForImageTextToText, AutoProcessor, AutoTokenizer, Qwen2VLForConditionalGenerationfrom auto_round import AutoRoundMLLM+from auto_round.utils import get_block_namesfrom ...helpers import get_model_path, opt_name_or_path@@ -258,3 +260,53 @@ class TestAutoRoundMLLM:output_text = processor.batch_decode(generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False)++ def test_mllm_early_stop_tracking(self, tiny_qwen_2_5_vl_model_path):+ from auto_round.utils import mllm_load_model++ model_name = tiny_qwen_2_5_vl_model_path+ model, processor, tokenizer, image_processor = mllm_load_model(model_name)+ autoround = AutoRoundMLLM(+ model,+ tokenizer,+ iters=1,+ nsamples=1,+ seqlen=32,+ quant_nontext_module=True,+ processor=processor,+ image_processor=image_processor,+ )++ call_log = []+ original_should_stop = autoround._should_stop_cache_forward++ def tracked_should_stop(name):+ result = original_should_stop(name)+ call_log.append(+ {+ "name": name,+ "result": result,+ "last_cache_name": getattr(autoround, "last_cache_name", None),+ }+ )+ return result++ autoround._should_stop_cache_forward = tracked_should_stop++ try:+ all_blocks = get_block_names(model, quant_vision=True)+ if not all_blocks:+ pytest.skip("No blocks found in the model")++ all_first_block_names = [block[0] for block in all_blocks if block]+ inputs = autoround.cache_inter_data(all_first_block_names, nsamples=2)+ print(f"call_log: {call_log}")+ stop_calls = [c for c in call_log if c["result"] is True]+ assert len(stop_calls) > 0, "Should trigger early-stop during calibration"+ last_cache_values = [c["last_cache_name"] for c in call_log]+ assert (+ last_cache_values[-1] == "model.language_model.layers.0"+ ), "last_cache_name should update to model.language_model.layers.0"+ assert "model.language_model.layers.0" in inputs, "Should have cached language model block"+ finally:+ autoround._should_stop_cache_forward = original_should_stopdiff --git a/test/test_cuda/models/test_vlms.py b/test/test_cuda/models/test_mllm.pysimilarity index 61%rename from test/test_cuda/models/test_vlms.pyrename to test/test_cuda/models/test_mllm.pyindex 3cbdc2a67..13643388c 100644--- a/test/test_cuda/models/test_vlms.py+++ b/test/test_cuda/models/test_mllm.py@@ -6,12 +6,37 @@ import shutilimport pytestimport requestsfrom PIL import Image-from transformers import AutoRoundConfig+from transformers import AutoModelForImageTextToText, AutoProcessor, AutoTokenizer, Qwen2VLForConditionalGeneration++from auto_round import AutoRoundMLLM+from auto_round.utils import get_block_namesfrom ...envs import require_gptqmodel, require_optimum, require_vlm_env+from ...helpers import get_model_path+++class VisionDataLoader:+ def __init__(self):+ self.batch_size = 1+ def __iter__(self):+ for _ in range(2):+ yield {+ "text": [+ {+ "role": "user",+ "content": "<image>\nDescribe the image and list the main objects you see.",+ },+ {+ "role": "assistant",+ "content": "The image shows a bus and surrounding street scene.",+ },+ ],+ "image": "http://images.cocodataset.org/train2017/000000033471.jpg",+ }-class TestAutoRound:++class TestAutoRoundMLLM:@classmethoddef setup_class(self):self.save_dir = "./saved"@@ -39,7 +64,7 @@ class TestAutoRound:# res == """<s> There is a girl who likes adventure, and she is looking for a partner to go on a treasure hunt. She has found a map that leads to a hidden treasure, but she needs a partner to help her decipher the clues and find the treasure. You""")def qwen_inference(self, quantized_model_dir):- from transformers import AutoProcessor, AutoTokenizer, Qwen2VLForConditionalGeneration+ from transformers import AutoProcessor, AutoTokenizertokenizer = AutoTokenizer.from_pretrained(quantized_model_dir)processor = AutoProcessor.from_pretrained(quantized_model_dir, trust_remote_code=True)@@ -85,7 +110,7 @@ class TestAutoRound:@require_gptqmodel@require_optimumdef test_vlm_tune(self):- from transformers import AutoProcessor, AutoTokenizer, Qwen2VLForConditionalGeneration+ from transformers import AutoProcessor, AutoTokenizerfrom auto_round import AutoRoundMLLM@@ -151,3 +176,71 @@ class TestAutoRound:assert not is_mllm_model(model_name)model, _ = llm_load_model(model_name)assert not is_mllm_model(model)++ def test_llama32_vision_early_stop_tracking(self):+ """Test early-stop during calibration for Llama-3.2-11B-Vision-Instruct."""+ model_path = get_model_path("meta-llama/Llama-3.2-11B-Vision-Instruct")+ if not os.path.exists(model_path):+ pytest.skip(f"Llama-3.2-11B-Vision-Instruct not found in {model_path}")++ tokenizer = AutoTokenizer.from_pretrained(model_path)+ processor = AutoProcessor.from_pretrained(model_path, trust_remote_code=True)+ model = AutoModelForImageTextToText.from_pretrained(+ model_path, trust_remote_code=True, device_map="auto", torch_dtype="auto"+ )++ autoround = AutoRoundMLLM(+ model=model,+ tokenizer=tokenizer,+ processor=processor,+ bits=4,+ group_size=128,+ nsamples=2,+ batch_size=1,+ iters=1,+ dataset=VisionDataLoader(),+ seqlen=8,+ quant_nontext_module=True,+ )++ call_log = []+ original_should_stop = autoround._should_stop_cache_forward++ def tracked_should_stop(name):+ result = original_should_stop(name)+ call_log.append(+ {+ "name": name,+ "result": result,+ "last_cache_name": getattr(autoround, "last_cache_name", None),+ }+ )+ return result++ autoround._should_stop_cache_forward = tracked_should_stop++ try:+ all_blocks = get_block_names(model, quant_vision=True)+ if not all_blocks:+ pytest.skip("No blocks found in Llama-3.2-11B-Vision-Instruct")++ all_first_block_names = [block[0] for block in all_blocks if block]+ if len(all_first_block_names) < 3:+ pytest.skip("Need 3 block groups for Llama-3.2 vision test")++ inputs = autoround.cache_inter_data(all_first_block_names, nsamples=2)+ print(f"call_log: {call_log}")++ stop_calls = [c for c in call_log if c["result"] is True]+ assert len(stop_calls) > 0, "Should trigger early-stop during calibration"++ last_cache_values = [c["last_cache_name"] for c in call_log]+ assert last_cache_values[0] is None, "last_cache_name should start as None"+ assert (+ last_cache_values[-1] == "model.language_model.layers.0"+ ), "last_cache_name should update to model.language_model.layers.0"++ assert "model.language_model.layers.0" in inputs, "Should have cached language model block"+ assert len(inputs) >= 3, "Should have cached at least 3 input keys"+ finally:+ autoround._should_stop_cache_forward = original_should_stop