Skip to content

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

fix gemma3 gguf ut fail (#1735)

Heng Guo98db0b3c07b5
diff --git a/auto_round/export/export_to_gguf/convert.py b/auto_round/export/export_to_gguf/convert.py
index 6e8078afa..78e0089e0 100644
--- a/auto_round/export/export_to_gguf/convert.py
+++ b/auto_round/export/export_to_gguf/convert.py
@@ -395,6 +395,13 @@ def _special_name_handle(cls, name):
visual_keys = ["multi_modal_projector", "vision_tower", "multimodal_projector"]
name = remove_prefix(name, visual_keys)
+ # AutoRound exports tensors from a live transformers model, while gguf tensor_mapping
+ # expects checkpoint-style names. Normalize known Gemma3 vision/projector variants.
+ if name.startswith("vision_tower.") and not name.startswith("vision_tower.vision_model."):
+ name = name.replace("vision_tower.", "vision_tower.vision_model.", 1)
+ if name.startswith("multi_modal_projector.mm_input_projection_weight"):
+ name = name.replace("mm_input_projection_weight", "mm_input_projection.weight", 1)
+
# for LlavaForConditionalGeneration
if cls.model_arch == gguf.MODEL_ARCH.LLAMA:
name = name.replace("language_model.", "")
diff --git a/test/helpers.py b/test/helpers.py
index 739b8925f..fcf62b116 100644
--- a/test/helpers.py
+++ b/test/helpers.py
@@ -45,10 +45,8 @@ def generate_prompt(model_obj_or_str, tokenizer=None, text="The capital of Franc
def eval_generated_prompt(
model, tokenizer=None, prompt_text="The United States of", target_text="America", max_new_tokens=10, device=None
):
- """Evaluate the generated text using a model and tokenizer."""
- out = generate_prompt(model, tokenizer, text=prompt_text, max_new_tokens=max_new_tokens, device=device)
- assert target_text.lower() in out.lower(), f"Expected '{target_text}' in output, but got: {out}"
- return out
+ 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}"
def evaluate_accuracy(
@@ -257,6 +255,9 @@ def get_tiny_model(
**kwargs: Extra keyword arguments forwarded to the model loader or
``AutoConfig.from_pretrained``.
"""
+ if "use_config" in kwargs:
+ from_config = kwargs.pop("use_config")
+
model_name_or_path = get_model_path(model_name_or_path)
if from_config:
@@ -315,30 +316,35 @@ def get_tiny_model(
and v[0] in ["diffusers", "transformers"]
):
_reduce_config_layers(getattr(model, k).config, num_layers, num_experts)
+ return model
else:
- trust_remote_code = kwargs.pop("trust_remote_code", True)
+ trust_remote_code = kwargs.get("trust_remote_code", True)
config = transformers.AutoConfig.from_pretrained(model_name_or_path, trust_remote_code=trust_remote_code)
- # Special cases, for transformers == 5.4.0
- if config.model_type == "qwen3_omni_moe":
- config.initializer_range = 0.02 # Default initializer range for weight initialization
- _reduce_config_layers(config, num_layers, num_experts)
-
- # Pick the right model class
- base_lib = transformers
- architectures = getattr(config, "architectures", [None])[0]
- if (
- is_mllm
- and architectures.endswith("Model")
- and hasattr(base_lib, n := architectures.replace("Model", "ForConditionalGeneration"))
- ):
- model_cls = getattr(base_lib, n)
- elif hasattr(base_lib, architectures):
- model_cls = getattr(base_lib, architectures)
- else:
- model_cls = transformers.AutoModelForCausalLM # default to causal LM if we can't find a better match
- model = model_cls._from_config(config)
- model = model.eval()
- return model
+ use_config_only = not (not trust_remote_code and getattr(config, "auto_map", None))
+ if use_config_only:
+ # Special cases, for transformers == 5.4.0
+ if config.model_type == "qwen3_omni_moe":
+ config.initializer_range = 0.02 # Default initializer range for weight initialization
+ _reduce_config_layers(config, num_layers, num_experts)
+
+ # Pick the right model class
+ base_lib = transformers
+ architectures = getattr(config, "architectures", [None])[0]
+ if (
+ is_mllm
+ and architectures.endswith("Model")
+ and hasattr(base_lib, n := architectures.replace("Model", "ForConditionalGeneration"))
+ ):
+ model_cls = getattr(base_lib, n)
+ elif hasattr(base_lib, architectures):
+ model_cls = getattr(base_lib, architectures)
+ else:
+ model_cls = (
+ transformers.AutoModelForCausalLM
+ ) # default to causal LM if we can't find a better match
+ model = model_cls._from_config(config)
+ model = model.eval()
+ return model
# ---- original path: load pretrained weights then slice ----
def slice_layers(module):
@@ -407,6 +413,9 @@ def save_tiny_model(
weights instead of downloading the full checkpoint.
**kwargs: Extra keyword arguments forwarded to the model loader.
"""
+ if "use_config" in kwargs:
+ from_config = kwargs.pop("use_config")
+
model = get_tiny_model(
model_name_or_path,
num_layers=num_layers,
@@ -425,25 +434,48 @@ def save_tiny_model(
set_attr(model, key, copy.deepcopy(weight))
test_path = os.path.dirname(__file__)
tiny_model_path = os.path.join(test_path, tiny_model_path.removeprefix("./"))
+ shutil.rmtree(tiny_model_path, ignore_errors=True)
+
+ if not kwargs.get("trust_remote_code", True) and getattr(getattr(model, "config", None), "auto_map", None):
+ del model.config.auto_map
model.save_pretrained(tiny_model_path)
if not is_diffusion:
tokenizer = transformers.AutoTokenizer.from_pretrained(model_name_or_path, **kwargs)
tokenizer.save_pretrained(tiny_model_path)
# copy tokenizer.model
+ model_path = model_name_or_path
if not os.path.isdir(model_name_or_path):
+ from huggingface_hub.errors import GatedRepoError, HfHubHTTPError, HFValidationError
+
from auto_round.utils import download_hf_model
- model_path = download_hf_model(model_name_or_path)
- else:
- model_path = model_name_or_path
+ try:
+ model_path = download_hf_model(model_name_or_path)
+ except (GatedRepoError, HfHubHTTPError, HFValidationError):
+ model_path = model_name_or_path
if os.path.isfile(os.path.join(model_path, "tokenizer.model")):
shutil.copy(os.path.join(model_path, "tokenizer.model"), os.path.join(tiny_model_path, "tokenizer.model"))
if is_mllm:
- processor = transformers.AutoProcessor.from_pretrained(model_name_or_path, **kwargs)
- image_processor = transformers.AutoImageProcessor.from_pretrained(model_name_or_path, **kwargs)
- processor.save_pretrained(tiny_model_path)
- image_processor.save_pretrained(tiny_model_path)
+ sources = [model_path]
+ if model_name_or_path not in sources:
+ sources.insert(0, model_name_or_path)
+
+ for source in sources:
+ try:
+ processor = transformers.AutoProcessor.from_pretrained(source, **kwargs)
+ processor.save_pretrained(tiny_model_path)
+ break
+ except (OSError, ValueError):
+ continue
+
+ for source in sources:
+ try:
+ image_processor = transformers.AutoImageProcessor.from_pretrained(source, **kwargs)
+ image_processor.save_pretrained(tiny_model_path)
+ break
+ except (OSError, ValueError):
+ continue
print(f"[Fixture]: built tiny model path:{tiny_model_path} for testing in session")
return tiny_model_path
@@ -505,6 +537,7 @@ def model_infer(model, tokenizer, apply_chat_template=False):
# Dummy dataloader for testing
class DataLoader:
+
def __init__(self):
self.batch_size = 1
diff --git a/test/test_cuda/export/test_gguf_format.py b/test/test_cuda/export/test_gguf_format.py
index 557c9b6bc..1e413970f 100644
--- a/test/test_cuda/export/test_gguf_format.py
+++ b/test/test_cuda/export/test_gguf_format.py
@@ -122,7 +122,7 @@ class TestAutoRound:
from ...helpers import save_tiny_model
model_name = get_model_path("ibm-granite/granite-4.0-h-tiny")
- tiny_model_path = save_tiny_model(model_name, "tiny_model_path", num_layers=2)
+ tiny_model_path = save_tiny_model(model_name, "tiny_granite_model_path", num_layers=2)
from auto_round import AutoRound
autoround = AutoRound(
@@ -141,6 +141,7 @@ class TestAutoRound:
@require_gguf
def test_vlm_gguf(self):
from huggingface_hub import hf_hub_download
+ from huggingface_hub.errors import GatedRepoError, HfHubHTTPError
from ...helpers import save_tiny_model
@@ -150,7 +151,12 @@ class TestAutoRound:
)
# Needs tokenizer.model for gguf
# New transformers won't download it even with use_fast=False
- file_path = hf_hub_download(repo_id=model_name, filename="tokenizer.model", local_dir=tiny_model_path)
+ tokenizer_model_path = os.path.join(tiny_model_path, "tokenizer.model")
+ if not os.path.isfile(tokenizer_model_path):
+ try:
+ hf_hub_download(repo_id=model_name, filename="tokenizer.model", local_dir=tiny_model_path)
+ except (GatedRepoError, HfHubHTTPError) as error:
+ pytest.skip(f"tokenizer.model unavailable for {model_name}: {error}")
from auto_round import AutoRound
@@ -171,7 +177,7 @@ class TestAutoRound:
if "mmproj-model.gguf" in file:
assert abs(file_size - 75) < 5.0
else:
- assert abs(file_size - 690) < 5.0
+ assert abs(file_size - 683) < 5.0
shutil.rmtree(tiny_model_path, ignore_errors=True)
@@ -214,7 +220,7 @@ class TestAutoRound:
model_path = get_model_path("Qwen/Qwen3-1.7B")
tiny_model_path = "./tmp/tiny_qwen3_1b"
- save_tiny_model(model_path, tiny_model_path, num_layers=8)
+ tiny_model_path = save_tiny_model(model_path, tiny_model_path, num_layers=8)
autoround = AutoRound(
tiny_model_path,
iters=0,