minicpmv.py 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031
  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, Mapping, Optional, Tuple,
  28. TypedDict, Union)
  29. import numpy as np
  30. import torch
  31. import torch.nn.functional as F
  32. import torch.types
  33. from PIL import Image
  34. from torch import nn
  35. from torch.nn.init import trunc_normal_
  36. from transformers.configuration_utils import PretrainedConfig
  37. from aphrodite.attention import AttentionMetadata
  38. from aphrodite.common.config import CacheConfig, MultiModalConfig
  39. from aphrodite.common.sequence import (IntermediateTensors, SamplerOutput,
  40. SequenceData)
  41. from aphrodite.common.utils import progress_bar
  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 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. 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_version_by_config(config: PretrainedConfig) -> Tuple[int, ...]:
  327. version_float = getattr(config, "version", None)
  328. # The old configs do not include version number
  329. # TODO: Remove this after the HF repos are updated
  330. if version_float is None:
  331. if config.hidden_size == 2304 and config.query_num == 64:
  332. return (2, 0)
  333. return (2, 5)
  334. version_str = str(version_float)
  335. return tuple(int(x) for x in version_str.split("."))
  336. def get_max_minicpmv_image_tokens(ctx: InputContext):
  337. hf_config = ctx.get_hf_config(PretrainedConfig)
  338. return getattr(hf_config, "query_num", 64)
  339. def dummy_seq_data_for_minicpmv(seq_len: int, num_images: int):
  340. token_ids = [0] * seq_len
  341. return SequenceData(token_ids)
  342. def dummy_image_for_minicpmv(hf_config: PretrainedConfig, num_images: int):
  343. width = height = hf_config.image_size
  344. image = Image.new("RGB", (width, height), color=0)
  345. return {"image": image if num_images == 1 else [image] * num_images}
  346. def dummy_data_for_minicpmv(ctx: InputContext, seq_len: int,
  347. mm_counts: Mapping[str, int]):
  348. hf_config = ctx.get_hf_config()
  349. num_images = mm_counts["image"]
  350. seq_data = dummy_seq_data_for_minicpmv(seq_len, num_images)
  351. mm_data = dummy_image_for_minicpmv(hf_config, num_images)
  352. return seq_data, mm_data
  353. def input_processor_for_minicpmv(ctx: InputContext, llm_inputs: LLMInputs):
  354. multi_modal_data = llm_inputs.get("multi_modal_data")
  355. if multi_modal_data is None or "image" not in multi_modal_data:
  356. return llm_inputs
  357. model_config = ctx.model_config
  358. version = get_version_by_config(model_config.hf_config)
  359. tokenizer = cached_get_tokenizer(model_config.tokenizer,
  360. trust_remote_code=True)
  361. image_processor = cached_get_image_processor(model_config.tokenizer)
  362. def get_placeholder(image_size: Tuple[int, int], num_image: int):
  363. if version == (2, 0) or version == (2, 5):
  364. return image_processor. \
  365. get_slice_image_placeholder(image_size)
  366. return image_processor. \
  367. get_slice_image_placeholder(image_size, num_image)
  368. prompt = llm_inputs.get("prompt")
  369. if prompt is None:
  370. token_ids = llm_inputs.get("prompt_token_ids")
  371. prompt = tokenizer.decode(token_ids)
  372. pattern = "(<image>./</image>)"
  373. images = multi_modal_data["image"]
  374. if isinstance(images, Image.Image):
  375. images = [images]
  376. image_tags = re.findall(pattern, prompt)
  377. if len(image_tags) == 0:
  378. new_token_ids = token_ids
  379. new_prompt = prompt
  380. else:
  381. text_chunks = prompt.split(pattern)
  382. new_prompt_chunks: List[str] = []
  383. for i in range(len(images)):
  384. new_prompt_chunks += [
  385. text_chunks[i],
  386. get_placeholder(images[i].size, i)
  387. ]
  388. new_prompt_chunks.append(text_chunks[-1])
  389. new_prompt = "".join(new_prompt_chunks)
  390. new_token_ids = tokenizer.encode(new_prompt)
  391. llm_inputs = LLMInputs(
  392. prompt_token_ids=new_token_ids,
  393. prompt=new_prompt,
  394. multi_modal_data=multi_modal_data,
  395. )
  396. return llm_inputs
  397. class MiniCPMVBaseModel(nn.Module, SupportsMultiModal):
  398. """
  399. The abstract class of MiniCPMV can only be inherited, but cannot be
  400. instantiated.
  401. """
  402. def __init__(
  403. self,
  404. config: PretrainedConfig,
  405. multimodal_config: MultiModalConfig,
  406. cache_config: Optional[CacheConfig] = None,
  407. quant_config: Optional[QuantizationConfig] = None,
  408. ):
  409. super().__init__()
  410. self.config = config
  411. self.multimodal_config = multimodal_config
  412. self.version = get_version_by_config(self.config)
  413. self.llm = self.init_llm(config, cache_config, quant_config)
  414. self.vpm = self.init_vision_module()
  415. param_dtype = torch.get_default_dtype()
  416. self.vpm.to(dtype=param_dtype)
  417. self.vision_dim = (self.vpm.embed_dim if self.version == (2, 0) else
  418. self.vpm.embeddings.embed_dim)
  419. self.embed_dim = self.config.hidden_size
  420. self.resampler = self.init_resampler(self.embed_dim, self.vision_dim)
  421. self.resampler.to(device="cuda", dtype=param_dtype)
  422. self.lm_head = ParallelLMHead(config.vocab_size,
  423. config.hidden_size,
  424. quant_config=quant_config)
  425. self.logits_processor = LogitsProcessor(config.vocab_size)
  426. self.sampler = Sampler()
  427. def get_embedding(
  428. self,
  429. input_ids: torch.Tensor,
  430. image_inputs: Optional[MiniCPMVImageInputs],
  431. ) -> Tuple[torch.Tensor, torch.Tensor]:
  432. vlm_embedding: torch.Tensor = self.llm.embed_tokens(input_ids)
  433. if hasattr(self.config, "scale_emb"):
  434. vlm_embedding *= self.config.scale_emb
  435. if image_inputs is None: # No image
  436. vision_hidden_states = torch.tensor([], device=input_ids.device)
  437. else:
  438. vision_hidden_states = self.get_vision_hidden_states(image_inputs)
  439. # See NOTE in _parse_and_validate_inputs
  440. image_bounds = image_inputs["image_bounds"]
  441. if len(image_bounds) > 0:
  442. image_indices = torch.stack([
  443. torch.arange(start, end, dtype=torch.long)
  444. for start, end in image_bounds.tolist()
  445. ]).to(vlm_embedding.device)
  446. vlm_embedding.scatter_(
  447. 0,
  448. image_indices.view(-1, 1).repeat(1,
  449. vlm_embedding.shape[-1]),
  450. vision_hidden_states.view(-1,
  451. vision_hidden_states.shape[-1]),
  452. )
  453. return vlm_embedding, vision_hidden_states
  454. def _get_image_bounds(self, input_ids: torch.Tensor) -> torch.Tensor:
  455. tokenizer = cached_get_tokenizer(self.config._name_or_path,
  456. trust_remote_code=True)
  457. start_cond = input_ids == tokenizer.im_start_id
  458. end_cond = input_ids == tokenizer.im_end_id
  459. if hasattr(tokenizer, "slice_start_id"):
  460. start_cond |= (input_ids == tokenizer.slice_start_id)
  461. end_cond |= (input_ids == tokenizer.slice_end_id)
  462. image_start_tokens, = torch.where(start_cond)
  463. image_start_tokens += 1
  464. image_end_tokens, = torch.where(end_cond)
  465. valid_image_nums = max(len(image_start_tokens), len(image_end_tokens))
  466. if valid_image_nums == 0:
  467. return torch.zeros((0, 2), device=input_ids.device)
  468. return torch.hstack([
  469. image_start_tokens[:valid_image_nums].unsqueeze(-1),
  470. image_end_tokens[:valid_image_nums].unsqueeze(-1),
  471. ])
  472. def _parse_and_validate_inputs(
  473. self,
  474. input_ids: torch.Tensor,
  475. **kwargs: object,
  476. ) -> Optional[MiniCPMVImageInputs]:
  477. pixel_values = kwargs.pop("pixel_values", [])
  478. tgt_sizes = kwargs.pop("tgt_sizes", [])
  479. if not isinstance(pixel_values, (torch.Tensor, list)):
  480. raise ValueError("Incorrect type of pixel values. "
  481. f"Got type: {type(pixel_values)}")
  482. if not isinstance(tgt_sizes, (torch.Tensor, list)):
  483. raise ValueError("Incorrect type of target sizes. "
  484. f"Got type: {type(tgt_sizes)}")
  485. if len(pixel_values) != len(tgt_sizes):
  486. raise ValueError("Inconsistent batch lengths, found: "
  487. f"{len(pixel_values)} vs. {len(tgt_sizes)}")
  488. pixel_values_flat: List[torch.Tensor] = []
  489. tgt_sizes_flat: List[torch.Tensor] = []
  490. for b in range(len(pixel_values)):
  491. pixel_values_flat += pixel_values[b]
  492. tgt_sizes_flat += tgt_sizes[b]
  493. # NOTE: Input IDs does not contain image tokens during memory profiling,
  494. # so we allow it to be empty
  495. if len(pixel_values_flat) != len(tgt_sizes_flat):
  496. raise ValueError("Inconsistent flattened lengths, found: "
  497. f"{len(pixel_values_flat)} vs. "
  498. f"{len(tgt_sizes_flat)}")
  499. if len(pixel_values_flat) == 0:
  500. return None
  501. return MiniCPMVImageInputs(
  502. image_bounds=self._get_image_bounds(input_ids),
  503. pixel_values=pixel_values_flat,
  504. tgt_sizes=torch.stack(tgt_sizes_flat),
  505. )
  506. def forward(
  507. self,
  508. input_ids: torch.Tensor,
  509. positions: torch.Tensor,
  510. kv_caches: List[torch.Tensor],
  511. attn_metadata: AttentionMetadata,
  512. intermediate_tensors: Optional[IntermediateTensors] = None,
  513. **kwargs: Any,
  514. ) -> torch.Tensor:
  515. image_inputs = self._parse_and_validate_inputs(input_ids, **kwargs)
  516. vlm_embeddings, _ = self.get_embedding(input_ids, image_inputs)
  517. output = self.llm(
  518. input_ids=None,
  519. positions=positions,
  520. kv_caches=kv_caches,
  521. attn_metadata=attn_metadata,
  522. intermediate_tensors=intermediate_tensors,
  523. inputs_embeds=vlm_embeddings,
  524. )
  525. return output
  526. def compute_logits(
  527. self,
  528. hidden_states: torch.Tensor,
  529. sampling_metadata: SamplingMetadata,
  530. ) -> Optional[torch.Tensor]:
  531. logits = self.logits_processor(self.lm_head, hidden_states,
  532. sampling_metadata)
  533. return logits
  534. def sample(
  535. self,
  536. logits: torch.Tensor,
  537. sampling_metadata: SamplingMetadata,
  538. ) -> Optional[SamplerOutput]:
  539. next_tokens = self.sampler(logits, sampling_metadata)
  540. return next_tokens
  541. def load_weights(self, weights: Iterable[Tuple[str, torch.Tensor]]):
  542. stacked_params_mapping = [
  543. # (param_name, shard_name, shard_id)
  544. ("qkv_proj", "q_proj", "q"),
  545. ("qkv_proj", "k_proj", "k"),
  546. ("qkv_proj", "v_proj", "v"),
  547. ("gate_up_proj", "gate_proj", 0),
  548. ("gate_up_proj", "up_proj", 1),
  549. ]
  550. params_dict = dict(self.named_parameters())
  551. weights_list = list(weights)
  552. for name, loaded_weight in progress_bar(weights_list,
  553. desc="Loading modules..."):
  554. for key_to_modify, new_key in _KEYS_TO_MODIFY_MAPPING.items():
  555. if key_to_modify in name:
  556. name = name.replace(key_to_modify, new_key)
  557. if "rotary_emb.inv_freq" in name:
  558. continue
  559. if ("rotary_emb.cos_cached" in name
  560. or "rotary_emb.sin_cached" in name):
  561. # Models trained using ColossalAI may include these tensors in
  562. # the checkpoint. Skip them.
  563. continue
  564. use_default_weight_loading = False
  565. if self.is_default_weight_loading(name):
  566. use_default_weight_loading = True
  567. else:
  568. for param_name, weight_name, shard_id in stacked_params_mapping:
  569. if weight_name not in name:
  570. continue
  571. param = params_dict[name.replace(weight_name, param_name)]
  572. weight_loader = param.weight_loader
  573. weight_loader(param, loaded_weight, shard_id)
  574. break
  575. else:
  576. use_default_weight_loading = True
  577. if use_default_weight_loading:
  578. param = params_dict[name]
  579. weight_loader = getattr(param, "weight_loader",
  580. default_weight_loader)
  581. weight_loader(param, loaded_weight)
  582. def init_llm(
  583. self,
  584. config: PretrainedConfig,
  585. cache_config: Optional[CacheConfig] = None,
  586. quant_config: Optional[QuantizationConfig] = None,
  587. ) -> nn.Module:
  588. raise NotImplementedError
  589. def init_vision_module(self) -> nn.Module:
  590. raise NotImplementedError
  591. def init_resampler(self, embed_dim: int, vision_dim: int) -> nn.Module:
  592. raise NotImplementedError
  593. def get_vision_embedding(
  594. self,
  595. pixel_values: List[torch.Tensor],
  596. patch_attn_mask: Optional[torch.Tensor] = None,
  597. tgt_sizes: Optional[torch.Tensor] = None,
  598. ) -> torch.Tensor:
  599. raise NotImplementedError
  600. def get_vision_hidden_states(self,
  601. data: MiniCPMVImageInputs) -> torch.Tensor:
  602. raise NotImplementedError
  603. def is_default_weight_loading(self, name: str) -> bool:
  604. raise NotImplementedError
  605. class MiniCPMV2(MiniCPMVBaseModel):
  606. def __init__(
  607. self,
  608. config: PretrainedConfig,
  609. multimodal_config: MultiModalConfig,
  610. cache_config: Optional[CacheConfig] = None,
  611. quant_config: Optional[QuantizationConfig] = None,
  612. ):
  613. super().__init__(config, multimodal_config, cache_config, quant_config)
  614. assert self.version == (2, 0)
  615. def init_llm(
  616. self,
  617. config: PretrainedConfig,
  618. cache_config: Optional[CacheConfig] = None,
  619. quant_config: Optional[QuantizationConfig] = None,
  620. ) -> nn.Module:
  621. return MiniCPMModel(config,
  622. cache_config=cache_config,
  623. quant_config=quant_config)
  624. def init_vision_module(self) -> nn.Module:
  625. # TODO :refactor this vision model
  626. try:
  627. import timm
  628. except ImportError:
  629. raise ImportError("Please install timm==0.9.10") from ImportError
  630. with set_default_torch_dtype(torch.float16):
  631. model = timm.create_model(
  632. "vit_so400m_patch14_siglip_384.webli",
  633. pretrained=False,
  634. num_classes=0,
  635. dynamic_img_size=True,
  636. dynamic_img_pad=True,
  637. )
  638. if (isinstance(model, timm.models.VisionTransformer)
  639. and model.attn_pool is not None):
  640. model.attn_pool = torch.nn.Identity()
  641. if self.config.drop_vision_last_layer:
  642. model.blocks = model.blocks[:-1]
  643. return model
  644. def init_resampler(self, embed_dim: int, vision_dim: int) -> nn.Module:
  645. with set_default_torch_dtype(torch.float16):
  646. resampler = Resampler2(
  647. embed_dim=embed_dim,
  648. num_heads=embed_dim // 128,
  649. grid_size=int(math.sqrt(self.config.query_num)),
  650. kv_dim=vision_dim,
  651. adaptive=True,
  652. )
  653. return resampler
  654. def get_vision_embedding(
  655. self,
  656. pixel_values: List[torch.Tensor],
  657. patch_attn_mask: Optional[torch.Tensor] = None,
  658. tgt_sizes: Optional[torch.Tensor] = None,
  659. ) -> torch.Tensor:
  660. res = []
  661. dtype = self.vpm.pos_embed.data.dtype
  662. for pixel_value in pixel_values:
  663. H, W = pixel_value[0].shape[-2:]
  664. tgt_size = (
  665. math.ceil(H / self.vpm.patch_embed.patch_size[0]),
  666. math.ceil(W / self.vpm.patch_embed.patch_size[0]),
  667. )
  668. vision_embedding = self.vpm.forward_features(
  669. pixel_value.unsqueeze(0).type(dtype))
  670. if (hasattr(self.vpm, "num_prefix_tokens")
  671. and self.vpm.num_prefix_tokens > 0):
  672. vision_embedding = vision_embedding[:, self.vpm.
  673. num_prefix_tokens:]
  674. res.append(self.resampler(vision_embedding, tgt_size))
  675. return torch.vstack(res)
  676. def get_vision_hidden_states(self,
  677. data: MiniCPMVImageInputs) -> torch.Tensor:
  678. pixel_values = data["pixel_values"]
  679. return self.get_vision_embedding(pixel_values)
  680. def is_default_weight_loading(self, name: str) -> bool:
  681. return "resampler" in name or "vpm" in name
  682. class MiniCPMV2_5(MiniCPMVBaseModel):
  683. def __init__(
  684. self,
  685. config: PretrainedConfig,
  686. multimodal_config: MultiModalConfig,
  687. cache_config: Optional[CacheConfig] = None,
  688. quant_config: Optional[QuantizationConfig] = None,
  689. ):
  690. super().__init__(config, multimodal_config, cache_config, quant_config)
  691. assert self.version == (2, 5)
  692. def init_llm(
  693. self,
  694. config: PretrainedConfig,
  695. cache_config: Optional[CacheConfig] = None,
  696. quant_config: Optional[QuantizationConfig] = None,
  697. ) -> nn.Module:
  698. return LlamaModel(config,
  699. cache_config=cache_config,
  700. quant_config=quant_config)
  701. def init_vision_module(self) -> nn.Module:
  702. model = Idefics2VisionTransformer(self.config.vision_config)
  703. if self.config.drop_vision_last_layer:
  704. model.encoder.layers = model.encoder.layers[:-1]
  705. return model
  706. def init_resampler(self, embed_dim: int, vision_dim: int) -> nn.Module:
  707. with set_default_torch_dtype(torch.float16):
  708. resampler = Resampler2_5(
  709. num_queries=self.config.query_num,
  710. embed_dim=embed_dim,
  711. num_heads=embed_dim // 128,
  712. kv_dim=vision_dim,
  713. )
  714. return resampler
  715. def get_vision_embedding(
  716. self,
  717. pixel_values: List[torch.Tensor],
  718. patch_attn_mask: Optional[torch.Tensor] = None,
  719. tgt_sizes: Optional[torch.Tensor] = None,
  720. ) -> torch.Tensor:
  721. vision_embedding = self.vpm(pixel_values,
  722. patch_attention_mask=patch_attn_mask)
  723. vision_embedding = self.resampler(vision_embedding, tgt_sizes)
  724. return vision_embedding
  725. def get_vision_hidden_states(self,
  726. data: MiniCPMVImageInputs) -> torch.Tensor:
  727. pixel_values = data["pixel_values"]
  728. tgt_sizes = data["tgt_sizes"]
  729. device = self.vpm.embeddings.position_embedding.weight.device
  730. dtype = self.vpm.embeddings.position_embedding.weight.dtype
  731. all_pixel_values_lst = [
  732. i.flatten(end_dim=1).permute(1, 0) for i in pixel_values
  733. ]
  734. max_patches = (tgt_sizes[:, 0] * tgt_sizes[:, 1]).max().item()
  735. assert isinstance(max_patches, int)
  736. all_pixel_values = torch.nn.utils.rnn.pad_sequence(
  737. all_pixel_values_lst, batch_first=True, padding_value=0.0)
  738. B, L, _ = all_pixel_values.shape
  739. all_pixel_values = all_pixel_values.permute(0, 2,
  740. 1).reshape(B, 3, -1, L)
  741. patch_attn_mask = torch.zeros((B, 1, max_patches),
  742. dtype=torch.bool,
  743. device=device)
  744. for i in range(B):
  745. patch_attn_mask[i, :tgt_sizes[i][0] * tgt_sizes[i][1]] = True
  746. return self.get_vision_embedding(all_pixel_values.type(dtype),
  747. patch_attn_mask, tgt_sizes)
  748. def is_default_weight_loading(self, name: str) -> bool:
  749. return "resampler" in name
  750. # NOTE: Currently, information about this model is unavailable. We are
  751. # temporarily using `MiniCPMVQwen2` as it's name. The name may need
  752. # to be modified in the future.
  753. class MiniCPMVQwen2(MiniCPMVBaseModel):
  754. def __init__(
  755. self,
  756. config: PretrainedConfig,
  757. multimodal_config: MultiModalConfig,
  758. cache_config: Optional[CacheConfig] = None,
  759. quant_config: Optional[QuantizationConfig] = None,
  760. ):
  761. super().__init__(config, multimodal_config, cache_config, quant_config)
  762. def init_llm(
  763. self,
  764. config: PretrainedConfig,
  765. cache_config: Optional[CacheConfig] = None,
  766. quant_config: Optional[QuantizationConfig] = None,
  767. ) -> nn.Module:
  768. return Qwen2Model(config,
  769. cache_config=cache_config,
  770. quant_config=quant_config)
  771. def init_vision_module(self) -> nn.Module:
  772. # A custom version of SiglipVisionTransformer, won't work with TP
  773. from aphrodite.modeling.models.na_vit import SiglipVisionTransformer
  774. if self.config._attn_implementation == "flash_attention_2":
  775. self.config.vision_config._attn_implementation = "flash_attention_2"
  776. else:
  777. # not support sdpa
  778. self.config.vision_config._attn_implementation = "eager"
  779. model = SiglipVisionTransformer(self.config.vision_config)
  780. if self.config.drop_vision_last_layer:
  781. model.encoder.layers = model.encoder.layers[:-1]
  782. return model
  783. def init_resampler(self, embed_dim: int, vision_dim: int) -> nn.Module:
  784. with set_default_torch_dtype(torch.float16):
  785. resampler = Resampler2_5(
  786. num_queries=self.config.query_num,
  787. embed_dim=embed_dim,
  788. num_heads=embed_dim // 128,
  789. kv_dim=vision_dim,
  790. )
  791. return resampler
  792. def get_vision_embedding(
  793. self,
  794. pixel_values: List[torch.Tensor],
  795. patch_attn_mask: Optional[torch.Tensor] = None,
  796. tgt_sizes: Optional[torch.Tensor] = None,
  797. ) -> torch.Tensor:
  798. vision_embedding = self.vpm(
  799. pixel_values,
  800. patch_attention_mask=patch_attn_mask,
  801. tgt_sizes=tgt_sizes,
  802. ).last_hidden_state
  803. return vision_embedding
  804. def get_vision_hidden_states(self,
  805. data: MiniCPMVImageInputs) -> torch.Tensor:
  806. pixel_values = data["pixel_values"]
  807. tgt_sizes = data["tgt_sizes"]
  808. device = self.vpm.embeddings.position_embedding.weight.device
  809. dtype = self.vpm.embeddings.position_embedding.weight.dtype
  810. all_pixel_values_lst = [
  811. i.flatten(end_dim=1).permute(1, 0) for i in pixel_values
  812. ]
  813. max_patches = (tgt_sizes[:, 0] * tgt_sizes[:, 1]).max().item()
  814. assert isinstance(max_patches, int)
  815. all_pixel_values = torch.nn.utils.rnn.pad_sequence(
  816. all_pixel_values_lst, batch_first=True, padding_value=0.0)
  817. B, L, _ = all_pixel_values.shape
  818. all_pixel_values = all_pixel_values.permute(0, 2,
  819. 1).reshape(B, 3, -1, L)
  820. patch_attn_mask = torch.zeros((B, 1, max_patches),
  821. dtype=torch.bool,
  822. device=device)
  823. for i in range(B):
  824. patch_attn_mask[i, 0, :tgt_sizes[i][0] * tgt_sizes[i][1]] = True
  825. vision_embedding = self.vpm(
  826. all_pixel_values.type(dtype),
  827. patch_attention_mask=patch_attn_mask,
  828. tgt_sizes=tgt_sizes,
  829. ).last_hidden_state
  830. return self.resampler(vision_embedding, tgt_sizes)
  831. def is_default_weight_loading(self, name: str) -> bool:
  832. return "resampler" in name or "vpm" in name
  833. @MULTIMODAL_REGISTRY.register_image_input_mapper()
  834. @MULTIMODAL_REGISTRY.register_max_image_tokens(get_max_minicpmv_image_tokens)
  835. @INPUT_REGISTRY.register_dummy_data(dummy_data_for_minicpmv)
  836. @INPUT_REGISTRY.register_input_processor(input_processor_for_minicpmv)
  837. class MiniCPMV(MiniCPMVBaseModel):
  838. """
  839. Different versions of MiniCPMV use different visual encoders and LLMs,
  840. which is not conducive to the current integration logic of LoRA and
  841. bitsandbytes in aphrodite. Therefore, it is necessary to separate them.
  842. """
  843. def __new__(
  844. cls,
  845. config: PretrainedConfig,
  846. multimodal_config: MultiModalConfig,
  847. cache_config: Optional[CacheConfig] = None,
  848. quant_config: Optional[QuantizationConfig] = None,
  849. ):
  850. if not hasattr(config, "version"):
  851. if config.hidden_size == 2304 and config.query_num == 64:
  852. version = (2, 0)
  853. else:
  854. version = (2, 5)
  855. else:
  856. version = str(config.version).split(".")
  857. version = tuple([int(x) for x in version])
  858. # Dispatch class based on version
  859. if version == (2, 0):
  860. instance_class = MiniCPMV2
  861. elif version == (2, 5):
  862. instance_class = MiniCPMV2_5
  863. else:
  864. instance_class = MiniCPMVQwen2
  865. return instance_class(config, multimodal_config, cache_config,
  866. quant_config)