| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202 |
- # Copyright 2021 Iz Beltagy, Matthew E. Peters, Arman Cohan and The HuggingFace Inc. team. All rights reserved.
- #
- # Licensed under the Apache License, Version 2.0 (the "License");
- # you may not use this file except in compliance with the License.
- # You may obtain a copy of the License at
- #
- # http://www.apache.org/licenses/LICENSE-2.0
- #
- # Unless required by applicable law or agreed to in writing, software
- # distributed under the License is distributed on an "AS IS" BASIS,
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- # See the License for the specific language governing permissions and
- # limitations under the License.
- """PyTorch LED model."""
- import math
- from dataclasses import dataclass
- import torch
- from torch import nn
- from torch.nn import CrossEntropyLoss
- from ... import initialization as init
- from ...activations import ACT2FN
- from ...cache_utils import Cache, DynamicCache, EncoderDecoderCache
- from ...generation import GenerationMixin
- from ...masking_utils import create_bidirectional_mask, create_causal_mask
- from ...modeling_layers import GradientCheckpointingLayer
- from ...modeling_outputs import BaseModelOutputWithPastAndCrossAttentions
- from ...modeling_utils import PreTrainedModel
- from ...utils import ModelOutput, auto_docstring, logging
- from .configuration_led import LEDConfig
- logger = logging.get_logger(__name__)
- def shift_tokens_right(input_ids: torch.Tensor, pad_token_id: int, decoder_start_token_id: int):
- """
- Shift input ids one token to the right.
- """
- shifted_input_ids = input_ids.new_zeros(input_ids.shape)
- shifted_input_ids[:, 1:] = input_ids[:, :-1].clone()
- shifted_input_ids[:, 0] = decoder_start_token_id
- if pad_token_id is None:
- raise ValueError("config.pad_token_id has to be defined.")
- # replace possible -100 values in labels by `pad_token_id`
- shifted_input_ids.masked_fill_(shifted_input_ids == -100, pad_token_id)
- return shifted_input_ids
- def _prepare_4d_attention_mask_inverted(mask: torch.Tensor, dtype: torch.dtype, tgt_len: int | None = None):
- """
- Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
- """
- bsz, src_len = mask.size()
- tgt_len = tgt_len if tgt_len is not None else src_len
- expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)
- inverted_mask = 1.0 - expanded_mask
- expanded_attention_mask = inverted_mask.masked_fill(inverted_mask.bool(), torch.finfo(dtype).min)
- # make sure that global_attn_mask is positive
- expanded_attention_mask = expanded_attention_mask * inverted_mask
- return expanded_attention_mask
- class LEDLearnedPositionalEmbedding(nn.Embedding):
- """
- This module learns positional embeddings up to a fixed maximum size.
- """
- def __init__(self, num_embeddings: int, embedding_dim: int):
- super().__init__(num_embeddings, embedding_dim)
- def forward(self, input_ids_shape: torch.Size, past_key_values_length: int = 0):
- """`input_ids_shape` is expected to be [bsz x seqlen]."""
- bsz, seq_len = input_ids_shape[:2]
- positions = torch.arange(
- past_key_values_length, past_key_values_length + seq_len, dtype=torch.long, device=self.weight.device
- )
- return super().forward(positions)
- # Copied from transformers.models.longformer.modeling_longformer.LongformerSelfAttention with Longformer->LEDEncoder
- class LEDEncoderSelfAttention(nn.Module):
- def __init__(self, config, layer_id):
- super().__init__()
- if config.hidden_size % config.num_attention_heads != 0:
- raise ValueError(
- f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
- f"heads ({config.num_attention_heads})"
- )
- self.num_heads = config.num_attention_heads
- self.head_dim = int(config.hidden_size / config.num_attention_heads)
- self.embed_dim = config.hidden_size
- self.query = nn.Linear(config.hidden_size, self.embed_dim)
- self.key = nn.Linear(config.hidden_size, self.embed_dim)
- self.value = nn.Linear(config.hidden_size, self.embed_dim)
- # separate projection layers for tokens with global attention
- self.query_global = nn.Linear(config.hidden_size, self.embed_dim)
- self.key_global = nn.Linear(config.hidden_size, self.embed_dim)
- self.value_global = nn.Linear(config.hidden_size, self.embed_dim)
- self.dropout = config.attention_probs_dropout_prob
- self.layer_id = layer_id
- attention_window = config.attention_window[self.layer_id]
- assert attention_window % 2 == 0, (
- f"`attention_window` for layer {self.layer_id} has to be an even value. Given {attention_window}"
- )
- assert attention_window > 0, (
- f"`attention_window` for layer {self.layer_id} has to be positive. Given {attention_window}"
- )
- self.one_sided_attn_window_size = attention_window // 2
- self.config = config
- def forward(
- self,
- hidden_states,
- attention_mask=None,
- is_index_masked=None,
- is_index_global_attn=None,
- is_global_attn=None,
- output_attentions=False,
- ):
- """
- [`LEDEncoderSelfAttention`] expects *len(hidden_states)* to be multiple of *attention_window*. Padding to
- *attention_window* happens in [`LEDEncoderModel.forward`] to avoid redoing the padding on each layer.
- The *attention_mask* is changed in [`LEDEncoderModel.forward`] from 0, 1, 2 to:
- - -10000: no attention
- - 0: local attention
- - +10000: global attention
- """
- hidden_states = hidden_states.transpose(0, 1)
- # project hidden states
- query_vectors = self.query(hidden_states)
- key_vectors = self.key(hidden_states)
- value_vectors = self.value(hidden_states)
- seq_len, batch_size, embed_dim = hidden_states.size()
- assert embed_dim == self.embed_dim, (
- f"hidden_states should have embed_dim = {self.embed_dim}, but has {embed_dim}"
- )
- # normalize query
- query_vectors /= math.sqrt(self.head_dim)
- query_vectors = query_vectors.view(seq_len, batch_size, self.num_heads, self.head_dim).transpose(0, 1)
- key_vectors = key_vectors.view(seq_len, batch_size, self.num_heads, self.head_dim).transpose(0, 1)
- attn_scores = self._sliding_chunks_query_key_matmul(
- query_vectors, key_vectors, self.one_sided_attn_window_size
- )
- # values to pad for attention probs
- remove_from_windowed_attention_mask = (attention_mask != 0)[:, :, None, None]
- # cast to fp32/fp16 then replace 1's with -inf
- float_mask = remove_from_windowed_attention_mask.type_as(query_vectors).masked_fill(
- remove_from_windowed_attention_mask, torch.finfo(query_vectors.dtype).min
- )
- # diagonal mask with zeros everywhere and -inf inplace of padding
- diagonal_mask = self._sliding_chunks_query_key_matmul(
- float_mask.new_ones(size=float_mask.size()), float_mask, self.one_sided_attn_window_size
- )
- # pad local attention probs
- attn_scores += diagonal_mask
- assert list(attn_scores.size()) == [
- batch_size,
- seq_len,
- self.num_heads,
- self.one_sided_attn_window_size * 2 + 1,
- ], (
- f"local_attn_probs should be of size ({batch_size}, {seq_len}, {self.num_heads},"
- f" {self.one_sided_attn_window_size * 2 + 1}), but is of size {attn_scores.size()}"
- )
- # compute local attention probs from global attention keys and contact over window dim
- if is_global_attn:
- # compute global attn indices required through out forward fn
- (
- max_num_global_attn_indices,
- is_index_global_attn_nonzero,
- is_local_index_global_attn_nonzero,
- is_local_index_no_global_attn_nonzero,
- ) = self._get_global_attn_indices(is_index_global_attn)
- # calculate global attn probs from global key
- global_key_attn_scores = self._concat_with_global_key_attn_probs(
- query_vectors=query_vectors,
- key_vectors=key_vectors,
- max_num_global_attn_indices=max_num_global_attn_indices,
- is_index_global_attn_nonzero=is_index_global_attn_nonzero,
- is_local_index_global_attn_nonzero=is_local_index_global_attn_nonzero,
- is_local_index_no_global_attn_nonzero=is_local_index_no_global_attn_nonzero,
- )
- # concat to local_attn_probs
- # (batch_size, seq_len, num_heads, extra attention count + 2*window+1)
- attn_scores = torch.cat((global_key_attn_scores, attn_scores), dim=-1)
- # free memory
- del global_key_attn_scores
- attn_probs = nn.functional.softmax(
- attn_scores, dim=-1, dtype=torch.float32
- ) # use fp32 for numerical stability
- # softmax sometimes inserts NaN if all positions are masked, replace them with 0
- attn_probs = torch.masked_fill(attn_probs, is_index_masked[:, :, None, None], 0.0)
- attn_probs = attn_probs.type_as(attn_scores)
- # free memory
- del attn_scores
- # apply dropout
- attn_probs = nn.functional.dropout(attn_probs, p=self.dropout, training=self.training)
- value_vectors = value_vectors.view(seq_len, batch_size, self.num_heads, self.head_dim).transpose(0, 1)
- # compute local attention output with global attention value and add
- if is_global_attn:
- # compute sum of global and local attn
- attn_output = self._compute_attn_output_with_global_indices(
- value_vectors=value_vectors,
- attn_probs=attn_probs,
- max_num_global_attn_indices=max_num_global_attn_indices,
- is_index_global_attn_nonzero=is_index_global_attn_nonzero,
- is_local_index_global_attn_nonzero=is_local_index_global_attn_nonzero,
- )
- else:
- # compute local attn only
- attn_output = self._sliding_chunks_matmul_attn_probs_value(
- attn_probs, value_vectors, self.one_sided_attn_window_size
- )
- assert attn_output.size() == (batch_size, seq_len, self.num_heads, self.head_dim), "Unexpected size"
- attn_output = attn_output.transpose(0, 1).reshape(seq_len, batch_size, embed_dim).contiguous()
- # compute value for global attention and overwrite to attention output
- # TODO: remove the redundant computation
- if is_global_attn:
- global_attn_output, global_attn_probs = self._compute_global_attn_output_from_hidden(
- hidden_states=hidden_states,
- max_num_global_attn_indices=max_num_global_attn_indices,
- is_local_index_global_attn_nonzero=is_local_index_global_attn_nonzero,
- is_index_global_attn_nonzero=is_index_global_attn_nonzero,
- is_local_index_no_global_attn_nonzero=is_local_index_no_global_attn_nonzero,
- is_index_masked=is_index_masked,
- )
- # get only non zero global attn output
- nonzero_global_attn_output = global_attn_output[
- is_local_index_global_attn_nonzero[0], :, is_local_index_global_attn_nonzero[1]
- ]
- # overwrite values with global attention
- attn_output[is_index_global_attn_nonzero[::-1]] = nonzero_global_attn_output.view(
- len(is_local_index_global_attn_nonzero[0]), -1
- )
- # The attention weights for tokens with global attention are
- # just filler values, they were never used to compute the output.
- # Fill with 0 now, the correct values are in 'global_attn_probs'.
- attn_probs[is_index_global_attn_nonzero] = 0
- outputs = (attn_output.transpose(0, 1),)
- if output_attentions:
- outputs += (attn_probs,)
- return outputs + (global_attn_probs,) if (is_global_attn and output_attentions) else outputs
- @staticmethod
- def _pad_and_transpose_last_two_dims(hidden_states_padded, padding):
- """pads rows and then flips rows and columns"""
- hidden_states_padded = nn.functional.pad(
- hidden_states_padded, padding
- ) # padding value is not important because it will be overwritten
- hidden_states_padded = hidden_states_padded.view(
- *hidden_states_padded.size()[:-2], hidden_states_padded.size(-1), hidden_states_padded.size(-2)
- )
- return hidden_states_padded
- @staticmethod
- def _pad_and_diagonalize(chunked_hidden_states):
- """
- shift every row 1 step right, converting columns into diagonals.
- Example:
- ```python
- chunked_hidden_states: [
- 0.4983,
- 2.6918,
- -0.0071,
- 1.0492,
- -1.8348,
- 0.7672,
- 0.2986,
- 0.0285,
- -0.7584,
- 0.4206,
- -0.0405,
- 0.1599,
- 2.0514,
- -1.1600,
- 0.5372,
- 0.2629,
- ]
- window_overlap = num_rows = 4
- ```
- (pad & diagonalize) => [ 0.4983, 2.6918, -0.0071, 1.0492, 0.0000, 0.0000, 0.0000
- 0.0000, -1.8348, 0.7672, 0.2986, 0.0285, 0.0000, 0.0000 0.0000, 0.0000, -0.7584, 0.4206,
- -0.0405, 0.1599, 0.0000 0.0000, 0.0000, 0.0000, 2.0514, -1.1600, 0.5372, 0.2629 ]
- """
- total_num_heads, num_chunks, window_overlap, hidden_dim = chunked_hidden_states.size()
- chunked_hidden_states = nn.functional.pad(
- chunked_hidden_states, (0, window_overlap + 1)
- ) # 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
- chunked_hidden_states = chunked_hidden_states.view(
- total_num_heads, num_chunks, -1
- ) # total_num_heads x num_chunks x window_overlap*window_overlap+window_overlap
- chunked_hidden_states = chunked_hidden_states[
- :, :, :-window_overlap
- ] # total_num_heads x num_chunks x window_overlap*window_overlap
- chunked_hidden_states = chunked_hidden_states.view(
- total_num_heads, num_chunks, window_overlap, window_overlap + hidden_dim
- )
- chunked_hidden_states = chunked_hidden_states[:, :, :, :-1]
- return chunked_hidden_states
- @staticmethod
- def _chunk(hidden_states, window_overlap, onnx_export: bool = False):
- """convert into overlapping chunks. Chunk size = 2w, overlap size = w"""
- if not onnx_export:
- # non-overlapping chunks of size = 2w
- hidden_states = hidden_states.view(
- hidden_states.size(0),
- torch.div(hidden_states.size(1), (window_overlap * 2), rounding_mode="trunc"),
- window_overlap * 2,
- hidden_states.size(2),
- )
- # use `as_strided` to make the chunks overlap with an overlap size = window_overlap
- chunk_size = list(hidden_states.size())
- chunk_size[1] = chunk_size[1] * 2 - 1
- chunk_stride = list(hidden_states.stride())
- chunk_stride[1] = chunk_stride[1] // 2
- return hidden_states.as_strided(size=chunk_size, stride=chunk_stride)
- # When exporting to ONNX, use this separate logic
- # have to use slow implementation since as_strided, unfold and 2d-tensor indexing aren't supported (yet) in ONNX export
- # TODO replace this with
- # > return hidden_states.unfold(dimension=1, size=window_overlap * 2, step=window_overlap).transpose(2, 3)
- # once `unfold` is supported
- # the case hidden_states.size(1) == window_overlap * 2 can also simply return hidden_states.unsqueeze(1), but that's control flow
- chunk_size = [
- hidden_states.size(0),
- torch.div(hidden_states.size(1), window_overlap, rounding_mode="trunc") - 1,
- window_overlap * 2,
- hidden_states.size(2),
- ]
- overlapping_chunks = torch.empty(chunk_size, device=hidden_states.device)
- for chunk in range(chunk_size[1]):
- overlapping_chunks[:, chunk, :, :] = hidden_states[
- :, chunk * window_overlap : chunk * window_overlap + 2 * window_overlap, :
- ]
- return overlapping_chunks
- @staticmethod
- def _mask_invalid_locations(input_tensor, affected_seq_len) -> torch.Tensor:
- beginning_mask_2d = input_tensor.new_ones(affected_seq_len, affected_seq_len + 1).tril().flip(dims=[0])
- beginning_mask = beginning_mask_2d[None, :, None, :]
- ending_mask = beginning_mask.flip(dims=(1, 3))
- beginning_input = input_tensor[:, :affected_seq_len, :, : affected_seq_len + 1]
- beginning_mask = beginning_mask.expand(beginning_input.size())
- input_tensor[:, :affected_seq_len, :, : affected_seq_len + 1] = torch.full_like(
- beginning_input, -float("inf")
- ).where(beginning_mask.bool(), beginning_input)
- ending_input = input_tensor[:, -affected_seq_len:, :, -(affected_seq_len + 1) :]
- ending_mask = ending_mask.expand(ending_input.size())
- input_tensor[:, -affected_seq_len:, :, -(affected_seq_len + 1) :] = torch.full_like(
- ending_input, -float("inf")
- ).where(ending_mask.bool(), ending_input)
- def _sliding_chunks_query_key_matmul(self, query: torch.Tensor, key: torch.Tensor, window_overlap: int):
- """
- Matrix multiplication of query and key tensors using with a sliding window attention pattern. This
- implementation splits the input into overlapping chunks of size 2w (e.g. 512 for pretrained LEDEncoder) with an
- overlap of size window_overlap
- """
- batch_size, seq_len, num_heads, head_dim = query.size()
- assert seq_len % (window_overlap * 2) == 0, (
- f"Sequence length should be multiple of {window_overlap * 2}. Given {seq_len}"
- )
- assert query.size() == key.size()
- chunks_count = torch.div(seq_len, window_overlap, rounding_mode="trunc") - 1
- # group batch_size and num_heads dimensions into one, then chunk seq_len into chunks of size window_overlap * 2
- query = query.transpose(1, 2).reshape(batch_size * num_heads, seq_len, head_dim)
- key = key.transpose(1, 2).reshape(batch_size * num_heads, seq_len, head_dim)
- query = self._chunk(query, window_overlap, getattr(self.config, "onnx_export", False))
- key = self._chunk(key, window_overlap, getattr(self.config, "onnx_export", False))
- # matrix multiplication
- # bcxd: batch_size * num_heads x chunks x 2window_overlap x head_dim
- # bcyd: batch_size * num_heads x chunks x 2window_overlap x head_dim
- # bcxy: batch_size * num_heads x chunks x 2window_overlap x 2window_overlap
- diagonal_chunked_attention_scores = torch.einsum("bcxd,bcyd->bcxy", (query, key)) # multiply
- # convert diagonals into columns
- diagonal_chunked_attention_scores = self._pad_and_transpose_last_two_dims(
- diagonal_chunked_attention_scores, padding=(0, 0, 0, 1)
- )
- # allocate space for the overall attention matrix where the chunks are combined. The last dimension
- # has (window_overlap * 2 + 1) columns. The first (window_overlap) columns are the window_overlap lower triangles (attention from a word to
- # window_overlap previous words). The following column is attention score from each word to itself, then
- # followed by window_overlap columns for the upper triangle.
- diagonal_attention_scores = diagonal_chunked_attention_scores.new_zeros(
- (batch_size * num_heads, chunks_count + 1, window_overlap, window_overlap * 2 + 1)
- )
- # copy parts from diagonal_chunked_attention_scores into the combined matrix of attentions
- # - copying the main diagonal and the upper triangle
- diagonal_attention_scores[:, :-1, :, window_overlap:] = diagonal_chunked_attention_scores[
- :, :, :window_overlap, : window_overlap + 1
- ]
- diagonal_attention_scores[:, -1, :, window_overlap:] = diagonal_chunked_attention_scores[
- :, -1, window_overlap:, : window_overlap + 1
- ]
- # - copying the lower triangle
- diagonal_attention_scores[:, 1:, :, :window_overlap] = diagonal_chunked_attention_scores[
- :, :, -(window_overlap + 1) : -1, window_overlap + 1 :
- ]
- diagonal_attention_scores[:, 0, 1:window_overlap, 1:window_overlap] = diagonal_chunked_attention_scores[
- :, 0, : window_overlap - 1, 1 - window_overlap :
- ]
- # separate batch_size and num_heads dimensions again
- diagonal_attention_scores = diagonal_attention_scores.view(
- batch_size, num_heads, seq_len, 2 * window_overlap + 1
- ).transpose(2, 1)
- self._mask_invalid_locations(diagonal_attention_scores, window_overlap)
- return diagonal_attention_scores
- def _sliding_chunks_matmul_attn_probs_value(
- self, attn_probs: torch.Tensor, value: torch.Tensor, window_overlap: int
- ):
- """
- Same as _sliding_chunks_query_key_matmul but for attn_probs and value tensors. Returned tensor will be of the
- same shape as `attn_probs`
- """
- batch_size, seq_len, num_heads, head_dim = value.size()
- assert seq_len % (window_overlap * 2) == 0
- assert attn_probs.size()[:3] == value.size()[:3]
- assert attn_probs.size(3) == 2 * window_overlap + 1
- chunks_count = torch.div(seq_len, window_overlap, rounding_mode="trunc") - 1
- # group batch_size and num_heads dimensions into one, then chunk seq_len into chunks of size 2 window overlap
- chunked_attn_probs = attn_probs.transpose(1, 2).reshape(
- batch_size * num_heads,
- torch.div(seq_len, window_overlap, rounding_mode="trunc"),
- window_overlap,
- 2 * window_overlap + 1,
- )
- # group batch_size and num_heads dimensions into one
- value = value.transpose(1, 2).reshape(batch_size * num_heads, seq_len, head_dim)
- # pad seq_len with w at the beginning of the sequence and another window overlap at the end
- padded_value = nn.functional.pad(value, (0, 0, window_overlap, window_overlap), value=-1)
- # chunk padded_value into chunks of size 3 window overlap and an overlap of size window overlap
- chunked_value_size = (batch_size * num_heads, chunks_count + 1, 3 * window_overlap, head_dim)
- chunked_value_stride = padded_value.stride()
- chunked_value_stride = (
- chunked_value_stride[0],
- window_overlap * chunked_value_stride[1],
- chunked_value_stride[1],
- chunked_value_stride[2],
- )
- chunked_value = padded_value.as_strided(size=chunked_value_size, stride=chunked_value_stride)
- chunked_attn_probs = self._pad_and_diagonalize(chunked_attn_probs)
- context = torch.einsum("bcwd,bcdh->bcwh", (chunked_attn_probs, chunked_value))
- return context.view(batch_size, num_heads, seq_len, head_dim).transpose(1, 2)
- @staticmethod
- def _get_global_attn_indices(is_index_global_attn):
- """compute global attn indices required throughout forward pass"""
- # helper variable
- num_global_attn_indices = is_index_global_attn.long().sum(dim=1)
- # max number of global attn indices in batch
- max_num_global_attn_indices = num_global_attn_indices.max()
- # indices of global attn
- is_index_global_attn_nonzero = is_index_global_attn.nonzero(as_tuple=True)
- # helper variable
- is_local_index_global_attn = torch.arange(
- max_num_global_attn_indices, device=is_index_global_attn.device
- ) < num_global_attn_indices.unsqueeze(dim=-1)
- # location of the non-padding values within global attention indices
- is_local_index_global_attn_nonzero = is_local_index_global_attn.nonzero(as_tuple=True)
- # location of the padding values within global attention indices
- is_local_index_no_global_attn_nonzero = (is_local_index_global_attn == 0).nonzero(as_tuple=True)
- return (
- max_num_global_attn_indices,
- is_index_global_attn_nonzero,
- is_local_index_global_attn_nonzero,
- is_local_index_no_global_attn_nonzero,
- )
- def _concat_with_global_key_attn_probs(
- self,
- key_vectors,
- query_vectors,
- max_num_global_attn_indices,
- is_index_global_attn_nonzero,
- is_local_index_global_attn_nonzero,
- is_local_index_no_global_attn_nonzero,
- ):
- batch_size = key_vectors.shape[0]
- # create only global key vectors
- key_vectors_only_global = key_vectors.new_zeros(
- batch_size, max_num_global_attn_indices, self.num_heads, self.head_dim
- )
- key_vectors_only_global[is_local_index_global_attn_nonzero] = key_vectors[is_index_global_attn_nonzero]
- # (batch_size, seq_len, num_heads, max_num_global_attn_indices)
- attn_probs_from_global_key = torch.einsum("blhd,bshd->blhs", (query_vectors, key_vectors_only_global))
- # need to transpose since ONNX export only supports consecutive indexing: https://pytorch.org/docs/stable/onnx.html#writes-sets
- attn_probs_from_global_key = attn_probs_from_global_key.transpose(1, 3)
- attn_probs_from_global_key[
- is_local_index_no_global_attn_nonzero[0], is_local_index_no_global_attn_nonzero[1], :, :
- ] = torch.finfo(attn_probs_from_global_key.dtype).min
- attn_probs_from_global_key = attn_probs_from_global_key.transpose(1, 3)
- return attn_probs_from_global_key
- def _compute_attn_output_with_global_indices(
- self,
- value_vectors,
- attn_probs,
- max_num_global_attn_indices,
- is_index_global_attn_nonzero,
- is_local_index_global_attn_nonzero,
- ):
- batch_size = attn_probs.shape[0]
- # cut local attn probs to global only
- attn_probs_only_global = attn_probs.narrow(-1, 0, max_num_global_attn_indices)
- # get value vectors for global only
- value_vectors_only_global = value_vectors.new_zeros(
- batch_size, max_num_global_attn_indices, self.num_heads, self.head_dim
- )
- value_vectors_only_global[is_local_index_global_attn_nonzero] = value_vectors[is_index_global_attn_nonzero]
- # use `matmul` because `einsum` crashes sometimes with fp16
- # attn = torch.einsum('blhs,bshd->blhd', (selected_attn_probs, selected_v))
- # compute attn output only global
- attn_output_only_global = torch.matmul(
- attn_probs_only_global.transpose(1, 2).clone(), value_vectors_only_global.transpose(1, 2).clone()
- ).transpose(1, 2)
- # reshape attn probs
- attn_probs_without_global = attn_probs.narrow(
- -1, max_num_global_attn_indices, attn_probs.size(-1) - max_num_global_attn_indices
- ).contiguous()
- # compute attn output with global
- attn_output_without_global = self._sliding_chunks_matmul_attn_probs_value(
- attn_probs_without_global, value_vectors, self.one_sided_attn_window_size
- )
- return attn_output_only_global + attn_output_without_global
- def _compute_global_attn_output_from_hidden(
- self,
- hidden_states,
- max_num_global_attn_indices,
- is_local_index_global_attn_nonzero,
- is_index_global_attn_nonzero,
- is_local_index_no_global_attn_nonzero,
- is_index_masked,
- ):
- seq_len, batch_size = hidden_states.shape[:2]
- # prepare global hidden states
- global_attn_hidden_states = hidden_states.new_zeros(max_num_global_attn_indices, batch_size, self.embed_dim)
- global_attn_hidden_states[is_local_index_global_attn_nonzero[::-1]] = hidden_states[
- is_index_global_attn_nonzero[::-1]
- ]
- # global key, query, value
- global_query_vectors_only_global = self.query_global(global_attn_hidden_states)
- global_key_vectors = self.key_global(hidden_states)
- global_value_vectors = self.value_global(hidden_states)
- # normalize
- global_query_vectors_only_global /= math.sqrt(self.head_dim)
- # reshape
- global_query_vectors_only_global = (
- global_query_vectors_only_global.contiguous()
- .view(max_num_global_attn_indices, batch_size * self.num_heads, self.head_dim)
- .transpose(0, 1)
- ) # (batch_size * self.num_heads, max_num_global_attn_indices, head_dim)
- global_key_vectors = (
- global_key_vectors.contiguous().view(-1, batch_size * self.num_heads, self.head_dim).transpose(0, 1)
- ) # batch_size * self.num_heads, seq_len, head_dim)
- global_value_vectors = (
- global_value_vectors.contiguous().view(-1, batch_size * self.num_heads, self.head_dim).transpose(0, 1)
- ) # batch_size * self.num_heads, seq_len, head_dim)
- # compute attn scores
- global_attn_scores = torch.bmm(global_query_vectors_only_global, global_key_vectors.transpose(1, 2))
- assert list(global_attn_scores.size()) == [
- batch_size * self.num_heads,
- max_num_global_attn_indices,
- seq_len,
- ], (
- "global_attn_scores have the wrong size. Size should be"
- f" {(batch_size * self.num_heads, max_num_global_attn_indices, seq_len)}, but is"
- f" {global_attn_scores.size()}."
- )
- global_attn_scores = global_attn_scores.view(batch_size, self.num_heads, max_num_global_attn_indices, seq_len)
- # need to transpose since ONNX export only supports consecutive indexing: https://pytorch.org/docs/stable/onnx.html#writes-sets
- global_attn_scores = global_attn_scores.transpose(1, 2)
- global_attn_scores[
- is_local_index_no_global_attn_nonzero[0], is_local_index_no_global_attn_nonzero[1], :, :
- ] = torch.finfo(global_attn_scores.dtype).min
- global_attn_scores = global_attn_scores.transpose(1, 2)
- global_attn_scores = global_attn_scores.masked_fill(
- is_index_masked[:, None, None, :],
- torch.finfo(global_attn_scores.dtype).min,
- )
- global_attn_scores = global_attn_scores.view(batch_size * self.num_heads, max_num_global_attn_indices, seq_len)
- # compute global attn probs
- global_attn_probs_float = nn.functional.softmax(
- global_attn_scores, dim=-1, dtype=torch.float32
- ) # use fp32 for numerical stability
- global_attn_probs = nn.functional.dropout(
- global_attn_probs_float.type_as(global_attn_scores), p=self.dropout, training=self.training
- )
- # global attn output
- global_attn_output = torch.bmm(global_attn_probs, global_value_vectors)
- assert list(global_attn_output.size()) == [
- batch_size * self.num_heads,
- max_num_global_attn_indices,
- self.head_dim,
- ], (
- "global_attn_output tensor has the wrong size. Size should be"
- f" {(batch_size * self.num_heads, max_num_global_attn_indices, self.head_dim)}, but is"
- f" {global_attn_output.size()}."
- )
- global_attn_probs = global_attn_probs.view(batch_size, self.num_heads, max_num_global_attn_indices, seq_len)
- global_attn_output = global_attn_output.view(
- batch_size, self.num_heads, max_num_global_attn_indices, self.head_dim
- )
- return global_attn_output, global_attn_probs
- class LEDEncoderAttention(nn.Module):
- def __init__(self, config, layer_id):
- super().__init__()
- self.longformer_self_attn = LEDEncoderSelfAttention(config, layer_id=layer_id)
- self.output = nn.Linear(config.d_model, config.d_model)
- def forward(
- self,
- hidden_states: torch.Tensor,
- attention_mask: torch.Tensor | None = None,
- is_index_masked: torch.Tensor | None = None,
- is_index_global_attn: torch.Tensor | None = None,
- is_global_attn: bool | None = None,
- output_attentions: bool = False,
- ) -> tuple[torch.Tensor, torch.Tensor | None, tuple[torch.Tensor] | None]:
- """Input shape: Batch x Time x Channel"""
- self_outputs = self.longformer_self_attn(
- hidden_states=hidden_states,
- attention_mask=attention_mask,
- is_index_masked=is_index_masked,
- is_index_global_attn=is_index_global_attn,
- is_global_attn=is_global_attn,
- output_attentions=output_attentions,
- )
- attn_output = self.output(self_outputs[0])
- outputs = (attn_output,) + self_outputs[1:]
- return outputs
- class LEDDecoderAttention(nn.Module):
- """Multi-headed attention from 'Attention Is All You Need' paper"""
- def __init__(
- self,
- embed_dim: int,
- num_heads: int,
- dropout: float | None = 0.0,
- is_decoder: bool | None = False,
- bias: bool | None = True,
- layer_idx: bool | None = None,
- ):
- super().__init__()
- self.embed_dim = embed_dim
- self.num_heads = num_heads
- self.dropout = dropout
- self.head_dim = embed_dim // num_heads
- if self.head_dim * num_heads != self.embed_dim:
- raise ValueError(
- f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:"
- f" {num_heads})."
- )
- self.scaling = self.head_dim**-0.5
- self.is_decoder = is_decoder
- self.layer_idx = layer_idx
- self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
- self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
- self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
- self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
- def forward(
- self,
- hidden_states: torch.Tensor,
- key_value_states: torch.Tensor | None = None,
- past_key_values: Cache | None = None,
- attention_mask: torch.Tensor | None = None,
- output_attentions: bool = False,
- ) -> tuple[torch.Tensor, torch.Tensor | None, Cache | None]:
- """Input shape: Batch x Time x Channel"""
- # if key_value_states are provided this layer is used as a cross-attention layer
- # for the decoder
- is_cross_attention = key_value_states is not None
- bsz, tgt_len, embed_dim = hidden_states.size()
- # get query proj
- query_states = self.q_proj(hidden_states) * self.scaling
- is_updated = False
- if past_key_values is not None:
- if isinstance(past_key_values, EncoderDecoderCache):
- is_updated = past_key_values.is_updated.get(self.layer_idx)
- if is_cross_attention:
- # after the first generated id, we can subsequently re-use all key/value_states from cache
- curr_past_key_values = past_key_values.cross_attention_cache
- else:
- curr_past_key_values = past_key_values.self_attention_cache
- else:
- curr_past_key_values = past_key_values
- current_states = key_value_states if is_cross_attention else hidden_states
- if is_cross_attention and past_key_values is not None and is_updated:
- # reuse k,v, cross_attentions
- key_states = curr_past_key_values.layers[self.layer_idx].keys
- value_states = curr_past_key_values.layers[self.layer_idx].values
- else:
- key_states = self.k_proj(current_states)
- value_states = self.v_proj(current_states)
- key_states = key_states.view(bsz, -1, self.num_heads, self.head_dim).transpose(1, 2)
- value_states = value_states.view(bsz, -1, self.num_heads, self.head_dim).transpose(1, 2)
- if past_key_values is not None:
- # save all key/value_states to cache to be re-used for fast auto-regressive generation
- key_states, value_states = curr_past_key_values.update(key_states, value_states, self.layer_idx)
- # set flag that curr layer for cross-attn is already updated so we can re-use in subsequent calls
- if is_cross_attention and isinstance(past_key_values, EncoderDecoderCache):
- past_key_values.is_updated[self.layer_idx] = True
- proj_shape = (bsz * self.num_heads, -1, self.head_dim)
- query_states = query_states.view(bsz, tgt_len, self.num_heads, self.head_dim).transpose(1, 2)
- query_states = query_states.reshape(*proj_shape)
- key_states = key_states.reshape(*proj_shape)
- value_states = value_states.reshape(*proj_shape)
- src_len = key_states.size(1)
- attn_weights = torch.bmm(query_states, key_states.transpose(1, 2))
- if attn_weights.size() != (bsz * self.num_heads, tgt_len, src_len):
- raise ValueError(
- f"Attention weights should be of size {(bsz * self.num_heads, tgt_len, src_len)}, but is"
- f" {attn_weights.size()}"
- )
- if attention_mask is not None:
- if attention_mask.size() != (bsz, 1, tgt_len, src_len):
- raise ValueError(
- f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is {attention_mask.size()}"
- )
- attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + attention_mask
- attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
- attn_weights = nn.functional.softmax(attn_weights, dim=-1)
- if output_attentions:
- # this operation is a bit awkward, but it's required to
- # make sure that attn_weights keeps its gradient.
- # In order to do so, attn_weights have to be reshaped
- # twice and have to be reused in the following
- attn_weights_reshaped = attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
- attn_weights = attn_weights_reshaped.view(bsz * self.num_heads, tgt_len, src_len)
- else:
- attn_weights_reshaped = None
- attn_probs = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
- attn_output = torch.bmm(attn_probs, value_states)
- if attn_output.size() != (bsz * self.num_heads, tgt_len, self.head_dim):
- raise ValueError(
- f"`attn_output` should be of size {(bsz, self.num_heads, tgt_len, self.head_dim)}, but is"
- f" {attn_output.size()}"
- )
- attn_output = (
- attn_output.view(bsz, self.num_heads, tgt_len, self.head_dim)
- .transpose(1, 2)
- .reshape(bsz, tgt_len, embed_dim)
- )
- attn_output = self.out_proj(attn_output)
- return attn_output, attn_weights_reshaped, past_key_values
- class LEDEncoderLayer(GradientCheckpointingLayer):
- def __init__(self, config: LEDConfig, layer_id: int):
- super().__init__()
- self.embed_dim = config.d_model
- self.self_attn = LEDEncoderAttention(config, layer_id)
- self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim)
- self.dropout = config.dropout
- self.activation_fn = ACT2FN[config.activation_function]
- self.activation_dropout = config.activation_dropout
- self.fc1 = nn.Linear(self.embed_dim, config.encoder_ffn_dim)
- self.fc2 = nn.Linear(config.encoder_ffn_dim, self.embed_dim)
- self.final_layer_norm = nn.LayerNorm(self.embed_dim)
- def forward(
- self,
- hidden_states: torch.Tensor,
- attention_mask: torch.Tensor,
- is_index_masked=None,
- is_index_global_attn=None,
- is_global_attn=None,
- output_attentions=False,
- ):
- """
- Args:
- hidden_states (`torch.FloatTensor`): input to the layer of shape *(batch, seq_len, embed_dim)*
- attention_mask (`torch.FloatTensor`): attention mask of size
- *(batch, 1, tgt_len, src_len)* where padding elements are indicated by very large negative values.
- """
- residual = hidden_states
- attn_outputs = self.self_attn(
- hidden_states=hidden_states,
- attention_mask=attention_mask,
- is_index_masked=is_index_masked,
- is_index_global_attn=is_index_global_attn,
- is_global_attn=is_global_attn,
- output_attentions=output_attentions,
- )
- hidden_states = attn_outputs[0]
- hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
- hidden_states = residual + hidden_states
- hidden_states = self.self_attn_layer_norm(hidden_states)
- residual = hidden_states
- hidden_states = self.activation_fn(self.fc1(hidden_states))
- hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training)
- hidden_states = self.fc2(hidden_states)
- hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
- hidden_states = residual + hidden_states
- hidden_states = self.final_layer_norm(hidden_states)
- if hidden_states.dtype == torch.float16 and not torch.isfinite(hidden_states).all():
- clamp_value = torch.finfo(hidden_states.dtype).max - 1000
- hidden_states = torch.clamp(hidden_states, min=-clamp_value, max=clamp_value)
- return (hidden_states,) + attn_outputs[1:]
- class LEDDecoderLayer(GradientCheckpointingLayer):
- def __init__(self, config: LEDConfig, layer_idx=None):
- super().__init__()
- self.embed_dim = config.d_model
- self.self_attn = LEDDecoderAttention(
- embed_dim=self.embed_dim,
- num_heads=config.decoder_attention_heads,
- dropout=config.attention_dropout,
- is_decoder=True,
- layer_idx=layer_idx,
- )
- self.dropout = config.dropout
- self.activation_fn = ACT2FN[config.activation_function]
- self.activation_dropout = config.activation_dropout
- self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim)
- self.encoder_attn = LEDDecoderAttention(
- self.embed_dim,
- config.decoder_attention_heads,
- dropout=config.attention_dropout,
- is_decoder=True,
- layer_idx=layer_idx,
- )
- self.encoder_attn_layer_norm = nn.LayerNorm(self.embed_dim)
- self.fc1 = nn.Linear(self.embed_dim, config.decoder_ffn_dim)
- self.fc2 = nn.Linear(config.decoder_ffn_dim, self.embed_dim)
- self.final_layer_norm = nn.LayerNorm(self.embed_dim)
- def forward(
- self,
- hidden_states: torch.Tensor,
- attention_mask: torch.Tensor | None = None,
- encoder_hidden_states: torch.Tensor | None = None,
- encoder_attention_mask: torch.Tensor | None = None,
- past_key_values: Cache | None = None,
- output_attentions: bool | None = False,
- use_cache: bool | None = True,
- **kwargs,
- ):
- """
- Args:
- hidden_states (`torch.FloatTensor`): input to the layer of shape *(batch, seq_len, embed_dim)*
- attention_mask (`torch.FloatTensor`): attention mask of size
- *(batch, 1, tgt_len, src_len)* where padding elements are indicated by very large negative values.
- encoder_hidden_states (`torch.FloatTensor`):
- cross attention input to the layer of shape *(batch, seq_len, embed_dim)*
- encoder_attention_mask (`torch.FloatTensor`): encoder attention mask of size
- *(batch, 1, tgt_len, src_len)* where padding elements are indicated by very large negative values.
- past_key_values (`Cache`): cached past key and value projection states
- output_attentions (`bool`): Whether the base model outputs attentions.
- This requires the attentions tensor to be reshaped in this function.
- """
- residual = hidden_states
- # Self-Attention
- hidden_states, self_attn_weights, present_key_value = self.self_attn(
- hidden_states=hidden_states,
- past_key_values=past_key_values,
- attention_mask=attention_mask,
- output_attentions=output_attentions,
- )
- hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
- hidden_states = residual + hidden_states
- hidden_states = self.self_attn_layer_norm(hidden_states)
- # Cross-Attention Block
- cross_attn_present_key_value = None
- cross_attn_weights = None
- if encoder_hidden_states is not None:
- residual = hidden_states
- hidden_states, cross_attn_weights, cross_attn_present_key_value = self.encoder_attn(
- hidden_states=hidden_states,
- key_value_states=encoder_hidden_states,
- attention_mask=encoder_attention_mask,
- past_key_values=past_key_values,
- output_attentions=output_attentions,
- )
- hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
- hidden_states = residual + hidden_states
- hidden_states = self.encoder_attn_layer_norm(hidden_states)
- # Fully Connected
- residual = hidden_states
- hidden_states = self.activation_fn(self.fc1(hidden_states))
- hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training)
- hidden_states = self.fc2(hidden_states)
- hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
- hidden_states = residual + hidden_states
- hidden_states = self.final_layer_norm(hidden_states)
- outputs = (hidden_states,)
- if output_attentions:
- outputs += (self_attn_weights, cross_attn_weights)
- if use_cache:
- outputs += (past_key_values,)
- return outputs
- class LEDClassificationHead(nn.Module):
- """Head for sentence-level classification tasks."""
- def __init__(
- self,
- input_dim: int,
- inner_dim: int,
- num_classes: int,
- pooler_dropout: float,
- ):
- super().__init__()
- self.dense = nn.Linear(input_dim, inner_dim)
- self.dropout = nn.Dropout(p=pooler_dropout)
- self.out_proj = nn.Linear(inner_dim, num_classes)
- def forward(self, hidden_states: torch.Tensor):
- hidden_states = self.dropout(hidden_states)
- hidden_states = self.dense(hidden_states)
- hidden_states = torch.tanh(hidden_states)
- hidden_states = self.dropout(hidden_states)
- hidden_states = self.out_proj(hidden_states)
- return hidden_states
- @auto_docstring
- class LEDPreTrainedModel(PreTrainedModel):
- config: LEDConfig
- base_model_prefix = "led"
- supports_gradient_checkpointing = True
- @property
- def dummy_inputs(self):
- pad_token = self.config.pad_token_id
- input_ids = torch.tensor([[0, 6, 10, 4, 2], [0, 8, 12, 2, pad_token]], device=self.device)
- dummy_inputs = {
- "attention_mask": input_ids.ne(pad_token),
- "input_ids": input_ids,
- }
- return dummy_inputs
- def _init_weights(self, module):
- super()._init_weights(module)
- if isinstance(module, LEDForConditionalGeneration):
- init.zeros_(module.final_logits_bias)
- @dataclass
- @auto_docstring(
- custom_intro="""
- Base class for LEDEncoder's outputs, with potential hidden states, local and global attentions.
- """
- )
- # Copied from transformers.models.longformer.modeling_longformer.LongformerBaseModelOutput with Longformer->LEDEncoder
- class LEDEncoderBaseModelOutput(ModelOutput):
- r"""
- attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
- Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, x +
- attention_window + 1)`, where `x` is the number of tokens with global attention mask.
- Local attentions weights after the attention softmax, used to compute the weighted average in the
- self-attention heads. Those are the attention weights from every token in the sequence to every token with
- global attention (first `x` values) and to every token in the attention window (remaining `attention_window
- + 1` values). Note that the first `x` values refer to tokens with fixed positions in the text, but the
- remaining `attention_window + 1` values refer to tokens with relative positions: the attention weight of a
- token to itself is located at index `x + attention_window / 2` and the `attention_window / 2` preceding
- (succeeding) values are the attention weights to the `attention_window / 2` preceding (succeeding) tokens.
- If the attention window contains a token with global attention, the attention weight at the corresponding
- index is set to 0; the value should be accessed from the first `x` attention weights. If a token has global
- attention, the attention weights to all other tokens in `attentions` is set to 0, the values should be
- accessed from `global_attentions`.
- global_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
- Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, x)`,
- where `x` is the number of tokens with global attention mask.
- Global attentions weights after the attention softmax, used to compute the weighted average in the
- self-attention heads. Those are the attention weights from every token with global attention to every token
- in the sequence.
- """
- last_hidden_state: torch.FloatTensor
- hidden_states: tuple[torch.FloatTensor, ...] | None = None
- attentions: tuple[torch.FloatTensor, ...] | None = None
- global_attentions: tuple[torch.FloatTensor, ...] | None = None
- @dataclass
- @auto_docstring(
- custom_intro="""
- Base class for model encoder's outputs that also contains : pre-computed hidden states that can speed up sequential
- decoding.
- """
- )
- class LEDSeq2SeqModelOutput(ModelOutput):
- r"""
- last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
- Sequence of hidden-states at the output of the last layer of the decoder of the model.
- If `past_key_values` is used only the last hidden-state of the sequences of shape `(batch_size, 1,
- hidden_size)` is output.
- past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
- It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).
- Contains pre-computed hidden-states (key and values in the attention blocks) of the decoder that can be
- used (see `past_key_values` input) to speed up sequential decoding.
- encoder_global_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
- Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, x)`,
- where `x` is the number of tokens with global attention mask.
- Global attentions weights after the attention softmax, used to compute the weighted average in the
- self-attention heads. Those are the attention weights from every token with global attention to every token
- in the sequence.
- """
- last_hidden_state: torch.FloatTensor | None = None
- past_key_values: Cache | None = None
- decoder_hidden_states: tuple[torch.FloatTensor, ...] | None = None
- decoder_attentions: tuple[torch.FloatTensor, ...] | None = None
- cross_attentions: tuple[torch.FloatTensor, ...] | None = None
- encoder_last_hidden_state: torch.FloatTensor | None = None
- encoder_hidden_states: tuple[torch.FloatTensor, ...] | None = None
- encoder_attentions: tuple[torch.FloatTensor, ...] | None = None
- encoder_global_attentions: tuple[torch.FloatTensor, ...] | None = None
- @dataclass
- @auto_docstring(
- custom_intro="""
- Base class for sequence-to-sequence language models outputs.
- """
- )
- class LEDSeq2SeqLMOutput(ModelOutput):
- r"""
- loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
- Language modeling loss.
- logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
- Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
- past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
- It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).
- Contains pre-computed hidden-states (key and values in the attention blocks) of the decoder that can be
- used (see `past_key_values` input) to speed up sequential decoding.
- encoder_global_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
- Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, x)`,
- where `x` is the number of tokens with global attention mask.
- Global attentions weights after the attention softmax, used to compute the weighted average in the
- self-attention heads. Those are the attention weights from every token with global attention to every token
- in the sequence.
- """
- loss: torch.FloatTensor | None = None
- logits: torch.FloatTensor | None = None
- past_key_values: Cache | None = None
- decoder_hidden_states: tuple[torch.FloatTensor, ...] | None = None
- decoder_attentions: tuple[torch.FloatTensor, ...] | None = None
- cross_attentions: tuple[torch.FloatTensor, ...] | None = None
- encoder_last_hidden_state: torch.FloatTensor | None = None
- encoder_hidden_states: tuple[torch.FloatTensor, ...] | None = None
- encoder_attentions: tuple[torch.FloatTensor, ...] | None = None
- encoder_global_attentions: tuple[torch.FloatTensor, ...] | None = None
- @dataclass
- @auto_docstring(
- custom_intro="""
- Base class for outputs of sequence-to-sequence sentence classification models.
- """
- )
- class LEDSeq2SeqSequenceClassifierOutput(ModelOutput):
- r"""
- loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `label` is provided):
- Classification (or regression if config.num_labels==1) loss.
- logits (`torch.FloatTensor` of shape `(batch_size, config.num_labels)`):
- Classification (or regression if config.num_labels==1) scores (before SoftMax).
- past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
- It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).
- Contains pre-computed hidden-states (key and values in the attention blocks) of the decoder that can be
- used (see `past_key_values` input) to speed up sequential decoding.
- encoder_global_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
- Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, x)`,
- where `x` is the number of tokens with global attention mask.
- Global attentions weights after the attention softmax, used to compute the weighted average in the
- self-attention heads. Those are the attention weights from every token with global attention to every token
- in the sequence.
- """
- loss: torch.FloatTensor | None = None
- logits: torch.FloatTensor | None = None
- past_key_values: Cache | None = None
- decoder_hidden_states: tuple[torch.FloatTensor, ...] | None = None
- decoder_attentions: tuple[torch.FloatTensor, ...] | None = None
- cross_attentions: tuple[torch.FloatTensor, ...] | None = None
- encoder_last_hidden_state: torch.FloatTensor | None = None
- encoder_hidden_states: tuple[torch.FloatTensor, ...] | None = None
- encoder_attentions: tuple[torch.FloatTensor, ...] | None = None
- encoder_global_attentions: tuple[torch.FloatTensor, ...] | None = None
- @dataclass
- @auto_docstring(
- custom_intro="""
- Base class for outputs of sequence-to-sequence question answering models.
- """
- )
- class LEDSeq2SeqQuestionAnsweringModelOutput(ModelOutput):
- r"""
- loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
- Total span extraction loss is the sum of a Cross-Entropy for the start and end positions.
- past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
- It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).
- Contains pre-computed hidden-states (key and values in the attention blocks) of the decoder that can be
- used (see `past_key_values` input) to speed up sequential decoding.
- encoder_global_attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
- Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, x)`,
- where `x` is the number of tokens with global attention mask.
- Global attentions weights after the attention softmax, used to compute the weighted average in the
- self-attention heads. Those are the attention weights from every token with global attention to every token
- in the sequence.
- """
- loss: torch.FloatTensor | None = None
- start_logits: torch.FloatTensor | None = None
- end_logits: torch.FloatTensor | None = None
- past_key_values: Cache | None = None
- decoder_hidden_states: tuple[torch.FloatTensor, ...] | None = None
- decoder_attentions: tuple[torch.FloatTensor, ...] | None = None
- cross_attentions: tuple[torch.FloatTensor, ...] | None = None
- encoder_last_hidden_state: torch.FloatTensor | None = None
- encoder_hidden_states: tuple[torch.FloatTensor, ...] | None = None
- encoder_attentions: tuple[torch.FloatTensor, ...] | None = None
- encoder_global_attentions: tuple[torch.FloatTensor, ...] | None = None
- class LEDEncoder(LEDPreTrainedModel):
- """
- Transformer encoder consisting of *config.encoder_layers* self-attention layers. Each layer is a
- [`LEDEncoderLayer`].
- Args:
- config: LEDConfig
- embed_tokens (nn.Embedding): output embedding
- """
- def __init__(self, config: LEDConfig):
- super().__init__(config)
- self.dropout = config.dropout
- self.layerdrop = config.encoder_layerdrop
- embed_dim = config.d_model
- self.padding_idx = config.pad_token_id
- self.max_source_positions = config.max_encoder_position_embeddings
- if isinstance(config.attention_window, int):
- if config.attention_window % 2 != 0:
- raise ValueError("`config.attention_window` has to be an even value")
- if config.attention_window <= 0:
- raise ValueError("`config.attention_window` has to be positive")
- config.attention_window = [config.attention_window] * config.num_hidden_layers # one value per layer
- else:
- if len(config.attention_window) != config.num_hidden_layers:
- raise ValueError(
- "`len(config.attention_window)` should equal `config.num_hidden_layers`. "
- f"Expected {config.num_hidden_layers}, given {len(config.attention_window)}"
- )
- self.embed_tokens = nn.Embedding(config.vocab_size, embed_dim, self.padding_idx)
- self.embed_positions = LEDLearnedPositionalEmbedding(
- self.max_source_positions,
- embed_dim,
- )
- self.layers = nn.ModuleList([LEDEncoderLayer(config, i) for i in range(config.encoder_layers)])
- self.layernorm_embedding = nn.LayerNorm(embed_dim)
- self.gradient_checkpointing = False
- # Initialize weights and apply final processing
- self.post_init()
- def _merge_to_attention_mask(self, attention_mask: torch.Tensor, global_attention_mask: torch.Tensor):
- # longformer self-attention expects attention mask to have 0 (no attn), 1 (local attn), 2 (global attn)
- # (global_attention_mask + 1) => 1 for local attention, 2 for global attention
- # => final attention_mask => 0 for no attention, 1 for local attention 2 for global attention
- if attention_mask is not None:
- attention_mask = attention_mask * (global_attention_mask + 1)
- else:
- # simply use `global_attention_mask` as `attention_mask`
- # if no `attention_mask` is given
- attention_mask = global_attention_mask + 1
- return attention_mask
- def _pad_to_window_size(
- self,
- input_ids: torch.Tensor,
- attention_mask: torch.Tensor,
- inputs_embeds: torch.Tensor,
- pad_token_id: int,
- ):
- """A helper function to pad tokens and mask to work with implementation of Longformer self-attention."""
- # padding
- attention_window = (
- self.config.attention_window
- if isinstance(self.config.attention_window, int)
- else max(self.config.attention_window)
- )
- if attention_window % 2 != 0:
- raise ValueError(f"`attention_window` should be an even value. Given {attention_window}")
- input_shape = input_ids.shape if input_ids is not None else inputs_embeds.shape
- batch_size, seq_len = input_shape[:2]
- padding_len = (attention_window - seq_len % attention_window) % attention_window
- if padding_len > 0:
- logger.warning_once(
- f"Input ids are automatically padded from {seq_len} to {seq_len + padding_len} to be a multiple of "
- f"`config.attention_window`: {attention_window}"
- )
- if input_ids is not None:
- input_ids = nn.functional.pad(input_ids, (0, padding_len), value=pad_token_id)
- if inputs_embeds is not None:
- input_ids_padding = inputs_embeds.new_full(
- (batch_size, padding_len),
- self.config.pad_token_id,
- dtype=torch.long,
- )
- inputs_embeds_padding = self.embed_tokens(input_ids_padding)
- inputs_embeds = torch.cat([inputs_embeds, inputs_embeds_padding], dim=-2)
- attention_mask = nn.functional.pad(
- attention_mask, (0, padding_len), value=False
- ) # no attention on the padding tokens
- return padding_len, input_ids, attention_mask, inputs_embeds
- def forward(
- self,
- input_ids=None,
- attention_mask=None,
- global_attention_mask=None,
- inputs_embeds=None,
- output_attentions=None,
- output_hidden_states=None,
- return_dict=None,
- **kwargs,
- ):
- r"""
- Args:
- input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
- Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
- provide it.
- Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
- [`PreTrainedTokenizer.__call__`] for details.
- [What are input IDs?](../glossary#input-ids)
- attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
- Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
- - 1 for tokens that are **not masked**,
- - 0 for tokens that are **masked**.
- [What are attention masks?](../glossary#attention-mask)
- global_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
- Mask to decide the attention given on each token, local attention or global attention for the encoder.
- Tokens with global attention attends to all other tokens, and all other tokens attend to them. This is
- important for task-specific finetuning because it makes the model more flexible at representing the
- task. For example, for classification, the <s> token should be given global attention. For QA, all
- question tokens should also have global attention. Please refer to the [Longformer
- paper](https://huggingface.co/papers/2004.05150) for more details. Mask values selected in `[0, 1]`:
- - 0 for local attention (a sliding window attention),
- - 1 for global attention (tokens that attend to all other tokens, and all other tokens attend to them).
- inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
- Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
- This is useful if you want more control over how to convert `input_ids` indices into associated vectors
- than the model's internal embedding lookup matrix.
- output_attentions (`bool`, *optional*):
- Whether or not to return the attentions tensors of all attention layers. See `attentions` under
- returned tensors for more detail.
- output_hidden_states (`bool`, *optional*):
- Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
- for more detail.
- return_dict (`bool`, *optional*):
- Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
- """
- output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
- output_hidden_states = (
- output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
- )
- return_dict = return_dict if return_dict is not None else self.config.return_dict
- # check input_ids and inputs_embeds
- if input_ids is not None and inputs_embeds is not None:
- raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
- elif input_ids is None and inputs_embeds is None:
- raise ValueError("You have to specify either input_ids or inputs_embeds")
- if inputs_embeds is None:
- inputs_embeds = self.embed_tokens(input_ids)
- # create default attention_mask
- if attention_mask is None:
- attention_mask = torch.ones(inputs_embeds.size()[:-1], device=inputs_embeds.device, dtype=torch.long)
- # merge `global_attention_mask` and `attention_mask`
- if global_attention_mask is not None:
- attention_mask = self._merge_to_attention_mask(attention_mask, global_attention_mask)
- # pad input if necessary
- padding_len, input_ids, attention_mask, inputs_embeds = self._pad_to_window_size(
- input_ids=input_ids,
- attention_mask=attention_mask,
- inputs_embeds=inputs_embeds,
- pad_token_id=self.config.pad_token_id,
- )
- # retrieve input_shape
- if input_ids is not None:
- input_shape = input_ids.size()
- input_ids = input_ids.view(-1, input_shape[-1])
- elif inputs_embeds is not None:
- input_shape = inputs_embeds.size()[:-1]
- # convert attention_mask to float
- if attention_mask is not None:
- # [bsz, seq_len] -> [bsz, seq_len]; 1 -> 0.0; 0 -> "-inf"
- attention_mask = _prepare_4d_attention_mask_inverted(attention_mask, inputs_embeds.dtype)[:, 0, 0, :]
- # get masking tensors
- is_index_masked = attention_mask < 0
- is_index_global_attn = attention_mask > 0
- is_global_attn = is_index_global_attn.flatten().any().item()
- embed_pos = self.embed_positions(input_shape)
- hidden_states = inputs_embeds + embed_pos
- hidden_states = self.layernorm_embedding(hidden_states)
- hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
- encoder_states = () if output_hidden_states else None
- all_attentions = () if output_attentions else None
- all_global_attentions = () if (output_attentions and is_global_attn) else None
- for idx, encoder_layer in enumerate(self.layers):
- if output_hidden_states:
- encoder_states = encoder_states + (hidden_states,)
- # add LayerDrop (see https://huggingface.co/papers/1909.11556 for description)
- dropout_probability = torch.rand([])
- if self.training and (dropout_probability < self.layerdrop): # skip the layer
- layer_outputs = (None, None, None)
- else:
- layer_outputs = encoder_layer(
- hidden_states,
- attention_mask=attention_mask,
- is_index_masked=is_index_masked,
- is_index_global_attn=is_index_global_attn,
- is_global_attn=is_global_attn,
- output_attentions=output_attentions,
- )
- hidden_states = layer_outputs[0]
- if output_attentions:
- # 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)
- all_attentions = all_attentions + (layer_outputs[1].transpose(1, 2),)
- if is_global_attn:
- # bzs x num_attn_heads x num_global_attn x seq_len => bzs x num_attn_heads x seq_len x num_global_attn
- all_global_attentions = all_global_attentions + (layer_outputs[2].transpose(2, 3),)
- if output_hidden_states:
- encoder_states = encoder_states + (hidden_states,)
- # undo padding
- if padding_len > 0:
- # unpad `hidden_states` because the calling function is expecting a length == input_ids.size(1)
- hidden_states = hidden_states[:, :-padding_len]
- if output_hidden_states:
- encoder_states = tuple(state[:, :-padding_len] for state in encoder_states)
- if output_attentions:
- all_attentions = tuple(state[:, :, :-padding_len, :] for state in all_attentions)
- if not return_dict:
- return tuple(
- v for v in [hidden_states, encoder_states, all_attentions, all_global_attentions] if v is not None
- )
- return LEDEncoderBaseModelOutput(
- last_hidden_state=hidden_states,
- hidden_states=encoder_states,
- attentions=all_attentions,
- global_attentions=all_global_attentions,
- )
- class LEDDecoder(LEDPreTrainedModel):
- """
- Transformer decoder consisting of *config.decoder_layers* layers. Each layer is a [`LEDDecoderLayer`]
- Args:
- config: LEDConfig
- embed_tokens (nn.Embedding): output embedding
- """
- def __init__(self, config: LEDConfig):
- super().__init__(config)
- self.dropout = config.dropout
- self.layerdrop = config.decoder_layerdrop
- self.padding_idx = config.pad_token_id
- self.max_target_positions = config.max_decoder_position_embeddings
- self.embed_tokens = nn.Embedding(config.vocab_size, config.d_model, self.padding_idx)
- self.embed_positions = LEDLearnedPositionalEmbedding(
- self.max_target_positions,
- config.d_model,
- )
- self.layers = nn.ModuleList([LEDDecoderLayer(config, layer_idx=i) for i in range(config.decoder_layers)])
- self.layernorm_embedding = nn.LayerNorm(config.d_model)
- self.gradient_checkpointing = False
- # Initialize weights and apply final processing
- self.post_init()
- def forward(
- self,
- input_ids=None,
- attention_mask=None,
- global_attention_mask=None,
- encoder_hidden_states=None,
- encoder_attention_mask=None,
- past_key_values=None,
- inputs_embeds=None,
- use_cache=None,
- output_attentions=None,
- output_hidden_states=None,
- return_dict=None,
- **kwargs,
- ):
- r"""
- Args:
- input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
- Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
- provide it.
- Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
- [`PreTrainedTokenizer.__call__`] for details.
- [What are input IDs?](../glossary#input-ids)
- attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
- Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
- - 1 for tokens that are **not masked**,
- - 0 for tokens that are **masked**.
- [What are attention masks?](../glossary#attention-mask)
- global_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
- Mask to decide the attention given on each token, local attention or global attention. Tokens with
- global attention attends to all other tokens, and all other tokens attend to them. This is important
- for task-specific finetuning because it makes the model more flexible at representing the task. For
- example, for classification, the <s> token should be given global attention. For QA, all question
- tokens should also have global attention. Please refer to the [Longformer
- paper](https://huggingface.co/papers/2004.05150) for more details. Mask values selected in `[0, 1]`:
- - 0 for local attention (a sliding window attention),
- - 1 for global attention (tokens that attend to all other tokens, and all other tokens attend to them).
- encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, encoder_sequence_length, hidden_size)`, *optional*):
- Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
- of the decoder.
- encoder_attention_mask (`torch.LongTensor` of shape `(batch_size, encoder_sequence_length)`, *optional*):
- Mask to avoid performing cross-attention on padding tokens indices of encoder input_ids. Mask values
- selected in `[0, 1]`:
- - 1 for tokens that are **not masked**,
- - 0 for tokens that are **masked**.
- [What are attention masks?](../glossary#attention-mask)
- past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
- It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).
- Contains pre-computed hidden-states (key and values in the self-attention blocks and in the
- cross-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
- If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those
- that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of
- all `decoder_input_ids` of shape `(batch_size, sequence_length)`.
- inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
- Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
- This is useful if you want more control over how to convert `input_ids` indices into associated vectors
- than the model's internal embedding lookup matrix.
- output_attentions (`bool`, *optional*):
- Whether or not to return the attentions tensors of all attention layers. See `attentions` under
- returned tensors for more detail.
- output_hidden_states (`bool`, *optional*):
- Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
- for more detail.
- return_dict (`bool`, *optional*):
- Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
- """
- output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
- output_hidden_states = (
- output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
- )
- use_cache = use_cache if use_cache is not None else self.config.use_cache
- return_dict = return_dict if return_dict is not None else self.config.return_dict
- # retrieve input_ids and inputs_embeds
- if input_ids is not None and inputs_embeds is not None:
- raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
- elif input_ids is not None:
- input_shape = input_ids.size()
- input_ids = input_ids.view(-1, input_shape[-1])
- elif inputs_embeds is not None:
- input_shape = inputs_embeds.size()[:-1]
- else:
- raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
- if inputs_embeds is None:
- inputs_embeds = self.embed_tokens(input_ids)
- if self.gradient_checkpointing and self.training:
- if use_cache:
- logger.warning_once(
- "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
- )
- use_cache = False
- if use_cache and past_key_values is None:
- past_key_values = EncoderDecoderCache(DynamicCache(config=self.config), DynamicCache(config=self.config))
- past_key_values_length = past_key_values.get_seq_length() if past_key_values is not None else 0
- combined_attention_mask = None
- if input_shape[-1] > 1: # only create a causal mask when we go over a single token
- combined_attention_mask = create_causal_mask(
- config=self.config,
- inputs_embeds=inputs_embeds,
- attention_mask=attention_mask,
- past_key_values=past_key_values,
- )
- encoder_attention_mask = create_bidirectional_mask(
- config=self.config,
- inputs_embeds=inputs_embeds,
- attention_mask=encoder_attention_mask,
- encoder_hidden_states=encoder_hidden_states,
- )
- # embed positions
- positions = self.embed_positions(input_shape, past_key_values_length)
- hidden_states = inputs_embeds + positions
- hidden_states = self.layernorm_embedding(hidden_states)
- hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
- # decoder layers
- all_hidden_states = () if output_hidden_states else None
- all_self_attns = () if output_attentions else None
- all_cross_attentions = () if output_attentions else None
- for idx, decoder_layer in enumerate(self.layers):
- # add LayerDrop (see https://huggingface.co/papers/1909.11556 for description)
- if output_hidden_states:
- all_hidden_states += (hidden_states,)
- if self.training:
- dropout_probability = torch.rand([])
- if dropout_probability < self.layerdrop:
- continue
- layer_outputs = decoder_layer(
- hidden_states,
- combined_attention_mask,
- encoder_hidden_states, # as a positional argument for gradient checkpointing
- encoder_attention_mask=encoder_attention_mask,
- past_key_values=past_key_values,
- output_attentions=output_attentions,
- use_cache=use_cache,
- )
- hidden_states = layer_outputs[0]
- if output_attentions:
- all_self_attns += (layer_outputs[1],)
- all_cross_attentions += (layer_outputs[2],)
- # add hidden states from the last decoder layer
- if output_hidden_states:
- all_hidden_states += (hidden_states,)
- if not return_dict:
- return tuple(
- v
- for v in [hidden_states, past_key_values, all_hidden_states, all_self_attns, all_cross_attentions]
- if v is not None
- )
- return BaseModelOutputWithPastAndCrossAttentions(
- last_hidden_state=hidden_states,
- past_key_values=past_key_values,
- hidden_states=all_hidden_states,
- attentions=all_self_attns,
- cross_attentions=all_cross_attentions,
- )
- @auto_docstring
- class LEDModel(LEDPreTrainedModel):
- _tied_weights_keys = {
- "encoder.embed_tokens.weight": "shared.weight",
- "decoder.embed_tokens.weight": "shared.weight",
- }
- def __init__(self, config: LEDConfig):
- super().__init__(config)
- padding_idx, vocab_size = config.pad_token_id, config.vocab_size
- self.shared = nn.Embedding(vocab_size, config.d_model, padding_idx)
- self.encoder = LEDEncoder(config)
- self.decoder = LEDDecoder(config)
- # Initialize weights and apply final processing
- self.post_init()
- def get_input_embeddings(self):
- return self.shared
- def set_input_embeddings(self, value):
- self.shared = value
- self.encoder.embed_tokens = self.shared
- self.decoder.embed_tokens = self.shared
- @auto_docstring
- def forward(
- self,
- input_ids: torch.LongTensor | None = None,
- attention_mask: torch.Tensor | None = None,
- decoder_input_ids: torch.LongTensor | None = None,
- decoder_attention_mask: torch.LongTensor | None = None,
- encoder_outputs: tuple[tuple[torch.FloatTensor]] | None = None,
- global_attention_mask: torch.FloatTensor | None = None,
- past_key_values: Cache | None = None,
- inputs_embeds: torch.FloatTensor | None = None,
- decoder_inputs_embeds: torch.FloatTensor | None = None,
- use_cache: bool | None = None,
- output_attentions: bool | None = None,
- output_hidden_states: bool | None = None,
- return_dict: bool | None = None,
- **kwargs,
- ) -> tuple[torch.Tensor] | LEDSeq2SeqModelOutput:
- r"""
- decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
- Indices of decoder input sequence tokens in the vocabulary.
- Indices can be obtained using [`LedTokenizer`]. See [`PreTrainedTokenizer.encode`] and
- [`PreTrainedTokenizer.__call__`] for details.
- [What are input IDs?](../glossary#input-ids)
- LED uses the `eos_token_id` as the starting token for `decoder_input_ids` generation. If `past_key_values`
- is used, optionally only the last `decoder_input_ids` have to be input (see `past_key_values`).
- decoder_attention_mask (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
- Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
- be used by default.
- If you want to change padding behavior, you should read [`modeling_led._prepare_decoder_inputs`] and modify
- to your needs. See diagram 1 in [the paper](https://huggingface.co/papers/1910.13461) for more information on the
- default strategy.
- global_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
- Mask to decide the attention given on each token, local attention or global attention for the encoder.
- Tokens with global attention attends to all other tokens, and all other tokens attend to them. This is
- important for task-specific finetuning because it makes the model more flexible at representing the task.
- For example, for classification, the <s> token should be given global attention. For QA, all question
- tokens should also have global attention. Please refer to the [Longformer
- paper](https://huggingface.co/papers/2004.05150) for more details. Mask values selected in `[0, 1]`:
- - 0 for local attention (a sliding window attention),
- - 1 for global attention (tokens that attend to all other tokens, and all other tokens attend to them).
- """
- output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
- output_hidden_states = (
- output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
- )
- use_cache = use_cache if use_cache is not None else self.config.use_cache
- return_dict = return_dict if return_dict is not None else self.config.return_dict
- # Using this like Bart, as LED is derived from it. So far
- # No checkpoint on the hub exists that uses that in practice.
- # https://github.com/huggingface/transformers/blob/ac3cb660cad283163f7c73cad511124e845ca388/src/transformers/models/bart/modeling_bart.py#L1153
- if decoder_input_ids is None and decoder_inputs_embeds is None:
- decoder_input_ids = shift_tokens_right(
- input_ids, self.config.pad_token_id, self.config.decoder_start_token_id
- )
- if encoder_outputs is None:
- encoder_outputs = self.encoder(
- input_ids=input_ids,
- attention_mask=attention_mask,
- global_attention_mask=global_attention_mask,
- inputs_embeds=inputs_embeds,
- output_attentions=output_attentions,
- output_hidden_states=output_hidden_states,
- return_dict=return_dict,
- )
- # If the user passed a tuple for encoder_outputs, we wrap it in a LEDEncoderBaseModelOutput when return_dict=False
- elif return_dict and not isinstance(encoder_outputs, LEDEncoderBaseModelOutput):
- encoder_outputs = LEDEncoderBaseModelOutput(
- last_hidden_state=encoder_outputs[0],
- hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,
- attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,
- global_attentions=encoder_outputs[3] if len(encoder_outputs) > 3 else None,
- )
- # decoder outputs consists of (dec_features, past_key_values, dec_hidden, dec_attn)
- decoder_outputs = self.decoder(
- input_ids=decoder_input_ids,
- attention_mask=decoder_attention_mask,
- encoder_hidden_states=encoder_outputs[0],
- encoder_attention_mask=attention_mask,
- past_key_values=past_key_values,
- inputs_embeds=decoder_inputs_embeds,
- use_cache=use_cache,
- output_attentions=output_attentions,
- output_hidden_states=output_hidden_states,
- return_dict=return_dict,
- )
- if not return_dict:
- return decoder_outputs + encoder_outputs
- return LEDSeq2SeqModelOutput(
- last_hidden_state=decoder_outputs.last_hidden_state,
- past_key_values=decoder_outputs.past_key_values,
- decoder_hidden_states=decoder_outputs.hidden_states,
- decoder_attentions=decoder_outputs.attentions,
- cross_attentions=decoder_outputs.cross_attentions,
- encoder_last_hidden_state=encoder_outputs.last_hidden_state,
- encoder_hidden_states=encoder_outputs.hidden_states,
- encoder_attentions=encoder_outputs.attentions,
- encoder_global_attentions=encoder_outputs.global_attentions,
- )
- @auto_docstring(
- custom_intro="""
- The LED Model with a language modeling head. Can be used for summarization.
- """
- )
- class LEDForConditionalGeneration(LEDPreTrainedModel, GenerationMixin):
- base_model_prefix = "led"
- _keys_to_ignore_on_load_missing = ["final_logits_bias"]
- _tied_weights_keys = {
- "lm_head.weight": "led.shared.weight",
- }
- def __init__(self, config: LEDConfig):
- super().__init__(config)
- self.led = LEDModel(config)
- self.register_buffer("final_logits_bias", torch.zeros((1, self.led.shared.num_embeddings)))
- self.lm_head = nn.Linear(config.d_model, self.led.shared.num_embeddings, bias=False)
- # Initialize weights and apply final processing
- self.post_init()
- def resize_token_embeddings(
- self, new_num_tokens: int, pad_to_multiple_of: int | None = None, mean_resizing: bool = True
- ) -> nn.Embedding:
- new_embeddings = super().resize_token_embeddings(new_num_tokens, pad_to_multiple_of, mean_resizing)
- self._resize_final_logits_bias(new_embeddings.weight.shape[0])
- return new_embeddings
- def _resize_final_logits_bias(self, new_num_tokens: int) -> None:
- old_num_tokens = self.final_logits_bias.shape[-1]
- if new_num_tokens <= old_num_tokens:
- new_bias = self.final_logits_bias[:, :new_num_tokens]
- else:
- extra_bias = torch.zeros((1, new_num_tokens - old_num_tokens), device=self.final_logits_bias.device)
- new_bias = torch.cat([self.final_logits_bias, extra_bias], dim=1)
- self.register_buffer("final_logits_bias", new_bias)
- @auto_docstring
- def forward(
- self,
- input_ids: torch.LongTensor | None = None,
- attention_mask: torch.Tensor | None = None,
- decoder_input_ids: torch.LongTensor | None = None,
- decoder_attention_mask: torch.LongTensor | None = None,
- encoder_outputs: tuple[tuple[torch.FloatTensor]] | None = None,
- global_attention_mask: torch.FloatTensor | None = None,
- past_key_values: Cache | None = None,
- inputs_embeds: torch.FloatTensor | None = None,
- decoder_inputs_embeds: torch.FloatTensor | None = None,
- labels: torch.LongTensor | None = None,
- use_cache: bool | None = None,
- output_attentions: bool | None = None,
- output_hidden_states: bool | None = None,
- return_dict: bool | None = None,
- **kwargs,
- ) -> tuple[torch.Tensor] | LEDSeq2SeqLMOutput:
- r"""
- decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
- Indices of decoder input sequence tokens in the vocabulary.
- Indices can be obtained using [`LedTokenizer`]. See [`PreTrainedTokenizer.encode`] and
- [`PreTrainedTokenizer.__call__`] for details.
- [What are input IDs?](../glossary#input-ids)
- LED uses the `eos_token_id` as the starting token for `decoder_input_ids` generation. If `past_key_values`
- is used, optionally only the last `decoder_input_ids` have to be input (see `past_key_values`).
- decoder_attention_mask (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
- Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
- be used by default.
- If you want to change padding behavior, you should read [`modeling_led._prepare_decoder_inputs`] and modify
- to your needs. See diagram 1 in [the paper](https://huggingface.co/papers/1910.13461) for more information on the
- default strategy.
- global_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
- Mask to decide the attention given on each token, local attention or global attention for the encoder.
- Tokens with global attention attends to all other tokens, and all other tokens attend to them. This is
- important for task-specific finetuning because it makes the model more flexible at representing the task.
- For example, for classification, the <s> token should be given global attention. For QA, all question
- tokens should also have global attention. Please refer to the [Longformer
- paper](https://huggingface.co/papers/2004.05150) for more details. Mask values selected in `[0, 1]`:
- - 0 for local attention (a sliding window attention),
- - 1 for global attention (tokens that attend to all other tokens, and all other tokens attend to them).
- labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
- Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
- config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
- (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
- Example Summarization:
- ```python
- >>> import torch
- >>> from transformers import AutoTokenizer, LEDForConditionalGeneration
- >>> model = LEDForConditionalGeneration.from_pretrained("allenai/led-large-16384-arxiv")
- >>> tokenizer = AutoTokenizer.from_pretrained("allenai/led-large-16384-arxiv")
- >>> ARTICLE_TO_SUMMARIZE = '''Transformers (Vaswani et al., 2017) have achieved state-of-the-art
- ... results in a wide range of natural language tasks including generative language modeling
- ... (Dai et al., 2019; Radford et al., 2019) and discriminative ... language understanding (Devlin et al., 2019).
- ... This success is partly due to the self-attention component which enables the network to capture contextual
- ... information from the entire sequence. While powerful, the memory and computational requirements of
- ... self-attention grow quadratically with sequence length, making it infeasible (or very expensive) to
- ... process long sequences. To address this limitation, we present Longformer, a modified Transformer
- ... architecture with a self-attention operation that scales linearly with the sequence length, making it
- ... versatile for processing long documents (Fig 1). This is an advantage for natural language tasks such as
- ... long document classification, question answering (QA), and coreference resolution, where existing approaches
- ... partition or shorten the long context into smaller sequences that fall within the typical 512 token limit
- ... of BERT-style pretrained models. Such partitioning could potentially result in loss of important
- ... cross-partition information, and to mitigate this problem, existing methods often rely on complex
- ... architectures to address such interactions. On the other hand, our proposed Longformer is able to build
- ... contextual representations of the entire context using multiple layers of attention, reducing the need for
- ... task-specific architectures.'''
- >>> inputs = tokenizer.encode(ARTICLE_TO_SUMMARIZE, return_tensors="pt")
- >>> # Global attention on the first token (cf. Beltagy et al. 2020)
- >>> global_attention_mask = torch.zeros_like(inputs)
- >>> global_attention_mask[:, 0] = 1
- >>> # Generate Summary
- >>> summary_ids = model.generate(inputs, global_attention_mask=global_attention_mask, num_beams=3, max_length=32)
- >>> print(tokenizer.decode(summary_ids[0], skip_special_tokens=True, clean_up_tokenization_spaces=True))
- ```
- Example Conditional generation :
- ```python
- >>> from transformers import AutoTokenizer, LEDForConditionalGeneration
- >>> tokenizer = AutoTokenizer.from_pretrained("allenai/led-base-16384")
- >>> TXT = "My friends are <mask> but they eat too many carbs."
- >>> model = LEDForConditionalGeneration.from_pretrained("allenai/led-base-16384")
- >>> input_ids = tokenizer([TXT], return_tensors="pt")["input_ids"]
- >>> prediction = model.generate(input_ids)[0]
- >>> print(tokenizer.decode(prediction, skip_special_tokens=True))
- ```
- """
- return_dict = return_dict if return_dict is not None else self.config.return_dict
- if labels is not None:
- if use_cache:
- logger.warning("The `use_cache` argument is changed to `False` since `labels` is provided.")
- use_cache = False
- if decoder_input_ids is None and decoder_inputs_embeds is None:
- decoder_input_ids = shift_tokens_right(
- labels, self.config.pad_token_id, self.config.decoder_start_token_id
- )
- outputs = self.led(
- input_ids,
- attention_mask=attention_mask,
- decoder_input_ids=decoder_input_ids,
- decoder_attention_mask=decoder_attention_mask,
- encoder_outputs=encoder_outputs,
- global_attention_mask=global_attention_mask,
- past_key_values=past_key_values,
- inputs_embeds=inputs_embeds,
- decoder_inputs_embeds=decoder_inputs_embeds,
- use_cache=use_cache,
- output_attentions=output_attentions,
- output_hidden_states=output_hidden_states,
- return_dict=return_dict,
- )
- lm_logits = self.lm_head(outputs[0]) + self.final_logits_bias
- masked_lm_loss = None
- if labels is not None:
- loss_fct = CrossEntropyLoss()
- masked_lm_loss = loss_fct(lm_logits.view(-1, self.config.vocab_size), labels.view(-1))
- if not return_dict:
- output = (lm_logits,) + outputs[1:]
- return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
- return LEDSeq2SeqLMOutput(
- loss=masked_lm_loss,
- logits=lm_logits,
- past_key_values=outputs.past_key_values,
- decoder_hidden_states=outputs.decoder_hidden_states,
- decoder_attentions=outputs.decoder_attentions,
- cross_attentions=outputs.cross_attentions,
- encoder_last_hidden_state=outputs.encoder_last_hidden_state,
- encoder_hidden_states=outputs.encoder_hidden_states,
- encoder_attentions=outputs.encoder_attentions,
- encoder_global_attentions=outputs.encoder_global_attentions,
- )
- def prepare_decoder_input_ids_from_labels(self, labels: torch.Tensor):
- return shift_tokens_right(labels, self.config.pad_token_id, self.config.decoder_start_token_id)
- @auto_docstring
- class LEDForQuestionAnswering(LEDPreTrainedModel):
- def __init__(self, config):
- super().__init__(config)
- config.num_labels = 2
- self.num_labels = config.num_labels
- self.led = LEDModel(config)
- self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
- # Initialize weights and apply final processing
- self.post_init()
- @auto_docstring
- def forward(
- self,
- input_ids: torch.LongTensor | None = None,
- attention_mask: torch.Tensor | None = None,
- decoder_input_ids: torch.LongTensor | None = None,
- decoder_attention_mask: torch.LongTensor | None = None,
- encoder_outputs: tuple[tuple[torch.FloatTensor]] | None = None,
- global_attention_mask: torch.FloatTensor | None = None,
- start_positions: torch.LongTensor | None = None,
- end_positions: torch.LongTensor | None = None,
- inputs_embeds: torch.FloatTensor | None = None,
- decoder_inputs_embeds: torch.FloatTensor | None = None,
- use_cache: bool | None = None,
- output_attentions: bool | None = None,
- output_hidden_states: bool | None = None,
- return_dict: bool | None = None,
- **kwargs,
- ) -> tuple[torch.Tensor] | LEDSeq2SeqQuestionAnsweringModelOutput:
- r"""
- decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
- Indices of decoder input sequence tokens in the vocabulary.
- Indices can be obtained using [`LedTokenizer`]. See [`PreTrainedTokenizer.encode`] and
- [`PreTrainedTokenizer.__call__`] for details.
- [What are input IDs?](../glossary#input-ids)
- LED uses the `eos_token_id` as the starting token for `decoder_input_ids` generation. If `past_key_values`
- is used, optionally only the last `decoder_input_ids` have to be input (see `past_key_values`).
- decoder_attention_mask (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
- Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
- be used by default.
- If you want to change padding behavior, you should read [`modeling_led._prepare_decoder_inputs`] and modify
- to your needs. See diagram 1 in [the paper](https://huggingface.co/papers/1910.13461) for more information on the
- default strategy.
- global_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
- Mask to decide the attention given on each token, local attention or global attention for the encoder.
- Tokens with global attention attends to all other tokens, and all other tokens attend to them. This is
- important for task-specific finetuning because it makes the model more flexible at representing the task.
- For example, for classification, the <s> token should be given global attention. For QA, all question
- tokens should also have global attention. Please refer to the [Longformer
- paper](https://huggingface.co/papers/2004.05150) for more details. Mask values selected in `[0, 1]`:
- - 0 for local attention (a sliding window attention),
- - 1 for global attention (tokens that attend to all other tokens, and all other tokens attend to them).
- """
- return_dict = return_dict if return_dict is not None else self.config.return_dict
- if start_positions is not None and end_positions is not None:
- use_cache = False
- outputs = self.led(
- input_ids,
- attention_mask=attention_mask,
- decoder_input_ids=decoder_input_ids,
- decoder_attention_mask=decoder_attention_mask,
- global_attention_mask=global_attention_mask,
- encoder_outputs=encoder_outputs,
- inputs_embeds=inputs_embeds,
- decoder_inputs_embeds=decoder_inputs_embeds,
- use_cache=use_cache,
- output_attentions=output_attentions,
- output_hidden_states=output_hidden_states,
- return_dict=return_dict,
- )
- sequence_output = outputs[0]
- logits = self.qa_outputs(sequence_output)
- start_logits, end_logits = logits.split(1, dim=-1)
- start_logits = start_logits.squeeze(-1).contiguous()
- end_logits = end_logits.squeeze(-1).contiguous()
- total_loss = None
- if start_positions is not None and end_positions is not None:
- # If we are on multi-GPU, split add a dimension
- if len(start_positions.size()) > 1:
- start_positions = start_positions.squeeze(-1)
- if len(end_positions.size()) > 1:
- end_positions = end_positions.squeeze(-1)
- # sometimes the start/end positions are outside our model inputs, we ignore these terms
- ignored_index = start_logits.size(1)
- start_positions = start_positions.clamp(0, ignored_index)
- end_positions = end_positions.clamp(0, ignored_index)
- loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
- start_loss = loss_fct(start_logits, start_positions)
- end_loss = loss_fct(end_logits, end_positions)
- total_loss = (start_loss + end_loss) / 2
- if not return_dict:
- output = (
- start_logits,
- end_logits,
- ) + outputs[1:]
- return ((total_loss,) + output) if total_loss is not None else output
- return LEDSeq2SeqQuestionAnsweringModelOutput(
- loss=total_loss,
- start_logits=start_logits,
- end_logits=end_logits,
- past_key_values=outputs.past_key_values,
- decoder_hidden_states=outputs.decoder_hidden_states,
- decoder_attentions=outputs.decoder_attentions,
- cross_attentions=outputs.cross_attentions,
- encoder_last_hidden_state=outputs.encoder_last_hidden_state,
- encoder_hidden_states=outputs.encoder_hidden_states,
- encoder_attentions=outputs.encoder_attentions,
- encoder_global_attentions=outputs.encoder_global_attentions,
- )
- __all__ = [
- "LEDForConditionalGeneration",
- "LEDForQuestionAnswering",
- "LEDModel",
- "LEDPreTrainedModel",
- ]
|