minicpmv.py 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010
  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 functools import partial
  27. from typing import (Any, Callable, Iterable, List, Optional, Tuple, TypedDict,
  28. Union)
  29. import numpy as np
  30. import torch
  31. import torch.nn.functional as F
  32. import torch.types
  33. from loguru import logger
  34. from PIL import Image
  35. from torch import nn
  36. from torch.nn.init import trunc_normal_
  37. from transformers.configuration_utils import PretrainedConfig
  38. from aphrodite.attention import AttentionMetadata
  39. from aphrodite.common.config import CacheConfig, MultiModalConfig
  40. from aphrodite.common.sequence import (IntermediateTensors, SamplerOutput,
  41. SequenceData)
  42. from aphrodite.inputs import INPUT_REGISTRY, InputContext, LLMInputs
  43. from aphrodite.modeling.layers.linear import ReplicatedLinear
  44. from aphrodite.modeling.layers.logits_processor import LogitsProcessor
  45. from aphrodite.modeling.layers.sampler import Sampler
  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 SupportsVision
  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. cached_get_tokenizer)
  57. from aphrodite.quantization.base_config 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. def get_abs_pos(abs_pos: torch.Tensor, tgt_size: torch.Tensor):
  83. # abs_pos: L, C
  84. # tgt_size: (H, W)
  85. # return: M, C
  86. src_size = int(math.sqrt(abs_pos.size(0)))
  87. # tgt_size = int(math.sqrt(tgt_size))
  88. dtype = abs_pos.dtype
  89. return (F.interpolate(
  90. abs_pos.float().reshape(1, src_size, src_size, -1).permute(0, 3, 1, 2),
  91. size=(tgt_size[0], tgt_size[1]),
  92. mode="bicubic",
  93. align_corners=False,
  94. ).permute(0, 2, 3, 1).flatten(0, 2).to(dtype=dtype))
  95. # https://github.com/facebookresearch/mae/blob/efb2a8062c206524e35e47d04501ed4f544c0ae8/util/pos_embed.py#L20
  96. def get_2d_sincos_pos_embed(
  97. embed_dim: int,
  98. grid_size: Union[int, Tuple[int, int]],
  99. cls_token: bool = False,
  100. version: Tuple[int, int] = (2, 0),
  101. ):
  102. """
  103. grid_size: int of the grid height and width
  104. return:
  105. pos_embed: [grid_size*grid_size, embed_dim] or
  106. [1+grid_size*grid_size, embed_dim] (w/ or w/o cls_token)
  107. """
  108. if isinstance(grid_size, int):
  109. grid_h_size, grid_w_size = grid_size, grid_size
  110. else:
  111. grid_h_size, grid_w_size = grid_size[0], grid_size[1]
  112. grid_h = np.arange(grid_h_size, dtype=np.float32)
  113. grid_w = np.arange(grid_w_size, dtype=np.float32)
  114. grid = np.meshgrid(grid_w, grid_h) # here w goes first
  115. grid = np.stack(grid, axis=0)
  116. if version == (2, 0):
  117. grid = grid.reshape([2, 1, grid_h_size, grid_w_size])
  118. pos_embed = get_2d_sincos_pos_embed_from_grid(embed_dim, grid, version)
  119. if cls_token:
  120. pos_embed = np.concatenate([np.zeros([1, embed_dim]), pos_embed],
  121. axis=0)
  122. else:
  123. pos_embed = get_2d_sincos_pos_embed_from_grid(embed_dim, grid, version)
  124. return pos_embed
  125. def get_2d_sincos_pos_embed_from_grid(embed_dim: int,
  126. grid: np.ndarray,
  127. version: Tuple[int, int] = (2, 0)):
  128. assert embed_dim % 2 == 0
  129. # use half of dimensions to encode grid_h
  130. emb_h = get_1d_sincos_pos_embed_from_grid(
  131. embed_dim // 2, grid[0], version) # (H*W, D/2) or (H, W, D/2)
  132. emb_w = get_1d_sincos_pos_embed_from_grid(
  133. embed_dim // 2, grid[1], version) # (H*W, D/2) or (H, W, D/2)
  134. if version == (2, 0):
  135. emb = np.concatenate([emb_h, emb_w], axis=1) # (H*W, D)
  136. else:
  137. emb = np.concatenate([emb_h, emb_w], axis=-1) # (H, W, D)
  138. return emb
  139. def get_1d_sincos_pos_embed_from_grid(embed_dim: int,
  140. pos: np.ndarray,
  141. version: Tuple[int, int] = (2, 0)):
  142. """
  143. embed_dim: output dimension for each position
  144. pos: a list of positions to be encoded: size (M,) / (H, W)
  145. out: (M, D) / (H, W, D)
  146. """
  147. assert embed_dim % 2 == 0
  148. omega = np.arange(embed_dim // 2, dtype=np.float32)
  149. omega /= embed_dim / 2.0
  150. omega = 1.0 / 10000**omega # (D/2,)
  151. if version == (2, 0):
  152. pos = pos.reshape(-1) # (M,)
  153. out = np.einsum("m,d->md", pos, omega) # (M, D/2), outer product
  154. emb_sin = np.sin(out) # (M, D/2)
  155. emb_cos = np.cos(out) # (M, D/2)
  156. emb = np.concatenate([emb_sin, emb_cos], axis=1) # (M, D)
  157. else:
  158. out = np.einsum("hw,d->hwd", pos, omega) # (H, W, D/2), outer product
  159. emb_sin = np.sin(out) # (H, W, D/2)
  160. emb_cos = np.cos(out) # (H, W, D/2)
  161. emb = np.concatenate([emb_sin, emb_cos], axis=-1) # (H, W, D)
  162. return emb
  163. class BaseResampler(nn.Module):
  164. """
  165. A 2D perceiver-resampler network with one cross attention layers by
  166. (grid_size**2) learnable queries and 2d sincos pos_emb
  167. Outputs:
  168. A tensor with the shape of (grid_size**2, embed_dim)
  169. """
  170. def __init__(
  171. self,
  172. num_queries: int,
  173. embed_dim: int,
  174. num_heads: int,
  175. kv_dim: Optional[int] = None,
  176. norm_layer: Callable[[int], nn.LayerNorm] = DEFAULT_LN,
  177. ) -> None:
  178. super().__init__()
  179. self.num_queries = num_queries
  180. self.embed_dim = embed_dim
  181. self.num_heads = num_heads
  182. self.query = nn.Parameter(torch.zeros(self.num_queries, embed_dim))
  183. trunc_normal_(self.query, std=0.02)
  184. if kv_dim is not None and kv_dim != embed_dim:
  185. self.kv_proj = ReplicatedLinear(kv_dim, embed_dim, bias=False)
  186. else:
  187. # Maintain the same return value with ReplicatedLinear.forward
  188. self.kv_proj = lambda *args, **kwargs: (
  189. nn.Identity()(*args, **kwargs),
  190. None,
  191. )
  192. self.attn = nn.MultiheadAttention(embed_dim, num_heads)
  193. self.ln_q = norm_layer(embed_dim)
  194. self.ln_kv = norm_layer(embed_dim)
  195. self.ln_post = norm_layer(embed_dim)
  196. self.proj = nn.Parameter(
  197. (embed_dim**-0.5) * torch.randn(embed_dim, embed_dim))
  198. def _init_weights(self, m: nn.Module) -> None:
  199. if isinstance(m, nn.Linear):
  200. trunc_normal_(m.weight, std=0.02)
  201. if isinstance(m, nn.Linear) and m.bias is not None:
  202. nn.init.constant_(m.bias, 0)
  203. elif isinstance(m, nn.LayerNorm):
  204. nn.init.constant_(m.bias, 0)
  205. nn.init.constant_(m.weight, 1.0)
  206. def _repeat(self, query, N: int):
  207. return query.unsqueeze(1).repeat(1, N, 1)
  208. class Resampler2(BaseResampler):
  209. def __init__(
  210. self,
  211. grid_size: int,
  212. embed_dim: int,
  213. num_heads: int,
  214. kv_dim: Optional[int] = None,
  215. norm_layer: Callable[[int], nn.LayerNorm] = DEFAULT_LN,
  216. adaptive: bool = False,
  217. ) -> None:
  218. super().__init__(grid_size**2, embed_dim, num_heads, kv_dim,
  219. norm_layer)
  220. self.adaptive = adaptive
  221. pos_embed_arr = get_2d_sincos_pos_embed(embed_dim,
  222. grid_size,
  223. version=(2, 0))
  224. self.pos_embed = nn.Parameter(
  225. torch.from_numpy(pos_embed_arr).float()).requires_grad_(False)
  226. self.apply(self._init_weights)
  227. def forward(
  228. self,
  229. x: torch.Tensor,
  230. tgt_sizes: torch.Tensor,
  231. attn_mask: Optional[torch.Tensor] = None,
  232. ):
  233. if self.adaptive:
  234. pos_embed_arr = get_2d_sincos_pos_embed(self.embed_dim,
  235. tgt_sizes,
  236. version=(2, 0))
  237. pos_embed = torch.from_numpy(pos_embed_arr).to(device=x.device,
  238. dtype=x.dtype)
  239. else:
  240. pos_embed = get_abs_pos(self.pos_embed, tgt_sizes)
  241. x, _ = self.kv_proj(x)
  242. x = self.ln_kv(x).permute(1, 0, 2)
  243. N = x.shape[1]
  244. q = self.ln_q(self.query)
  245. out = self.attn(
  246. self._repeat(q, N) + self.pos_embed.unsqueeze(1),
  247. x + pos_embed.unsqueeze(1),
  248. x,
  249. attn_mask=attn_mask,
  250. )[0]
  251. x = out.permute(1, 0, 2)
  252. x = self.ln_post(x)
  253. x = x @ self.proj
  254. return x
  255. class Resampler2_5(BaseResampler):
  256. def __init__(
  257. self,
  258. num_queries: int,
  259. embed_dim: int,
  260. num_heads: int,
  261. kv_dim: Optional[int] = None,
  262. norm_layer: Callable[[int], nn.LayerNorm] = DEFAULT_LN,
  263. max_size: Tuple[int, int] = (70, 70),
  264. ) -> None:
  265. super().__init__(num_queries, embed_dim, num_heads, kv_dim, norm_layer)
  266. self.max_size = max_size
  267. self._set_2d_pos_cache(self.max_size)
  268. self.apply(self._init_weights)
  269. def _set_2d_pos_cache(self,
  270. max_size: Tuple[int, int],
  271. device: torch.types.Device = "cpu") -> None:
  272. pos_embed_arr = get_2d_sincos_pos_embed(self.embed_dim,
  273. max_size,
  274. version=(2, 5))
  275. pos_embed = torch.from_numpy(pos_embed_arr).float().to(device)
  276. self.register_buffer("pos_embed", pos_embed, persistent=False)
  277. def _adjust_pos_cache(self, tgt_sizes: torch.Tensor,
  278. device: torch.types.Device) -> None:
  279. max_h = tgt_sizes[:, 0].max().item()
  280. max_w = tgt_sizes[:, 1].max().item()
  281. assert isinstance(max_h, int) and isinstance(max_w, int)
  282. if max_h > self.max_size[0] or max_w > self.max_size[1]:
  283. self.max_size = (
  284. max(max_h, self.max_size[0]),
  285. max(max_w, self.max_size[1]),
  286. )
  287. self._set_2d_pos_cache(self.max_size, device)
  288. def forward(self, x: torch.Tensor,
  289. tgt_sizes: torch.Tensor) -> torch.Tensor:
  290. assert x.shape[0] == tgt_sizes.shape[0]
  291. bs = x.shape[0]
  292. device = x.device
  293. dtype = x.dtype
  294. patch_len = tgt_sizes[:, 0] * tgt_sizes[:, 1]
  295. self._adjust_pos_cache(tgt_sizes, device=device)
  296. max_patch_len = patch_len.max().item()
  297. assert isinstance(max_patch_len, int)
  298. key_padding_mask = torch.zeros((bs, max_patch_len),
  299. dtype=torch.bool,
  300. device=device)
  301. pos_embed = []
  302. for i in range(bs):
  303. tgt_h, tgt_w = tgt_sizes[i].tolist()
  304. pos_embed.append(self.pos_embed[:tgt_h, :tgt_w, :].reshape(
  305. (tgt_h * tgt_w, -1)).to(dtype)) # patches * D
  306. key_padding_mask[i, patch_len[i]:] = True
  307. pos_embed = torch.nn.utils.rnn.pad_sequence(pos_embed,
  308. batch_first=True,
  309. padding_value=0.0).permute(
  310. 1, 0,
  311. 2) # BLD => L * B * D
  312. x, _ = self.kv_proj(x) # B * L * D
  313. x = self.ln_kv(x).permute(1, 0, 2) # L * B * D
  314. q = self.ln_q(self.query) # Q * D
  315. out = self.attn(
  316. self._repeat(q, bs), # Q * B * D
  317. x + pos_embed, # L * B * D + L * B * D
  318. x,
  319. key_padding_mask=key_padding_mask,
  320. )[0]
  321. # out: Q * B * D
  322. x = out.permute(1, 0, 2) # B * Q * D
  323. x = self.ln_post(x)
  324. x = x @ self.proj
  325. return x
  326. def get_max_minicpmv_image_tokens(ctx: InputContext):
  327. hf_config = ctx.get_hf_config(PretrainedConfig)
  328. return getattr(hf_config, "query_num", 64)
  329. def dummy_seq_data_for_minicpmv(seq_len: int):
  330. token_ids = [0] * seq_len
  331. return SequenceData(token_ids)
  332. def dummy_image_for_minicpmv(hf_config: PretrainedConfig):
  333. width = height = hf_config.image_size
  334. image = Image.new("RGB", (width, height), color=0)
  335. return {"image": image}
  336. def dummy_data_for_minicpmv(ctx: InputContext, seq_len: int):
  337. hf_config = ctx.get_hf_config(PretrainedConfig)
  338. seq_data = dummy_seq_data_for_minicpmv(seq_len)
  339. mm_data = dummy_image_for_minicpmv(hf_config)
  340. return seq_data, mm_data
  341. def input_processor_for_minicpmv(ctx: InputContext, llm_inputs: LLMInputs):
  342. multi_modal_data = llm_inputs.get("multi_modal_data")
  343. if multi_modal_data is None or "image" not in multi_modal_data:
  344. return llm_inputs
  345. model_config = ctx.model_config
  346. tokenizer = cached_get_tokenizer(model_config.tokenizer,
  347. trust_remote_code=True)
  348. prompt = llm_inputs.get("prompt")
  349. if prompt is None:
  350. token_ids = llm_inputs.get("prompt_token_ids")
  351. prompt = tokenizer.decode(token_ids)
  352. image_processor = cached_get_image_processor(model_config.tokenizer)
  353. pattern = "(<image>./</image>)"
  354. image = multi_modal_data["image"]
  355. image_tags = re.findall(pattern, prompt)
  356. if len(image_tags) == 0:
  357. new_token_ids = token_ids
  358. new_prompt = prompt
  359. else:
  360. if len(image_tags) > 1:
  361. logger.warning("Multiple image input is not supported yet, "
  362. "so any extra image tokens will be treated "
  363. "as plain text.")
  364. text_chunks = prompt.split(pattern)
  365. new_prompt = (text_chunks[0] +
  366. image_processor.get_slice_image_placeholder(image.size) +
  367. "".join(text_chunks[1:]))
  368. new_token_ids = tokenizer.encode(new_prompt)
  369. llm_inputs = LLMInputs(
  370. prompt_token_ids=new_token_ids,
  371. prompt=new_prompt,
  372. multi_modal_data=multi_modal_data,
  373. )
  374. return llm_inputs
  375. class MiniCPMVBaseModel(nn.Module, SupportsVision):
  376. """
  377. The abstract class of MiniCPMV can only be inherited, but cannot be
  378. instantiated.
  379. """
  380. def __init__(
  381. self,
  382. config: PretrainedConfig,
  383. multimodal_config: MultiModalConfig,
  384. cache_config: Optional[CacheConfig] = None,
  385. quant_config: Optional[QuantizationConfig] = None,
  386. ):
  387. super().__init__()
  388. self.config = config
  389. self.multimodal_config = multimodal_config
  390. if not hasattr(self.config, "version"):
  391. if self.config.hidden_size == 2304 and self.config.query_num == 64:
  392. self.version = (2, 0)
  393. else:
  394. self.version = (2, 5)
  395. else:
  396. self.version = str(self.config.version).split(".")
  397. self.version = tuple([int(x) for x in self.version])
  398. self.llm = self.init_llm(config, cache_config, quant_config)
  399. self.vpm = self.init_vision_module()
  400. param_dtype = torch.get_default_dtype()
  401. self.vpm.to(dtype=param_dtype)
  402. self.vision_dim = (self.vpm.embed_dim if self.version == (2, 0) else
  403. self.vpm.embeddings.embed_dim)
  404. self.embed_dim = self.config.hidden_size
  405. self.resampler = self.init_resampler(self.embed_dim, self.vision_dim)
  406. self.resampler.to(device="cuda", dtype=param_dtype)
  407. self.lm_head = ParallelLMHead(config.vocab_size,
  408. config.hidden_size,
  409. quant_config=quant_config)
  410. self.logits_processor = LogitsProcessor(config.vocab_size)
  411. self.sampler = Sampler()
  412. def get_embedding(
  413. self,
  414. input_ids: torch.Tensor,
  415. image_inputs: Optional[MiniCPMVImageInputs],
  416. ) -> Tuple[torch.Tensor, torch.Tensor]:
  417. vlm_embedding: torch.Tensor = self.llm.embed_tokens(input_ids)
  418. if hasattr(self.config, "scale_emb"):
  419. vlm_embedding *= self.config.scale_emb
  420. if image_inputs is None: # No image
  421. vision_hidden_states = torch.tensor([], device=input_ids.device)
  422. else:
  423. vision_hidden_states = self.get_vision_hidden_states(image_inputs)
  424. # See NOTE in _parse_and_validate_inputs
  425. image_bounds = image_inputs["image_bounds"]
  426. if len(image_bounds) > 0:
  427. image_indices = torch.stack([
  428. torch.arange(start, end, dtype=torch.long)
  429. for start, end in image_bounds.tolist()
  430. ]).to(vlm_embedding.device)
  431. vlm_embedding.scatter_(
  432. 0,
  433. image_indices.view(-1, 1).repeat(1,
  434. vlm_embedding.shape[-1]),
  435. vision_hidden_states.view(-1,
  436. vision_hidden_states.shape[-1]),
  437. )
  438. return vlm_embedding, vision_hidden_states
  439. def _get_image_bounds(self, input_ids: torch.Tensor) -> torch.Tensor:
  440. tokenizer = cached_get_tokenizer(self.config._name_or_path,
  441. trust_remote_code=True)
  442. start_cond = input_ids == tokenizer.im_start_id
  443. end_cond = input_ids == tokenizer.im_end_id
  444. if hasattr(tokenizer, "slice_start_id"):
  445. start_cond |= (input_ids == tokenizer.slice_start_id)
  446. end_cond |= (input_ids == tokenizer.slice_end_id)
  447. image_start_tokens, = torch.where(start_cond)
  448. image_start_tokens += 1
  449. image_end_tokens, = torch.where(end_cond)
  450. valid_image_nums = max(len(image_start_tokens), len(image_end_tokens))
  451. if valid_image_nums == 0:
  452. return torch.zeros((0, 2), device=input_ids.device)
  453. return torch.hstack([
  454. image_start_tokens[:valid_image_nums].unsqueeze(-1),
  455. image_end_tokens[:valid_image_nums].unsqueeze(-1),
  456. ])
  457. def _parse_and_validate_inputs(
  458. self,
  459. input_ids: torch.Tensor,
  460. **kwargs: object,
  461. ) -> Optional[MiniCPMVImageInputs]:
  462. pixel_values = kwargs.pop("pixel_values", [])
  463. tgt_sizes = kwargs.pop("tgt_sizes", [])
  464. if not isinstance(pixel_values, (torch.Tensor, list)):
  465. raise ValueError("Incorrect type of pixel values. "
  466. f"Got type: {type(pixel_values)}")
  467. if not isinstance(tgt_sizes, (torch.Tensor, list)):
  468. raise ValueError("Incorrect type of target sizes. "
  469. f"Got type: {type(tgt_sizes)}")
  470. if len(pixel_values) != len(tgt_sizes):
  471. raise ValueError("Inconsistent batch lengths, found: "
  472. f"{len(pixel_values)} vs. {len(tgt_sizes)}")
  473. pixel_values_flat: List[torch.Tensor] = []
  474. tgt_sizes_flat: List[torch.Tensor] = []
  475. for b in range(len(pixel_values)):
  476. pixel_values_flat += pixel_values[b]
  477. tgt_sizes_flat += tgt_sizes[b]
  478. # NOTE: Input IDs does not contain image tokens during memory profiling,
  479. # so we allow it to be empty
  480. if len(pixel_values_flat) != len(tgt_sizes_flat):
  481. raise ValueError("Inconsistent flattened lengths, found: "
  482. f"{len(pixel_values_flat)} vs. "
  483. f"{len(tgt_sizes_flat)}")
  484. if len(pixel_values_flat) == 0:
  485. return None
  486. return MiniCPMVImageInputs(
  487. image_bounds=self._get_image_bounds(input_ids),
  488. pixel_values=pixel_values_flat,
  489. tgt_sizes=torch.stack(tgt_sizes_flat),
  490. )
  491. def forward(
  492. self,
  493. input_ids: torch.Tensor,
  494. positions: torch.Tensor,
  495. kv_caches: List[torch.Tensor],
  496. attn_metadata: AttentionMetadata,
  497. intermediate_tensors: Optional[IntermediateTensors] = None,
  498. **kwargs: Any,
  499. ) -> torch.Tensor:
  500. image_inputs = self._parse_and_validate_inputs(input_ids, **kwargs)
  501. vlm_embeddings, _ = self.get_embedding(input_ids, image_inputs)
  502. output = self.llm(
  503. input_ids=None,
  504. positions=positions,
  505. kv_caches=kv_caches,
  506. attn_metadata=attn_metadata,
  507. intermediate_tensors=intermediate_tensors,
  508. inputs_embeds=vlm_embeddings,
  509. )
  510. return output
  511. def compute_logits(self, hidden_states: torch.Tensor,
  512. sampling_metadata: SamplingMetadata) -> torch.Tensor:
  513. logits = self.logits_processor(self.lm_head, hidden_states,
  514. sampling_metadata)
  515. return logits
  516. def sample(
  517. self,
  518. logits: torch.Tensor,
  519. sampling_metadata: SamplingMetadata,
  520. ) -> Optional[SamplerOutput]:
  521. next_tokens = self.sampler(logits, sampling_metadata)
  522. return next_tokens
  523. def load_weights(self, weights: Iterable[Tuple[str, torch.Tensor]]):
  524. stacked_params_mapping = [
  525. # (param_name, shard_name, shard_id)
  526. ("qkv_proj", "q_proj", "q"),
  527. ("qkv_proj", "k_proj", "k"),
  528. ("qkv_proj", "v_proj", "v"),
  529. ("gate_up_proj", "gate_proj", 0),
  530. ("gate_up_proj", "up_proj", 1),
  531. ]
  532. params_dict = dict(self.named_parameters())
  533. for name, loaded_weight in weights:
  534. for key_to_modify, new_key in _KEYS_TO_MODIFY_MAPPING.items():
  535. if key_to_modify in name:
  536. name = name.replace(key_to_modify, new_key)
  537. if "rotary_emb.inv_freq" in name:
  538. continue
  539. if ("rotary_emb.cos_cached" in name
  540. or "rotary_emb.sin_cached" in name):
  541. # Models trained using ColossalAI may include these tensors in
  542. # the checkpoint. Skip them.
  543. continue
  544. use_default_weight_loading = False
  545. if self.is_default_weight_loading(name):
  546. use_default_weight_loading = True
  547. else:
  548. for param_name, weight_name, shard_id in stacked_params_mapping:
  549. if weight_name not in name:
  550. continue
  551. param = params_dict[name.replace(weight_name, param_name)]
  552. weight_loader = param.weight_loader
  553. weight_loader(param, loaded_weight, shard_id)
  554. break
  555. else:
  556. use_default_weight_loading = True
  557. if use_default_weight_loading:
  558. param = params_dict[name]
  559. weight_loader = getattr(param, "weight_loader",
  560. default_weight_loader)
  561. weight_loader(param, loaded_weight)
  562. def init_llm(
  563. self,
  564. config: PretrainedConfig,
  565. cache_config: Optional[CacheConfig] = None,
  566. quant_config: Optional[QuantizationConfig] = None,
  567. ) -> nn.Module:
  568. raise NotImplementedError
  569. def init_vision_module(self) -> nn.Module:
  570. raise NotImplementedError
  571. def init_resampler(self, embed_dim: int, vision_dim: int) -> nn.Module:
  572. raise NotImplementedError
  573. def get_vision_embedding(
  574. self,
  575. pixel_values: List[torch.Tensor],
  576. patch_attn_mask: Optional[torch.Tensor] = None,
  577. tgt_sizes: Optional[torch.Tensor] = None,
  578. ) -> torch.Tensor:
  579. raise NotImplementedError
  580. def get_vision_hidden_states(self,
  581. data: MiniCPMVImageInputs) -> torch.Tensor:
  582. raise NotImplementedError
  583. def is_default_weight_loading(self, name: str) -> bool:
  584. raise NotImplementedError
  585. class MiniCPMV2(MiniCPMVBaseModel):
  586. def __init__(
  587. self,
  588. config: PretrainedConfig,
  589. multimodal_config: MultiModalConfig,
  590. cache_config: Optional[CacheConfig] = None,
  591. quant_config: Optional[QuantizationConfig] = None,
  592. ):
  593. super().__init__(config, multimodal_config, cache_config, quant_config)
  594. assert self.version == (2, 0)
  595. def init_llm(
  596. self,
  597. config: PretrainedConfig,
  598. cache_config: Optional[CacheConfig] = None,
  599. quant_config: Optional[QuantizationConfig] = None,
  600. ) -> nn.Module:
  601. return MiniCPMModel(config,
  602. cache_config=cache_config,
  603. quant_config=quant_config)
  604. def init_vision_module(self) -> nn.Module:
  605. # TODO :refactor this vision model
  606. try:
  607. import timm
  608. except ImportError:
  609. raise ImportError("Please install timm==0.9.10") from ImportError
  610. with set_default_torch_dtype(torch.float16):
  611. model = timm.create_model(
  612. "vit_so400m_patch14_siglip_384.webli",
  613. pretrained=False,
  614. num_classes=0,
  615. dynamic_img_size=True,
  616. dynamic_img_pad=True,
  617. )
  618. if (isinstance(model, timm.models.VisionTransformer)
  619. and model.attn_pool is not None):
  620. model.attn_pool = torch.nn.Identity()
  621. if self.config.drop_vision_last_layer:
  622. model.blocks = model.blocks[:-1]
  623. return model
  624. def init_resampler(self, embed_dim: int, vision_dim: int) -> nn.Module:
  625. with set_default_torch_dtype(torch.float16):
  626. resampler = Resampler2(
  627. embed_dim=embed_dim,
  628. num_heads=embed_dim // 128,
  629. grid_size=int(math.sqrt(self.config.query_num)),
  630. kv_dim=vision_dim,
  631. adaptive=True,
  632. )
  633. return resampler
  634. def get_vision_embedding(
  635. self,
  636. pixel_values: List[torch.Tensor],
  637. patch_attn_mask: Optional[torch.Tensor] = None,
  638. tgt_sizes: Optional[torch.Tensor] = None,
  639. ) -> torch.Tensor:
  640. res = []
  641. dtype = self.vpm.pos_embed.data.dtype
  642. for pixel_value in pixel_values:
  643. H, W = pixel_value[0].shape[-2:]
  644. tgt_size = (
  645. math.ceil(H / self.vpm.patch_embed.patch_size[0]),
  646. math.ceil(W / self.vpm.patch_embed.patch_size[0]),
  647. )
  648. vision_embedding = self.vpm.forward_features(
  649. pixel_value.unsqueeze(0).type(dtype))
  650. if (hasattr(self.vpm, "num_prefix_tokens")
  651. and self.vpm.num_prefix_tokens > 0):
  652. vision_embedding = vision_embedding[:, self.vpm.
  653. num_prefix_tokens:]
  654. res.append(self.resampler(vision_embedding, tgt_size))
  655. return torch.vstack(res)
  656. def get_vision_hidden_states(self,
  657. data: MiniCPMVImageInputs) -> torch.Tensor:
  658. pixel_values = data["pixel_values"]
  659. return self.get_vision_embedding(pixel_values)
  660. def is_default_weight_loading(self, name: str) -> bool:
  661. return "resampler" in name or "vpm" in name
  662. class MiniCPMV2_5(MiniCPMVBaseModel):
  663. def __init__(
  664. self,
  665. config: PretrainedConfig,
  666. multimodal_config: MultiModalConfig,
  667. cache_config: Optional[CacheConfig] = None,
  668. quant_config: Optional[QuantizationConfig] = None,
  669. ):
  670. super().__init__(config, multimodal_config, cache_config, quant_config)
  671. assert self.version == (2, 5)
  672. def init_llm(
  673. self,
  674. config: PretrainedConfig,
  675. cache_config: Optional[CacheConfig] = None,
  676. quant_config: Optional[QuantizationConfig] = None,
  677. ) -> nn.Module:
  678. return LlamaModel(config,
  679. cache_config=cache_config,
  680. quant_config=quant_config)
  681. def init_vision_module(self) -> nn.Module:
  682. model = Idefics2VisionTransformer(self.config.vision_config)
  683. if self.config.drop_vision_last_layer:
  684. model.encoder.layers = model.encoder.layers[:-1]
  685. return model
  686. def init_resampler(self, embed_dim: int, vision_dim: int) -> nn.Module:
  687. with set_default_torch_dtype(torch.float16):
  688. resampler = Resampler2_5(
  689. num_queries=self.config.query_num,
  690. embed_dim=embed_dim,
  691. num_heads=embed_dim // 128,
  692. kv_dim=vision_dim,
  693. )
  694. return resampler
  695. def get_vision_embedding(
  696. self,
  697. pixel_values: List[torch.Tensor],
  698. patch_attn_mask: Optional[torch.Tensor] = None,
  699. tgt_sizes: Optional[torch.Tensor] = None,
  700. ) -> torch.Tensor:
  701. vision_embedding = self.vpm(pixel_values,
  702. patch_attention_mask=patch_attn_mask)
  703. vision_embedding = self.resampler(vision_embedding, tgt_sizes)
  704. return vision_embedding
  705. def get_vision_hidden_states(self,
  706. data: MiniCPMVImageInputs) -> torch.Tensor:
  707. pixel_values = data["pixel_values"]
  708. tgt_sizes = data["tgt_sizes"]
  709. device = self.vpm.embeddings.position_embedding.weight.device
  710. dtype = self.vpm.embeddings.position_embedding.weight.dtype
  711. all_pixel_values_lst = [
  712. i.flatten(end_dim=1).permute(1, 0) for i in pixel_values
  713. ]
  714. max_patches = (tgt_sizes[:, 0] * tgt_sizes[:, 1]).max().item()
  715. assert isinstance(max_patches, int)
  716. all_pixel_values = torch.nn.utils.rnn.pad_sequence(
  717. all_pixel_values_lst, batch_first=True, padding_value=0.0)
  718. B, L, _ = all_pixel_values.shape
  719. all_pixel_values = all_pixel_values.permute(0, 2,
  720. 1).reshape(B, 3, -1, L)
  721. patch_attn_mask = torch.zeros((B, 1, max_patches),
  722. dtype=torch.bool,
  723. device=device)
  724. for i in range(B):
  725. patch_attn_mask[i, :tgt_sizes[i][0] * tgt_sizes[i][1]] = True
  726. return self.get_vision_embedding(all_pixel_values.type(dtype),
  727. patch_attn_mask, tgt_sizes)
  728. def is_default_weight_loading(self, name: str) -> bool:
  729. return "resampler" in name
  730. # NOTE: Currently, information about this model is unavailable. We are
  731. # temporarily using `MiniCPMVQwen2` as it's name. The name may need
  732. # to be modified in the future.
  733. class MiniCPMVQwen2(MiniCPMVBaseModel):
  734. def __init__(
  735. self,
  736. config: PretrainedConfig,
  737. multimodal_config: MultiModalConfig,
  738. cache_config: Optional[CacheConfig] = None,
  739. quant_config: Optional[QuantizationConfig] = None,
  740. ):
  741. super().__init__(config, multimodal_config, cache_config, quant_config)
  742. def init_llm(
  743. self,
  744. config: PretrainedConfig,
  745. cache_config: Optional[CacheConfig] = None,
  746. quant_config: Optional[QuantizationConfig] = None,
  747. ) -> nn.Module:
  748. return Qwen2Model(config,
  749. cache_config=cache_config,
  750. quant_config=quant_config)
  751. def init_vision_module(self) -> nn.Module:
  752. # A custom version of SiglipVisionTransformer, won't work with TP
  753. from aphrodite.modeling.models.na_vit import SiglipVisionTransformer
  754. if self.config._attn_implementation == "flash_attention_2":
  755. self.config.vision_config._attn_implementation = "flash_attention_2"
  756. else:
  757. # not support sdpa
  758. self.config.vision_config._attn_implementation = "eager"
  759. model = SiglipVisionTransformer(self.config.vision_config)
  760. if self.config.drop_vision_last_layer:
  761. model.encoder.layers = model.encoder.layers[:-1]
  762. return model
  763. def init_resampler(self, embed_dim: int, vision_dim: int) -> nn.Module:
  764. with set_default_torch_dtype(torch.float16):
  765. resampler = Resampler2_5(
  766. num_queries=self.config.query_num,
  767. embed_dim=embed_dim,
  768. num_heads=embed_dim // 128,
  769. kv_dim=vision_dim,
  770. )
  771. return resampler
  772. def get_vision_embedding(
  773. self,
  774. pixel_values: List[torch.Tensor],
  775. patch_attn_mask: Optional[torch.Tensor] = None,
  776. tgt_sizes: Optional[torch.Tensor] = None,
  777. ) -> torch.Tensor:
  778. vision_embedding = self.vpm(
  779. pixel_values,
  780. patch_attention_mask=patch_attn_mask,
  781. tgt_sizes=tgt_sizes,
  782. ).last_hidden_state
  783. return vision_embedding
  784. def get_vision_hidden_states(self,
  785. data: MiniCPMVImageInputs) -> torch.Tensor:
  786. pixel_values = data["pixel_values"]
  787. tgt_sizes = data["tgt_sizes"]
  788. device = self.vpm.embeddings.position_embedding.weight.device
  789. dtype = self.vpm.embeddings.position_embedding.weight.dtype
  790. all_pixel_values_lst = [
  791. i.flatten(end_dim=1).permute(1, 0) for i in pixel_values
  792. ]
  793. max_patches = (tgt_sizes[:, 0] * tgt_sizes[:, 1]).max().item()
  794. assert isinstance(max_patches, int)
  795. all_pixel_values = torch.nn.utils.rnn.pad_sequence(
  796. all_pixel_values_lst, batch_first=True, padding_value=0.0)
  797. B, L, _ = all_pixel_values.shape
  798. all_pixel_values = all_pixel_values.permute(0, 2,
  799. 1).reshape(B, 3, -1, L)
  800. patch_attn_mask = torch.zeros((B, 1, max_patches),
  801. dtype=torch.bool,
  802. device=device)
  803. for i in range(B):
  804. patch_attn_mask[i, 0, :tgt_sizes[i][0] * tgt_sizes[i][1]] = True
  805. vision_embedding = self.vpm(
  806. all_pixel_values.type(dtype),
  807. patch_attention_mask=patch_attn_mask,
  808. tgt_sizes=tgt_sizes,
  809. ).last_hidden_state
  810. return self.resampler(vision_embedding, tgt_sizes)
  811. def is_default_weight_loading(self, name: str) -> bool:
  812. return "resampler" in name or "vpm" in name
  813. @MULTIMODAL_REGISTRY.register_image_input_mapper()
  814. @MULTIMODAL_REGISTRY.register_max_image_tokens(get_max_minicpmv_image_tokens)
  815. @INPUT_REGISTRY.register_dummy_data(dummy_data_for_minicpmv)
  816. @INPUT_REGISTRY.register_input_processor(input_processor_for_minicpmv)
  817. class MiniCPMV(MiniCPMVBaseModel):
  818. """
  819. Different versions of MiniCPMV use different visual encoders and LLMs,
  820. which is not conducive to the current integration logic of LoRA and
  821. bitsandbytes in aphrodite. Therefore, it is necessary to separate them.
  822. """
  823. def __new__(
  824. cls,
  825. config: PretrainedConfig,
  826. multimodal_config: MultiModalConfig,
  827. cache_config: Optional[CacheConfig] = None,
  828. quant_config: Optional[QuantizationConfig] = None,
  829. ):
  830. if not hasattr(config, "version"):
  831. if config.hidden_size == 2304 and config.query_num == 64:
  832. version = (2, 0)
  833. else:
  834. version = (2, 5)
  835. else:
  836. version = str(config.version).split(".")
  837. version = tuple([int(x) for x in version])
  838. # Dispatch class based on version
  839. if version == (2, 0):
  840. instance_class = MiniCPMV2
  841. elif version == (2, 5):
  842. instance_class = MiniCPMV2_5
  843. else:
  844. instance_class = MiniCPMVQwen2
  845. return instance_class(config, multimodal_config, cache_config,
  846. quant_config)