intern_vit.py 10 KB

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