char-fork/llama.cpp

git clone https://git.t4t.associates/char-fork/llama.cpp

Xuan-Son Nguyenconvert: add @ModelBase.example (#27208)fa88ae936

char/aliceai-t5-moe
4.4 KiB99 linesraw
1from __future__ import annotations
2
3from typing import Callable, Iterable, TYPE_CHECKING
4
5if TYPE_CHECKING:
6    from torch import Tensor
7
8from .base import MmprojModel, ModelBase, gguf
9
10
11@ModelBase.register("InternVisionModel")
12@ModelBase.example("OpenGVLab/InternVL3-2B", "OpenGVLab/InternVL2_5-1B")
13class InternVisionModel(MmprojModel):
14
15    min_dynamic_tiles: int = 0
16    max_dynamic_tiles: int = 0
17
18    def __init__(self, *args, **kwargs):
19        super().__init__(*args, **kwargs)
20        assert self.hparams_vision is not None
21        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 None
26        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.hparams
33        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_act
36        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_ratio
43        downsample_ratio = self.global_config.get("downsample_ratio")
44        assert downsample_ratio is not None
45        self.gguf_writer.add_vision_projector_scale_factor(int(1.0 / downsample_ratio))
46        # older models may not have min/max_dynamic_patch in config
47        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.F32
55        return super().tensor_force_quant(name, new_name, bid, n_dims)
56
57    @classmethod
58    def filter_tensors(cls, item: tuple[str, Callable[[], Tensor]]) -> tuple[str, Callable[[], Tensor]] | None:
59        name, gen = item
60
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 None
64        # deal with intern-s1 special case
65        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 name
76        if name.startswith("vision_model"):
77            name = "vision_tower." + name
78        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 needed
85        if ".qkv." in name:
86            if data_torch.ndim == 2: # weight
87                c3, _ = data_torch.shape
88            else: # bias
89                c3 = data_torch.shape[0]
90            assert c3 % 3 == 0
91            c = c3 // 3
92            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)