model.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  1. import math
  2. import re
  3. from typing import Iterable, List, Optional, Tuple
  4. import numpy as np
  5. import torch
  6. from sglang.srt.layers.quantization.base_config import QuantizationConfig
  7. from sglang.version import __version__ as sglang_version
  8. from packaging import version
  9. if version.parse(sglang_version) >= version.parse("0.4.9"):
  10. # sglang >= 0.4.9
  11. from sglang.srt.multimodal.mm_utils import (
  12. get_anyres_image_grid_shape,
  13. )
  14. else:
  15. # 0.4.7 <= sglang < 0.4.9
  16. from sglang.srt.mm_utils import (
  17. get_anyres_image_grid_shape,
  18. )
  19. from sglang.srt.model_executor.forward_batch_info import ForwardBatch
  20. from sglang.srt.model_loader.weight_utils import default_weight_loader
  21. from sglang.srt.models.qwen2 import Qwen2ForCausalLM
  22. from sglang.srt.utils import add_prefix
  23. from torch import nn
  24. from transformers import (
  25. CLIPVisionConfig,
  26. CLIPVisionModel,
  27. SiglipVisionConfig,
  28. SiglipVisionModel,
  29. )
  30. from ..vlm_hf_model.configuration_mineru2 import Mineru2QwenConfig
  31. from ..vlm_hf_model.modeling_mineru2 import build_vision_projector
  32. from ...utils.models_download_utils import auto_download_and_get_model_root_path
  33. def flatten_nested_list(nested_list):
  34. if isinstance(nested_list, list):
  35. return [item for sublist in nested_list for item in flatten_nested_list(sublist)]
  36. else:
  37. return [nested_list]
  38. def downgrade_modality(modality):
  39. modality_str = str(modality)
  40. if "MULTI_IMAGES" in modality_str:
  41. return "multi-images"
  42. if "IMAGE" in modality_str:
  43. return "image"
  44. if "VIDEO" in modality_str:
  45. return "video"
  46. if "AUDIO" in modality_str:
  47. return "audio"
  48. raise ValueError(f"Unexpected modality: {modality_str}")
  49. class Mineru2QwenForCausalLM(nn.Module):
  50. def __init__(
  51. self,
  52. config: Mineru2QwenConfig,
  53. quant_config: Optional[QuantizationConfig] = None,
  54. prefix: str = "",
  55. ) -> None:
  56. super().__init__()
  57. self.config = config
  58. if getattr(self.config, "projector_hidden_act", None) is None:
  59. self.config.projector_hidden_act = "gelu"
  60. if getattr(self.config, "image_token_index", None) is None:
  61. self.config.image_token_index = 151646
  62. # load vision tower
  63. mm_vision_tower = self.config.mm_vision_tower
  64. model_root_path = auto_download_and_get_model_root_path(mm_vision_tower, "vlm")
  65. mm_vision_tower = f"{model_root_path}/{mm_vision_tower}"
  66. if "clip" in mm_vision_tower:
  67. vision_config = CLIPVisionConfig.from_pretrained(mm_vision_tower)
  68. self.vision_tower = CLIPVisionModel(vision_config) # type: ignore
  69. elif "siglip" in mm_vision_tower:
  70. vision_config = SiglipVisionConfig.from_pretrained(mm_vision_tower)
  71. self.vision_tower = SiglipVisionModel(vision_config) # type: ignore
  72. # Siglip needs all feature tokens
  73. self.config.mm_vision_select_feature = "full"
  74. else:
  75. raise ValueError(f"Unexpected mm_vision_tower: {mm_vision_tower}")
  76. ### EDIT: change projector
  77. # the name `projector` contains `proj` which is often used in attention layers, which can cause bugs in quantization.
  78. self.multi_modal_mlp = build_vision_projector(config)
  79. self.language_model = Qwen2ForCausalLM(
  80. config,
  81. quant_config=quant_config,
  82. prefix=add_prefix("language_model", prefix),
  83. )
  84. if "unpad" in getattr(config, "mm_patch_merge_type", ""):
  85. self.language_model.model.image_newline = nn.Parameter(torch.empty(config.hidden_size))
  86. language_model_device = next(self.language_model.parameters()).device
  87. self.vision_tower = self.vision_tower.to(language_model_device)
  88. self.vision_tower.eval()
  89. self.vision_feature_layer = self.config.mm_vision_select_layer
  90. self.vision_feature_select_strategy = self.config.mm_vision_select_feature
  91. self.image_size = self.vision_tower.config.image_size
  92. self.patch_size = self.vision_tower.config.patch_size
  93. self.mm_patch_merge_type = getattr(self.config, "mm_patch_merge_type", "flat")
  94. self.image_aspect_ratio = getattr(self.config, "image_aspect_ratio", "square")
  95. self.image_grid_pinpoints = getattr(self.config, "image_grid_pinpoints", None)
  96. self.image_feature_len = int((self.image_size // self.patch_size) ** 2)
  97. if self.vision_feature_select_strategy in ("patch", "full"):
  98. pass
  99. elif self.vision_feature_select_strategy == "cls_patch":
  100. self.image_feature_len += 1
  101. else:
  102. raise ValueError(f"Unexpected select feature: {self.select_feature}")
  103. def pad_input_ids(self, input_ids: List[int], image_inputs):
  104. image_sizes = flatten_nested_list([item.image_sizes for item in image_inputs.mm_items])
  105. pad_values = [item.pad_value for item in image_inputs.mm_items]
  106. # hardcode for spatial_unpad + anyres
  107. # if image_inputs.modalities is not None and (
  108. # "multi-images" in image_inputs.modalities or "video" in image_inputs.modalities
  109. # ):
  110. # image_aspect_ratio = "pad"
  111. # else:
  112. # image_aspect_ratio = "anyres"
  113. offset_list = []
  114. image_inputs.image_pad_len = []
  115. for image_idx, image_s in enumerate(image_sizes):
  116. if len(image_sizes) > 16:
  117. # 2x2 pooling with stride 2
  118. new_image_feature_len = math.ceil(self.image_size / self.patch_size / 2) ** 2
  119. else:
  120. new_image_feature_len = self.image_feature_len # multiimage
  121. height = width = self.num_patches_per_side
  122. if "anyres" in self.config.image_aspect_ratio:
  123. num_patch_width, num_patch_height = get_anyres_image_grid_shape(
  124. image_s,
  125. self.image_grid_pinpoints,
  126. self.vision_tower.config.image_size,
  127. )
  128. h = num_patch_height * height
  129. w = num_patch_width * width
  130. ### EDIT: remove `unpad_image_shape`
  131. # new_h, new_w = unpad_image_shape(h, w, image_s)
  132. new_h, new_w = h, w
  133. if "anyres_max" in self.config.image_aspect_ratio:
  134. matched_anyres_max_num_patches = re.match(r".*anyres_max_(\d+)", self.config.image_aspect_ratio)
  135. if matched_anyres_max_num_patches:
  136. max_num_patches = int(matched_anyres_max_num_patches.group(1))
  137. times = math.sqrt(new_h * new_w / (max_num_patches * self.image_feature_len))
  138. if times > 1.1:
  139. new_h = int(new_h // times)
  140. new_w = int(new_w // times)
  141. new_image_feature_len += new_h * (new_w + 1)
  142. try:
  143. offset = input_ids.index(self.config.image_token_index)
  144. except ValueError:
  145. offset = 0
  146. # old_len + pad_len - 1, because we need to remove image_token_id
  147. input_ids = input_ids[:offset] + [pad_values[image_idx]] * new_image_feature_len + input_ids[offset + 1 :]
  148. offset_list.append(offset)
  149. image_inputs.image_pad_len.append(new_image_feature_len)
  150. image_inputs.image_offsets = offset_list
  151. return input_ids
  152. def encode_images(self, pixel_values: torch.Tensor) -> torch.Tensor:
  153. pixel_values = pixel_values.to(device=self.vision_tower.device, dtype=self.vision_tower.dtype)
  154. image_outputs = self.vision_tower(pixel_values, output_hidden_states=True)
  155. # NOTE: This is not memory efficient. (output_hidden_states=True) will save all the hidden stated.
  156. selected_image_feature = image_outputs.hidden_states[self.vision_feature_layer]
  157. if self.vision_feature_select_strategy in ["default", "patch"]:
  158. selected_image_feature = selected_image_feature[:, 1:]
  159. elif self.vision_feature_select_strategy == "full":
  160. selected_image_feature = selected_image_feature
  161. else:
  162. raise ValueError(f"Unexpected select feature strategy: {self.vision_feature_select_strategy}")
  163. image_features = self.multi_modal_mlp(selected_image_feature)
  164. return image_features
  165. @torch.no_grad()
  166. def forward(
  167. self,
  168. input_ids: torch.LongTensor,
  169. positions: torch.Tensor,
  170. forward_batch: ForwardBatch,
  171. ) -> torch.Tensor:
  172. image_inputs = forward_batch.mm_inputs
  173. if image_inputs is None:
  174. image_inputs = []
  175. if forward_batch.forward_mode.is_extend():
  176. # Clamp input ids. This is because the input_ids for the image tokens are
  177. # filled with the hash values of the image for the prefix matching in the radix attention.
  178. # There values are useless because their embeddings will be replaced by vision embeddings anyway.
  179. input_ids.clamp_(min=0, max=self.config.vocab_size - 1)
  180. # Embed text inputs
  181. input_embeds = self.language_model.model.embed_tokens(input_ids)
  182. # Got List[List[str]] extend it to List[str]
  183. # The length of the List should be equal to batch size
  184. modalities_list = []
  185. max_image_offset = []
  186. for im in image_inputs:
  187. if im:
  188. modalities_list.extend([downgrade_modality(item.modality) for item in im.mm_items])
  189. if im and im.image_offsets:
  190. max_image_offset.append(np.max(np.array(im.image_offsets) + np.array(im.image_pad_len)))
  191. else:
  192. max_image_offset.append(-1)
  193. start_positions = positions[forward_batch.extend_start_loc].cpu().numpy()
  194. need_vision = start_positions <= np.array(max_image_offset)
  195. if need_vision.any():
  196. bs = forward_batch.batch_size
  197. if version.parse(sglang_version) >= version.parse("0.4.9.post3"):
  198. # sglang >= 0.4.9.post3
  199. pixel_values = flatten_nested_list(
  200. [[item.feature for item in image_inputs[i].mm_items] for i in range(bs) if need_vision[i]]
  201. ) # image_inputs[batch_idx].mm_items[item_idx].pixel_values is Tensor
  202. image_sizes = [
  203. flatten_nested_list([item.model_specific_data["image_sizes"] for item in image_inputs[i].mm_items])
  204. for i in range(bs)
  205. if need_vision[i]
  206. ] # image_inputs[batch_idx].mm_items[item_idx].image_sizes should be tuple, but is list of tuple for now.
  207. else:
  208. # 0.4.7 <= sglang <= 0.4.9.post2
  209. pixel_values = flatten_nested_list(
  210. [[item.pixel_values for item in image_inputs[i].mm_items] for i in range(bs) if need_vision[i]]
  211. ) # image_inputs[batch_idx].mm_items[item_idx].pixel_values is Tensor
  212. image_sizes = [
  213. flatten_nested_list([item.image_sizes for item in image_inputs[i].mm_items])
  214. for i in range(bs)
  215. if need_vision[i]
  216. ] # image_inputs[batch_idx].mm_items[item_idx].image_sizes should be tuple, but is list of tuple for now.
  217. ########## Encode Image ########
  218. if pixel_values[0].ndim == 4:
  219. # llava-hd: BS, num_patch, C=3, H=336, W=336, num_patch obtained from process_images
  220. np.concatenate(pixel_values, axis=0)
  221. # ndim=4
  222. concat_images = torch.tensor(
  223. np.concatenate(pixel_values, axis=0),
  224. device=self.vision_tower.device,
  225. )
  226. image_features = self.encode_images(concat_images)
  227. split_sizes = [image.shape[0] for image in pixel_values]
  228. image_features = torch.split(image_features, split_sizes, dim=0)
  229. # hd image_features: BS, num_patch, 576, 4096
  230. else:
  231. # normal pixel: BS, C=3, H=336, W=336
  232. pixel_values = torch.tensor(np.array(pixel_values), device=self.vision_tower.device)
  233. image_features = self.encode_images(pixel_values)
  234. # image_features: BS, 576, 4096
  235. if self.mm_patch_merge_type.startswith("spatial"):
  236. new_image_features = []
  237. height = width = self.num_patches_per_side
  238. for image_idx, image_feature in enumerate(image_features):
  239. if modalities_list[image_idx] == "image":
  240. image_aspect_ratio = self.config.image_aspect_ratio # single image
  241. elif modalities_list[image_idx] == "multi-images" or modalities_list[image_idx] == "video":
  242. image_aspect_ratio = "pad" # multi image
  243. # image_aspect_ratio = (
  244. # "anyres" if len(image_sizes[image_idx]) == 1 else "pad"
  245. # )
  246. if (
  247. image_feature.shape[0] > 1
  248. and "anyres" in image_aspect_ratio
  249. and modalities_list[image_idx] == "image"
  250. ):
  251. base_image_feature = image_feature[0]
  252. image_feature = image_feature[1:]
  253. assert height * width == base_image_feature.shape[0]
  254. if "anyres_max" in image_aspect_ratio:
  255. matched_anyres_max_num_patches = re.match(r".*anyres_max_(\d+)", image_aspect_ratio)
  256. if matched_anyres_max_num_patches:
  257. max_num_patches = int(matched_anyres_max_num_patches.group(1))
  258. if image_aspect_ratio == "anyres" or "anyres_max" in image_aspect_ratio:
  259. vision_tower_image_size = self.image_size
  260. try:
  261. num_patch_width, num_patch_height = get_anyres_image_grid_shape(
  262. image_sizes[image_idx][0],
  263. self.config.image_grid_pinpoints,
  264. vision_tower_image_size,
  265. )
  266. except Exception as e:
  267. print(f"Error: {e}")
  268. num_patch_width, num_patch_height = 2, 2
  269. image_feature = image_feature.view(num_patch_height, num_patch_width, height, width, -1)
  270. else:
  271. image_feature = image_feature.view(2, 2, height, width, -1)
  272. if "unpad" in self.mm_patch_merge_type:
  273. unit = image_feature.shape[2]
  274. image_feature = image_feature.permute(4, 0, 2, 1, 3).contiguous()
  275. image_feature = image_feature.flatten(1, 2).flatten(2, 3)
  276. ### EDIT: remove `unpad_image`
  277. # image_feature = unpad_image(image_feature, image_sizes[image_idx][0])
  278. if "anyres_max" in image_aspect_ratio and matched_anyres_max_num_patches:
  279. c, h, w = image_feature.shape
  280. times = math.sqrt(h * w / (max_num_patches * unit**2))
  281. if times > 1.1:
  282. image_feature = image_feature[None]
  283. image_feature = nn.functional.interpolate(
  284. image_feature,
  285. [int(h // times), int(w // times)],
  286. mode="bilinear",
  287. )[0]
  288. image_feature = torch.cat(
  289. (
  290. image_feature,
  291. self.language_model.model.image_newline[:, None, None].expand(
  292. *image_feature.shape[:-1], 1
  293. ),
  294. ),
  295. dim=-1,
  296. )
  297. image_feature = image_feature.flatten(1, 2).transpose(0, 1)
  298. else:
  299. image_feature = image_feature.permute(0, 2, 1, 3, 4).contiguous()
  300. image_feature = image_feature.flatten(0, 3)
  301. image_feature = torch.cat((base_image_feature, image_feature), dim=0)
  302. image_feature = image_feature.unsqueeze(0)
  303. else:
  304. if modalities_list[image_idx] == "video": # video
  305. # 2x2 pooling
  306. num_of_frames = image_feature.shape[0]
  307. image_feature = image_feature.view(num_of_frames, height, width, -1)
  308. image_feature = image_feature.permute(0, 3, 1, 2).contiguous() # N, C, H, W
  309. height, weight = image_feature.shape[2:]
  310. scaled_shape = [
  311. math.ceil(height / 2),
  312. math.ceil(weight / 2),
  313. ]
  314. image_feature = nn.functional.interpolate(image_feature, size=scaled_shape, mode="bilinear")
  315. image_feature = image_feature.flatten(2).transpose(1, 2).contiguous() # N, C, H*W
  316. if "unpad" in self.mm_patch_merge_type:
  317. image_feature = torch.cat(
  318. (
  319. image_feature,
  320. # Expand to (bs, 1, hidden_dim) and concat at the end of the image tokens
  321. self.language_model.model.image_newline[None, None].expand(
  322. image_feature.shape[0],
  323. 1,
  324. image_feature.shape[-1],
  325. ),
  326. ),
  327. dim=1,
  328. )
  329. new_image_features.append(image_feature)
  330. image_features = new_image_features
  331. # Fill in the placeholder for the image
  332. extend_start_loc_cpu = forward_batch.extend_start_loc.cpu().numpy()
  333. extend_seq_lens = forward_batch.extend_seq_lens.cpu().numpy()
  334. prefix_lens_cpu = forward_batch.extend_prefix_lens_cpu
  335. pt = 0
  336. for i in range(bs):
  337. if not need_vision[i]:
  338. continue
  339. start_idx = extend_start_loc_cpu[i]
  340. seq_len = extend_seq_lens[i]
  341. prefix_len = prefix_lens_cpu[i]
  342. # Multiple images
  343. for image_idx, image_offset in enumerate(image_inputs[i].image_offsets):
  344. if image_offset + image_inputs[i].image_pad_len[image_idx] <= prefix_len:
  345. continue
  346. if image_offset >= prefix_len + seq_len:
  347. break
  348. tmp_image_feature = image_features[pt][image_idx]
  349. pad_len = tmp_image_feature.shape[0]
  350. input_offset = image_offset - prefix_len
  351. left_idx = start_idx + input_offset
  352. right_idx = left_idx + pad_len
  353. assert right_idx > start_idx
  354. if input_offset < 0:
  355. left_idx = start_idx
  356. tmp_image_feature = tmp_image_feature[-input_offset:]
  357. if right_idx > start_idx + seq_len:
  358. tmp_image_feature = tmp_image_feature[: start_idx + seq_len - right_idx]
  359. right_idx = start_idx + seq_len
  360. try:
  361. input_embeds[left_idx:right_idx] = tmp_image_feature
  362. except RuntimeError as e:
  363. print(f"RuntimeError in image encoding: {e}")
  364. print(f"{input_embeds.shape=}, {tmp_image_feature.shape=}")
  365. print(f"{start_idx=}, {image_offset=}, {prefix_len=}, {pad_len=}")
  366. pt += 1
  367. return self.language_model(input_ids, positions, forward_batch, input_embeds=input_embeds)
  368. elif forward_batch.forward_mode.is_decode():
  369. return self.language_model(input_ids, positions, forward_batch)
  370. else:
  371. raise ValueError(f"Unexpected forward mode: {forward_batch.forward_mode}")
  372. def load_weights(self, weights: Iterable[Tuple[str, torch.Tensor]]):
  373. projector_weights = {
  374. "model.mm_projector": "multi_modal_mlp",
  375. "model.vision_tower.vision_tower": "vision_tower",
  376. # Update the vision tower weights if we find them in the checkpoint (it may be finetuned).
  377. "model.image_newline": "language_model.model.image_newline",
  378. }
  379. params_dict = dict(self.named_parameters())
  380. for name, loaded_weight in weights:
  381. if "projector" in name or "vision_tower" in name or "image_newline" in name:
  382. for weight_name, param_name in projector_weights.items():
  383. if weight_name in name:
  384. name = name.replace(weight_name, param_name)
  385. param = params_dict[name]
  386. weight_loader = getattr(param, "weight_loader", default_weight_loader)
  387. weight_loader(param, loaded_weight)
  388. else:
  389. self.language_model.load_weights([(name, loaded_weight)])
  390. @property
  391. def num_patches_per_side(self):
  392. return self.image_size // self.patch_size
  393. EntryClass = [Mineru2QwenForCausalLM]