"""Load the local Qwen2.5-VL checkpoint and processor. No training logic.""" from __future__ import annotations import logging from pathlib import Path from typing import Any import torch logger = logging.getLogger(__name__) VISION_TOKEN_IDS: tuple[int, ...] = (151652, 151653, 151654, 151655) DEFAULT_MODEL_DIR = Path("third-party/qwen") PROCESSOR_COPY_NAMES = ( "preprocessor_config.json", "chat_template.json", "tokenizer.json", "tokenizer_config.json", "vocab.json", "merges.txt", "special_tokens_map.json", "generation_config.json", ) def resolve_attn_implementation(preferred: str | None) -> str: if not preferred or preferred == "sdpa": return "sdpa" if preferred == "flash_attention_2": try: import flash_attn # noqa: F401 return "flash_attention_2" except Exception: logger.warning("flash_attention_2 requested but unavailable; using sdpa") return "sdpa" return preferred def _dtype(name: str | None) -> torch.dtype | str: if name in (None, "auto"): return "auto" return getattr(torch, name) def load_processor(model_dir: str | Path, min_pixels: int, max_pixels: int): from transformers import AutoProcessor processor = AutoProcessor.from_pretrained(str(model_dir), trust_remote_code=True) if hasattr(processor, "image_processor") and processor.image_processor is not None: processor.image_processor.min_pixels = min_pixels processor.image_processor.max_pixels = max_pixels return processor def language_lora_target_names(model) -> list[str]: suffixes = ("q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj") skip = ("visual", "vision", "merger") names: list[str] = [] for name, _module in model.named_modules(): if not name.endswith(suffixes): continue lowered = name.lower() if any(part in lowered for part in skip): continue names.append(name) return names def freeze_vision(model) -> int: frozen = 0 for name, param in model.named_parameters(): lowered = name.lower() if any(part in lowered for part in ("visual", "vision", "merger")): param.requires_grad = False frozen += 1 return frozen def load_model( model_dir: str | Path, *, torch_dtype: str = "bfloat16", attn_implementation: str | None = "flash_attention_2", gradient_checkpointing: bool = True, use_cache: bool | None = None, ) -> Any: try: from transformers import Qwen2_5_VLForConditionalGeneration except ImportError: # newer transformers fold the class into AutoModel from transformers import AutoModelForImageTextToText as Qwen2_5_VLForConditionalGeneration attn = resolve_attn_implementation(attn_implementation) kwargs: dict[str, Any] = { "trust_remote_code": True, "torch_dtype": _dtype(torch_dtype), "attn_implementation": attn, } # Transformers 5.x Qwen2.5-VL rejects use_cache on from_pretrained; set it on config. cache_on = (not gradient_checkpointing) if use_cache is None else bool(use_cache) try: model = Qwen2_5_VLForConditionalGeneration.from_pretrained(str(model_dir), **kwargs) except TypeError: kwargs.pop("torch_dtype", None) kwargs["dtype"] = _dtype(torch_dtype) model = Qwen2_5_VLForConditionalGeneration.from_pretrained(str(model_dir), **kwargs) if hasattr(model, "config"): model.config.use_cache = cache_on if gradient_checkpointing and hasattr(model, "gradient_checkpointing_enable"): model.gradient_checkpointing_enable() if hasattr(model, "config"): model.config.use_cache = False frozen = freeze_vision(model) logger.info("Loaded %s attn=%s frozen_vision_tensors=%s", model_dir, attn, frozen) return model def copy_processor_files(model_dir: str | Path, output_dir: str | Path) -> list[str]: src = Path(model_dir) dst = Path(output_dir) dst.mkdir(parents=True, exist_ok=True) copied: list[str] = [] for name in PROCESSOR_COPY_NAMES: src_file = src / name if src_file.is_file(): target = dst / name target.write_bytes(src_file.read_bytes()) copied.append(name) return copied