| 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 |
|
|