modeling_led.py 135 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714
  1. # coding=utf-8
  2. # Copyright 2021 Iz Beltagy, Matthew E. Peters, Arman Cohan and The HuggingFace Inc. team. 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. """PyTorch LED model."""
  16. import math
  17. import warnings
  18. from dataclasses import dataclass
  19. from typing import List, Optional, Tuple, Union
  20. import torch
  21. import torch.utils.checkpoint
  22. from torch import nn
  23. from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
  24. from ...activations import ACT2FN
  25. from ...generation import GenerationMixin
  26. from ...modeling_attn_mask_utils import _create_4d_causal_attention_mask
  27. from ...modeling_outputs import (
  28. BaseModelOutputWithPastAndCrossAttentions,
  29. Seq2SeqLMOutput,
  30. Seq2SeqModelOutput,
  31. Seq2SeqQuestionAnsweringModelOutput,
  32. Seq2SeqSequenceClassifierOutput,
  33. )
  34. from ...modeling_utils import PreTrainedModel
  35. from ...utils import (
  36. ModelOutput,
  37. add_code_sample_docstrings,
  38. add_end_docstrings,
  39. add_start_docstrings,
  40. add_start_docstrings_to_model_forward,
  41. logging,
  42. replace_return_docstrings,
  43. )
  44. from .configuration_led import LEDConfig
  45. logger = logging.get_logger(__name__)
  46. _CHECKPOINT_FOR_DOC = "allenai/led-base-16384"
  47. _CONFIG_FOR_DOC = "LEDConfig"
  48. def shift_tokens_right(input_ids: torch.Tensor, pad_token_id: int, decoder_start_token_id: int):
  49. """
  50. Shift input ids one token to the right.
  51. """
  52. shifted_input_ids = input_ids.new_zeros(input_ids.shape)
  53. shifted_input_ids[:, 1:] = input_ids[:, :-1].clone()
  54. shifted_input_ids[:, 0] = decoder_start_token_id
  55. if pad_token_id is None:
  56. raise ValueError("config.pad_token_id has to be defined.")
  57. # replace possible -100 values in labels by `pad_token_id`
  58. shifted_input_ids.masked_fill_(shifted_input_ids == -100, pad_token_id)
  59. return shifted_input_ids
  60. def _prepare_4d_attention_mask_inverted(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
  61. """
  62. Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
  63. """
  64. bsz, src_len = mask.size()
  65. tgt_len = tgt_len if tgt_len is not None else src_len
  66. expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)
  67. inverted_mask = 1.0 - expanded_mask
  68. expanded_attention_mask = inverted_mask.masked_fill(inverted_mask.bool(), torch.finfo(dtype).min)
  69. # make sure that global_attn_mask is positive
  70. expanded_attention_mask = expanded_attention_mask * inverted_mask
  71. return expanded_attention_mask
  72. class LEDLearnedPositionalEmbedding(nn.Embedding):
  73. """
  74. This module learns positional embeddings up to a fixed maximum size.
  75. """
  76. def __init__(self, num_embeddings: int, embedding_dim: int):
  77. super().__init__(num_embeddings, embedding_dim)
  78. def forward(self, input_ids_shape: torch.Size, past_key_values_length: int = 0):
  79. """`input_ids_shape` is expected to be [bsz x seqlen]."""
  80. bsz, seq_len = input_ids_shape[:2]
  81. positions = torch.arange(
  82. past_key_values_length, past_key_values_length + seq_len, dtype=torch.long, device=self.weight.device
  83. )
  84. return super().forward(positions)
  85. # Copied from transformers.models.longformer.modeling_longformer.LongformerSelfAttention with Longformer->LEDEncoder
  86. class LEDEncoderSelfAttention(nn.Module):
  87. def __init__(self, config, layer_id):
  88. super().__init__()
  89. if config.hidden_size % config.num_attention_heads != 0:
  90. raise ValueError(
  91. f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
  92. f"heads ({config.num_attention_heads})"
  93. )
  94. self.num_heads = config.num_attention_heads
  95. self.head_dim = int(config.hidden_size / config.num_attention_heads)
  96. self.embed_dim = config.hidden_size
  97. self.query = nn.Linear(config.hidden_size, self.embed_dim)
  98. self.key = nn.Linear(config.hidden_size, self.embed_dim)
  99. self.value = nn.Linear(config.hidden_size, self.embed_dim)
  100. # separate projection layers for tokens with global attention
  101. self.query_global = nn.Linear(config.hidden_size, self.embed_dim)
  102. self.key_global = nn.Linear(config.hidden_size, self.embed_dim)
  103. self.value_global = nn.Linear(config.hidden_size, self.embed_dim)
  104. self.dropout = config.attention_probs_dropout_prob
  105. self.layer_id = layer_id
  106. attention_window = config.attention_window[self.layer_id]
  107. assert (
  108. attention_window % 2 == 0
  109. ), f"`attention_window` for layer {self.layer_id} has to be an even value. Given {attention_window}"
  110. assert (
  111. attention_window > 0
  112. ), f"`attention_window` for layer {self.layer_id} has to be positive. Given {attention_window}"
  113. self.one_sided_attn_window_size = attention_window // 2
  114. self.config = config
  115. def forward(
  116. self,
  117. hidden_states,
  118. attention_mask=None,
  119. layer_head_mask=None,
  120. is_index_masked=None,
  121. is_index_global_attn=None,
  122. is_global_attn=None,
  123. output_attentions=False,
  124. ):
  125. """
  126. [`LEDEncoderSelfAttention`] expects *len(hidden_states)* to be multiple of *attention_window*. Padding to
  127. *attention_window* happens in [`LEDEncoderModel.forward`] to avoid redoing the padding on each layer.
  128. The *attention_mask* is changed in [`LEDEncoderModel.forward`] from 0, 1, 2 to:
  129. - -10000: no attention
  130. - 0: local attention
  131. - +10000: global attention
  132. """
  133. hidden_states = hidden_states.transpose(0, 1)
  134. # project hidden states
  135. query_vectors = self.query(hidden_states)
  136. key_vectors = self.key(hidden_states)
  137. value_vectors = self.value(hidden_states)
  138. seq_len, batch_size, embed_dim = hidden_states.size()
  139. assert (
  140. embed_dim == self.embed_dim
  141. ), f"hidden_states should have embed_dim = {self.embed_dim}, but has {embed_dim}"
  142. # normalize query
  143. query_vectors /= math.sqrt(self.head_dim)
  144. query_vectors = query_vectors.view(seq_len, batch_size, self.num_heads, self.head_dim).transpose(0, 1)
  145. key_vectors = key_vectors.view(seq_len, batch_size, self.num_heads, self.head_dim).transpose(0, 1)
  146. attn_scores = self._sliding_chunks_query_key_matmul(
  147. query_vectors, key_vectors, self.one_sided_attn_window_size
  148. )
  149. # values to pad for attention probs
  150. remove_from_windowed_attention_mask = (attention_mask != 0)[:, :, None, None]
  151. # cast to fp32/fp16 then replace 1's with -inf
  152. float_mask = remove_from_windowed_attention_mask.type_as(query_vectors).masked_fill(
  153. remove_from_windowed_attention_mask, torch.finfo(query_vectors.dtype).min
  154. )
  155. # diagonal mask with zeros everywhere and -inf inplace of padding
  156. diagonal_mask = self._sliding_chunks_query_key_matmul(
  157. float_mask.new_ones(size=float_mask.size()), float_mask, self.one_sided_attn_window_size
  158. )
  159. # pad local attention probs
  160. attn_scores += diagonal_mask
  161. assert list(attn_scores.size()) == [
  162. batch_size,
  163. seq_len,
  164. self.num_heads,
  165. self.one_sided_attn_window_size * 2 + 1,
  166. ], (
  167. f"local_attn_probs should be of size ({batch_size}, {seq_len}, {self.num_heads},"
  168. f" {self.one_sided_attn_window_size * 2 + 1}), but is of size {attn_scores.size()}"
  169. )
  170. # compute local attention probs from global attention keys and contact over window dim
  171. if is_global_attn:
  172. # compute global attn indices required through out forward fn
  173. (
  174. max_num_global_attn_indices,
  175. is_index_global_attn_nonzero,
  176. is_local_index_global_attn_nonzero,
  177. is_local_index_no_global_attn_nonzero,
  178. ) = self._get_global_attn_indices(is_index_global_attn)
  179. # calculate global attn probs from global key
  180. global_key_attn_scores = self._concat_with_global_key_attn_probs(
  181. query_vectors=query_vectors,
  182. key_vectors=key_vectors,
  183. max_num_global_attn_indices=max_num_global_attn_indices,
  184. is_index_global_attn_nonzero=is_index_global_attn_nonzero,
  185. is_local_index_global_attn_nonzero=is_local_index_global_attn_nonzero,
  186. is_local_index_no_global_attn_nonzero=is_local_index_no_global_attn_nonzero,
  187. )
  188. # concat to local_attn_probs
  189. # (batch_size, seq_len, num_heads, extra attention count + 2*window+1)
  190. attn_scores = torch.cat((global_key_attn_scores, attn_scores), dim=-1)
  191. # free memory
  192. del global_key_attn_scores
  193. attn_probs = nn.functional.softmax(
  194. attn_scores, dim=-1, dtype=torch.float32
  195. ) # use fp32 for numerical stability
  196. if layer_head_mask is not None:
  197. assert layer_head_mask.size() == (
  198. self.num_heads,
  199. ), f"Head mask for a single layer should be of size {(self.num_heads,)}, but is {layer_head_mask.size()}"
  200. attn_probs = layer_head_mask.view(1, 1, -1, 1) * attn_probs
  201. # softmax sometimes inserts NaN if all positions are masked, replace them with 0
  202. attn_probs = torch.masked_fill(attn_probs, is_index_masked[:, :, None, None], 0.0)
  203. attn_probs = attn_probs.type_as(attn_scores)
  204. # free memory
  205. del attn_scores
  206. # apply dropout
  207. attn_probs = nn.functional.dropout(attn_probs, p=self.dropout, training=self.training)
  208. value_vectors = value_vectors.view(seq_len, batch_size, self.num_heads, self.head_dim).transpose(0, 1)
  209. # compute local attention output with global attention value and add
  210. if is_global_attn:
  211. # compute sum of global and local attn
  212. attn_output = self._compute_attn_output_with_global_indices(
  213. value_vectors=value_vectors,
  214. attn_probs=attn_probs,
  215. max_num_global_attn_indices=max_num_global_attn_indices,
  216. is_index_global_attn_nonzero=is_index_global_attn_nonzero,
  217. is_local_index_global_attn_nonzero=is_local_index_global_attn_nonzero,
  218. )
  219. else:
  220. # compute local attn only
  221. attn_output = self._sliding_chunks_matmul_attn_probs_value(
  222. attn_probs, value_vectors, self.one_sided_attn_window_size
  223. )
  224. assert attn_output.size() == (batch_size, seq_len, self.num_heads, self.head_dim), "Unexpected size"
  225. attn_output = attn_output.transpose(0, 1).reshape(seq_len, batch_size, embed_dim).contiguous()
  226. # compute value for global attention and overwrite to attention output
  227. # TODO: remove the redundant computation
  228. if is_global_attn:
  229. global_attn_output, global_attn_probs = self._compute_global_attn_output_from_hidden(
  230. hidden_states=hidden_states,
  231. max_num_global_attn_indices=max_num_global_attn_indices,
  232. layer_head_mask=layer_head_mask,
  233. is_local_index_global_attn_nonzero=is_local_index_global_attn_nonzero,
  234. is_index_global_attn_nonzero=is_index_global_attn_nonzero,
  235. is_local_index_no_global_attn_nonzero=is_local_index_no_global_attn_nonzero,
  236. is_index_masked=is_index_masked,
  237. )
  238. # get only non zero global attn output
  239. nonzero_global_attn_output = global_attn_output[
  240. is_local_index_global_attn_nonzero[0], :, is_local_index_global_attn_nonzero[1]
  241. ]
  242. # overwrite values with global attention
  243. attn_output[is_index_global_attn_nonzero[::-1]] = nonzero_global_attn_output.view(
  244. len(is_local_index_global_attn_nonzero[0]), -1
  245. )
  246. # The attention weights for tokens with global attention are
  247. # just filler values, they were never used to compute the output.
  248. # Fill with 0 now, the correct values are in 'global_attn_probs'.
  249. attn_probs[is_index_global_attn_nonzero] = 0
  250. outputs = (attn_output.transpose(0, 1),)
  251. if output_attentions:
  252. outputs += (attn_probs,)
  253. return outputs + (global_attn_probs,) if (is_global_attn and output_attentions) else outputs
  254. @staticmethod
  255. def _pad_and_transpose_last_two_dims(hidden_states_padded, padding):
  256. """pads rows and then flips rows and columns"""
  257. hidden_states_padded = nn.functional.pad(
  258. hidden_states_padded, padding
  259. ) # padding value is not important because it will be overwritten
  260. hidden_states_padded = hidden_states_padded.view(
  261. *hidden_states_padded.size()[:-2], hidden_states_padded.size(-1), hidden_states_padded.size(-2)
  262. )
  263. return hidden_states_padded
  264. @staticmethod
  265. def _pad_and_diagonalize(chunked_hidden_states):
  266. """
  267. shift every row 1 step right, converting columns into diagonals.
  268. Example:
  269. ```python
  270. chunked_hidden_states: [
  271. 0.4983,
  272. 2.6918,
  273. -0.0071,
  274. 1.0492,
  275. -1.8348,
  276. 0.7672,
  277. 0.2986,
  278. 0.0285,
  279. -0.7584,
  280. 0.4206,
  281. -0.0405,
  282. 0.1599,
  283. 2.0514,
  284. -1.1600,
  285. 0.5372,
  286. 0.2629,
  287. ]
  288. window_overlap = num_rows = 4
  289. ```
  290. (pad & diagonalize) => [ 0.4983, 2.6918, -0.0071, 1.0492, 0.0000, 0.0000, 0.0000
  291. 0.0000, -1.8348, 0.7672, 0.2986, 0.0285, 0.0000, 0.0000 0.0000, 0.0000, -0.7584, 0.4206,
  292. -0.0405, 0.1599, 0.0000 0.0000, 0.0000, 0.0000, 2.0514, -1.1600, 0.5372, 0.2629 ]
  293. """
  294. total_num_heads, num_chunks, window_overlap, hidden_dim = chunked_hidden_states.size()
  295. chunked_hidden_states = nn.functional.pad(
  296. chunked_hidden_states, (0, window_overlap + 1)
  297. ) # total_num_heads x num_chunks x window_overlap x (hidden_dim+window_overlap+1). Padding value is not important because it'll be overwritten
  298. chunked_hidden_states = chunked_hidden_states.view(
  299. total_num_heads, num_chunks, -1
  300. ) # total_num_heads x num_chunks x window_overlap*window_overlap+window_overlap
  301. chunked_hidden_states = chunked_hidden_states[
  302. :, :, :-window_overlap
  303. ] # total_num_heads x num_chunks x window_overlap*window_overlap
  304. chunked_hidden_states = chunked_hidden_states.view(
  305. total_num_heads, num_chunks, window_overlap, window_overlap + hidden_dim
  306. )
  307. chunked_hidden_states = chunked_hidden_states[:, :, :, :-1]
  308. return chunked_hidden_states
  309. @staticmethod
  310. def _chunk(hidden_states, window_overlap, onnx_export: bool = False):
  311. """convert into overlapping chunks. Chunk size = 2w, overlap size = w"""
  312. if not onnx_export:
  313. # non-overlapping chunks of size = 2w
  314. hidden_states = hidden_states.view(
  315. hidden_states.size(0),
  316. torch.div(hidden_states.size(1), (window_overlap * 2), rounding_mode="trunc"),
  317. window_overlap * 2,
  318. hidden_states.size(2),
  319. )
  320. # use `as_strided` to make the chunks overlap with an overlap size = window_overlap
  321. chunk_size = list(hidden_states.size())
  322. chunk_size[1] = chunk_size[1] * 2 - 1
  323. chunk_stride = list(hidden_states.stride())
  324. chunk_stride[1] = chunk_stride[1] // 2
  325. return hidden_states.as_strided(size=chunk_size, stride=chunk_stride)
  326. # When exporting to ONNX, use this separate logic
  327. # have to use slow implementation since as_strided, unfold and 2d-tensor indexing aren't supported (yet) in ONNX export
  328. # TODO replace this with
  329. # > return hidden_states.unfold(dimension=1, size=window_overlap * 2, step=window_overlap).transpose(2, 3)
  330. # once `unfold` is supported
  331. # the case hidden_states.size(1) == window_overlap * 2 can also simply return hidden_states.unsqueeze(1), but that's control flow
  332. chunk_size = [
  333. hidden_states.size(0),
  334. torch.div(hidden_states.size(1), window_overlap, rounding_mode="trunc") - 1,
  335. window_overlap * 2,
  336. hidden_states.size(2),
  337. ]
  338. overlapping_chunks = torch.empty(chunk_size, device=hidden_states.device)
  339. for chunk in range(chunk_size[1]):
  340. overlapping_chunks[:, chunk, :, :] = hidden_states[
  341. :, chunk * window_overlap : chunk * window_overlap + 2 * window_overlap, :
  342. ]
  343. return overlapping_chunks
  344. @staticmethod
  345. def _mask_invalid_locations(input_tensor, affected_seq_len) -> torch.Tensor:
  346. beginning_mask_2d = input_tensor.new_ones(affected_seq_len, affected_seq_len + 1).tril().flip(dims=[0])
  347. beginning_mask = beginning_mask_2d[None, :, None, :]
  348. ending_mask = beginning_mask.flip(dims=(1, 3))
  349. beginning_input = input_tensor[:, :affected_seq_len, :, : affected_seq_len + 1]
  350. beginning_mask = beginning_mask.expand(beginning_input.size())
  351. input_tensor[:, :affected_seq_len, :, : affected_seq_len + 1] = torch.full_like(
  352. beginning_input, -float("inf")
  353. ).where(beginning_mask.bool(), beginning_input)
  354. ending_input = input_tensor[:, -affected_seq_len:, :, -(affected_seq_len + 1) :]
  355. ending_mask = ending_mask.expand(ending_input.size())
  356. input_tensor[:, -affected_seq_len:, :, -(affected_seq_len + 1) :] = torch.full_like(
  357. ending_input, -float("inf")
  358. ).where(ending_mask.bool(), ending_input)
  359. def _sliding_chunks_query_key_matmul(self, query: torch.Tensor, key: torch.Tensor, window_overlap: int):
  360. """
  361. Matrix multiplication of query and key tensors using with a sliding window attention pattern. This
  362. implementation splits the input into overlapping chunks of size 2w (e.g. 512 for pretrained LEDEncoder) with an
  363. overlap of size window_overlap
  364. """
  365. batch_size, seq_len, num_heads, head_dim = query.size()
  366. assert (
  367. seq_len % (window_overlap * 2) == 0
  368. ), f"Sequence length should be multiple of {window_overlap * 2}. Given {seq_len}"
  369. assert query.size() == key.size()
  370. chunks_count = torch.div(seq_len, window_overlap, rounding_mode="trunc") - 1
  371. # group batch_size and num_heads dimensions into one, then chunk seq_len into chunks of size window_overlap * 2
  372. query = query.transpose(1, 2).reshape(batch_size * num_heads, seq_len, head_dim)
  373. key = key.transpose(1, 2).reshape(batch_size * num_heads, seq_len, head_dim)
  374. query = self._chunk(query, window_overlap, getattr(self.config, "onnx_export", False))
  375. key = self._chunk(key, window_overlap, getattr(self.config, "onnx_export", False))
  376. # matrix multiplication
  377. # bcxd: batch_size * num_heads x chunks x 2window_overlap x head_dim
  378. # bcyd: batch_size * num_heads x chunks x 2window_overlap x head_dim
  379. # bcxy: batch_size * num_heads x chunks x 2window_overlap x 2window_overlap
  380. diagonal_chunked_attention_scores = torch.einsum("bcxd,bcyd->bcxy", (query, key)) # multiply
  381. # convert diagonals into columns
  382. diagonal_chunked_attention_scores = self._pad_and_transpose_last_two_dims(
  383. diagonal_chunked_attention_scores, padding=(0, 0, 0, 1)
  384. )
  385. # allocate space for the overall attention matrix where the chunks are combined. The last dimension
  386. # has (window_overlap * 2 + 1) columns. The first (window_overlap) columns are the window_overlap lower triangles (attention from a word to
  387. # window_overlap previous words). The following column is attention score from each word to itself, then
  388. # followed by window_overlap columns for the upper triangle.
  389. diagonal_attention_scores = diagonal_chunked_attention_scores.new_zeros(
  390. (batch_size * num_heads, chunks_count + 1, window_overlap, window_overlap * 2 + 1)
  391. )
  392. # copy parts from diagonal_chunked_attention_scores into the combined matrix of attentions
  393. # - copying the main diagonal and the upper triangle
  394. diagonal_attention_scores[:, :-1, :, window_overlap:] = diagonal_chunked_attention_scores[
  395. :, :, :window_overlap, : window_overlap + 1
  396. ]
  397. diagonal_attention_scores[:, -1, :, window_overlap:] = diagonal_chunked_attention_scores[
  398. :, -1, window_overlap:, : window_overlap + 1
  399. ]
  400. # - copying the lower triangle
  401. diagonal_attention_scores[:, 1:, :, :window_overlap] = diagonal_chunked_attention_scores[
  402. :, :, -(window_overlap + 1) : -1, window_overlap + 1 :
  403. ]
  404. diagonal_attention_scores[:, 0, 1:window_overlap, 1:window_overlap] = diagonal_chunked_attention_scores[
  405. :, 0, : window_overlap - 1, 1 - window_overlap :
  406. ]
  407. # separate batch_size and num_heads dimensions again
  408. diagonal_attention_scores = diagonal_attention_scores.view(
  409. batch_size, num_heads, seq_len, 2 * window_overlap + 1
  410. ).transpose(2, 1)
  411. self._mask_invalid_locations(diagonal_attention_scores, window_overlap)
  412. return diagonal_attention_scores
  413. def _sliding_chunks_matmul_attn_probs_value(
  414. self, attn_probs: torch.Tensor, value: torch.Tensor, window_overlap: int
  415. ):
  416. """
  417. Same as _sliding_chunks_query_key_matmul but for attn_probs and value tensors. Returned tensor will be of the
  418. same shape as `attn_probs`
  419. """
  420. batch_size, seq_len, num_heads, head_dim = value.size()
  421. assert seq_len % (window_overlap * 2) == 0
  422. assert attn_probs.size()[:3] == value.size()[:3]
  423. assert attn_probs.size(3) == 2 * window_overlap + 1
  424. chunks_count = torch.div(seq_len, window_overlap, rounding_mode="trunc") - 1
  425. # group batch_size and num_heads dimensions into one, then chunk seq_len into chunks of size 2 window overlap
  426. chunked_attn_probs = attn_probs.transpose(1, 2).reshape(
  427. batch_size * num_heads,
  428. torch.div(seq_len, window_overlap, rounding_mode="trunc"),
  429. window_overlap,
  430. 2 * window_overlap + 1,
  431. )
  432. # group batch_size and num_heads dimensions into one
  433. value = value.transpose(1, 2).reshape(batch_size * num_heads, seq_len, head_dim)
  434. # pad seq_len with w at the beginning of the sequence and another window overlap at the end
  435. padded_value = nn.functional.pad(value, (0, 0, window_overlap, window_overlap), value=-1)
  436. # chunk padded_value into chunks of size 3 window overlap and an overlap of size window overlap
  437. chunked_value_size = (batch_size * num_heads, chunks_count + 1, 3 * window_overlap, head_dim)
  438. chunked_value_stride = padded_value.stride()
  439. chunked_value_stride = (
  440. chunked_value_stride[0],
  441. window_overlap * chunked_value_stride[1],
  442. chunked_value_stride[1],
  443. chunked_value_stride[2],
  444. )
  445. chunked_value = padded_value.as_strided(size=chunked_value_size, stride=chunked_value_stride)
  446. chunked_attn_probs = self._pad_and_diagonalize(chunked_attn_probs)
  447. context = torch.einsum("bcwd,bcdh->bcwh", (chunked_attn_probs, chunked_value))
  448. return context.view(batch_size, num_heads, seq_len, head_dim).transpose(1, 2)
  449. @staticmethod
  450. def _get_global_attn_indices(is_index_global_attn):
  451. """compute global attn indices required throughout forward pass"""
  452. # helper variable
  453. num_global_attn_indices = is_index_global_attn.long().sum(dim=1)
  454. # max number of global attn indices in batch
  455. max_num_global_attn_indices = num_global_attn_indices.max()
  456. # indices of global attn
  457. is_index_global_attn_nonzero = is_index_global_attn.nonzero(as_tuple=True)
  458. # helper variable
  459. is_local_index_global_attn = torch.arange(
  460. max_num_global_attn_indices, device=is_index_global_attn.device
  461. ) < num_global_attn_indices.unsqueeze(dim=-1)
  462. # location of the non-padding values within global attention indices
  463. is_local_index_global_attn_nonzero = is_local_index_global_attn.nonzero(as_tuple=True)
  464. # location of the padding values within global attention indices
  465. is_local_index_no_global_attn_nonzero = (is_local_index_global_attn == 0).nonzero(as_tuple=True)
  466. return (
  467. max_num_global_attn_indices,
  468. is_index_global_attn_nonzero,
  469. is_local_index_global_attn_nonzero,
  470. is_local_index_no_global_attn_nonzero,
  471. )
  472. def _concat_with_global_key_attn_probs(
  473. self,
  474. key_vectors,
  475. query_vectors,
  476. max_num_global_attn_indices,
  477. is_index_global_attn_nonzero,
  478. is_local_index_global_attn_nonzero,
  479. is_local_index_no_global_attn_nonzero,
  480. ):
  481. batch_size = key_vectors.shape[0]
  482. # create only global key vectors
  483. key_vectors_only_global = key_vectors.new_zeros(
  484. batch_size, max_num_global_attn_indices, self.num_heads, self.head_dim
  485. )
  486. key_vectors_only_global[is_local_index_global_attn_nonzero] = key_vectors[is_index_global_attn_nonzero]
  487. # (batch_size, seq_len, num_heads, max_num_global_attn_indices)
  488. attn_probs_from_global_key = torch.einsum("blhd,bshd->blhs", (query_vectors, key_vectors_only_global))
  489. # need to transpose since ONNX export only supports consecutive indexing: https://pytorch.org/docs/stable/onnx.html#writes-sets
  490. attn_probs_from_global_key = attn_probs_from_global_key.transpose(1, 3)
  491. attn_probs_from_global_key[
  492. is_local_index_no_global_attn_nonzero[0], is_local_index_no_global_attn_nonzero[1], :, :
  493. ] = torch.finfo(attn_probs_from_global_key.dtype).min
  494. attn_probs_from_global_key = attn_probs_from_global_key.transpose(1, 3)
  495. return attn_probs_from_global_key
  496. def _compute_attn_output_with_global_indices(
  497. self,
  498. value_vectors,
  499. attn_probs,
  500. max_num_global_attn_indices,
  501. is_index_global_attn_nonzero,
  502. is_local_index_global_attn_nonzero,
  503. ):
  504. batch_size = attn_probs.shape[0]
  505. # cut local attn probs to global only
  506. attn_probs_only_global = attn_probs.narrow(-1, 0, max_num_global_attn_indices)
  507. # get value vectors for global only
  508. value_vectors_only_global = value_vectors.new_zeros(
  509. batch_size, max_num_global_attn_indices, self.num_heads, self.head_dim
  510. )
  511. value_vectors_only_global[is_local_index_global_attn_nonzero] = value_vectors[is_index_global_attn_nonzero]
  512. # use `matmul` because `einsum` crashes sometimes with fp16
  513. # attn = torch.einsum('blhs,bshd->blhd', (selected_attn_probs, selected_v))
  514. # compute attn output only global
  515. attn_output_only_global = torch.matmul(
  516. attn_probs_only_global.transpose(1, 2).clone(), value_vectors_only_global.transpose(1, 2).clone()
  517. ).transpose(1, 2)
  518. # reshape attn probs
  519. attn_probs_without_global = attn_probs.narrow(
  520. -1, max_num_global_attn_indices, attn_probs.size(-1) - max_num_global_attn_indices
  521. ).contiguous()
  522. # compute attn output with global
  523. attn_output_without_global = self._sliding_chunks_matmul_attn_probs_value(
  524. attn_probs_without_global, value_vectors, self.one_sided_attn_window_size
  525. )
  526. return attn_output_only_global + attn_output_without_global
  527. def _compute_global_attn_output_from_hidden(
  528. self,
  529. hidden_states,
  530. max_num_global_attn_indices,
  531. layer_head_mask,
  532. is_local_index_global_attn_nonzero,
  533. is_index_global_attn_nonzero,
  534. is_local_index_no_global_attn_nonzero,
  535. is_index_masked,
  536. ):
  537. seq_len, batch_size = hidden_states.shape[:2]
  538. # prepare global hidden states
  539. global_attn_hidden_states = hidden_states.new_zeros(max_num_global_attn_indices, batch_size, self.embed_dim)
  540. global_attn_hidden_states[is_local_index_global_attn_nonzero[::-1]] = hidden_states[
  541. is_index_global_attn_nonzero[::-1]
  542. ]
  543. # global key, query, value
  544. global_query_vectors_only_global = self.query_global(global_attn_hidden_states)
  545. global_key_vectors = self.key_global(hidden_states)
  546. global_value_vectors = self.value_global(hidden_states)
  547. # normalize
  548. global_query_vectors_only_global /= math.sqrt(self.head_dim)
  549. # reshape
  550. global_query_vectors_only_global = (
  551. global_query_vectors_only_global.contiguous()
  552. .view(max_num_global_attn_indices, batch_size * self.num_heads, self.head_dim)
  553. .transpose(0, 1)
  554. ) # (batch_size * self.num_heads, max_num_global_attn_indices, head_dim)
  555. global_key_vectors = (
  556. global_key_vectors.contiguous().view(-1, batch_size * self.num_heads, self.head_dim).transpose(0, 1)
  557. ) # batch_size * self.num_heads, seq_len, head_dim)
  558. global_value_vectors = (
  559. global_value_vectors.contiguous().view(-1, batch_size * self.num_heads, self.head_dim).transpose(0, 1)
  560. ) # batch_size * self.num_heads, seq_len, head_dim)
  561. # compute attn scores
  562. global_attn_scores = torch.bmm(global_query_vectors_only_global, global_key_vectors.transpose(1, 2))
  563. assert list(global_attn_scores.size()) == [
  564. batch_size * self.num_heads,
  565. max_num_global_attn_indices,
  566. seq_len,
  567. ], (
  568. "global_attn_scores have the wrong size. Size should be"
  569. f" {(batch_size * self.num_heads, max_num_global_attn_indices, seq_len)}, but is"
  570. f" {global_attn_scores.size()}."
  571. )
  572. global_attn_scores = global_attn_scores.view(batch_size, self.num_heads, max_num_global_attn_indices, seq_len)
  573. # need to transpose since ONNX export only supports consecutive indexing: https://pytorch.org/docs/stable/onnx.html#writes-sets
  574. global_attn_scores = global_attn_scores.transpose(1, 2)
  575. global_attn_scores[
  576. is_local_index_no_global_attn_nonzero[0], is_local_index_no_global_attn_nonzero[1], :, :
  577. ] = torch.finfo(global_attn_scores.dtype).min
  578. global_attn_scores = global_attn_scores.transpose(1, 2)
  579. global_attn_scores = global_attn_scores.masked_fill(
  580. is_index_masked[:, None, None, :],
  581. torch.finfo(global_attn_scores.dtype).min,
  582. )
  583. global_attn_scores = global_attn_scores.view(batch_size * self.num_heads, max_num_global_attn_indices, seq_len)
  584. # compute global attn probs
  585. global_attn_probs_float = nn.functional.softmax(
  586. global_attn_scores, dim=-1, dtype=torch.float32
  587. ) # use fp32 for numerical stability
  588. # apply layer head masking
  589. if layer_head_mask is not None:
  590. assert layer_head_mask.size() == (
  591. self.num_heads,
  592. ), f"Head mask for a single layer should be of size {(self.num_heads,)}, but is {layer_head_mask.size()}"
  593. global_attn_probs_float = layer_head_mask.view(1, -1, 1, 1) * global_attn_probs_float.view(
  594. batch_size, self.num_heads, max_num_global_attn_indices, seq_len
  595. )
  596. global_attn_probs_float = global_attn_probs_float.view(
  597. batch_size * self.num_heads, max_num_global_attn_indices, seq_len
  598. )
  599. global_attn_probs = nn.functional.dropout(
  600. global_attn_probs_float.type_as(global_attn_scores), p=self.dropout, training=self.training
  601. )
  602. # global attn output
  603. global_attn_output = torch.bmm(global_attn_probs, global_value_vectors)
  604. assert list(global_attn_output.size()) == [
  605. batch_size * self.num_heads,
  606. max_num_global_attn_indices,
  607. self.head_dim,
  608. ], (
  609. "global_attn_output tensor has the wrong size. Size should be"
  610. f" {(batch_size * self.num_heads, max_num_global_attn_indices, self.head_dim)}, but is"
  611. f" {global_attn_output.size()}."
  612. )
  613. global_attn_probs = global_attn_probs.view(batch_size, self.num_heads, max_num_global_attn_indices, seq_len)
  614. global_attn_output = global_attn_output.view(
  615. batch_size, self.num_heads, max_num_global_attn_indices, self.head_dim
  616. )
  617. return global_attn_output, global_attn_probs
  618. class LEDEncoderAttention(nn.Module):
  619. def __init__(self, config, layer_id):
  620. super().__init__()
  621. self.longformer_self_attn = LEDEncoderSelfAttention(config, layer_id=layer_id)
  622. self.output = nn.Linear(config.d_model, config.d_model)
  623. def forward(
  624. self,
  625. hidden_states: torch.Tensor,
  626. attention_mask: Optional[torch.Tensor] = None,
  627. layer_head_mask: Optional[torch.Tensor] = None,
  628. is_index_masked: Optional[torch.Tensor] = None,
  629. is_index_global_attn: Optional[torch.Tensor] = None,
  630. is_global_attn: Optional[bool] = None,
  631. output_attentions: bool = False,
  632. ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
  633. """Input shape: Batch x Time x Channel"""
  634. self_outputs = self.longformer_self_attn(
  635. hidden_states=hidden_states,
  636. attention_mask=attention_mask,
  637. layer_head_mask=layer_head_mask,
  638. is_index_masked=is_index_masked,
  639. is_index_global_attn=is_index_global_attn,
  640. is_global_attn=is_global_attn,
  641. output_attentions=output_attentions,
  642. )
  643. attn_output = self.output(self_outputs[0])
  644. outputs = (attn_output,) + self_outputs[1:]
  645. return outputs
  646. class LEDDecoderAttention(nn.Module):
  647. """Multi-headed attention from 'Attention Is All You Need' paper"""
  648. def __init__(
  649. self,
  650. embed_dim: int,
  651. num_heads: int,
  652. dropout: float = 0.0,
  653. is_decoder: bool = False,
  654. bias: bool = True,
  655. ):
  656. super().__init__()
  657. self.embed_dim = embed_dim
  658. self.num_heads = num_heads
  659. self.dropout = dropout
  660. self.head_dim = embed_dim // num_heads
  661. if self.head_dim * num_heads != self.embed_dim:
  662. raise ValueError(
  663. f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:"
  664. f" {num_heads})."
  665. )
  666. self.scaling = self.head_dim**-0.5
  667. self.is_decoder = is_decoder
  668. self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
  669. self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
  670. self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
  671. self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
  672. def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
  673. return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
  674. def forward(
  675. self,
  676. hidden_states: torch.Tensor,
  677. key_value_states: Optional[torch.Tensor] = None,
  678. past_key_value: Optional[Tuple[torch.Tensor]] = None,
  679. attention_mask: Optional[torch.Tensor] = None,
  680. layer_head_mask: Optional[torch.Tensor] = None,
  681. output_attentions: bool = False,
  682. ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
  683. """Input shape: Batch x Time x Channel"""
  684. # if key_value_states are provided this layer is used as a cross-attention layer
  685. # for the decoder
  686. is_cross_attention = key_value_states is not None
  687. bsz, tgt_len, embed_dim = hidden_states.size()
  688. # get query proj
  689. query_states = self.q_proj(hidden_states) * self.scaling
  690. # get key, value proj
  691. if is_cross_attention and past_key_value is not None:
  692. # reuse k,v, cross_attentions
  693. key_states = past_key_value[0]
  694. value_states = past_key_value[1]
  695. elif is_cross_attention:
  696. # cross_attentions
  697. key_states = self._shape(self.k_proj(key_value_states), -1, bsz)
  698. value_states = self._shape(self.v_proj(key_value_states), -1, bsz)
  699. elif past_key_value is not None:
  700. # reuse k, v, self_attention
  701. key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
  702. value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
  703. key_states = torch.cat([past_key_value[0], key_states], dim=2)
  704. value_states = torch.cat([past_key_value[1], value_states], dim=2)
  705. else:
  706. # self_attention
  707. key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
  708. value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
  709. if self.is_decoder:
  710. # if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states.
  711. # Further calls to cross_attention layer can then reuse all cross-attention
  712. # key/value_states (first "if" case)
  713. # if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of
  714. # all previous decoder key/value_states. Further calls to uni-directional self-attention
  715. # can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
  716. # if encoder bi-directional self-attention `past_key_value` is always `None`
  717. past_key_value = (key_states, value_states)
  718. proj_shape = (bsz * self.num_heads, -1, self.head_dim)
  719. query_states = self._shape(query_states, tgt_len, bsz).view(*proj_shape)
  720. key_states = key_states.view(*proj_shape)
  721. value_states = value_states.view(*proj_shape)
  722. src_len = key_states.size(1)
  723. attn_weights = torch.bmm(query_states, key_states.transpose(1, 2))
  724. if attn_weights.size() != (bsz * self.num_heads, tgt_len, src_len):
  725. raise ValueError(
  726. f"Attention weights should be of size {(bsz * self.num_heads, tgt_len, src_len)}, but is"
  727. f" {attn_weights.size()}"
  728. )
  729. if attention_mask is not None:
  730. if attention_mask.size() != (bsz, 1, tgt_len, src_len):
  731. raise ValueError(
  732. f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is {attention_mask.size()}"
  733. )
  734. attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + attention_mask
  735. attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
  736. attn_weights = nn.functional.softmax(attn_weights, dim=-1)
  737. if layer_head_mask is not None:
  738. if layer_head_mask.size() != (self.num_heads,):
  739. raise ValueError(
  740. f"Head mask for a single layer should be of size {(self.num_heads,)}, but is"
  741. f" {layer_head_mask.size()}"
  742. )
  743. attn_weights = layer_head_mask.view(1, -1, 1, 1) * attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
  744. attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
  745. if output_attentions:
  746. # this operation is a bit awkward, but it's required to
  747. # make sure that attn_weights keeps its gradient.
  748. # In order to do so, attn_weights have to be reshaped
  749. # twice and have to be reused in the following
  750. attn_weights_reshaped = attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
  751. attn_weights = attn_weights_reshaped.view(bsz * self.num_heads, tgt_len, src_len)
  752. else:
  753. attn_weights_reshaped = None
  754. attn_probs = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
  755. attn_output = torch.bmm(attn_probs, value_states)
  756. if attn_output.size() != (bsz * self.num_heads, tgt_len, self.head_dim):
  757. raise ValueError(
  758. f"`attn_output` should be of size {(bsz, self.num_heads, tgt_len, self.head_dim)}, but is"
  759. f" {attn_output.size()}"
  760. )
  761. attn_output = (
  762. attn_output.view(bsz, self.num_heads, tgt_len, self.head_dim)
  763. .transpose(1, 2)
  764. .reshape(bsz, tgt_len, embed_dim)
  765. )
  766. attn_output = self.out_proj(attn_output)
  767. return attn_output, attn_weights_reshaped, past_key_value
  768. class LEDEncoderLayer(nn.Module):
  769. def __init__(self, config: LEDConfig, layer_id: int):
  770. super().__init__()
  771. self.embed_dim = config.d_model
  772. self.self_attn = LEDEncoderAttention(config, layer_id)
  773. self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim)
  774. self.dropout = config.dropout
  775. self.activation_fn = ACT2FN[config.activation_function]
  776. self.activation_dropout = config.activation_dropout
  777. self.fc1 = nn.Linear(self.embed_dim, config.encoder_ffn_dim)
  778. self.fc2 = nn.Linear(config.encoder_ffn_dim, self.embed_dim)
  779. self.final_layer_norm = nn.LayerNorm(self.embed_dim)
  780. def forward(
  781. self,
  782. hidden_states: torch.Tensor,
  783. attention_mask: torch.Tensor,
  784. layer_head_mask: torch.Tensor,
  785. is_index_masked=None,
  786. is_index_global_attn=None,
  787. is_global_attn=None,
  788. output_attentions=False,
  789. ):
  790. """
  791. Args:
  792. hidden_states (`torch.FloatTensor`): input to the layer of shape *(batch, seq_len, embed_dim)*
  793. attention_mask (`torch.FloatTensor`): attention mask of size
  794. *(batch, 1, tgt_len, src_len)* where padding elements are indicated by very large negative values.
  795. layer_head_mask (`torch.FloatTensor`): mask for attention heads in a given layer of size
  796. *(encoder_attention_heads,)*.
  797. """
  798. residual = hidden_states
  799. attn_outputs = self.self_attn(
  800. hidden_states=hidden_states,
  801. attention_mask=attention_mask,
  802. layer_head_mask=layer_head_mask,
  803. is_index_masked=is_index_masked,
  804. is_index_global_attn=is_index_global_attn,
  805. is_global_attn=is_global_attn,
  806. output_attentions=output_attentions,
  807. )
  808. hidden_states = attn_outputs[0]
  809. hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
  810. hidden_states = residual + hidden_states
  811. hidden_states = self.self_attn_layer_norm(hidden_states)
  812. residual = hidden_states
  813. hidden_states = self.activation_fn(self.fc1(hidden_states))
  814. hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training)
  815. hidden_states = self.fc2(hidden_states)
  816. hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
  817. hidden_states = residual + hidden_states
  818. hidden_states = self.final_layer_norm(hidden_states)
  819. if hidden_states.dtype == torch.float16 and (
  820. torch.isinf(hidden_states).any() or torch.isnan(hidden_states).any()
  821. ):
  822. clamp_value = torch.finfo(hidden_states.dtype).max - 1000
  823. hidden_states = torch.clamp(hidden_states, min=-clamp_value, max=clamp_value)
  824. return (hidden_states,) + attn_outputs[1:]
  825. class LEDDecoderLayer(nn.Module):
  826. def __init__(self, config: LEDConfig):
  827. super().__init__()
  828. self.embed_dim = config.d_model
  829. self.self_attn = LEDDecoderAttention(
  830. embed_dim=self.embed_dim,
  831. num_heads=config.decoder_attention_heads,
  832. dropout=config.attention_dropout,
  833. is_decoder=True,
  834. )
  835. self.dropout = config.dropout
  836. self.activation_fn = ACT2FN[config.activation_function]
  837. self.activation_dropout = config.activation_dropout
  838. self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim)
  839. self.encoder_attn = LEDDecoderAttention(
  840. self.embed_dim,
  841. config.decoder_attention_heads,
  842. dropout=config.attention_dropout,
  843. is_decoder=True,
  844. )
  845. self.encoder_attn_layer_norm = nn.LayerNorm(self.embed_dim)
  846. self.fc1 = nn.Linear(self.embed_dim, config.decoder_ffn_dim)
  847. self.fc2 = nn.Linear(config.decoder_ffn_dim, self.embed_dim)
  848. self.final_layer_norm = nn.LayerNorm(self.embed_dim)
  849. def forward(
  850. self,
  851. hidden_states: torch.Tensor,
  852. attention_mask: Optional[torch.Tensor] = None,
  853. encoder_hidden_states: Optional[torch.Tensor] = None,
  854. encoder_attention_mask: Optional[torch.Tensor] = None,
  855. layer_head_mask: Optional[torch.Tensor] = None,
  856. cross_attn_layer_head_mask: Optional[torch.Tensor] = None,
  857. past_key_value: Optional[Tuple[torch.Tensor]] = None,
  858. output_attentions: Optional[bool] = False,
  859. use_cache: Optional[bool] = True,
  860. ):
  861. """
  862. Args:
  863. hidden_states (`torch.FloatTensor`): input to the layer of shape *(batch, seq_len, embed_dim)*
  864. attention_mask (`torch.FloatTensor`): attention mask of size
  865. *(batch, 1, tgt_len, src_len)* where padding elements are indicated by very large negative values.
  866. encoder_hidden_states (`torch.FloatTensor`):
  867. cross attention input to the layer of shape *(batch, seq_len, embed_dim)*
  868. encoder_attention_mask (`torch.FloatTensor`): encoder attention mask of size
  869. *(batch, 1, tgt_len, src_len)* where padding elements are indicated by very large negative values.
  870. layer_head_mask (`torch.FloatTensor`): mask for attention heads in a given layer of size
  871. *(decoder_attention_heads,)*.
  872. cross_attn_layer_head_mask (`torch.FloatTensor`): mask for encoder attention heads in a given layer of
  873. size *(decoder_attention_heads,)*.
  874. past_key_value (`Tuple(torch.FloatTensor)`): cached past key and value projection states
  875. output_attentions (`bool`): Whether the base model outputs attentions.
  876. This requires the attentions tensor to be reshaped in this function.
  877. """
  878. residual = hidden_states
  879. # Self-Attention
  880. # decoder uni-directional self-attention cached key/values tuple is at positions 1,2
  881. self_attn_past_key_value = past_key_value[:2] if past_key_value is not None else None
  882. # add present self-attn cache to positions 1,2 of present_key_value tuple
  883. hidden_states, self_attn_weights, present_key_value = self.self_attn(
  884. hidden_states=hidden_states,
  885. past_key_value=self_attn_past_key_value,
  886. attention_mask=attention_mask,
  887. layer_head_mask=layer_head_mask,
  888. output_attentions=output_attentions,
  889. )
  890. hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
  891. hidden_states = residual + hidden_states
  892. hidden_states = self.self_attn_layer_norm(hidden_states)
  893. # Cross-Attention Block
  894. cross_attn_present_key_value = None
  895. cross_attn_weights = None
  896. if encoder_hidden_states is not None:
  897. residual = hidden_states
  898. # cross_attn cached key/values tuple is at positions 3,4 of present_key_value tuple
  899. cross_attn_past_key_value = past_key_value[-2:] if past_key_value is not None else None
  900. hidden_states, cross_attn_weights, cross_attn_present_key_value = self.encoder_attn(
  901. hidden_states=hidden_states,
  902. key_value_states=encoder_hidden_states,
  903. attention_mask=encoder_attention_mask,
  904. layer_head_mask=cross_attn_layer_head_mask,
  905. past_key_value=cross_attn_past_key_value,
  906. output_attentions=output_attentions,
  907. )
  908. hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
  909. hidden_states = residual + hidden_states
  910. hidden_states = self.encoder_attn_layer_norm(hidden_states)
  911. # add cross-attn to positions 3,4 of present_key_value tuple
  912. present_key_value = present_key_value + cross_attn_present_key_value
  913. # Fully Connected
  914. residual = hidden_states
  915. hidden_states = self.activation_fn(self.fc1(hidden_states))
  916. hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training)
  917. hidden_states = self.fc2(hidden_states)
  918. hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
  919. hidden_states = residual + hidden_states
  920. hidden_states = self.final_layer_norm(hidden_states)
  921. outputs = (hidden_states,)
  922. if output_attentions:
  923. outputs += (self_attn_weights, cross_attn_weights)
  924. if use_cache:
  925. outputs += (present_key_value,)
  926. return outputs
  927. class LEDClassificationHead(nn.Module):
  928. """Head for sentence-level classification tasks."""
  929. def __init__(
  930. self,
  931. input_dim: int,
  932. inner_dim: int,
  933. num_classes: int,
  934. pooler_dropout: float,
  935. ):
  936. super().__init__()
  937. self.dense = nn.Linear(input_dim, inner_dim)
  938. self.dropout = nn.Dropout(p=pooler_dropout)
  939. self.out_proj = nn.Linear(inner_dim, num_classes)
  940. def forward(self, hidden_states: torch.Tensor):
  941. hidden_states = self.dropout(hidden_states)
  942. hidden_states = self.dense(hidden_states)
  943. hidden_states = torch.tanh(hidden_states)
  944. hidden_states = self.dropout(hidden_states)
  945. hidden_states = self.out_proj(hidden_states)
  946. return hidden_states
  947. class LEDPreTrainedModel(PreTrainedModel):
  948. config_class = LEDConfig
  949. base_model_prefix = "led"
  950. supports_gradient_checkpointing = True
  951. def _init_weights(self, module):
  952. std = self.config.init_std
  953. if isinstance(module, nn.Linear):
  954. module.weight.data.normal_(mean=0.0, std=std)
  955. if module.bias is not None:
  956. module.bias.data.zero_()
  957. elif isinstance(module, nn.Embedding):
  958. module.weight.data.normal_(mean=0.0, std=std)
  959. if module.padding_idx is not None:
  960. module.weight.data[module.padding_idx].zero_()
  961. @property
  962. def dummy_inputs(self):
  963. pad_token = self.config.pad_token_id
  964. input_ids = torch.tensor([[0, 6, 10, 4, 2], [0, 8, 12, 2, pad_token]], device=self.device)
  965. dummy_inputs = {
  966. "attention_mask": input_ids.ne(pad_token),
  967. "input_ids": input_ids,
  968. }
  969. return dummy_inputs
  970. @dataclass
  971. # Copied from transformers.models.longformer.modeling_longformer.LongformerBaseModelOutput with Longformer->LEDEncoder
  972. class LEDEncoderBaseModelOutput(ModelOutput):
  973. """
  974. Base class for LEDEncoder's outputs, with potential hidden states, local and global attentions.
  975. Args:
  976. last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
  977. Sequence of hidden-states at the output of the last layer of the model.
  978. hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
  979. Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
  980. shape `(batch_size, sequence_length, hidden_size)`.
  981. Hidden-states of the model at the output of each layer plus the initial embedding outputs.
  982. attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
  983. Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, x +
  984. attention_window + 1)`, where `x` is the number of tokens with global attention mask.
  985. Local attentions weights after the attention softmax, used to compute the weighted average in the
  986. self-attention heads. Those are the attention weights from every token in the sequence to every token with
  987. global attention (first `x` values) and to every token in the attention window (remaining `attention_window
  988. + 1` values). Note that the first `x` values refer to tokens with fixed positions in the text, but the
  989. remaining `attention_window + 1` values refer to tokens with relative positions: the attention weight of a
  990. token to itself is located at index `x + attention_window / 2` and the `attention_window / 2` preceding
  991. (succeeding) values are the attention weights to the `attention_window / 2` preceding (succeeding) tokens.
  992. If the attention window contains a token with global attention, the attention weight at the corresponding
  993. index is set to 0; the value should be accessed from the first `x` attention weights. If a token has global
  994. attention, the attention weights to all other tokens in `attentions` is set to 0, the values should be
  995. accessed from `global_attentions`.
  996. global_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
  997. Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, x)`,
  998. where `x` is the number of tokens with global attention mask.
  999. Global attentions weights after the attention softmax, used to compute the weighted average in the
  1000. self-attention heads. Those are the attention weights from every token with global attention to every token
  1001. in the sequence.
  1002. """
  1003. last_hidden_state: torch.FloatTensor
  1004. hidden_states: Optional[Tuple[torch.FloatTensor, ...]] = None
  1005. attentions: Optional[Tuple[torch.FloatTensor, ...]] = None
  1006. global_attentions: Optional[Tuple[torch.FloatTensor, ...]] = None
  1007. @dataclass
  1008. class LEDSeq2SeqModelOutput(ModelOutput):
  1009. """
  1010. Base class for model encoder's outputs that also contains : pre-computed hidden states that can speed up sequential
  1011. decoding.
  1012. Args:
  1013. last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
  1014. Sequence of hidden-states at the output of the last layer of the decoder of the model.
  1015. If `past_key_values` is used only the last hidden-state of the sequences of shape `(batch_size, 1,
  1016. hidden_size)` is output.
  1017. past_key_values (`List[torch.FloatTensor]`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
  1018. List of `torch.FloatTensor` of length `config.n_layers`, with each tensor of shape `(2, batch_size,
  1019. num_heads, sequence_length, embed_size_per_head)`).
  1020. Contains pre-computed hidden-states (key and values in the attention blocks) of the decoder that can be
  1021. used (see `past_key_values` input) to speed up sequential decoding.
  1022. decoder_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
  1023. Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
  1024. shape `(batch_size, sequence_length, hidden_size)`.
  1025. Hidden-states of the decoder at the output of each layer plus the initial embedding outputs.
  1026. decoder_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
  1027. Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
  1028. sequence_length)`.
  1029. Attentions weights of the decoder, after the attention softmax, used to compute the weighted average in the
  1030. self-attention heads.
  1031. cross_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
  1032. Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
  1033. sequence_length)`.
  1034. Attentions weights of the decoder's cross-attention layer, after the attention softmax, used to compute the
  1035. weighted average in the cross-attention heads.
  1036. encoder_last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
  1037. Sequence of hidden-states at the output of the last layer of the encoder of the model.
  1038. encoder_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
  1039. Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
  1040. shape `(batch_size, sequence_length, hidden_size)`.
  1041. Hidden-states of the encoder at the output of each layer plus the initial embedding outputs.
  1042. encoder_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
  1043. Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
  1044. sequence_length)`.
  1045. Attentions weights of the encoder, after the attention softmax, used to compute the weighted average in the
  1046. self-attention heads.
  1047. encoder_global_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
  1048. Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, x)`,
  1049. where `x` is the number of tokens with global attention mask.
  1050. Global attentions weights after the attention softmax, used to compute the weighted average in the
  1051. self-attention heads. Those are the attention weights from every token with global attention to every token
  1052. in the sequence.
  1053. """
  1054. last_hidden_state: torch.FloatTensor = None
  1055. past_key_values: Optional[List[torch.FloatTensor]] = None
  1056. decoder_hidden_states: Optional[Tuple[torch.FloatTensor, ...]] = None
  1057. decoder_attentions: Optional[Tuple[torch.FloatTensor, ...]] = None
  1058. cross_attentions: Optional[Tuple[torch.FloatTensor, ...]] = None
  1059. encoder_last_hidden_state: Optional[torch.FloatTensor] = None
  1060. encoder_hidden_states: Optional[Tuple[torch.FloatTensor, ...]] = None
  1061. encoder_attentions: Optional[Tuple[torch.FloatTensor, ...]] = None
  1062. encoder_global_attentions: Optional[Tuple[torch.FloatTensor, ...]] = None
  1063. @dataclass
  1064. class LEDSeq2SeqLMOutput(ModelOutput):
  1065. """
  1066. Base class for sequence-to-sequence language models outputs.
  1067. Args:
  1068. loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
  1069. Language modeling loss.
  1070. logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
  1071. Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
  1072. past_key_values (`List[torch.FloatTensor]`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
  1073. List of `torch.FloatTensor` of length `config.n_layers`, with each tensor of shape `(2, batch_size,
  1074. num_heads, sequence_length, embed_size_per_head)`).
  1075. Contains pre-computed hidden-states (key and values in the attention blocks) of the decoder that can be
  1076. used (see `past_key_values` input) to speed up sequential decoding.
  1077. decoder_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
  1078. Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
  1079. shape `(batch_size, sequence_length, hidden_size)`.
  1080. Hidden-states of the decoder at the output of each layer plus the initial embedding outputs.
  1081. decoder_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
  1082. Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
  1083. sequence_length)`.
  1084. Attentions weights of the decoder, after the attention softmax, used to compute the weighted average in the
  1085. self-attention heads.
  1086. cross_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
  1087. Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
  1088. sequence_length)`.
  1089. Attentions weights of the decoder's cross-attention layer, after the attention softmax, used to compute the
  1090. weighted average in the cross-attention heads.
  1091. encoder_last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
  1092. Sequence of hidden-states at the output of the last layer of the encoder of the model.
  1093. encoder_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
  1094. Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
  1095. shape `(batch_size, sequence_length, hidden_size)`.
  1096. Hidden-states of the encoder at the output of each layer plus the initial embedding outputs.
  1097. encoder_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
  1098. Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
  1099. sequence_length)`.
  1100. Attentions weights of the encoder, after the attention softmax, used to compute the weighted average in the
  1101. self-attention heads.
  1102. encoder_global_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
  1103. Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, x)`,
  1104. where `x` is the number of tokens with global attention mask.
  1105. Global attentions weights after the attention softmax, used to compute the weighted average in the
  1106. self-attention heads. Those are the attention weights from every token with global attention to every token
  1107. in the sequence.
  1108. """
  1109. loss: Optional[torch.FloatTensor] = None
  1110. logits: torch.FloatTensor = None
  1111. past_key_values: Optional[List[torch.FloatTensor]] = None
  1112. decoder_hidden_states: Optional[Tuple[torch.FloatTensor, ...]] = None
  1113. decoder_attentions: Optional[Tuple[torch.FloatTensor, ...]] = None
  1114. cross_attentions: Optional[Tuple[torch.FloatTensor, ...]] = None
  1115. encoder_last_hidden_state: Optional[torch.FloatTensor] = None
  1116. encoder_hidden_states: Optional[Tuple[torch.FloatTensor, ...]] = None
  1117. encoder_attentions: Optional[Tuple[torch.FloatTensor, ...]] = None
  1118. encoder_global_attentions: Optional[Tuple[torch.FloatTensor, ...]] = None
  1119. @dataclass
  1120. class LEDSeq2SeqSequenceClassifierOutput(ModelOutput):
  1121. """
  1122. Base class for outputs of sequence-to-sequence sentence classification models.
  1123. Args:
  1124. loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `label` is provided):
  1125. Classification (or regression if config.num_labels==1) loss.
  1126. logits (`torch.FloatTensor` of shape `(batch_size, config.num_labels)`):
  1127. Classification (or regression if config.num_labels==1) scores (before SoftMax).
  1128. past_key_values (`List[torch.FloatTensor]`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
  1129. List of `torch.FloatTensor` of length `config.n_layers`, with each tensor of shape `(2, batch_size,
  1130. num_heads, sequence_length, embed_size_per_head)`).
  1131. Contains pre-computed hidden-states (key and values in the attention blocks) of the decoder that can be
  1132. used (see `past_key_values` input) to speed up sequential decoding.
  1133. decoder_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
  1134. Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
  1135. shape `(batch_size, sequence_length, hidden_size)`.
  1136. Hidden-states of the decoder at the output of each layer plus the initial embedding outputs.
  1137. decoder_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
  1138. Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
  1139. sequence_length)`.
  1140. Attentions weights of the decoder, after the attention softmax, used to compute the weighted average in the
  1141. self-attention heads.
  1142. cross_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
  1143. Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
  1144. sequence_length)`.
  1145. Attentions weights of the decoder's cross-attention layer, after the attention softmax, used to compute the
  1146. weighted average in the cross-attention heads.
  1147. encoder_last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
  1148. Sequence of hidden-states at the output of the last layer of the encoder of the model.
  1149. encoder_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
  1150. Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
  1151. shape `(batch_size, sequence_length, hidden_size)`.
  1152. Hidden-states of the encoder at the output of each layer plus the initial embedding outputs.
  1153. encoder_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
  1154. Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
  1155. sequence_length)`.
  1156. Attentions weights of the encoder, after the attention softmax, used to compute the weighted average in the
  1157. self-attention heads.
  1158. encoder_global_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
  1159. Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, x)`,
  1160. where `x` is the number of tokens with global attention mask.
  1161. Global attentions weights after the attention softmax, used to compute the weighted average in the
  1162. self-attention heads. Those are the attention weights from every token with global attention to every token
  1163. in the sequence.
  1164. """
  1165. loss: Optional[torch.FloatTensor] = None
  1166. logits: torch.FloatTensor = None
  1167. past_key_values: Optional[List[torch.FloatTensor]] = None
  1168. decoder_hidden_states: Optional[Tuple[torch.FloatTensor, ...]] = None
  1169. decoder_attentions: Optional[Tuple[torch.FloatTensor, ...]] = None
  1170. cross_attentions: Optional[Tuple[torch.FloatTensor, ...]] = None
  1171. encoder_last_hidden_state: Optional[torch.FloatTensor] = None
  1172. encoder_hidden_states: Optional[Tuple[torch.FloatTensor, ...]] = None
  1173. encoder_attentions: Optional[Tuple[torch.FloatTensor, ...]] = None
  1174. encoder_global_attentions: Optional[Tuple[torch.FloatTensor, ...]] = None
  1175. @dataclass
  1176. class LEDSeq2SeqQuestionAnsweringModelOutput(ModelOutput):
  1177. """
  1178. Base class for outputs of sequence-to-sequence question answering models.
  1179. Args:
  1180. loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
  1181. Total span extraction loss is the sum of a Cross-Entropy for the start and end positions.
  1182. start_logits (`torch.FloatTensor` of shape `(batch_size, sequence_length)`):
  1183. Span-start scores (before SoftMax).
  1184. end_logits (`torch.FloatTensor` of shape `(batch_size, sequence_length)`):
  1185. Span-end scores (before SoftMax).
  1186. past_key_values (`List[torch.FloatTensor]`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
  1187. List of `torch.FloatTensor` of length `config.n_layers`, with each tensor of shape `(2, batch_size,
  1188. num_heads, sequence_length, embed_size_per_head)`).
  1189. Contains pre-computed hidden-states (key and values in the attention blocks) of the decoder that can be
  1190. used (see `past_key_values` input) to speed up sequential decoding.
  1191. decoder_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
  1192. Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
  1193. shape `(batch_size, sequence_length, hidden_size)`.
  1194. Hidden-states of the decoder at the output of each layer plus the initial embedding outputs.
  1195. decoder_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
  1196. Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
  1197. sequence_length)`.
  1198. Attentions weights of the decoder, after the attention softmax, used to compute the weighted average in the
  1199. self-attention heads.
  1200. cross_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
  1201. Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
  1202. sequence_length)`.
  1203. Attentions weights of the decoder's cross-attention layer, after the attention softmax, used to compute the
  1204. weighted average in the cross-attention heads.
  1205. encoder_last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
  1206. Sequence of hidden-states at the output of the last layer of the encoder of the model.
  1207. encoder_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
  1208. Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
  1209. shape `(batch_size, sequence_length, hidden_size)`.
  1210. Hidden-states of the encoder at the output of each layer plus the initial embedding outputs.
  1211. encoder_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
  1212. Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
  1213. sequence_length)`.
  1214. Attentions weights of the encoder, after the attention softmax, used to compute the weighted average in the
  1215. self-attention heads.
  1216. encoder_global_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
  1217. Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, x)`,
  1218. where `x` is the number of tokens with global attention mask.
  1219. Global attentions weights after the attention softmax, used to compute the weighted average in the
  1220. self-attention heads. Those are the attention weights from every token with global attention to every token
  1221. in the sequence.
  1222. """
  1223. loss: Optional[torch.FloatTensor] = None
  1224. start_logits: torch.FloatTensor = None
  1225. end_logits: torch.FloatTensor = None
  1226. past_key_values: Optional[List[torch.FloatTensor]] = None
  1227. decoder_hidden_states: Optional[Tuple[torch.FloatTensor, ...]] = None
  1228. decoder_attentions: Optional[Tuple[torch.FloatTensor, ...]] = None
  1229. cross_attentions: Optional[Tuple[torch.FloatTensor, ...]] = None
  1230. encoder_last_hidden_state: Optional[torch.FloatTensor] = None
  1231. encoder_hidden_states: Optional[Tuple[torch.FloatTensor, ...]] = None
  1232. encoder_attentions: Optional[Tuple[torch.FloatTensor, ...]] = None
  1233. encoder_global_attentions: Optional[Tuple[torch.FloatTensor, ...]] = None
  1234. LED_START_DOCSTRING = r"""
  1235. This model inherits from [`PreTrainedModel`]. See the superclass documentation for the generic methods the library
  1236. implements for all its models (such as downloading or saving, resizing the input embeddings, pruning heads etc.)
  1237. This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
  1238. Use it as a regular PyTorch Module and refer to the PyTorch documentation for general usage and behavior.
  1239. Parameters:
  1240. config ([`LEDConfig`]):
  1241. Model configuration class with all the parameters of the model. Initializing with a config file does not
  1242. load the weights associated with the model, only the configuration. Check out the
  1243. [`~PreTrainedModel.from_pretrained`] method to load the model weights.
  1244. """
  1245. LED_GENERATION_EXAMPLE = r"""
  1246. Summarization example:
  1247. ```python
  1248. >>> import torch
  1249. >>> from transformers import AutoTokenizer, LEDForConditionalGeneration
  1250. >>> model = LEDForConditionalGeneration.from_pretrained("allenai/led-large-16384-arxiv")
  1251. >>> tokenizer = AutoTokenizer.from_pretrained("allenai/led-large-16384-arxiv")
  1252. >>> ARTICLE_TO_SUMMARIZE = '''Transformers (Vaswani et al., 2017) have achieved state-of-the-art
  1253. ... results in a wide range of natural language tasks including generative language modeling
  1254. ... (Dai et al., 2019; Radford et al., 2019) and discriminative ... language understanding (Devlin et al., 2019).
  1255. ... This success is partly due to the self-attention component which enables the network to capture contextual
  1256. ... information from the entire sequence. While powerful, the memory and computational requirements of
  1257. ... self-attention grow quadratically with sequence length, making it infeasible (or very expensive) to
  1258. ... process long sequences. To address this limitation, we present Longformer, a modified Transformer
  1259. ... architecture with a self-attention operation that scales linearly with the sequence length, making it
  1260. ... versatile for processing long documents (Fig 1). This is an advantage for natural language tasks such as
  1261. ... long document classification, question answering (QA), and coreference resolution, where existing approaches
  1262. ... partition or shorten the long context into smaller sequences that fall within the typical 512 token limit
  1263. ... of BERT-style pretrained models. Such partitioning could potentially result in loss of important
  1264. ... cross-partition information, and to mitigate this problem, existing methods often rely on complex
  1265. ... architectures to address such interactions. On the other hand, our proposed Longformer is able to build
  1266. ... contextual representations of the entire context using multiple layers of attention, reducing the need for
  1267. ... task-specific architectures.'''
  1268. >>> inputs = tokenizer.encode(ARTICLE_TO_SUMMARIZE, return_tensors="pt")
  1269. >>> # Global attention on the first token (cf. Beltagy et al. 2020)
  1270. >>> global_attention_mask = torch.zeros_like(inputs)
  1271. >>> global_attention_mask[:, 0] = 1
  1272. >>> # Generate Summary
  1273. >>> summary_ids = model.generate(inputs, global_attention_mask=global_attention_mask, num_beams=3, max_length=32)
  1274. >>> print(tokenizer.decode(summary_ids[0], skip_special_tokens=True, clean_up_tokenization_spaces=True))
  1275. ```
  1276. """
  1277. LED_INPUTS_DOCSTRING = r"""
  1278. Args:
  1279. input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
  1280. Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
  1281. it.
  1282. Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
  1283. [`PreTrainedTokenizer.__call__`] for details.
  1284. [What are input IDs?](../glossary#input-ids)
  1285. attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
  1286. Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
  1287. - 1 for tokens that are **not masked**,
  1288. - 0 for tokens that are **masked**.
  1289. [What are attention masks?](../glossary#attention-mask)
  1290. decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
  1291. Indices of decoder input sequence tokens in the vocabulary.
  1292. Indices can be obtained using [`LedTokenizer`]. See [`PreTrainedTokenizer.encode`] and
  1293. [`PreTrainedTokenizer.__call__`] for details.
  1294. [What are input IDs?](../glossary#input-ids)
  1295. LED uses the `eos_token_id` as the starting token for `decoder_input_ids` generation. If `past_key_values`
  1296. is used, optionally only the last `decoder_input_ids` have to be input (see `past_key_values`).
  1297. decoder_attention_mask (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
  1298. Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
  1299. be used by default.
  1300. If you want to change padding behavior, you should read [`modeling_led._prepare_decoder_inputs`] and modify
  1301. to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more information on the
  1302. default strategy.
  1303. global_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
  1304. Mask to decide the attention given on each token, local attention or global attention for the encoder.
  1305. Tokens with global attention attends to all other tokens, and all other tokens attend to them. This is
  1306. important for task-specific finetuning because it makes the model more flexible at representing the task.
  1307. For example, for classification, the <s> token should be given global attention. For QA, all question
  1308. tokens should also have global attention. Please refer to the [Longformer
  1309. paper](https://arxiv.org/abs/2004.05150) for more details. Mask values selected in `[0, 1]`:
  1310. - 0 for local attention (a sliding window attention),
  1311. - 1 for global attention (tokens that attend to all other tokens, and all other tokens attend to them).
  1312. head_mask (`torch.Tensor` of shape `(encoder_layers, encoder_attention_heads)`, *optional*):
  1313. Mask to nullify selected heads of the attention modules in the encoder. Mask values selected in `[0, 1]`:
  1314. - 1 indicates the head is **not masked**,
  1315. - 0 indicates the head is **masked**.
  1316. decoder_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
  1317. Mask to nullify selected heads of the attention modules in the decoder. Mask values selected in `[0, 1]`:
  1318. - 1 indicates the head is **not masked**,
  1319. - 0 indicates the head is **masked**.
  1320. cross_attn_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
  1321. Mask to nullify selected heads of the cross-attention modules in the decoder. Mask values selected in `[0,
  1322. 1]`:
  1323. - 1 indicates the head is **not masked**,
  1324. - 0 indicates the head is **masked**.
  1325. encoder_outputs (`tuple(tuple(torch.FloatTensor)`, *optional*):
  1326. Tuple consists of (`last_hidden_state`, *optional*: `hidden_states`, *optional*: `attentions`)
  1327. `last_hidden_state` of shape `(batch_size, sequence_length, hidden_size)`, *optional*) is a sequence of
  1328. hidden-states at the output of the last layer of the encoder. Used in the cross-attention of the decoder.
  1329. past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
  1330. Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
  1331. `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape
  1332. `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.
  1333. Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
  1334. blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
  1335. If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
  1336. don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
  1337. `decoder_input_ids` of shape `(batch_size, sequence_length)`.
  1338. inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
  1339. Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
  1340. is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
  1341. model's internal embedding lookup matrix.
  1342. decoder_inputs_embeds (`torch.FloatTensor` of shape `(batch_size, target_sequence_length, hidden_size)`, *optional*):
  1343. Optionally, instead of passing `decoder_input_ids` you can choose to directly pass an embedded
  1344. representation. If `past_key_values` is used, optionally only the last `decoder_inputs_embeds` have to be
  1345. input (see `past_key_values`). This is useful if you want more control over how to convert
  1346. `decoder_input_ids` indices into associated vectors than the model's internal embedding lookup matrix.
  1347. If `decoder_input_ids` and `decoder_inputs_embeds` are both unset, `decoder_inputs_embeds` takes the value
  1348. of `inputs_embeds`.
  1349. use_cache (`bool`, *optional*):
  1350. If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
  1351. `past_key_values`).
  1352. output_attentions (`bool`, *optional*):
  1353. Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
  1354. tensors for more detail.
  1355. output_hidden_states (`bool`, *optional*):
  1356. Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
  1357. more detail.
  1358. return_dict (`bool`, *optional*):
  1359. Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
  1360. """
  1361. class LEDEncoder(LEDPreTrainedModel):
  1362. """
  1363. Transformer encoder consisting of *config.encoder_layers* self-attention layers. Each layer is a
  1364. [`LEDEncoderLayer`].
  1365. Args:
  1366. config: LEDConfig
  1367. embed_tokens (nn.Embedding): output embedding
  1368. """
  1369. def __init__(self, config: LEDConfig, embed_tokens: Optional[nn.Embedding] = None):
  1370. super().__init__(config)
  1371. self.dropout = config.dropout
  1372. self.layerdrop = config.encoder_layerdrop
  1373. embed_dim = config.d_model
  1374. self.padding_idx = config.pad_token_id
  1375. self.max_source_positions = config.max_encoder_position_embeddings
  1376. if isinstance(config.attention_window, int):
  1377. if config.attention_window % 2 != 0:
  1378. raise ValueError("`config.attention_window` has to be an even value")
  1379. if config.attention_window <= 0:
  1380. raise ValueError("`config.attention_window` has to be positive")
  1381. config.attention_window = [config.attention_window] * config.num_hidden_layers # one value per layer
  1382. else:
  1383. if len(config.attention_window) != config.num_hidden_layers:
  1384. raise ValueError(
  1385. "`len(config.attention_window)` should equal `config.num_hidden_layers`. "
  1386. f"Expected {config.num_hidden_layers}, given {len(config.attention_window)}"
  1387. )
  1388. if embed_tokens is not None:
  1389. self.embed_tokens = embed_tokens
  1390. else:
  1391. self.embed_tokens = nn.Embedding(config.vocab_size, embed_dim, self.padding_idx)
  1392. self.embed_positions = LEDLearnedPositionalEmbedding(
  1393. self.max_source_positions,
  1394. embed_dim,
  1395. )
  1396. self.layers = nn.ModuleList([LEDEncoderLayer(config, i) for i in range(config.encoder_layers)])
  1397. self.layernorm_embedding = nn.LayerNorm(embed_dim)
  1398. self.gradient_checkpointing = False
  1399. # Initialize weights and apply final processing
  1400. self.post_init()
  1401. def _merge_to_attention_mask(self, attention_mask: torch.Tensor, global_attention_mask: torch.Tensor):
  1402. # longformer self-attention expects attention mask to have 0 (no attn), 1 (local attn), 2 (global attn)
  1403. # (global_attention_mask + 1) => 1 for local attention, 2 for global attention
  1404. # => final attention_mask => 0 for no attention, 1 for local attention 2 for global attention
  1405. if attention_mask is not None:
  1406. attention_mask = attention_mask * (global_attention_mask + 1)
  1407. else:
  1408. # simply use `global_attention_mask` as `attention_mask`
  1409. # if no `attention_mask` is given
  1410. attention_mask = global_attention_mask + 1
  1411. return attention_mask
  1412. def _pad_to_window_size(
  1413. self,
  1414. input_ids: torch.Tensor,
  1415. attention_mask: torch.Tensor,
  1416. inputs_embeds: torch.Tensor,
  1417. pad_token_id: int,
  1418. ):
  1419. """A helper function to pad tokens and mask to work with implementation of Longformer self-attention."""
  1420. # padding
  1421. attention_window = (
  1422. self.config.attention_window
  1423. if isinstance(self.config.attention_window, int)
  1424. else max(self.config.attention_window)
  1425. )
  1426. if attention_window % 2 != 0:
  1427. raise ValueError(f"`attention_window` should be an even value. Given {attention_window}")
  1428. input_shape = input_ids.shape if input_ids is not None else inputs_embeds.shape
  1429. batch_size, seq_len = input_shape[:2]
  1430. padding_len = (attention_window - seq_len % attention_window) % attention_window
  1431. if padding_len > 0:
  1432. logger.warning_once(
  1433. f"Input ids are automatically padded from {seq_len} to {seq_len + padding_len} to be a multiple of "
  1434. f"`config.attention_window`: {attention_window}"
  1435. )
  1436. if input_ids is not None:
  1437. input_ids = nn.functional.pad(input_ids, (0, padding_len), value=pad_token_id)
  1438. if inputs_embeds is not None:
  1439. input_ids_padding = inputs_embeds.new_full(
  1440. (batch_size, padding_len),
  1441. self.config.pad_token_id,
  1442. dtype=torch.long,
  1443. )
  1444. inputs_embeds_padding = self.embed_tokens(input_ids_padding)
  1445. inputs_embeds = torch.cat([inputs_embeds, inputs_embeds_padding], dim=-2)
  1446. attention_mask = nn.functional.pad(
  1447. attention_mask, (0, padding_len), value=False
  1448. ) # no attention on the padding tokens
  1449. return padding_len, input_ids, attention_mask, inputs_embeds
  1450. def forward(
  1451. self,
  1452. input_ids=None,
  1453. attention_mask=None,
  1454. global_attention_mask=None,
  1455. head_mask=None,
  1456. inputs_embeds=None,
  1457. output_attentions=None,
  1458. output_hidden_states=None,
  1459. return_dict=None,
  1460. ):
  1461. r"""
  1462. Args:
  1463. input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
  1464. Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
  1465. provide it.
  1466. Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
  1467. [`PreTrainedTokenizer.__call__`] for details.
  1468. [What are input IDs?](../glossary#input-ids)
  1469. attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
  1470. Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
  1471. - 1 for tokens that are **not masked**,
  1472. - 0 for tokens that are **masked**.
  1473. [What are attention masks?](../glossary#attention-mask)
  1474. global_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
  1475. Mask to decide the attention given on each token, local attention or global attention for the encoder.
  1476. Tokens with global attention attends to all other tokens, and all other tokens attend to them. This is
  1477. important for task-specific finetuning because it makes the model more flexible at representing the
  1478. task. For example, for classification, the <s> token should be given global attention. For QA, all
  1479. question tokens should also have global attention. Please refer to the [Longformer
  1480. paper](https://arxiv.org/abs/2004.05150) for more details. Mask values selected in `[0, 1]`:
  1481. - 0 for local attention (a sliding window attention),
  1482. - 1 for global attention (tokens that attend to all other tokens, and all other tokens attend to them).
  1483. head_mask (`torch.Tensor` of shape `(encoder_layers, encoder_attention_heads)`, *optional*):
  1484. Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:
  1485. - 1 indicates the head is **not masked**,
  1486. - 0 indicates the head is **masked**.
  1487. inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
  1488. Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
  1489. This is useful if you want more control over how to convert `input_ids` indices into associated vectors
  1490. than the model's internal embedding lookup matrix.
  1491. output_attentions (`bool`, *optional*):
  1492. Whether or not to return the attentions tensors of all attention layers. See `attentions` under
  1493. returned tensors for more detail.
  1494. output_hidden_states (`bool`, *optional*):
  1495. Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
  1496. for more detail.
  1497. return_dict (`bool`, *optional*):
  1498. Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
  1499. """
  1500. output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
  1501. output_hidden_states = (
  1502. output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
  1503. )
  1504. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  1505. # check input_ids and inputs_embeds
  1506. if input_ids is not None and inputs_embeds is not None:
  1507. raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
  1508. elif input_ids is None and inputs_embeds is None:
  1509. raise ValueError("You have to specify either input_ids or inputs_embeds")
  1510. if inputs_embeds is None:
  1511. inputs_embeds = self.embed_tokens(input_ids)
  1512. # create default attention_mask
  1513. if attention_mask is None:
  1514. attention_mask = torch.ones(inputs_embeds.size()[:-1], device=inputs_embeds.device, dtype=torch.long)
  1515. # merge `global_attention_mask` and `attention_mask`
  1516. if global_attention_mask is not None:
  1517. attention_mask = self._merge_to_attention_mask(attention_mask, global_attention_mask)
  1518. # pad input if necessary
  1519. padding_len, input_ids, attention_mask, inputs_embeds = self._pad_to_window_size(
  1520. input_ids=input_ids,
  1521. attention_mask=attention_mask,
  1522. inputs_embeds=inputs_embeds,
  1523. pad_token_id=self.config.pad_token_id,
  1524. )
  1525. # retrieve input_shape
  1526. if input_ids is not None:
  1527. input_shape = input_ids.size()
  1528. input_ids = input_ids.view(-1, input_shape[-1])
  1529. elif inputs_embeds is not None:
  1530. input_shape = inputs_embeds.size()[:-1]
  1531. # convert attention_mask to float
  1532. if attention_mask is not None:
  1533. # [bsz, seq_len] -> [bsz, seq_len]; 1 -> 0.0; 0 -> "-inf"
  1534. attention_mask = _prepare_4d_attention_mask_inverted(attention_mask, inputs_embeds.dtype)[:, 0, 0, :]
  1535. # get masking tensors
  1536. is_index_masked = attention_mask < 0
  1537. is_index_global_attn = attention_mask > 0
  1538. is_global_attn = is_index_global_attn.flatten().any().item()
  1539. embed_pos = self.embed_positions(input_shape)
  1540. hidden_states = inputs_embeds + embed_pos
  1541. hidden_states = self.layernorm_embedding(hidden_states)
  1542. hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
  1543. encoder_states = () if output_hidden_states else None
  1544. all_attentions = () if output_attentions else None
  1545. all_global_attentions = () if (output_attentions and is_global_attn) else None
  1546. # check if head_mask has a correct number of layers specified if desired
  1547. if head_mask is not None:
  1548. if head_mask.size()[0] != len(self.layers):
  1549. raise ValueError(
  1550. f"The head_mask should be specified for {len(self.layers)} layers, but it is for"
  1551. f" {head_mask.size()[0]}."
  1552. )
  1553. for idx, encoder_layer in enumerate(self.layers):
  1554. if output_hidden_states:
  1555. encoder_states = encoder_states + (hidden_states,)
  1556. # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
  1557. dropout_probability = torch.rand([])
  1558. if self.training and (dropout_probability < self.layerdrop): # skip the layer
  1559. layer_outputs = (None, None, None)
  1560. else:
  1561. if self.gradient_checkpointing and self.training:
  1562. layer_outputs = self._gradient_checkpointing_func(
  1563. encoder_layer.__call__,
  1564. hidden_states,
  1565. attention_mask,
  1566. head_mask[idx] if head_mask is not None else None,
  1567. is_index_masked,
  1568. is_index_global_attn,
  1569. is_global_attn,
  1570. output_attentions,
  1571. )
  1572. else:
  1573. layer_outputs = encoder_layer(
  1574. hidden_states,
  1575. attention_mask=attention_mask,
  1576. layer_head_mask=(head_mask[idx] if head_mask is not None else None),
  1577. is_index_masked=is_index_masked,
  1578. is_index_global_attn=is_index_global_attn,
  1579. is_global_attn=is_global_attn,
  1580. output_attentions=output_attentions,
  1581. )
  1582. hidden_states = layer_outputs[0]
  1583. if output_attentions:
  1584. # bzs x seq_len x num_attn_heads x (num_global_attn + attention_window_len + 1) => bzs x num_attn_heads x seq_len x (num_global_attn + attention_window_len + 1)
  1585. all_attentions = all_attentions + (layer_outputs[1].transpose(1, 2),)
  1586. if is_global_attn:
  1587. # bzs x num_attn_heads x num_global_attn x seq_len => bzs x num_attn_heads x seq_len x num_global_attn
  1588. all_global_attentions = all_global_attentions + (layer_outputs[2].transpose(2, 3),)
  1589. if output_hidden_states:
  1590. encoder_states = encoder_states + (hidden_states,)
  1591. # undo padding
  1592. if padding_len > 0:
  1593. # unpad `hidden_states` because the calling function is expecting a length == input_ids.size(1)
  1594. hidden_states = hidden_states[:, :-padding_len]
  1595. if output_hidden_states:
  1596. encoder_states = tuple([state[:, :-padding_len] for state in encoder_states])
  1597. if output_attentions:
  1598. all_attentions = tuple([state[:, :, :-padding_len, :] for state in all_attentions])
  1599. if not return_dict:
  1600. return tuple(
  1601. v for v in [hidden_states, encoder_states, all_attentions, all_global_attentions] if v is not None
  1602. )
  1603. return LEDEncoderBaseModelOutput(
  1604. last_hidden_state=hidden_states,
  1605. hidden_states=encoder_states,
  1606. attentions=all_attentions,
  1607. global_attentions=all_global_attentions,
  1608. )
  1609. class LEDDecoder(LEDPreTrainedModel):
  1610. """
  1611. Transformer decoder consisting of *config.decoder_layers* layers. Each layer is a [`LEDDecoderLayer`]
  1612. Args:
  1613. config: LEDConfig
  1614. embed_tokens (nn.Embedding): output embedding
  1615. """
  1616. def __init__(self, config: LEDConfig, embed_tokens: Optional[nn.Embedding] = None):
  1617. super().__init__(config)
  1618. self.dropout = config.dropout
  1619. self.layerdrop = config.decoder_layerdrop
  1620. self.padding_idx = config.pad_token_id
  1621. self.max_target_positions = config.max_decoder_position_embeddings
  1622. if embed_tokens is not None:
  1623. self.embed_tokens = embed_tokens
  1624. else:
  1625. self.embed_tokens = nn.Embedding(config.vocab_size, config.d_model, self.padding_idx)
  1626. self.embed_positions = LEDLearnedPositionalEmbedding(
  1627. self.max_target_positions,
  1628. config.d_model,
  1629. )
  1630. self.layers = nn.ModuleList([LEDDecoderLayer(config) for _ in range(config.decoder_layers)])
  1631. self.layernorm_embedding = nn.LayerNorm(config.d_model)
  1632. self.gradient_checkpointing = False
  1633. # Initialize weights and apply final processing
  1634. self.post_init()
  1635. def forward(
  1636. self,
  1637. input_ids=None,
  1638. attention_mask=None,
  1639. global_attention_mask=None,
  1640. encoder_hidden_states=None,
  1641. encoder_attention_mask=None,
  1642. head_mask=None,
  1643. cross_attn_head_mask=None,
  1644. past_key_values=None,
  1645. inputs_embeds=None,
  1646. use_cache=None,
  1647. output_attentions=None,
  1648. output_hidden_states=None,
  1649. return_dict=None,
  1650. ):
  1651. r"""
  1652. Args:
  1653. input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
  1654. Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
  1655. provide it.
  1656. Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
  1657. [`PreTrainedTokenizer.__call__`] for details.
  1658. [What are input IDs?](../glossary#input-ids)
  1659. attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
  1660. Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
  1661. - 1 for tokens that are **not masked**,
  1662. - 0 for tokens that are **masked**.
  1663. [What are attention masks?](../glossary#attention-mask)
  1664. global_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
  1665. Mask to decide the attention given on each token, local attention or global attention. Tokens with
  1666. global attention attends to all other tokens, and all other tokens attend to them. This is important
  1667. for task-specific finetuning because it makes the model more flexible at representing the task. For
  1668. example, for classification, the <s> token should be given global attention. For QA, all question
  1669. tokens should also have global attention. Please refer to the [Longformer
  1670. paper](https://arxiv.org/abs/2004.05150) for more details. Mask values selected in `[0, 1]`:
  1671. - 0 for local attention (a sliding window attention),
  1672. - 1 for global attention (tokens that attend to all other tokens, and all other tokens attend to them).
  1673. encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, encoder_sequence_length, hidden_size)`, *optional*):
  1674. Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
  1675. of the decoder.
  1676. encoder_attention_mask (`torch.LongTensor` of shape `(batch_size, encoder_sequence_length)`, *optional*):
  1677. Mask to avoid performing cross-attention on padding tokens indices of encoder input_ids. Mask values
  1678. selected in `[0, 1]`:
  1679. - 1 for tokens that are **not masked**,
  1680. - 0 for tokens that are **masked**.
  1681. [What are attention masks?](../glossary#attention-mask)
  1682. head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
  1683. Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:
  1684. - 1 indicates the head is **not masked**,
  1685. - 0 indicates the head is **masked**.
  1686. cross_attn_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
  1687. Mask to nullify selected heads of the cross-attention modules. Mask values selected in `[0, 1]`:
  1688. - 1 indicates the head is **not masked**,
  1689. - 0 indicates the head is **masked**.
  1690. past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
  1691. Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
  1692. shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of
  1693. shape `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.
  1694. Contains pre-computed hidden-states (key and values in the self-attention blocks and in the
  1695. cross-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
  1696. If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those
  1697. that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of
  1698. all `decoder_input_ids` of shape `(batch_size, sequence_length)`.
  1699. inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
  1700. Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
  1701. This is useful if you want more control over how to convert `input_ids` indices into associated vectors
  1702. than the model's internal embedding lookup matrix.
  1703. output_attentions (`bool`, *optional*):
  1704. Whether or not to return the attentions tensors of all attention layers. See `attentions` under
  1705. returned tensors for more detail.
  1706. output_hidden_states (`bool`, *optional*):
  1707. Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
  1708. for more detail.
  1709. return_dict (`bool`, *optional*):
  1710. Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
  1711. """
  1712. output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
  1713. output_hidden_states = (
  1714. output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
  1715. )
  1716. use_cache = use_cache if use_cache is not None else self.config.use_cache
  1717. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  1718. # retrieve input_ids and inputs_embeds
  1719. if input_ids is not None and inputs_embeds is not None:
  1720. raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
  1721. elif input_ids is not None:
  1722. input_shape = input_ids.size()
  1723. input_ids = input_ids.view(-1, input_shape[-1])
  1724. elif inputs_embeds is not None:
  1725. input_shape = inputs_embeds.size()[:-1]
  1726. else:
  1727. raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
  1728. # past_key_values_length
  1729. past_key_values_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0
  1730. if inputs_embeds is None:
  1731. inputs_embeds = self.embed_tokens(input_ids)
  1732. # create causal mask
  1733. # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
  1734. combined_attention_mask = None
  1735. if input_shape[-1] > 1:
  1736. combined_attention_mask = _create_4d_causal_attention_mask(
  1737. input_shape, inputs_embeds.dtype, inputs_embeds.device, past_key_values_length=past_key_values_length
  1738. )
  1739. if attention_mask is not None and combined_attention_mask is not None:
  1740. # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
  1741. combined_attention_mask = combined_attention_mask + _prepare_4d_attention_mask_inverted(
  1742. attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]
  1743. )
  1744. # expand encoder attention mask
  1745. if encoder_hidden_states is not None and encoder_attention_mask is not None:
  1746. # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
  1747. encoder_attention_mask = _prepare_4d_attention_mask_inverted(
  1748. encoder_attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]
  1749. )
  1750. # embed positions
  1751. positions = self.embed_positions(input_shape, past_key_values_length)
  1752. hidden_states = inputs_embeds + positions
  1753. hidden_states = self.layernorm_embedding(hidden_states)
  1754. hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
  1755. if self.gradient_checkpointing and self.training:
  1756. if use_cache:
  1757. logger.warning_once(
  1758. "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
  1759. )
  1760. use_cache = False
  1761. # decoder layers
  1762. all_hidden_states = () if output_hidden_states else None
  1763. all_self_attns = () if output_attentions else None
  1764. all_cross_attentions = () if output_attentions else None
  1765. next_decoder_cache = () if use_cache else None
  1766. # check if head_mask/cross_attn_head_mask has a correct number of layers specified if desired
  1767. for attn_mask, mask_name in zip([head_mask, cross_attn_head_mask], ["head_mask", "cross_attn_head_mask"]):
  1768. if attn_mask is not None:
  1769. if attn_mask.size()[0] != len(self.layers):
  1770. raise ValueError(
  1771. f"The `{mask_name}` should be specified for {len(self.layers)} layers, but it is for"
  1772. f" {head_mask.size()[0]}."
  1773. )
  1774. for idx, decoder_layer in enumerate(self.layers):
  1775. # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
  1776. if output_hidden_states:
  1777. all_hidden_states += (hidden_states,)
  1778. if self.training:
  1779. dropout_probability = torch.rand([])
  1780. if dropout_probability < self.layerdrop:
  1781. continue
  1782. past_key_value = past_key_values[idx] if past_key_values is not None else None
  1783. if self.gradient_checkpointing and self.training:
  1784. layer_outputs = self._gradient_checkpointing_func(
  1785. decoder_layer.__call__,
  1786. hidden_states,
  1787. combined_attention_mask,
  1788. encoder_hidden_states,
  1789. encoder_attention_mask,
  1790. head_mask[idx] if head_mask is not None else None,
  1791. cross_attn_head_mask[idx] if cross_attn_head_mask is not None else None,
  1792. None,
  1793. output_attentions,
  1794. use_cache,
  1795. )
  1796. else:
  1797. layer_outputs = decoder_layer(
  1798. hidden_states,
  1799. attention_mask=combined_attention_mask,
  1800. encoder_hidden_states=encoder_hidden_states,
  1801. encoder_attention_mask=encoder_attention_mask,
  1802. layer_head_mask=(head_mask[idx] if head_mask is not None else None),
  1803. cross_attn_layer_head_mask=(
  1804. cross_attn_head_mask[idx] if cross_attn_head_mask is not None else None
  1805. ),
  1806. past_key_value=past_key_value,
  1807. output_attentions=output_attentions,
  1808. use_cache=use_cache,
  1809. )
  1810. hidden_states = layer_outputs[0]
  1811. if use_cache:
  1812. next_decoder_cache += (layer_outputs[3 if output_attentions else 1],)
  1813. if output_attentions:
  1814. all_self_attns += (layer_outputs[1],)
  1815. all_cross_attentions += (layer_outputs[2],)
  1816. # add hidden states from the last decoder layer
  1817. if output_hidden_states:
  1818. all_hidden_states += (hidden_states,)
  1819. next_cache = next_decoder_cache if use_cache else None
  1820. if not return_dict:
  1821. return tuple(
  1822. v
  1823. for v in [hidden_states, next_cache, all_hidden_states, all_self_attns, all_cross_attentions]
  1824. if v is not None
  1825. )
  1826. return BaseModelOutputWithPastAndCrossAttentions(
  1827. last_hidden_state=hidden_states,
  1828. past_key_values=next_cache,
  1829. hidden_states=all_hidden_states,
  1830. attentions=all_self_attns,
  1831. cross_attentions=all_cross_attentions,
  1832. )
  1833. @add_start_docstrings(
  1834. "The bare LED Model outputting raw hidden-states without any specific head on top.",
  1835. LED_START_DOCSTRING,
  1836. )
  1837. class LEDModel(LEDPreTrainedModel):
  1838. _tied_weights_keys = ["decoder.embed_tokens.weight", "encoder.embed_tokens.weight"]
  1839. def __init__(self, config: LEDConfig):
  1840. super().__init__(config)
  1841. padding_idx, vocab_size = config.pad_token_id, config.vocab_size
  1842. self.shared = nn.Embedding(vocab_size, config.d_model, padding_idx)
  1843. self.encoder = LEDEncoder(config, self.shared)
  1844. self.decoder = LEDDecoder(config, self.shared)
  1845. # Initialize weights and apply final processing
  1846. self.post_init()
  1847. def get_input_embeddings(self):
  1848. return self.shared
  1849. def set_input_embeddings(self, value):
  1850. self.shared = value
  1851. self.encoder.embed_tokens = self.shared
  1852. self.decoder.embed_tokens = self.shared
  1853. def get_encoder(self):
  1854. return self.encoder
  1855. def get_decoder(self):
  1856. return self.decoder
  1857. @add_start_docstrings_to_model_forward(LED_INPUTS_DOCSTRING)
  1858. @add_code_sample_docstrings(
  1859. checkpoint=_CHECKPOINT_FOR_DOC,
  1860. output_type=Seq2SeqModelOutput,
  1861. config_class=_CONFIG_FOR_DOC,
  1862. )
  1863. def forward(
  1864. self,
  1865. input_ids: Optional[torch.LongTensor] = None,
  1866. attention_mask: Optional[torch.Tensor] = None,
  1867. decoder_input_ids: Optional[torch.LongTensor] = None,
  1868. decoder_attention_mask: Optional[torch.LongTensor] = None,
  1869. head_mask: Optional[torch.Tensor] = None,
  1870. decoder_head_mask: Optional[torch.Tensor] = None,
  1871. cross_attn_head_mask: Optional[torch.Tensor] = None,
  1872. encoder_outputs: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
  1873. global_attention_mask: Optional[torch.FloatTensor] = None,
  1874. past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
  1875. inputs_embeds: Optional[torch.FloatTensor] = None,
  1876. decoder_inputs_embeds: Optional[torch.FloatTensor] = None,
  1877. use_cache: Optional[bool] = None,
  1878. output_attentions: Optional[bool] = None,
  1879. output_hidden_states: Optional[bool] = None,
  1880. return_dict: Optional[bool] = None,
  1881. ) -> Union[Tuple[torch.Tensor], LEDSeq2SeqModelOutput]:
  1882. output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
  1883. output_hidden_states = (
  1884. output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
  1885. )
  1886. use_cache = use_cache if use_cache is not None else self.config.use_cache
  1887. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  1888. # Using this like Bart, as LED is derived from it. So far
  1889. # No checkpoint on the hub exists that uses that in practice.
  1890. # https://github.com/huggingface/transformers/blob/ac3cb660cad283163f7c73cad511124e845ca388/src/transformers/models/bart/modeling_bart.py#L1153
  1891. if decoder_input_ids is None and decoder_inputs_embeds is None:
  1892. decoder_input_ids = shift_tokens_right(
  1893. input_ids, self.config.pad_token_id, self.config.decoder_start_token_id
  1894. )
  1895. if encoder_outputs is None:
  1896. encoder_outputs = self.encoder(
  1897. input_ids=input_ids,
  1898. attention_mask=attention_mask,
  1899. global_attention_mask=global_attention_mask,
  1900. head_mask=head_mask,
  1901. inputs_embeds=inputs_embeds,
  1902. output_attentions=output_attentions,
  1903. output_hidden_states=output_hidden_states,
  1904. return_dict=return_dict,
  1905. )
  1906. # If the user passed a tuple for encoder_outputs, we wrap it in a LEDEncoderBaseModelOutput when return_dict=False
  1907. elif return_dict and not isinstance(encoder_outputs, LEDEncoderBaseModelOutput):
  1908. encoder_outputs = LEDEncoderBaseModelOutput(
  1909. last_hidden_state=encoder_outputs[0],
  1910. hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,
  1911. attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,
  1912. global_attentions=encoder_outputs[3] if len(encoder_outputs) > 3 else None,
  1913. )
  1914. # decoder outputs consists of (dec_features, past_key_value, dec_hidden, dec_attn)
  1915. decoder_outputs = self.decoder(
  1916. input_ids=decoder_input_ids,
  1917. attention_mask=decoder_attention_mask,
  1918. encoder_hidden_states=encoder_outputs[0],
  1919. encoder_attention_mask=attention_mask,
  1920. head_mask=decoder_head_mask,
  1921. cross_attn_head_mask=cross_attn_head_mask,
  1922. past_key_values=past_key_values,
  1923. inputs_embeds=decoder_inputs_embeds,
  1924. use_cache=use_cache,
  1925. output_attentions=output_attentions,
  1926. output_hidden_states=output_hidden_states,
  1927. return_dict=return_dict,
  1928. )
  1929. if not return_dict:
  1930. return decoder_outputs + encoder_outputs
  1931. return LEDSeq2SeqModelOutput(
  1932. last_hidden_state=decoder_outputs.last_hidden_state,
  1933. past_key_values=decoder_outputs.past_key_values,
  1934. decoder_hidden_states=decoder_outputs.hidden_states,
  1935. decoder_attentions=decoder_outputs.attentions,
  1936. cross_attentions=decoder_outputs.cross_attentions,
  1937. encoder_last_hidden_state=encoder_outputs.last_hidden_state,
  1938. encoder_hidden_states=encoder_outputs.hidden_states,
  1939. encoder_attentions=encoder_outputs.attentions,
  1940. encoder_global_attentions=encoder_outputs.global_attentions,
  1941. )
  1942. @add_start_docstrings(
  1943. "The LED Model with a language modeling head. Can be used for summarization.", LED_START_DOCSTRING
  1944. )
  1945. class LEDForConditionalGeneration(LEDPreTrainedModel, GenerationMixin):
  1946. base_model_prefix = "led"
  1947. _keys_to_ignore_on_load_missing = ["final_logits_bias"]
  1948. _tied_weights_keys = ["decoder.embed_tokens.weight", "encoder.embed_tokens.weight", "lm_head.weight"]
  1949. def __init__(self, config: LEDConfig):
  1950. super().__init__(config)
  1951. self.led = LEDModel(config)
  1952. self.register_buffer("final_logits_bias", torch.zeros((1, self.led.shared.num_embeddings)))
  1953. self.lm_head = nn.Linear(config.d_model, self.led.shared.num_embeddings, bias=False)
  1954. # Initialize weights and apply final processing
  1955. self.post_init()
  1956. def get_encoder(self):
  1957. return self.led.get_encoder()
  1958. def get_decoder(self):
  1959. return self.led.get_decoder()
  1960. def resize_token_embeddings(self, new_num_tokens: int, pad_to_multiple_of: Optional[int] = None) -> nn.Embedding:
  1961. new_embeddings = super().resize_token_embeddings(new_num_tokens, pad_to_multiple_of)
  1962. self._resize_final_logits_bias(new_embeddings.weight.shape[0])
  1963. return new_embeddings
  1964. def _resize_final_logits_bias(self, new_num_tokens: int) -> None:
  1965. old_num_tokens = self.final_logits_bias.shape[-1]
  1966. if new_num_tokens <= old_num_tokens:
  1967. new_bias = self.final_logits_bias[:, :new_num_tokens]
  1968. else:
  1969. extra_bias = torch.zeros((1, new_num_tokens - old_num_tokens), device=self.final_logits_bias.device)
  1970. new_bias = torch.cat([self.final_logits_bias, extra_bias], dim=1)
  1971. self.register_buffer("final_logits_bias", new_bias)
  1972. def get_output_embeddings(self):
  1973. return self.lm_head
  1974. def set_output_embeddings(self, new_embeddings):
  1975. self.lm_head = new_embeddings
  1976. @add_start_docstrings_to_model_forward(LED_INPUTS_DOCSTRING)
  1977. @replace_return_docstrings(output_type=Seq2SeqLMOutput, config_class=_CONFIG_FOR_DOC)
  1978. @add_end_docstrings(LED_GENERATION_EXAMPLE)
  1979. def forward(
  1980. self,
  1981. input_ids: Optional[torch.LongTensor] = None,
  1982. attention_mask: Optional[torch.Tensor] = None,
  1983. decoder_input_ids: Optional[torch.LongTensor] = None,
  1984. decoder_attention_mask: Optional[torch.LongTensor] = None,
  1985. head_mask: Optional[torch.Tensor] = None,
  1986. decoder_head_mask: Optional[torch.Tensor] = None,
  1987. cross_attn_head_mask: Optional[torch.Tensor] = None,
  1988. encoder_outputs: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
  1989. global_attention_mask: Optional[torch.FloatTensor] = None,
  1990. past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
  1991. inputs_embeds: Optional[torch.FloatTensor] = None,
  1992. decoder_inputs_embeds: Optional[torch.FloatTensor] = None,
  1993. labels: Optional[torch.LongTensor] = None,
  1994. use_cache: Optional[bool] = None,
  1995. output_attentions: Optional[bool] = None,
  1996. output_hidden_states: Optional[bool] = None,
  1997. return_dict: Optional[bool] = None,
  1998. ) -> Union[Tuple[torch.Tensor], LEDSeq2SeqLMOutput]:
  1999. r"""
  2000. labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
  2001. Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
  2002. config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
  2003. (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
  2004. Returns:
  2005. Conditional generation example:
  2006. ```python
  2007. >>> from transformers import AutoTokenizer, LEDForConditionalGeneration
  2008. >>> tokenizer = AutoTokenizer.from_pretrained("allenai/led-base-16384")
  2009. >>> TXT = "My friends are <mask> but they eat too many carbs."
  2010. >>> model = LEDForConditionalGeneration.from_pretrained("allenai/led-base-16384")
  2011. >>> input_ids = tokenizer([TXT], return_tensors="pt")["input_ids"]
  2012. >>> prediction = model.generate(input_ids)[0]
  2013. >>> print(tokenizer.decode(prediction, skip_special_tokens=True))
  2014. ```"""
  2015. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  2016. if labels is not None:
  2017. if use_cache:
  2018. logger.warning("The `use_cache` argument is changed to `False` since `labels` is provided.")
  2019. use_cache = False
  2020. if decoder_input_ids is None and decoder_inputs_embeds is None:
  2021. decoder_input_ids = shift_tokens_right(
  2022. labels, self.config.pad_token_id, self.config.decoder_start_token_id
  2023. )
  2024. outputs = self.led(
  2025. input_ids,
  2026. attention_mask=attention_mask,
  2027. decoder_input_ids=decoder_input_ids,
  2028. decoder_attention_mask=decoder_attention_mask,
  2029. encoder_outputs=encoder_outputs,
  2030. global_attention_mask=global_attention_mask,
  2031. head_mask=head_mask,
  2032. decoder_head_mask=decoder_head_mask,
  2033. cross_attn_head_mask=cross_attn_head_mask,
  2034. past_key_values=past_key_values,
  2035. inputs_embeds=inputs_embeds,
  2036. decoder_inputs_embeds=decoder_inputs_embeds,
  2037. use_cache=use_cache,
  2038. output_attentions=output_attentions,
  2039. output_hidden_states=output_hidden_states,
  2040. return_dict=return_dict,
  2041. )
  2042. lm_logits = self.lm_head(outputs[0]) + self.final_logits_bias
  2043. masked_lm_loss = None
  2044. if labels is not None:
  2045. loss_fct = CrossEntropyLoss()
  2046. masked_lm_loss = loss_fct(lm_logits.view(-1, self.config.vocab_size), labels.view(-1))
  2047. if not return_dict:
  2048. output = (lm_logits,) + outputs[1:]
  2049. return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
  2050. return LEDSeq2SeqLMOutput(
  2051. loss=masked_lm_loss,
  2052. logits=lm_logits,
  2053. past_key_values=outputs.past_key_values,
  2054. decoder_hidden_states=outputs.decoder_hidden_states,
  2055. decoder_attentions=outputs.decoder_attentions,
  2056. cross_attentions=outputs.cross_attentions,
  2057. encoder_last_hidden_state=outputs.encoder_last_hidden_state,
  2058. encoder_hidden_states=outputs.encoder_hidden_states,
  2059. encoder_attentions=outputs.encoder_attentions,
  2060. encoder_global_attentions=outputs.encoder_global_attentions,
  2061. )
  2062. def prepare_decoder_input_ids_from_labels(self, labels: torch.Tensor):
  2063. return shift_tokens_right(labels, self.config.pad_token_id, self.config.decoder_start_token_id)
  2064. @staticmethod
  2065. def _reorder_cache(past_key_values, beam_idx):
  2066. reordered_past = ()
  2067. for layer_past in past_key_values:
  2068. # cached cross_attention states don't have to be reordered -> they are always the same
  2069. reordered_past += (
  2070. tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past[:2])
  2071. + layer_past[2:],
  2072. )
  2073. return reordered_past
  2074. @add_start_docstrings(
  2075. """
  2076. LED model with a sequence classification/head on top (a linear layer on top of the pooled output) e.g. for GLUE
  2077. tasks.
  2078. """,
  2079. LED_START_DOCSTRING,
  2080. )
  2081. class LEDForSequenceClassification(LEDPreTrainedModel):
  2082. _tied_weights_keys = ["decoder.embed_tokens.weight", "encoder.embed_tokens.weight"]
  2083. def __init__(self, config: LEDConfig, **kwargs):
  2084. warnings.warn(
  2085. "The `transformers.LEDForSequenceClassification` class is deprecated and will be removed in version 5 of"
  2086. " Transformers. No actual method were provided in the original paper on how to perfom"
  2087. " sequence classification.",
  2088. FutureWarning,
  2089. )
  2090. super().__init__(config, **kwargs)
  2091. self.led = LEDModel(config)
  2092. self.classification_head = LEDClassificationHead(
  2093. config.d_model,
  2094. config.d_model,
  2095. config.num_labels,
  2096. config.classifier_dropout,
  2097. )
  2098. # Initialize weights and apply final processing
  2099. self.post_init()
  2100. @add_start_docstrings_to_model_forward(LED_INPUTS_DOCSTRING)
  2101. @add_code_sample_docstrings(
  2102. checkpoint=_CHECKPOINT_FOR_DOC,
  2103. output_type=Seq2SeqSequenceClassifierOutput,
  2104. config_class=_CONFIG_FOR_DOC,
  2105. )
  2106. def forward(
  2107. self,
  2108. input_ids: Optional[torch.LongTensor] = None,
  2109. attention_mask: Optional[torch.Tensor] = None,
  2110. decoder_input_ids: Optional[torch.LongTensor] = None,
  2111. decoder_attention_mask: Optional[torch.LongTensor] = None,
  2112. head_mask: Optional[torch.Tensor] = None,
  2113. decoder_head_mask: Optional[torch.Tensor] = None,
  2114. cross_attn_head_mask: Optional[torch.Tensor] = None,
  2115. encoder_outputs: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
  2116. global_attention_mask: Optional[torch.FloatTensor] = None,
  2117. inputs_embeds: Optional[torch.FloatTensor] = None,
  2118. decoder_inputs_embeds: Optional[torch.FloatTensor] = None,
  2119. labels: Optional[torch.LongTensor] = None,
  2120. use_cache: Optional[bool] = None,
  2121. output_attentions: Optional[bool] = None,
  2122. output_hidden_states: Optional[bool] = None,
  2123. return_dict: Optional[bool] = None,
  2124. ) -> Union[Tuple[torch.Tensor], LEDSeq2SeqSequenceClassifierOutput]:
  2125. r"""
  2126. labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
  2127. Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
  2128. config.num_labels - 1]`. If `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
  2129. """
  2130. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  2131. if labels is not None:
  2132. use_cache = False
  2133. if input_ids is None and inputs_embeds is not None:
  2134. raise NotImplementedError(
  2135. f"Passing input embeddings is currently not supported for {self.__class__.__name__}"
  2136. )
  2137. outputs = self.led(
  2138. input_ids,
  2139. attention_mask=attention_mask,
  2140. decoder_input_ids=decoder_input_ids,
  2141. decoder_attention_mask=decoder_attention_mask,
  2142. global_attention_mask=global_attention_mask,
  2143. head_mask=head_mask,
  2144. decoder_head_mask=decoder_head_mask,
  2145. cross_attn_head_mask=cross_attn_head_mask,
  2146. encoder_outputs=encoder_outputs,
  2147. inputs_embeds=inputs_embeds,
  2148. decoder_inputs_embeds=decoder_inputs_embeds,
  2149. use_cache=use_cache,
  2150. output_attentions=output_attentions,
  2151. output_hidden_states=output_hidden_states,
  2152. return_dict=return_dict,
  2153. )
  2154. hidden_states = outputs[0] # last hidden state
  2155. eos_mask = input_ids.eq(self.config.eos_token_id).to(hidden_states.device)
  2156. if len(torch.unique_consecutive(eos_mask.sum(1))) > 1:
  2157. raise ValueError("All examples must have the same number of <eos> tokens.")
  2158. sentence_representation = hidden_states[eos_mask, :].view(hidden_states.size(0), -1, hidden_states.size(-1))[
  2159. :, -1, :
  2160. ]
  2161. logits = self.classification_head(sentence_representation)
  2162. loss = None
  2163. if labels is not None:
  2164. if self.config.problem_type is None:
  2165. if self.config.num_labels == 1:
  2166. self.config.problem_type = "regression"
  2167. elif self.config.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
  2168. self.config.problem_type = "single_label_classification"
  2169. else:
  2170. self.config.problem_type = "multi_label_classification"
  2171. if self.config.problem_type == "regression":
  2172. loss_fct = MSELoss()
  2173. if self.config.num_labels == 1:
  2174. loss = loss_fct(logits.squeeze(), labels.squeeze())
  2175. else:
  2176. loss = loss_fct(logits, labels)
  2177. elif self.config.problem_type == "single_label_classification":
  2178. loss_fct = CrossEntropyLoss()
  2179. loss = loss_fct(logits.view(-1, self.config.num_labels), labels.view(-1))
  2180. elif self.config.problem_type == "multi_label_classification":
  2181. loss_fct = BCEWithLogitsLoss()
  2182. loss = loss_fct(logits, labels)
  2183. if not return_dict:
  2184. output = (logits,) + outputs[1:]
  2185. return ((loss,) + output) if loss is not None else output
  2186. return LEDSeq2SeqSequenceClassifierOutput(
  2187. loss=loss,
  2188. logits=logits,
  2189. past_key_values=outputs.past_key_values,
  2190. decoder_hidden_states=outputs.decoder_hidden_states,
  2191. decoder_attentions=outputs.decoder_attentions,
  2192. cross_attentions=outputs.cross_attentions,
  2193. encoder_last_hidden_state=outputs.encoder_last_hidden_state,
  2194. encoder_hidden_states=outputs.encoder_hidden_states,
  2195. encoder_attentions=outputs.encoder_attentions,
  2196. encoder_global_attentions=outputs.encoder_global_attentions,
  2197. )
  2198. @add_start_docstrings(
  2199. """
  2200. LED Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear layer
  2201. on top of the hidden-states output to compute `span start logits` and `span end logits`).
  2202. """,
  2203. LED_START_DOCSTRING,
  2204. )
  2205. class LEDForQuestionAnswering(LEDPreTrainedModel):
  2206. _tied_weights_keys = ["decoder.embed_tokens.weight", "encoder.embed_tokens.weight"]
  2207. def __init__(self, config):
  2208. super().__init__(config)
  2209. config.num_labels = 2
  2210. self.num_labels = config.num_labels
  2211. self.led = LEDModel(config)
  2212. self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
  2213. # Initialize weights and apply final processing
  2214. self.post_init()
  2215. @add_start_docstrings_to_model_forward(LED_INPUTS_DOCSTRING)
  2216. @add_code_sample_docstrings(
  2217. checkpoint=_CHECKPOINT_FOR_DOC,
  2218. output_type=Seq2SeqQuestionAnsweringModelOutput,
  2219. config_class=_CONFIG_FOR_DOC,
  2220. )
  2221. def forward(
  2222. self,
  2223. input_ids: Optional[torch.LongTensor] = None,
  2224. attention_mask: Optional[torch.Tensor] = None,
  2225. decoder_input_ids: Optional[torch.LongTensor] = None,
  2226. decoder_attention_mask: Optional[torch.LongTensor] = None,
  2227. head_mask: Optional[torch.Tensor] = None,
  2228. decoder_head_mask: Optional[torch.Tensor] = None,
  2229. cross_attn_head_mask: Optional[torch.Tensor] = None,
  2230. encoder_outputs: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
  2231. global_attention_mask: Optional[torch.FloatTensor] = None,
  2232. start_positions: Optional[torch.LongTensor] = None,
  2233. end_positions: Optional[torch.LongTensor] = None,
  2234. inputs_embeds: Optional[torch.FloatTensor] = None,
  2235. decoder_inputs_embeds: Optional[torch.FloatTensor] = None,
  2236. use_cache: Optional[bool] = None,
  2237. output_attentions: Optional[bool] = None,
  2238. output_hidden_states: Optional[bool] = None,
  2239. return_dict: Optional[bool] = None,
  2240. ) -> Union[Tuple[torch.Tensor], LEDSeq2SeqQuestionAnsweringModelOutput]:
  2241. r"""
  2242. start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
  2243. Labels for position (index) of the start of the labelled span for computing the token classification loss.
  2244. Positions are clamped to the length of the sequence (*sequence_length*). Position outside of the sequence
  2245. are not taken into account for computing the loss.
  2246. end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
  2247. Labels for position (index) of the end of the labelled span for computing the token classification loss.
  2248. Positions are clamped to the length of the sequence (*sequence_length*). Position outside of the sequence
  2249. are not taken into account for computing the loss.
  2250. """
  2251. return_dict = return_dict if return_dict is not None else self.config.use_return_dict
  2252. if start_positions is not None and end_positions is not None:
  2253. use_cache = False
  2254. outputs = self.led(
  2255. input_ids,
  2256. attention_mask=attention_mask,
  2257. decoder_input_ids=decoder_input_ids,
  2258. decoder_attention_mask=decoder_attention_mask,
  2259. global_attention_mask=global_attention_mask,
  2260. head_mask=head_mask,
  2261. decoder_head_mask=decoder_head_mask,
  2262. cross_attn_head_mask=cross_attn_head_mask,
  2263. encoder_outputs=encoder_outputs,
  2264. inputs_embeds=inputs_embeds,
  2265. decoder_inputs_embeds=decoder_inputs_embeds,
  2266. use_cache=use_cache,
  2267. output_attentions=output_attentions,
  2268. output_hidden_states=output_hidden_states,
  2269. return_dict=return_dict,
  2270. )
  2271. sequence_output = outputs[0]
  2272. logits = self.qa_outputs(sequence_output)
  2273. start_logits, end_logits = logits.split(1, dim=-1)
  2274. start_logits = start_logits.squeeze(-1).contiguous()
  2275. end_logits = end_logits.squeeze(-1).contiguous()
  2276. total_loss = None
  2277. if start_positions is not None and end_positions is not None:
  2278. # If we are on multi-GPU, split add a dimension
  2279. if len(start_positions.size()) > 1:
  2280. start_positions = start_positions.squeeze(-1)
  2281. if len(end_positions.size()) > 1:
  2282. end_positions = end_positions.squeeze(-1)
  2283. # sometimes the start/end positions are outside our model inputs, we ignore these terms
  2284. ignored_index = start_logits.size(1)
  2285. start_positions = start_positions.clamp(0, ignored_index)
  2286. end_positions = end_positions.clamp(0, ignored_index)
  2287. loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
  2288. start_loss = loss_fct(start_logits, start_positions)
  2289. end_loss = loss_fct(end_logits, end_positions)
  2290. total_loss = (start_loss + end_loss) / 2
  2291. if not return_dict:
  2292. output = (
  2293. start_logits,
  2294. end_logits,
  2295. ) + outputs[1:]
  2296. return ((total_loss,) + output) if total_loss is not None else output
  2297. return LEDSeq2SeqQuestionAnsweringModelOutput(
  2298. loss=total_loss,
  2299. start_logits=start_logits,
  2300. end_logits=end_logits,
  2301. past_key_values=outputs.past_key_values,
  2302. decoder_hidden_states=outputs.decoder_hidden_states,
  2303. decoder_attentions=outputs.decoder_attentions,
  2304. cross_attentions=outputs.cross_attentions,
  2305. encoder_last_hidden_state=outputs.encoder_last_hidden_state,
  2306. encoder_hidden_states=outputs.encoder_hidden_states,
  2307. encoder_attentions=outputs.encoder_attentions,
  2308. encoder_global_attentions=outputs.encoder_global_attentions,
  2309. )