File size: 4,381 Bytes
5f4e9ea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
"""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