modeling_roberta.py 76 KB

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