modeling_xlnet.py 95 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171
  1. # Copyright 2018 Google AI, Google Brain and Carnegie Mellon University Authors and the HuggingFace Inc. team.
  2. # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
  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 XLNet model.
  17. """
  18. from collections.abc import Callable
  19. from dataclasses import dataclass
  20. import torch
  21. from torch import nn
  22. from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
  23. from ... import initialization as init
  24. from ...activations import ACT2FN, get_activation
  25. from ...generation import GenerationMixin
  26. from ...modeling_utils import PreTrainedModel
  27. from ...pytorch_utils import apply_chunking_to_forward
  28. from ...utils import ModelOutput, auto_docstring, logging
  29. from .configuration_xlnet import XLNetConfig
  30. logger = logging.get_logger(__name__)
  31. class XLNetRelativeAttention(nn.Module):
  32. def __init__(self, config):
  33. super().__init__()
  34. if config.d_model % config.n_head != 0:
  35. raise ValueError(
  36. f"The hidden size ({config.d_model}) is not a multiple of the number of attention "
  37. f"heads ({config.n_head}"
  38. )
  39. self.n_head = config.n_head
  40. self.d_head = config.d_head
  41. self.d_model = config.d_model
  42. self.scale = 1 / (config.d_head**0.5)
  43. self.q = nn.Parameter(torch.FloatTensor(config.d_model, self.n_head, self.d_head))
  44. self.k = nn.Parameter(torch.FloatTensor(config.d_model, self.n_head, self.d_head))
  45. self.v = nn.Parameter(torch.FloatTensor(config.d_model, self.n_head, self.d_head))
  46. self.o = nn.Parameter(torch.FloatTensor(config.d_model, self.n_head, self.d_head))
  47. self.r = nn.Parameter(torch.FloatTensor(config.d_model, self.n_head, self.d_head))
  48. self.r_r_bias = nn.Parameter(torch.FloatTensor(self.n_head, self.d_head))
  49. self.r_s_bias = nn.Parameter(torch.FloatTensor(self.n_head, self.d_head))
  50. self.r_w_bias = nn.Parameter(torch.FloatTensor(self.n_head, self.d_head))
  51. self.seg_embed = nn.Parameter(torch.FloatTensor(2, self.n_head, self.d_head))
  52. self.layer_norm = nn.LayerNorm(config.d_model, eps=config.layer_norm_eps)
  53. self.dropout = nn.Dropout(config.dropout)
  54. @staticmethod
  55. def rel_shift(x, klen=-1):
  56. """perform relative shift to form the relative attention score."""
  57. x_size = x.shape
  58. x = x.reshape(x_size[1], x_size[0], x_size[2], x_size[3])
  59. x = x[1:, ...]
  60. x = x.reshape(x_size[0], x_size[1] - 1, x_size[2], x_size[3])
  61. # x = x[:, 0:klen, :, :]
  62. x = torch.index_select(x, 1, torch.arange(klen, device=x.device, dtype=torch.long))
  63. return x
  64. @staticmethod
  65. def rel_shift_bnij(x, klen=-1):
  66. x_size = x.shape
  67. x = x.reshape(x_size[0], x_size[1], x_size[3], x_size[2])
  68. x = x[:, :, 1:, :]
  69. x = x.reshape(x_size[0], x_size[1], x_size[2], x_size[3] - 1)
  70. # Note: the tensor-slice form was faster in my testing than torch.index_select
  71. # However, tracing doesn't like the nature of the slice, and if klen changes
  72. # during the run then it'll fail, whereas index_select will be fine.
  73. x = torch.index_select(x, 3, torch.arange(klen, device=x.device, dtype=torch.long))
  74. # x = x[:, :, :, :klen]
  75. return x
  76. def rel_attn_core(
  77. self,
  78. q_head,
  79. k_head_h,
  80. v_head_h,
  81. k_head_r,
  82. seg_mat=None,
  83. attn_mask=None,
  84. output_attentions=False,
  85. ):
  86. """Core relative positional attention operations."""
  87. # content based attention score
  88. ac = torch.einsum("ibnd,jbnd->bnij", q_head + self.r_w_bias, k_head_h)
  89. # position based attention score
  90. bd = torch.einsum("ibnd,jbnd->bnij", q_head + self.r_r_bias, k_head_r)
  91. bd = self.rel_shift_bnij(bd, klen=ac.shape[3])
  92. # segment based attention score
  93. if seg_mat is None:
  94. ef = 0
  95. else:
  96. ef = torch.einsum("ibnd,snd->ibns", q_head + self.r_s_bias, self.seg_embed)
  97. ef = torch.einsum("ijbs,ibns->bnij", seg_mat, ef)
  98. # merge attention scores and perform masking
  99. attn_score = (ac + bd + ef) * self.scale
  100. if attn_mask is not None:
  101. # attn_score = attn_score * (1 - attn_mask) - 1e30 * attn_mask
  102. if attn_mask.dtype == torch.float16:
  103. attn_score = attn_score - 65500 * torch.einsum("ijbn->bnij", attn_mask)
  104. else:
  105. attn_score = attn_score - 1e30 * torch.einsum("ijbn->bnij", attn_mask)
  106. # attention probability
  107. attn_prob = nn.functional.softmax(attn_score, dim=3)
  108. attn_prob = self.dropout(attn_prob)
  109. # attention output
  110. attn_vec = torch.einsum("bnij,jbnd->ibnd", attn_prob, v_head_h)
  111. if output_attentions:
  112. return attn_vec, torch.einsum("bnij->ijbn", attn_prob)
  113. return attn_vec
  114. def post_attention(self, h, attn_vec, residual=True):
  115. """Post-attention processing."""
  116. # post-attention projection (back to `d_model`)
  117. attn_out = torch.einsum("ibnd,hnd->ibh", attn_vec, self.o)
  118. attn_out = self.dropout(attn_out)
  119. if residual:
  120. attn_out = attn_out + h
  121. output = self.layer_norm(attn_out)
  122. return output
  123. def forward(
  124. self,
  125. h,
  126. g,
  127. attn_mask_h,
  128. attn_mask_g,
  129. r,
  130. seg_mat,
  131. mems=None,
  132. target_mapping=None,
  133. output_attentions=False,
  134. ):
  135. if g is not None:
  136. # Two-stream attention with relative positional encoding.
  137. # content based attention score
  138. if mems is not None and mems.dim() > 1:
  139. cat = torch.cat([mems, h], dim=0)
  140. else:
  141. cat = h
  142. # content-based key head
  143. k_head_h = torch.einsum("ibh,hnd->ibnd", cat, self.k)
  144. # content-based value head
  145. v_head_h = torch.einsum("ibh,hnd->ibnd", cat, self.v)
  146. # position-based key head
  147. k_head_r = torch.einsum("ibh,hnd->ibnd", r, self.r)
  148. # h-stream
  149. # content-stream query head
  150. q_head_h = torch.einsum("ibh,hnd->ibnd", h, self.q)
  151. # core attention ops
  152. attn_vec_h = self.rel_attn_core(
  153. q_head_h,
  154. k_head_h,
  155. v_head_h,
  156. k_head_r,
  157. seg_mat=seg_mat,
  158. attn_mask=attn_mask_h,
  159. output_attentions=output_attentions,
  160. )
  161. if output_attentions:
  162. attn_vec_h, attn_prob_h = attn_vec_h
  163. # post processing
  164. output_h = self.post_attention(h, attn_vec_h)
  165. # g-stream
  166. # query-stream query head
  167. q_head_g = torch.einsum("ibh,hnd->ibnd", g, self.q)
  168. # core attention ops
  169. if target_mapping is not None:
  170. q_head_g = torch.einsum("mbnd,mlb->lbnd", q_head_g, target_mapping)
  171. attn_vec_g = self.rel_attn_core(
  172. q_head_g,
  173. k_head_h,
  174. v_head_h,
  175. k_head_r,
  176. seg_mat=seg_mat,
  177. attn_mask=attn_mask_g,
  178. output_attentions=output_attentions,
  179. )
  180. if output_attentions:
  181. attn_vec_g, attn_prob_g = attn_vec_g
  182. attn_vec_g = torch.einsum("lbnd,mlb->mbnd", attn_vec_g, target_mapping)
  183. else:
  184. attn_vec_g = self.rel_attn_core(
  185. q_head_g,
  186. k_head_h,
  187. v_head_h,
  188. k_head_r,
  189. seg_mat=seg_mat,
  190. attn_mask=attn_mask_g,
  191. output_attentions=output_attentions,
  192. )
  193. if output_attentions:
  194. attn_vec_g, attn_prob_g = attn_vec_g
  195. # post processing
  196. output_g = self.post_attention(g, attn_vec_g)
  197. if output_attentions:
  198. attn_prob = attn_prob_h, attn_prob_g
  199. else:
  200. # Multi-head attention with relative positional encoding
  201. if mems is not None and mems.dim() > 1:
  202. cat = torch.cat([mems, h], dim=0)
  203. else:
  204. cat = h
  205. # content heads
  206. q_head_h = torch.einsum("ibh,hnd->ibnd", h, self.q)
  207. k_head_h = torch.einsum("ibh,hnd->ibnd", cat, self.k)
  208. v_head_h = torch.einsum("ibh,hnd->ibnd", cat, self.v)
  209. # positional heads
  210. # type casting for fp16 support
  211. k_head_r = torch.einsum("ibh,hnd->ibnd", r.type(self.r.dtype), self.r)
  212. # core attention ops
  213. attn_vec = self.rel_attn_core(
  214. q_head_h,
  215. k_head_h,
  216. v_head_h,
  217. k_head_r,
  218. seg_mat=seg_mat,
  219. attn_mask=attn_mask_h,
  220. output_attentions=output_attentions,
  221. )
  222. if output_attentions:
  223. attn_vec, attn_prob = attn_vec
  224. # post processing
  225. output_h = self.post_attention(h, attn_vec)
  226. output_g = None
  227. outputs = (output_h, output_g)
  228. if output_attentions:
  229. outputs = outputs + (attn_prob,)
  230. return outputs
  231. class XLNetFeedForward(nn.Module):
  232. def __init__(self, config):
  233. super().__init__()
  234. self.layer_norm = nn.LayerNorm(config.d_model, eps=config.layer_norm_eps)
  235. self.layer_1 = nn.Linear(config.d_model, config.d_inner)
  236. self.layer_2 = nn.Linear(config.d_inner, config.d_model)
  237. self.dropout = nn.Dropout(config.dropout)
  238. if isinstance(config.ff_activation, str):
  239. self.activation_function = ACT2FN[config.ff_activation]
  240. else:
  241. self.activation_function = config.ff_activation
  242. def forward(self, inp):
  243. output = inp
  244. output = self.layer_1(output)
  245. output = self.activation_function(output)
  246. output = self.dropout(output)
  247. output = self.layer_2(output)
  248. output = self.dropout(output)
  249. output = self.layer_norm(output + inp)
  250. return output
  251. class XLNetLayer(nn.Module):
  252. def __init__(self, config):
  253. super().__init__()
  254. self.rel_attn = XLNetRelativeAttention(config)
  255. self.ff = XLNetFeedForward(config)
  256. self.dropout = nn.Dropout(config.dropout)
  257. self.chunk_size_feed_forward = config.chunk_size_feed_forward
  258. self.seq_len_dim = 1
  259. def forward(
  260. self,
  261. output_h,
  262. output_g,
  263. attn_mask_h,
  264. attn_mask_g,
  265. r,
  266. seg_mat,
  267. mems=None,
  268. target_mapping=None,
  269. output_attentions=False,
  270. ):
  271. outputs = self.rel_attn(
  272. output_h,
  273. output_g,
  274. attn_mask_h,
  275. attn_mask_g,
  276. r,
  277. seg_mat,
  278. mems=mems,
  279. target_mapping=target_mapping,
  280. output_attentions=output_attentions,
  281. )
  282. output_h, output_g = outputs[:2]
  283. if output_g is not None:
  284. output_g = apply_chunking_to_forward(
  285. self.ff_chunk, self.chunk_size_feed_forward, self.seq_len_dim, output_g
  286. )
  287. output_h = apply_chunking_to_forward(self.ff_chunk, self.chunk_size_feed_forward, self.seq_len_dim, output_h)
  288. outputs = (output_h, output_g) + outputs[2:] # Add again attentions if there are there
  289. return outputs
  290. def ff_chunk(self, output_x):
  291. output_x = self.ff(output_x)
  292. return output_x
  293. # Copied from transformers.models.xlm.modeling_xlm.XLMPoolerStartLogits with XLM->XLNet
  294. class XLNetPoolerStartLogits(nn.Module):
  295. """
  296. Compute SQuAD start logits from sequence hidden states.
  297. Args:
  298. config ([`XLNetConfig`]):
  299. The config used by the model, will be used to grab the `hidden_size` of the model.
  300. """
  301. def __init__(self, config: XLNetConfig):
  302. super().__init__()
  303. self.dense = nn.Linear(config.hidden_size, 1)
  304. def forward(self, hidden_states: torch.FloatTensor, p_mask: torch.FloatTensor | None = None) -> torch.FloatTensor:
  305. """
  306. Args:
  307. hidden_states (`torch.FloatTensor` of shape `(batch_size, seq_len, hidden_size)`):
  308. The final hidden states of the model.
  309. p_mask (`torch.FloatTensor` of shape `(batch_size, seq_len)`, *optional*):
  310. Mask for tokens at invalid position, such as query and special symbols (PAD, SEP, CLS). 1.0 means token
  311. should be masked.
  312. Returns:
  313. `torch.FloatTensor`: The start logits for SQuAD.
  314. """
  315. x = self.dense(hidden_states).squeeze(-1)
  316. if p_mask is not None:
  317. if p_mask.dtype == torch.float16:
  318. x = x * (1 - p_mask) - 65500 * p_mask
  319. else:
  320. x = x * (1 - p_mask) - 1e30 * p_mask
  321. return x
  322. # Copied from transformers.models.xlm.modeling_xlm.XLMPoolerEndLogits with XLM->XLNet
  323. class XLNetPoolerEndLogits(nn.Module):
  324. """
  325. Compute SQuAD end logits from sequence hidden states.
  326. Args:
  327. config ([`XLNetConfig`]):
  328. The config used by the model, will be used to grab the `hidden_size` of the model and the `layer_norm_eps`
  329. to use.
  330. """
  331. def __init__(self, config: XLNetConfig):
  332. super().__init__()
  333. self.dense_0 = nn.Linear(config.hidden_size * 2, config.hidden_size)
  334. self.activation = nn.Tanh()
  335. self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
  336. self.dense_1 = nn.Linear(config.hidden_size, 1)
  337. def forward(
  338. self,
  339. hidden_states: torch.FloatTensor,
  340. start_states: torch.FloatTensor | None = None,
  341. start_positions: torch.LongTensor | None = None,
  342. p_mask: torch.FloatTensor | None = None,
  343. ) -> torch.FloatTensor:
  344. """
  345. Args:
  346. hidden_states (`torch.FloatTensor` of shape `(batch_size, seq_len, hidden_size)`):
  347. The final hidden states of the model.
  348. start_states (`torch.FloatTensor` of shape `(batch_size, seq_len, hidden_size)`, *optional*):
  349. The hidden states of the first tokens for the labeled span.
  350. start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
  351. The position of the first token for the labeled span.
  352. p_mask (`torch.FloatTensor` of shape `(batch_size, seq_len)`, *optional*):
  353. Mask for tokens at invalid position, such as query and special symbols (PAD, SEP, CLS). 1.0 means token
  354. should be masked.
  355. <Tip>
  356. One of `start_states` or `start_positions` should be not `None`. If both are set, `start_positions` overrides
  357. `start_states`.
  358. </Tip>
  359. Returns:
  360. `torch.FloatTensor`: The end logits for SQuAD.
  361. """
  362. assert start_states is not None or start_positions is not None, (
  363. "One of start_states, start_positions should be not None"
  364. )
  365. if start_positions is not None:
  366. slen, hsz = hidden_states.shape[-2:]
  367. start_positions = start_positions[:, None, None].expand(-1, -1, hsz) # shape (bsz, 1, hsz)
  368. start_states = hidden_states.gather(-2, start_positions) # shape (bsz, 1, hsz)
  369. start_states = start_states.expand(-1, slen, -1) # shape (bsz, slen, hsz)
  370. x = self.dense_0(torch.cat([hidden_states, start_states], dim=-1))
  371. x = self.activation(x)
  372. x = self.LayerNorm(x)
  373. x = self.dense_1(x).squeeze(-1)
  374. if p_mask is not None:
  375. if p_mask.dtype == torch.float16:
  376. x = x * (1 - p_mask) - 65500 * p_mask
  377. else:
  378. x = x * (1 - p_mask) - 1e30 * p_mask
  379. return x
  380. # Copied from transformers.models.xlm.modeling_xlm.XLMPoolerAnswerClass with XLM->XLNet
  381. class XLNetPoolerAnswerClass(nn.Module):
  382. """
  383. Compute SQuAD 2.0 answer class from classification and start tokens hidden states.
  384. Args:
  385. config ([`XLNetConfig`]):
  386. The config used by the model, will be used to grab the `hidden_size` of the model.
  387. """
  388. def __init__(self, config: XLNetConfig):
  389. super().__init__()
  390. self.dense_0 = nn.Linear(config.hidden_size * 2, config.hidden_size)
  391. self.activation = nn.Tanh()
  392. self.dense_1 = nn.Linear(config.hidden_size, 1, bias=False)
  393. def forward(
  394. self,
  395. hidden_states: torch.FloatTensor,
  396. start_states: torch.FloatTensor | None = None,
  397. start_positions: torch.LongTensor | None = None,
  398. cls_index: torch.LongTensor | None = None,
  399. ) -> torch.FloatTensor:
  400. """
  401. Args:
  402. hidden_states (`torch.FloatTensor` of shape `(batch_size, seq_len, hidden_size)`):
  403. The final hidden states of the model.
  404. start_states (`torch.FloatTensor` of shape `(batch_size, seq_len, hidden_size)`, *optional*):
  405. The hidden states of the first tokens for the labeled span.
  406. start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
  407. The position of the first token for the labeled span.
  408. cls_index (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
  409. Position of the CLS token for each sentence in the batch. If `None`, takes the last token.
  410. <Tip>
  411. One of `start_states` or `start_positions` should be not `None`. If both are set, `start_positions` overrides
  412. `start_states`.
  413. </Tip>
  414. Returns:
  415. `torch.FloatTensor`: The SQuAD 2.0 answer class.
  416. """
  417. # No dependency on end_feature so that we can obtain one single `cls_logits` for each sample.
  418. hsz = hidden_states.shape[-1]
  419. assert start_states is not None or start_positions is not None, (
  420. "One of start_states, start_positions should be not None"
  421. )
  422. if start_positions is not None:
  423. start_positions = start_positions[:, None, None].expand(-1, -1, hsz) # shape (bsz, 1, hsz)
  424. start_states = hidden_states.gather(-2, start_positions).squeeze(-2) # shape (bsz, hsz)
  425. if cls_index is not None:
  426. cls_index = cls_index[:, None, None].expand(-1, -1, hsz) # shape (bsz, 1, hsz)
  427. cls_token_state = hidden_states.gather(-2, cls_index).squeeze(-2) # shape (bsz, hsz)
  428. else:
  429. cls_token_state = hidden_states[:, -1, :] # shape (bsz, hsz)
  430. x = self.dense_0(torch.cat([start_states, cls_token_state], dim=-1))
  431. x = self.activation(x)
  432. x = self.dense_1(x).squeeze(-1)
  433. return x
  434. # Copied from transformers.models.xlm.modeling_xlm.XLMSequenceSummary with XLM->XLNet
  435. class XLNetSequenceSummary(nn.Module):
  436. r"""
  437. Compute a single vector summary of a sequence hidden states.
  438. Args:
  439. config ([`XLNetConfig`]):
  440. The config used by the model. Relevant arguments in the config class of the model are (refer to the actual
  441. config class of your model for the default values it uses):
  442. - **summary_type** (`str`) -- The method to use to make this summary. Accepted values are:
  443. - `"last"` -- Take the last token hidden state (like XLNet)
  444. - `"first"` -- Take the first token hidden state (like Bert)
  445. - `"mean"` -- Take the mean of all tokens hidden states
  446. - `"cls_index"` -- Supply a Tensor of classification token position (GPT/GPT-2)
  447. - `"attn"` -- Not implemented now, use multi-head attention
  448. - **summary_use_proj** (`bool`) -- Add a projection after the vector extraction.
  449. - **summary_proj_to_labels** (`bool`) -- If `True`, the projection outputs to `config.num_labels` classes
  450. (otherwise to `config.hidden_size`).
  451. - **summary_activation** (`Optional[str]`) -- Set to `"tanh"` to add a tanh activation to the output,
  452. another string or `None` will add no activation.
  453. - **summary_first_dropout** (`float`) -- Optional dropout probability before the projection and activation.
  454. - **summary_last_dropout** (`float`)-- Optional dropout probability after the projection and activation.
  455. """
  456. def __init__(self, config: XLNetConfig):
  457. super().__init__()
  458. self.summary_type = getattr(config, "summary_type", "last")
  459. if self.summary_type == "attn":
  460. # We should use a standard multi-head attention module with absolute positional embedding for that.
  461. # Cf. https://github.com/zihangdai/xlnet/blob/master/modeling.py#L253-L276
  462. # We can probably just use the multi-head attention module of PyTorch >=1.1.0
  463. raise NotImplementedError
  464. self.summary = nn.Identity()
  465. if hasattr(config, "summary_use_proj") and config.summary_use_proj:
  466. if hasattr(config, "summary_proj_to_labels") and config.summary_proj_to_labels and config.num_labels > 0:
  467. num_classes = config.num_labels
  468. else:
  469. num_classes = config.hidden_size
  470. self.summary = nn.Linear(config.hidden_size, num_classes)
  471. activation_string = getattr(config, "summary_activation", None)
  472. self.activation: Callable = get_activation(activation_string) if activation_string else nn.Identity()
  473. self.first_dropout = nn.Identity()
  474. if hasattr(config, "summary_first_dropout") and config.summary_first_dropout > 0:
  475. self.first_dropout = nn.Dropout(config.summary_first_dropout)
  476. self.last_dropout = nn.Identity()
  477. if hasattr(config, "summary_last_dropout") and config.summary_last_dropout > 0:
  478. self.last_dropout = nn.Dropout(config.summary_last_dropout)
  479. def forward(
  480. self, hidden_states: torch.FloatTensor, cls_index: torch.LongTensor | None = None
  481. ) -> torch.FloatTensor:
  482. """
  483. Compute a single vector summary of a sequence hidden states.
  484. Args:
  485. hidden_states (`torch.FloatTensor` of shape `[batch_size, seq_len, hidden_size]`):
  486. The hidden states of the last layer.
  487. cls_index (`torch.LongTensor` of shape `[batch_size]` or `[batch_size, ...]` where ... are optional leading dimensions of `hidden_states`, *optional*):
  488. Used if `summary_type == "cls_index"` and takes the last token of the sequence as classification token.
  489. Returns:
  490. `torch.FloatTensor`: The summary of the sequence hidden states.
  491. """
  492. if self.summary_type == "last":
  493. output = hidden_states[:, -1]
  494. elif self.summary_type == "first":
  495. output = hidden_states[:, 0]
  496. elif self.summary_type == "mean":
  497. output = hidden_states.mean(dim=1)
  498. elif self.summary_type == "cls_index":
  499. if cls_index is None:
  500. cls_index = torch.full_like(
  501. hidden_states[..., :1, :],
  502. hidden_states.shape[-2] - 1,
  503. dtype=torch.long,
  504. )
  505. else:
  506. cls_index = cls_index.unsqueeze(-1).unsqueeze(-1)
  507. cls_index = cls_index.expand((-1,) * (cls_index.dim() - 1) + (hidden_states.size(-1),))
  508. # shape of cls_index: (bsz, XX, 1, hidden_size) where XX are optional leading dim of hidden_states
  509. output = hidden_states.gather(-2, cls_index).squeeze(-2) # shape (bsz, XX, hidden_size)
  510. elif self.summary_type == "attn":
  511. raise NotImplementedError
  512. output = self.first_dropout(output)
  513. output = self.summary(output)
  514. output = self.activation(output)
  515. output = self.last_dropout(output)
  516. return output
  517. @auto_docstring
  518. class XLNetPreTrainedModel(PreTrainedModel):
  519. config: XLNetConfig
  520. base_model_prefix = "transformer"
  521. @torch.no_grad()
  522. def _init_weights(self, module):
  523. """Initialize the weights."""
  524. super()._init_weights(module)
  525. if isinstance(module, XLNetRelativeAttention):
  526. for param in [
  527. module.q,
  528. module.k,
  529. module.v,
  530. module.o,
  531. module.r,
  532. module.r_r_bias,
  533. module.r_s_bias,
  534. module.r_w_bias,
  535. module.seg_embed,
  536. ]:
  537. init.normal_(param, mean=0.0, std=self.config.initializer_range)
  538. elif isinstance(module, XLNetModel):
  539. init.normal_(module.mask_emb, mean=0.0, std=self.config.initializer_range)
  540. @dataclass
  541. @auto_docstring(
  542. custom_intro="""
  543. Output type of [`XLNetModel`].
  544. """
  545. )
  546. class XLNetModelOutput(ModelOutput):
  547. r"""
  548. last_hidden_state (`torch.FloatTensor` of shape `(batch_size, num_predict, hidden_size)`):
  549. Sequence of hidden-states at the last layer of the model.
  550. `num_predict` corresponds to `target_mapping.shape[1]`. If `target_mapping` is `None`, then `num_predict`
  551. corresponds to `sequence_length`.
  552. mems (`list[torch.FloatTensor]` of length `config.n_layers`):
  553. Contains pre-computed hidden-states. Can be used (see `mems` input) to speed up sequential decoding. The
  554. token ids which have their past given to this model should not be passed as `input_ids` as they have
  555. already been computed.
  556. """
  557. last_hidden_state: torch.FloatTensor
  558. mems: list[torch.FloatTensor] | None = None
  559. hidden_states: tuple[torch.FloatTensor, ...] | None = None
  560. attentions: tuple[torch.FloatTensor, ...] | None = None
  561. @dataclass
  562. @auto_docstring(
  563. custom_intro="""
  564. Output type of [`XLNetLMHeadModel`].
  565. """
  566. )
  567. class XLNetLMHeadModelOutput(ModelOutput):
  568. r"""
  569. loss (`torch.FloatTensor` of shape *(1,)*, *optional*, returned when `labels` is provided):
  570. Language modeling loss (for next-token prediction).
  571. logits (`torch.FloatTensor` of shape `(batch_size, num_predict, config.vocab_size)`):
  572. Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
  573. `num_predict` corresponds to `target_mapping.shape[1]`. If `target_mapping` is `None`, then `num_predict`
  574. corresponds to `sequence_length`.
  575. mems (`list[torch.FloatTensor]` of length `config.n_layers`):
  576. Contains pre-computed hidden-states. Can be used (see `mems` input) to speed up sequential decoding. The
  577. token ids which have their past given to this model should not be passed as `input_ids` as they have
  578. already been computed.
  579. """
  580. loss: torch.FloatTensor | None = None
  581. logits: torch.FloatTensor | None = None
  582. mems: list[torch.FloatTensor] | None = None
  583. hidden_states: tuple[torch.FloatTensor, ...] | None = None
  584. attentions: tuple[torch.FloatTensor, ...] | None = None
  585. @dataclass
  586. @auto_docstring(
  587. custom_intro="""
  588. Output type of [`XLNetForSequenceClassification`].
  589. """
  590. )
  591. class XLNetForSequenceClassificationOutput(ModelOutput):
  592. r"""
  593. loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `label` is provided):
  594. Classification (or regression if config.num_labels==1) loss.
  595. logits (`torch.FloatTensor` of shape `(batch_size, config.num_labels)`):
  596. Classification (or regression if config.num_labels==1) scores (before SoftMax).
  597. mems (`list[torch.FloatTensor]` of length `config.n_layers`):
  598. Contains pre-computed hidden-states. Can be used (see `mems` input) to speed up sequential decoding. The
  599. token ids which have their past given to this model should not be passed as `input_ids` as they have
  600. already been computed.
  601. """
  602. loss: torch.FloatTensor | None = None
  603. logits: torch.FloatTensor | None = None
  604. mems: list[torch.FloatTensor] | None = None
  605. hidden_states: tuple[torch.FloatTensor, ...] | None = None
  606. attentions: tuple[torch.FloatTensor, ...] | None = None
  607. @dataclass
  608. @auto_docstring(
  609. custom_intro="""
  610. Output type of [`XLNetForTokenClassificationOutput`].
  611. """
  612. )
  613. class XLNetForTokenClassificationOutput(ModelOutput):
  614. r"""
  615. loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
  616. Classification loss.
  617. logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.num_labels)`):
  618. Classification scores (before SoftMax).
  619. mems (`list[torch.FloatTensor]` of length `config.n_layers`):
  620. Contains pre-computed hidden-states. Can be used (see `mems` input) to speed up sequential decoding. The
  621. token ids which have their past given to this model should not be passed as `input_ids` as they have
  622. already been computed.
  623. """
  624. loss: torch.FloatTensor | None = None
  625. logits: torch.FloatTensor | None = None
  626. mems: list[torch.FloatTensor] | None = None
  627. hidden_states: tuple[torch.FloatTensor, ...] | None = None
  628. attentions: tuple[torch.FloatTensor, ...] | None = None
  629. @dataclass
  630. @auto_docstring(
  631. custom_intro="""
  632. Output type of [`XLNetForMultipleChoice`].
  633. """
  634. )
  635. class XLNetForMultipleChoiceOutput(ModelOutput):
  636. r"""
  637. loss (`torch.FloatTensor` of shape *(1,)*, *optional*, returned when `labels` is provided):
  638. Classification loss.
  639. logits (`torch.FloatTensor` of shape `(batch_size, num_choices)`):
  640. *num_choices* is the second dimension of the input tensors. (see *input_ids* above).
  641. Classification scores (before SoftMax).
  642. mems (`list[torch.FloatTensor]` of length `config.n_layers`):
  643. Contains pre-computed hidden-states. Can be used (see `mems` input) to speed up sequential decoding. The
  644. token ids which have their past given to this model should not be passed as `input_ids` as they have
  645. already been computed.
  646. """
  647. loss: torch.FloatTensor | None = None
  648. logits: torch.FloatTensor | None = None
  649. mems: list[torch.FloatTensor] | None = None
  650. hidden_states: tuple[torch.FloatTensor, ...] | None = None
  651. attentions: tuple[torch.FloatTensor, ...] | None = None
  652. @dataclass
  653. @auto_docstring(
  654. custom_intro="""
  655. Output type of [`XLNetForQuestionAnsweringSimple`].
  656. """
  657. )
  658. class XLNetForQuestionAnsweringSimpleOutput(ModelOutput):
  659. r"""
  660. loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
  661. Total span extraction loss is the sum of a Cross-Entropy for the start and end positions.
  662. start_logits (`torch.FloatTensor` of shape `(batch_size, sequence_length,)`):
  663. Span-start scores (before SoftMax).
  664. end_logits (`torch.FloatTensor` of shape `(batch_size, sequence_length,)`):
  665. Span-end scores (before SoftMax).
  666. mems (`list[torch.FloatTensor]` of length `config.n_layers`):
  667. Contains pre-computed hidden-states. Can be used (see `mems` input) to speed up sequential decoding. The
  668. token ids which have their past given to this model should not be passed as `input_ids` as they have
  669. already been computed.
  670. """
  671. loss: torch.FloatTensor | None = None
  672. start_logits: torch.FloatTensor | None = None
  673. end_logits: torch.FloatTensor | None = None
  674. mems: list[torch.FloatTensor] | None = None
  675. hidden_states: tuple[torch.FloatTensor, ...] | None = None
  676. attentions: tuple[torch.FloatTensor, ...] | None = None
  677. @dataclass
  678. @auto_docstring(
  679. custom_intro="""
  680. Output type of [`XLNetForQuestionAnswering`].
  681. """
  682. )
  683. class XLNetForQuestionAnsweringOutput(ModelOutput):
  684. r"""
  685. loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned if both `start_positions` and `end_positions` are provided):
  686. Classification loss as the sum of start token, end token (and is_impossible if provided) classification
  687. losses.
  688. 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):
  689. Log probabilities for the top config.start_n_top start token possibilities (beam-search).
  690. start_top_index (`torch.LongTensor` of shape `(batch_size, config.start_n_top)`, *optional*, returned if `start_positions` or `end_positions` is not provided):
  691. Indices for the top config.start_n_top start token possibilities (beam-search).
  692. 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):
  693. Log probabilities for the top `config.start_n_top * config.end_n_top` end token possibilities
  694. (beam-search).
  695. 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):
  696. Indices for the top `config.start_n_top * config.end_n_top` end token possibilities (beam-search).
  697. cls_logits (`torch.FloatTensor` of shape `(batch_size,)`, *optional*, returned if `start_positions` or `end_positions` is not provided):
  698. Log probabilities for the `is_impossible` label of the answers.
  699. mems (`list[torch.FloatTensor]` of length `config.n_layers`):
  700. Contains pre-computed hidden-states. Can be used (see `mems` input) to speed up sequential decoding. The
  701. token ids which have their past given to this model should not be passed as `input_ids` as they have
  702. already been computed.
  703. """
  704. loss: torch.FloatTensor | None = None
  705. start_top_log_probs: torch.FloatTensor | None = None
  706. start_top_index: torch.LongTensor | None = None
  707. end_top_log_probs: torch.FloatTensor | None = None
  708. end_top_index: torch.LongTensor | None = None
  709. cls_logits: torch.FloatTensor | None = None
  710. mems: list[torch.FloatTensor] | None = None
  711. hidden_states: tuple[torch.FloatTensor, ...] | None = None
  712. attentions: tuple[torch.FloatTensor, ...] | None = None
  713. @auto_docstring
  714. class XLNetModel(XLNetPreTrainedModel):
  715. def __init__(self, config):
  716. super().__init__(config)
  717. self.mem_len = config.mem_len
  718. self.reuse_len = config.reuse_len
  719. self.d_model = config.d_model
  720. self.same_length = config.same_length
  721. self.attn_type = config.attn_type
  722. self.bi_data = config.bi_data
  723. self.clamp_len = config.clamp_len
  724. self.n_layer = config.n_layer
  725. self.word_embedding = nn.Embedding(config.vocab_size, config.d_model)
  726. self.mask_emb = nn.Parameter(torch.FloatTensor(1, 1, config.d_model))
  727. self.layer = nn.ModuleList([XLNetLayer(config) for _ in range(config.n_layer)])
  728. self.dropout = nn.Dropout(config.dropout)
  729. # Initialize weights and apply final processing
  730. self.post_init()
  731. def get_input_embeddings(self):
  732. return self.word_embedding
  733. def set_input_embeddings(self, new_embeddings):
  734. self.word_embedding = new_embeddings
  735. def create_mask(self, qlen, mlen):
  736. """
  737. Creates causal attention mask. Float mask where 1.0 indicates masked, 0.0 indicates not-masked.
  738. Args:
  739. qlen: Sequence length
  740. mlen: Mask length
  741. ::
  742. same_length=False: same_length=True: <mlen > < qlen > <mlen > < qlen >
  743. ^ [0 0 0 0 0 1 1 1 1] [0 0 0 0 0 1 1 1 1]
  744. [0 0 0 0 0 0 1 1 1] [1 0 0 0 0 0 1 1 1]
  745. qlen [0 0 0 0 0 0 0 1 1] [1 1 0 0 0 0 0 1 1]
  746. [0 0 0 0 0 0 0 0 1] [1 1 1 0 0 0 0 0 1]
  747. v [0 0 0 0 0 0 0 0 0] [1 1 1 1 0 0 0 0 0]
  748. """
  749. mask = torch.ones((qlen, qlen + mlen), device=self.device)
  750. if self.same_length:
  751. mask_lo = mask[:, :qlen].tril(-1)
  752. mask.triu_(mlen + 1)
  753. mask[:, :qlen] += mask_lo
  754. else:
  755. mask.triu_(mlen + 1)
  756. return mask
  757. def cache_mem(self, curr_out, prev_mem):
  758. # cache hidden states into memory.
  759. if self.reuse_len is not None and self.reuse_len > 0:
  760. curr_out = curr_out[: self.reuse_len]
  761. if self.mem_len is None or self.mem_len == 0:
  762. # If `use_mems` is active but no `mem_len` is defined, the model behaves like GPT-2 at inference time
  763. # and returns all of the past and current hidden states.
  764. cutoff = 0
  765. else:
  766. # If `use_mems` is active and `mem_len` is defined, the model returns the last `mem_len` hidden
  767. # states. This is the preferred setting for training and long-form generation.
  768. cutoff = -self.mem_len
  769. if prev_mem is None:
  770. # if `use_mems` is active and `mem_len` is defined, the model
  771. new_mem = curr_out[cutoff:]
  772. else:
  773. new_mem = torch.cat([prev_mem, curr_out], dim=0)[cutoff:]
  774. return new_mem.detach()
  775. @staticmethod
  776. def positional_embedding(pos_seq, inv_freq, bsz=None):
  777. sinusoid_inp = torch.einsum("i,d->id", pos_seq, inv_freq)
  778. pos_emb = torch.cat([torch.sin(sinusoid_inp), torch.cos(sinusoid_inp)], dim=-1)
  779. pos_emb = pos_emb[:, None, :]
  780. if bsz is not None:
  781. pos_emb = pos_emb.expand(-1, bsz, -1)
  782. return pos_emb
  783. def relative_positional_encoding(self, qlen, klen, bsz=None, device=None):
  784. # create relative positional encoding.
  785. freq_seq = torch.arange(0, self.d_model, 2.0, dtype=torch.int64, device=device).float()
  786. inv_freq = 1 / torch.pow(10000, (freq_seq / self.d_model))
  787. if self.attn_type == "bi":
  788. # beg, end = klen - 1, -qlen
  789. beg, end = klen, -qlen
  790. elif self.attn_type == "uni":
  791. # beg, end = klen - 1, -1
  792. beg, end = klen, -1
  793. else:
  794. raise ValueError(f"Unknown `attn_type` {self.attn_type}.")
  795. if self.bi_data:
  796. fwd_pos_seq = torch.arange(beg, end, -1.0, dtype=torch.int64, device=device).float()
  797. bwd_pos_seq = torch.arange(-beg, -end, 1.0, dtype=torch.int64, device=device).float()
  798. if self.clamp_len > 0:
  799. fwd_pos_seq = fwd_pos_seq.clamp(-self.clamp_len, self.clamp_len)
  800. bwd_pos_seq = bwd_pos_seq.clamp(-self.clamp_len, self.clamp_len)
  801. if bsz is not None:
  802. fwd_pos_emb = self.positional_embedding(fwd_pos_seq, inv_freq, bsz // 2)
  803. bwd_pos_emb = self.positional_embedding(bwd_pos_seq, inv_freq, bsz // 2)
  804. else:
  805. fwd_pos_emb = self.positional_embedding(fwd_pos_seq, inv_freq)
  806. bwd_pos_emb = self.positional_embedding(bwd_pos_seq, inv_freq)
  807. pos_emb = torch.cat([fwd_pos_emb, bwd_pos_emb], dim=1)
  808. else:
  809. fwd_pos_seq = torch.arange(beg, end, -1.0, dtype=torch.int64, device=device).float()
  810. if self.clamp_len > 0:
  811. fwd_pos_seq = fwd_pos_seq.clamp(-self.clamp_len, self.clamp_len)
  812. pos_emb = self.positional_embedding(fwd_pos_seq, inv_freq, bsz)
  813. return pos_emb
  814. @auto_docstring
  815. def forward(
  816. self,
  817. input_ids: torch.Tensor | None = None,
  818. attention_mask: torch.Tensor | None = None,
  819. mems: torch.Tensor | None = None,
  820. perm_mask: torch.Tensor | None = None,
  821. target_mapping: torch.Tensor | None = None,
  822. token_type_ids: torch.Tensor | None = None,
  823. input_mask: torch.Tensor | None = None,
  824. inputs_embeds: torch.Tensor | None = None,
  825. use_mems: bool | None = None,
  826. output_attentions: bool | None = None,
  827. output_hidden_states: bool | None = None,
  828. return_dict: bool | None = None,
  829. **kwargs, # delete after depreciation warning is removed
  830. ) -> tuple | XLNetModelOutput:
  831. r"""
  832. mems (`list[torch.FloatTensor]` of length `config.n_layers`):
  833. Contains pre-computed hidden-states (see `mems` output below) . Can be used to speed up sequential
  834. decoding. The token ids which have their past given to this model should not be passed as `input_ids` as
  835. they have already been computed.
  836. `use_mems` has to be set to `True` to make use of `mems`.
  837. perm_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length, sequence_length)`, *optional*):
  838. Mask to indicate the attention pattern for each input token with values selected in `[0, 1]`:
  839. - if `perm_mask[k, i, j] = 0`, i attend to j in batch k;
  840. - if `perm_mask[k, i, j] = 1`, i does not attend to j in batch k.
  841. If not set, each token attends to all the others (full bidirectional attention). Only used during
  842. pretraining (to define factorization order) or for sequential decoding (generation).
  843. target_mapping (`torch.FloatTensor` of shape `(batch_size, num_predict, sequence_length)`, *optional*):
  844. Mask to indicate the output tokens to use. If `target_mapping[k, i, j] = 1`, the i-th predict in batch k is
  845. on the j-th token. Only used during pretraining for partial prediction or for sequential decoding
  846. (generation).
  847. input_mask (`torch.FloatTensor` of shape `batch_size, sequence_length`, *optional*):
  848. Mask to avoid performing attention on padding token indices. Negative of `attention_mask`, i.e. with 0 for
  849. real tokens and 1 for padding which is kept for compatibility with the original code base.
  850. Mask values selected in `[0, 1]`:
  851. - 1 for tokens that are **masked**,
  852. - 0 for tokens that are **not masked**.
  853. You can only uses one of `input_mask` and `attention_mask`.
  854. use_mems (`bool`, *optional*):
  855. Whether to use memory states to speed up sequential decoding. If set to `True`, the model will use the hidden
  856. states from previous forward passes to compute attention, which can significantly improve performance for
  857. sequential decoding tasks.
  858. """
  859. output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
  860. output_hidden_states = (
  861. output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
  862. )
  863. return_dict = return_dict if return_dict is not None else self.config.return_dict
  864. if self.training:
  865. use_mems = use_mems if use_mems is not None else self.config.use_mems_train
  866. else:
  867. use_mems = use_mems if use_mems is not None else self.config.use_mems_eval
  868. # the original code for XLNet uses shapes [len, bsz] with the batch dimension at the end
  869. # but we want a unified interface in the library with the batch size on the first dimension
  870. # so we move here the first dimension (batch) to the end
  871. if input_ids is not None and inputs_embeds is not None:
  872. raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
  873. elif input_ids is not None:
  874. input_ids = input_ids.transpose(0, 1).contiguous()
  875. qlen, bsz = input_ids.shape[0], input_ids.shape[1]
  876. elif inputs_embeds is not None:
  877. inputs_embeds = inputs_embeds.transpose(0, 1).contiguous()
  878. qlen, bsz = inputs_embeds.shape[0], inputs_embeds.shape[1]
  879. else:
  880. raise ValueError("You have to specify either input_ids or inputs_embeds")
  881. token_type_ids = token_type_ids.transpose(0, 1).contiguous() if token_type_ids is not None else None
  882. input_mask = input_mask.transpose(0, 1).contiguous() if input_mask is not None else None
  883. attention_mask = attention_mask.transpose(0, 1).contiguous() if attention_mask is not None else None
  884. perm_mask = perm_mask.permute(1, 2, 0).contiguous() if perm_mask is not None else None
  885. target_mapping = target_mapping.permute(1, 2, 0).contiguous() if target_mapping is not None else None
  886. mlen = mems[0].shape[0] if mems is not None and mems[0] is not None else 0
  887. klen = mlen + qlen
  888. dtype_float = self.dtype
  889. device = self.device
  890. # Attention mask
  891. # causal attention mask
  892. if self.attn_type == "uni":
  893. attn_mask = self.create_mask(qlen, mlen)
  894. attn_mask = attn_mask[:, :, None, None]
  895. elif self.attn_type == "bi":
  896. attn_mask = None
  897. else:
  898. raise ValueError(f"Unsupported attention type: {self.attn_type}")
  899. # data mask: input mask & perm mask
  900. assert input_mask is None or attention_mask is None, "You can only use one of input_mask (uses 1 for padding) "
  901. "or attention_mask (uses 0 for padding, added for compatibility with BERT). Please choose one."
  902. if input_mask is None and attention_mask is not None:
  903. input_mask = 1.0 - attention_mask
  904. if input_mask is not None and perm_mask is not None:
  905. data_mask = input_mask[None] + perm_mask
  906. elif input_mask is not None and perm_mask is None:
  907. data_mask = input_mask[None]
  908. elif input_mask is None and perm_mask is not None:
  909. data_mask = perm_mask
  910. else:
  911. data_mask = None
  912. if data_mask is not None:
  913. # all mems can be attended to
  914. if mlen > 0:
  915. mems_mask = torch.zeros([data_mask.shape[0], mlen, bsz]).to(data_mask)
  916. data_mask = torch.cat([mems_mask, data_mask], dim=1)
  917. if attn_mask is None:
  918. attn_mask = data_mask[:, :, :, None]
  919. else:
  920. attn_mask += data_mask[:, :, :, None]
  921. if attn_mask is not None:
  922. attn_mask = (attn_mask > 0).to(dtype_float)
  923. if attn_mask is not None:
  924. non_tgt_mask = -torch.eye(qlen).to(attn_mask)
  925. if mlen > 0:
  926. non_tgt_mask = torch.cat([torch.zeros([qlen, mlen]).to(attn_mask), non_tgt_mask], dim=-1)
  927. non_tgt_mask = ((attn_mask + non_tgt_mask[:, :, None, None]) > 0).to(attn_mask)
  928. else:
  929. non_tgt_mask = None
  930. # Word embeddings and prepare h & g hidden states
  931. if inputs_embeds is not None:
  932. word_emb_k = inputs_embeds
  933. else:
  934. word_emb_k = self.word_embedding(input_ids)
  935. output_h = self.dropout(word_emb_k)
  936. if target_mapping is not None:
  937. word_emb_q = self.mask_emb.expand(target_mapping.shape[0], bsz, -1)
  938. # else: # We removed the inp_q input which was same as target mapping
  939. # inp_q_ext = inp_q[:, :, None]
  940. # word_emb_q = inp_q_ext * self.mask_emb + (1 - inp_q_ext) * word_emb_k
  941. output_g = self.dropout(word_emb_q)
  942. else:
  943. output_g = None
  944. # Segment embedding
  945. if token_type_ids is not None:
  946. # Convert `token_type_ids` to one-hot `seg_mat`
  947. if mlen > 0:
  948. mem_pad = torch.zeros([mlen, bsz], dtype=torch.long, device=device)
  949. cat_ids = torch.cat([mem_pad, token_type_ids], dim=0)
  950. else:
  951. cat_ids = token_type_ids
  952. # `1` indicates not in the same segment [qlen x klen x bsz]
  953. seg_mat = (token_type_ids[:, None] != cat_ids[None, :]).long()
  954. seg_mat = nn.functional.one_hot(seg_mat, num_classes=2).to(dtype_float)
  955. else:
  956. seg_mat = None
  957. # Positional encoding
  958. pos_emb = self.relative_positional_encoding(qlen, klen, bsz=bsz, device=output_h.device)
  959. pos_emb = self.dropout(pos_emb)
  960. new_mems = ()
  961. if mems is None:
  962. mems = [None] * len(self.layer)
  963. attentions = [] if output_attentions else None
  964. hidden_states = [] if output_hidden_states else None
  965. for i, layer_module in enumerate(self.layer):
  966. if use_mems:
  967. # cache new mems
  968. new_mems = new_mems + (self.cache_mem(output_h, mems[i]),)
  969. if output_hidden_states:
  970. hidden_states.append((output_h, output_g) if output_g is not None else output_h)
  971. outputs = layer_module(
  972. output_h,
  973. output_g,
  974. attn_mask_h=non_tgt_mask,
  975. attn_mask_g=attn_mask,
  976. r=pos_emb,
  977. seg_mat=seg_mat,
  978. mems=mems[i],
  979. target_mapping=target_mapping,
  980. output_attentions=output_attentions,
  981. )
  982. output_h, output_g = outputs[:2]
  983. if output_attentions:
  984. attentions.append(outputs[2])
  985. # Add last hidden state
  986. if output_hidden_states:
  987. hidden_states.append((output_h, output_g) if output_g is not None else output_h)
  988. output = self.dropout(output_g if output_g is not None else output_h)
  989. # Prepare outputs, we transpose back here to shape [bsz, len, hidden_dim] (cf. beginning of forward() method)
  990. output = output.permute(1, 0, 2).contiguous()
  991. if not use_mems:
  992. new_mems = None
  993. if output_hidden_states:
  994. if output_g is not None:
  995. hidden_states = tuple(h.permute(1, 0, 2).contiguous() for hs in hidden_states for h in hs)
  996. else:
  997. hidden_states = tuple(hs.permute(1, 0, 2).contiguous() for hs in hidden_states)
  998. if output_attentions:
  999. if target_mapping is not None:
  1000. # when target_mapping is provided, there are 2-tuple of attentions
  1001. attentions = tuple(
  1002. tuple(att_stream.permute(2, 3, 0, 1).contiguous() for att_stream in t) for t in attentions
  1003. )
  1004. else:
  1005. attentions = tuple(t.permute(2, 3, 0, 1).contiguous() for t in attentions)
  1006. if not return_dict:
  1007. return tuple(v for v in [output, new_mems, hidden_states, attentions] if v is not None)
  1008. return XLNetModelOutput(
  1009. last_hidden_state=output, mems=new_mems, hidden_states=hidden_states, attentions=attentions
  1010. )
  1011. @auto_docstring(
  1012. custom_intro="""
  1013. XLNet Model with a language modeling head on top (linear layer with weights tied to the input embeddings).
  1014. """
  1015. )
  1016. class XLNetLMHeadModel(XLNetPreTrainedModel, GenerationMixin):
  1017. _tied_weights_keys = {"lm_loss.weight": "transformer.word_embedding.weight"}
  1018. def __init__(self, config):
  1019. super().__init__(config)
  1020. self.attn_type = config.attn_type
  1021. self.same_length = config.same_length
  1022. self.transformer = XLNetModel(config)
  1023. self.lm_loss = nn.Linear(config.d_model, config.vocab_size, bias=True)
  1024. # Initialize weights and apply final processing
  1025. self.post_init()
  1026. def get_output_embeddings(self):
  1027. return self.lm_loss
  1028. def set_output_embeddings(self, new_embeddings):
  1029. self.lm_loss = new_embeddings
  1030. def prepare_inputs_for_generation(
  1031. self, input_ids, past_key_values=None, use_mems=None, is_first_iteration=False, **kwargs
  1032. ):
  1033. # Overwritten -- this model has unique input preparation
  1034. # Add dummy token at the end (no attention on this one)
  1035. effective_batch_size = input_ids.shape[0]
  1036. dummy_token = torch.zeros((effective_batch_size, 1), dtype=torch.long, device=input_ids.device)
  1037. # At every pass, the attention values for the new token and the two last generated tokens
  1038. # are computed, the rest is reloaded from the `past` cache. A purely auto-regressive model would have
  1039. # offset = 1; offset = 2 seems to have slightly better computation.
  1040. offset = 2
  1041. if past_key_values:
  1042. input_ids = torch.cat([input_ids[:, -offset:], dummy_token], dim=1)
  1043. else:
  1044. input_ids = torch.cat([input_ids, dummy_token], dim=1)
  1045. # Build permutation mask so that previous tokens don't see last token
  1046. sequence_length = input_ids.shape[1]
  1047. perm_mask = torch.zeros(
  1048. (effective_batch_size, sequence_length, sequence_length), dtype=torch.float, device=input_ids.device
  1049. )
  1050. perm_mask[:, :, -1] = 1.0
  1051. # We'll only predict the last token
  1052. target_mapping = torch.zeros(
  1053. (effective_batch_size, 1, sequence_length), dtype=torch.float, device=input_ids.device
  1054. )
  1055. target_mapping[:, 0, -1] = 1.0
  1056. model_inputs = {
  1057. "input_ids": input_ids,
  1058. "perm_mask": perm_mask,
  1059. "target_mapping": target_mapping,
  1060. "use_mems": use_mems,
  1061. }
  1062. # if past is defined in model kwargs then use it for faster decoding
  1063. if past_key_values:
  1064. model_inputs["mems"] = tuple(layer_past[:-offset, :, :] for layer_past in past_key_values)
  1065. # Attention mask is computed on the fly on XLNetModel.forward()
  1066. kwargs.pop("attention_mask", None)
  1067. # TODO: Ignoring use_cache should not happen, fixme.
  1068. kwargs.pop("use_cache", None)
  1069. # Forward ALL kwargs that are uninitialized (e.g. `use_cache`).
  1070. for key, value in kwargs.items():
  1071. if key not in model_inputs:
  1072. model_inputs[key] = value
  1073. return model_inputs
  1074. @auto_docstring
  1075. def forward(
  1076. self,
  1077. input_ids: torch.Tensor | None = None,
  1078. attention_mask: torch.Tensor | None = None,
  1079. mems: torch.Tensor | None = None,
  1080. perm_mask: torch.Tensor | None = None,
  1081. target_mapping: torch.Tensor | None = None,
  1082. token_type_ids: torch.Tensor | None = None,
  1083. input_mask: torch.Tensor | None = None,
  1084. inputs_embeds: torch.Tensor | None = None,
  1085. labels: torch.Tensor | None = None,
  1086. use_mems: bool | None = None,
  1087. output_attentions: bool | None = None,
  1088. output_hidden_states: bool | None = None,
  1089. return_dict: bool | None = None,
  1090. logits_to_keep: int | torch.Tensor = 0,
  1091. **kwargs, # delete when `use_cache` is removed in XLNetModel
  1092. ) -> tuple | XLNetLMHeadModelOutput:
  1093. r"""
  1094. mems (`list[torch.FloatTensor]` of length `config.n_layers`):
  1095. Contains pre-computed hidden-states (see `mems` output below) . Can be used to speed up sequential
  1096. decoding. The token ids which have their past given to this model should not be passed as `input_ids` as
  1097. they have already been computed.
  1098. `use_mems` has to be set to `True` to make use of `mems`.
  1099. perm_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length, sequence_length)`, *optional*):
  1100. Mask to indicate the attention pattern for each input token with values selected in `[0, 1]`:
  1101. - if `perm_mask[k, i, j] = 0`, i attend to j in batch k;
  1102. - if `perm_mask[k, i, j] = 1`, i does not attend to j in batch k.
  1103. If not set, each token attends to all the others (full bidirectional attention). Only used during
  1104. pretraining (to define factorization order) or for sequential decoding (generation).
  1105. target_mapping (`torch.FloatTensor` of shape `(batch_size, num_predict, sequence_length)`, *optional*):
  1106. Mask to indicate the output tokens to use. If `target_mapping[k, i, j] = 1`, the i-th predict in batch k is
  1107. on the j-th token. Only used during pretraining for partial prediction or for sequential decoding
  1108. (generation).
  1109. input_mask (`torch.FloatTensor` of shape `batch_size, sequence_length`, *optional*):
  1110. Mask to avoid performing attention on padding token indices. Negative of `attention_mask`, i.e. with 0 for
  1111. real tokens and 1 for padding which is kept for compatibility with the original code base.
  1112. Mask values selected in `[0, 1]`:
  1113. - 1 for tokens that are **masked**,
  1114. - 0 for tokens that are **not masked**.
  1115. You can only uses one of `input_mask` and `attention_mask`.
  1116. labels (`torch.LongTensor` of shape `(batch_size, num_predict)`, *optional*):
  1117. Labels for masked language modeling. `num_predict` corresponds to `target_mapping.shape[1]`. If
  1118. `target_mapping` is `None`, then `num_predict` corresponds to `sequence_length`.
  1119. The labels should correspond to the masked input words that should be predicted and depends on
  1120. `target_mapping`. Note in order to perform standard auto-regressive language modeling a *<mask>* token has
  1121. to be added to the `input_ids` (see the `prepare_inputs_for_generation` function and examples below)
  1122. Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100` are ignored, the loss
  1123. is only computed for labels in `[0, ..., config.vocab_size]`
  1124. use_mems (`bool`, *optional*):
  1125. Whether to use memory states to speed up sequential decoding. If set to `True`, the model will use the hidden
  1126. states from previous forward passes to compute attention, which can significantly improve performance for
  1127. sequential decoding tasks.
  1128. Examples:
  1129. ```python
  1130. >>> from transformers import AutoTokenizer, XLNetLMHeadModel
  1131. >>> import torch
  1132. >>> tokenizer = AutoTokenizer.from_pretrained("xlnet/xlnet-large-cased")
  1133. >>> model = XLNetLMHeadModel.from_pretrained("xlnet/xlnet-large-cased")
  1134. >>> # We show how to setup inputs to predict a next token using a bi-directional context.
  1135. >>> input_ids = torch.tensor(
  1136. ... tokenizer.encode("Hello, my dog is very <mask>", add_special_tokens=False)
  1137. ... ).unsqueeze(
  1138. ... 0
  1139. ... ) # We will predict the masked token
  1140. >>> perm_mask = torch.zeros((1, input_ids.shape[1], input_ids.shape[1]), dtype=torch.float)
  1141. >>> perm_mask[:, :, -1] = 1.0 # Previous tokens don't see last token
  1142. >>> target_mapping = torch.zeros(
  1143. ... (1, 1, input_ids.shape[1]), dtype=torch.float
  1144. ... ) # Shape [1, 1, seq_length] => let's predict one token
  1145. >>> target_mapping[
  1146. ... 0, 0, -1
  1147. ... ] = 1.0 # Our first (and only) prediction will be the last token of the sequence (the masked token)
  1148. >>> outputs = model(input_ids, perm_mask=perm_mask, target_mapping=target_mapping)
  1149. >>> next_token_logits = outputs[
  1150. ... 0
  1151. ... ] # Output has shape [target_mapping.size(0), target_mapping.size(1), config.vocab_size]
  1152. >>> # The same way can the XLNetLMHeadModel be used to be trained by standard auto-regressive language modeling.
  1153. >>> input_ids = torch.tensor(
  1154. ... tokenizer.encode("Hello, my dog is very <mask>", add_special_tokens=False)
  1155. ... ).unsqueeze(
  1156. ... 0
  1157. ... ) # We will predict the masked token
  1158. >>> labels = torch.tensor(tokenizer.encode("cute", add_special_tokens=False)).unsqueeze(0)
  1159. >>> assert labels.shape[0] == 1, "only one word will be predicted"
  1160. >>> perm_mask = torch.zeros((1, input_ids.shape[1], input_ids.shape[1]), dtype=torch.float)
  1161. >>> perm_mask[
  1162. ... :, :, -1
  1163. ... ] = 1.0 # Previous tokens don't see last token as is done in standard auto-regressive lm training
  1164. >>> target_mapping = torch.zeros(
  1165. ... (1, 1, input_ids.shape[1]), dtype=torch.float
  1166. ... ) # Shape [1, 1, seq_length] => let's predict one token
  1167. >>> target_mapping[
  1168. ... 0, 0, -1
  1169. ... ] = 1.0 # Our first (and only) prediction will be the last token of the sequence (the masked token)
  1170. >>> outputs = model(input_ids, perm_mask=perm_mask, target_mapping=target_mapping, labels=labels)
  1171. >>> loss = outputs.loss
  1172. >>> next_token_logits = (
  1173. ... outputs.logits
  1174. ... ) # Logits have shape [target_mapping.size(0), target_mapping.size(1), config.vocab_size]
  1175. ```"""
  1176. return_dict = return_dict if return_dict is not None else self.config.return_dict
  1177. transformer_outputs = self.transformer(
  1178. input_ids,
  1179. attention_mask=attention_mask,
  1180. mems=mems,
  1181. perm_mask=perm_mask,
  1182. target_mapping=target_mapping,
  1183. token_type_ids=token_type_ids,
  1184. input_mask=input_mask,
  1185. inputs_embeds=inputs_embeds,
  1186. use_mems=use_mems,
  1187. output_attentions=output_attentions,
  1188. output_hidden_states=output_hidden_states,
  1189. return_dict=return_dict,
  1190. **kwargs,
  1191. )
  1192. hidden_states = transformer_outputs[0]
  1193. # Only compute necessary logits
  1194. slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
  1195. logits = self.lm_loss(hidden_states[:, slice_indices, :])
  1196. loss = None
  1197. if labels is not None:
  1198. # Flatten the tokens
  1199. loss_fct = CrossEntropyLoss()
  1200. loss = loss_fct(logits.view(-1, logits.size(-1)), labels.view(-1))
  1201. if not return_dict:
  1202. output = (logits,) + transformer_outputs[1:]
  1203. return ((loss,) + output) if loss is not None else output
  1204. return XLNetLMHeadModelOutput(
  1205. loss=loss,
  1206. logits=logits,
  1207. mems=transformer_outputs.mems,
  1208. hidden_states=transformer_outputs.hidden_states,
  1209. attentions=transformer_outputs.attentions,
  1210. )
  1211. @staticmethod
  1212. def _reorder_cache(mems: list[torch.Tensor], beam_idx: torch.Tensor) -> list[torch.Tensor]:
  1213. """
  1214. This function is used to re-order the `mems` cache if [`~PreTrainedModel.beam_search`] or
  1215. [`~PreTrainedModel.beam_sample`] is called. This is required to match `mems` with the correct beam_idx at every
  1216. generation step.
  1217. """
  1218. return [layer_past.index_select(1, beam_idx.to(layer_past.device)) for layer_past in mems]
  1219. @auto_docstring(
  1220. custom_intro="""
  1221. XLNet Model with a sequence classification/regression head on top (a linear layer on top of the pooled output) e.g.
  1222. for GLUE tasks.
  1223. """
  1224. )
  1225. class XLNetForSequenceClassification(XLNetPreTrainedModel):
  1226. def __init__(self, config):
  1227. super().__init__(config)
  1228. self.num_labels = config.num_labels
  1229. self.config = config
  1230. self.transformer = XLNetModel(config)
  1231. self.sequence_summary = XLNetSequenceSummary(config)
  1232. self.logits_proj = nn.Linear(config.d_model, config.num_labels)
  1233. # Initialize weights and apply final processing
  1234. self.post_init()
  1235. @auto_docstring
  1236. def forward(
  1237. self,
  1238. input_ids: torch.Tensor | None = None,
  1239. attention_mask: torch.Tensor | None = None,
  1240. mems: torch.Tensor | None = None,
  1241. perm_mask: torch.Tensor | None = None,
  1242. target_mapping: torch.Tensor | None = None,
  1243. token_type_ids: torch.Tensor | None = None,
  1244. input_mask: torch.Tensor | None = None,
  1245. inputs_embeds: torch.Tensor | None = None,
  1246. labels: torch.Tensor | None = None,
  1247. use_mems: bool | None = None,
  1248. output_attentions: bool | None = None,
  1249. output_hidden_states: bool | None = None,
  1250. return_dict: bool | None = None,
  1251. **kwargs, # delete when `use_cache` is removed in XLNetModel
  1252. ) -> tuple | XLNetForSequenceClassificationOutput:
  1253. r"""
  1254. mems (`list[torch.FloatTensor]` of length `config.n_layers`):
  1255. Contains pre-computed hidden-states (see `mems` output below) . Can be used to speed up sequential
  1256. decoding. The token ids which have their past given to this model should not be passed as `input_ids` as
  1257. they have already been computed.
  1258. `use_mems` has to be set to `True` to make use of `mems`.
  1259. perm_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length, sequence_length)`, *optional*):
  1260. Mask to indicate the attention pattern for each input token with values selected in `[0, 1]`:
  1261. - if `perm_mask[k, i, j] = 0`, i attend to j in batch k;
  1262. - if `perm_mask[k, i, j] = 1`, i does not attend to j in batch k.
  1263. If not set, each token attends to all the others (full bidirectional attention). Only used during
  1264. pretraining (to define factorization order) or for sequential decoding (generation).
  1265. target_mapping (`torch.FloatTensor` of shape `(batch_size, num_predict, sequence_length)`, *optional*):
  1266. Mask to indicate the output tokens to use. If `target_mapping[k, i, j] = 1`, the i-th predict in batch k is
  1267. on the j-th token. Only used during pretraining for partial prediction or for sequential decoding
  1268. (generation).
  1269. input_mask (`torch.FloatTensor` of shape `batch_size, sequence_length`, *optional*):
  1270. Mask to avoid performing attention on padding token indices. Negative of `attention_mask`, i.e. with 0 for
  1271. real tokens and 1 for padding which is kept for compatibility with the original code base.
  1272. Mask values selected in `[0, 1]`:
  1273. - 1 for tokens that are **masked**,
  1274. - 0 for tokens that are **not masked**.
  1275. You can only uses one of `input_mask` and `attention_mask`.
  1276. labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
  1277. Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
  1278. config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
  1279. `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
  1280. use_mems (`bool`, *optional*):
  1281. Whether to use memory states to speed up sequential decoding. If set to `True`, the model will use the hidden
  1282. states from previous forward passes to compute attention, which can significantly improve performance for
  1283. sequential decoding tasks.
  1284. """
  1285. return_dict = return_dict if return_dict is not None else self.config.return_dict
  1286. transformer_outputs = self.transformer(
  1287. input_ids,
  1288. attention_mask=attention_mask,
  1289. mems=mems,
  1290. perm_mask=perm_mask,
  1291. target_mapping=target_mapping,
  1292. token_type_ids=token_type_ids,
  1293. input_mask=input_mask,
  1294. inputs_embeds=inputs_embeds,
  1295. use_mems=use_mems,
  1296. output_attentions=output_attentions,
  1297. output_hidden_states=output_hidden_states,
  1298. return_dict=return_dict,
  1299. **kwargs,
  1300. )
  1301. output = transformer_outputs[0]
  1302. output = self.sequence_summary(output)
  1303. logits = self.logits_proj(output)
  1304. loss = None
  1305. if labels is not None:
  1306. if self.config.problem_type is None:
  1307. if self.num_labels == 1:
  1308. self.config.problem_type = "regression"
  1309. elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
  1310. self.config.problem_type = "single_label_classification"
  1311. else:
  1312. self.config.problem_type = "multi_label_classification"
  1313. if self.config.problem_type == "regression":
  1314. loss_fct = MSELoss()
  1315. if self.num_labels == 1:
  1316. loss = loss_fct(logits.squeeze(), labels.squeeze())
  1317. else:
  1318. loss = loss_fct(logits, labels)
  1319. elif self.config.problem_type == "single_label_classification":
  1320. loss_fct = CrossEntropyLoss()
  1321. loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
  1322. elif self.config.problem_type == "multi_label_classification":
  1323. loss_fct = BCEWithLogitsLoss()
  1324. loss = loss_fct(logits, labels)
  1325. if not return_dict:
  1326. output = (logits,) + transformer_outputs[1:]
  1327. return ((loss,) + output) if loss is not None else output
  1328. return XLNetForSequenceClassificationOutput(
  1329. loss=loss,
  1330. logits=logits,
  1331. mems=transformer_outputs.mems,
  1332. hidden_states=transformer_outputs.hidden_states,
  1333. attentions=transformer_outputs.attentions,
  1334. )
  1335. @auto_docstring
  1336. class XLNetForTokenClassification(XLNetPreTrainedModel):
  1337. def __init__(self, config):
  1338. super().__init__(config)
  1339. self.num_labels = config.num_labels
  1340. self.transformer = XLNetModel(config)
  1341. self.classifier = nn.Linear(config.hidden_size, config.num_labels)
  1342. # Initialize weights and apply final processing
  1343. self.post_init()
  1344. @auto_docstring
  1345. def forward(
  1346. self,
  1347. input_ids: torch.Tensor | None = None,
  1348. attention_mask: torch.Tensor | None = None,
  1349. mems: torch.Tensor | None = None,
  1350. perm_mask: torch.Tensor | None = None,
  1351. target_mapping: torch.Tensor | None = None,
  1352. token_type_ids: torch.Tensor | None = None,
  1353. input_mask: torch.Tensor | None = None,
  1354. inputs_embeds: torch.Tensor | None = None,
  1355. labels: torch.Tensor | None = None,
  1356. use_mems: bool | None = None,
  1357. output_attentions: bool | None = None,
  1358. output_hidden_states: bool | None = None,
  1359. return_dict: bool | None = None,
  1360. **kwargs, # delete when `use_cache` is removed in XLNetModel
  1361. ) -> tuple | XLNetForTokenClassificationOutput:
  1362. r"""
  1363. mems (`list[torch.FloatTensor]` of length `config.n_layers`):
  1364. Contains pre-computed hidden-states (see `mems` output below) . Can be used to speed up sequential
  1365. decoding. The token ids which have their past given to this model should not be passed as `input_ids` as
  1366. they have already been computed.
  1367. `use_mems` has to be set to `True` to make use of `mems`.
  1368. perm_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length, sequence_length)`, *optional*):
  1369. Mask to indicate the attention pattern for each input token with values selected in `[0, 1]`:
  1370. - if `perm_mask[k, i, j] = 0`, i attend to j in batch k;
  1371. - if `perm_mask[k, i, j] = 1`, i does not attend to j in batch k.
  1372. If not set, each token attends to all the others (full bidirectional attention). Only used during
  1373. pretraining (to define factorization order) or for sequential decoding (generation).
  1374. target_mapping (`torch.FloatTensor` of shape `(batch_size, num_predict, sequence_length)`, *optional*):
  1375. Mask to indicate the output tokens to use. If `target_mapping[k, i, j] = 1`, the i-th predict in batch k is
  1376. on the j-th token. Only used during pretraining for partial prediction or for sequential decoding
  1377. (generation).
  1378. input_mask (`torch.FloatTensor` of shape `batch_size, sequence_length`, *optional*):
  1379. Mask to avoid performing attention on padding token indices. Negative of `attention_mask`, i.e. with 0 for
  1380. real tokens and 1 for padding which is kept for compatibility with the original code base.
  1381. Mask values selected in `[0, 1]`:
  1382. - 1 for tokens that are **masked**,
  1383. - 0 for tokens that are **not masked**.
  1384. You can only uses one of `input_mask` and `attention_mask`.
  1385. labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
  1386. Labels for computing the multiple choice classification loss. Indices should be in `[0, ..., num_choices]`
  1387. where *num_choices* is the size of the second dimension of the input tensors. (see *input_ids* above)
  1388. use_mems (`bool`, *optional*):
  1389. Whether to use memory states to speed up sequential decoding. If set to `True`, the model will use the hidden
  1390. states from previous forward passes to compute attention, which can significantly improve performance for
  1391. sequential decoding tasks.emory states to speed up sequential decoding. If set to `True`, the model will use the hidden
  1392. states from previous forward passes to compute attention, which can significantly improve performance for
  1393. sequential decoding tasks.
  1394. """
  1395. return_dict = return_dict if return_dict is not None else self.config.return_dict
  1396. outputs = self.transformer(
  1397. input_ids,
  1398. attention_mask=attention_mask,
  1399. mems=mems,
  1400. perm_mask=perm_mask,
  1401. target_mapping=target_mapping,
  1402. token_type_ids=token_type_ids,
  1403. input_mask=input_mask,
  1404. inputs_embeds=inputs_embeds,
  1405. use_mems=use_mems,
  1406. output_attentions=output_attentions,
  1407. output_hidden_states=output_hidden_states,
  1408. return_dict=return_dict,
  1409. )
  1410. sequence_output = outputs[0]
  1411. logits = self.classifier(sequence_output)
  1412. loss = None
  1413. if labels is not None:
  1414. loss_fct = CrossEntropyLoss()
  1415. loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
  1416. if not return_dict:
  1417. output = (logits,) + outputs[1:]
  1418. return ((loss,) + output) if loss is not None else output
  1419. return XLNetForTokenClassificationOutput(
  1420. loss=loss,
  1421. logits=logits,
  1422. mems=outputs.mems,
  1423. hidden_states=outputs.hidden_states,
  1424. attentions=outputs.attentions,
  1425. )
  1426. @auto_docstring
  1427. class XLNetForMultipleChoice(XLNetPreTrainedModel):
  1428. def __init__(self, config):
  1429. super().__init__(config)
  1430. self.transformer = XLNetModel(config)
  1431. self.sequence_summary = XLNetSequenceSummary(config)
  1432. self.logits_proj = nn.Linear(config.d_model, 1)
  1433. # Initialize weights and apply final processing
  1434. self.post_init()
  1435. @auto_docstring
  1436. def forward(
  1437. self,
  1438. input_ids: torch.Tensor | None = None,
  1439. token_type_ids: torch.Tensor | None = None,
  1440. input_mask: torch.Tensor | None = None,
  1441. attention_mask: torch.Tensor | None = None,
  1442. mems: torch.Tensor | None = None,
  1443. perm_mask: torch.Tensor | None = None,
  1444. target_mapping: torch.Tensor | None = None,
  1445. inputs_embeds: torch.Tensor | None = None,
  1446. labels: torch.Tensor | None = None,
  1447. use_mems: bool | None = None,
  1448. output_attentions: bool | None = None,
  1449. output_hidden_states: bool | None = None,
  1450. return_dict: bool | None = None,
  1451. **kwargs, # delete when `use_cache` is removed in XLNetModel
  1452. ) -> tuple | XLNetForMultipleChoiceOutput:
  1453. r"""
  1454. input_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`):
  1455. Indices of input sequence tokens in the vocabulary.
  1456. Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
  1457. [`PreTrainedTokenizer.__call__`] for details.
  1458. [What are input IDs?](../glossary#input-ids)
  1459. token_type_ids (`torch.LongTensor` of shape `(batch_size, num_choices, sequence_length)`, *optional*):
  1460. Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
  1461. 1]`:
  1462. - 0 corresponds to a *sentence A* token,
  1463. - 1 corresponds to a *sentence B* token.
  1464. [What are token type IDs?](../glossary#token-type-ids)
  1465. input_mask (`torch.FloatTensor` of shape `batch_size, num_choices, sequence_length`, *optional*):
  1466. Mask to avoid performing attention on padding token indices. Negative of `attention_mask`, i.e. with 0 for
  1467. real tokens and 1 for padding which is kept for compatibility with the original code base.
  1468. Mask values selected in `[0, 1]`:
  1469. - 1 for tokens that are **masked**,
  1470. - 0 for tokens that are **not masked**.
  1471. You can only uses one of `input_mask` and `attention_mask`.
  1472. mems (`list[torch.FloatTensor]` of length `config.n_layers`):
  1473. Contains pre-computed hidden-states (see `mems` output below) . Can be used to speed up sequential
  1474. decoding. The token ids which have their past given to this model should not be passed as `input_ids` as
  1475. they have already been computed.
  1476. `use_mems` has to be set to `True` to make use of `mems`.
  1477. perm_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length, sequence_length)`, *optional*):
  1478. Mask to indicate the attention pattern for each input token with values selected in `[0, 1]`:
  1479. - if `perm_mask[k, i, j] = 0`, i attend to j in batch k;
  1480. - if `perm_mask[k, i, j] = 1`, i does not attend to j in batch k.
  1481. If not set, each token attends to all the others (full bidirectional attention). Only used during
  1482. pretraining (to define factorization order) or for sequential decoding (generation).
  1483. target_mapping (`torch.FloatTensor` of shape `(batch_size, num_predict, sequence_length)`, *optional*):
  1484. Mask to indicate the output tokens to use. If `target_mapping[k, i, j] = 1`, the i-th predict in batch k is
  1485. on the j-th token. Only used during pretraining for partial prediction or for sequential decoding
  1486. (generation).
  1487. inputs_embeds (`torch.FloatTensor` of shape `(batch_size, num_choices, sequence_length, hidden_size)`, *optional*):
  1488. Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
  1489. is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
  1490. model's internal embedding lookup matrix.
  1491. labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
  1492. Labels for computing the multiple choice classification loss. Indices should be in `[0, ...,
  1493. use_mems (`bool`, *optional*):
  1494. Whether to use memory states to speed up sequential decoding. If set to `True`, the model will use the hidden
  1495. states from previous forward passes to compute attention, which can significantly improve performance for
  1496. sequential decoding tasks.
  1497. """
  1498. return_dict = return_dict if return_dict is not None else self.config.return_dict
  1499. num_choices = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1]
  1500. flat_input_ids = input_ids.view(-1, input_ids.size(-1)) if input_ids is not None else None
  1501. flat_token_type_ids = token_type_ids.view(-1, token_type_ids.size(-1)) if token_type_ids is not None else None
  1502. flat_attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None
  1503. flat_input_mask = input_mask.view(-1, input_mask.size(-1)) if input_mask is not None else None
  1504. flat_inputs_embeds = (
  1505. inputs_embeds.view(-1, inputs_embeds.size(-2), inputs_embeds.size(-1))
  1506. if inputs_embeds is not None
  1507. else None
  1508. )
  1509. transformer_outputs = self.transformer(
  1510. flat_input_ids,
  1511. token_type_ids=flat_token_type_ids,
  1512. input_mask=flat_input_mask,
  1513. attention_mask=flat_attention_mask,
  1514. mems=mems,
  1515. perm_mask=perm_mask,
  1516. target_mapping=target_mapping,
  1517. inputs_embeds=flat_inputs_embeds,
  1518. use_mems=use_mems,
  1519. output_attentions=output_attentions,
  1520. output_hidden_states=output_hidden_states,
  1521. return_dict=return_dict,
  1522. **kwargs,
  1523. )
  1524. output = transformer_outputs[0]
  1525. output = self.sequence_summary(output)
  1526. logits = self.logits_proj(output)
  1527. reshaped_logits = logits.view(-1, num_choices)
  1528. loss = None
  1529. if labels is not None:
  1530. loss_fct = CrossEntropyLoss()
  1531. loss = loss_fct(reshaped_logits, labels.view(-1))
  1532. if not return_dict:
  1533. output = (reshaped_logits,) + transformer_outputs[1:]
  1534. return ((loss,) + output) if loss is not None else output
  1535. return XLNetForMultipleChoiceOutput(
  1536. loss=loss,
  1537. logits=reshaped_logits,
  1538. mems=transformer_outputs.mems,
  1539. hidden_states=transformer_outputs.hidden_states,
  1540. attentions=transformer_outputs.attentions,
  1541. )
  1542. @auto_docstring(
  1543. custom_intro="""
  1544. XLNet Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear
  1545. layers on top of the hidden-states output to compute `span start logits` and `span end logits`).
  1546. """
  1547. )
  1548. class XLNetForQuestionAnsweringSimple(XLNetPreTrainedModel):
  1549. def __init__(self, config):
  1550. super().__init__(config)
  1551. self.num_labels = config.num_labels
  1552. self.transformer = XLNetModel(config)
  1553. self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
  1554. # Initialize weights and apply final processing
  1555. self.post_init()
  1556. @auto_docstring
  1557. def forward(
  1558. self,
  1559. input_ids: torch.Tensor | None = None,
  1560. attention_mask: torch.Tensor | None = None,
  1561. mems: torch.Tensor | None = None,
  1562. perm_mask: torch.Tensor | None = None,
  1563. target_mapping: torch.Tensor | None = None,
  1564. token_type_ids: torch.Tensor | None = None,
  1565. input_mask: torch.Tensor | None = None,
  1566. inputs_embeds: torch.Tensor | None = None,
  1567. start_positions: torch.Tensor | None = None,
  1568. end_positions: torch.Tensor | None = None,
  1569. use_mems: bool | None = None,
  1570. output_attentions: bool | None = None,
  1571. output_hidden_states: bool | None = None,
  1572. return_dict: bool | None = None,
  1573. **kwargs, # delete when `use_cache` is removed in XLNetModel
  1574. ) -> tuple | XLNetForQuestionAnsweringSimpleOutput:
  1575. r"""
  1576. mems (`list[torch.FloatTensor]` of length `config.n_layers`):
  1577. Contains pre-computed hidden-states (see `mems` output below) . Can be used to speed up sequential
  1578. decoding. The token ids which have their past given to this model should not be passed as `input_ids` as
  1579. they have already been computed.
  1580. `use_mems` has to be set to `True` to make use of `mems`.
  1581. perm_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length, sequence_length)`, *optional*):
  1582. Mask to indicate the attention pattern for each input token with values selected in `[0, 1]`:
  1583. - if `perm_mask[k, i, j] = 0`, i attend to j in batch k;
  1584. - if `perm_mask[k, i, j] = 1`, i does not attend to j in batch k.
  1585. If not set, each token attends to all the others (full bidirectional attention). Only used during
  1586. pretraining (to define factorization order) or for sequential decoding (generation).
  1587. target_mapping (`torch.FloatTensor` of shape `(batch_size, num_predict, sequence_length)`, *optional*):
  1588. Mask to indicate the output tokens to use. If `target_mapping[k, i, j] = 1`, the i-th predict in batch k is
  1589. on the j-th token. Only used during pretraining for partial prediction or for sequential decoding
  1590. (generation).
  1591. input_mask (`torch.FloatTensor` of shape `batch_size, sequence_length`, *optional*):
  1592. Mask to avoid performing attention on padding token indices. Negative of `attention_mask`, i.e. with 0 for
  1593. real tokens and 1 for padding which is kept for compatibility with the original code base.
  1594. Mask values selected in `[0, 1]`:
  1595. - 1 for tokens that are **masked**,
  1596. - 0 for tokens that are **not masked**.
  1597. You can only uses one of `input_mask` and `attention_mask`.
  1598. use_mems (`bool`, *optional*):
  1599. Whether to use memory states to speed up sequential decoding. If set to `True`, the model will use the hidden
  1600. states from previous forward passes to compute attention, which can significantly improve performance for
  1601. sequential decoding tasks.
  1602. """
  1603. return_dict = return_dict if return_dict is not None else self.config.return_dict
  1604. outputs = self.transformer(
  1605. input_ids,
  1606. attention_mask=attention_mask,
  1607. mems=mems,
  1608. perm_mask=perm_mask,
  1609. target_mapping=target_mapping,
  1610. token_type_ids=token_type_ids,
  1611. input_mask=input_mask,
  1612. inputs_embeds=inputs_embeds,
  1613. use_mems=use_mems,
  1614. output_attentions=output_attentions,
  1615. output_hidden_states=output_hidden_states,
  1616. return_dict=return_dict,
  1617. **kwargs,
  1618. )
  1619. sequence_output = outputs[0]
  1620. logits = self.qa_outputs(sequence_output)
  1621. start_logits, end_logits = logits.split(1, dim=-1)
  1622. start_logits = start_logits.squeeze(-1).contiguous()
  1623. end_logits = end_logits.squeeze(-1).contiguous()
  1624. total_loss = None
  1625. if start_positions is not None and end_positions is not None:
  1626. # If we are on multi-GPU, split add a dimension
  1627. if len(start_positions.size()) > 1:
  1628. start_positions = start_positions.squeeze(-1)
  1629. if len(end_positions.size()) > 1:
  1630. end_positions = end_positions.squeeze(-1)
  1631. # sometimes the start/end positions are outside our model inputs, we ignore these terms
  1632. ignored_index = start_logits.size(1)
  1633. start_positions = start_positions.clamp(0, ignored_index)
  1634. end_positions = end_positions.clamp(0, ignored_index)
  1635. loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
  1636. start_loss = loss_fct(start_logits, start_positions)
  1637. end_loss = loss_fct(end_logits, end_positions)
  1638. total_loss = (start_loss + end_loss) / 2
  1639. if not return_dict:
  1640. output = (start_logits, end_logits) + outputs[1:]
  1641. return ((total_loss,) + output) if total_loss is not None else output
  1642. return XLNetForQuestionAnsweringSimpleOutput(
  1643. loss=total_loss,
  1644. start_logits=start_logits,
  1645. end_logits=end_logits,
  1646. mems=outputs.mems,
  1647. hidden_states=outputs.hidden_states,
  1648. attentions=outputs.attentions,
  1649. )
  1650. @auto_docstring
  1651. class XLNetForQuestionAnswering(XLNetPreTrainedModel):
  1652. def __init__(self, config):
  1653. super().__init__(config)
  1654. self.start_n_top = config.start_n_top
  1655. self.end_n_top = config.end_n_top
  1656. self.transformer = XLNetModel(config)
  1657. self.start_logits = XLNetPoolerStartLogits(config)
  1658. self.end_logits = XLNetPoolerEndLogits(config)
  1659. self.answer_class = XLNetPoolerAnswerClass(config)
  1660. # Initialize weights and apply final processing
  1661. self.post_init()
  1662. @auto_docstring
  1663. def forward(
  1664. self,
  1665. input_ids: torch.Tensor | None = None,
  1666. attention_mask: torch.Tensor | None = None,
  1667. mems: torch.Tensor | None = None,
  1668. perm_mask: torch.Tensor | None = None,
  1669. target_mapping: torch.Tensor | None = None,
  1670. token_type_ids: torch.Tensor | None = None,
  1671. input_mask: torch.Tensor | None = None,
  1672. inputs_embeds: torch.Tensor | None = None,
  1673. start_positions: torch.Tensor | None = None,
  1674. end_positions: torch.Tensor | None = None,
  1675. is_impossible: torch.Tensor | None = None,
  1676. cls_index: torch.Tensor | None = None,
  1677. p_mask: torch.Tensor | None = None,
  1678. use_mems: bool | None = None,
  1679. output_attentions: bool | None = None,
  1680. output_hidden_states: bool | None = None,
  1681. return_dict: bool | None = None,
  1682. **kwargs, # delete when `use_cache` is removed in XLNetModel
  1683. ) -> tuple | XLNetForQuestionAnsweringOutput:
  1684. r"""
  1685. mems (`list[torch.FloatTensor]` of length `config.n_layers`):
  1686. Contains pre-computed hidden-states (see `mems` output below) . Can be used to speed up sequential
  1687. decoding. The token ids which have their past given to this model should not be passed as `input_ids` as
  1688. they have already been computed.
  1689. `use_mems` has to be set to `True` to make use of `mems`.
  1690. perm_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length, sequence_length)`, *optional*):
  1691. Mask to indicate the attention pattern for each input token with values selected in `[0, 1]`:
  1692. - if `perm_mask[k, i, j] = 0`, i attend to j in batch k;
  1693. - if `perm_mask[k, i, j] = 1`, i does not attend to j in batch k.
  1694. If not set, each token attends to all the others (full bidirectional attention). Only used during
  1695. pretraining (to define factorization order) or for sequential decoding (generation).
  1696. target_mapping (`torch.FloatTensor` of shape `(batch_size, num_predict, sequence_length)`, *optional*):
  1697. Mask to indicate the output tokens to use. If `target_mapping[k, i, j] = 1`, the i-th predict in batch k is
  1698. on the j-th token. Only used during pretraining for partial prediction or for sequential decoding
  1699. (generation).
  1700. input_mask (`torch.FloatTensor` of shape `batch_size, sequence_length`, *optional*):
  1701. Mask to avoid performing attention on padding token indices. Negative of `attention_mask`, i.e. with 0 for
  1702. real tokens and 1 for padding which is kept for compatibility with the original code base.
  1703. Mask values selected in `[0, 1]`:
  1704. - 1 for tokens that are **masked**,
  1705. - 0 for tokens that are **not masked**.
  1706. You can only uses one of `input_mask` and `attention_mask`.
  1707. is_impossible (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
  1708. Labels whether a question has an answer or no answer (SQuAD 2.0)
  1709. cls_index (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
  1710. Labels for position (index) of the classification token to use as input for computing plausibility of the
  1711. answer.
  1712. p_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
  1713. Optional mask of tokens which can't be in answers (e.g. [CLS], [PAD], ...). 1.0 means token should be
  1714. masked. 0.0 mean token is not masked.
  1715. use_mems (`bool`, *optional*):
  1716. Whether to use memory states to speed up sequential decoding. If set to `True`, the model will use the hidden
  1717. states from previous forward passes to compute attention, which can significantly improve performance for
  1718. sequential decoding tasks.
  1719. Example:
  1720. ```python
  1721. >>> from transformers import AutoTokenizer, XLNetForQuestionAnswering
  1722. >>> import torch
  1723. >>> tokenizer = AutoTokenizer.from_pretrained("xlnet/xlnet-base-cased")
  1724. >>> model = XLNetForQuestionAnswering.from_pretrained("xlnet/xlnet-base-cased")
  1725. >>> input_ids = torch.tensor(tokenizer.encode("Hello, my dog is cute", add_special_tokens=True)).unsqueeze(
  1726. ... 0
  1727. ... ) # Batch size 1
  1728. >>> start_positions = torch.tensor([1])
  1729. >>> end_positions = torch.tensor([3])
  1730. >>> outputs = model(input_ids, start_positions=start_positions, end_positions=end_positions)
  1731. >>> loss = outputs.loss
  1732. ```"""
  1733. return_dict = return_dict if return_dict is not None else self.config.return_dict
  1734. transformer_outputs = self.transformer(
  1735. input_ids,
  1736. attention_mask=attention_mask,
  1737. mems=mems,
  1738. perm_mask=perm_mask,
  1739. target_mapping=target_mapping,
  1740. token_type_ids=token_type_ids,
  1741. input_mask=input_mask,
  1742. inputs_embeds=inputs_embeds,
  1743. use_mems=use_mems,
  1744. output_attentions=output_attentions,
  1745. output_hidden_states=output_hidden_states,
  1746. return_dict=return_dict,
  1747. **kwargs,
  1748. )
  1749. hidden_states = transformer_outputs[0]
  1750. start_logits = self.start_logits(hidden_states, p_mask=p_mask)
  1751. outputs = transformer_outputs[1:] # Keep mems, hidden states, attentions if there are in it
  1752. if start_positions is not None and end_positions is not None:
  1753. # If we are on multi-GPU, let's remove the dimension added by batch splitting
  1754. for x in (start_positions, end_positions, cls_index, is_impossible):
  1755. if x is not None and x.dim() > 1:
  1756. x.squeeze_(-1)
  1757. # during training, compute the end logits based on the ground truth of the start position
  1758. end_logits = self.end_logits(hidden_states, start_positions=start_positions, p_mask=p_mask)
  1759. loss_fct = CrossEntropyLoss()
  1760. start_loss = loss_fct(start_logits, start_positions)
  1761. end_loss = loss_fct(end_logits, end_positions)
  1762. total_loss = (start_loss + end_loss) / 2
  1763. if cls_index is not None and is_impossible is not None:
  1764. # Predict answerability from the representation of CLS and START
  1765. cls_logits = self.answer_class(hidden_states, start_positions=start_positions, cls_index=cls_index)
  1766. loss_fct_cls = nn.BCEWithLogitsLoss()
  1767. cls_loss = loss_fct_cls(cls_logits, is_impossible)
  1768. # note(zhiliny): by default multiply the loss by 0.5 so that the scale is comparable to start_loss and end_loss
  1769. total_loss += cls_loss * 0.5
  1770. if not return_dict:
  1771. return (total_loss,) + transformer_outputs[1:]
  1772. else:
  1773. return XLNetForQuestionAnsweringOutput(
  1774. loss=total_loss,
  1775. mems=transformer_outputs.mems,
  1776. hidden_states=transformer_outputs.hidden_states,
  1777. attentions=transformer_outputs.attentions,
  1778. )
  1779. else:
  1780. # during inference, compute the end logits based on beam search
  1781. bsz, slen, hsz = hidden_states.size()
  1782. start_log_probs = nn.functional.softmax(start_logits, dim=-1) # shape (bsz, slen)
  1783. start_top_log_probs, start_top_index = torch.topk(
  1784. start_log_probs, self.start_n_top, dim=-1
  1785. ) # shape (bsz, start_n_top)
  1786. start_top_index_exp = start_top_index.unsqueeze(-1).expand(-1, -1, hsz) # shape (bsz, start_n_top, hsz)
  1787. start_states = torch.gather(hidden_states, -2, start_top_index_exp) # shape (bsz, start_n_top, hsz)
  1788. start_states = start_states.unsqueeze(1).expand(-1, slen, -1, -1) # shape (bsz, slen, start_n_top, hsz)
  1789. hidden_states_expanded = hidden_states.unsqueeze(2).expand_as(
  1790. start_states
  1791. ) # shape (bsz, slen, start_n_top, hsz)
  1792. p_mask = p_mask.unsqueeze(-1) if p_mask is not None else None
  1793. end_logits = self.end_logits(hidden_states_expanded, start_states=start_states, p_mask=p_mask)
  1794. end_log_probs = nn.functional.softmax(end_logits, dim=1) # shape (bsz, slen, start_n_top)
  1795. end_top_log_probs, end_top_index = torch.topk(
  1796. end_log_probs, self.end_n_top, dim=1
  1797. ) # shape (bsz, end_n_top, start_n_top)
  1798. end_top_log_probs = end_top_log_probs.view(-1, self.start_n_top * self.end_n_top)
  1799. end_top_index = end_top_index.view(-1, self.start_n_top * self.end_n_top)
  1800. start_states = torch.einsum(
  1801. "blh,bl->bh", hidden_states, start_log_probs
  1802. ) # get the representation of START as weighted sum of hidden states
  1803. cls_logits = self.answer_class(
  1804. hidden_states, start_states=start_states, cls_index=cls_index
  1805. ) # Shape (batch size,): one single `cls_logits` for each sample
  1806. if not return_dict:
  1807. outputs = (start_top_log_probs, start_top_index, end_top_log_probs, end_top_index, cls_logits)
  1808. return outputs + transformer_outputs[1:]
  1809. else:
  1810. return XLNetForQuestionAnsweringOutput(
  1811. start_top_log_probs=start_top_log_probs,
  1812. start_top_index=start_top_index,
  1813. end_top_log_probs=end_top_log_probs,
  1814. end_top_index=end_top_index,
  1815. cls_logits=cls_logits,
  1816. mems=transformer_outputs.mems,
  1817. hidden_states=transformer_outputs.hidden_states,
  1818. attentions=transformer_outputs.attentions,
  1819. )
  1820. __all__ = [
  1821. "XLNetForMultipleChoice",
  1822. "XLNetForQuestionAnswering",
  1823. "XLNetForQuestionAnsweringSimple",
  1824. "XLNetForSequenceClassification",
  1825. "XLNetForTokenClassification",
  1826. "XLNetLMHeadModel",
  1827. "XLNetModel",
  1828. "XLNetPreTrainedModel",
  1829. ]