modeling_xlm.py 74 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646
  1. # coding=utf-8
  2. # Copyright 2019-present, Facebook, Inc and 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. """
  16. PyTorch XLM model.
  17. """
  18. import math
  19. from dataclasses import dataclass
  20. from typing import Callable, Optional, Union
  21. import numpy as np
  22. import torch
  23. from torch import nn
  24. from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
  25. from ...activations import gelu, get_activation
  26. from ...cache_utils import DynamicCache, EncoderDecoderCache
  27. from ...generation import GenerationMixin
  28. from ...modeling_outputs import (
  29. BaseModelOutput,
  30. MaskedLMOutput,
  31. MultipleChoiceModelOutput,
  32. QuestionAnsweringModelOutput,
  33. SequenceClassifierOutput,
  34. TokenClassifierOutput,
  35. )
  36. from ...modeling_utils import PreTrainedModel
  37. from ...pytorch_utils import apply_chunking_to_forward, find_pruneable_heads_and_indices, prune_linear_layer
  38. from ...utils import ModelOutput, auto_docstring, logging
  39. from .configuration_xlm import XLMConfig
  40. logger = logging.get_logger(__name__)
  41. def create_sinusoidal_embeddings(n_pos, dim, out):
  42. position_enc = np.array([[pos / np.power(10000, 2 * (j // 2) / dim) for j in range(dim)] for pos in range(n_pos)])
  43. out.requires_grad = False
  44. out[:, 0::2] = torch.FloatTensor(np.sin(position_enc[:, 0::2]))
  45. out[:, 1::2] = torch.FloatTensor(np.cos(position_enc[:, 1::2]))
  46. out.detach_()
  47. def get_masks(slen, lengths, causal, padding_mask=None):
  48. """
  49. Generate hidden states mask, and optionally an attention mask.
  50. """
  51. alen = torch.arange(slen, dtype=torch.long, device=lengths.device)
  52. if padding_mask is not None:
  53. mask = padding_mask
  54. else:
  55. assert lengths.max().item() <= slen
  56. mask = alen < lengths[:, None]
  57. # attention mask is the same as mask, or triangular inferior attention (causal)
  58. bs = lengths.size(0)
  59. if causal:
  60. attn_mask = alen[None, None, :].repeat(bs, slen, 1) <= alen[None, :, None]
  61. else:
  62. attn_mask = mask
  63. # sanity check
  64. assert mask.size() == (bs, slen)
  65. assert causal is False or attn_mask.size() == (bs, slen, slen)
  66. return mask, attn_mask
  67. @dataclass
  68. @auto_docstring(
  69. custom_intro="""
  70. Base class for outputs of question answering models using a [`~modeling_utils.XLMSQuADHead`].
  71. """
  72. )
  73. class XLMSquadHeadOutput(ModelOutput):
  74. r"""
  75. loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned if both `start_positions` and `end_positions` are provided):
  76. Classification loss as the sum of start token, end token (and is_impossible if provided) classification
  77. losses.
  78. start_top_log_probs (`torch.FloatTensor` of shape `(batch_size, config.start_n_top)`, *optional*, returned if `start_positions` or `end_positions` is not provided):
  79. Log probabilities for the top config.start_n_top start token possibilities (beam-search).
  80. start_top_index (`torch.LongTensor` of shape `(batch_size, config.start_n_top)`, *optional*, returned if `start_positions` or `end_positions` is not provided):
  81. Indices for the top config.start_n_top start token possibilities (beam-search).
  82. end_top_log_probs (`torch.FloatTensor` of shape `(batch_size, config.start_n_top * config.end_n_top)`, *optional*, returned if `start_positions` or `end_positions` is not provided):
  83. Log probabilities for the top `config.start_n_top * config.end_n_top` end token possibilities
  84. (beam-search).
  85. end_top_index (`torch.LongTensor` of shape `(batch_size, config.start_n_top * config.end_n_top)`, *optional*, returned if `start_positions` or `end_positions` is not provided):
  86. Indices for the top `config.start_n_top * config.end_n_top` end token possibilities (beam-search).
  87. cls_logits (`torch.FloatTensor` of shape `(batch_size,)`, *optional*, returned if `start_positions` or `end_positions` is not provided):
  88. Log probabilities for the `is_impossible` label of the answers.
  89. """
  90. loss: Optional[torch.FloatTensor] = None
  91. start_top_log_probs: Optional[torch.FloatTensor] = None
  92. start_top_index: Optional[torch.LongTensor] = None
  93. end_top_log_probs: Optional[torch.FloatTensor] = None
  94. end_top_index: Optional[torch.LongTensor] = None
  95. cls_logits: Optional[torch.FloatTensor] = None
  96. class XLMPoolerStartLogits(nn.Module):
  97. """
  98. Compute SQuAD start logits from sequence hidden states.
  99. Args:
  100. config ([`XLMConfig`]):
  101. The config used by the model, will be used to grab the `hidden_size` of the model.
  102. """
  103. def __init__(self, config: XLMConfig):
  104. super().__init__()
  105. self.dense = nn.Linear(config.hidden_size, 1)
  106. def forward(
  107. self, hidden_states: torch.FloatTensor, p_mask: Optional[torch.FloatTensor] = None
  108. ) -> torch.FloatTensor:
  109. """
  110. Args:
  111. hidden_states (`torch.FloatTensor` of shape `(batch_size, seq_len, hidden_size)`):
  112. The final hidden states of the model.
  113. p_mask (`torch.FloatTensor` of shape `(batch_size, seq_len)`, *optional*):
  114. Mask for tokens at invalid position, such as query and special symbols (PAD, SEP, CLS). 1.0 means token
  115. should be masked.
  116. Returns:
  117. `torch.FloatTensor`: The start logits for SQuAD.
  118. """
  119. x = self.dense(hidden_states).squeeze(-1)
  120. if p_mask is not None:
  121. if p_mask.dtype == torch.float16:
  122. x = x * (1 - p_mask) - 65500 * p_mask
  123. else:
  124. x = x * (1 - p_mask) - 1e30 * p_mask
  125. return x
  126. class XLMPoolerEndLogits(nn.Module):
  127. """
  128. Compute SQuAD end logits from sequence hidden states.
  129. Args:
  130. config ([`XLMConfig`]):
  131. The config used by the model, will be used to grab the `hidden_size` of the model and the `layer_norm_eps`
  132. to use.
  133. """
  134. def __init__(self, config: XLMConfig):
  135. super().__init__()
  136. self.dense_0 = nn.Linear(config.hidden_size * 2, config.hidden_size)
  137. self.activation = nn.Tanh()
  138. self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
  139. self.dense_1 = nn.Linear(config.hidden_size, 1)
  140. def forward(
  141. self,
  142. hidden_states: torch.FloatTensor,
  143. start_states: Optional[torch.FloatTensor] = None,
  144. start_positions: Optional[torch.LongTensor] = None,
  145. p_mask: Optional[torch.FloatTensor] = None,
  146. ) -> torch.FloatTensor:
  147. """
  148. Args:
  149. hidden_states (`torch.FloatTensor` of shape `(batch_size, seq_len, hidden_size)`):
  150. The final hidden states of the model.
  151. start_states (`torch.FloatTensor` of shape `(batch_size, seq_len, hidden_size)`, *optional*):
  152. The hidden states of the first tokens for the labeled span.
  153. start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
  154. The position of the first token for the labeled span.
  155. p_mask (`torch.FloatTensor` of shape `(batch_size, seq_len)`, *optional*):
  156. Mask for tokens at invalid position, such as query and special symbols (PAD, SEP, CLS). 1.0 means token
  157. should be masked.
  158. <Tip>
  159. One of `start_states` or `start_positions` should be not `None`. If both are set, `start_positions` overrides
  160. `start_states`.
  161. </Tip>
  162. Returns:
  163. `torch.FloatTensor`: The end logits for SQuAD.
  164. """
  165. assert start_states is not None or start_positions is not None, (
  166. "One of start_states, start_positions should be not None"
  167. )
  168. if start_positions is not None:
  169. slen, hsz = hidden_states.shape[-2:]
  170. start_positions = start_positions[:, None, None].expand(-1, -1, hsz) # shape (bsz, 1, hsz)
  171. start_states = hidden_states.gather(-2, start_positions) # shape (bsz, 1, hsz)
  172. start_states = start_states.expand(-1, slen, -1) # shape (bsz, slen, hsz)
  173. x = self.dense_0(torch.cat([hidden_states, start_states], dim=-1))
  174. x = self.activation(x)
  175. x = self.LayerNorm(x)
  176. x = self.dense_1(x).squeeze(-1)
  177. if p_mask is not None:
  178. if p_mask.dtype == torch.float16:
  179. x = x * (1 - p_mask) - 65500 * p_mask
  180. else:
  181. x = x * (1 - p_mask) - 1e30 * p_mask
  182. return x
  183. class XLMPoolerAnswerClass(nn.Module):
  184. """
  185. Compute SQuAD 2.0 answer class from classification and start tokens hidden states.
  186. Args:
  187. config ([`XLMConfig`]):
  188. The config used by the model, will be used to grab the `hidden_size` of the model.
  189. """
  190. def __init__(self, config: XLMConfig):
  191. super().__init__()
  192. self.dense_0 = nn.Linear(config.hidden_size * 2, config.hidden_size)
  193. self.activation = nn.Tanh()
  194. self.dense_1 = nn.Linear(config.hidden_size, 1, bias=False)
  195. def forward(
  196. self,
  197. hidden_states: torch.FloatTensor,
  198. start_states: Optional[torch.FloatTensor] = None,
  199. start_positions: Optional[torch.LongTensor] = None,
  200. cls_index: Optional[torch.LongTensor] = None,
  201. ) -> torch.FloatTensor:
  202. """
  203. Args:
  204. hidden_states (`torch.FloatTensor` of shape `(batch_size, seq_len, hidden_size)`):
  205. The final hidden states of the model.
  206. start_states (`torch.FloatTensor` of shape `(batch_size, seq_len, hidden_size)`, *optional*):
  207. The hidden states of the first tokens for the labeled span.
  208. start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
  209. The position of the first token for the labeled span.
  210. cls_index (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
  211. Position of the CLS token for each sentence in the batch. If `None`, takes the last token.
  212. <Tip>
  213. One of `start_states` or `start_positions` should be not `None`. If both are set, `start_positions` overrides
  214. `start_states`.
  215. </Tip>
  216. Returns:
  217. `torch.FloatTensor`: The SQuAD 2.0 answer class.
  218. """
  219. # No dependency on end_feature so that we can obtain one single `cls_logits` for each sample.
  220. hsz = hidden_states.shape[-1]
  221. assert start_states is not None or start_positions is not None, (
  222. "One of start_states, start_positions should be not None"
  223. )
  224. if start_positions is not None:
  225. start_positions = start_positions[:, None, None].expand(-1, -1, hsz) # shape (bsz, 1, hsz)
  226. start_states = hidden_states.gather(-2, start_positions).squeeze(-2) # shape (bsz, hsz)
  227. if cls_index is not None:
  228. cls_index = cls_index[:, None, None].expand(-1, -1, hsz) # shape (bsz, 1, hsz)
  229. cls_token_state = hidden_states.gather(-2, cls_index).squeeze(-2) # shape (bsz, hsz)
  230. else:
  231. cls_token_state = hidden_states[:, -1, :] # shape (bsz, hsz)
  232. x = self.dense_0(torch.cat([start_states, cls_token_state], dim=-1))
  233. x = self.activation(x)
  234. x = self.dense_1(x).squeeze(-1)
  235. return x
  236. class XLMSQuADHead(nn.Module):
  237. r"""
  238. A SQuAD head inspired by XLNet.
  239. Args:
  240. config ([`XLMConfig`]):
  241. The config used by the model, will be used to grab the `hidden_size` of the model and the `layer_norm_eps`
  242. to use.
  243. """
  244. def __init__(self, config: XLMConfig):
  245. super().__init__()
  246. self.start_n_top = config.start_n_top
  247. self.end_n_top = config.end_n_top
  248. self.start_logits = XLMPoolerStartLogits(config)
  249. self.end_logits = XLMPoolerEndLogits(config)
  250. self.answer_class = XLMPoolerAnswerClass(config)
  251. @auto_docstring
  252. def forward(
  253. self,
  254. hidden_states: torch.FloatTensor,
  255. start_positions: Optional[torch.LongTensor] = None,
  256. end_positions: Optional[torch.LongTensor] = None,
  257. cls_index: Optional[torch.LongTensor] = None,
  258. is_impossible: Optional[torch.LongTensor] = None,
  259. p_mask: Optional[torch.FloatTensor] = None,
  260. return_dict: bool = False,
  261. ) -> Union[XLMSquadHeadOutput, tuple[torch.FloatTensor]]:
  262. r"""
  263. hidden_states (`torch.FloatTensor` of shape `(batch_size, seq_len, hidden_size)`):
  264. Final hidden states of the model on the sequence tokens.
  265. start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
  266. Positions of the first token for the labeled span.
  267. end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
  268. Positions of the last token for the labeled span.
  269. cls_index (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
  270. Position of the CLS token for each sentence in the batch. If `None`, takes the last token.
  271. is_impossible (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
  272. Whether the question has a possible answer in the paragraph or not.
  273. p_mask (`torch.FloatTensor` of shape `(batch_size, seq_len)`, *optional*):
  274. Mask for tokens at invalid position, such as query and special symbols (PAD, SEP, CLS). 1.0 means token
  275. should be masked.
  276. """
  277. start_logits = self.start_logits(hidden_states, p_mask=p_mask)
  278. if start_positions is not None and end_positions is not None:
  279. # If we are on multi-GPU, let's remove the dimension added by batch splitting
  280. for x in (start_positions, end_positions, cls_index, is_impossible):
  281. if x is not None and x.dim() > 1:
  282. x.squeeze_(-1)
  283. # during training, compute the end logits based on the ground truth of the start position
  284. end_logits = self.end_logits(hidden_states, start_positions=start_positions, p_mask=p_mask)
  285. loss_fct = CrossEntropyLoss()
  286. start_loss = loss_fct(start_logits, start_positions)
  287. end_loss = loss_fct(end_logits, end_positions)
  288. total_loss = (start_loss + end_loss) / 2
  289. if cls_index is not None and is_impossible is not None:
  290. # Predict answerability from the representation of CLS and START
  291. cls_logits = self.answer_class(hidden_states, start_positions=start_positions, cls_index=cls_index)
  292. loss_fct_cls = nn.BCEWithLogitsLoss()
  293. cls_loss = loss_fct_cls(cls_logits, is_impossible)
  294. # note(zhiliny): by default multiply the loss by 0.5 so that the scale is comparable to start_loss and end_loss
  295. total_loss += cls_loss * 0.5
  296. return XLMSquadHeadOutput(loss=total_loss) if return_dict else (total_loss,)
  297. else:
  298. # during inference, compute the end logits based on beam search
  299. bsz, slen, hsz = hidden_states.size()
  300. start_log_probs = nn.functional.softmax(start_logits, dim=-1) # shape (bsz, slen)
  301. start_top_log_probs, start_top_index = torch.topk(
  302. start_log_probs, self.start_n_top, dim=-1
  303. ) # shape (bsz, start_n_top)
  304. start_top_index_exp = start_top_index.unsqueeze(-1).expand(-1, -1, hsz) # shape (bsz, start_n_top, hsz)
  305. start_states = torch.gather(hidden_states, -2, start_top_index_exp) # shape (bsz, start_n_top, hsz)
  306. start_states = start_states.unsqueeze(1).expand(-1, slen, -1, -1) # shape (bsz, slen, start_n_top, hsz)
  307. hidden_states_expanded = hidden_states.unsqueeze(2).expand_as(
  308. start_states
  309. ) # shape (bsz, slen, start_n_top, hsz)
  310. p_mask = p_mask.unsqueeze(-1) if p_mask is not None else None
  311. end_logits = self.end_logits(hidden_states_expanded, start_states=start_states, p_mask=p_mask)
  312. end_log_probs = nn.functional.softmax(end_logits, dim=1) # shape (bsz, slen, start_n_top)
  313. end_top_log_probs, end_top_index = torch.topk(
  314. end_log_probs, self.end_n_top, dim=1
  315. ) # shape (bsz, end_n_top, start_n_top)
  316. end_top_log_probs = end_top_log_probs.view(-1, self.start_n_top * self.end_n_top)
  317. end_top_index = end_top_index.view(-1, self.start_n_top * self.end_n_top)
  318. start_states = torch.einsum("blh,bl->bh", hidden_states, start_log_probs)
  319. cls_logits = self.answer_class(hidden_states, start_states=start_states, cls_index=cls_index)
  320. if not return_dict:
  321. return (start_top_log_probs, start_top_index, end_top_log_probs, end_top_index, cls_logits)
  322. else:
  323. return XLMSquadHeadOutput(
  324. start_top_log_probs=start_top_log_probs,
  325. start_top_index=start_top_index,
  326. end_top_log_probs=end_top_log_probs,
  327. end_top_index=end_top_index,
  328. cls_logits=cls_logits,
  329. )
  330. class XLMSequenceSummary(nn.Module):
  331. r"""
  332. Compute a single vector summary of a sequence hidden states.
  333. Args:
  334. config ([`XLMConfig`]):
  335. The config used by the model. Relevant arguments in the config class of the model are (refer to the actual
  336. config class of your model for the default values it uses):
  337. - **summary_type** (`str`) -- The method to use to make this summary. Accepted values are:
  338. - `"last"` -- Take the last token hidden state (like XLNet)
  339. - `"first"` -- Take the first token hidden state (like Bert)
  340. - `"mean"` -- Take the mean of all tokens hidden states
  341. - `"cls_index"` -- Supply a Tensor of classification token position (GPT/GPT-2)
  342. - `"attn"` -- Not implemented now, use multi-head attention
  343. - **summary_use_proj** (`bool`) -- Add a projection after the vector extraction.
  344. - **summary_proj_to_labels** (`bool`) -- If `True`, the projection outputs to `config.num_labels` classes
  345. (otherwise to `config.hidden_size`).
  346. - **summary_activation** (`Optional[str]`) -- Set to `"tanh"` to add a tanh activation to the output,
  347. another string or `None` will add no activation.
  348. - **summary_first_dropout** (`float`) -- Optional dropout probability before the projection and activation.
  349. - **summary_last_dropout** (`float`)-- Optional dropout probability after the projection and activation.
  350. """
  351. def __init__(self, config: XLMConfig):
  352. super().__init__()
  353. self.summary_type = getattr(config, "summary_type", "last")
  354. if self.summary_type == "attn":
  355. # We should use a standard multi-head attention module with absolute positional embedding for that.
  356. # Cf. https://github.com/zihangdai/xlnet/blob/master/modeling.py#L253-L276
  357. # We can probably just use the multi-head attention module of PyTorch >=1.1.0
  358. raise NotImplementedError
  359. self.summary = nn.Identity()
  360. if hasattr(config, "summary_use_proj") and config.summary_use_proj:
  361. if hasattr(config, "summary_proj_to_labels") and config.summary_proj_to_labels and config.num_labels > 0:
  362. num_classes = config.num_labels
  363. else:
  364. num_classes = config.hidden_size
  365. self.summary = nn.Linear(config.hidden_size, num_classes)
  366. activation_string = getattr(config, "summary_activation", None)
  367. self.activation: Callable = get_activation(activation_string) if activation_string else nn.Identity()
  368. self.first_dropout = nn.Identity()
  369. if hasattr(config, "summary_first_dropout") and config.summary_first_dropout > 0:
  370. self.first_dropout = nn.Dropout(config.summary_first_dropout)
  371. self.last_dropout = nn.Identity()
  372. if hasattr(config, "summary_last_dropout") and config.summary_last_dropout > 0:
  373. self.last_dropout = nn.Dropout(config.summary_last_dropout)
  374. def forward(
  375. self, hidden_states: torch.FloatTensor, cls_index: Optional[torch.LongTensor] = None
  376. ) -> torch.FloatTensor:
  377. """
  378. Compute a single vector summary of a sequence hidden states.
  379. Args:
  380. hidden_states (`torch.FloatTensor` of shape `[batch_size, seq_len, hidden_size]`):
  381. The hidden states of the last layer.
  382. cls_index (`torch.LongTensor` of shape `[batch_size]` or `[batch_size, ...]` where ... are optional leading dimensions of `hidden_states`, *optional*):
  383. Used if `summary_type == "cls_index"` and takes the last token of the sequence as classification token.
  384. Returns:
  385. `torch.FloatTensor`: The summary of the sequence hidden states.
  386. """
  387. if self.summary_type == "last":
  388. output = hidden_states[:, -1]
  389. elif self.summary_type == "first":
  390. output = hidden_states[:, 0]
  391. elif self.summary_type == "mean":
  392. output = hidden_states.mean(dim=1)
  393. elif self.summary_type == "cls_index":
  394. if cls_index is None:
  395. cls_index = torch.full_like(
  396. hidden_states[..., :1, :],
  397. hidden_states.shape[-2] - 1,
  398. dtype=torch.long,
  399. )
  400. else:
  401. cls_index = cls_index.unsqueeze(-1).unsqueeze(-1)
  402. cls_index = cls_index.expand((-1,) * (cls_index.dim() - 1) + (hidden_states.size(-1),))
  403. # shape of cls_index: (bsz, XX, 1, hidden_size) where XX are optional leading dim of hidden_states
  404. output = hidden_states.gather(-2, cls_index).squeeze(-2) # shape (bsz, XX, hidden_size)
  405. elif self.summary_type == "attn":
  406. raise NotImplementedError
  407. output = self.first_dropout(output)
  408. output = self.summary(output)
  409. output = self.activation(output)
  410. output = self.last_dropout(output)
  411. return output
  412. class MultiHeadAttention(nn.Module):
  413. def __init__(self, n_heads, dim, config, layer_idx: int = 0):
  414. super().__init__()
  415. self.layer_id = layer_idx
  416. self.dim = dim
  417. self.n_heads = n_heads
  418. self.head_dim = dim // n_heads
  419. self.dropout = config.attention_dropout
  420. assert self.dim % self.n_heads == 0
  421. self.q_lin = nn.Linear(dim, dim)
  422. self.k_lin = nn.Linear(dim, dim)
  423. self.v_lin = nn.Linear(dim, dim)
  424. self.out_lin = nn.Linear(dim, dim)
  425. self.pruned_heads = set()
  426. def prune_heads(self, heads):
  427. attention_head_size = self.dim // self.n_heads
  428. if len(heads) == 0:
  429. return
  430. heads, index = find_pruneable_heads_and_indices(heads, self.n_heads, attention_head_size, self.pruned_heads)
  431. # Prune linear layers
  432. self.q_lin = prune_linear_layer(self.q_lin, index)
  433. self.k_lin = prune_linear_layer(self.k_lin, index)
  434. self.v_lin = prune_linear_layer(self.v_lin, index)
  435. self.out_lin = prune_linear_layer(self.out_lin, index, dim=1)
  436. # Update hyper params
  437. self.n_heads = self.n_heads - len(heads)
  438. self.dim = attention_head_size * self.n_heads
  439. self.pruned_heads = self.pruned_heads.union(heads)
  440. def forward(
  441. self,
  442. input,
  443. mask,
  444. kv=None,
  445. cache=None,
  446. head_mask=None,
  447. output_attentions=False,
  448. cache_position=None,
  449. ):
  450. """
  451. Self-attention (if kv is None) or attention over source sentence (provided by kv).
  452. """
  453. # Input is (bs, qlen, dim)
  454. # Mask is (bs, klen) (non-causal) or (bs, klen, klen)
  455. bs, qlen, dim = input.size()
  456. is_cross_attention = kv is not None
  457. mask_reshape = (bs, 1, qlen, -1) if mask.dim() == 3 else (bs, 1, 1, -1)
  458. q = self.q_lin(input).view(bs, -1, self.n_heads, self.head_dim).transpose(1, 2)
  459. if cache is not None:
  460. if isinstance(cache, EncoderDecoderCache):
  461. is_updated = cache.is_updated.get(self.layer_id)
  462. if is_cross_attention:
  463. # after the first generated id, we can subsequently re-use all key/value_states from cache
  464. curr_past_key_value = cache.cross_attention_cache
  465. else:
  466. curr_past_key_value = cache.self_attention_cache
  467. else:
  468. curr_past_key_value = cache
  469. current_states = kv if is_cross_attention else input
  470. if is_cross_attention and cache is not None and is_updated:
  471. # reuse k,v, cross_attentions
  472. k = curr_past_key_value.key_cache[self.layer_id]
  473. v = curr_past_key_value.value_cache[self.layer_id]
  474. else:
  475. k = self.k_lin(current_states)
  476. v = self.v_lin(current_states)
  477. k = k.view(bs, -1, self.n_heads, self.head_dim).transpose(1, 2)
  478. v = v.view(bs, -1, self.n_heads, self.head_dim).transpose(1, 2)
  479. if cache is not None:
  480. # save all key/value_states to cache to be re-used for fast auto-regressive generation
  481. cache_position = cache_position if not is_cross_attention else None
  482. k, v = curr_past_key_value.update(k, v, self.layer_id, {"cache_position": cache_position})
  483. # set flag that curr layer for cross-attn is already updated so we can re-use in subsequent calls
  484. if is_cross_attention:
  485. cache.is_updated[self.layer_id] = True
  486. q = q / math.sqrt(self.head_dim) # (bs, n_heads, qlen, head_dim)
  487. scores = torch.matmul(q, k.transpose(2, 3)) # (bs, n_heads, qlen, klen)
  488. mask = (mask == 0).view(mask_reshape).expand_as(scores) # (bs, n_heads, qlen, klen)
  489. scores.masked_fill_(mask, torch.finfo(scores.dtype).min) # (bs, n_heads, qlen, klen)
  490. weights = nn.functional.softmax(scores.float(), dim=-1).type_as(scores) # (bs, n_heads, qlen, klen)
  491. weights = nn.functional.dropout(weights, p=self.dropout, training=self.training) # (bs, n_heads, qlen, klen)
  492. # Mask heads if we want to
  493. if head_mask is not None:
  494. weights = weights * head_mask
  495. context = torch.matmul(weights, v) # (bs, n_heads, qlen, head_dim)
  496. context = context.transpose(1, 2).contiguous().view(bs, -1, self.n_heads * self.head_dim)
  497. outputs = (self.out_lin(context),)
  498. if output_attentions:
  499. outputs = outputs + (weights,)
  500. return outputs
  501. class TransformerFFN(nn.Module):
  502. def __init__(self, in_dim, dim_hidden, out_dim, config):
  503. super().__init__()
  504. self.dropout = config.dropout
  505. self.lin1 = nn.Linear(in_dim, dim_hidden)
  506. self.lin2 = nn.Linear(dim_hidden, out_dim)
  507. self.act = gelu if config.gelu_activation else nn.functional.relu
  508. self.chunk_size_feed_forward = config.chunk_size_feed_forward
  509. self.seq_len_dim = 1
  510. def forward(self, input):
  511. return apply_chunking_to_forward(self.ff_chunk, self.chunk_size_feed_forward, self.seq_len_dim, input)
  512. def ff_chunk(self, input):
  513. x = self.lin1(input)
  514. x = self.act(x)
  515. x = self.lin2(x)
  516. x = nn.functional.dropout(x, p=self.dropout, training=self.training)
  517. return x
  518. @auto_docstring
  519. class XLMPreTrainedModel(PreTrainedModel):
  520. config: XLMConfig
  521. load_tf_weights = None
  522. base_model_prefix = "transformer"
  523. def __init__(self, *inputs, **kwargs):
  524. super().__init__(*inputs, **kwargs)
  525. @property
  526. def dummy_inputs(self):
  527. inputs_list = torch.tensor([[7, 6, 0, 0, 1], [1, 2, 3, 0, 0], [0, 0, 0, 4, 5]])
  528. attns_list = torch.tensor([[1, 1, 0, 0, 1], [1, 1, 1, 0, 0], [1, 0, 0, 1, 1]])
  529. if self.config.use_lang_emb and self.config.n_langs > 1:
  530. langs_list = torch.tensor([[1, 1, 0, 0, 1], [1, 1, 1, 0, 0], [1, 0, 0, 1, 1]])
  531. else:
  532. langs_list = None
  533. return {"input_ids": inputs_list, "attention_mask": attns_list, "langs": langs_list}
  534. def _init_weights(self, module):
  535. """Initialize the weights."""
  536. if isinstance(module, nn.Embedding):
  537. if self.config is not None and self.config.embed_init_std is not None:
  538. nn.init.normal_(module.weight, mean=0, std=self.config.embed_init_std)
  539. if module.padding_idx is not None:
  540. module.weight.data[module.padding_idx].zero_()
  541. if isinstance(module, nn.Linear):
  542. if self.config is not None and self.config.init_std is not None:
  543. nn.init.normal_(module.weight, mean=0, std=self.config.init_std)
  544. if module.bias is not None:
  545. nn.init.constant_(module.bias, 0.0)
  546. if isinstance(module, nn.LayerNorm):
  547. module.bias.data.zero_()
  548. module.weight.data.fill_(1.0)
  549. if isinstance(module, XLMModel) and self.config.sinusoidal_embeddings:
  550. create_sinusoidal_embeddings(
  551. self.config.max_position_embeddings, self.config.emb_dim, out=module.position_embeddings.weight
  552. )
  553. @dataclass
  554. @auto_docstring(
  555. custom_intro="""
  556. Base class for outputs of question answering models using a `XLMSQuADHead`.
  557. """
  558. )
  559. class XLMForQuestionAnsweringOutput(ModelOutput):
  560. r"""
  561. loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned if both `start_positions` and `end_positions` are provided):
  562. Classification loss as the sum of start token, end token (and is_impossible if provided) classification
  563. losses.
  564. start_top_log_probs (`torch.FloatTensor` of shape `(batch_size, config.start_n_top)`, *optional*, returned if `start_positions` or `end_positions` is not provided):
  565. Log probabilities for the top config.start_n_top start token possibilities (beam-search).
  566. start_top_index (`torch.LongTensor` of shape `(batch_size, config.start_n_top)`, *optional*, returned if `start_positions` or `end_positions` is not provided):
  567. Indices for the top config.start_n_top start token possibilities (beam-search).
  568. end_top_log_probs (`torch.FloatTensor` of shape `(batch_size, config.start_n_top * config.end_n_top)`, *optional*, returned if `start_positions` or `end_positions` is not provided):
  569. Log probabilities for the top `config.start_n_top * config.end_n_top` end token possibilities
  570. (beam-search).
  571. end_top_index (`torch.LongTensor` of shape `(batch_size, config.start_n_top * config.end_n_top)`, *optional*, returned if `start_positions` or `end_positions` is not provided):
  572. Indices for the top `config.start_n_top * config.end_n_top` end token possibilities (beam-search).
  573. cls_logits (`torch.FloatTensor` of shape `(batch_size,)`, *optional*, returned if `start_positions` or `end_positions` is not provided):
  574. Log probabilities for the `is_impossible` label of the answers.
  575. """
  576. loss: Optional[torch.FloatTensor] = None
  577. start_top_log_probs: Optional[torch.FloatTensor] = None
  578. start_top_index: Optional[torch.LongTensor] = None
  579. end_top_log_probs: Optional[torch.FloatTensor] = None
  580. end_top_index: Optional[torch.LongTensor] = None
  581. cls_logits: Optional[torch.FloatTensor] = None
  582. hidden_states: Optional[tuple[torch.FloatTensor, ...]] = None
  583. attentions: Optional[tuple[torch.FloatTensor, ...]] = None
  584. @auto_docstring
  585. class XLMModel(XLMPreTrainedModel):
  586. def __init__(self, config):
  587. super().__init__(config)
  588. # encoder / decoder, output layer
  589. self.is_encoder = config.is_encoder
  590. self.is_decoder = not config.is_encoder
  591. if self.is_decoder:
  592. raise NotImplementedError("Currently XLM can only be used as an encoder")
  593. # self.with_output = with_output
  594. self.causal = config.causal
  595. # dictionary / languages
  596. self.n_langs = config.n_langs
  597. self.use_lang_emb = config.use_lang_emb
  598. self.n_words = config.n_words
  599. self.eos_index = config.eos_index
  600. self.pad_index = config.pad_index
  601. # self.dico = dico
  602. # self.id2lang = config.id2lang
  603. # self.lang2id = config.lang2id
  604. # assert len(self.dico) == self.n_words
  605. # assert len(self.id2lang) == len(self.lang2id) == self.n_langs
  606. # model parameters
  607. self.dim = config.emb_dim # 512 by default
  608. self.hidden_dim = self.dim * 4 # 2048 by default
  609. self.n_heads = config.n_heads # 8 by default
  610. self.n_layers = config.n_layers
  611. self.dropout = config.dropout
  612. self.attention_dropout = config.attention_dropout
  613. assert self.dim % self.n_heads == 0, "transformer dim must be a multiple of n_heads"
  614. # embeddings
  615. self.position_embeddings = nn.Embedding(config.max_position_embeddings, self.dim)
  616. if config.n_langs > 1 and config.use_lang_emb:
  617. self.lang_embeddings = nn.Embedding(self.n_langs, self.dim)
  618. self.embeddings = nn.Embedding(self.n_words, self.dim, padding_idx=self.pad_index)
  619. self.layer_norm_emb = nn.LayerNorm(self.dim, eps=config.layer_norm_eps)
  620. # transformer layers
  621. self.attentions = nn.ModuleList()
  622. self.layer_norm1 = nn.ModuleList()
  623. self.ffns = nn.ModuleList()
  624. self.layer_norm2 = nn.ModuleList()
  625. # if self.is_decoder:
  626. # self.layer_norm15 = nn.ModuleList()
  627. # self.encoder_attn = nn.ModuleList()
  628. for i in range(self.n_layers):
  629. self.attentions.append(MultiHeadAttention(self.n_heads, self.dim, config=config, layer_idx=i))
  630. self.layer_norm1.append(nn.LayerNorm(self.dim, eps=config.layer_norm_eps))
  631. # if self.is_decoder:
  632. # self.layer_norm15.append(nn.LayerNorm(self.dim, eps=config.layer_norm_eps))
  633. # self.encoder_attn.append(MultiHeadAttention(self.n_heads, self.dim, dropout=self.attention_dropout))
  634. self.ffns.append(TransformerFFN(self.dim, self.hidden_dim, self.dim, config=config))
  635. self.layer_norm2.append(nn.LayerNorm(self.dim, eps=config.layer_norm_eps))
  636. if hasattr(config, "pruned_heads"):
  637. pruned_heads = config.pruned_heads.copy().items()
  638. config.pruned_heads = {}
  639. for layer, heads in pruned_heads:
  640. if self.attentions[int(layer)].n_heads == config.n_heads:
  641. self.prune_heads({int(layer): list(map(int, heads))})
  642. # Initialize weights and apply final processing
  643. self.post_init()
  644. self.register_buffer(
  645. "position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
  646. )
  647. def get_input_embeddings(self):
  648. return self.embeddings
  649. def set_input_embeddings(self, new_embeddings):
  650. self.embeddings = new_embeddings
  651. def _prune_heads(self, heads_to_prune):
  652. """
  653. Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
  654. class PreTrainedModel
  655. """
  656. for layer, heads in heads_to_prune.items():
  657. self.attentions[layer].prune_heads(heads)
  658. @auto_docstring
  659. def forward(
  660. self,
  661. input_ids: Optional[torch.Tensor] = None,
  662. attention_mask: Optional[torch.Tensor] = None,
  663. langs: Optional[torch.Tensor] = None,
  664. token_type_ids: Optional[torch.Tensor] = None,
  665. position_ids: Optional[torch.Tensor] = None,
  666. lengths: Optional[torch.Tensor] = None,
  667. cache: Optional[dict[str, torch.Tensor]] = None,
  668. head_mask: Optional[torch.Tensor] = None,
  669. inputs_embeds: Optional[torch.Tensor] = None,
  670. output_attentions: Optional[bool] = None,
  671. output_hidden_states: Optional[bool] = None,
  672. return_dict: Optional[bool] = None,
  673. cache_position: Optional[torch.Tensor] = None,
  674. **kwargs, # Dummy kwargs for now
  675. ) -> Union[tuple, BaseModelOutput]:
  676. r"""
  677. langs (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
  678. A parallel sequence of tokens to be used to indicate the language of each token in the input. Indices are
  679. languages ids which can be obtained from the language names by using two conversion mappings provided in
  680. the configuration of the model (only provided for multilingual models). More precisely, the *language name
  681. to language id* mapping is in `model.config.lang2id` (which is a dictionary string to int) and the
  682. *language id to language name* mapping is in `model.config.id2lang` (dictionary int to string).
  683. See usage examples detailed in the [multilingual documentation](../multilingual).
  684. lengths (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
  685. Length of each sentence that can be used to avoid performing attention on padding token indices. You can
  686. also use *attention_mask* for the same result (see above), kept here for compatibility. Indices selected in
  687. `[0, ..., input_ids.size(-1)]`.
  688. cache (`dict[str, torch.FloatTensor]`, *optional*):
  689. Instance of `EncoderDecoderCache` that contains precomputed KV states. Can be used to speed up sequential
  690. decoding.
  691. """
  692. output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
  693. output_hidden_states = (
  694. output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
  695. )
  696. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  697. if input_ids is not None:
  698. bs, slen = input_ids.size()
  699. else:
  700. bs, slen = inputs_embeds.size()[:-1]
  701. device = input_ids.device if input_ids is not None else inputs_embeds.device
  702. if cache is None:
  703. cache = EncoderDecoderCache(DynamicCache(config=self.config), DynamicCache(config=self.config))
  704. if isinstance(cache, tuple):
  705. cache = EncoderDecoderCache.from_legacy_cache(cache)
  706. if lengths is None:
  707. if input_ids is not None:
  708. lengths = (input_ids != self.pad_index).sum(dim=1).long()
  709. else:
  710. lengths = torch.tensor([slen] * bs, device=device)
  711. # check inputs
  712. assert lengths.size(0) == bs
  713. assert lengths.max().item() <= slen
  714. # generate masks
  715. mask, attn_mask = get_masks(slen, lengths, self.causal, padding_mask=attention_mask)
  716. # position_ids
  717. if position_ids is None:
  718. position_ids = self.position_ids[:, :slen]
  719. else:
  720. assert position_ids.size() == (bs, slen) # (slen, bs)
  721. # langs
  722. if langs is not None:
  723. assert langs.size() == (bs, slen) # (slen, bs)
  724. # Prepare head mask if needed
  725. head_mask = self.get_head_mask(head_mask, self.config.n_layers)
  726. # do not recompute cached elements
  727. if cache is not None and input_ids is not None:
  728. _slen = slen - cache.get_seq_length()
  729. input_ids = input_ids[:, -_slen:]
  730. position_ids = position_ids[:, -_slen:]
  731. if langs is not None:
  732. langs = langs[:, -_slen:]
  733. mask = mask[:, -_slen:]
  734. attn_mask = attn_mask[:, -_slen:]
  735. # embeddings
  736. if inputs_embeds is None:
  737. inputs_embeds = self.embeddings(input_ids)
  738. tensor = inputs_embeds + self.position_embeddings(position_ids).expand_as(inputs_embeds)
  739. if langs is not None and self.use_lang_emb and self.n_langs > 1:
  740. tensor = tensor + self.lang_embeddings(langs)
  741. if token_type_ids is not None:
  742. tensor = tensor + self.embeddings(token_type_ids)
  743. tensor = self.layer_norm_emb(tensor)
  744. tensor = nn.functional.dropout(tensor, p=self.dropout, training=self.training)
  745. tensor *= mask.unsqueeze(-1).to(tensor.dtype)
  746. # transformer layers
  747. hidden_states = () if output_hidden_states else None
  748. attentions = () if output_attentions else None
  749. for i in range(self.n_layers):
  750. if output_hidden_states:
  751. hidden_states = hidden_states + (tensor,)
  752. # self attention
  753. attn_outputs = self.attentions[i](
  754. tensor,
  755. attn_mask,
  756. cache=cache,
  757. head_mask=head_mask[i],
  758. output_attentions=output_attentions,
  759. cache_position=cache_position,
  760. )
  761. attn = attn_outputs[0]
  762. if output_attentions:
  763. attentions = attentions + (attn_outputs[1],)
  764. attn = nn.functional.dropout(attn, p=self.dropout, training=self.training)
  765. tensor = tensor + attn
  766. tensor = self.layer_norm1[i](tensor)
  767. # FFN
  768. tensor = tensor + self.ffns[i](tensor)
  769. tensor = self.layer_norm2[i](tensor)
  770. tensor *= mask.unsqueeze(-1).to(tensor.dtype)
  771. # Add last hidden state
  772. if output_hidden_states:
  773. hidden_states = hidden_states + (tensor,)
  774. if not return_dict:
  775. return tuple(v for v in [tensor, hidden_states, attentions] if v is not None)
  776. return BaseModelOutput(last_hidden_state=tensor, hidden_states=hidden_states, attentions=attentions)
  777. class XLMPredLayer(nn.Module):
  778. """
  779. Prediction layer (cross_entropy or adaptive_softmax).
  780. """
  781. def __init__(self, config):
  782. super().__init__()
  783. self.asm = config.asm
  784. self.n_words = config.n_words
  785. self.pad_index = config.pad_index
  786. dim = config.emb_dim
  787. if config.asm is False:
  788. self.proj = nn.Linear(dim, config.n_words, bias=True)
  789. else:
  790. self.proj = nn.AdaptiveLogSoftmaxWithLoss(
  791. in_features=dim,
  792. n_classes=config.n_words,
  793. cutoffs=config.asm_cutoffs,
  794. div_value=config.asm_div_value,
  795. head_bias=True, # default is False
  796. )
  797. def forward(self, x, y=None):
  798. """Compute the loss, and optionally the scores."""
  799. outputs = ()
  800. if self.asm is False:
  801. scores = self.proj(x)
  802. outputs = (scores,) + outputs
  803. if y is not None:
  804. loss = nn.functional.cross_entropy(scores.view(-1, self.n_words), y.view(-1), reduction="mean")
  805. outputs = (loss,) + outputs
  806. else:
  807. scores = self.proj.log_prob(x)
  808. outputs = (scores,) + outputs
  809. if y is not None:
  810. _, loss = self.proj(x, y)
  811. outputs = (loss,) + outputs
  812. return outputs
  813. @auto_docstring(
  814. custom_intro="""
  815. The XLM Model transformer with a language modeling head on top (linear layer with weights tied to the input
  816. embeddings).
  817. """
  818. )
  819. class XLMWithLMHeadModel(XLMPreTrainedModel, GenerationMixin):
  820. _tied_weights_keys = ["pred_layer.proj.weight"]
  821. def __init__(self, config):
  822. super().__init__(config)
  823. self.transformer = XLMModel(config)
  824. self.pred_layer = XLMPredLayer(config)
  825. # Initialize weights and apply final processing
  826. self.post_init()
  827. def get_output_embeddings(self):
  828. return self.pred_layer.proj
  829. def set_output_embeddings(self, new_embeddings):
  830. self.pred_layer.proj = new_embeddings
  831. def prepare_inputs_for_generation(self, input_ids, **kwargs):
  832. # Overwritten -- this model uses config options to prepare inputs
  833. mask_token_id = self.config.mask_token_id
  834. lang_id = self.config.lang_id
  835. effective_batch_size = input_ids.shape[0]
  836. mask_token = torch.full((effective_batch_size, 1), mask_token_id, dtype=torch.long, device=input_ids.device)
  837. input_ids = torch.cat([input_ids, mask_token], dim=1)
  838. if lang_id is not None:
  839. langs = torch.full_like(input_ids, lang_id)
  840. else:
  841. langs = None
  842. model_inputs = {"input_ids": input_ids, "langs": langs}
  843. # They are calculated on the fly on XLMModel.forward()
  844. kwargs.pop("token_type_ids", None)
  845. kwargs.pop("attention_mask", None)
  846. # Forward ALL kwargs that are uninitialized (e.g. `use_cache`).
  847. for key, value in kwargs.items():
  848. if key not in model_inputs:
  849. model_inputs[key] = value
  850. return model_inputs
  851. @auto_docstring
  852. def forward(
  853. self,
  854. input_ids: Optional[torch.Tensor] = None,
  855. attention_mask: Optional[torch.Tensor] = None,
  856. langs: Optional[torch.Tensor] = None,
  857. token_type_ids: Optional[torch.Tensor] = None,
  858. position_ids: Optional[torch.Tensor] = None,
  859. lengths: Optional[torch.Tensor] = None,
  860. cache: Optional[dict[str, torch.Tensor]] = None,
  861. head_mask: Optional[torch.Tensor] = None,
  862. inputs_embeds: Optional[torch.Tensor] = None,
  863. labels: Optional[torch.Tensor] = None,
  864. output_attentions: Optional[bool] = None,
  865. output_hidden_states: Optional[bool] = None,
  866. return_dict: Optional[bool] = None,
  867. cache_position: Optional[torch.Tensor] = None,
  868. **kwargs,
  869. ) -> Union[tuple, MaskedLMOutput]:
  870. r"""
  871. langs (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
  872. A parallel sequence of tokens to be used to indicate the language of each token in the input. Indices are
  873. languages ids which can be obtained from the language names by using two conversion mappings provided in
  874. the configuration of the model (only provided for multilingual models). More precisely, the *language name
  875. to language id* mapping is in `model.config.lang2id` (which is a dictionary string to int) and the
  876. *language id to language name* mapping is in `model.config.id2lang` (dictionary int to string).
  877. See usage examples detailed in the [multilingual documentation](../multilingual).
  878. lengths (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
  879. Length of each sentence that can be used to avoid performing attention on padding token indices. You can
  880. also use *attention_mask* for the same result (see above), kept here for compatibility. Indices selected in
  881. `[0, ..., input_ids.size(-1)]`.
  882. cache (`dict[str, torch.FloatTensor]`, *optional*):
  883. Instance of `EncoderDecoderCache` that contains precomputed KV states. Can be used to speed up sequential
  884. decoding.
  885. labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
  886. Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
  887. `labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100`
  888. are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]`
  889. """
  890. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  891. transformer_outputs = self.transformer(
  892. input_ids,
  893. attention_mask=attention_mask,
  894. langs=langs,
  895. token_type_ids=token_type_ids,
  896. position_ids=position_ids,
  897. lengths=lengths,
  898. cache=cache,
  899. head_mask=head_mask,
  900. inputs_embeds=inputs_embeds,
  901. output_attentions=output_attentions,
  902. output_hidden_states=output_hidden_states,
  903. return_dict=return_dict,
  904. cache_position=cache_position,
  905. **kwargs,
  906. )
  907. output = transformer_outputs[0]
  908. outputs = self.pred_layer(output, labels) # (loss, logits) or (logits,) depending on if labels are provided.
  909. if not return_dict:
  910. return outputs + transformer_outputs[1:]
  911. return MaskedLMOutput(
  912. loss=outputs[0] if labels is not None else None,
  913. logits=outputs[0] if labels is None else outputs[1],
  914. hidden_states=transformer_outputs.hidden_states,
  915. attentions=transformer_outputs.attentions,
  916. )
  917. @auto_docstring(
  918. custom_intro="""
  919. XLM Model with a sequence classification/regression head on top (a linear layer on top of the pooled output) e.g.
  920. for GLUE tasks.
  921. """
  922. )
  923. class XLMForSequenceClassification(XLMPreTrainedModel):
  924. def __init__(self, config):
  925. super().__init__(config)
  926. self.num_labels = config.num_labels
  927. self.config = config
  928. self.transformer = XLMModel(config)
  929. self.sequence_summary = XLMSequenceSummary(config)
  930. # Initialize weights and apply final processing
  931. self.post_init()
  932. @auto_docstring
  933. def forward(
  934. self,
  935. input_ids: Optional[torch.Tensor] = None,
  936. attention_mask: Optional[torch.Tensor] = None,
  937. langs: Optional[torch.Tensor] = None,
  938. token_type_ids: Optional[torch.Tensor] = None,
  939. position_ids: Optional[torch.Tensor] = None,
  940. lengths: Optional[torch.Tensor] = None,
  941. cache: Optional[dict[str, torch.Tensor]] = None,
  942. head_mask: Optional[torch.Tensor] = None,
  943. inputs_embeds: Optional[torch.Tensor] = None,
  944. labels: Optional[torch.Tensor] = None,
  945. output_attentions: Optional[bool] = None,
  946. output_hidden_states: Optional[bool] = None,
  947. return_dict: Optional[bool] = None,
  948. ) -> Union[tuple, SequenceClassifierOutput]:
  949. r"""
  950. langs (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
  951. A parallel sequence of tokens to be used to indicate the language of each token in the input. Indices are
  952. languages ids which can be obtained from the language names by using two conversion mappings provided in
  953. the configuration of the model (only provided for multilingual models). More precisely, the *language name
  954. to language id* mapping is in `model.config.lang2id` (which is a dictionary string to int) and the
  955. *language id to language name* mapping is in `model.config.id2lang` (dictionary int to string).
  956. See usage examples detailed in the [multilingual documentation](../multilingual).
  957. lengths (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
  958. Length of each sentence that can be used to avoid performing attention on padding token indices. You can
  959. also use *attention_mask* for the same result (see above), kept here for compatibility. Indices selected in
  960. `[0, ..., input_ids.size(-1)]`.
  961. cache (`dict[str, torch.FloatTensor]`, *optional*):
  962. Instance of `EncoderDecoderCache` that contains precomputed KV states. Can be used to speed up sequential
  963. decoding.
  964. labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
  965. Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
  966. config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
  967. `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
  968. """
  969. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  970. transformer_outputs = self.transformer(
  971. input_ids,
  972. attention_mask=attention_mask,
  973. langs=langs,
  974. token_type_ids=token_type_ids,
  975. position_ids=position_ids,
  976. lengths=lengths,
  977. cache=cache,
  978. head_mask=head_mask,
  979. inputs_embeds=inputs_embeds,
  980. output_attentions=output_attentions,
  981. output_hidden_states=output_hidden_states,
  982. return_dict=return_dict,
  983. )
  984. output = transformer_outputs[0]
  985. logits = self.sequence_summary(output)
  986. loss = None
  987. if labels is not None:
  988. if self.config.problem_type is None:
  989. if self.num_labels == 1:
  990. self.config.problem_type = "regression"
  991. elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
  992. self.config.problem_type = "single_label_classification"
  993. else:
  994. self.config.problem_type = "multi_label_classification"
  995. if self.config.problem_type == "regression":
  996. loss_fct = MSELoss()
  997. if self.num_labels == 1:
  998. loss = loss_fct(logits.squeeze(), labels.squeeze())
  999. else:
  1000. loss = loss_fct(logits, labels)
  1001. elif self.config.problem_type == "single_label_classification":
  1002. loss_fct = CrossEntropyLoss()
  1003. loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
  1004. elif self.config.problem_type == "multi_label_classification":
  1005. loss_fct = BCEWithLogitsLoss()
  1006. loss = loss_fct(logits, labels)
  1007. if not return_dict:
  1008. output = (logits,) + transformer_outputs[1:]
  1009. return ((loss,) + output) if loss is not None else output
  1010. return SequenceClassifierOutput(
  1011. loss=loss,
  1012. logits=logits,
  1013. hidden_states=transformer_outputs.hidden_states,
  1014. attentions=transformer_outputs.attentions,
  1015. )
  1016. @auto_docstring(
  1017. custom_intro="""
  1018. XLM Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear
  1019. layers on top of the hidden-states output to compute `span start logits` and `span end logits`).
  1020. """
  1021. )
  1022. class XLMForQuestionAnsweringSimple(XLMPreTrainedModel):
  1023. def __init__(self, config):
  1024. super().__init__(config)
  1025. self.transformer = XLMModel(config)
  1026. self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
  1027. # Initialize weights and apply final processing
  1028. self.post_init()
  1029. @auto_docstring
  1030. def forward(
  1031. self,
  1032. input_ids: Optional[torch.Tensor] = None,
  1033. attention_mask: Optional[torch.Tensor] = None,
  1034. langs: Optional[torch.Tensor] = None,
  1035. token_type_ids: Optional[torch.Tensor] = None,
  1036. position_ids: Optional[torch.Tensor] = None,
  1037. lengths: Optional[torch.Tensor] = None,
  1038. cache: Optional[dict[str, torch.Tensor]] = None,
  1039. head_mask: Optional[torch.Tensor] = None,
  1040. inputs_embeds: Optional[torch.Tensor] = None,
  1041. start_positions: Optional[torch.Tensor] = None,
  1042. end_positions: Optional[torch.Tensor] = None,
  1043. output_attentions: Optional[bool] = None,
  1044. output_hidden_states: Optional[bool] = None,
  1045. return_dict: Optional[bool] = None,
  1046. ) -> Union[tuple, QuestionAnsweringModelOutput]:
  1047. r"""
  1048. langs (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
  1049. A parallel sequence of tokens to be used to indicate the language of each token in the input. Indices are
  1050. languages ids which can be obtained from the language names by using two conversion mappings provided in
  1051. the configuration of the model (only provided for multilingual models). More precisely, the *language name
  1052. to language id* mapping is in `model.config.lang2id` (which is a dictionary string to int) and the
  1053. *language id to language name* mapping is in `model.config.id2lang` (dictionary int to string).
  1054. See usage examples detailed in the [multilingual documentation](../multilingual).
  1055. lengths (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
  1056. Length of each sentence that can be used to avoid performing attention on padding token indices. You can
  1057. also use *attention_mask* for the same result (see above), kept here for compatibility. Indices selected in
  1058. `[0, ..., input_ids.size(-1)]`.
  1059. cache (`dict[str, torch.FloatTensor]`, *optional*):
  1060. Instance of `EncoderDecoderCache` that contains precomputed KV states. Can be used to speed up sequential
  1061. decoding.
  1062. """
  1063. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  1064. transformer_outputs = self.transformer(
  1065. input_ids,
  1066. attention_mask=attention_mask,
  1067. langs=langs,
  1068. token_type_ids=token_type_ids,
  1069. position_ids=position_ids,
  1070. lengths=lengths,
  1071. cache=cache,
  1072. head_mask=head_mask,
  1073. inputs_embeds=inputs_embeds,
  1074. output_attentions=output_attentions,
  1075. output_hidden_states=output_hidden_states,
  1076. return_dict=return_dict,
  1077. )
  1078. sequence_output = transformer_outputs[0]
  1079. logits = self.qa_outputs(sequence_output)
  1080. start_logits, end_logits = logits.split(1, dim=-1)
  1081. start_logits = start_logits.squeeze(-1).contiguous()
  1082. end_logits = end_logits.squeeze(-1).contiguous()
  1083. total_loss = None
  1084. if start_positions is not None and end_positions is not None:
  1085. # If we are on multi-GPU, split add a dimension
  1086. if len(start_positions.size()) > 1:
  1087. start_positions = start_positions.squeeze(-1)
  1088. if len(end_positions.size()) > 1:
  1089. end_positions = end_positions.squeeze(-1)
  1090. # sometimes the start/end positions are outside our model inputs, we ignore these terms
  1091. ignored_index = start_logits.size(1)
  1092. start_positions = start_positions.clamp(0, ignored_index)
  1093. end_positions = end_positions.clamp(0, ignored_index)
  1094. loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
  1095. start_loss = loss_fct(start_logits, start_positions)
  1096. end_loss = loss_fct(end_logits, end_positions)
  1097. total_loss = (start_loss + end_loss) / 2
  1098. if not return_dict:
  1099. output = (start_logits, end_logits) + transformer_outputs[1:]
  1100. return ((total_loss,) + output) if total_loss is not None else output
  1101. return QuestionAnsweringModelOutput(
  1102. loss=total_loss,
  1103. start_logits=start_logits,
  1104. end_logits=end_logits,
  1105. hidden_states=transformer_outputs.hidden_states,
  1106. attentions=transformer_outputs.attentions,
  1107. )
  1108. @auto_docstring
  1109. class XLMForQuestionAnswering(XLMPreTrainedModel):
  1110. def __init__(self, config):
  1111. super().__init__(config)
  1112. self.transformer = XLMModel(config)
  1113. self.qa_outputs = XLMSQuADHead(config)
  1114. # Initialize weights and apply final processing
  1115. self.post_init()
  1116. @auto_docstring
  1117. def forward(
  1118. self,
  1119. input_ids: Optional[torch.Tensor] = None,
  1120. attention_mask: Optional[torch.Tensor] = None,
  1121. langs: Optional[torch.Tensor] = None,
  1122. token_type_ids: Optional[torch.Tensor] = None,
  1123. position_ids: Optional[torch.Tensor] = None,
  1124. lengths: Optional[torch.Tensor] = None,
  1125. cache: Optional[dict[str, torch.Tensor]] = None,
  1126. head_mask: Optional[torch.Tensor] = None,
  1127. inputs_embeds: Optional[torch.Tensor] = None,
  1128. start_positions: Optional[torch.Tensor] = None,
  1129. end_positions: Optional[torch.Tensor] = None,
  1130. is_impossible: Optional[torch.Tensor] = None,
  1131. cls_index: Optional[torch.Tensor] = None,
  1132. p_mask: Optional[torch.Tensor] = None,
  1133. output_attentions: Optional[bool] = None,
  1134. output_hidden_states: Optional[bool] = None,
  1135. return_dict: Optional[bool] = None,
  1136. ) -> Union[tuple, XLMForQuestionAnsweringOutput]:
  1137. r"""
  1138. langs (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
  1139. A parallel sequence of tokens to be used to indicate the language of each token in the input. Indices are
  1140. languages ids which can be obtained from the language names by using two conversion mappings provided in
  1141. the configuration of the model (only provided for multilingual models). More precisely, the *language name
  1142. to language id* mapping is in `model.config.lang2id` (which is a dictionary string to int) and the
  1143. *language id to language name* mapping is in `model.config.id2lang` (dictionary int to string).
  1144. See usage examples detailed in the [multilingual documentation](../multilingual).
  1145. lengths (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
  1146. Length of each sentence that can be used to avoid performing attention on padding token indices. You can
  1147. also use *attention_mask* for the same result (see above), kept here for compatibility. Indices selected in
  1148. `[0, ..., input_ids.size(-1)]`.
  1149. cache (`dict[str, torch.FloatTensor]`, *optional*):
  1150. Instance of `EncoderDecoderCache` that contains precomputed KV states. Can be used to speed up sequential
  1151. decoding.
  1152. is_impossible (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
  1153. Labels whether a question has an answer or no answer (SQuAD 2.0)
  1154. cls_index (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
  1155. Labels for position (index) of the classification token to use as input for computing plausibility of the
  1156. answer.
  1157. p_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
  1158. Optional mask of tokens which can't be in answers (e.g. [CLS], [PAD], ...). 1.0 means token should be
  1159. masked. 0.0 mean token is not masked.
  1160. Example:
  1161. ```python
  1162. >>> from transformers import AutoTokenizer, XLMForQuestionAnswering
  1163. >>> import torch
  1164. >>> tokenizer = AutoTokenizer.from_pretrained("FacebookAI/xlm-mlm-en-2048")
  1165. >>> model = XLMForQuestionAnswering.from_pretrained("FacebookAI/xlm-mlm-en-2048")
  1166. >>> input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute", add_special_tokens=True)).unsqueeze(
  1167. ... 0
  1168. ... ) # Batch size 1
  1169. >>> start_positions = torch.tensor([1])
  1170. >>> end_positions = torch.tensor([3])
  1171. >>> outputs = model(input_ids, start_positions=start_positions, end_positions=end_positions)
  1172. >>> loss = outputs.loss
  1173. ```"""
  1174. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  1175. transformer_outputs = self.transformer(
  1176. input_ids,
  1177. attention_mask=attention_mask,
  1178. langs=langs,
  1179. token_type_ids=token_type_ids,
  1180. position_ids=position_ids,
  1181. lengths=lengths,
  1182. cache=cache,
  1183. head_mask=head_mask,
  1184. inputs_embeds=inputs_embeds,
  1185. output_attentions=output_attentions,
  1186. output_hidden_states=output_hidden_states,
  1187. return_dict=return_dict,
  1188. )
  1189. output = transformer_outputs[0]
  1190. outputs = self.qa_outputs(
  1191. output,
  1192. start_positions=start_positions,
  1193. end_positions=end_positions,
  1194. cls_index=cls_index,
  1195. is_impossible=is_impossible,
  1196. p_mask=p_mask,
  1197. return_dict=return_dict,
  1198. )
  1199. if not return_dict:
  1200. return outputs + transformer_outputs[1:]
  1201. return XLMForQuestionAnsweringOutput(
  1202. loss=outputs.loss,
  1203. start_top_log_probs=outputs.start_top_log_probs,
  1204. start_top_index=outputs.start_top_index,
  1205. end_top_log_probs=outputs.end_top_log_probs,
  1206. end_top_index=outputs.end_top_index,
  1207. cls_logits=outputs.cls_logits,
  1208. hidden_states=transformer_outputs.hidden_states,
  1209. attentions=transformer_outputs.attentions,
  1210. )
  1211. @auto_docstring
  1212. class XLMForTokenClassification(XLMPreTrainedModel):
  1213. def __init__(self, config):
  1214. super().__init__(config)
  1215. self.num_labels = config.num_labels
  1216. self.transformer = XLMModel(config)
  1217. self.dropout = nn.Dropout(config.dropout)
  1218. self.classifier = nn.Linear(config.hidden_size, config.num_labels)
  1219. # Initialize weights and apply final processing
  1220. self.post_init()
  1221. @auto_docstring
  1222. def forward(
  1223. self,
  1224. input_ids: Optional[torch.Tensor] = None,
  1225. attention_mask: Optional[torch.Tensor] = None,
  1226. langs: Optional[torch.Tensor] = None,
  1227. token_type_ids: Optional[torch.Tensor] = None,
  1228. position_ids: Optional[torch.Tensor] = None,
  1229. lengths: Optional[torch.Tensor] = None,
  1230. cache: Optional[dict[str, torch.Tensor]] = None,
  1231. head_mask: Optional[torch.Tensor] = None,
  1232. inputs_embeds: Optional[torch.Tensor] = None,
  1233. labels: Optional[torch.Tensor] = None,
  1234. output_attentions: Optional[bool] = None,
  1235. output_hidden_states: Optional[bool] = None,
  1236. return_dict: Optional[bool] = None,
  1237. ) -> Union[tuple, TokenClassifierOutput]:
  1238. r"""
  1239. langs (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
  1240. A parallel sequence of tokens to be used to indicate the language of each token in the input. Indices are
  1241. languages ids which can be obtained from the language names by using two conversion mappings provided in
  1242. the configuration of the model (only provided for multilingual models). More precisely, the *language name
  1243. to language id* mapping is in `model.config.lang2id` (which is a dictionary string to int) and the
  1244. *language id to language name* mapping is in `model.config.id2lang` (dictionary int to string).
  1245. See usage examples detailed in the [multilingual documentation](../multilingual).
  1246. lengths (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
  1247. Length of each sentence that can be used to avoid performing attention on padding token indices. You can
  1248. also use *attention_mask* for the same result (see above), kept here for compatibility. Indices selected in
  1249. `[0, ..., input_ids.size(-1)]`.
  1250. cache (`dict[str, torch.FloatTensor]`, *optional*):
  1251. Instance of `EncoderDecoderCache` that contains precomputed KV states. Can be used to speed up sequential
  1252. decoding.
  1253. labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
  1254. Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
  1255. """
  1256. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  1257. outputs = self.transformer(
  1258. input_ids,
  1259. attention_mask=attention_mask,
  1260. langs=langs,
  1261. token_type_ids=token_type_ids,
  1262. position_ids=position_ids,
  1263. lengths=lengths,
  1264. cache=cache,
  1265. head_mask=head_mask,
  1266. inputs_embeds=inputs_embeds,
  1267. output_attentions=output_attentions,
  1268. output_hidden_states=output_hidden_states,
  1269. return_dict=return_dict,
  1270. )
  1271. sequence_output = outputs[0]
  1272. sequence_output = self.dropout(sequence_output)
  1273. logits = self.classifier(sequence_output)
  1274. loss = None
  1275. if labels is not None:
  1276. loss_fct = CrossEntropyLoss()
  1277. loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
  1278. if not return_dict:
  1279. output = (logits,) + outputs[1:]
  1280. return ((loss,) + output) if loss is not None else output
  1281. return TokenClassifierOutput(
  1282. loss=loss,
  1283. logits=logits,
  1284. hidden_states=outputs.hidden_states,
  1285. attentions=outputs.attentions,
  1286. )
  1287. @auto_docstring
  1288. class XLMForMultipleChoice(XLMPreTrainedModel):
  1289. def __init__(self, config, *inputs, **kwargs):
  1290. super().__init__(config, *inputs, **kwargs)
  1291. self.transformer = XLMModel(config)
  1292. self.sequence_summary = XLMSequenceSummary(config)
  1293. self.logits_proj = nn.Linear(config.num_labels, 1)
  1294. # Initialize weights and apply final processing
  1295. self.post_init()
  1296. @auto_docstring
  1297. def forward(
  1298. self,
  1299. input_ids: Optional[torch.Tensor] = None,
  1300. attention_mask: Optional[torch.Tensor] = None,
  1301. langs: Optional[torch.Tensor] = None,
  1302. token_type_ids: Optional[torch.Tensor] = None,
  1303. position_ids: Optional[torch.Tensor] = None,
  1304. lengths: Optional[torch.Tensor] = None,
  1305. cache: Optional[dict[str, torch.Tensor]] = None,
  1306. head_mask: Optional[torch.Tensor] = None,
  1307. inputs_embeds: Optional[torch.Tensor] = None,
  1308. labels: Optional[torch.Tensor] = None,
  1309. output_attentions: Optional[bool] = None,
  1310. output_hidden_states: Optional[bool] = None,
  1311. return_dict: Optional[bool] = None,
  1312. ) -> Union[tuple, MultipleChoiceModelOutput]:
  1313. r"""
  1314. input_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`):
  1315. Indices of input sequence tokens in the vocabulary.
  1316. Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
  1317. [`PreTrainedTokenizer.__call__`] for details.
  1318. [What are input IDs?](../glossary#input-ids)
  1319. langs (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`, *optional*):
  1320. A parallel sequence of tokens to be used to indicate the language of each token in the input. Indices are
  1321. languages ids which can be obtained from the language names by using two conversion mappings provided in
  1322. the configuration of the model (only provided for multilingual models). More precisely, the *language name
  1323. to language id* mapping is in `model.config.lang2id` (which is a dictionary string to int) and the
  1324. *language id to language name* mapping is in `model.config.id2lang` (dictionary int to string).
  1325. See usage examples detailed in the [multilingual documentation](../multilingual).
  1326. token_type_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`, *optional*):
  1327. Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
  1328. 1]`:
  1329. - 0 corresponds to a *sentence A* token,
  1330. - 1 corresponds to a *sentence B* token.
  1331. [What are token type IDs?](../glossary#token-type-ids)
  1332. position_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`, *optional*):
  1333. Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
  1334. config.max_position_embeddings - 1]`.
  1335. [What are position IDs?](../glossary#position-ids)
  1336. lengths (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
  1337. Length of each sentence that can be used to avoid performing attention on padding token indices. You can
  1338. also use *attention_mask* for the same result (see above), kept here for compatibility. Indices selected in
  1339. `[0, ..., input_ids.size(-1)]`.
  1340. cache (`dict[str, torch.FloatTensor]`, *optional*):
  1341. Instance of `EncoderDecoderCache` that contains precomputed KV states. Can be used to speed up sequential
  1342. decoding.
  1343. inputs_embeds (`torch.FloatTensor` of shape `(batch_size, num_choices, sequence_length, hidden_size)`, *optional*):
  1344. Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
  1345. is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
  1346. model's internal embedding lookup matrix.
  1347. labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
  1348. Labels for computing the multiple choice classification loss. Indices should be in `[0, ...,
  1349. num_choices-1]` where `num_choices` is the size of the second dimension of the input tensors. (See
  1350. `input_ids` above)
  1351. """
  1352. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  1353. num_choices = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1]
  1354. input_ids = input_ids.view(-1, input_ids.size(-1)) if input_ids is not None else None
  1355. attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None
  1356. token_type_ids = token_type_ids.view(-1, token_type_ids.size(-1)) if token_type_ids is not None else None
  1357. position_ids = position_ids.view(-1, position_ids.size(-1)) if position_ids is not None else None
  1358. langs = langs.view(-1, langs.size(-1)) if langs is not None else None
  1359. inputs_embeds = (
  1360. inputs_embeds.view(-1, inputs_embeds.size(-2), inputs_embeds.size(-1))
  1361. if inputs_embeds is not None
  1362. else None
  1363. )
  1364. if lengths is not None:
  1365. logger.warning(
  1366. "The `lengths` parameter cannot be used with the XLM multiple choice models. Please use the "
  1367. "attention mask instead."
  1368. )
  1369. lengths = None
  1370. transformer_outputs = self.transformer(
  1371. input_ids=input_ids,
  1372. attention_mask=attention_mask,
  1373. langs=langs,
  1374. token_type_ids=token_type_ids,
  1375. position_ids=position_ids,
  1376. lengths=lengths,
  1377. cache=cache,
  1378. head_mask=head_mask,
  1379. inputs_embeds=inputs_embeds,
  1380. output_attentions=output_attentions,
  1381. output_hidden_states=output_hidden_states,
  1382. return_dict=return_dict,
  1383. )
  1384. output = transformer_outputs[0]
  1385. logits = self.sequence_summary(output)
  1386. logits = self.logits_proj(logits)
  1387. reshaped_logits = logits.view(-1, num_choices)
  1388. loss = None
  1389. if labels is not None:
  1390. loss_fct = CrossEntropyLoss()
  1391. loss = loss_fct(reshaped_logits, labels)
  1392. if not return_dict:
  1393. output = (reshaped_logits,) + transformer_outputs[1:]
  1394. return ((loss,) + output) if loss is not None else output
  1395. return MultipleChoiceModelOutput(
  1396. loss=loss,
  1397. logits=reshaped_logits,
  1398. hidden_states=transformer_outputs.hidden_states,
  1399. attentions=transformer_outputs.attentions,
  1400. )
  1401. __all__ = [
  1402. "XLMForMultipleChoice",
  1403. "XLMForQuestionAnswering",
  1404. "XLMForQuestionAnsweringSimple",
  1405. "XLMForSequenceClassification",
  1406. "XLMForTokenClassification",
  1407. "XLMModel",
  1408. "XLMPreTrainedModel",
  1409. "XLMWithLMHeadModel",
  1410. ]