File size: 3,280 Bytes
d5049a2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations

from typing import List

import torch
from peft import LoraConfig, PeftModel, TaskType, get_peft_model
from transformers import AutoModelForMultimodalLM, AutoProcessor


VISION_MARKERS = ("visual", "vision", "image", "merger")
LORA_LEAF_NAMES = {
    "q_proj",
    "k_proj",
    "v_proj",
    "o_proj",
    "gate_proj",
    "up_proj",
    "down_proj",
    "in_proj_qkv",
    "in_proj_z",
    "in_proj_a",
    "in_proj_b",
    "out_proj",
}


def load_processor(model_path: str, local_files_only: bool = True):
    return AutoProcessor.from_pretrained(
        model_path,
        trust_remote_code=True,
        local_files_only=local_files_only,
    )


def load_base_model(
    model_path: str,
    *,
    attn_implementation: str = "sdpa",
    local_files_only: bool = True,
):
    return AutoModelForMultimodalLM.from_pretrained(
        model_path,
        torch_dtype=torch.bfloat16,
        attn_implementation=attn_implementation,
        trust_remote_code=True,
        local_files_only=local_files_only,
        low_cpu_mem_usage=True,
    )


def freeze_vision_parameters(model) -> int:
    count = 0
    for name, parameter in model.named_parameters():
        if any(marker in name.lower() for marker in VISION_MARKERS):
            parameter.requires_grad_(False)
            count += parameter.numel()
    return count


def discover_lora_targets(model) -> List[str]:
    """Return exact linear-module paths, excluding the vision tower and lm_head."""
    targets: List[str] = []
    for name, module in model.named_modules():
        if not isinstance(module, torch.nn.Linear):
            continue
        lower = name.lower()
        if any(marker in lower for marker in VISION_MARKERS) or lower.endswith("lm_head"):
            continue
        if name.rsplit(".", 1)[-1] in LORA_LEAF_NAMES:
            targets.append(name)
    if not targets:
        raise RuntimeError(
            "No supported LoRA targets were found. Print model.named_modules() and "
            "update LORA_LEAF_NAMES for this local model revision."
        )
    return sorted(set(targets))


def prepare_trainable_model(
    model,
    *,
    adapter_path: str | None,
    lora_r: int,
    lora_alpha: int,
    lora_dropout: float,
    freeze_vision: bool,
):
    if freeze_vision:
        freeze_vision_parameters(model)
    model.config.use_cache = False
    if hasattr(model, "gradient_checkpointing_enable"):
        model.gradient_checkpointing_enable(
            gradient_checkpointing_kwargs={"use_reentrant": False}
        )
    if hasattr(model, "enable_input_require_grads"):
        model.enable_input_require_grads()

    if adapter_path:
        return PeftModel.from_pretrained(model, adapter_path, is_trainable=True)

    targets = discover_lora_targets(model)
    config = LoraConfig(
        r=lora_r,
        lora_alpha=lora_alpha,
        lora_dropout=lora_dropout,
        bias="none",
        task_type=TaskType.CAUSAL_LM,
        target_modules=targets,
    )
    return get_peft_model(model, config)


def trainable_parameter_summary(model) -> tuple[int, int]:
    trainable = sum(p.numel() for p in model.parameters() if p.requires_grad)
    total = sum(p.numel() for p in model.parameters())
    return trainable, total