modeling_data2vec_text.py 69 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541
  1. # coding=utf-8
  2. # Copyright 2022 The HuggingFace Inc. team.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. """PyTorch Data2VecText model."""
  16. import math
  17. from typing import List, Optional, Tuple, Union
  18. import torch
  19. import torch.utils.checkpoint
  20. from torch import nn
  21. from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
  22. from ...activations import ACT2FN, gelu
  23. from ...generation import GenerationMixin
  24. from ...modeling_outputs import (
  25. BaseModelOutputWithPastAndCrossAttentions,
  26. BaseModelOutputWithPoolingAndCrossAttentions,
  27. CausalLMOutputWithCrossAttentions,
  28. MaskedLMOutput,
  29. MultipleChoiceModelOutput,
  30. QuestionAnsweringModelOutput,
  31. SequenceClassifierOutput,
  32. TokenClassifierOutput,
  33. )
  34. from ...modeling_utils import PreTrainedModel
  35. from ...pytorch_utils import apply_chunking_to_forward, find_pruneable_heads_and_indices, prune_linear_layer
  36. from ...utils import (
  37. add_code_sample_docstrings,
  38. add_start_docstrings,
  39. add_start_docstrings_to_model_forward,
  40. logging,
  41. replace_return_docstrings,
  42. )
  43. from .configuration_data2vec_text import Data2VecTextConfig
  44. logger = logging.get_logger(__name__)
  45. _HIDDEN_STATES_START_POSITION = 2
  46. # General docstring
  47. _CHECKPOINT_FOR_DOC = "facebook/data2vec-text-base"
  48. _CONFIG_FOR_DOC = "Data2VecTextConfig"
  49. # Copied from transformers.models.roberta.modeling_roberta.RobertaEmbeddings with Roberta->Data2VecText
  50. class Data2VecTextForTextEmbeddings(nn.Module):
  51. """
  52. Same as BertEmbeddings with a tiny tweak for positional embeddings indexing.
  53. """
  54. # Copied from transformers.models.bert.modeling_bert.BertEmbeddings.__init__
  55. def __init__(self, config):
  56. super().__init__()
  57. self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
  58. self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)
  59. self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)
  60. # self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load
  61. # any TensorFlow checkpoint file
  62. self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
  63. self.dropout = nn.Dropout(config.hidden_dropout_prob)
  64. # position_ids (1, len position emb) is contiguous in memory and exported when serialized
  65. self.position_embedding_type = getattr(config, "position_embedding_type", "absolute")
  66. self.register_buffer(
  67. "position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
  68. )
  69. self.register_buffer(
  70. "token_type_ids", torch.zeros(self.position_ids.size(), dtype=torch.long), persistent=False
  71. )
  72. # End copy
  73. self.padding_idx = config.pad_token_id
  74. self.position_embeddings = nn.Embedding(
  75. config.max_position_embeddings, config.hidden_size, padding_idx=self.padding_idx
  76. )
  77. def forward(
  78. self, input_ids=None, token_type_ids=None, position_ids=None, inputs_embeds=None, past_key_values_length=0
  79. ):
  80. if position_ids is None:
  81. if input_ids is not None:
  82. # Create the position ids from the input token ids. Any padded tokens remain padded.
  83. position_ids = create_position_ids_from_input_ids(input_ids, self.padding_idx, past_key_values_length)
  84. else:
  85. position_ids = self.create_position_ids_from_inputs_embeds(inputs_embeds)
  86. if input_ids is not None:
  87. input_shape = input_ids.size()
  88. else:
  89. input_shape = inputs_embeds.size()[:-1]
  90. seq_length = input_shape[1]
  91. # Setting the token_type_ids to the registered buffer in constructor where it is all zeros, which usually occurs
  92. # when its auto-generated, registered buffer helps users when tracing the model without passing token_type_ids, solves
  93. # issue #5664
  94. if token_type_ids is None:
  95. if hasattr(self, "token_type_ids"):
  96. buffered_token_type_ids = self.token_type_ids[:, :seq_length]
  97. buffered_token_type_ids_expanded = buffered_token_type_ids.expand(input_shape[0], seq_length)
  98. token_type_ids = buffered_token_type_ids_expanded
  99. else:
  100. token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)
  101. if inputs_embeds is None:
  102. inputs_embeds = self.word_embeddings(input_ids)
  103. token_type_embeddings = self.token_type_embeddings(token_type_ids)
  104. embeddings = inputs_embeds + token_type_embeddings
  105. if self.position_embedding_type == "absolute":
  106. position_embeddings = self.position_embeddings(position_ids)
  107. embeddings += position_embeddings
  108. embeddings = self.LayerNorm(embeddings)
  109. embeddings = self.dropout(embeddings)
  110. return embeddings
  111. def create_position_ids_from_inputs_embeds(self, inputs_embeds):
  112. """
  113. We are provided embeddings directly. We cannot infer which are padded so just generate sequential position ids.
  114. Args:
  115. inputs_embeds: torch.Tensor
  116. Returns: torch.Tensor
  117. """
  118. input_shape = inputs_embeds.size()[:-1]
  119. sequence_length = input_shape[1]
  120. position_ids = torch.arange(
  121. self.padding_idx + 1, sequence_length + self.padding_idx + 1, dtype=torch.long, device=inputs_embeds.device
  122. )
  123. return position_ids.unsqueeze(0).expand(input_shape)
  124. # Copied from transformers.models.roberta.modeling_roberta.RobertaSelfAttention with Roberta->Data2VecText
  125. class Data2VecTextSelfAttention(nn.Module):
  126. def __init__(self, config, position_embedding_type=None):
  127. super().__init__()
  128. if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
  129. raise ValueError(
  130. f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
  131. f"heads ({config.num_attention_heads})"
  132. )
  133. self.num_attention_heads = config.num_attention_heads
  134. self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
  135. self.all_head_size = self.num_attention_heads * self.attention_head_size
  136. self.query = nn.Linear(config.hidden_size, self.all_head_size)
  137. self.key = nn.Linear(config.hidden_size, self.all_head_size)
  138. self.value = nn.Linear(config.hidden_size, self.all_head_size)
  139. self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
  140. self.position_embedding_type = position_embedding_type or getattr(
  141. config, "position_embedding_type", "absolute"
  142. )
  143. if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
  144. self.max_position_embeddings = config.max_position_embeddings
  145. self.distance_embedding = nn.Embedding(2 * config.max_position_embeddings - 1, self.attention_head_size)
  146. self.is_decoder = config.is_decoder
  147. def transpose_for_scores(self, x: torch.Tensor) -> torch.Tensor:
  148. new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
  149. x = x.view(new_x_shape)
  150. return x.permute(0, 2, 1, 3)
  151. def forward(
  152. self,
  153. hidden_states: torch.Tensor,
  154. attention_mask: Optional[torch.FloatTensor] = None,
  155. head_mask: Optional[torch.FloatTensor] = None,
  156. encoder_hidden_states: Optional[torch.FloatTensor] = None,
  157. encoder_attention_mask: Optional[torch.FloatTensor] = None,
  158. past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
  159. output_attentions: Optional[bool] = False,
  160. ) -> Tuple[torch.Tensor]:
  161. mixed_query_layer = self.query(hidden_states)
  162. # If this is instantiated as a cross-attention module, the keys
  163. # and values come from an encoder; the attention mask needs to be
  164. # such that the encoder's padding tokens are not attended to.
  165. is_cross_attention = encoder_hidden_states is not None
  166. if is_cross_attention and past_key_value is not None:
  167. # reuse k,v, cross_attentions
  168. key_layer = past_key_value[0]
  169. value_layer = past_key_value[1]
  170. attention_mask = encoder_attention_mask
  171. elif is_cross_attention:
  172. key_layer = self.transpose_for_scores(self.key(encoder_hidden_states))
  173. value_layer = self.transpose_for_scores(self.value(encoder_hidden_states))
  174. attention_mask = encoder_attention_mask
  175. elif past_key_value is not None:
  176. key_layer = self.transpose_for_scores(self.key(hidden_states))
  177. value_layer = self.transpose_for_scores(self.value(hidden_states))
  178. key_layer = torch.cat([past_key_value[0], key_layer], dim=2)
  179. value_layer = torch.cat([past_key_value[1], value_layer], dim=2)
  180. else:
  181. key_layer = self.transpose_for_scores(self.key(hidden_states))
  182. value_layer = self.transpose_for_scores(self.value(hidden_states))
  183. query_layer = self.transpose_for_scores(mixed_query_layer)
  184. use_cache = past_key_value is not None
  185. if self.is_decoder:
  186. # if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states.
  187. # Further calls to cross_attention layer can then reuse all cross-attention
  188. # key/value_states (first "if" case)
  189. # if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of
  190. # all previous decoder key/value_states. Further calls to uni-directional self-attention
  191. # can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
  192. # if encoder bi-directional self-attention `past_key_value` is always `None`
  193. past_key_value = (key_layer, value_layer)
  194. # Take the dot product between "query" and "key" to get the raw attention scores.
  195. attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
  196. if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query":
  197. query_length, key_length = query_layer.shape[2], key_layer.shape[2]
  198. if use_cache:
  199. position_ids_l = torch.tensor(key_length - 1, dtype=torch.long, device=hidden_states.device).view(
  200. -1, 1
  201. )
  202. else:
  203. position_ids_l = torch.arange(query_length, dtype=torch.long, device=hidden_states.device).view(-1, 1)
  204. position_ids_r = torch.arange(key_length, dtype=torch.long, device=hidden_states.device).view(1, -1)
  205. distance = position_ids_l - position_ids_r
  206. positional_embedding = self.distance_embedding(distance + self.max_position_embeddings - 1)
  207. positional_embedding = positional_embedding.to(dtype=query_layer.dtype) # fp16 compatibility
  208. if self.position_embedding_type == "relative_key":
  209. relative_position_scores = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
  210. attention_scores = attention_scores + relative_position_scores
  211. elif self.position_embedding_type == "relative_key_query":
  212. relative_position_scores_query = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding)
  213. relative_position_scores_key = torch.einsum("bhrd,lrd->bhlr", key_layer, positional_embedding)
  214. attention_scores = attention_scores + relative_position_scores_query + relative_position_scores_key
  215. attention_scores = attention_scores / math.sqrt(self.attention_head_size)
  216. if attention_mask is not None:
  217. # Apply the attention mask is (precomputed for all layers in Data2VecTextModel forward() function)
  218. attention_scores = attention_scores + attention_mask
  219. # Normalize the attention scores to probabilities.
  220. attention_probs = nn.functional.softmax(attention_scores, dim=-1)
  221. # This is actually dropping out entire tokens to attend to, which might
  222. # seem a bit unusual, but is taken from the original Transformer paper.
  223. attention_probs = self.dropout(attention_probs)
  224. # Mask heads if we want to
  225. if head_mask is not None:
  226. attention_probs = attention_probs * head_mask
  227. context_layer = torch.matmul(attention_probs, value_layer)
  228. context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
  229. new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
  230. context_layer = context_layer.view(new_context_layer_shape)
  231. outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
  232. if self.is_decoder:
  233. outputs = outputs + (past_key_value,)
  234. return outputs
  235. # Copied from transformers.models.bert.modeling_bert.BertSelfOutput
  236. class Data2VecTextSelfOutput(nn.Module):
  237. def __init__(self, config):
  238. super().__init__()
  239. self.dense = nn.Linear(config.hidden_size, config.hidden_size)
  240. self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
  241. self.dropout = nn.Dropout(config.hidden_dropout_prob)
  242. def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
  243. hidden_states = self.dense(hidden_states)
  244. hidden_states = self.dropout(hidden_states)
  245. hidden_states = self.LayerNorm(hidden_states + input_tensor)
  246. return hidden_states
  247. DATA2VEC_TEXT_SELF_ATTENTION_CLASSES = {
  248. "eager": Data2VecTextSelfAttention,
  249. }
  250. # Copied from transformers.models.bert.modeling_bert.BertAttention with Bert->Data2VecText,BERT->DATA2VEC_TEXT
  251. class Data2VecTextAttention(nn.Module):
  252. def __init__(self, config, position_embedding_type=None):
  253. super().__init__()
  254. self.self = DATA2VEC_TEXT_SELF_ATTENTION_CLASSES[config._attn_implementation](
  255. config, position_embedding_type=position_embedding_type
  256. )
  257. self.output = Data2VecTextSelfOutput(config)
  258. self.pruned_heads = set()
  259. def prune_heads(self, heads):
  260. if len(heads) == 0:
  261. return
  262. heads, index = find_pruneable_heads_and_indices(
  263. heads, self.self.num_attention_heads, self.self.attention_head_size, self.pruned_heads
  264. )
  265. # Prune linear layers
  266. self.self.query = prune_linear_layer(self.self.query, index)
  267. self.self.key = prune_linear_layer(self.self.key, index)
  268. self.self.value = prune_linear_layer(self.self.value, index)
  269. self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
  270. # Update hyper params and store pruned heads
  271. self.self.num_attention_heads = self.self.num_attention_heads - len(heads)
  272. self.self.all_head_size = self.self.attention_head_size * self.self.num_attention_heads
  273. self.pruned_heads = self.pruned_heads.union(heads)
  274. def forward(
  275. self,
  276. hidden_states: torch.Tensor,
  277. attention_mask: Optional[torch.FloatTensor] = None,
  278. head_mask: Optional[torch.FloatTensor] = None,
  279. encoder_hidden_states: Optional[torch.FloatTensor] = None,
  280. encoder_attention_mask: Optional[torch.FloatTensor] = None,
  281. past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
  282. output_attentions: Optional[bool] = False,
  283. ) -> Tuple[torch.Tensor]:
  284. self_outputs = self.self(
  285. hidden_states,
  286. attention_mask,
  287. head_mask,
  288. encoder_hidden_states,
  289. encoder_attention_mask,
  290. past_key_value,
  291. output_attentions,
  292. )
  293. attention_output = self.output(self_outputs[0], hidden_states)
  294. outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
  295. return outputs
  296. # Copied from transformers.models.bert.modeling_bert.BertIntermediate
  297. class Data2VecTextIntermediate(nn.Module):
  298. def __init__(self, config):
  299. super().__init__()
  300. self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
  301. if isinstance(config.hidden_act, str):
  302. self.intermediate_act_fn = ACT2FN[config.hidden_act]
  303. else:
  304. self.intermediate_act_fn = config.hidden_act
  305. def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
  306. hidden_states = self.dense(hidden_states)
  307. hidden_states = self.intermediate_act_fn(hidden_states)
  308. return hidden_states
  309. # Copied from transformers.models.bert.modeling_bert.BertOutput
  310. class Data2VecTextOutput(nn.Module):
  311. def __init__(self, config):
  312. super().__init__()
  313. self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
  314. self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
  315. self.dropout = nn.Dropout(config.hidden_dropout_prob)
  316. def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
  317. hidden_states = self.dense(hidden_states)
  318. hidden_states = self.dropout(hidden_states)
  319. hidden_states = self.LayerNorm(hidden_states + input_tensor)
  320. return hidden_states
  321. # Copied from transformers.models.bert.modeling_bert.BertLayer with Bert->Data2VecText
  322. class Data2VecTextLayer(nn.Module):
  323. def __init__(self, config):
  324. super().__init__()
  325. self.chunk_size_feed_forward = config.chunk_size_feed_forward
  326. self.seq_len_dim = 1
  327. self.attention = Data2VecTextAttention(config)
  328. self.is_decoder = config.is_decoder
  329. self.add_cross_attention = config.add_cross_attention
  330. if self.add_cross_attention:
  331. if not self.is_decoder:
  332. raise ValueError(f"{self} should be used as a decoder model if cross attention is added")
  333. self.crossattention = Data2VecTextAttention(config, position_embedding_type="absolute")
  334. self.intermediate = Data2VecTextIntermediate(config)
  335. self.output = Data2VecTextOutput(config)
  336. def forward(
  337. self,
  338. hidden_states: torch.Tensor,
  339. attention_mask: Optional[torch.FloatTensor] = None,
  340. head_mask: Optional[torch.FloatTensor] = None,
  341. encoder_hidden_states: Optional[torch.FloatTensor] = None,
  342. encoder_attention_mask: Optional[torch.FloatTensor] = None,
  343. past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
  344. output_attentions: Optional[bool] = False,
  345. ) -> Tuple[torch.Tensor]:
  346. # decoder uni-directional self-attention cached key/values tuple is at positions 1,2
  347. self_attn_past_key_value = past_key_value[:2] if past_key_value is not None else None
  348. self_attention_outputs = self.attention(
  349. hidden_states,
  350. attention_mask,
  351. head_mask,
  352. output_attentions=output_attentions,
  353. past_key_value=self_attn_past_key_value,
  354. )
  355. attention_output = self_attention_outputs[0]
  356. # if decoder, the last output is tuple of self-attn cache
  357. if self.is_decoder:
  358. outputs = self_attention_outputs[1:-1]
  359. present_key_value = self_attention_outputs[-1]
  360. else:
  361. outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
  362. cross_attn_present_key_value = None
  363. if self.is_decoder and encoder_hidden_states is not None:
  364. if not hasattr(self, "crossattention"):
  365. raise ValueError(
  366. f"If `encoder_hidden_states` are passed, {self} has to be instantiated with cross-attention layers"
  367. " by setting `config.add_cross_attention=True`"
  368. )
  369. # cross_attn cached key/values tuple is at positions 3,4 of past_key_value tuple
  370. cross_attn_past_key_value = past_key_value[-2:] if past_key_value is not None else None
  371. cross_attention_outputs = self.crossattention(
  372. attention_output,
  373. attention_mask,
  374. head_mask,
  375. encoder_hidden_states,
  376. encoder_attention_mask,
  377. cross_attn_past_key_value,
  378. output_attentions,
  379. )
  380. attention_output = cross_attention_outputs[0]
  381. outputs = outputs + cross_attention_outputs[1:-1] # add cross attentions if we output attention weights
  382. # add cross-attn cache to positions 3,4 of present_key_value tuple
  383. cross_attn_present_key_value = cross_attention_outputs[-1]
  384. present_key_value = present_key_value + cross_attn_present_key_value
  385. layer_output = apply_chunking_to_forward(
  386. self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, attention_output
  387. )
  388. outputs = (layer_output,) + outputs
  389. # if decoder, return the attn key/values as the last output
  390. if self.is_decoder:
  391. outputs = outputs + (present_key_value,)
  392. return outputs
  393. def feed_forward_chunk(self, attention_output):
  394. intermediate_output = self.intermediate(attention_output)
  395. layer_output = self.output(intermediate_output, attention_output)
  396. return layer_output
  397. # Copied from transformers.models.bert.modeling_bert.BertEncoder with Bert->Data2VecText
  398. class Data2VecTextEncoder(nn.Module):
  399. def __init__(self, config):
  400. super().__init__()
  401. self.config = config
  402. self.layer = nn.ModuleList([Data2VecTextLayer(config) for _ in range(config.num_hidden_layers)])
  403. self.gradient_checkpointing = False
  404. def forward(
  405. self,
  406. hidden_states: torch.Tensor,
  407. attention_mask: Optional[torch.FloatTensor] = None,
  408. head_mask: Optional[torch.FloatTensor] = None,
  409. encoder_hidden_states: Optional[torch.FloatTensor] = None,
  410. encoder_attention_mask: Optional[torch.FloatTensor] = None,
  411. past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
  412. use_cache: Optional[bool] = None,
  413. output_attentions: Optional[bool] = False,
  414. output_hidden_states: Optional[bool] = False,
  415. return_dict: Optional[bool] = True,
  416. ) -> Union[Tuple[torch.Tensor], BaseModelOutputWithPastAndCrossAttentions]:
  417. all_hidden_states = () if output_hidden_states else None
  418. all_self_attentions = () if output_attentions else None
  419. all_cross_attentions = () if output_attentions and self.config.add_cross_attention else None
  420. if self.gradient_checkpointing and self.training:
  421. if use_cache:
  422. logger.warning_once(
  423. "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
  424. )
  425. use_cache = False
  426. next_decoder_cache = () if use_cache else None
  427. for i, layer_module in enumerate(self.layer):
  428. if output_hidden_states:
  429. all_hidden_states = all_hidden_states + (hidden_states,)
  430. layer_head_mask = head_mask[i] if head_mask is not None else None
  431. past_key_value = past_key_values[i] if past_key_values is not None else None
  432. if self.gradient_checkpointing and self.training:
  433. layer_outputs = self._gradient_checkpointing_func(
  434. layer_module.__call__,
  435. hidden_states,
  436. attention_mask,
  437. layer_head_mask,
  438. encoder_hidden_states,
  439. encoder_attention_mask,
  440. past_key_value,
  441. output_attentions,
  442. )
  443. else:
  444. layer_outputs = layer_module(
  445. hidden_states,
  446. attention_mask,
  447. layer_head_mask,
  448. encoder_hidden_states,
  449. encoder_attention_mask,
  450. past_key_value,
  451. output_attentions,
  452. )
  453. hidden_states = layer_outputs[0]
  454. if use_cache:
  455. next_decoder_cache += (layer_outputs[-1],)
  456. if output_attentions:
  457. all_self_attentions = all_self_attentions + (layer_outputs[1],)
  458. if self.config.add_cross_attention:
  459. all_cross_attentions = all_cross_attentions + (layer_outputs[2],)
  460. if output_hidden_states:
  461. all_hidden_states = all_hidden_states + (hidden_states,)
  462. if not return_dict:
  463. return tuple(
  464. v
  465. for v in [
  466. hidden_states,
  467. next_decoder_cache,
  468. all_hidden_states,
  469. all_self_attentions,
  470. all_cross_attentions,
  471. ]
  472. if v is not None
  473. )
  474. return BaseModelOutputWithPastAndCrossAttentions(
  475. last_hidden_state=hidden_states,
  476. past_key_values=next_decoder_cache,
  477. hidden_states=all_hidden_states,
  478. attentions=all_self_attentions,
  479. cross_attentions=all_cross_attentions,
  480. )
  481. # Copied from transformers.models.bert.modeling_bert.BertPooler
  482. class Data2VecTextPooler(nn.Module):
  483. def __init__(self, config):
  484. super().__init__()
  485. self.dense = nn.Linear(config.hidden_size, config.hidden_size)
  486. self.activation = nn.Tanh()
  487. def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
  488. # We "pool" the model by simply taking the hidden state corresponding
  489. # to the first token.
  490. first_token_tensor = hidden_states[:, 0]
  491. pooled_output = self.dense(first_token_tensor)
  492. pooled_output = self.activation(pooled_output)
  493. return pooled_output
  494. class Data2VecTextPreTrainedModel(PreTrainedModel):
  495. """
  496. An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
  497. models.
  498. """
  499. config_class = Data2VecTextConfig
  500. base_model_prefix = "data2vec_text"
  501. supports_gradient_checkpointing = True
  502. _no_split_modules = ["Data2VecTextForTextEmbeddings", "Data2VecTextLayer"]
  503. def _init_weights(self, module):
  504. """Initialize the weights"""
  505. if isinstance(module, nn.Linear):
  506. # Slightly different from the TF version which uses truncated_normal for initialization
  507. # cf https://github.com/pytorch/pytorch/pull/5617
  508. module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
  509. if module.bias is not None:
  510. module.bias.data.zero_()
  511. elif isinstance(module, nn.Embedding):
  512. module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
  513. if module.padding_idx is not None:
  514. module.weight.data[module.padding_idx].zero_()
  515. elif isinstance(module, nn.LayerNorm):
  516. if hasattr(module, "bias") and module.bias is not None:
  517. module.bias.data.zero_()
  518. if hasattr(module, "weight") and module.weight is not None:
  519. module.weight.data.fill_(1.0)
  520. DATA2VECTEXT_START_DOCSTRING = r"""
  521. Data2VecText was proposed in [data2vec: A General Framework for Self-supervised Learning in Speech, Vision and
  522. Language](https://arxiv.org/pdf/2202.03555) by Alexei Baevski, Wei-Ning Hsu, Qiantong Xu, Arun Babu, Jiatao Gu and
  523. Michael Auli.
  524. This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
  525. library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
  526. etc.)
  527. This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
  528. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
  529. and behavior.
  530. Parameters:
  531. config ([`Data2VecTextConfig`]): Model configuration class with all the parameters of the
  532. model. Initializing with a config file does not load the weights associated with the model, only the
  533. configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
  534. """
  535. DATA2VECTEXT_INPUTS_DOCSTRING = r"""
  536. Args:
  537. input_ids (`torch.LongTensor` of shape `({0})`):
  538. Indices of input sequence tokens in the vocabulary.
  539. Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
  540. [`PreTrainedTokenizer.__call__`] for details.
  541. [What are input IDs?](../glossary#input-ids)
  542. attention_mask (`torch.FloatTensor` of shape `({0})`, *optional*):
  543. Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
  544. - 1 for tokens that are **not masked**,
  545. - 0 for tokens that are **masked**.
  546. [What are attention masks?](../glossary#attention-mask)
  547. token_type_ids (`torch.LongTensor` of shape `({0})`, *optional*):
  548. Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
  549. 1]`:
  550. - 0 corresponds to a *sentence A* token,
  551. - 1 corresponds to a *sentence B* token.
  552. [What are token type IDs?](../glossary#token-type-ids)
  553. position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
  554. Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
  555. config.max_position_embeddings - 1]`.
  556. [What are position IDs?](../glossary#position-ids)
  557. head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
  558. Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
  559. - 1 indicates the head is **not masked**,
  560. - 0 indicates the head is **masked**.
  561. inputs_embeds (`torch.FloatTensor` of shape `({0}, hidden_size)`, *optional*):
  562. Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
  563. is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
  564. model's internal embedding lookup matrix.
  565. output_attentions (`bool`, *optional*):
  566. Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
  567. tensors for more detail.
  568. output_hidden_states (`bool`, *optional*):
  569. Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
  570. more detail.
  571. return_dict (`bool`, *optional*):
  572. Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
  573. """
  574. @add_start_docstrings(
  575. "The bare Data2VecText Model for text transformer outputting raw hidden-states without any specific head on top.",
  576. DATA2VECTEXT_START_DOCSTRING,
  577. )
  578. class Data2VecTextModel(Data2VecTextPreTrainedModel):
  579. """
  580. The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of
  581. cross-attention is added between the self-attention layers, following the architecture described in *Attention is
  582. all you need*_ by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Lukasz
  583. Kaiser and Illia Polosukhin.
  584. To behave as an decoder the model needs to be initialized with the `is_decoder` argument of the configuration set
  585. to `True`. To be used in a Seq2Seq model, the model needs to initialized with both `is_decoder` argument and
  586. `add_cross_attention` set to `True`; an `encoder_hidden_states` is then expected as an input to the forward pass.
  587. .. _*Attention is all you need*: https://arxiv.org/abs/1706.03762
  588. """
  589. def __init__(self, config, add_pooling_layer=True):
  590. super().__init__(config)
  591. self.config = config
  592. self.embeddings = Data2VecTextForTextEmbeddings(config)
  593. self.encoder = Data2VecTextEncoder(config)
  594. self.pooler = Data2VecTextPooler(config) if add_pooling_layer else None
  595. # Initialize weights and apply final processing
  596. self.post_init()
  597. def get_input_embeddings(self):
  598. return self.embeddings.word_embeddings
  599. def set_input_embeddings(self, value):
  600. self.embeddings.word_embeddings = value
  601. def _prune_heads(self, heads_to_prune):
  602. """
  603. Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
  604. class PreTrainedModel
  605. """
  606. for layer, heads in heads_to_prune.items():
  607. self.encoder.layer[layer].attention.prune_heads(heads)
  608. @add_start_docstrings_to_model_forward(DATA2VECTEXT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
  609. @add_code_sample_docstrings(
  610. checkpoint=_CHECKPOINT_FOR_DOC,
  611. output_type=BaseModelOutputWithPoolingAndCrossAttentions,
  612. config_class=_CONFIG_FOR_DOC,
  613. )
  614. # Copied from transformers.models.clap.modeling_clap.ClapTextModel.forward
  615. def forward(
  616. self,
  617. input_ids: Optional[torch.Tensor] = None,
  618. attention_mask: Optional[torch.Tensor] = None,
  619. token_type_ids: Optional[torch.Tensor] = None,
  620. position_ids: Optional[torch.Tensor] = None,
  621. head_mask: Optional[torch.Tensor] = None,
  622. inputs_embeds: Optional[torch.Tensor] = None,
  623. encoder_hidden_states: Optional[torch.Tensor] = None,
  624. encoder_attention_mask: Optional[torch.Tensor] = None,
  625. past_key_values: Optional[List[torch.FloatTensor]] = None,
  626. use_cache: Optional[bool] = None,
  627. output_attentions: Optional[bool] = None,
  628. output_hidden_states: Optional[bool] = None,
  629. return_dict: Optional[bool] = None,
  630. ) -> Union[Tuple[torch.Tensor], BaseModelOutputWithPoolingAndCrossAttentions]:
  631. r"""
  632. encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
  633. Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
  634. the model is configured as a decoder.
  635. encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
  636. Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
  637. the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
  638. - 1 for tokens that are **not masked**,
  639. - 0 for tokens that are **masked**.
  640. past_key_values (`tuple(tuple(torch.FloatTensor))` of length `config.n_layers` with each tuple having 4 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
  641. Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
  642. If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
  643. don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
  644. `decoder_input_ids` of shape `(batch_size, sequence_length)`.
  645. use_cache (`bool`, *optional*):
  646. If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
  647. `past_key_values`).
  648. """
  649. output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
  650. output_hidden_states = (
  651. output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
  652. )
  653. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  654. if self.config.is_decoder:
  655. use_cache = use_cache if use_cache is not None else self.config.use_cache
  656. else:
  657. use_cache = False
  658. if input_ids is not None and inputs_embeds is not None:
  659. raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
  660. elif input_ids is not None:
  661. self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
  662. input_shape = input_ids.size()
  663. elif inputs_embeds is not None:
  664. input_shape = inputs_embeds.size()[:-1]
  665. else:
  666. raise ValueError("You have to specify either input_ids or inputs_embeds")
  667. batch_size, seq_length = input_shape
  668. device = input_ids.device if input_ids is not None else inputs_embeds.device
  669. # past_key_values_length
  670. past_key_values_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0
  671. if attention_mask is None:
  672. attention_mask = torch.ones(((batch_size, seq_length + past_key_values_length)), device=device)
  673. if token_type_ids is None:
  674. if hasattr(self.embeddings, "token_type_ids"):
  675. buffered_token_type_ids = self.embeddings.token_type_ids[:, :seq_length]
  676. buffered_token_type_ids_expanded = buffered_token_type_ids.expand(batch_size, seq_length)
  677. token_type_ids = buffered_token_type_ids_expanded
  678. else:
  679. token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
  680. # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
  681. # ourselves in which case we just need to make it broadcastable to all heads.
  682. extended_attention_mask: torch.Tensor = self.get_extended_attention_mask(attention_mask, input_shape)
  683. # If a 2D or 3D attention mask is provided for the cross-attention
  684. # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
  685. if self.config.is_decoder and encoder_hidden_states is not None:
  686. encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size()
  687. encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
  688. if encoder_attention_mask is None:
  689. encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device)
  690. encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask)
  691. else:
  692. encoder_extended_attention_mask = None
  693. # Prepare head mask if needed
  694. # 1.0 in head_mask indicate we keep the head
  695. # attention_probs has shape bsz x n_heads x N x N
  696. # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
  697. # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
  698. head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
  699. embedding_output = self.embeddings(
  700. input_ids=input_ids,
  701. position_ids=position_ids,
  702. token_type_ids=token_type_ids,
  703. inputs_embeds=inputs_embeds,
  704. past_key_values_length=past_key_values_length,
  705. )
  706. encoder_outputs = self.encoder(
  707. embedding_output,
  708. attention_mask=extended_attention_mask,
  709. head_mask=head_mask,
  710. encoder_hidden_states=encoder_hidden_states,
  711. encoder_attention_mask=encoder_extended_attention_mask,
  712. past_key_values=past_key_values,
  713. use_cache=use_cache,
  714. output_attentions=output_attentions,
  715. output_hidden_states=output_hidden_states,
  716. return_dict=return_dict,
  717. )
  718. sequence_output = encoder_outputs[0]
  719. pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
  720. if not return_dict:
  721. return (sequence_output, pooled_output) + encoder_outputs[1:]
  722. return BaseModelOutputWithPoolingAndCrossAttentions(
  723. last_hidden_state=sequence_output,
  724. pooler_output=pooled_output,
  725. past_key_values=encoder_outputs.past_key_values,
  726. hidden_states=encoder_outputs.hidden_states,
  727. attentions=encoder_outputs.attentions,
  728. cross_attentions=encoder_outputs.cross_attentions,
  729. )
  730. @add_start_docstrings(
  731. """Data2VecText Model with a `language modeling` head on top for CLM fine-tuning.""", DATA2VECTEXT_START_DOCSTRING
  732. )
  733. class Data2VecTextForCausalLM(Data2VecTextPreTrainedModel, GenerationMixin):
  734. _tied_weights_keys = ["lm_head.decoder.weight", "lm_head.decoder.bias"]
  735. def __init__(self, config):
  736. super().__init__(config)
  737. if not config.is_decoder:
  738. logger.warning("If you want to use `Data2VecTextLMHeadModel` as a standalone, add `is_decoder=True.`")
  739. self.data2vec_text = Data2VecTextModel(config, add_pooling_layer=False)
  740. self.lm_head = Data2VecTextLMHead(config)
  741. # Initialize weights and apply final processing
  742. self.post_init()
  743. def get_output_embeddings(self):
  744. return self.lm_head.decoder
  745. def set_output_embeddings(self, new_embeddings):
  746. self.lm_head.decoder = new_embeddings
  747. @add_start_docstrings_to_model_forward(DATA2VECTEXT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
  748. @replace_return_docstrings(output_type=CausalLMOutputWithCrossAttentions, config_class=_CONFIG_FOR_DOC)
  749. def forward(
  750. self,
  751. input_ids: Optional[torch.LongTensor] = None,
  752. attention_mask: Optional[torch.FloatTensor] = None,
  753. token_type_ids: Optional[torch.LongTensor] = None,
  754. position_ids: Optional[torch.LongTensor] = None,
  755. head_mask: Optional[torch.FloatTensor] = None,
  756. inputs_embeds: Optional[torch.FloatTensor] = None,
  757. encoder_hidden_states: Optional[torch.FloatTensor] = None,
  758. encoder_attention_mask: Optional[torch.FloatTensor] = None,
  759. labels: Optional[torch.LongTensor] = None,
  760. past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
  761. use_cache: Optional[bool] = None,
  762. output_attentions: Optional[bool] = None,
  763. output_hidden_states: Optional[bool] = None,
  764. return_dict: Optional[bool] = None,
  765. ) -> Union[Tuple, CausalLMOutputWithCrossAttentions]:
  766. r"""
  767. encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
  768. Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
  769. the model is configured as a decoder.
  770. encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
  771. Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
  772. the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
  773. - 1 for tokens that are **not masked**,
  774. - 0 for tokens that are **masked**.
  775. labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
  776. Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in
  777. `[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are
  778. ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
  779. past_key_values (`tuple(tuple(torch.FloatTensor))` of length `config.n_layers` with each tuple having 4 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
  780. Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
  781. If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
  782. don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
  783. `decoder_input_ids` of shape `(batch_size, sequence_length)`.
  784. use_cache (`bool`, *optional*):
  785. If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
  786. `past_key_values`).
  787. Returns:
  788. Example:
  789. ```python
  790. >>> from transformers import AutoTokenizer, Data2VecTextForCausalLM, Data2VecTextConfig
  791. >>> import torch
  792. >>> tokenizer = AutoTokenizer.from_pretrained("facebook/data2vec-text-base")
  793. >>> config = Data2VecTextConfig.from_pretrained("facebook/data2vec-text-base")
  794. >>> config.is_decoder = True
  795. >>> model = Data2VecTextForCausalLM.from_pretrained("facebook/data2vec-text-base", config=config)
  796. >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
  797. >>> outputs = model(**inputs)
  798. >>> prediction_logits = outputs.logits
  799. ```"""
  800. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  801. if labels is not None:
  802. use_cache = False
  803. outputs = self.data2vec_text(
  804. input_ids,
  805. attention_mask=attention_mask,
  806. token_type_ids=token_type_ids,
  807. position_ids=position_ids,
  808. head_mask=head_mask,
  809. inputs_embeds=inputs_embeds,
  810. encoder_hidden_states=encoder_hidden_states,
  811. encoder_attention_mask=encoder_attention_mask,
  812. past_key_values=past_key_values,
  813. use_cache=use_cache,
  814. output_attentions=output_attentions,
  815. output_hidden_states=output_hidden_states,
  816. return_dict=return_dict,
  817. )
  818. sequence_output = outputs[0]
  819. prediction_scores = self.lm_head(sequence_output)
  820. lm_loss = None
  821. if labels is not None:
  822. # we are doing next-token prediction; shift prediction scores and input ids by one
  823. shifted_prediction_scores = prediction_scores[:, :-1, :].contiguous()
  824. labels = labels[:, 1:].contiguous()
  825. loss_fct = CrossEntropyLoss()
  826. labels = labels.to(shifted_prediction_scores.device)
  827. lm_loss = loss_fct(shifted_prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
  828. if not return_dict:
  829. output = (prediction_scores,) + outputs[2:]
  830. return ((lm_loss,) + output) if lm_loss is not None else output
  831. return CausalLMOutputWithCrossAttentions(
  832. loss=lm_loss,
  833. logits=prediction_scores,
  834. past_key_values=outputs.past_key_values,
  835. hidden_states=outputs.hidden_states,
  836. attentions=outputs.attentions,
  837. cross_attentions=outputs.cross_attentions,
  838. )
  839. def _reorder_cache(self, past_key_values, beam_idx):
  840. reordered_past = ()
  841. for layer_past in past_key_values:
  842. reordered_past += (
  843. tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
  844. )
  845. return reordered_past
  846. @add_start_docstrings("""data2vec Model with a `language modeling` head on top.""", DATA2VECTEXT_START_DOCSTRING)
  847. class Data2VecTextForMaskedLM(Data2VecTextPreTrainedModel):
  848. _tied_weights_keys = ["lm_head.decoder.weight", "lm_head.decoder.bias"]
  849. def __init__(self, config):
  850. super().__init__(config)
  851. if config.is_decoder:
  852. logger.warning(
  853. "If you want to use `Data2VecTextForMaskedLM` make sure `config.is_decoder=False` for "
  854. "bi-directional self-attention."
  855. )
  856. self.data2vec_text = Data2VecTextModel(config, add_pooling_layer=False)
  857. self.lm_head = Data2VecTextLMHead(config)
  858. # Initialize weights and apply final processing
  859. self.post_init()
  860. def get_output_embeddings(self):
  861. return self.lm_head.decoder
  862. def set_output_embeddings(self, new_embeddings):
  863. self.lm_head.decoder = new_embeddings
  864. @add_start_docstrings_to_model_forward(DATA2VECTEXT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
  865. @add_code_sample_docstrings(
  866. checkpoint=_CHECKPOINT_FOR_DOC,
  867. output_type=MaskedLMOutput,
  868. config_class=_CONFIG_FOR_DOC,
  869. mask="<mask>",
  870. )
  871. def forward(
  872. self,
  873. input_ids: Optional[torch.LongTensor] = None,
  874. attention_mask: Optional[torch.FloatTensor] = None,
  875. token_type_ids: Optional[torch.LongTensor] = None,
  876. position_ids: Optional[torch.LongTensor] = None,
  877. head_mask: Optional[torch.FloatTensor] = None,
  878. inputs_embeds: Optional[torch.FloatTensor] = None,
  879. encoder_hidden_states: Optional[torch.FloatTensor] = None,
  880. encoder_attention_mask: Optional[torch.FloatTensor] = None,
  881. labels: Optional[torch.LongTensor] = None,
  882. output_attentions: Optional[bool] = None,
  883. output_hidden_states: Optional[bool] = None,
  884. return_dict: Optional[bool] = None,
  885. ) -> Union[Tuple, MaskedLMOutput]:
  886. r"""
  887. labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
  888. Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
  889. config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
  890. loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
  891. kwargs (`Dict[str, any]`, *optional*, defaults to *{}*):
  892. Used to hide legacy arguments that have been deprecated.
  893. """
  894. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  895. outputs = self.data2vec_text(
  896. input_ids,
  897. attention_mask=attention_mask,
  898. token_type_ids=token_type_ids,
  899. position_ids=position_ids,
  900. head_mask=head_mask,
  901. inputs_embeds=inputs_embeds,
  902. encoder_hidden_states=encoder_hidden_states,
  903. encoder_attention_mask=encoder_attention_mask,
  904. output_attentions=output_attentions,
  905. output_hidden_states=output_hidden_states,
  906. return_dict=return_dict,
  907. )
  908. sequence_output = outputs[0]
  909. prediction_scores = self.lm_head(sequence_output)
  910. masked_lm_loss = None
  911. if labels is not None:
  912. loss_fct = CrossEntropyLoss()
  913. labels = labels.to(prediction_scores.device)
  914. masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
  915. if not return_dict:
  916. output = (prediction_scores,) + outputs[2:]
  917. return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
  918. return MaskedLMOutput(
  919. loss=masked_lm_loss,
  920. logits=prediction_scores,
  921. hidden_states=outputs.hidden_states,
  922. attentions=outputs.attentions,
  923. )
  924. # Copied from transformers.models.roberta.modeling_roberta.RobertaLMHead with Roberta->Data2VecText
  925. class Data2VecTextLMHead(nn.Module):
  926. """Data2VecText Head for masked language modeling."""
  927. def __init__(self, config):
  928. super().__init__()
  929. self.dense = nn.Linear(config.hidden_size, config.hidden_size)
  930. self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
  931. self.decoder = nn.Linear(config.hidden_size, config.vocab_size)
  932. self.bias = nn.Parameter(torch.zeros(config.vocab_size))
  933. self.decoder.bias = self.bias
  934. def forward(self, features, **kwargs):
  935. x = self.dense(features)
  936. x = gelu(x)
  937. x = self.layer_norm(x)
  938. # project back to size of vocabulary with bias
  939. x = self.decoder(x)
  940. return x
  941. def _tie_weights(self):
  942. # To tie those two weights if they get disconnected (on TPU or when the bias is resized)
  943. # For accelerate compatibility and to not break backward compatibility
  944. if self.decoder.bias.device.type == "meta":
  945. self.decoder.bias = self.bias
  946. else:
  947. self.bias = self.decoder.bias
  948. @add_start_docstrings(
  949. """
  950. Data2VecText Model transformer with a sequence classification/regression head on top (a linear layer on top of the
  951. pooled output) e.g. for GLUE tasks.
  952. """,
  953. DATA2VECTEXT_START_DOCSTRING,
  954. )
  955. class Data2VecTextForSequenceClassification(Data2VecTextPreTrainedModel):
  956. def __init__(self, config):
  957. super().__init__(config)
  958. self.num_labels = config.num_labels
  959. self.config = config
  960. self.data2vec_text = Data2VecTextModel(config, add_pooling_layer=False)
  961. self.classifier = Data2VecTextClassificationHead(config)
  962. # Initialize weights and apply final processing
  963. self.post_init()
  964. @add_start_docstrings_to_model_forward(DATA2VECTEXT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
  965. @add_code_sample_docstrings(
  966. checkpoint=_CHECKPOINT_FOR_DOC,
  967. output_type=SequenceClassifierOutput,
  968. config_class=_CONFIG_FOR_DOC,
  969. )
  970. def forward(
  971. self,
  972. input_ids: Optional[torch.LongTensor] = None,
  973. attention_mask: Optional[torch.FloatTensor] = None,
  974. token_type_ids: Optional[torch.LongTensor] = None,
  975. position_ids: Optional[torch.LongTensor] = None,
  976. head_mask: Optional[torch.FloatTensor] = None,
  977. inputs_embeds: Optional[torch.FloatTensor] = None,
  978. labels: Optional[torch.LongTensor] = None,
  979. output_attentions: Optional[bool] = None,
  980. output_hidden_states: Optional[bool] = None,
  981. return_dict: Optional[bool] = None,
  982. ) -> Union[Tuple, SequenceClassifierOutput]:
  983. r"""
  984. labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
  985. Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
  986. config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
  987. `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
  988. """
  989. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  990. outputs = self.data2vec_text(
  991. input_ids,
  992. attention_mask=attention_mask,
  993. token_type_ids=token_type_ids,
  994. position_ids=position_ids,
  995. head_mask=head_mask,
  996. inputs_embeds=inputs_embeds,
  997. output_attentions=output_attentions,
  998. output_hidden_states=output_hidden_states,
  999. return_dict=return_dict,
  1000. )
  1001. sequence_output = outputs[0]
  1002. logits = self.classifier(sequence_output)
  1003. loss = None
  1004. if labels is not None:
  1005. labels = labels.to(logits.device)
  1006. if self.config.problem_type is None:
  1007. if self.num_labels == 1:
  1008. self.config.problem_type = "regression"
  1009. elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
  1010. self.config.problem_type = "single_label_classification"
  1011. else:
  1012. self.config.problem_type = "multi_label_classification"
  1013. if self.config.problem_type == "regression":
  1014. loss_fct = MSELoss()
  1015. if self.num_labels == 1:
  1016. loss = loss_fct(logits.squeeze(), labels.squeeze())
  1017. else:
  1018. loss = loss_fct(logits, labels)
  1019. elif self.config.problem_type == "single_label_classification":
  1020. loss_fct = CrossEntropyLoss()
  1021. loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
  1022. elif self.config.problem_type == "multi_label_classification":
  1023. loss_fct = BCEWithLogitsLoss()
  1024. loss = loss_fct(logits, labels)
  1025. if not return_dict:
  1026. output = (logits,) + outputs[2:]
  1027. return ((loss,) + output) if loss is not None else output
  1028. return SequenceClassifierOutput(
  1029. loss=loss,
  1030. logits=logits,
  1031. hidden_states=outputs.hidden_states,
  1032. attentions=outputs.attentions,
  1033. )
  1034. @add_start_docstrings(
  1035. """
  1036. Data2VecText Model with a multiple choice classification head on top (a linear layer on top of the pooled output
  1037. and a softmax) e.g. for RocStories/SWAG tasks.
  1038. """,
  1039. DATA2VECTEXT_START_DOCSTRING,
  1040. )
  1041. class Data2VecTextForMultipleChoice(Data2VecTextPreTrainedModel):
  1042. def __init__(self, config):
  1043. super().__init__(config)
  1044. self.data2vec_text = Data2VecTextModel(config)
  1045. self.dropout = nn.Dropout(config.hidden_dropout_prob)
  1046. self.classifier = nn.Linear(config.hidden_size, 1)
  1047. # Initialize weights and apply final processing
  1048. self.post_init()
  1049. @add_start_docstrings_to_model_forward(
  1050. DATA2VECTEXT_INPUTS_DOCSTRING.format("batch_size, num_choices, sequence_length")
  1051. )
  1052. @add_code_sample_docstrings(
  1053. checkpoint=_CHECKPOINT_FOR_DOC,
  1054. output_type=MultipleChoiceModelOutput,
  1055. config_class=_CONFIG_FOR_DOC,
  1056. )
  1057. def forward(
  1058. self,
  1059. input_ids: Optional[torch.LongTensor] = None,
  1060. token_type_ids: Optional[torch.LongTensor] = None,
  1061. attention_mask: Optional[torch.FloatTensor] = None,
  1062. labels: Optional[torch.LongTensor] = None,
  1063. position_ids: Optional[torch.LongTensor] = None,
  1064. head_mask: Optional[torch.FloatTensor] = None,
  1065. inputs_embeds: Optional[torch.FloatTensor] = None,
  1066. output_attentions: Optional[bool] = None,
  1067. output_hidden_states: Optional[bool] = None,
  1068. return_dict: Optional[bool] = None,
  1069. ) -> Union[Tuple, MultipleChoiceModelOutput]:
  1070. r"""
  1071. labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
  1072. Labels for computing the multiple choice classification loss. Indices should be in `[0, ...,
  1073. num_choices-1]` where `num_choices` is the size of the second dimension of the input tensors. (See
  1074. `input_ids` above)
  1075. """
  1076. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  1077. num_choices = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1]
  1078. flat_input_ids = input_ids.view(-1, input_ids.size(-1)) if input_ids is not None else None
  1079. flat_position_ids = position_ids.view(-1, position_ids.size(-1)) if position_ids is not None else None
  1080. flat_token_type_ids = token_type_ids.view(-1, token_type_ids.size(-1)) if token_type_ids is not None else None
  1081. flat_attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None
  1082. flat_inputs_embeds = (
  1083. inputs_embeds.view(-1, inputs_embeds.size(-2), inputs_embeds.size(-1))
  1084. if inputs_embeds is not None
  1085. else None
  1086. )
  1087. outputs = self.data2vec_text(
  1088. flat_input_ids,
  1089. position_ids=flat_position_ids,
  1090. token_type_ids=flat_token_type_ids,
  1091. attention_mask=flat_attention_mask,
  1092. head_mask=head_mask,
  1093. inputs_embeds=flat_inputs_embeds,
  1094. output_attentions=output_attentions,
  1095. output_hidden_states=output_hidden_states,
  1096. return_dict=return_dict,
  1097. )
  1098. pooled_output = outputs[1]
  1099. pooled_output = self.dropout(pooled_output)
  1100. logits = self.classifier(pooled_output)
  1101. reshaped_logits = logits.view(-1, num_choices)
  1102. loss = None
  1103. if labels is not None:
  1104. loss_fct = CrossEntropyLoss()
  1105. labels = labels.to(reshaped_logits.device)
  1106. loss = loss_fct(reshaped_logits, labels)
  1107. if not return_dict:
  1108. output = (reshaped_logits,) + outputs[2:]
  1109. return ((loss,) + output) if loss is not None else output
  1110. return MultipleChoiceModelOutput(
  1111. loss=loss,
  1112. logits=reshaped_logits,
  1113. hidden_states=outputs.hidden_states,
  1114. attentions=outputs.attentions,
  1115. )
  1116. @add_start_docstrings(
  1117. """
  1118. Data2VecText Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g.
  1119. for Named-Entity-Recognition (NER) tasks.
  1120. """,
  1121. DATA2VECTEXT_START_DOCSTRING,
  1122. )
  1123. class Data2VecTextForTokenClassification(Data2VecTextPreTrainedModel):
  1124. def __init__(self, config):
  1125. super().__init__(config)
  1126. self.num_labels = config.num_labels
  1127. self.data2vec_text = Data2VecTextModel(config, add_pooling_layer=False)
  1128. classifier_dropout = (
  1129. config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
  1130. )
  1131. self.dropout = nn.Dropout(classifier_dropout)
  1132. self.classifier = nn.Linear(config.hidden_size, config.num_labels)
  1133. # Initialize weights and apply final processing
  1134. self.post_init()
  1135. @add_start_docstrings_to_model_forward(DATA2VECTEXT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
  1136. @add_code_sample_docstrings(
  1137. checkpoint=_CHECKPOINT_FOR_DOC,
  1138. output_type=TokenClassifierOutput,
  1139. config_class=_CONFIG_FOR_DOC,
  1140. )
  1141. def forward(
  1142. self,
  1143. input_ids: Optional[torch.LongTensor] = None,
  1144. attention_mask: Optional[torch.FloatTensor] = None,
  1145. token_type_ids: Optional[torch.LongTensor] = None,
  1146. position_ids: Optional[torch.LongTensor] = None,
  1147. head_mask: Optional[torch.FloatTensor] = None,
  1148. inputs_embeds: Optional[torch.FloatTensor] = None,
  1149. labels: Optional[torch.LongTensor] = None,
  1150. output_attentions: Optional[bool] = None,
  1151. output_hidden_states: Optional[bool] = None,
  1152. return_dict: Optional[bool] = None,
  1153. ) -> Union[Tuple, TokenClassifierOutput]:
  1154. r"""
  1155. labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
  1156. Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
  1157. """
  1158. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  1159. outputs = self.data2vec_text(
  1160. input_ids,
  1161. attention_mask=attention_mask,
  1162. token_type_ids=token_type_ids,
  1163. position_ids=position_ids,
  1164. head_mask=head_mask,
  1165. inputs_embeds=inputs_embeds,
  1166. output_attentions=output_attentions,
  1167. output_hidden_states=output_hidden_states,
  1168. return_dict=return_dict,
  1169. )
  1170. sequence_output = outputs[0]
  1171. sequence_output = self.dropout(sequence_output)
  1172. logits = self.classifier(sequence_output)
  1173. loss = None
  1174. if labels is not None:
  1175. loss_fct = CrossEntropyLoss()
  1176. labels = labels.to(logits.device)
  1177. loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
  1178. if not return_dict:
  1179. output = (logits,) + outputs[2:]
  1180. return ((loss,) + output) if loss is not None else output
  1181. return TokenClassifierOutput(
  1182. loss=loss,
  1183. logits=logits,
  1184. hidden_states=outputs.hidden_states,
  1185. attentions=outputs.attentions,
  1186. )
  1187. # Copied from transformers.models.roberta.modeling_roberta.RobertaClassificationHead with Roberta->Data2VecText
  1188. class Data2VecTextClassificationHead(nn.Module):
  1189. """Head for sentence-level classification tasks."""
  1190. def __init__(self, config):
  1191. super().__init__()
  1192. self.dense = nn.Linear(config.hidden_size, config.hidden_size)
  1193. classifier_dropout = (
  1194. config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
  1195. )
  1196. self.dropout = nn.Dropout(classifier_dropout)
  1197. self.out_proj = nn.Linear(config.hidden_size, config.num_labels)
  1198. def forward(self, features, **kwargs):
  1199. x = features[:, 0, :] # take <s> token (equiv. to [CLS])
  1200. x = self.dropout(x)
  1201. x = self.dense(x)
  1202. x = torch.tanh(x)
  1203. x = self.dropout(x)
  1204. x = self.out_proj(x)
  1205. return x
  1206. @add_start_docstrings(
  1207. """
  1208. Data2VecText Model with a span classification head on top for extractive question-answering tasks like SQuAD (a
  1209. linear layers on top of the hidden-states output to compute `span start logits` and `span end logits`).
  1210. """,
  1211. DATA2VECTEXT_START_DOCSTRING,
  1212. )
  1213. class Data2VecTextForQuestionAnswering(Data2VecTextPreTrainedModel):
  1214. def __init__(self, config):
  1215. super().__init__(config)
  1216. self.num_labels = config.num_labels
  1217. self.data2vec_text = Data2VecTextModel(config, add_pooling_layer=False)
  1218. self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
  1219. # Initialize weights and apply final processing
  1220. self.post_init()
  1221. @add_start_docstrings_to_model_forward(DATA2VECTEXT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
  1222. @add_code_sample_docstrings(
  1223. checkpoint=_CHECKPOINT_FOR_DOC,
  1224. output_type=QuestionAnsweringModelOutput,
  1225. config_class=_CONFIG_FOR_DOC,
  1226. )
  1227. def forward(
  1228. self,
  1229. input_ids: Optional[torch.LongTensor] = None,
  1230. attention_mask: Optional[torch.FloatTensor] = None,
  1231. token_type_ids: Optional[torch.LongTensor] = None,
  1232. position_ids: Optional[torch.LongTensor] = None,
  1233. head_mask: Optional[torch.FloatTensor] = None,
  1234. inputs_embeds: Optional[torch.FloatTensor] = None,
  1235. start_positions: Optional[torch.LongTensor] = None,
  1236. end_positions: Optional[torch.LongTensor] = None,
  1237. output_attentions: Optional[bool] = None,
  1238. output_hidden_states: Optional[bool] = None,
  1239. return_dict: Optional[bool] = None,
  1240. ) -> Union[Tuple, QuestionAnsweringModelOutput]:
  1241. r"""
  1242. start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
  1243. Labels for position (index) of the start of the labelled span for computing the token classification loss.
  1244. Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
  1245. are not taken into account for computing the loss.
  1246. end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
  1247. Labels for position (index) of the end of the labelled span for computing the token classification loss.
  1248. Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
  1249. are not taken into account for computing the loss.
  1250. """
  1251. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  1252. outputs = self.data2vec_text(
  1253. input_ids,
  1254. attention_mask=attention_mask,
  1255. token_type_ids=token_type_ids,
  1256. position_ids=position_ids,
  1257. head_mask=head_mask,
  1258. inputs_embeds=inputs_embeds,
  1259. output_attentions=output_attentions,
  1260. output_hidden_states=output_hidden_states,
  1261. return_dict=return_dict,
  1262. )
  1263. sequence_output = outputs[0]
  1264. logits = self.qa_outputs(sequence_output)
  1265. start_logits, end_logits = logits.split(1, dim=-1)
  1266. start_logits = start_logits.squeeze(-1).contiguous()
  1267. end_logits = end_logits.squeeze(-1).contiguous()
  1268. total_loss = None
  1269. if start_positions is not None and end_positions is not None:
  1270. # If we are on multi-GPU, split add a dimension
  1271. if len(start_positions.size()) > 1:
  1272. start_positions = start_positions.squeeze(-1)
  1273. if len(end_positions.size()) > 1:
  1274. end_positions = end_positions.squeeze(-1)
  1275. # sometimes the start/end positions are outside our model inputs, we ignore these terms
  1276. ignored_index = start_logits.size(1)
  1277. start_positions = start_positions.clamp(0, ignored_index)
  1278. end_positions = end_positions.clamp(0, ignored_index)
  1279. loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
  1280. start_loss = loss_fct(start_logits, start_positions)
  1281. end_loss = loss_fct(end_logits, end_positions)
  1282. total_loss = (start_loss + end_loss) / 2
  1283. if not return_dict:
  1284. output = (start_logits, end_logits) + outputs[2:]
  1285. return ((total_loss,) + output) if total_loss is not None else output
  1286. return QuestionAnsweringModelOutput(
  1287. loss=total_loss,
  1288. start_logits=start_logits,
  1289. end_logits=end_logits,
  1290. hidden_states=outputs.hidden_states,
  1291. attentions=outputs.attentions,
  1292. )
  1293. def create_position_ids_from_input_ids(input_ids, padding_idx, past_key_values_length=0):
  1294. """
  1295. Replace non-padding symbols with their position numbers. Position numbers begin at padding_idx+1. Padding symbols
  1296. are ignored. This is modified from fairseq's `utils.make_positions`.
  1297. Args:
  1298. x: torch.Tensor x:
  1299. Returns: torch.Tensor
  1300. """
  1301. # The series of casts and type-conversions here are carefully balanced to both work with ONNX export and XLA.
  1302. mask = input_ids.ne(padding_idx).int()
  1303. incremental_indices = (torch.cumsum(mask, dim=1).type_as(mask) + past_key_values_length) * mask
  1304. return incremental_indices.long() + padding_idx