PTQ-Level Efficiency, QAT-Level Accuracy | 训练后量化的效率,量化感知训练的精度
add support for gemma4 model (#1655)
Heng Guo55977e7b46a2
diff --git a/auto_round/compressors/base.py b/auto_round/compressors/base.pyindex c416dadb6..18a3f1d89 100644--- a/auto_round/compressors/base.py+++ b/auto_round/compressors/base.py@@ -70,7 +70,7 @@ from auto_round.schemes import (scheme_to_preset_name,)from auto_round.sign_sgd import SignSGD-from auto_round.special_model_handler import get_predefined_ignore_layers, update_module+from auto_round.special_model_handler import get_predefined_fixed_attr, get_predefined_ignore_layers, update_modulefrom auto_round.utils import (INNER_SUPPORTED_LAYER_TYPES,SUPPORTED_DTYPES,@@ -568,6 +568,12 @@ class BaseCompressor(object):self.hadamard_config = normalize_hadamard_config(hadamard_config, self.data_type)self.model = apply_hadamard_transform(self.model, self.hadamard_config, data_type=self.data_type)+ self.blocks_requiring_input_ids = []+ self.has_variable_block_shape = False+ fixed_attr = get_predefined_fixed_attr(self.model) or {}+ for key, value in fixed_attr.items():+ setattr(self, key, value)+def _gen_auto_scheme(self) -> dict[str, dict]:if self.mllm:logger.info("AutoScheme is not yet supported for multimodal LLMs.")@@ -1515,17 +1521,20 @@ class BaseCompressor(object):if not all_blocks:raise ValueError("Could not find any blocks. Check the model or quant_block_list.")- all_first_block_names = [block[0] for block in all_blocks]+ if not self.has_variable_block_shape:+ to_cache_block_names = [block[0] for block in all_blocks]+ else:+ to_cache_block_names = flatten_list(all_blocks)layer_names = self._get_quantized_layer_names_outside_blocks()- if self.act_bits < 16 and (not self.act_dynamic or len(layer_names) > 0):+ if self.act_bits < 16 and (not self.act_dynamic or len(layer_names) > 0) or self.has_variable_block_shape:if len(layer_names) > 0:logger.warning("quantize layers outside blocks for static activation quantizaiton"" will significantly increase calibration time")- all_inputs = self.try_cache_inter_data_gpucpu(all_first_block_names, self.nsamples, layer_names)+ all_inputs = self.try_cache_inter_data_gpucpu(to_cache_block_names, self.nsamples, layer_names)else:- all_inputs = self.cache_inter_data(all_first_block_names, self.nsamples)+ all_inputs = self.cache_inter_data(to_cache_block_names, self.nsamples)# Clear hooks for multi-GPU setupsif hasattr(self.model, "hf_device_map") and len(self.model.hf_device_map) > 1:@@ -1549,20 +1558,28 @@ class BaseCompressor(object):if total_samples < self.batch_size:self.batch_size = total_sampleslogger.warning(f"Forcing batch size to {total_samples}")+ tmp_dtype = self.amp_dtype if self.amp else torch.float32input_ids = to_device(inputs.pop("input_ids"), self.cache_device)- input_others = to_device(inputs, self.cache_device)-- tmp_dtype = self.amp_dtype if self.amp else torch.float32input_ids = [id_.to(tmp_dtype) for id_ in input_ids]- for key, val in input_others.items():- if isinstance(val, torch.Tensor) and val.dtype in (torch.float16, torch.bfloat16):- input_others[key] = val.to(tmp_dtype)- elif isinstance(val, list):- input_others[key] = [to_dtype(v, tmp_dtype) for v in val]+ def process_input_others(input_others):+ input_others = to_device(input_others, self.cache_device)+ for key, val in input_others.items():+ if isinstance(val, torch.Tensor) and val.dtype in (torch.float16, torch.bfloat16):+ input_others[key] = val.to(tmp_dtype)+ elif isinstance(val, list):+ input_others[key] = [to_dtype(v, tmp_dtype) for v in val]+ return input_others++ input_others = inputs+ input_others = process_input_others(input_others)for block_name in block_names:+ if block_name in all_inputs.keys():+ input_others = all_inputs[block_name]+ input_others = process_input_others(input_others)+ all_inputs.pop(block_name)pbar.set_description(f"Quantizing {block_name}")block = get_module(self.model, block_name)materialize_model_(block)@@ -1813,14 +1830,17 @@ class BaseCompressor(object):self.model = self.model.to(self.amp_dtype)layer_names = self._get_quantized_layer_names_outside_blocks()- all_first_block_names = [block[0] for block in all_blocks]+ if not self.has_variable_block_shape:+ to_cache_block_names = [block[0] for block in all_blocks]+ else:+ to_cache_block_names = flatten_list(all_blocks)if len(layer_names) > 0:logger.info("Starting to cache block inputs. This may be slow due to external block layers: %s", layer_names)else:logger.info("start to cache block inputs")- all_inputs = self.try_cache_inter_data_gpucpu(all_first_block_names, self.nsamples, layer_names=layer_names)+ all_inputs = self.try_cache_inter_data_gpucpu(to_cache_block_names, self.nsamples, layer_names=layer_names)is_quantized_embedding = self._quantize_embedding_layer()clear_memory(device_list=self.device_list)all_q_inputs = None@@ -1828,7 +1848,7 @@ class BaseCompressor(object):all_inputs = copy.deepcopy(self.inputs)clear_memory(self.inputs, device_list=self.device_list)all_q_inputs = self.try_cache_inter_data_gpucpu(- all_first_block_names, self.nsamples, layer_names=layer_names+ to_cache_block_names, self.nsamples, layer_names=layer_names)# Remove accelerate dispatch hooks before moving parameters.# hf_device_map is kept for reference but hooks are no longer needed.@@ -1876,6 +1896,7 @@ class BaseCompressor(object):nblocks=self.nblocks,device=self.device,pbar=pbar,+ input_others_extra_blocks=all_inputs,)if self.is_immediate_packing and len(self.formats) != 1:raise ValueError(@@ -2084,6 +2105,7 @@ class BaseCompressor(object):first_block_name = self.quant_block_list[0][0]class _FakeDecodingLayer(torch.nn.Module):+def forward(self, *args, **kwargs):return args, kwargs@@ -2268,10 +2290,12 @@ class BaseCompressor(object):Raises:Exception: If caching on GPU fails, switches to CPU and caches there."""+ block_names = flatten_list(block_names)if is_quantized_input_module(self.model):layer_names = []if layer_names is None:layer_names = []+ self.blocks_requiring_input_ids = [data if isinstance(data, str) else data[0] for data in block_names]calibrate_on_cpu = Falsecannot_calibrate_on_cpu = False@@ -2280,6 +2304,7 @@ 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 not getattr(self, "mllm", False)):# low_gpu_mem_usage or calibrate only the embedding layer, which is also very fast on CPUcalibrate_on_cpu = True@@ -2426,17 +2451,18 @@ class BaseCompressor(object):if layer_names is None:layer_names = []self.inputs = {}+ block_names = flatten_list(block_names)self.to_cached_layers = block_names + layer_namestmp_dtype = None # TODO delete this as most model is not fp32 now- ## have bug if block name is not the first block+ # There is a bug if the block name is not the first blockif (len(block_names) > 1 or len(layer_names) > 0) and self.low_gpu_mem_usage:tmp_dtype = self.model.dtypeif self.amp:if self.model.dtype != self.model.dtype:self.model = self.model.to(torch.bfloat16)else:- self.model = self.model.to(torch.float32) ##model on cpu+ self.model = self.model.to(torch.float32) # model on cpuself.last_cache_name = self._infer_last_cache_name(block_names, layer_names, last_cache_name)self._cache_target_set = set(self.to_cached_layers)@@ -2571,6 +2597,12 @@ class BaseCompressor(object):or isinstance(kwargs[key], list)or isinstance(kwargs[key], tuple)):+ if (+ self.has_variable_block_shape+ and name not in self.blocks_requiring_input_ids+ and key == "hidden_states"+ ):+ continueif key not in self.inputs[name].keys(): # initializationdata = to_device(kwargs[key], device=torch.device("cpu"))if data is None or (self.batch_size > 1 and key in self.shared_cache_keys):@@ -2655,6 +2687,7 @@ class BaseCompressor(object):self.hook_handles.append(hook_handle)def _register_act_max_hook(self, model):+def get_act_max_hook(module, input, output):if isinstance(input, (tuple, list)):input = input[0]@@ -3259,7 +3292,7 @@ class BaseCompressor(object):return None, outputdef _split_inputs(self, inputs: dict, first_input_name: str) -> tuple[torch.Tensor, dict]:- input_ids = inputs[first_input_name]+ input_ids = inputs.get(first_input_name, None)inputs.pop(first_input_name, None)input_others = inputsreturn input_ids, input_others@@ -3267,13 +3300,13 @@ class BaseCompressor(object):def _preprocess_block_inputs(self, inputs, first_input_name="input_ids"):input_ids, input_others = self._split_inputs(inputs, first_input_name)clear_memory(device_list=self.device_list)- input_ids = to_device(input_ids, self.cache_device)+ tmp_dtype = self.amp_dtype if self.amp else torch.float32+ if input_ids is not None:+ input_ids = to_device(input_ids, self.cache_device)+ input_ids = to_dtype(input_ids, tmp_dtype)input_others = to_device(input_others, self.cache_device)# As in calibration phase, we may use bf16 for calibration due to low_gpu_memory usage- tmp_dtype = self.amp_dtype if self.amp else torch.float32- input_ids = to_dtype(input_ids, tmp_dtype)-for key in input_others.keys():if isinstance(input_others[key], torch.Tensor) and (input_others[key].dtype == torch.float16 or input_others[key].dtype == torch.bfloat16@@ -3293,6 +3326,7 @@ class BaseCompressor(object):nblocks: int = 1,device: str = "cpu",pbar: tqdm = None,+ input_others_extra_blocks: dict = None,):"""Quantize and dequantize the weights of the specified blocks in the model.@@ -3316,12 +3350,17 @@ class BaseCompressor(object):pbar = tqdm(range(0, len(block_names), nblocks))for i in range(0, len(block_names), nblocks):+ if input_others_extra_blocks and block_names[i] in input_others_extra_blocks:+ input_others = input_others_extra_blocks[block_names[i]]+ _, input_others = self._preprocess_block_inputs(input_others)+ input_others_extra_blocks.pop(block_names[i])if i != 0:pbar.update(1)if nblocks == 1:n = block_names[i]pbar.set_description(f"Quantizing {n}")m = get_module(model, n)+else:names = block_names[i : min(i + nblocks, len(block_names))]pbar.set_description(f"Quantizing [{i + 1}-{min(i + nblocks, len(block_names))}]/{len(block_names)}")diff --git a/auto_round/compressors/mllm/compressor.py b/auto_round/compressors/mllm/compressor.pyindex 06d7a512f..5b9f64ca8 100644--- a/auto_round/compressors/mllm/compressor.py+++ b/auto_round/compressors/mllm/compressor.py@@ -281,7 +281,10 @@ class MLLMCompressor(BaseCompressor):)dataset = "liuhaotian/llava_conv_58k"elif self.template is not None and not _only_text_test(- model, tokenizer, self.device, self.template.model_type+ model,+ tokenizer,+ self.device,+ getattr(getattr(model, "config", None), "model_type", None) or self.template.model_type,):logger.warning(f"{model.config.model_type} does not support for {dataset},"diff --git a/auto_round/compressors/shard_writer.py b/auto_round/compressors/shard_writer.pyindex f89ba714a..af3f510a3 100644--- a/auto_round/compressors/shard_writer.py+++ b/auto_round/compressors/shard_writer.py@@ -17,6 +17,7 @@ import osfrom collections import OrderedDictimport torch+from torch.nn import Parameterfrom auto_round.logger import loggerfrom auto_round.utils import get_lm_head_name, get_module@@ -196,7 +197,26 @@ class ShardWriter:and isinstance(module, torch.nn.Module)and all(f"{module_path}.{k}" in self._all_saved for k in module.state_dict().keys())):- module.to("meta")+ self._move_module_to_meta(module)++ def _move_module_to_meta(self, module: torch.nn.Module):+ for child in module.children():+ self._move_module_to_meta(child)++ for name, param in list(module._parameters.items()):+ if param is None:+ continue+ if isinstance(param, Parameter):+ meta_param = Parameter(param.detach().to(device="meta"), requires_grad=param.requires_grad)+ elif isinstance(param, torch.Tensor):+ meta_param = Parameter(param.detach().to(device="meta"), requires_grad=param.requires_grad)+ else:+ continue+ module._parameters[name] = meta_param++ for name, buffer in list(module._buffers.items()):+ if isinstance(buffer, torch.Tensor):+ module._buffers[name] = buffer.detach().to(device="meta")def finalize(self):"""Saves remaining weights, renames files, and writes the index JSON."""@@ -225,7 +245,7 @@ class ShardWriter:layer_name = ".".join(pname.split(".")[:-1])if self.lm_head_name is not None and layer_name == self.lm_head_name and tie_word_embeddings:lm_head_module = get_module(self.model, self.lm_head_name)- lm_head_module.to("meta") # Must to meta, otherwise model's saver will dump it again+ self._move_module_to_meta(lm_head_module) # Must to meta, otherwise model's saver will dump it againcontinueself._add_tensor(pname, tensor.detach().to("cpu"))diff --git a/auto_round/export/export_to_gguf/packing.py b/auto_round/export/export_to_gguf/packing.pyindex 218e7ca94..92b13d045 100644--- a/auto_round/export/export_to_gguf/packing.py+++ b/auto_round/export/export_to_gguf/packing.py@@ -77,11 +77,21 @@ def ggml_quant(n_blocks = data.nelement() // block_sizesplit_num = 16 if max(data.shape) > 100_000 else 1blocks = data.reshape((n_blocks, block_size))- scale = scale.to(device).reshape(blocks.shape[0], -1) if scale is not None else scale- zp = zp.to(device).reshape(blocks.shape[0], -1) if zp is not None and isinstance(zp, torch.Tensor) else zp- wmin = wmin.to(device).reshape(blocks.shape[0], -1) if wmin is not None else wmin- d_scale = d_scale.to(device).reshape(blocks.shape[0], -1) if d_scale is not None else d_scale- d_wmin = d_wmin.to(device).reshape(blocks.shape[0], -1) if d_wmin is not None else d_wmin++ def _safe_reshape(t):+ if t is None or not isinstance(t, torch.Tensor):+ return t+ # Q4_0 / Q5_0 etc. compute their own scales; metadata from a different+ # group size (e.g. 256 vs block_size 32) cannot be reshaped and is unused.+ if t.nelement() % blocks.shape[0] != 0:+ return None+ return t.to(device).reshape(blocks.shape[0], -1)++ scale = _safe_reshape(scale)+ zp = _safe_reshape(zp)+ wmin = _safe_reshape(wmin)+ d_scale = _safe_reshape(d_scale)+ d_wmin = _safe_reshape(d_wmin)quant_func = GGML_QUANT_TYPE[ggml_type]results = []chunk_size = (n_blocks + split_num - 1) // split_numdiff --git a/auto_round/special_model_handler.py b/auto_round/special_model_handler.pyindex 023ccabf5..1a336ee6f 100644--- a/auto_round/special_model_handler.py+++ b/auto_round/special_model_handler.py@@ -48,6 +48,7 @@ SUPPORT_ONLY_TEXT_MODELS = ["qwen2_5_omni","qwen3_omni_moe","gemma3",+ "gemma4",]NOT_SUPPORT_ONLY_TEXT_MODELS = ["mllama", "mistral3_2"]@@ -59,6 +60,136 @@ SPECIAL_SHARED_CACHE_KEYS["MiniMaxText01ForCausalLM"] = ("slope_rate",)MISTRAL_3_2_MODELS = ["Mistral-Small-3.2", "Magistral-Small", "Devstral-Small"]+def _patch_gemma4_model(model):+ """Patch each Gemma4 decoder layer so it recomputes position_embeddings and+ attention_mask from the cached position_ids when the cached versions have+ wrong dimensions (sliding_attention vs full_attention head_dims differ).++ During auto-round block-wise quantization the cached inputs from block 0+ (always a sliding_attention layer) are reused for every subsequent block.+ Full-attention layers (head_dim=512) would receive position embeddings+ computed for sliding layers (head_dim=256), causing a shape mismatch crash.+ """+ import types as _types++ try:+ from transformers.masking_utils import create_causal_mask, create_sliding_window_causal_mask+ from transformers.models.gemma4.modeling_gemma4 import Gemma4TextModel+ except ImportError:+ return model++ # Find the Gemma4TextModel by traversing the hierarchy+ text_model = None+ for _, submodule in model.named_modules():+ if isinstance(submodule, Gemma4TextModel):+ text_model = submodule+ break++ if text_model is None:+ return model++ rotary_emb = text_model.rotary_emb+ # Shared dict to propagate KV state between anchor/sharer layers (like+ # Gemma4TextModel.forward does in newer transformers versions).+ shared_kv_states_global = {}++ for layer in text_model.layers:+ original_forward = layer.forward+ layer_type = getattr(getattr(layer, "self_attn", None), "layer_type", None)+ if layer_type is None:+ continue+ head_dim = getattr(getattr(layer, "self_attn", None), "head_dim", None)+ is_full = layer_type == "full_attention"++ def _make_layer_forward(orig_fwd, lt, hd, is_full_attn, re, cfg, skv_global):+ import inspect++ orig_params = list(inspect.signature(orig_fwd).parameters)+ orig_has_shared_kv = "shared_kv_states" in orig_params++ def patched_layer_forward(+ self,+ hidden_states,+ per_layer_input=None,+ shared_kv_states=None,+ position_embeddings=None,+ attention_mask=None,+ position_ids=None,+ **kwargs,+ ):+ # Ensure shared_kv_states is always a dict (newer transformers+ # versions pass it as positional arg 3; None causes item assignment crash)+ if shared_kv_states is None:+ shared_kv_states = skv_global+ # Recompute position_embeddings when cached dim doesn't match+ if (+ hd is not None+ and position_embeddings is not None+ and isinstance(position_embeddings, (tuple, list))+ and len(position_embeddings) == 2+ ):+ cos, _ = position_embeddings+ if cos.shape[-1] != hd and position_ids is not None:+ position_embeddings = re(hidden_states, position_ids, lt)++ # per_layer_input is token-specific but is cached as shared positional+ # input (only 1st batch stored). Truncate/pad to match hidden_states seq_len.+ if per_layer_input is not None and per_layer_input.shape[1] != hidden_states.shape[1]:+ hs_seq = hidden_states.shape[1]+ pl_seq = per_layer_input.shape[1]+ if hs_seq <= pl_seq:+ per_layer_input = per_layer_input[:, :hs_seq, :]+ else:+ pad = per_layer_input[:, -1:, :].expand(-1, hs_seq - pl_seq, -1)+ per_layer_input = torch.cat([per_layer_input, pad], dim=1)++ # Recompute attention_mask for full-attention layers when a+ # sliding-window mask was cached (it would be too restrictive)+ if is_full_attn and attention_mask is not None and position_ids is not None:+ # Only rebuild if the mask was created for a shorter context+ # (sliding window masks have finite bandwidth)+ try:+ attention_mask = create_causal_mask(+ config=cfg,+ inputs_embeds=hidden_states,+ attention_mask=None,+ past_key_values=kwargs.get("past_key_values"),+ position_ids=position_ids,+ )+ except Exception:+ pass # fall back to whatever was cached++ if orig_has_shared_kv:+ return orig_fwd(+ hidden_states,+ per_layer_input,+ shared_kv_states,+ position_embeddings=position_embeddings,+ attention_mask=attention_mask,+ position_ids=position_ids,+ **kwargs,+ )+ return orig_fwd(+ hidden_states,+ per_layer_input,+ position_embeddings=position_embeddings,+ attention_mask=attention_mask,+ position_ids=position_ids,+ **kwargs,+ )++ return patched_layer_forward++ layer.forward = _types.MethodType(+ _make_layer_forward(+ original_forward, layer_type, head_dim, is_full, rotary_emb, text_model.config, shared_kv_states_global+ ),+ layer,+ )++ return model++def _handle_special_model(model):if hasattr(model, "config") and model.config.model_type == "deepseek_vl_v2":from functools import partial@@ -72,6 +203,12 @@ def _handle_special_model(model):from functools import partialmodel.forward = partial(_qwen3_omni_moe_forward, model)+ if hasattr(model, "config") and model.config.model_type == "gemma4":+ import transformers+ from packaging import version++ if version.parse(transformers.__version__) < version.parse("5.6"):+ _patch_gemma4_model(model)return model@@ -550,7 +687,6 @@ register_ignore_layers(],)-# glm5register_ignore_layers(matchers=[@@ -559,7 +695,6 @@ register_ignore_layers(ignore_layers=[get_glm_flash_ignore_layers, "weights_proj"], # vllm issue)-# step3p5register_ignore_layers(matchers=[@@ -608,6 +743,34 @@ def get_predefined_ignore_layers(model: torch.nn.Module) -> list[str]:return list(dict.fromkeys(layers))+# Maps model_type -> fixed attributes to set on the BaseCompressor instance.+# Only used when transformers >= 5.6, which natively supports per-block+# position_embedding recomputation (has_variable_block_shape).+_PRE_DEFINED_FIXED_ATTR = {"gemma4": {"has_variable_block_shape": True}}+++def get_predefined_fixed_attr(model: torch.nn.Module) -> dict | None:+ """Return fixed compressor attributes for models that need special caching.++ For Gemma4 with transformers >= 5.6, each decoder block must cache its own+ inputs because sliding vs full-attention layers require different+ position_embeddings. Returns ``None`` for older transformers, which instead+ rely on the per-layer forward patch applied in ``_handle_special_model``.+ """+ import transformers+ from packaging import version++ config = getattr(model, "config", None)+ if config is None or not hasattr(config, "model_type"):+ return None+ attrs = _PRE_DEFINED_FIXED_ATTR.get(config.model_type)+ if attrs is None:+ return None+ if version.parse(transformers.__version__) >= version.parse("5.6"):+ return attrs+ return None++def load_next_step_diffusion(pretrained_model_name_or_path, device_str):try:from models.gen_pipeline import NextStepPipeline # pylint: disable=E0401diff --git a/auto_round/utils/common.py b/auto_round/utils/common.pyindex 36cf34084..30c9edc0c 100644--- a/auto_round/utils/common.py+++ b/auto_round/utils/common.py@@ -717,43 +717,133 @@ def is_transformers_version_greater_or_equal_4():return version.parse(transformers.__version__) >= version.parse("4.0.0")+import json++def parse_layer_config_arg(s: str) -> dict:- """Parse --layer_config with unquoted keys/values.+ def strip_matching_quotes(token: str) -> str:+ token = token.strip().replace("“", '"').replace("”", '"')+ if len(token) >= 2 and token[0] == token[-1] and token[0] in ("'", '"'):+ return token[1:-1]+ return token++ def normalize_scalar(value):+ if not isinstance(value, str):+ return value++ value = strip_matching_quotes(value)+ if value.lstrip("-").isdigit():+ return int(value)+ try:+ return float(value)+ except ValueError:+ pass++ lower_value = value.lower()+ if lower_value == "true":+ return True+ if lower_value == "false":+ return False+ if lower_value in ("null", "none"):+ return None+ return value++ def normalize_tree(value):+ if isinstance(value, dict):+ return {normalize_scalar(k): normalize_tree(v) for k, v in value.items()}+ if isinstance(value, list):+ return [normalize_tree(item) for item in value]+ return normalize_scalar(value)++ def escape_invalid_json_backslashes(text: str) -> str:+ escaped = []+ in_string = False+ index = 0++ while index < len(text):+ ch = text[index]+ if not in_string:+ if ch == '"':+ in_string = True+ escaped.append(ch)+ index += 1+ continue++ if ch == "\\":+ next_ch = text[index + 1] if index + 1 < len(text) else ""+ if next_ch not in {'"', "\\", "/", "b", "f", "n", "r", "t", "u"}:+ escaped.append("\\\\")+ index += 1+ continue- Delimiters are ``{``, ``}``, ``,``, ``:``. Each non-delimiter token is- auto-typed: numeric strings become ``int``, everything else stays ``str``.+ if ch == '"':+ in_string = False+ escaped.append(ch)+ index += 1- Example::+ s = strip_matching_quotes(s)- {mtp:{bits:8},mtp.fc:{bits:16,data_type:fp}}- """- tokens = re.findall(r"[{}:,]|[^\s{}:,]+", s)- pos = [0]+ # 1. Prefer strict JSON.+ try:+ return normalize_tree(json.loads(s))+ except Exception:+ pass++ # 2. Repair shell-friendly regex strings like "\d" into valid JSON escapes.+ try:+ return normalize_tree(json.loads(escape_invalid_json_backslashes(s)))+ except Exception:+ pass- def _val():- tok = tokens[pos[0]]+ # 3. Fallback parser for CLI-friendly dict syntax.+ tokens = re.findall(r"[{}:,]|[^\s{}:,]+", s)+ pos = 0++ def peek():+ return tokens[pos] if pos < len(tokens) else None++ def consume(expected=None):+ nonlocal pos+ tok = peek()+ if tok is None:+ raise ValueError("Unexpected end of input")+ if expected and tok != expected:+ raise ValueError(f"Expected '{expected}', got '{tok}'")+ pos += 1+ return tok++ def parse_value():+ tok = peek()if tok == "{":- return _dict()- pos[0] += 1- try:- return int(tok)- except ValueError:- return tok+ return parse_dict()++ consume()+ return normalize_scalar(tok)- def _dict():- pos[0] += 1 # consume '{'+ def parse_dict():+ consume("{")result = {}- while tokens[pos[0]] != "}":- key = tokens[pos[0]]- pos[0] += 1 # key- pos[0] += 1 # consume ':'- result[key] = _val()- if tokens[pos[0]] == ",":- pos[0] += 1 # consume ','- pos[0] += 1 # consume '}'++ while True:+ tok = peek()+ if tok == "}":+ consume("}")+ break++ key = normalize_scalar(consume())+ consume(":")+ value = parse_value()+ result[key] = value++ if peek() == ",":+ consume(",")+return result- return _dict()+ result = parse_dict()+ if not isinstance(result, dict):+ raise ValueError("--layer_config must parse to a dictionary")+ return resultdef compress_layer_names(names: list) -> str:diff --git a/auto_round/utils/model.py b/auto_round/utils/model.pyindex 26256d6a4..6acaa8770 100644--- a/auto_round/utils/model.py+++ b/auto_round/utils/model.py@@ -1346,7 +1346,7 @@ def mv_module_from_gpu(module):for attr_name in list(module._parameters.keys()):p = module._parameters[attr_name]if p is not None and p.device.type != "meta" and p.device.type != "cpu":- module._parameters[attr_name] = p.to("cpu")+ module._parameters[attr_name] = torch.nn.Parameter(p.to("cpu"), requires_grad=p.requires_grad)for attr_name in list(module._buffers.keys()):b = module._buffers[attr_name]if b is not None and b.device.type != "meta" and b.device.type != "cpu":diff --git a/auto_round/wrapper.py b/auto_round/wrapper.pyindex 2478db548..782786a13 100644--- a/auto_round/wrapper.py+++ b/auto_round/wrapper.py@@ -653,10 +653,10 @@ class WrapperMultiblock(torch.nn.Module):super(WrapperMultiblock, self).__init__()self.layers = torch.nn.ModuleList(module_list)- def forward(self, x, **kwargs):+ def forward(self, x, *args, **kwargs):hidden_states = xfor idx, decoder_layer in enumerate(self.layers):- layer_outputs = decoder_layer(hidden_states, **kwargs)+ layer_outputs = decoder_layer(hidden_states, *args, **kwargs)hidden_states = layer_outputsif isinstance(hidden_states, tuple) or isinstance(hidden_states, list):hidden_states = layer_outputs[0]diff --git a/test/test_cpu/utils/test_cli_usage.py b/test/test_cpu/utils/test_cli_usage.pyindex 6b84cad60..c95d29eab 100644--- a/test/test_cpu/utils/test_cli_usage.py+++ b/test/test_cpu/utils/test_cli_usage.py@@ -95,3 +95,27 @@ def test_parse_layer_config():"mtp": {"bits": 8, "data_type": "int"},"mtp.fc": {"bits": 16, "data_type": "int"},}+++def test_parse_layer_config_with_quoted_regex_keys():+ """Quoted JSON-like input with regex paths should remain usable from the CLI."""+ result = parse_layer_config_arg(+ r'{"model.language_model.layers.\\d+.self_attn..":{"bits":"8"},'+ r'"model.language_model.layers.\\d+.router..*":{"bits":"8"}}'+ )+ assert result == {+ r"model.language_model.layers.\d+.self_attn..": {"bits": 8},+ r"model.language_model.layers.\d+.router..*": {"bits": 8},+ }+++def test_parse_layer_config_with_single_escaped_regex_keys():+ """Shell-passed strings often contain single backslashes that are invalid JSON but still recoverable."""+ result = parse_layer_config_arg(+ r'{"model.language_model.layers.\d+.self_attn..":{"bits":"8"},'+ r'"model.language_model.layers.\d+.mlp..":{"bits":"8"}}'+ )+ assert result == {+ r"model.language_model.layers.\d+.self_attn..": {"bits": 8},+ r"model.language_model.layers.\d+.mlp..": {"bits": 8},+ }diff --git a/test/test_cpu/utils/test_shard_writer.py b/test/test_cpu/utils/test_shard_writer.pyindex 2dc7c6b72..61d00ba92 100644--- a/test/test_cpu/utils/test_shard_writer.py+++ b/test/test_cpu/utils/test_shard_writer.py@@ -94,3 +94,17 @@ def test_finalize_skips_lm_head_when_tie_word_embeddings_true(tmp_path):assert "transformer_blocks.0.linear.weight" in saved_tensorsassert "lm_head.weight" not in saved_tensors, "lm_head must be skipped when tied"assert model.lm_head.weight.device.type == "meta"+++def test_finalize_offloads_module_with_tensor_in_parameters(tmp_path):+ model = _DiffusionStyleModel()+ model.transformer_blocks[0].linear._parameters["weight"] = model.transformer_blocks[0].linear.weight.to("cpu")+ rounder = _RounderStub(model, str(tmp_path))+ writer = ShardWriter(rounder)++ writer.save_module(model.transformer_blocks[0], "transformer_blocks.0")+ writer.finalize()++ offloaded_weight = model.transformer_blocks[0].linear._parameters["weight"]+ assert isinstance(offloaded_weight, torch.nn.Parameter)+ assert offloaded_weight.device.type == "meta"