PTQ-Level Efficiency, QAT-Level Accuracy | 训练后量化的效率,量化感知训练的精度
Fix layer_config bug and CI unstable issue (#1949)
Xin He05e67950513f
diff --git a/auto_round/compressors/base.py b/auto_round/compressors/base.pyindex c8d932b3d..dd7b1dd5b 100644--- a/auto_round/compressors/base.py+++ b/auto_round/compressors/base.py@@ -655,10 +655,13 @@ class BaseCompressor(object):if any(name.startswith(prefix) for prefix in block_prefixes)or not any(prefix.startswith(name.split(".")[0]) for prefix in block_prefixes)]- predefined_ignore_layers = compress_layer_names(predefined_ignore_layers)if predefined_ignore_layers:- logger.info(f"Using predefined ignore_layers: {compressed_predefined_ignore_layers}")- tmp_str = predefined_ignore_layers.replace(" ", "")+ logger.info(f"Using predefined ignore_layers: {compress_layer_names(predefined_ignore_layers)}")+ # Join the raw (uncompressed) names so that get_fp_layer_names can do exact+ # substring matching. Compressed forms like "layers.[0-61].gate" are+ # misinterpreted as regex character classes ([0-6] matches only digits 0-6)+ # and fail to cover layers with two-digit indices (7, 8, …).+ tmp_str = ",".join(predefined_ignore_layers)if self.ignore_layers == "":self.ignore_layers = tmp_strelse:diff --git a/auto_round/compressors/model_free.py b/auto_round/compressors/model_free.pyindex e9b7abde0..d5c89d395 100644--- a/auto_round/compressors/model_free.py+++ b/auto_round/compressors/model_free.py@@ -518,7 +518,7 @@ def _quantize_weight_mxfp(# quant_mx returns (qdq_tensor, shared_exp, None). We only need shared_exp# (the per-block log2 scale). The element-wise rounding to the FP4/FP8 grid# is performed inside QuantLinear.pack via dtype casts / pack_fp4_to_uint8.- _, shared_exp, _ = quant_mx(weight_dev, bits=bits, group_size=group_size, data_type=data_type)+ weight_dev, shared_exp, _ = quant_mx(weight_dev, bits=bits, group_size=group_size, data_type=data_type)# Reshape to (out_features, n_groups) so the on-disk weight_scale matches# the llm-compressor convention (and QuantLinear's registered buffer shape).shared_exp = shared_exp.reshape(out_features, in_features // group_size)diff --git a/auto_round/compressors/utils.py b/auto_round/compressors/utils.pyindex 74d851aca..3ac20abea 100644--- a/auto_round/compressors/utils.py+++ b/auto_round/compressors/utils.py@@ -558,6 +558,7 @@ def set_layer_config(# logger.warning_once(f"{n} skipped quantization (shape not divisible by 32).")# enforce shape divisibility for mxfp/nvfpif (is_nv_fp(default_dict["data_type"]) or is_mx_fp(default_dict["data_type"])) and not gguf_name:+ skipped_layers = []for n, m in model.named_modules():if type(m) in supported_types or m.__class__.__name__ in inner_supported_types:if m.weight.shape[1] % default_dict["group_size"]:@@ -565,9 +566,14 @@ def set_layer_config(layer_config[n].update({"bits": 16, "data_type": "fp", "act_bits": 16, "act_data_type": "fp", "fixed_by_user": True})- logger.warning_once(- f"{n} skipped quantization (shape not divisible by {default_dict['group_size']})."- )+ skipped_layers.append(n)++ compressed_skipped_layers = compress_layer_names(skipped_layers)+ if compressed_skipped_layers:+ logger.warning_once(+ f"some layers are skipped quantization (shape not divisible by {default_dict['group_size']}): "+ f"{compressed_skipped_layers}"+ )# 9. block layers: mark as in_blocks=Truefor name in get_layer_names_in_block(model, supported_types, quant_block_list, inner_supported_types):diff --git a/auto_round/experimental/utils.py b/auto_round/experimental/utils.pyindex 672a1e0fb..29509020b 100644--- a/auto_round/experimental/utils.py+++ b/auto_round/experimental/utils.py@@ -46,8 +46,7 @@ def update_parameter_data(module: torch.nn.Module, new_val: torch.Tensor, name:module.register_parameter(name, torch.nn.Parameter(new_val))else:logger.warning_once(- "Parameter %s not found in module %s, creating new parameter."- % (name, module.__class__.__name__ + str(getattr(module, "layer_idx", "")))+ "Parameter %s not found in module %s, creating new parameter." % (name, module.__class__.__name__))module.register_parameter(name, torch.nn.Parameter(new_val))diff --git a/auto_round/utils/offload.py b/auto_round/utils/offload.pyindex f0546db59..af9e34b23 100644--- a/auto_round/utils/offload.py+++ b/auto_round/utils/offload.py@@ -709,12 +709,18 @@ class OffloadManager:def _save_to_disk(self, name: str, module: torch.nn.Module) -> None:tmpdir = self._ensure_dir()safe_name = name.replace(".", "_")- save_path = os.path.join(tmpdir, f"{safe_name}.pt")+ save_path = os.path.join(tmpdir, f"{safe_name}.safetensors")try:+ from safetensors.torch import save_file as safe_save_file+# Skip meta tensors: they contain no real data (e.g. quantized weights# already flushed to disk by an immediate-saving shard writer).- state_dict = {k: v.cpu().contiguous() for k, v in module.state_dict().items() if v.device.type != "meta"}- torch.save(state_dict, save_path)+ state_dict = {+ k: v.cpu().contiguous()+ for k, v in module.state_dict().items()+ if isinstance(v, torch.Tensor) and v.device.type != "meta"+ }+ safe_save_file(state_dict, save_path)self._saved[name] = {"save_path": save_path}del state_dictexcept Exception as e:@@ -729,7 +735,9 @@ class OffloadManager:logger.warning(f"OffloadManager: file not found {save_path}")returntry:- state_dict = torch.load(save_path, map_location="cpu")+ from safetensors.torch import load_file as safe_load_file++ state_dict = safe_load_file(save_path, device="cpu")_load_state_dict_into_module(state_dict, module)except Exception as e:logger.warning(f"OffloadManager: failed to load {name}: {e}")diff --git a/auto_round/utils/weight_handler.py b/auto_round/utils/weight_handler.pyindex 77109d02a..2d5440362 100755--- a/auto_round/utils/weight_handler.py+++ b/auto_round/utils/weight_handler.py@@ -413,6 +413,10 @@ def convert_module_to_hp_if_necessary(# Check if it's a single quantized layer (has the attribute directly)if hasattr(model_or_layer, "quantized_weight_type") and model_or_layer.quantized_weight_type is not None:handler = get_handler(model_or_layer.quantized_weight_type)+ logger.info(+ f"Converting layer {model_or_layer.__class__.__name__} from "+ + f"{model_or_layer.quantized_weight_type.name} to {dtype}"+ )new_module = handler.convert_layer(model_or_layer, dtype, device, to_cpu)_sync_serialization_attrs(model_or_layer, new_module)return new_module@@ -420,9 +424,11 @@ def convert_module_to_hp_if_necessary(# Otherwise, traverse model and convert all quantized layers# Get handler for each layer to support mixed quantization typescnt = 0+ type_counts: dict = {}for n, m in model_or_layer.named_modules():if hasattr(m, "quantized_weight_type") and m.quantized_weight_type is not None:handler = get_handler(m.quantized_weight_type)+ type_counts[m.quantized_weight_type.name] = type_counts.get(m.quantized_weight_type.name, 0) + 1new_module = handler.convert_layer(m, dtype, device, to_cpu)_sync_serialization_attrs(m, new_module)new_module.quantized_weight_type = None # Clear quantized type after conversion@@ -431,6 +437,10 @@ def convert_module_to_hp_if_necessary(if cnt % 10 == 0:clear_memory()+ if type_counts:+ summary = ", ".join(f"{k}: {v} layers" for k, v in type_counts.items())+ logger.info(f"Converted quantized layers to {dtype}: {summary}")+return model_or_layerdiff --git a/test/helpers.py b/test/helpers.pyindex 5a1975bfe..60555cc46 100644--- a/test/helpers.py+++ b/test/helpers.py@@ -27,7 +27,14 @@ def forbid_threaded_packing(monkeypatch, module):monkeypatch.setattr(tctl, "threadpool_limits", _raise_threaded_packing)-def generate_prompt(model_obj_or_str, tokenizer=None, text="The capital of France is,", max_new_tokens=10, device=None):+def generate_prompt(+ model_obj_or_str,+ tokenizer=None,+ text="The capital of France is,",+ max_new_tokens=10,+ device=None,+ include_prompt=True,+):"""Generate text using a model and tokenizer.Args:@@ -37,7 +44,8 @@ def generate_prompt(model_obj_or_str, tokenizer=None, text="The capital of Francmax_new_tokens: Maximum number of new tokens to generate.Returns:- str: The generated text.+ str: The generated text. If include_prompt is False, returns only+ newly generated continuation tokens."""if device is None:device = get_major_device()@@ -50,16 +58,34 @@ def generate_prompt(model_obj_or_str, tokenizer=None, text="The capital of Francmodel = model.to(device)inputs = tokenizer(text, return_tensors="pt").to(model.device)generated_ids = model.generate(**inputs, max_new_tokens=max_new_tokens, do_sample=False)[0]- output = tokenizer.decode(generated_ids)+ if include_prompt:+ output_ids = generated_ids+ else:+ prompt_len = inputs["input_ids"].shape[-1]+ output_ids = generated_ids[prompt_len:]+ output = tokenizer.decode(output_ids)print(output)return outputdef eval_generated_prompt(- model, tokenizer=None, prompt_text="United States of", target_text="America", max_new_tokens=10, device=None+ model,+ tokenizer=None,+ prompt_text='Convert "hello" to uppercase, the answer is:',+ target_text="HELLO",+ max_new_tokens=10,+ device=None,):- generated_text = generate_prompt(model, tokenizer, prompt_text, max_new_tokens=max_new_tokens, device=device)- assert target_text in generated_text, f"Expected {target_text} in generated text: {generated_text}"+ generated_text = generate_prompt(+ model,+ tokenizer,+ prompt_text,+ max_new_tokens=max_new_tokens,+ device=device,+ include_prompt=False,+ )+ # accept lowercase target text as well, since some models may not follow the prompt exactly+ assert target_text.lower() in generated_text.lower(), f"Expected {target_text} in generated text: {generated_text}"def evaluate_accuracy(diff --git a/test/test_cuda/backends/test_marlin_backend.py b/test/test_cuda/backends/test_marlin_backend.pyindex 95b71b02b..d6541b8e4 100644--- a/test/test_cuda/backends/test_marlin_backend.py+++ b/test/test_cuda/backends/test_marlin_backend.py@@ -195,8 +195,8 @@ class TestAutoRoundMarlinBackend:)tokenizer = AutoTokenizer.from_pretrained(quantized_model_path)- # Inference generation check- eval_generated_prompt(model, tokenizer)+ # Inference generation check (smoke test only; OPT-125M is not instruction-following)+ model_infer(model, tokenizer)# Accuracy checkevaluate_accuracy(model, tokenizer, threshold=0.2, batch_size=16)torch.cuda.empty_cache()