minicpmv.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889
  1. # coding=utf-8
  2. # Adapted from
  3. # https://github.com/huggingface/transformers/blob/v4.28.0/src/transformers/models/llama/modeling_llama.py
  4. # Copyright 2023 The vLLM team.
  5. # Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
  6. #
  7. # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
  8. # and OPT implementations in this library. It has been modified from its
  9. # original forms to accommodate minor architectural differences compared
  10. # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
  11. #
  12. # Licensed under the Apache License, Version 2.0 (the "License");
  13. # you may not use this file except in compliance with the License.
  14. # You may obtain a copy of the License at
  15. #
  16. # http://www.apache.org/licenses/LICENSE-2.0
  17. #
  18. # Unless required by applicable law or agreed to in writing, software
  19. # distributed under the License is distributed on an "AS IS" BASIS,
  20. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  21. # See the License for the specific language governing permissions and
  22. # limitations under the License.
  23. """Inference-only MiniCPM-V model compatible with HuggingFace weights."""
  24. import math
  25. import re
  26. from array import array
  27. from functools import partial
  28. from typing import (Any, Callable, Iterable, List, Mapping, Optional, Tuple,
  29. TypedDict)
  30. import torch
  31. import torch.types
  32. from PIL import Image
  33. from torch import nn
  34. from torch.nn.init import trunc_normal_
  35. from transformers import PretrainedConfig
  36. from aphrodite.attention import AttentionMetadata
  37. from aphrodite.common.config import CacheConfig, MultiModalConfig
  38. from aphrodite.common.sequence import (APHRODITE_TOKEN_ID_ARRAY_TYPE,
  39. IntermediateTensors, SequenceData)
  40. from aphrodite.inputs import INPUT_REGISTRY, InputContext, LLMInputs
  41. from aphrodite.modeling.layers.linear import ReplicatedLinear
  42. from aphrodite.modeling.layers.logits_processor import LogitsProcessor
  43. from aphrodite.modeling.layers.resampler import (Resampler2,
  44. get_2d_sincos_pos_embed)
  45. from aphrodite.modeling.layers.sampler import Sampler, SamplerOutput
  46. from aphrodite.modeling.layers.vocab_parallel_embedding import ParallelLMHead
  47. from aphrodite.modeling.model_loader.utils import set_default_torch_dtype
  48. from aphrodite.modeling.model_loader.weight_utils import default_weight_loader
  49. from aphrodite.modeling.models.interfaces import SupportsMultiModal
  50. from aphrodite.modeling.models.llama import LlamaModel
  51. from aphrodite.modeling.models.minicpm import MiniCPMModel
  52. from aphrodite.modeling.models.qwen2 import Qwen2Model
  53. from aphrodite.modeling.sampling_metadata import SamplingMetadata
  54. from aphrodite.multimodal import MULTIMODAL_REGISTRY
  55. from aphrodite.multimodal.image import cached_get_image_processor
  56. from aphrodite.multimodal.utils import cached_get_tokenizer
  57. from aphrodite.quantization import QuantizationConfig
  58. from .idefics2_vision_model import Idefics2VisionTransformer
  59. _KEYS_TO_MODIFY_MAPPING = {
  60. "llm.lm_head": "lm_head",
  61. "llm.model": "llm",
  62. }
  63. class MiniCPMVImagePixelInputs(TypedDict):
  64. pixel_values: List[torch.Tensor]
  65. """
  66. Shape: `(batch_size * num_images, num_channels, height, width)`
  67. Note that the image size may vary, so we pass it as a list
  68. instead of a batched tensor.
  69. """
  70. image_bounds: torch.Tensor
  71. """
  72. Shape: `(batch_size * num_images, 2)`
  73. This should be in `(start, stop)` format.
  74. """
  75. tgt_sizes: torch.Tensor
  76. """
  77. Shape: `(batch_size * num_images, 2)`
  78. This should be in `(height, width)` format.
  79. """
  80. MiniCPMVImageInputs = MiniCPMVImagePixelInputs
  81. DEFAULT_LN = partial(nn.LayerNorm, eps=1e-6)
  82. class BaseResampler(nn.Module):
  83. """
  84. A 2D perceiver-resampler network with one cross attention layers by
  85. (grid_size**2) learnable queries and 2d sincos pos_emb
  86. Outputs:
  87. A tensor with the shape of (grid_size**2, embed_dim)
  88. """
  89. def __init__(
  90. self,
  91. num_queries: int,
  92. embed_dim: int,
  93. num_heads: int,
  94. kv_dim: Optional[int] = None,
  95. norm_layer: Callable[[int], nn.LayerNorm] = DEFAULT_LN,
  96. ) -> None:
  97. super().__init__()
  98. self.num_queries = num_queries
  99. self.embed_dim = embed_dim
  100. self.num_heads = num_heads
  101. self.query = nn.Parameter(torch.zeros(self.num_queries, embed_dim))
  102. trunc_normal_(self.query, std=0.02)
  103. if kv_dim is not None and kv_dim != embed_dim:
  104. self.kv_proj = ReplicatedLinear(kv_dim, embed_dim, bias=False)
  105. else:
  106. # Maintain the same return value with ReplicatedLinear.forward
  107. self.kv_proj = lambda *args, **kwargs: (
  108. nn.Identity()(*args, **kwargs),
  109. None,
  110. )
  111. self.attn = nn.MultiheadAttention(embed_dim, num_heads)
  112. self.ln_q = norm_layer(embed_dim)
  113. self.ln_kv = norm_layer(embed_dim)
  114. self.ln_post = norm_layer(embed_dim)
  115. self.proj = nn.Parameter(
  116. (embed_dim**-0.5) * torch.randn(embed_dim, embed_dim))
  117. def _init_weights(self, m: nn.Module) -> None:
  118. if isinstance(m, nn.Linear):
  119. trunc_normal_(m.weight, std=0.02)
  120. if isinstance(m, nn.Linear) and m.bias is not None:
  121. nn.init.constant_(m.bias, 0)
  122. elif isinstance(m, nn.LayerNorm):
  123. nn.init.constant_(m.bias, 0)
  124. nn.init.constant_(m.weight, 1.0)
  125. def _repeat(self, query, N: int):
  126. return query.unsqueeze(1).repeat(1, N, 1)
  127. class Resampler2_5(BaseResampler):
  128. def __init__(
  129. self,
  130. num_queries: int,
  131. embed_dim: int,
  132. num_heads: int,
  133. kv_dim: Optional[int] = None,
  134. norm_layer: Callable[[int], nn.LayerNorm] = DEFAULT_LN,
  135. max_size: Tuple[int, int] = (70, 70),
  136. ) -> None:
  137. super().__init__(num_queries, embed_dim, num_heads, kv_dim, norm_layer)
  138. self.max_size = max_size
  139. self._set_2d_pos_cache(self.max_size)
  140. self.apply(self._init_weights)
  141. def _set_2d_pos_cache(self,
  142. max_size: Tuple[int, int],
  143. device: torch.types.Device = "cpu") -> None:
  144. pos_embed_arr = get_2d_sincos_pos_embed(self.embed_dim,
  145. max_size,
  146. version=(2, 5))
  147. pos_embed = torch.from_numpy(pos_embed_arr).float().to(device)
  148. self.register_buffer("pos_embed", pos_embed, persistent=False)
  149. def _adjust_pos_cache(self, tgt_sizes: torch.Tensor,
  150. device: torch.types.Device) -> None:
  151. max_h = tgt_sizes[:, 0].max().item()
  152. max_w = tgt_sizes[:, 1].max().item()
  153. assert isinstance(max_h, int) and isinstance(max_w, int)
  154. if max_h > self.max_size[0] or max_w > self.max_size[1]:
  155. self.max_size = (
  156. max(max_h, self.max_size[0]),
  157. max(max_w, self.max_size[1]),
  158. )
  159. self._set_2d_pos_cache(self.max_size, device)
  160. def forward(self, x: torch.Tensor,
  161. tgt_sizes: torch.Tensor) -> torch.Tensor:
  162. assert x.shape[0] == tgt_sizes.shape[0]
  163. bs = x.shape[0]
  164. device = x.device
  165. dtype = x.dtype
  166. patch_len = tgt_sizes[:, 0] * tgt_sizes[:, 1]
  167. self._adjust_pos_cache(tgt_sizes, device=device)
  168. max_patch_len = patch_len.max().item()
  169. assert isinstance(max_patch_len, int)
  170. key_padding_mask = torch.zeros((bs, max_patch_len),
  171. dtype=torch.bool,
  172. device=device)
  173. pos_embed = []
  174. for i in range(bs):
  175. tgt_h, tgt_w = tgt_sizes[i].tolist()
  176. pos_embed.append(self.pos_embed[:tgt_h, :tgt_w, :].reshape(
  177. (tgt_h * tgt_w, -1)).to(dtype)) # patches * D
  178. key_padding_mask[i, patch_len[i]:] = True
  179. pos_embed = torch.nn.utils.rnn.pad_sequence(pos_embed,
  180. batch_first=True,
  181. padding_value=0.0).permute(
  182. 1, 0,
  183. 2) # BLD => L * B * D
  184. x, _ = self.kv_proj(x) # B * L * D
  185. x = self.ln_kv(x).permute(1, 0, 2) # L * B * D
  186. q = self.ln_q(self.query) # Q * D
  187. out = self.attn(
  188. self._repeat(q, bs), # Q * B * D
  189. x + pos_embed, # L * B * D + L * B * D
  190. x,
  191. key_padding_mask=key_padding_mask,
  192. )[0]
  193. # out: Q * B * D
  194. x = out.permute(1, 0, 2) # B * Q * D
  195. x = self.ln_post(x)
  196. x = x @ self.proj
  197. return x
  198. def get_version_by_config(config: PretrainedConfig) -> Tuple[int, ...]:
  199. version_float = getattr(config, "version", None)
  200. # The old configs do not include version number
  201. # TODO: Remove this after the HF repos are updated
  202. if version_float is None:
  203. if config.hidden_size == 2304 and config.query_num == 64:
  204. return (2, 0)
  205. return (2, 5)
  206. version_str = str(version_float)
  207. return tuple(int(x) for x in version_str.split("."))
  208. def get_max_minicpmv_image_tokens(ctx: InputContext):
  209. hf_config = ctx.get_hf_config()
  210. return getattr(hf_config, "query_num", 64)
  211. def dummy_seq_data_for_minicpmv(seq_len: int, num_images: int):
  212. token_ids = array(APHRODITE_TOKEN_ID_ARRAY_TYPE, [0]) * seq_len
  213. return SequenceData(token_ids)
  214. def dummy_image_for_minicpmv(hf_config: PretrainedConfig, num_images: int):
  215. width = height = hf_config.image_size
  216. image = Image.new("RGB", (width, height), color=0)
  217. return {"image": image if num_images == 1 else [image] * num_images}
  218. def dummy_data_for_minicpmv(ctx: InputContext, seq_len: int,
  219. mm_counts: Mapping[str, int]):
  220. hf_config = ctx.get_hf_config()
  221. num_images = mm_counts["image"]
  222. seq_data = dummy_seq_data_for_minicpmv(seq_len, num_images)
  223. mm_data = dummy_image_for_minicpmv(hf_config, num_images)
  224. return seq_data, mm_data
  225. def input_processor_for_minicpmv(ctx: InputContext, llm_inputs: LLMInputs):
  226. multi_modal_data = llm_inputs.get("multi_modal_data")
  227. if multi_modal_data is None or "image" not in multi_modal_data:
  228. return llm_inputs
  229. model_config = ctx.model_config
  230. version = get_version_by_config(model_config.hf_config)
  231. tokenizer = cached_get_tokenizer(model_config.tokenizer,
  232. trust_remote_code=True)
  233. image_processor = cached_get_image_processor(model_config.tokenizer)
  234. def get_placeholder(image_size: Tuple[int, int], num_image: int):
  235. if version == (2, 0) or version == (2, 5):
  236. return image_processor. \
  237. get_slice_image_placeholder(image_size)
  238. return image_processor. \
  239. get_slice_image_placeholder(image_size, num_image)
  240. prompt = llm_inputs.get("prompt")
  241. if prompt is None:
  242. token_ids = llm_inputs.get("prompt_token_ids")
  243. prompt = tokenizer.decode(token_ids)
  244. pattern = "(<image>./</image>)"
  245. images = multi_modal_data["image"]
  246. if isinstance(images, Image.Image):
  247. images = [images]
  248. image_tags = re.findall(pattern, prompt)
  249. if len(image_tags) == 0:
  250. new_token_ids = token_ids
  251. new_prompt = prompt
  252. else:
  253. text_chunks = prompt.split(pattern)
  254. new_prompt_chunks: List[str] = []
  255. for i in range(len(images)):
  256. new_prompt_chunks += [
  257. text_chunks[i],
  258. get_placeholder(images[i].size, i)
  259. ]
  260. new_prompt_chunks.append(text_chunks[-1])
  261. new_prompt = "".join(new_prompt_chunks)
  262. new_token_ids = tokenizer.encode(new_prompt)
  263. llm_inputs = LLMInputs(
  264. prompt_token_ids=new_token_ids,
  265. prompt=new_prompt,
  266. multi_modal_data=multi_modal_data,
  267. )
  268. return llm_inputs
  269. class MiniCPMVBaseModel(nn.Module, SupportsMultiModal):
  270. """
  271. The abstract class of MiniCPMV can only be inherited, but cannot be
  272. instantiated.
  273. """
  274. def __init__(
  275. self,
  276. config: PretrainedConfig,
  277. multimodal_config: MultiModalConfig,
  278. cache_config: Optional[CacheConfig] = None,
  279. quant_config: Optional[QuantizationConfig] = None,
  280. ):
  281. super().__init__()
  282. # All MiniCPM-V models disable `tie_word_embeddings` but
  283. # `PretrainedConfig.tie_word_embeddings` defaults to True; we cannot
  284. # check `tie_word_embeddings` until vLLM integrate MiniCPM-V model
  285. # and config class
  286. self.config = config
  287. self.multimodal_config = multimodal_config
  288. self.version = get_version_by_config(self.config)
  289. self.llm = self.init_llm(config, cache_config, quant_config)
  290. self.vpm = self.init_vision_module()
  291. param_dtype = torch.get_default_dtype()
  292. self.vpm.to(dtype=param_dtype)
  293. self.vision_dim = (self.vpm.embed_dim if self.version == (2, 0) else
  294. self.vpm.embeddings.embed_dim)
  295. self.embed_dim = self.config.hidden_size
  296. self.resampler = self.init_resampler(self.embed_dim, self.vision_dim)
  297. self.resampler.to(device="cuda", dtype=param_dtype)
  298. self.lm_head = ParallelLMHead(config.vocab_size,
  299. config.hidden_size,
  300. quant_config=quant_config)
  301. self.logits_processor = LogitsProcessor(config.vocab_size)
  302. self.sampler = Sampler()
  303. def get_embedding(
  304. self,
  305. input_ids: torch.Tensor,
  306. image_inputs: Optional[MiniCPMVImageInputs],
  307. ) -> Tuple[torch.Tensor, torch.Tensor]:
  308. vlm_embedding: torch.Tensor = self.llm.embed_tokens(input_ids)
  309. if hasattr(self.config, "scale_emb"):
  310. vlm_embedding *= self.config.scale_emb
  311. if image_inputs is None: # No image
  312. vision_hidden_states = torch.tensor([], device=input_ids.device)
  313. else:
  314. vision_hidden_states = self.get_vision_hidden_states(image_inputs)
  315. # See NOTE in _parse_and_validate_inputs
  316. image_bounds = image_inputs["image_bounds"]
  317. if len(image_bounds) > 0:
  318. image_indices = torch.stack([
  319. torch.arange(start, end, dtype=torch.long)
  320. for start, end in image_bounds.tolist()
  321. ]).to(vlm_embedding.device)
  322. vlm_embedding.scatter_(
  323. 0,
  324. image_indices.view(-1, 1).repeat(1,
  325. vlm_embedding.shape[-1]),
  326. vision_hidden_states.view(-1,
  327. vision_hidden_states.shape[-1]),
  328. )
  329. return vlm_embedding, vision_hidden_states
  330. def _get_image_bounds(self, input_ids: torch.Tensor) -> torch.Tensor:
  331. tokenizer = cached_get_tokenizer(self.config._name_or_path,
  332. trust_remote_code=True)
  333. start_cond = input_ids == tokenizer.im_start_id
  334. end_cond = input_ids == tokenizer.im_end_id
  335. if hasattr(tokenizer, "slice_start_id"):
  336. start_cond |= (input_ids == tokenizer.slice_start_id)
  337. end_cond |= (input_ids == tokenizer.slice_end_id)
  338. image_start_tokens, = torch.where(start_cond)
  339. image_start_tokens += 1
  340. image_end_tokens, = torch.where(end_cond)
  341. valid_image_nums = max(len(image_start_tokens), len(image_end_tokens))
  342. if valid_image_nums == 0:
  343. return torch.zeros((0, 2), device=input_ids.device)
  344. return torch.hstack([
  345. image_start_tokens[:valid_image_nums].unsqueeze(-1),
  346. image_end_tokens[:valid_image_nums].unsqueeze(-1),
  347. ])
  348. def _parse_and_validate_inputs(
  349. self,
  350. input_ids: torch.Tensor,
  351. **kwargs: object,
  352. ) -> Optional[MiniCPMVImageInputs]:
  353. pixel_values = kwargs.pop("pixel_values", [])
  354. tgt_sizes = kwargs.pop("tgt_sizes", [])
  355. if not isinstance(pixel_values, (torch.Tensor, list)):
  356. raise ValueError("Incorrect type of pixel values. "
  357. f"Got type: {type(pixel_values)}")
  358. if not isinstance(tgt_sizes, (torch.Tensor, list)):
  359. raise ValueError("Incorrect type of target sizes. "
  360. f"Got type: {type(tgt_sizes)}")
  361. if len(pixel_values) != len(tgt_sizes):
  362. raise ValueError("Inconsistent batch lengths, found: "
  363. f"{len(pixel_values)} vs. {len(tgt_sizes)}")
  364. pixel_values_flat: List[torch.Tensor] = []
  365. tgt_sizes_flat: List[torch.Tensor] = []
  366. for pixel_b, tgt_b in zip(pixel_values, tgt_sizes):
  367. if len(pixel_b) != len(tgt_b):
  368. raise ValueError("Inconsistent N lengths, found: "
  369. f"{len(pixel_b)} vs {len(tgt_b)}")
  370. for pixel_n, tgt_n in zip(pixel_b, tgt_b):
  371. pixel_values_flat += pixel_n
  372. tgt_sizes_flat += tgt_n
  373. # NOTE: Input IDs does not contain image tokens during memory profiling,
  374. # so we allow it to be empty
  375. if len(pixel_values_flat) != len(tgt_sizes_flat):
  376. raise ValueError("Inconsistent flattened lengths, found: "
  377. f"{len(pixel_values_flat)} vs. "
  378. f"{len(tgt_sizes_flat)}")
  379. if len(pixel_values_flat) == 0:
  380. return None
  381. return MiniCPMVImageInputs(
  382. image_bounds=self._get_image_bounds(input_ids),
  383. pixel_values=pixel_values_flat,
  384. tgt_sizes=torch.stack(tgt_sizes_flat),
  385. )
  386. def forward(
  387. self,
  388. input_ids: torch.Tensor,
  389. positions: torch.Tensor,
  390. kv_caches: List[torch.Tensor],
  391. attn_metadata: AttentionMetadata,
  392. intermediate_tensors: Optional[IntermediateTensors] = None,
  393. **kwargs: Any,
  394. ) -> torch.Tensor:
  395. image_inputs = self._parse_and_validate_inputs(input_ids, **kwargs)
  396. vlm_embeddings, _ = self.get_embedding(input_ids, image_inputs)
  397. output = self.llm(
  398. input_ids=None,
  399. positions=positions,
  400. kv_caches=kv_caches,
  401. attn_metadata=attn_metadata,
  402. intermediate_tensors=intermediate_tensors,
  403. inputs_embeds=vlm_embeddings,
  404. )
  405. return output
  406. def compute_logits(
  407. self,
  408. hidden_states: torch.Tensor,
  409. sampling_metadata: SamplingMetadata,
  410. ) -> Optional[torch.Tensor]:
  411. logits = self.logits_processor(self.lm_head, hidden_states,
  412. sampling_metadata)
  413. return logits
  414. def sample(
  415. self,
  416. logits: torch.Tensor,
  417. sampling_metadata: SamplingMetadata,
  418. ) -> Optional[SamplerOutput]:
  419. next_tokens = self.sampler(logits, sampling_metadata)
  420. return next_tokens
  421. def load_weights(self, weights: Iterable[Tuple[str, torch.Tensor]]):
  422. stacked_params_mapping = [
  423. # (param_name, shard_name, shard_id)
  424. ("qkv_proj", "q_proj", "q"),
  425. ("qkv_proj", "k_proj", "k"),
  426. ("qkv_proj", "v_proj", "v"),
  427. ("gate_up_proj", "gate_proj", 0),
  428. ("gate_up_proj", "up_proj", 1),
  429. ]
  430. params_dict = dict(self.named_parameters())
  431. for name, loaded_weight in weights:
  432. for key_to_modify, new_key in _KEYS_TO_MODIFY_MAPPING.items():
  433. if key_to_modify in name:
  434. name = name.replace(key_to_modify, new_key)
  435. if "rotary_emb.inv_freq" in name:
  436. continue
  437. if ("rotary_emb.cos_cached" in name
  438. or "rotary_emb.sin_cached" in name):
  439. # Models trained using ColossalAI may include these tensors in
  440. # the checkpoint. Skip them.
  441. continue
  442. use_default_weight_loading = False
  443. if self.is_default_weight_loading(name):
  444. use_default_weight_loading = True
  445. else:
  446. for param_name, weight_name, shard_id in stacked_params_mapping:
  447. if weight_name not in name:
  448. continue
  449. param = params_dict[name.replace(weight_name, param_name)]
  450. weight_loader = param.weight_loader
  451. weight_loader(param, loaded_weight, shard_id)
  452. break
  453. else:
  454. use_default_weight_loading = True
  455. if use_default_weight_loading:
  456. param = params_dict[name]
  457. weight_loader = getattr(param, "weight_loader",
  458. default_weight_loader)
  459. weight_loader(param, loaded_weight)
  460. def init_llm(
  461. self,
  462. config: PretrainedConfig,
  463. cache_config: Optional[CacheConfig] = None,
  464. quant_config: Optional[QuantizationConfig] = None,
  465. ) -> nn.Module:
  466. raise NotImplementedError
  467. def init_vision_module(self) -> nn.Module:
  468. raise NotImplementedError
  469. def init_resampler(self, embed_dim: int, vision_dim: int) -> nn.Module:
  470. raise NotImplementedError
  471. def get_vision_embedding(
  472. self,
  473. pixel_values: List[torch.Tensor],
  474. patch_attn_mask: Optional[torch.Tensor] = None,
  475. tgt_sizes: Optional[torch.Tensor] = None,
  476. ) -> torch.Tensor:
  477. raise NotImplementedError
  478. def get_vision_hidden_states(self,
  479. data: MiniCPMVImageInputs) -> torch.Tensor:
  480. raise NotImplementedError
  481. def is_default_weight_loading(self, name: str) -> bool:
  482. raise NotImplementedError
  483. class MiniCPMV2_0(MiniCPMVBaseModel):
  484. def __init__(
  485. self,
  486. config: PretrainedConfig,
  487. multimodal_config: MultiModalConfig,
  488. cache_config: Optional[CacheConfig] = None,
  489. quant_config: Optional[QuantizationConfig] = None,
  490. ):
  491. super().__init__(config, multimodal_config, cache_config, quant_config)
  492. assert self.version == (2, 0)
  493. def init_llm(
  494. self,
  495. config: PretrainedConfig,
  496. cache_config: Optional[CacheConfig] = None,
  497. quant_config: Optional[QuantizationConfig] = None,
  498. ) -> nn.Module:
  499. return MiniCPMModel(config,
  500. cache_config=cache_config,
  501. quant_config=quant_config)
  502. def init_vision_module(self) -> nn.Module:
  503. # TODO :refactor this vision model
  504. try:
  505. import timm
  506. except ImportError:
  507. raise ImportError("Please install timm==0.9.10") from ImportError
  508. with set_default_torch_dtype(torch.float16):
  509. model = timm.create_model(
  510. "vit_so400m_patch14_siglip_384.webli",
  511. pretrained=False,
  512. num_classes=0,
  513. dynamic_img_size=True,
  514. dynamic_img_pad=True,
  515. )
  516. if (isinstance(model, timm.models.VisionTransformer)
  517. and model.attn_pool is not None):
  518. model.attn_pool = torch.nn.Identity()
  519. if self.config.drop_vision_last_layer:
  520. model.blocks = model.blocks[:-1]
  521. return model
  522. def init_resampler(self, embed_dim: int, vision_dim: int) -> nn.Module:
  523. with set_default_torch_dtype(torch.float16):
  524. resampler = Resampler2(
  525. embed_dim=embed_dim,
  526. num_heads=embed_dim // 128,
  527. grid_size=int(math.sqrt(self.config.query_num)),
  528. kv_dim=vision_dim,
  529. adaptive=False,
  530. do_post_projection=True,
  531. )
  532. return resampler
  533. def get_vision_embedding(
  534. self,
  535. pixel_values: List[torch.Tensor],
  536. patch_attn_mask: Optional[torch.Tensor] = None,
  537. tgt_sizes: Optional[torch.Tensor] = None,
  538. ) -> torch.Tensor:
  539. res = []
  540. dtype = self.vpm.pos_embed.data.dtype
  541. for pixel_value in pixel_values:
  542. H, W = pixel_value[0].shape[-2:]
  543. tgt_size = (
  544. math.ceil(H / self.vpm.patch_embed.patch_size[0]),
  545. math.ceil(W / self.vpm.patch_embed.patch_size[0]),
  546. )
  547. vision_embedding = self.vpm.forward_features(
  548. pixel_value.unsqueeze(0).type(dtype))
  549. if (hasattr(self.vpm, "num_prefix_tokens")
  550. and self.vpm.num_prefix_tokens > 0):
  551. vision_embedding = vision_embedding[:, self.vpm.
  552. num_prefix_tokens:]
  553. res.append(self.resampler(vision_embedding, tgt_size))
  554. return torch.vstack(res)
  555. def get_vision_hidden_states(self,
  556. data: MiniCPMVImageInputs) -> torch.Tensor:
  557. pixel_values = data["pixel_values"]
  558. return self.get_vision_embedding(pixel_values)
  559. def is_default_weight_loading(self, name: str) -> bool:
  560. return "resampler" in name or "vpm" in name
  561. class MiniCPMV2_5(MiniCPMVBaseModel):
  562. def __init__(
  563. self,
  564. config: PretrainedConfig,
  565. multimodal_config: MultiModalConfig,
  566. cache_config: Optional[CacheConfig] = None,
  567. quant_config: Optional[QuantizationConfig] = None,
  568. ):
  569. super().__init__(config, multimodal_config, cache_config, quant_config)
  570. assert self.version == (2, 5)
  571. def init_llm(
  572. self,
  573. config: PretrainedConfig,
  574. cache_config: Optional[CacheConfig] = None,
  575. quant_config: Optional[QuantizationConfig] = None,
  576. ) -> nn.Module:
  577. return LlamaModel(config,
  578. cache_config=cache_config,
  579. quant_config=quant_config)
  580. def init_vision_module(self) -> nn.Module:
  581. model = Idefics2VisionTransformer(self.config.vision_config)
  582. if self.config.drop_vision_last_layer:
  583. model.encoder.layers = model.encoder.layers[:-1]
  584. return model
  585. def init_resampler(self, embed_dim: int, vision_dim: int) -> nn.Module:
  586. with set_default_torch_dtype(torch.float16):
  587. resampler = Resampler2_5(
  588. num_queries=self.config.query_num,
  589. embed_dim=embed_dim,
  590. num_heads=embed_dim // 128,
  591. kv_dim=vision_dim,
  592. )
  593. return resampler
  594. def get_vision_embedding(
  595. self,
  596. pixel_values: List[torch.Tensor],
  597. patch_attn_mask: Optional[torch.Tensor] = None,
  598. tgt_sizes: Optional[torch.Tensor] = None,
  599. ) -> torch.Tensor:
  600. vision_embedding = self.vpm(pixel_values,
  601. patch_attention_mask=patch_attn_mask)
  602. vision_embedding = self.resampler(vision_embedding, tgt_sizes)
  603. return vision_embedding
  604. def get_vision_hidden_states(self,
  605. data: MiniCPMVImageInputs) -> torch.Tensor:
  606. pixel_values = data["pixel_values"]
  607. tgt_sizes = data["tgt_sizes"]
  608. device = self.vpm.embeddings.position_embedding.weight.device
  609. dtype = self.vpm.embeddings.position_embedding.weight.dtype
  610. all_pixel_values_lst = [
  611. i.flatten(end_dim=1).permute(1, 0) for i in pixel_values
  612. ]
  613. max_patches = (tgt_sizes[:, 0] * tgt_sizes[:, 1]).max().item()
  614. assert isinstance(max_patches, int)
  615. all_pixel_values = torch.nn.utils.rnn.pad_sequence(
  616. all_pixel_values_lst, batch_first=True, padding_value=0.0)
  617. B, L, _ = all_pixel_values.shape
  618. all_pixel_values = all_pixel_values.permute(0, 2,
  619. 1).reshape(B, 3, -1, L)
  620. patch_attn_mask = torch.zeros((B, 1, max_patches),
  621. dtype=torch.bool,
  622. device=device)
  623. for i in range(B):
  624. patch_attn_mask[i, :tgt_sizes[i][0] * tgt_sizes[i][1]] = True
  625. return self.get_vision_embedding(all_pixel_values.type(dtype),
  626. patch_attn_mask, tgt_sizes)
  627. def is_default_weight_loading(self, name: str) -> bool:
  628. return "resampler" in name
  629. class MiniCPMV2_6(MiniCPMVBaseModel):
  630. def __init__(
  631. self,
  632. config: PretrainedConfig,
  633. multimodal_config: MultiModalConfig,
  634. cache_config: Optional[CacheConfig] = None,
  635. quant_config: Optional[QuantizationConfig] = None,
  636. ):
  637. super().__init__(config, multimodal_config, cache_config, quant_config)
  638. assert self.version == (2, 6)
  639. def init_llm(
  640. self,
  641. config: PretrainedConfig,
  642. cache_config: Optional[CacheConfig] = None,
  643. quant_config: Optional[QuantizationConfig] = None,
  644. ) -> nn.Module:
  645. return Qwen2Model(config,
  646. cache_config=cache_config,
  647. quant_config=quant_config)
  648. def init_vision_module(self) -> nn.Module:
  649. # A custom version of SiglipVisionTransformer, won't work with TP
  650. from aphrodite.modeling.models.na_vit import SiglipVisionTransformer
  651. if self.config._attn_implementation == "flash_attention_2":
  652. self.config.vision_config._attn_implementation = "flash_attention_2"
  653. else:
  654. # not support sdpa
  655. self.config.vision_config._attn_implementation = "eager"
  656. model = SiglipVisionTransformer(self.config.vision_config)
  657. if self.config.drop_vision_last_layer:
  658. model.encoder.layers = model.encoder.layers[:-1]
  659. return model
  660. def init_resampler(self, embed_dim: int, vision_dim: int) -> nn.Module:
  661. with set_default_torch_dtype(torch.float16):
  662. # The resampler in 2.6 remains consistent with the one in 2.5.
  663. resampler = Resampler2_5(
  664. num_queries=self.config.query_num,
  665. embed_dim=embed_dim,
  666. num_heads=embed_dim // 128,
  667. kv_dim=vision_dim,
  668. )
  669. return resampler
  670. def get_vision_embedding(
  671. self,
  672. pixel_values: List[torch.Tensor],
  673. patch_attn_mask: Optional[torch.Tensor] = None,
  674. tgt_sizes: Optional[torch.Tensor] = None,
  675. ) -> torch.Tensor:
  676. vision_embedding = self.vpm(
  677. pixel_values,
  678. patch_attention_mask=patch_attn_mask,
  679. tgt_sizes=tgt_sizes,
  680. ).last_hidden_state
  681. return vision_embedding
  682. def get_vision_hidden_states(self,
  683. data: MiniCPMVImageInputs) -> torch.Tensor:
  684. pixel_values = data["pixel_values"]
  685. tgt_sizes = data["tgt_sizes"]
  686. device = self.vpm.embeddings.position_embedding.weight.device
  687. dtype = self.vpm.embeddings.position_embedding.weight.dtype
  688. all_pixel_values_lst = [
  689. i.flatten(end_dim=1).permute(1, 0) for i in pixel_values
  690. ]
  691. max_patches = (tgt_sizes[:, 0] * tgt_sizes[:, 1]).max().item()
  692. assert isinstance(max_patches, int)
  693. all_pixel_values = torch.nn.utils.rnn.pad_sequence(
  694. all_pixel_values_lst, batch_first=True, padding_value=0.0)
  695. B, L, _ = all_pixel_values.shape
  696. all_pixel_values = all_pixel_values.permute(0, 2,
  697. 1).reshape(B, 3, -1, L)
  698. patch_attn_mask = torch.zeros((B, 1, max_patches),
  699. dtype=torch.bool,
  700. device=device)
  701. for i in range(B):
  702. patch_attn_mask[i, 0, :tgt_sizes[i][0] * tgt_sizes[i][1]] = True
  703. vision_embedding = self.vpm(
  704. all_pixel_values.type(dtype),
  705. patch_attention_mask=patch_attn_mask,
  706. tgt_sizes=tgt_sizes,
  707. ).last_hidden_state
  708. return self.resampler(vision_embedding, tgt_sizes)
  709. def is_default_weight_loading(self, name: str) -> bool:
  710. return "resampler" in name or "vpm" in name
  711. _SUPPORT_VERSION = {
  712. (2, 0): MiniCPMV2_0,
  713. (2, 5): MiniCPMV2_5,
  714. (2, 6): MiniCPMV2_6
  715. }
  716. @MULTIMODAL_REGISTRY.register_image_input_mapper()
  717. @MULTIMODAL_REGISTRY.register_max_image_tokens(get_max_minicpmv_image_tokens)
  718. @INPUT_REGISTRY.register_dummy_data(dummy_data_for_minicpmv)
  719. @INPUT_REGISTRY.register_input_processor(input_processor_for_minicpmv)
  720. class MiniCPMV(MiniCPMVBaseModel):
  721. """
  722. Different versions of MiniCPMV use different visual encoders and LLMs,
  723. which is not conducive to the current integration logic of LoRA and
  724. bitsandbytes in vLLM. Therefore, it is necessary to separate them.
  725. """
  726. def __new__(
  727. cls,
  728. config: PretrainedConfig,
  729. multimodal_config: MultiModalConfig,
  730. cache_config: Optional[CacheConfig] = None,
  731. quant_config: Optional[QuantizationConfig] = None,
  732. ):
  733. if not hasattr(config, "version"):
  734. if config.hidden_size == 2304 and config.query_num == 64:
  735. version = (2, 0)
  736. else:
  737. version = (2, 5)
  738. else:
  739. version = str(config.version).split(".")
  740. version = tuple([int(x) for x in version])
  741. # Dispatch class based on version
  742. instance_class = _SUPPORT_VERSION.get(version, None)
  743. if instance_class is None:
  744. raise ValueError(
  745. "Currently, MiniCPMV only supports versions 2.0, 2.5, and 2.6")
  746. return instance_class(config, multimodal_config, cache_config,
  747. quant_config)