Felipe97/llama-cpp-compiled
01.1k
1from __future__ import annotations2 3from typing import Callable, Iterable, TYPE_CHECKING4 5if TYPE_CHECKING:6 from torch import Tensor7 8from .base import MmprojModel, ModelBase, gguf9 10 11@ModelBase.register("InternVisionModel")12@ModelBase.example("OpenGVLab/InternVL3-2B", "OpenGVLab/InternVL2_5-1B")13class InternVisionModel(MmprojModel):14 15 min_dynamic_tiles: int = 016 max_dynamic_tiles: int = 017 18 def __init__(self, *args, **kwargs):19 super().__init__(*args, **kwargs)20 assert self.hparams_vision is not None21 self.min_dynamic_tiles = self.global_config.get("min_dynamic_patch", 0)22 self.max_dynamic_tiles = self.global_config.get("max_dynamic_patch", 0)23 24 def set_gguf_parameters(self):25 assert self.hparams_vision is not None26 if isinstance(self.hparams_vision['image_size'], list):27 self.hparams_vision['image_size'] = self.hparams_vision['image_size'][0]28 if isinstance(self.hparams_vision['patch_size'], list):29 self.hparams_vision['patch_size'] = self.hparams_vision['patch_size'][0]30 super().set_gguf_parameters()31 32 hparams = self.hparams33 self.gguf_writer.add_clip_projector_type(gguf.VisionProjectorType.INTERNVL)34 self.gguf_writer.add_vision_attention_layernorm_eps(hparams["layer_norm_eps"])35 # hidden_act36 if hparams["hidden_act"] == "silu":37 self.gguf_writer.add_vision_use_silu(True)38 elif hparams["hidden_act"] == "gelu":39 self.gguf_writer.add_vision_use_gelu(True)40 else:41 raise ValueError(f"Unsupported hidden_act: {hparams['hidden_act']}")42 # downsample_ratio43 downsample_ratio = self.global_config.get("downsample_ratio")44 assert downsample_ratio is not None45 self.gguf_writer.add_vision_projector_scale_factor(int(1.0 / downsample_ratio))46 # older models may not have min/max_dynamic_patch in config47 if self.min_dynamic_tiles > 0:48 self.gguf_writer.add_vision_preproc_min_tiles(self.min_dynamic_tiles)49 if self.max_dynamic_tiles > 0:50 self.gguf_writer.add_vision_preproc_max_tiles(self.max_dynamic_tiles)51 52 def tensor_force_quant(self, name, new_name, bid, n_dims):53 if ".position_embd." in new_name:54 return gguf.GGMLQuantizationType.F3255 return super().tensor_force_quant(name, new_name, bid, n_dims)56 57 @classmethod58 def filter_tensors(cls, item: tuple[str, Callable[[], Tensor]]) -> tuple[str, Callable[[], Tensor]] | None:59 name, gen = item60 61 vision_prefix = ['vision_model', 'mlp', 'model.vision_tower', 'model.multi_modal_projector']62 if not any([name.startswith(prefix) for prefix in vision_prefix]):63 return None64 # deal with intern-s1 special case65 names_map = {66 "model.multi_modal_projector.layer_norm.bias": "mlp1.0.bias",67 "model.multi_modal_projector.layer_norm.weight": "mlp1.0.weight",68 "model.multi_modal_projector.linear_1.bias": "mlp1.1.bias",69 "model.multi_modal_projector.linear_1.weight": "mlp1.1.weight",70 "model.multi_modal_projector.linear_2.bias": "mlp1.3.bias",71 "model.multi_modal_projector.linear_2.weight": "mlp1.3.weight",72 }73 if name in names_map:74 name = names_map[name]75 # correct name76 if name.startswith("vision_model"):77 name = "vision_tower." + name78 if (".ls" in name or ".lambda_" in name or "position_embedding" in name) and not name.endswith(".weight"):79 name += ".weight"80 81 return super().filter_tensors((name, gen))82 83 def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]:84 # split QKV tensors if needed85 if ".qkv." in name:86 if data_torch.ndim == 2: # weight87 c3, _ = data_torch.shape88 else: # bias89 c3 = data_torch.shape[0]90 assert c3 % 3 == 091 c = c3 // 392 wq = data_torch[:c]93 wk = data_torch[c: c * 2]94 wv = data_torch[c * 2:]95 yield from super().modify_tensors(wq, name.replace("attn.qkv", "self_attn.q_proj"), bid)96 yield from super().modify_tensors(wk, name.replace("attn.qkv", "self_attn.k_proj"), bid)97 yield from super().modify_tensors(wv, name.replace("attn.qkv", "self_attn.v_proj"), bid)98 else:99 yield from super().modify_tensors(data_torch, name, bid)100 