nlvr_encoder.py 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843
  1. import math
  2. import os
  3. import warnings
  4. from dataclasses import dataclass
  5. from typing import Optional, Tuple
  6. import torch
  7. from torch import Tensor, device, dtype, nn
  8. import torch.utils.checkpoint
  9. from torch import nn
  10. from torch.nn import CrossEntropyLoss
  11. import torch.nn.functional as F
  12. from transformers.activations import ACT2FN
  13. from transformers.file_utils import (
  14. ModelOutput,
  15. )
  16. from transformers.modeling_outputs import (
  17. BaseModelOutputWithPastAndCrossAttentions,
  18. BaseModelOutputWithPoolingAndCrossAttentions,
  19. CausalLMOutputWithCrossAttentions,
  20. MaskedLMOutput,
  21. MultipleChoiceModelOutput,
  22. NextSentencePredictorOutput,
  23. QuestionAnsweringModelOutput,
  24. SequenceClassifierOutput,
  25. TokenClassifierOutput,
  26. )
  27. from transformers.modeling_utils import (
  28. PreTrainedModel,
  29. apply_chunking_to_forward,
  30. find_pruneable_heads_and_indices,
  31. prune_linear_layer,
  32. )
  33. from transformers.utils import logging
  34. from transformers.models.bert.configuration_bert import BertConfig
  35. logger = logging.get_logger(__name__)
  36. class BertEmbeddings(nn.Module):
  37. """Construct the embeddings from word and position embeddings."""
  38. def __init__(self, config):
  39. super().__init__()
  40. self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
  41. self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)
  42. # self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load
  43. # any TensorFlow checkpoint file
  44. self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
  45. self.dropout = nn.Dropout(config.hidden_dropout_prob)
  46. # position_ids (1, len position emb) is contiguous in memory and exported when serialized
  47. self.register_buffer("position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)))
  48. self.position_embedding_type = getattr(config, "position_embedding_type", "absolute")
  49. self.config = config
  50. def forward(
  51. self, input_ids=None, position_ids=None, inputs_embeds=None, past_key_values_length=0
  52. ):
  53. if input_ids is not None:
  54. input_shape = input_ids.size()
  55. else:
  56. input_shape = inputs_embeds.size()[:-1]
  57. seq_length = input_shape[1]
  58. if position_ids is None:
  59. position_ids = self.position_ids[:, past_key_values_length : seq_length + past_key_values_length]
  60. if inputs_embeds is None:
  61. inputs_embeds = self.word_embeddings(input_ids)
  62. embeddings = inputs_embeds
  63. if self.position_embedding_type == "absolute":
  64. position_embeddings = self.position_embeddings(position_ids)
  65. embeddings += position_embeddings
  66. embeddings = self.LayerNorm(embeddings)
  67. embeddings = self.dropout(embeddings)
  68. return embeddings
  69. class BertSelfAttention(nn.Module):
  70. def __init__(self, config, is_cross_attention):
  71. super().__init__()
  72. self.config = config
  73. if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
  74. raise ValueError(
  75. "The hidden size (%d) is not a multiple of the number of attention "
  76. "heads (%d)" % (config.hidden_size, config.num_attention_heads)
  77. )
  78. self.num_attention_heads = config.num_attention_heads
  79. self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
  80. self.all_head_size = self.num_attention_heads * self.attention_head_size
  81. self.query = nn.Linear(config.hidden_size, self.all_head_size)
  82. if is_cross_attention:
  83. self.key = nn.Linear(config.encoder_width, self.all_head_size)
  84. self.value = nn.Linear(config.encoder_width, self.all_head_size)
  85. else:
  86. self.key = nn.Linear(config.hidden_size, self.all_head_size)
  87. self.value = nn.Linear(config.hidden_size, self.all_head_size)
  88. self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
  89. self.position_embedding_type = getattr(config, "position_embedding_type", "absolute")
  90. if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
  91. self.max_position_embeddings = config.max_position_embeddings
  92. self.distance_embedding = nn.Embedding(2 * config.max_position_embeddings - 1, self.attention_head_size)
  93. self.save_attention = False
  94. def save_attn_gradients(self, attn_gradients):
  95. self.attn_gradients = attn_gradients
  96. def get_attn_gradients(self):
  97. return self.attn_gradients
  98. def save_attention_map(self, attention_map):
  99. self.attention_map = attention_map
  100. def get_attention_map(self):
  101. return self.attention_map
  102. def transpose_for_scores(self, x):
  103. new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
  104. x = x.view(*new_x_shape)
  105. return x.permute(0, 2, 1, 3)
  106. def forward(
  107. self,
  108. hidden_states,
  109. attention_mask=None,
  110. head_mask=None,
  111. encoder_hidden_states=None,
  112. encoder_attention_mask=None,
  113. past_key_value=None,
  114. output_attentions=False,
  115. ):
  116. mixed_query_layer = self.query(hidden_states)
  117. # If this is instantiated as a cross-attention module, the keys
  118. # and values come from an encoder; the attention mask needs to be
  119. # such that the encoder's padding tokens are not attended to.
  120. is_cross_attention = encoder_hidden_states is not None
  121. if is_cross_attention:
  122. key_layer = self.transpose_for_scores(self.key(encoder_hidden_states))
  123. value_layer = self.transpose_for_scores(self.value(encoder_hidden_states))
  124. attention_mask = encoder_attention_mask
  125. elif past_key_value is not None:
  126. key_layer = self.transpose_for_scores(self.key(hidden_states))
  127. value_layer = self.transpose_for_scores(self.value(hidden_states))
  128. key_layer = torch.cat([past_key_value[0], key_layer], dim=2)
  129. value_layer = torch.cat([past_key_value[1], value_layer], dim=2)
  130. else:
  131. key_layer = self.transpose_for_scores(self.key(hidden_states))
  132. value_layer = self.transpose_for_scores(self.value(hidden_states))
  133. query_layer = self.transpose_for_scores(mixed_query_layer)
  134. past_key_value = (key_layer, value_layer)
  135. # Take the dot product between "query" and "key" to get the raw attention scores.
  136. attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
  137. if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
  138. seq_length = hidden_states.size()[1]
  139. position_ids_l = torch.arange(seq_length, dtype=torch.long, device=hidden_states.device).view(-1, 1)
  140. position_ids_r = torch.arange(seq_length, dtype=torch.long, device=hidden_states.device).view(1, -1)
  141. distance = position_ids_l - position_ids_r
  142. positional_embedding = self.distance_embedding(distance + self.max_position_embeddings - 1)
  143. positional_embedding = positional_embedding.to(dtype=query_layer.dtype) # fp16 compatibility
  144. if self.position_embedding_type == "relative_key":
  145. relative_position_scores = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
  146. attention_scores = attention_scores + relative_position_scores
  147. elif self.position_embedding_type == "relative_key_query":
  148. relative_position_scores_query = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
  149. relative_position_scores_key = torch.einsum("bhrd,lrd->bhlr", key_layer, positional_embedding)
  150. attention_scores = attention_scores + relative_position_scores_query + relative_position_scores_key
  151. attention_scores = attention_scores / math.sqrt(self.attention_head_size)
  152. if attention_mask is not None:
  153. # Apply the attention mask is (precomputed for all layers in BertModel forward() function)
  154. attention_scores = attention_scores + attention_mask
  155. # Normalize the attention scores to probabilities.
  156. attention_probs = nn.Softmax(dim=-1)(attention_scores)
  157. if is_cross_attention and self.save_attention:
  158. self.save_attention_map(attention_probs)
  159. attention_probs.register_hook(self.save_attn_gradients)
  160. # This is actually dropping out entire tokens to attend to, which might
  161. # seem a bit unusual, but is taken from the original Transformer paper.
  162. attention_probs_dropped = self.dropout(attention_probs)
  163. # Mask heads if we want to
  164. if head_mask is not None:
  165. attention_probs_dropped = attention_probs_dropped * head_mask
  166. context_layer = torch.matmul(attention_probs_dropped, value_layer)
  167. context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
  168. new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
  169. context_layer = context_layer.view(*new_context_layer_shape)
  170. outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
  171. outputs = outputs + (past_key_value,)
  172. return outputs
  173. class BertSelfOutput(nn.Module):
  174. def __init__(self, config, twin=False, merge=False):
  175. super().__init__()
  176. self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
  177. self.dropout = nn.Dropout(config.hidden_dropout_prob)
  178. if twin:
  179. self.dense0 = nn.Linear(config.hidden_size, config.hidden_size)
  180. self.dense1 = nn.Linear(config.hidden_size, config.hidden_size)
  181. else:
  182. self.dense = nn.Linear(config.hidden_size, config.hidden_size)
  183. if merge:
  184. self.act = ACT2FN[config.hidden_act]
  185. self.merge_layer = nn.Linear(config.hidden_size * 2, config.hidden_size)
  186. self.merge = True
  187. else:
  188. self.merge = False
  189. def forward(self, hidden_states, input_tensor):
  190. if type(hidden_states) == list:
  191. hidden_states0 = self.dense0(hidden_states[0])
  192. hidden_states1 = self.dense1(hidden_states[1])
  193. if self.merge:
  194. #hidden_states = self.merge_layer(self.act(torch.cat([hidden_states0,hidden_states1],dim=-1)))
  195. hidden_states = self.merge_layer(torch.cat([hidden_states0,hidden_states1],dim=-1))
  196. else:
  197. hidden_states = (hidden_states0+hidden_states1)/2
  198. else:
  199. hidden_states = self.dense(hidden_states)
  200. hidden_states = self.dropout(hidden_states)
  201. hidden_states = self.LayerNorm(hidden_states + input_tensor)
  202. return hidden_states
  203. class BertAttention(nn.Module):
  204. def __init__(self, config, is_cross_attention=False, layer_num=-1):
  205. super().__init__()
  206. if is_cross_attention:
  207. self.self0 = BertSelfAttention(config, is_cross_attention)
  208. self.self1 = BertSelfAttention(config, is_cross_attention)
  209. else:
  210. self.self = BertSelfAttention(config, is_cross_attention)
  211. self.output = BertSelfOutput(config, twin=is_cross_attention, merge=(is_cross_attention and layer_num>=6))
  212. self.pruned_heads = set()
  213. def prune_heads(self, heads):
  214. if len(heads) == 0:
  215. return
  216. heads, index = find_pruneable_heads_and_indices(
  217. heads, self.self.num_attention_heads, self.self.attention_head_size, self.pruned_heads
  218. )
  219. # Prune linear layers
  220. self.self.query = prune_linear_layer(self.self.query, index)
  221. self.self.key = prune_linear_layer(self.self.key, index)
  222. self.self.value = prune_linear_layer(self.self.value, index)
  223. self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
  224. # Update hyper params and store pruned heads
  225. self.self.num_attention_heads = self.self.num_attention_heads - len(heads)
  226. self.self.all_head_size = self.self.attention_head_size * self.self.num_attention_heads
  227. self.pruned_heads = self.pruned_heads.union(heads)
  228. def forward(
  229. self,
  230. hidden_states,
  231. attention_mask=None,
  232. head_mask=None,
  233. encoder_hidden_states=None,
  234. encoder_attention_mask=None,
  235. past_key_value=None,
  236. output_attentions=False,
  237. ):
  238. if type(encoder_hidden_states)==list:
  239. self_outputs0 = self.self0(
  240. hidden_states,
  241. attention_mask,
  242. head_mask,
  243. encoder_hidden_states[0],
  244. encoder_attention_mask[0],
  245. past_key_value,
  246. output_attentions,
  247. )
  248. self_outputs1 = self.self1(
  249. hidden_states,
  250. attention_mask,
  251. head_mask,
  252. encoder_hidden_states[1],
  253. encoder_attention_mask[1],
  254. past_key_value,
  255. output_attentions,
  256. )
  257. attention_output = self.output([self_outputs0[0],self_outputs1[0]], hidden_states)
  258. outputs = (attention_output,) + self_outputs0[1:] # add attentions if we output them
  259. else:
  260. self_outputs = self.self(
  261. hidden_states,
  262. attention_mask,
  263. head_mask,
  264. encoder_hidden_states,
  265. encoder_attention_mask,
  266. past_key_value,
  267. output_attentions,
  268. )
  269. attention_output = self.output(self_outputs[0], hidden_states)
  270. outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
  271. return outputs
  272. class BertIntermediate(nn.Module):
  273. def __init__(self, config):
  274. super().__init__()
  275. self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
  276. if isinstance(config.hidden_act, str):
  277. self.intermediate_act_fn = ACT2FN[config.hidden_act]
  278. else:
  279. self.intermediate_act_fn = config.hidden_act
  280. def forward(self, hidden_states):
  281. hidden_states = self.dense(hidden_states)
  282. hidden_states = self.intermediate_act_fn(hidden_states)
  283. return hidden_states
  284. class BertOutput(nn.Module):
  285. def __init__(self, config):
  286. super().__init__()
  287. self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
  288. self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
  289. self.dropout = nn.Dropout(config.hidden_dropout_prob)
  290. def forward(self, hidden_states, input_tensor):
  291. hidden_states = self.dense(hidden_states)
  292. hidden_states = self.dropout(hidden_states)
  293. hidden_states = self.LayerNorm(hidden_states + input_tensor)
  294. return hidden_states
  295. class BertLayer(nn.Module):
  296. def __init__(self, config, layer_num):
  297. super().__init__()
  298. self.config = config
  299. self.chunk_size_feed_forward = config.chunk_size_feed_forward
  300. self.seq_len_dim = 1
  301. self.attention = BertAttention(config)
  302. self.layer_num = layer_num
  303. if self.config.add_cross_attention:
  304. self.crossattention = BertAttention(config, is_cross_attention=self.config.add_cross_attention, layer_num=layer_num)
  305. self.intermediate = BertIntermediate(config)
  306. self.output = BertOutput(config)
  307. def forward(
  308. self,
  309. hidden_states,
  310. attention_mask=None,
  311. head_mask=None,
  312. encoder_hidden_states=None,
  313. encoder_attention_mask=None,
  314. past_key_value=None,
  315. output_attentions=False,
  316. mode=None,
  317. ):
  318. # decoder uni-directional self-attention cached key/values tuple is at positions 1,2
  319. self_attn_past_key_value = past_key_value[:2] if past_key_value is not None else None
  320. self_attention_outputs = self.attention(
  321. hidden_states,
  322. attention_mask,
  323. head_mask,
  324. output_attentions=output_attentions,
  325. past_key_value=self_attn_past_key_value,
  326. )
  327. attention_output = self_attention_outputs[0]
  328. outputs = self_attention_outputs[1:-1]
  329. present_key_value = self_attention_outputs[-1]
  330. if mode=='multimodal':
  331. assert encoder_hidden_states is not None, "encoder_hidden_states must be given for cross-attention layers"
  332. cross_attention_outputs = self.crossattention(
  333. attention_output,
  334. attention_mask,
  335. head_mask,
  336. encoder_hidden_states,
  337. encoder_attention_mask,
  338. output_attentions=output_attentions,
  339. )
  340. attention_output = cross_attention_outputs[0]
  341. outputs = outputs + cross_attention_outputs[1:-1] # add cross attentions if we output attention weights
  342. layer_output = apply_chunking_to_forward(
  343. self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, attention_output
  344. )
  345. outputs = (layer_output,) + outputs
  346. outputs = outputs + (present_key_value,)
  347. return outputs
  348. def feed_forward_chunk(self, attention_output):
  349. intermediate_output = self.intermediate(attention_output)
  350. layer_output = self.output(intermediate_output, attention_output)
  351. return layer_output
  352. class BertEncoder(nn.Module):
  353. def __init__(self, config):
  354. super().__init__()
  355. self.config = config
  356. self.layer = nn.ModuleList([BertLayer(config,i) for i in range(config.num_hidden_layers)])
  357. self.gradient_checkpointing = False
  358. def forward(
  359. self,
  360. hidden_states,
  361. attention_mask=None,
  362. head_mask=None,
  363. encoder_hidden_states=None,
  364. encoder_attention_mask=None,
  365. past_key_values=None,
  366. use_cache=None,
  367. output_attentions=False,
  368. output_hidden_states=False,
  369. return_dict=True,
  370. mode='multimodal',
  371. ):
  372. all_hidden_states = () if output_hidden_states else None
  373. all_self_attentions = () if output_attentions else None
  374. all_cross_attentions = () if output_attentions and self.config.add_cross_attention else None
  375. next_decoder_cache = () if use_cache else None
  376. for i in range(self.config.num_hidden_layers):
  377. layer_module = self.layer[i]
  378. if output_hidden_states:
  379. all_hidden_states = all_hidden_states + (hidden_states,)
  380. layer_head_mask = head_mask[i] if head_mask is not None else None
  381. past_key_value = past_key_values[i] if past_key_values is not None else None
  382. if self.gradient_checkpointing and self.training:
  383. if use_cache:
  384. logger.warn(
  385. "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
  386. )
  387. use_cache = False
  388. def create_custom_forward(module):
  389. def custom_forward(*inputs):
  390. return module(*inputs, past_key_value, output_attentions)
  391. return custom_forward
  392. layer_outputs = torch.utils.checkpoint.checkpoint(
  393. create_custom_forward(layer_module),
  394. hidden_states,
  395. attention_mask,
  396. layer_head_mask,
  397. encoder_hidden_states,
  398. encoder_attention_mask,
  399. mode=mode,
  400. )
  401. else:
  402. layer_outputs = layer_module(
  403. hidden_states,
  404. attention_mask,
  405. layer_head_mask,
  406. encoder_hidden_states,
  407. encoder_attention_mask,
  408. past_key_value,
  409. output_attentions,
  410. mode=mode,
  411. )
  412. hidden_states = layer_outputs[0]
  413. if use_cache:
  414. next_decoder_cache += (layer_outputs[-1],)
  415. if output_attentions:
  416. all_self_attentions = all_self_attentions + (layer_outputs[1],)
  417. if output_hidden_states:
  418. all_hidden_states = all_hidden_states + (hidden_states,)
  419. if not return_dict:
  420. return tuple(
  421. v
  422. for v in [
  423. hidden_states,
  424. next_decoder_cache,
  425. all_hidden_states,
  426. all_self_attentions,
  427. all_cross_attentions,
  428. ]
  429. if v is not None
  430. )
  431. return BaseModelOutputWithPastAndCrossAttentions(
  432. last_hidden_state=hidden_states,
  433. past_key_values=next_decoder_cache,
  434. hidden_states=all_hidden_states,
  435. attentions=all_self_attentions,
  436. cross_attentions=all_cross_attentions,
  437. )
  438. class BertPooler(nn.Module):
  439. def __init__(self, config):
  440. super().__init__()
  441. self.dense = nn.Linear(config.hidden_size, config.hidden_size)
  442. self.activation = nn.Tanh()
  443. def forward(self, hidden_states):
  444. # We "pool" the model by simply taking the hidden state corresponding
  445. # to the first token.
  446. first_token_tensor = hidden_states[:, 0]
  447. pooled_output = self.dense(first_token_tensor)
  448. pooled_output = self.activation(pooled_output)
  449. return pooled_output
  450. class BertPredictionHeadTransform(nn.Module):
  451. def __init__(self, config):
  452. super().__init__()
  453. self.dense = nn.Linear(config.hidden_size, config.hidden_size)
  454. if isinstance(config.hidden_act, str):
  455. self.transform_act_fn = ACT2FN[config.hidden_act]
  456. else:
  457. self.transform_act_fn = config.hidden_act
  458. self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
  459. def forward(self, hidden_states):
  460. hidden_states = self.dense(hidden_states)
  461. hidden_states = self.transform_act_fn(hidden_states)
  462. hidden_states = self.LayerNorm(hidden_states)
  463. return hidden_states
  464. class BertLMPredictionHead(nn.Module):
  465. def __init__(self, config):
  466. super().__init__()
  467. self.transform = BertPredictionHeadTransform(config)
  468. # The output weights are the same as the input embeddings, but there is
  469. # an output-only bias for each token.
  470. self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
  471. self.bias = nn.Parameter(torch.zeros(config.vocab_size))
  472. # Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings`
  473. self.decoder.bias = self.bias
  474. def forward(self, hidden_states):
  475. hidden_states = self.transform(hidden_states)
  476. hidden_states = self.decoder(hidden_states)
  477. return hidden_states
  478. class BertOnlyMLMHead(nn.Module):
  479. def __init__(self, config):
  480. super().__init__()
  481. self.predictions = BertLMPredictionHead(config)
  482. def forward(self, sequence_output):
  483. prediction_scores = self.predictions(sequence_output)
  484. return prediction_scores
  485. class BertPreTrainedModel(PreTrainedModel):
  486. """
  487. An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
  488. models.
  489. """
  490. config_class = BertConfig
  491. base_model_prefix = "bert"
  492. _keys_to_ignore_on_load_missing = [r"position_ids"]
  493. def _init_weights(self, module):
  494. """ Initialize the weights """
  495. if isinstance(module, (nn.Linear, nn.Embedding)):
  496. # Slightly different from the TF version which uses truncated_normal for initialization
  497. # cf https://github.com/pytorch/pytorch/pull/5617
  498. module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
  499. elif isinstance(module, nn.LayerNorm):
  500. module.bias.data.zero_()
  501. module.weight.data.fill_(1.0)
  502. if isinstance(module, nn.Linear) and module.bias is not None:
  503. module.bias.data.zero_()
  504. class BertModel(BertPreTrainedModel):
  505. """
  506. The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of
  507. cross-attention is added between the self-attention layers, following the architecture described in `Attention is
  508. all you need <https://arxiv.org/abs/1706.03762>`__ by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit,
  509. Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin.
  510. argument and :obj:`add_cross_attention` set to :obj:`True`; an :obj:`encoder_hidden_states` is then expected as an
  511. input to the forward pass.
  512. """
  513. def __init__(self, config, add_pooling_layer=True):
  514. super().__init__(config)
  515. self.config = config
  516. self.embeddings = BertEmbeddings(config)
  517. self.encoder = BertEncoder(config)
  518. self.pooler = BertPooler(config) if add_pooling_layer else None
  519. self.init_weights()
  520. def get_input_embeddings(self):
  521. return self.embeddings.word_embeddings
  522. def set_input_embeddings(self, value):
  523. self.embeddings.word_embeddings = value
  524. def _prune_heads(self, heads_to_prune):
  525. """
  526. Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
  527. class PreTrainedModel
  528. """
  529. for layer, heads in heads_to_prune.items():
  530. self.encoder.layer[layer].attention.prune_heads(heads)
  531. def get_extended_attention_mask(self, attention_mask: Tensor, input_shape: Tuple[int], device: device, is_decoder: bool) -> Tensor:
  532. """
  533. Makes broadcastable attention and causal masks so that future and masked tokens are ignored.
  534. Arguments:
  535. attention_mask (:obj:`torch.Tensor`):
  536. Mask with ones indicating tokens to attend to, zeros for tokens to ignore.
  537. input_shape (:obj:`Tuple[int]`):
  538. The shape of the input to the model.
  539. device: (:obj:`torch.device`):
  540. The device of the input to the model.
  541. Returns:
  542. :obj:`torch.Tensor` The extended attention mask, with a the same dtype as :obj:`attention_mask.dtype`.
  543. """
  544. # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
  545. # ourselves in which case we just need to make it broadcastable to all heads.
  546. if attention_mask.dim() == 3:
  547. extended_attention_mask = attention_mask[:, None, :, :]
  548. elif attention_mask.dim() == 2:
  549. # Provided a padding mask of dimensions [batch_size, seq_length]
  550. # - if the model is a decoder, apply a causal mask in addition to the padding mask
  551. # - if the model is an encoder, make the mask broadcastable to [batch_size, num_heads, seq_length, seq_length]
  552. if is_decoder:
  553. batch_size, seq_length = input_shape
  554. seq_ids = torch.arange(seq_length, device=device)
  555. causal_mask = seq_ids[None, None, :].repeat(batch_size, seq_length, 1) <= seq_ids[None, :, None]
  556. # in case past_key_values are used we need to add a prefix ones mask to the causal mask
  557. # causal and attention masks must have same type with pytorch version < 1.3
  558. causal_mask = causal_mask.to(attention_mask.dtype)
  559. if causal_mask.shape[1] < attention_mask.shape[1]:
  560. prefix_seq_len = attention_mask.shape[1] - causal_mask.shape[1]
  561. causal_mask = torch.cat(
  562. [
  563. torch.ones((batch_size, seq_length, prefix_seq_len), device=device, dtype=causal_mask.dtype),
  564. causal_mask,
  565. ],
  566. axis=-1,
  567. )
  568. extended_attention_mask = causal_mask[:, None, :, :] * attention_mask[:, None, None, :]
  569. else:
  570. extended_attention_mask = attention_mask[:, None, None, :]
  571. else:
  572. raise ValueError(
  573. "Wrong shape for input_ids (shape {}) or attention_mask (shape {})".format(
  574. input_shape, attention_mask.shape
  575. )
  576. )
  577. # Since attention_mask is 1.0 for positions we want to attend and 0.0 for
  578. # masked positions, this operation will create a tensor which is 0.0 for
  579. # positions we want to attend and -10000.0 for masked positions.
  580. # Since we are adding it to the raw scores before the softmax, this is
  581. # effectively the same as removing these entirely.
  582. extended_attention_mask = extended_attention_mask.to(dtype=self.dtype) # fp16 compatibility
  583. extended_attention_mask = (1.0 - extended_attention_mask) * -10000.0
  584. return extended_attention_mask
  585. def forward(
  586. self,
  587. input_ids=None,
  588. attention_mask=None,
  589. position_ids=None,
  590. head_mask=None,
  591. inputs_embeds=None,
  592. encoder_embeds=None,
  593. encoder_hidden_states=None,
  594. encoder_attention_mask=None,
  595. past_key_values=None,
  596. use_cache=None,
  597. output_attentions=None,
  598. output_hidden_states=None,
  599. return_dict=None,
  600. is_decoder=False,
  601. mode='multimodal',
  602. ):
  603. r"""
  604. encoder_hidden_states (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`, `optional`):
  605. Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
  606. the model is configured as a decoder.
  607. encoder_attention_mask (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):
  608. Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
  609. the cross-attention if the model is configured as a decoder. Mask values selected in ``[0, 1]``:
  610. - 1 for tokens that are **not masked**,
  611. - 0 for tokens that are **masked**.
  612. past_key_values (:obj:`tuple(tuple(torch.FloatTensor))` of length :obj:`config.n_layers` with each tuple having 4 tensors of shape :obj:`(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
  613. Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
  614. If :obj:`past_key_values` are used, the user can optionally input only the last :obj:`decoder_input_ids`
  615. (those that don't have their past key value states given to this model) of shape :obj:`(batch_size, 1)`
  616. instead of all :obj:`decoder_input_ids` of shape :obj:`(batch_size, sequence_length)`.
  617. use_cache (:obj:`bool`, `optional`):
  618. If set to :obj:`True`, :obj:`past_key_values` key value states are returned and can be used to speed up
  619. decoding (see :obj:`past_key_values`).
  620. """
  621. output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
  622. output_hidden_states = (
  623. output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
  624. )
  625. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  626. if is_decoder:
  627. use_cache = use_cache if use_cache is not None else self.config.use_cache
  628. else:
  629. use_cache = False
  630. if input_ids is not None and inputs_embeds is not None:
  631. raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
  632. elif input_ids is not None:
  633. input_shape = input_ids.size()
  634. batch_size, seq_length = input_shape
  635. device = input_ids.device
  636. elif inputs_embeds is not None:
  637. input_shape = inputs_embeds.size()[:-1]
  638. batch_size, seq_length = input_shape
  639. device = inputs_embeds.device
  640. elif encoder_embeds is not None:
  641. input_shape = encoder_embeds.size()[:-1]
  642. batch_size, seq_length = input_shape
  643. device = encoder_embeds.device
  644. else:
  645. raise ValueError("You have to specify either input_ids or inputs_embeds or encoder_embeds")
  646. # past_key_values_length
  647. past_key_values_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0
  648. if attention_mask is None:
  649. attention_mask = torch.ones(((batch_size, seq_length + past_key_values_length)), device=device)
  650. # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
  651. # ourselves in which case we just need to make it broadcastable to all heads.
  652. extended_attention_mask: torch.Tensor = self.get_extended_attention_mask(attention_mask, input_shape,
  653. device, is_decoder)
  654. # If a 2D or 3D attention mask is provided for the cross-attention
  655. # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
  656. if encoder_hidden_states is not None:
  657. if type(encoder_hidden_states) == list:
  658. encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states[0].size()
  659. else:
  660. encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size()
  661. encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
  662. if type(encoder_attention_mask) == list:
  663. encoder_extended_attention_mask = [self.invert_attention_mask(mask) for mask in encoder_attention_mask]
  664. elif encoder_attention_mask is None:
  665. encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device)
  666. encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask)
  667. else:
  668. encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask)
  669. else:
  670. encoder_extended_attention_mask = None
  671. # Prepare head mask if needed
  672. # 1.0 in head_mask indicate we keep the head
  673. # attention_probs has shape bsz x n_heads x N x N
  674. # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
  675. # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
  676. head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
  677. if encoder_embeds is None:
  678. embedding_output = self.embeddings(
  679. input_ids=input_ids,
  680. position_ids=position_ids,
  681. inputs_embeds=inputs_embeds,
  682. past_key_values_length=past_key_values_length,
  683. )
  684. else:
  685. embedding_output = encoder_embeds
  686. encoder_outputs = self.encoder(
  687. embedding_output,
  688. attention_mask=extended_attention_mask,
  689. head_mask=head_mask,
  690. encoder_hidden_states=encoder_hidden_states,
  691. encoder_attention_mask=encoder_extended_attention_mask,
  692. past_key_values=past_key_values,
  693. use_cache=use_cache,
  694. output_attentions=output_attentions,
  695. output_hidden_states=output_hidden_states,
  696. return_dict=return_dict,
  697. mode=mode,
  698. )
  699. sequence_output = encoder_outputs[0]
  700. pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
  701. if not return_dict:
  702. return (sequence_output, pooled_output) + encoder_outputs[1:]
  703. return BaseModelOutputWithPoolingAndCrossAttentions(
  704. last_hidden_state=sequence_output,
  705. pooler_output=pooled_output,
  706. past_key_values=encoder_outputs.past_key_values,
  707. hidden_states=encoder_outputs.hidden_states,
  708. attentions=encoder_outputs.attentions,
  709. cross_attentions=encoder_outputs.cross_attentions,
  710. )