intern_vit.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. # adapted from https://huggingface.co/OpenGVLab/InternVL2-4B/blob/main/modeling_intern_vit.py
  2. # --------------------------------------------------------
  3. # InternVL
  4. # Copyright (c) 2023 OpenGVLab
  5. # Licensed under The MIT License [see LICENSE for details]
  6. # --------------------------------------------------------
  7. from typing import Iterable, Optional, Tuple
  8. import torch
  9. import torch.nn as nn
  10. import torch.nn.functional as F
  11. from transformers import PretrainedConfig
  12. from aphrodite.common.utils import progress_bar
  13. from aphrodite.modeling.layers.activation import get_act_fn
  14. from aphrodite.modeling.layers.layernorm import RMSNorm
  15. from aphrodite.modeling.layers.linear import (ColumnParallelLinear,
  16. RowParallelLinear)
  17. from aphrodite.modeling.model_loader.weight_utils import default_weight_loader
  18. from aphrodite.quantization import QuantizationConfig
  19. NORM2FN = {
  20. 'rms_norm': RMSNorm,
  21. 'layer_norm': nn.LayerNorm,
  22. }
  23. class InternVisionEmbeddings(nn.Module):
  24. def __init__(self, config: PretrainedConfig):
  25. super().__init__()
  26. self.config = config
  27. self.embed_dim = config.hidden_size
  28. self.image_size = config.image_size
  29. self.patch_size = config.patch_size
  30. self.class_embedding = nn.Parameter(torch.randn(1, 1, self.embed_dim))
  31. self.patch_embedding = nn.Conv2d(in_channels=3,
  32. out_channels=self.embed_dim,
  33. kernel_size=self.patch_size,
  34. stride=self.patch_size)
  35. self.num_patches = (self.image_size // self.patch_size)**2
  36. self.num_positions = self.num_patches + 1
  37. self.position_embedding = nn.Parameter(
  38. torch.randn(1, self.num_positions, self.embed_dim))
  39. def _get_pos_embed(self, pos_embed, H, W):
  40. target_dtype = pos_embed.dtype
  41. pos_embed = pos_embed.float().reshape(
  42. 1, self.image_size // self.patch_size,
  43. self.image_size // self.patch_size, -1).permute(0, 3, 1, 2)
  44. pos_embed = F.interpolate(pos_embed,
  45. size=(H, W),
  46. mode='bicubic',
  47. align_corners=False)
  48. pos_embed = pos_embed.reshape(1, -1, H * W).permute(0, 2,
  49. 1).to(target_dtype)
  50. return pos_embed
  51. def forward(self, pixel_values: torch.FloatTensor) -> torch.Tensor:
  52. target_dtype = self.patch_embedding.weight.dtype
  53. patch_embeds = self.patch_embedding(pixel_values.to(
  54. target_dtype)) # shape = [*, channel, width, height]
  55. batch_size, _, height, width = patch_embeds.shape
  56. patch_embeds = patch_embeds.flatten(2).transpose(1, 2)
  57. class_embeds = self.class_embedding.expand(batch_size, 1,
  58. -1).to(target_dtype)
  59. embeddings = torch.cat([class_embeds, patch_embeds], dim=1)
  60. position_embedding = torch.cat([
  61. self.position_embedding[:, :1, :],
  62. self._get_pos_embed(self.position_embedding[:, 1:, :], height,
  63. width)
  64. ],
  65. dim=1)
  66. embeddings = embeddings + position_embedding.to(target_dtype)
  67. return embeddings
  68. class InternAttention(nn.Module):
  69. """Multi-headed attention from 'Attention Is All You Need' paper"""
  70. def __init__(self, config: PretrainedConfig):
  71. super().__init__()
  72. self.config = config
  73. self.embed_dim = config.hidden_size
  74. self.num_heads = config.num_attention_heads
  75. self.head_dim = self.embed_dim // self.num_heads
  76. if self.head_dim * self.num_heads != self.embed_dim:
  77. raise ValueError(
  78. f'embed_dim must be divisible by num_heads '
  79. f'(got `embed_dim`: {self.embed_dim} and `num_heads`:'
  80. f' {self.num_heads}).')
  81. self.scale = self.head_dim**-0.5
  82. self.qkv = nn.Linear(self.embed_dim,
  83. 3 * self.embed_dim,
  84. bias=config.qkv_bias)
  85. self.qk_normalization = config.qk_normalization
  86. if self.qk_normalization:
  87. self.q_norm = RMSNorm(self.embed_dim, eps=config.layer_norm_eps)
  88. self.k_norm = RMSNorm(self.embed_dim, eps=config.layer_norm_eps)
  89. self.proj = nn.Linear(self.embed_dim, self.embed_dim)
  90. def forward(self, x):
  91. B, N, C = x.shape
  92. qkv = self.qkv(x).reshape(B, N, 3, self.num_heads,
  93. C // self.num_heads).permute(2, 0, 3, 1, 4)
  94. q, k, v = qkv.unbind(0)
  95. if self.qk_normalization:
  96. B_, H_, N_, D_ = q.shape
  97. q = self.q_norm.forward_native(q.transpose(1, 2).flatten(
  98. -2, -1)).view(B_, N_, H_, D_).transpose(1, 2)
  99. k = self.k_norm.forward_native(k.transpose(1, 2).flatten(
  100. -2, -1)).view(B_, N_, H_, D_).transpose(1, 2)
  101. x = F.scaled_dot_product_attention(q, k, v, scale=self.scale)
  102. x = x.transpose(1, 2).reshape(B, N, C)
  103. x = self.proj(x)
  104. return x
  105. class InternMLP(nn.Module):
  106. def __init__(self,
  107. config: PretrainedConfig,
  108. quant_config: Optional[QuantizationConfig] = None):
  109. super().__init__()
  110. self.config = config
  111. self.activation_fn = get_act_fn(config.hidden_act)
  112. self.fc1 = ColumnParallelLinear(config.hidden_size,
  113. config.intermediate_size,
  114. bias=True,
  115. quant_config=quant_config)
  116. self.fc2 = RowParallelLinear(config.intermediate_size,
  117. config.hidden_size,
  118. bias=True,
  119. quant_config=quant_config)
  120. def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
  121. hidden_states, _ = self.fc1(hidden_states)
  122. hidden_states = self.activation_fn(hidden_states)
  123. hidden_states, _ = self.fc2(hidden_states)
  124. return hidden_states
  125. class InternVisionEncoderLayer(nn.Module):
  126. def __init__(self,
  127. config: PretrainedConfig,
  128. quant_config: Optional[QuantizationConfig] = None):
  129. super().__init__()
  130. self.embed_dim = config.hidden_size
  131. self.intermediate_size = config.intermediate_size
  132. self.norm_type = config.norm_type
  133. self.attn = InternAttention(config)
  134. self.mlp = InternMLP(config, quant_config=quant_config)
  135. self.norm1 = NORM2FN[self.norm_type](self.embed_dim,
  136. eps=config.layer_norm_eps)
  137. self.norm2 = NORM2FN[self.norm_type](self.embed_dim,
  138. eps=config.layer_norm_eps)
  139. self.ls1 = nn.Parameter(config.initializer_factor *
  140. torch.ones(self.embed_dim))
  141. self.ls2 = nn.Parameter(config.initializer_factor *
  142. torch.ones(self.embed_dim))
  143. def forward(
  144. self,
  145. hidden_states: torch.Tensor,
  146. ):
  147. hidden_states = hidden_states + self.attn(
  148. self.norm1(hidden_states)) * self.ls1
  149. hidden_states = hidden_states + self.mlp(
  150. self.norm2(hidden_states)) * self.ls2
  151. return hidden_states
  152. class InternVisionEncoder(nn.Module):
  153. def __init__(self,
  154. config: PretrainedConfig,
  155. quant_config: Optional[QuantizationConfig] = None,
  156. num_hidden_layers_override: Optional[int] = None):
  157. super().__init__()
  158. self.config = config
  159. if num_hidden_layers_override is None:
  160. num_hidden_layers = config.num_hidden_layers
  161. else:
  162. num_hidden_layers = num_hidden_layers_override
  163. self.layers = nn.ModuleList([
  164. InternVisionEncoderLayer(config=config, quant_config=quant_config)
  165. for _ in range(num_hidden_layers)
  166. ])
  167. def forward(self, inputs_embeds: torch.Tensor):
  168. hidden_states = inputs_embeds
  169. for encoder_layer in self.layers:
  170. hidden_states = encoder_layer(hidden_states)
  171. return hidden_states
  172. class InternVisionModel(nn.Module):
  173. def __init__(self,
  174. config: PretrainedConfig,
  175. quant_config: Optional[QuantizationConfig] = None,
  176. num_hidden_layers_override: Optional[int] = None):
  177. super().__init__()
  178. self.config = config
  179. self.embeddings = InternVisionEmbeddings(config)
  180. self.encoder = InternVisionEncoder(
  181. config=config,
  182. quant_config=quant_config,
  183. num_hidden_layers_override=num_hidden_layers_override)
  184. def resize_pos_embeddings(self, old_size, new_size, patch_size):
  185. pos_emb = self.embeddings.position_embedding
  186. _, num_positions, embed_dim = pos_emb.shape
  187. cls_emb = pos_emb[:, :1, :]
  188. pos_emb = pos_emb[:, 1:, :].reshape(1, old_size // patch_size,
  189. old_size // patch_size,
  190. -1).permute(0, 3, 1, 2)
  191. pos_emb = F.interpolate(pos_emb.float(),
  192. size=new_size // patch_size,
  193. mode='bicubic',
  194. align_corners=False)
  195. pos_emb = pos_emb.to(cls_emb.dtype).reshape(1, embed_dim,
  196. -1).permute(0, 2, 1)
  197. pos_emb = torch.cat([cls_emb, pos_emb], dim=1)
  198. self.embeddings.position_embedding = nn.Parameter(pos_emb)
  199. self.embeddings.image_size = new_size
  200. def get_input_embeddings(self):
  201. return self.embeddings
  202. def forward(
  203. self,
  204. pixel_values: Optional[torch.Tensor] = None,
  205. pixel_embeds: Optional[torch.Tensor] = None,
  206. ) -> torch.FloatTensor:
  207. if pixel_values is None and pixel_embeds is None:
  208. raise ValueError(
  209. 'You have to specify pixel_values or pixel_embeds')
  210. if pixel_embeds is not None:
  211. hidden_states = pixel_embeds
  212. elif pixel_values is not None:
  213. if pixel_values.ndim == 4:
  214. hidden_states = self.embeddings(pixel_values)
  215. else:
  216. raise ValueError(
  217. f'wrong pixel_values size: {pixel_values.shape}')
  218. encoder_outputs = self.encoder(inputs_embeds=hidden_states)
  219. return encoder_outputs
  220. def load_weights(self, weights: Iterable[Tuple[str, torch.Tensor]]):
  221. params_dict = dict(self.named_parameters())
  222. weights_list = list(weights)
  223. for name, loaded_weight in progress_bar(weights_list,
  224. desc="Loading modules..."):
  225. param = params_dict[name]
  226. weight_loader = getattr(param, "weight_loader",
  227. default_weight_loader)
  228. weight_loader(param, loaded_weight)