readme
Browse files- README.md +87 -0
- config.json +96 -0
- merges.txt +0 -0
- modeling_lsg_bart.py +2143 -0
- pytorch_model.bin +3 -0
- special_tokens_map.json +1 -0
- tokenizer.json +0 -0
- tokenizer_config.json +1 -0
- vocab.json +0 -0
README.md
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
language:
|
| 3 |
+
- en
|
| 4 |
+
tags:
|
| 5 |
+
- summarization
|
| 6 |
+
datasets:
|
| 7 |
+
- scientific_papers
|
| 8 |
+
metrics:
|
| 9 |
+
- rouge
|
| 10 |
+
model-index:
|
| 11 |
+
- name: ccdv/lsg-bart-base-4096-pubmed
|
| 12 |
+
results: []
|
| 13 |
+
---
|
| 14 |
+
|
| 15 |
+
<!-- This model card has been generated automatically according to the information the Trainer had access to. You
|
| 16 |
+
should probably proofread and complete it, then remove this comment. -->
|
| 17 |
+
|
| 18 |
+
**This model relies on a custom modeling file, you need to add trust_remote_code=True**\
|
| 19 |
+
**See [\#13467](https://github.com/huggingface/transformers/pull/13467)**
|
| 20 |
+
|
| 21 |
+
# ccdv/lsg-bart-base-4096-pubmed
|
| 22 |
+
|
| 23 |
+
This model is a fine-tuned version of [ccdv/lsg-bart-base-4096](https://huggingface.co/ccdv/lsg-bart-base-4096) on the scientific_papers pubmed dataset. \
|
| 24 |
+
It achieves the following results on the test set:
|
| 25 |
+
|
| 26 |
+
| Length | Sparse Type | Block Size | Sparsity | Connexions | R1 | R2 | RL | RLsum |
|
| 27 |
+
|:------ |:----------- |:---------- |:-------- | :--------- |:----- |:----- |:----- |:----- |
|
| 28 |
+
| 4096 | Local | 256 | 0 | 768 | 47.33 | 21.67 | 28.53 | 43.67 |
|
| 29 |
+
| 4096 | Local | 128 | 0 | 384 | 46.84 | 21.24 | 28.22 | 43.15 |
|
| 30 |
+
| 4096 | Pooling | 128 | 4 | 644 | 47.07 | 21.41 | 28.40 | 43.36 |
|
| 31 |
+
| 4096 | Stride | 128 | 4 | 644 | 47.02 | 21.46 | 28.33 | 43.35 |
|
| 32 |
+
| 4096 | Norm | 128 | 4 | 644 | 47.01 | 21.32 | 28.26 | 43.33 |
|
| 33 |
+
| 4096 | LSH | 128 | 4 | 644 | 46.92 | 21.27 | 28.26 | 43.26 |
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
## Model description
|
| 38 |
+
The model relies on Local-Sparse-Global attention to handle long sequences:
|
| 39 |
+

|
| 40 |
+
|
| 41 |
+
The model has about ~145 millions parameters (6 encoder layers - 6 decoder layers). \
|
| 42 |
+
The model is warm started from BART-base, converted to handle long sequences (encoder only) and fine tuned. \
|
| 43 |
+
|
| 44 |
+
## Intended uses & limitations
|
| 45 |
+
|
| 46 |
+
More information needed
|
| 47 |
+
|
| 48 |
+
## Training and evaluation data
|
| 49 |
+
|
| 50 |
+
More information needed
|
| 51 |
+
|
| 52 |
+
## Training procedure
|
| 53 |
+
|
| 54 |
+
### Training hyperparameters
|
| 55 |
+
|
| 56 |
+
The following hyperparameters were used during training:
|
| 57 |
+
- learning_rate: 8e-05
|
| 58 |
+
- train_batch_size: 8
|
| 59 |
+
- seed: 42
|
| 60 |
+
- gradient_accumulation_steps: 4
|
| 61 |
+
- total_train_batch_size: 32
|
| 62 |
+
- optimizer: Adam with betas=(0.9,0.999) and epsilon=1e-08
|
| 63 |
+
- lr_scheduler_type: linear
|
| 64 |
+
- num_epochs: 7.0
|
| 65 |
+
|
| 66 |
+
### Generate hyperparameters
|
| 67 |
+
|
| 68 |
+
The following hyperparameters were used during generation:
|
| 69 |
+
- dataset_name: scientific_papers
|
| 70 |
+
- dataset_config_name: pubmed
|
| 71 |
+
- eval_batch_size: 8
|
| 72 |
+
- early_stopping: True
|
| 73 |
+
- ignore_pad_token_for_loss: True
|
| 74 |
+
- length_penalty: 2.0
|
| 75 |
+
- max_length: 512
|
| 76 |
+
- min_length: 128
|
| 77 |
+
- num_beams: 5
|
| 78 |
+
- num_samples: None
|
| 79 |
+
- no_repeat_ngram_size: None
|
| 80 |
+
- seed: 123
|
| 81 |
+
|
| 82 |
+
### Framework versions
|
| 83 |
+
|
| 84 |
+
- Transformers 4.18.0
|
| 85 |
+
- Pytorch 1.10.1+cu102
|
| 86 |
+
- Datasets 2.1.0
|
| 87 |
+
- Tokenizers 0.11.6
|
config.json
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"_name_or_path": "ccdv/lsg-bart-base-4096-pubmed",
|
| 3 |
+
"activation_dropout": 0.1,
|
| 4 |
+
"activation_function": "gelu",
|
| 5 |
+
"adaptive": true,
|
| 6 |
+
"add_bias_logits": false,
|
| 7 |
+
"add_final_layer_norm": false,
|
| 8 |
+
"architectures": [
|
| 9 |
+
"LSGBartForConditionalGeneration"
|
| 10 |
+
],
|
| 11 |
+
"attention_dropout": 0.1,
|
| 12 |
+
"auto_map": {
|
| 13 |
+
"AutoConfig": "modeling_lsg_bart.LSGBartConfig",
|
| 14 |
+
"AutoModel": "modeling_lsg_bart.LSGBartModel",
|
| 15 |
+
"AutoModelForCausalLM": "modeling_lsg_bart.LSGBartForCausalLM",
|
| 16 |
+
"AutoModelForQuestionAnswering": "modeling_lsg_bart.LSGBartForQuestionAnswering",
|
| 17 |
+
"AutoModelForSeq2SeqLM": "modeling_lsg_bart.LSGBartForConditionalGeneration",
|
| 18 |
+
"AutoModelForSequenceClassification": "modeling_lsg_bart.LSGBartForSequenceClassification"
|
| 19 |
+
},
|
| 20 |
+
"base_model_prefix": "lsg",
|
| 21 |
+
"block_size": 256,
|
| 22 |
+
"bos_token_id": 0,
|
| 23 |
+
"classif_dropout": 0.1,
|
| 24 |
+
"classifier_dropout": 0.0,
|
| 25 |
+
"d_model": 768,
|
| 26 |
+
"decoder_attention_heads": 12,
|
| 27 |
+
"decoder_ffn_dim": 3072,
|
| 28 |
+
"decoder_layerdrop": 0.0,
|
| 29 |
+
"decoder_layers": 6,
|
| 30 |
+
"decoder_start_token_id": 2,
|
| 31 |
+
"dropout": 0.1,
|
| 32 |
+
"early_stopping": true,
|
| 33 |
+
"encoder_attention_heads": 12,
|
| 34 |
+
"encoder_ffn_dim": 3072,
|
| 35 |
+
"encoder_layerdrop": 0.0,
|
| 36 |
+
"encoder_layers": 6,
|
| 37 |
+
"eos_token_id": 2,
|
| 38 |
+
"forced_bos_token_id": 0,
|
| 39 |
+
"forced_eos_token_id": 2,
|
| 40 |
+
"gradient_checkpointing": false,
|
| 41 |
+
"id2label": {
|
| 42 |
+
"0": "LABEL_0",
|
| 43 |
+
"1": "LABEL_1",
|
| 44 |
+
"2": "LABEL_2"
|
| 45 |
+
},
|
| 46 |
+
"init_std": 0.02,
|
| 47 |
+
"is_encoder_decoder": true,
|
| 48 |
+
"label2id": {
|
| 49 |
+
"LABEL_0": 0,
|
| 50 |
+
"LABEL_1": 1,
|
| 51 |
+
"LABEL_2": 2
|
| 52 |
+
},
|
| 53 |
+
"length_penalty": 2.0,
|
| 54 |
+
"lsh_num_pre_rounds": 1,
|
| 55 |
+
"max_length": 512,
|
| 56 |
+
"max_position_embeddings": 4096,
|
| 57 |
+
"min_length": 128,
|
| 58 |
+
"model_type": "bart",
|
| 59 |
+
"no_repeat_ngram_size": null,
|
| 60 |
+
"normalize_before": false,
|
| 61 |
+
"normalize_embedding": true,
|
| 62 |
+
"num_beams": 5,
|
| 63 |
+
"num_global_tokens": 1,
|
| 64 |
+
"num_hidden_layers": 6,
|
| 65 |
+
"pad_token_id": 1,
|
| 66 |
+
"pass_global_tokens_to_decoder": true,
|
| 67 |
+
"pool_with_global": true,
|
| 68 |
+
"scale_embedding": false,
|
| 69 |
+
"sparse_block_size": 0,
|
| 70 |
+
"sparsity_factor": 2,
|
| 71 |
+
"sparsity_type": "pooling",
|
| 72 |
+
"task_specific_params": {
|
| 73 |
+
"summarization": {
|
| 74 |
+
"length_penalty": 1.0,
|
| 75 |
+
"max_length": 128,
|
| 76 |
+
"min_length": 12,
|
| 77 |
+
"num_beams": 4
|
| 78 |
+
},
|
| 79 |
+
"summarization_cnn": {
|
| 80 |
+
"length_penalty": 2.0,
|
| 81 |
+
"max_length": 142,
|
| 82 |
+
"min_length": 56,
|
| 83 |
+
"num_beams": 4
|
| 84 |
+
},
|
| 85 |
+
"summarization_xsum": {
|
| 86 |
+
"length_penalty": 1.0,
|
| 87 |
+
"max_length": 62,
|
| 88 |
+
"min_length": 11,
|
| 89 |
+
"num_beams": 6
|
| 90 |
+
}
|
| 91 |
+
},
|
| 92 |
+
"torch_dtype": "float32",
|
| 93 |
+
"transformers_version": "4.18.0",
|
| 94 |
+
"use_cache": true,
|
| 95 |
+
"vocab_size": 50265
|
| 96 |
+
}
|
merges.txt
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
modeling_lsg_bart.py
ADDED
|
@@ -0,0 +1,2143 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from logging import warn
|
| 2 |
+
import torch
|
| 3 |
+
from transformers.models.bart.modeling_bart import *
|
| 4 |
+
from transformers.models.bart.modeling_bart import _expand_mask
|
| 5 |
+
import torch.nn as nn
|
| 6 |
+
from torch.nn import BCEWithLogitsLoss
|
| 7 |
+
import sys
|
| 8 |
+
|
| 9 |
+
AUTO_MAP = {
|
| 10 |
+
"AutoModel": "modeling_lsg_bart.LSGBartModel",
|
| 11 |
+
"AutoModelForCausalLM": "modeling_lsg_bart.LSGBartForCausalLM",
|
| 12 |
+
"AutoModelForQuestionAnswering": "modeling_lsg_bart.LSGBartForQuestionAnswering",
|
| 13 |
+
"AutoModelForSequenceClassification": "modeling_lsg_bart.LSGBartForSequenceClassification",
|
| 14 |
+
"AutoModelForSeq2SeqLM": "modeling_lsg_bart.LSGBartForConditionalGeneration"
|
| 15 |
+
}
|
| 16 |
+
|
| 17 |
+
class LSGBartConfig(BartConfig):
|
| 18 |
+
"""
|
| 19 |
+
This class overrides :class:`~transformers.RobertaConfig`. Please check the superclass for the appropriate
|
| 20 |
+
documentation alongside usage examples.
|
| 21 |
+
"""
|
| 22 |
+
|
| 23 |
+
base_model_prefix = "lsg"
|
| 24 |
+
model_type = "bart"
|
| 25 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
| 26 |
+
attribute_map = {"num_attention_heads": "encoder_attention_heads", "hidden_size": "d_model"}
|
| 27 |
+
|
| 28 |
+
def __init__(
|
| 29 |
+
self,
|
| 30 |
+
adaptive=True,
|
| 31 |
+
base_model_prefix="lsg",
|
| 32 |
+
block_size=128,
|
| 33 |
+
lsh_num_pre_rounds=1,
|
| 34 |
+
num_global_tokens=1,
|
| 35 |
+
pass_global_tokens_to_decoder=True,
|
| 36 |
+
pool_with_global=True,
|
| 37 |
+
sparse_block_size=128,
|
| 38 |
+
sparsity_factor=2,
|
| 39 |
+
sparsity_type="norm",
|
| 40 |
+
**kwargs
|
| 41 |
+
):
|
| 42 |
+
"""Constructs LSGConfig."""
|
| 43 |
+
super().__init__(**kwargs)
|
| 44 |
+
|
| 45 |
+
assert sparsity_type in ["norm", "lsh", "pooling", "stride"], "Sparsity mode must be 'norm', 'lsh' or 'pooling'"
|
| 46 |
+
|
| 47 |
+
self.adaptive = adaptive
|
| 48 |
+
self.auto_map = AUTO_MAP
|
| 49 |
+
self.base_model_prefix = base_model_prefix
|
| 50 |
+
self.block_size = block_size
|
| 51 |
+
self.lsh_num_pre_rounds = lsh_num_pre_rounds
|
| 52 |
+
self.num_global_tokens = num_global_tokens
|
| 53 |
+
self.pass_global_tokens_to_decoder = pass_global_tokens_to_decoder
|
| 54 |
+
self.pool_with_global = pool_with_global
|
| 55 |
+
self.sparse_block_size = sparse_block_size
|
| 56 |
+
self.sparsity_factor = sparsity_factor
|
| 57 |
+
self.sparsity_type = sparsity_type
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def shift_tokens_right(input_ids, pad_token_id, decoder_start_token_id):
|
| 61 |
+
"""
|
| 62 |
+
Shift input ids one token to the right.
|
| 63 |
+
"""
|
| 64 |
+
shifted_input_ids = input_ids.new_zeros(input_ids.shape)
|
| 65 |
+
shifted_input_ids[:, 1:] = input_ids[:, :-1].clone()
|
| 66 |
+
shifted_input_ids[:, 0] = decoder_start_token_id
|
| 67 |
+
|
| 68 |
+
if pad_token_id is None:
|
| 69 |
+
raise ValueError("self.model.config.pad_token_id has to be defined.")
|
| 70 |
+
# replace possible -100 values in labels by `pad_token_id`
|
| 71 |
+
shifted_input_ids.masked_fill_(shifted_input_ids == -100, pad_token_id)
|
| 72 |
+
|
| 73 |
+
return shifted_input_ids
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def _make_causal_mask(input_ids_shape, dtype, past_key_values_length=0):
|
| 77 |
+
"""
|
| 78 |
+
Make causal mask used for bi-directional self-attention.
|
| 79 |
+
"""
|
| 80 |
+
bsz, tgt_len = input_ids_shape
|
| 81 |
+
mask = torch.full((tgt_len, tgt_len), float("-inf"))
|
| 82 |
+
mask_cond = torch.arange(mask.size(-1))
|
| 83 |
+
mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)
|
| 84 |
+
mask = mask.to(dtype)
|
| 85 |
+
|
| 86 |
+
if past_key_values_length > 0:
|
| 87 |
+
mask = torch.cat([torch.zeros(tgt_len, past_key_values_length, dtype=dtype), mask], dim=-1)
|
| 88 |
+
return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len + past_key_values_length)
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def _expand_mask(mask, dtype, tgt_len=None):
|
| 92 |
+
"""
|
| 93 |
+
Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
|
| 94 |
+
"""
|
| 95 |
+
bsz, src_len = mask.size()
|
| 96 |
+
tgt_len = tgt_len if tgt_len is not None else src_len
|
| 97 |
+
|
| 98 |
+
expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)
|
| 99 |
+
|
| 100 |
+
inverted_mask = 1.0 - expanded_mask
|
| 101 |
+
|
| 102 |
+
return inverted_mask.masked_fill(inverted_mask.bool(), torch.finfo(dtype).min)
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
class BaseSelfAttention(nn.Module):
|
| 106 |
+
|
| 107 |
+
def __init__(
|
| 108 |
+
self,
|
| 109 |
+
embed_dim,
|
| 110 |
+
num_heads,
|
| 111 |
+
dropout=0.0,
|
| 112 |
+
is_decoder=False,
|
| 113 |
+
bias=True,
|
| 114 |
+
):
|
| 115 |
+
|
| 116 |
+
super().__init__()
|
| 117 |
+
self.embed_dim = embed_dim
|
| 118 |
+
self.num_heads = num_heads
|
| 119 |
+
self.dropout = dropout
|
| 120 |
+
self.head_dim = embed_dim // num_heads
|
| 121 |
+
|
| 122 |
+
if (self.head_dim * num_heads) != self.embed_dim:
|
| 123 |
+
raise ValueError(
|
| 124 |
+
f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}"
|
| 125 |
+
f" and `num_heads`: {num_heads})."
|
| 126 |
+
)
|
| 127 |
+
self.scaling = self.head_dim ** -0.5
|
| 128 |
+
self.is_decoder = is_decoder
|
| 129 |
+
|
| 130 |
+
self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
|
| 131 |
+
self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
|
| 132 |
+
self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
|
| 133 |
+
self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
|
| 134 |
+
|
| 135 |
+
def transpose_for_scores(self, x):
|
| 136 |
+
new_x_shape = x.size()[:-1] + (
|
| 137 |
+
self.num_heads,
|
| 138 |
+
self.head_dim,
|
| 139 |
+
)
|
| 140 |
+
x = x.view(*new_x_shape)
|
| 141 |
+
return x.permute(0, 2, 1, 3)
|
| 142 |
+
|
| 143 |
+
def reshape_output(self, context_layer):
|
| 144 |
+
context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
|
| 145 |
+
new_context_layer_shape = context_layer.size()[:-2] + (self.embed_dim,)
|
| 146 |
+
return context_layer.view(*new_context_layer_shape)
|
| 147 |
+
|
| 148 |
+
def project_QKV(self, hidden_states):
|
| 149 |
+
|
| 150 |
+
query_layer = self.transpose_for_scores(self.q_proj(hidden_states))
|
| 151 |
+
key_layer = self.transpose_for_scores(self.k_proj(hidden_states))
|
| 152 |
+
value_layer = self.transpose_for_scores(self.v_proj(hidden_states))
|
| 153 |
+
return query_layer, key_layer, value_layer
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
class BaseAttentionProduct(nn.Module):
|
| 157 |
+
|
| 158 |
+
def __init__(self, config):
|
| 159 |
+
"""
|
| 160 |
+
Compute attention: softmax(Q @ K.T) @ V
|
| 161 |
+
"""
|
| 162 |
+
super().__init__()
|
| 163 |
+
self.dropout = nn.Dropout(config.attention_dropout)
|
| 164 |
+
|
| 165 |
+
def forward(self, query_layer, key_layer, value_layer, attention_mask=None):
|
| 166 |
+
|
| 167 |
+
d = query_layer.shape[-1]
|
| 168 |
+
|
| 169 |
+
# Take the dot product between "query" and "key" to get the raw attention scores.
|
| 170 |
+
attention_scores = query_layer @ key_layer.transpose(-1, -2) / math.sqrt(d)
|
| 171 |
+
|
| 172 |
+
del query_layer
|
| 173 |
+
del key_layer
|
| 174 |
+
|
| 175 |
+
if attention_mask is not None:
|
| 176 |
+
# Apply the attention mask is (precomputed for all layers in RobertaModel forward() function)
|
| 177 |
+
attention_scores = attention_scores + attention_mask
|
| 178 |
+
del attention_mask
|
| 179 |
+
|
| 180 |
+
# Normalize the attention scores to probabilities.
|
| 181 |
+
attention_probs = nn.Softmax(dim=-1)(attention_scores)
|
| 182 |
+
|
| 183 |
+
# This is actually dropping out entire tokens to attend to, which might
|
| 184 |
+
# seem a bit unusual, but is taken from the original Transformer paper.
|
| 185 |
+
context_layer = self.dropout(attention_probs) @ value_layer
|
| 186 |
+
|
| 187 |
+
return context_layer
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
class LSGAttentionProduct(nn.Module):
|
| 191 |
+
|
| 192 |
+
def __init__(self, config, block_size=None, sparse_block_size=None, sparsity_factor=4):
|
| 193 |
+
"""
|
| 194 |
+
Compute block or overlapping blocks attention products
|
| 195 |
+
"""
|
| 196 |
+
super().__init__()
|
| 197 |
+
|
| 198 |
+
self.block_size = block_size
|
| 199 |
+
self.sparse_block_size = sparse_block_size
|
| 200 |
+
self.sparsity_factor = sparsity_factor
|
| 201 |
+
|
| 202 |
+
if self.block_size is None:
|
| 203 |
+
self.block_size = config.block_size
|
| 204 |
+
|
| 205 |
+
if self.sparse_block_size is None:
|
| 206 |
+
self.sparse_block_size = config.sparse_block_size
|
| 207 |
+
|
| 208 |
+
# Shape of blocks
|
| 209 |
+
self.local_shapes = (self.block_size*3, self.block_size)
|
| 210 |
+
if self.sparsity_factor > 0:
|
| 211 |
+
self.sparse_shapes = (self.sparse_block_size*3, self.block_size//self.sparsity_factor)
|
| 212 |
+
|
| 213 |
+
self.attention = BaseAttentionProduct(config)
|
| 214 |
+
|
| 215 |
+
def build_lsg_inputs(self, hidden_states, sparse_hidden_states, global_hidden_states, is_attn_mask=False):
|
| 216 |
+
|
| 217 |
+
# Build local tokens
|
| 218 |
+
local_hidden_states = self.reshape_to_local_block(hidden_states, is_attn_mask)
|
| 219 |
+
del hidden_states
|
| 220 |
+
|
| 221 |
+
# Build sparse tokens
|
| 222 |
+
if sparse_hidden_states is not None:
|
| 223 |
+
sparse_hidden_states = self.reshape_to_sparse_block(sparse_hidden_states, is_attn_mask)
|
| 224 |
+
|
| 225 |
+
return self.cat_global_sparse_local_tokens(global_hidden_states, sparse_hidden_states, local_hidden_states)
|
| 226 |
+
|
| 227 |
+
def forward(
|
| 228 |
+
self,
|
| 229 |
+
query_layer,
|
| 230 |
+
key_layer,
|
| 231 |
+
value_layer,
|
| 232 |
+
attention_mask=None,
|
| 233 |
+
sparse_key=None,
|
| 234 |
+
sparse_value=None,
|
| 235 |
+
sparse_mask=None,
|
| 236 |
+
global_key=None,
|
| 237 |
+
global_value=None,
|
| 238 |
+
global_mask=None
|
| 239 |
+
):
|
| 240 |
+
|
| 241 |
+
# Input batch, heads, length, hidden_size
|
| 242 |
+
n, h, t, d = query_layer.size()
|
| 243 |
+
n_blocks = t // self.block_size
|
| 244 |
+
assert t % self.block_size == 0
|
| 245 |
+
|
| 246 |
+
key_layer = self.build_lsg_inputs(
|
| 247 |
+
key_layer,
|
| 248 |
+
sparse_key,
|
| 249 |
+
global_key
|
| 250 |
+
)
|
| 251 |
+
del sparse_key
|
| 252 |
+
del global_key
|
| 253 |
+
|
| 254 |
+
value_layer = self.build_lsg_inputs(
|
| 255 |
+
value_layer,
|
| 256 |
+
sparse_value,
|
| 257 |
+
global_value
|
| 258 |
+
)
|
| 259 |
+
del sparse_value
|
| 260 |
+
del global_value
|
| 261 |
+
|
| 262 |
+
attention_mask = self.build_lsg_inputs(
|
| 263 |
+
attention_mask,
|
| 264 |
+
sparse_mask,
|
| 265 |
+
global_mask.transpose(-1, -2),
|
| 266 |
+
is_attn_mask=True
|
| 267 |
+
).transpose(-1, -2)
|
| 268 |
+
del sparse_mask
|
| 269 |
+
del global_mask
|
| 270 |
+
|
| 271 |
+
# expect (..., t, d) shape
|
| 272 |
+
# Compute attention
|
| 273 |
+
context_layer = self.attention(
|
| 274 |
+
query_layer=self.chunk(query_layer, n_blocks),
|
| 275 |
+
key_layer=key_layer,
|
| 276 |
+
value_layer=value_layer,
|
| 277 |
+
attention_mask=attention_mask
|
| 278 |
+
)
|
| 279 |
+
|
| 280 |
+
return context_layer.reshape(n, h, -1, d)
|
| 281 |
+
|
| 282 |
+
def reshape_to_local_block(self, hidden_states, is_attn_mask=False):
|
| 283 |
+
|
| 284 |
+
size, step = self.local_shapes
|
| 285 |
+
s = (size - step) // 2
|
| 286 |
+
|
| 287 |
+
# Pad before block reshaping
|
| 288 |
+
if is_attn_mask:
|
| 289 |
+
pad_value = -10000
|
| 290 |
+
hidden_states = hidden_states.transpose(-1, -2)
|
| 291 |
+
else:
|
| 292 |
+
pad_value = 0
|
| 293 |
+
|
| 294 |
+
hidden_states = torch.nn.functional.pad(
|
| 295 |
+
hidden_states.transpose(-1, -2),
|
| 296 |
+
pad=(s, s),
|
| 297 |
+
value=pad_value
|
| 298 |
+
).transpose(-1, -2)
|
| 299 |
+
|
| 300 |
+
# Make blocks
|
| 301 |
+
hidden_states = hidden_states.unfold(-2, size=size, step=step).transpose(-1, -2)
|
| 302 |
+
|
| 303 |
+
return hidden_states
|
| 304 |
+
|
| 305 |
+
def reshape_to_sparse_block(self, hidden_states, is_attn_mask=False):
|
| 306 |
+
|
| 307 |
+
size, step = self.sparse_shapes
|
| 308 |
+
|
| 309 |
+
# n, h, t, d*2 + 1
|
| 310 |
+
size = size*2
|
| 311 |
+
s = (size - step) // 2
|
| 312 |
+
|
| 313 |
+
# Pad before block reshaping
|
| 314 |
+
if is_attn_mask:
|
| 315 |
+
pad_value = -10000
|
| 316 |
+
hidden_states = hidden_states.transpose(-1, -2)
|
| 317 |
+
else:
|
| 318 |
+
pad_value = 0
|
| 319 |
+
|
| 320 |
+
hidden_states = torch.nn.functional.pad(
|
| 321 |
+
hidden_states.transpose(-1, -2),
|
| 322 |
+
pad=(s, s),
|
| 323 |
+
value=pad_value
|
| 324 |
+
).transpose(-1, -2)
|
| 325 |
+
|
| 326 |
+
# Make blocks
|
| 327 |
+
hidden_states = hidden_states.unfold(-2, size=size, step=step).transpose(-1, -2)
|
| 328 |
+
|
| 329 |
+
# Indexes for selection
|
| 330 |
+
u = (size - self.block_size * 3 // self.sparsity_factor) // 2
|
| 331 |
+
s = self.sparse_block_size
|
| 332 |
+
|
| 333 |
+
return torch.cat([hidden_states[..., u-s:u, :], hidden_states[..., -u:-u+s, :]], dim=-2)
|
| 334 |
+
|
| 335 |
+
def cat_global_sparse_local_tokens(self, x_global, x_sparse=None, x_local=None, dim=-2):
|
| 336 |
+
|
| 337 |
+
n, h, b, t, d = x_local.size()
|
| 338 |
+
x_global = x_global.unsqueeze(-3).expand(-1, -1, b, -1, -1)
|
| 339 |
+
if x_sparse is not None:
|
| 340 |
+
return torch.cat([x_global, x_sparse, x_local], dim=dim)
|
| 341 |
+
return torch.cat([x_global, x_local], dim=dim)
|
| 342 |
+
|
| 343 |
+
def chunk(self, x, n_blocks):
|
| 344 |
+
|
| 345 |
+
t, d = x.size()[-2:]
|
| 346 |
+
return x.reshape(*x.size()[:-2], n_blocks, -1, d)
|
| 347 |
+
|
| 348 |
+
|
| 349 |
+
class LSGBartEncoderAttention(BaseSelfAttention):
|
| 350 |
+
'''
|
| 351 |
+
Compute local attention with overlapping blocs
|
| 352 |
+
Use global attention for tokens with highest norm
|
| 353 |
+
'''
|
| 354 |
+
def __init__(
|
| 355 |
+
self,
|
| 356 |
+
config,
|
| 357 |
+
embed_dim,
|
| 358 |
+
num_heads,
|
| 359 |
+
dropout
|
| 360 |
+
):
|
| 361 |
+
|
| 362 |
+
super().__init__(embed_dim, num_heads, dropout)
|
| 363 |
+
|
| 364 |
+
self.block_size = config.block_size
|
| 365 |
+
self.sparse_block_size = config.sparse_block_size
|
| 366 |
+
self.num_global_tokens = config.num_global_tokens
|
| 367 |
+
self.sparsity_factor = config.sparsity_factor
|
| 368 |
+
|
| 369 |
+
self.attention = LSGAttentionProduct(
|
| 370 |
+
config,
|
| 371 |
+
block_size=config.block_size,
|
| 372 |
+
sparse_block_size=config.sparse_block_size,
|
| 373 |
+
sparsity_factor=self.sparsity_factor,
|
| 374 |
+
)
|
| 375 |
+
|
| 376 |
+
self.full_attention = BaseAttentionProduct(config)
|
| 377 |
+
|
| 378 |
+
sparse_functions = {
|
| 379 |
+
"norm": self.get_sparse_tokens_with_norm,
|
| 380 |
+
"pooling": self.get_sparse_tokens_with_pooling,
|
| 381 |
+
"lsh": self.get_sparse_tokens_with_lsh,
|
| 382 |
+
"stride": self.get_sparse_tokens_with_stride,
|
| 383 |
+
}
|
| 384 |
+
|
| 385 |
+
self.sparsity_type = config.sparsity_type
|
| 386 |
+
self.get_sparse_elements = sparse_functions[self.sparsity_type]
|
| 387 |
+
|
| 388 |
+
if config.sparsity_type == "stride":
|
| 389 |
+
if config.sparsity_factor > config.encoder_attention_heads:
|
| 390 |
+
logger.warning(
|
| 391 |
+
"Warning: sparsity_factor > encoder_attention_heads is not recommended for stride sparsity"
|
| 392 |
+
)
|
| 393 |
+
|
| 394 |
+
if config.sparsity_type == "lsh":
|
| 395 |
+
self.lsh_num_pre_rounds = config.lsh_num_pre_rounds
|
| 396 |
+
|
| 397 |
+
def get_sparse_tokens_with_norm(self, keys, values, mask):
|
| 398 |
+
|
| 399 |
+
if self.sparsity_factor == 1:
|
| 400 |
+
return keys, values, mask
|
| 401 |
+
|
| 402 |
+
with torch.no_grad():
|
| 403 |
+
|
| 404 |
+
block_size = min(self.block_size, self.sparse_block_size)
|
| 405 |
+
key_norm = keys.detach().norm(dim=-1, keepdim=True)
|
| 406 |
+
key_norm = key_norm * ~mask.transpose(-1, -2).bool()
|
| 407 |
+
key_norm = self.chunk(key_norm, block_size)
|
| 408 |
+
|
| 409 |
+
n, h, b, t, d = key_norm.size()
|
| 410 |
+
|
| 411 |
+
idx = key_norm.argsort(dim=-2)
|
| 412 |
+
del key_norm
|
| 413 |
+
idx += (torch.arange(b, device=keys.device)*t).reshape(1, 1, b, 1, 1)
|
| 414 |
+
|
| 415 |
+
split = (t - block_size // self.sparsity_factor, block_size // self.sparsity_factor)
|
| 416 |
+
sparse_idx = idx.split(split, -2)[-1].reshape(n, h, -1, 1)
|
| 417 |
+
|
| 418 |
+
d = keys.size()[-1]
|
| 419 |
+
keys = keys.gather(dim=-2, index=sparse_idx.expand(-1, -1, -1, d))
|
| 420 |
+
values = values.gather(dim=-2, index=sparse_idx.expand(-1, -1, -1, d))
|
| 421 |
+
mask = mask.expand(-1, h, -1, -1).transpose(-1, -2).gather(dim=-2, index=sparse_idx).transpose(-1, -2)
|
| 422 |
+
|
| 423 |
+
return keys, values, mask
|
| 424 |
+
|
| 425 |
+
def get_sparse_tokens_with_pooling(self, keys, values, mask):
|
| 426 |
+
|
| 427 |
+
if self.sparsity_factor == 1:
|
| 428 |
+
return keys, values, mask
|
| 429 |
+
|
| 430 |
+
keys = self.chunk(keys, self.sparsity_factor)
|
| 431 |
+
values = self.chunk(values, self.sparsity_factor)
|
| 432 |
+
|
| 433 |
+
n, h, b, t, d = keys.size()
|
| 434 |
+
mask = mask.reshape(n, 1, b, 1, t)
|
| 435 |
+
mask = ~mask.transpose(-1, -2).bool()
|
| 436 |
+
|
| 437 |
+
keys = keys * mask
|
| 438 |
+
values = values * mask
|
| 439 |
+
|
| 440 |
+
mask = mask.sum(dim=-2)
|
| 441 |
+
keys = keys.sum(dim=-2) / (mask + 1e-6)
|
| 442 |
+
values = values.sum(dim=-2) / (mask + 1e-6)
|
| 443 |
+
|
| 444 |
+
mask = - (1. - mask.clamp(0, 1)) * 1e4
|
| 445 |
+
return keys.reshape(n, h, -1, d), values.reshape(n, h, -1, d), mask.expand(-1, h, -1, -1).transpose(-1, -2)
|
| 446 |
+
|
| 447 |
+
def get_sparse_tokens_with_stride(self, keys, values, mask):
|
| 448 |
+
|
| 449 |
+
if self.sparsity_factor == 1:
|
| 450 |
+
return keys, values, mask
|
| 451 |
+
|
| 452 |
+
n, h, t, d = keys.size()
|
| 453 |
+
sparse_idx = torch.arange(t // self.sparsity_factor, device=keys.device) * self.sparsity_factor
|
| 454 |
+
sparse_idx = sparse_idx.reshape(1, 1, -1, 1) + (torch.arange(h, device=keys.device) % self.sparsity_factor).reshape(1, h, 1, 1)
|
| 455 |
+
sparse_idx = sparse_idx.expand(n, h, -1, 1)
|
| 456 |
+
|
| 457 |
+
keys = keys.gather(dim=-2, index=sparse_idx.expand(-1, -1, -1, d))
|
| 458 |
+
values = values.gather(dim=-2, index=sparse_idx.expand(-1, -1, -1, d))
|
| 459 |
+
mask = mask.expand(-1, h, -1, -1).transpose(-1, -2).gather(dim=-2, index=sparse_idx).transpose(-1, -2)
|
| 460 |
+
|
| 461 |
+
return keys, values, mask
|
| 462 |
+
|
| 463 |
+
def get_sparse_tokens_with_lsh(self, keys, values, mask):
|
| 464 |
+
|
| 465 |
+
if self.sparsity_factor == 1:
|
| 466 |
+
return keys, values, mask
|
| 467 |
+
|
| 468 |
+
block_size = min(self.block_size, self.sparse_block_size)
|
| 469 |
+
keys = self.chunk(keys, block_size)
|
| 470 |
+
values = self.chunk(values, block_size)
|
| 471 |
+
|
| 472 |
+
n, h, b, t, d = keys.size()
|
| 473 |
+
mask = mask.reshape(n, 1, b, 1, t)
|
| 474 |
+
mask = ~mask.transpose(-1, -2).bool()
|
| 475 |
+
|
| 476 |
+
keys = keys * mask
|
| 477 |
+
values = values * mask
|
| 478 |
+
mask = mask.expand(-1, h, -1, -1, -1).float()
|
| 479 |
+
|
| 480 |
+
extra_factor = 1
|
| 481 |
+
|
| 482 |
+
for _ in range(self.lsh_num_pre_rounds):
|
| 483 |
+
keys, values, mask = self.lsg_round(keys, values, mask, t*extra_factor)
|
| 484 |
+
|
| 485 |
+
keys, values, mask = self.lsg_round(keys, values, mask, t//self.sparsity_factor)
|
| 486 |
+
keys /= mask + 1e-8
|
| 487 |
+
values /= mask + 1e-8
|
| 488 |
+
|
| 489 |
+
mask = -10000 * (1. - mask.clamp(0, 1))
|
| 490 |
+
|
| 491 |
+
return keys.reshape(n, h, -1, d), values.reshape(n, h, -1, d), mask.transpose(-1, -2).reshape(n, h, 1, -1)
|
| 492 |
+
|
| 493 |
+
def lsg_round(self, keys, values, mask, output_size):
|
| 494 |
+
|
| 495 |
+
with torch.no_grad():
|
| 496 |
+
|
| 497 |
+
n_hashes = output_size // 2
|
| 498 |
+
n, h, b, t, d = keys.size()
|
| 499 |
+
binary_mask = mask.clamp(0, 1)
|
| 500 |
+
|
| 501 |
+
indexes = (torch.nn.functional.normalize(keys, dim=-1) * binary_mask) @ torch.randn(1, h, 1, d, n_hashes, device=keys.device)
|
| 502 |
+
indexes = torch.cat([indexes, -indexes], dim=-1).argmax(dim=-1, keepdim=True)
|
| 503 |
+
|
| 504 |
+
n, h, b, t, d = keys.size()
|
| 505 |
+
|
| 506 |
+
x_ = torch.zeros(n, h, b, output_size, d, device=keys.device)
|
| 507 |
+
mask_ = torch.zeros(n, h, b, output_size, 1, device=keys.device)
|
| 508 |
+
keys = torch.scatter_add(x_, dim=-2, index=indexes.expand(-1, -1, -1, -1, d), src=keys)
|
| 509 |
+
values = torch.scatter_add(x_, dim=-2, index=indexes.expand(-1, -1, -1, -1, d), src=values)
|
| 510 |
+
mask = torch.scatter_add(mask_, dim=-2, index=indexes, src=mask)
|
| 511 |
+
|
| 512 |
+
return keys[..., :output_size, :], values[..., :output_size, :], mask[..., :output_size, :]
|
| 513 |
+
|
| 514 |
+
def forward(
|
| 515 |
+
self,
|
| 516 |
+
hidden_states,
|
| 517 |
+
attention_mask=None,
|
| 518 |
+
layer_head_mask=None,
|
| 519 |
+
output_attentions=False
|
| 520 |
+
):
|
| 521 |
+
|
| 522 |
+
query_layer, key_layer, value_layer = self.project_QKV(hidden_states)
|
| 523 |
+
outputs = self.not_causal_forward(
|
| 524 |
+
query_layer,
|
| 525 |
+
key_layer,
|
| 526 |
+
value_layer,
|
| 527 |
+
attention_mask=attention_mask[:, :, :1, :],
|
| 528 |
+
head_mask=layer_head_mask,
|
| 529 |
+
output_attentions=output_attentions
|
| 530 |
+
)
|
| 531 |
+
|
| 532 |
+
return self.out_proj(outputs), None, None
|
| 533 |
+
|
| 534 |
+
def not_causal_forward(
|
| 535 |
+
self,
|
| 536 |
+
query_layer,
|
| 537 |
+
key_layer,
|
| 538 |
+
value_layer,
|
| 539 |
+
attention_mask=None,
|
| 540 |
+
head_mask=None,
|
| 541 |
+
output_attentions=False,
|
| 542 |
+
):
|
| 543 |
+
|
| 544 |
+
n, h, t, d = query_layer.size()
|
| 545 |
+
|
| 546 |
+
# Cat global mask
|
| 547 |
+
attention_mask = torch.nn.functional.pad(attention_mask, (self.num_global_tokens, 0), value=0)
|
| 548 |
+
|
| 549 |
+
# Use normal attention if local attention covers every tokens
|
| 550 |
+
if t <= 2 * self.block_size + self.num_global_tokens:
|
| 551 |
+
context_layer = self.full_attention(
|
| 552 |
+
query_layer=query_layer,
|
| 553 |
+
key_layer=key_layer,
|
| 554 |
+
value_layer=value_layer,
|
| 555 |
+
attention_mask=attention_mask
|
| 556 |
+
)
|
| 557 |
+
|
| 558 |
+
if head_mask is not None:
|
| 559 |
+
context_layer = context_layer * head_mask[:, :, :1, :1]
|
| 560 |
+
return self.reshape_output(context_layer)
|
| 561 |
+
|
| 562 |
+
# Split input into global tokens and other tokens
|
| 563 |
+
split = (self.num_global_tokens, t - self.num_global_tokens)
|
| 564 |
+
global_query, query_layer = query_layer.split(split, dim=-2)
|
| 565 |
+
|
| 566 |
+
# Get global_attention
|
| 567 |
+
bos = self.full_attention(
|
| 568 |
+
query_layer=global_query,
|
| 569 |
+
key_layer=key_layer,
|
| 570 |
+
value_layer=value_layer,
|
| 571 |
+
attention_mask=attention_mask
|
| 572 |
+
)
|
| 573 |
+
|
| 574 |
+
# Split K Q M on global and non global
|
| 575 |
+
global_key, key_layer = key_layer.split(split, dim=-2)
|
| 576 |
+
global_value, value_layer = value_layer.split(split, dim=-2)
|
| 577 |
+
global_mask, attention_mask = attention_mask.split(split, dim=-1)
|
| 578 |
+
|
| 579 |
+
n, h, t, d = key_layer.size()
|
| 580 |
+
|
| 581 |
+
# Get sparse idx
|
| 582 |
+
sparse_key, sparse_value, sparse_mask = (None, None, None)
|
| 583 |
+
|
| 584 |
+
if self.sparse_block_size and self.sparsity_factor > 0:
|
| 585 |
+
sparse_key, sparse_value, sparse_mask = self.get_sparse_elements(key_layer, value_layer, attention_mask)
|
| 586 |
+
|
| 587 |
+
# Expand masks on heads
|
| 588 |
+
attention_mask = attention_mask.expand(-1, h, -1, -1)
|
| 589 |
+
global_mask = global_mask.expand(-1, h, -1, -1)
|
| 590 |
+
|
| 591 |
+
# Compute dot product attention
|
| 592 |
+
context_layer = self.attention(
|
| 593 |
+
query_layer,
|
| 594 |
+
key_layer,
|
| 595 |
+
value_layer,
|
| 596 |
+
attention_mask,
|
| 597 |
+
sparse_key=sparse_key,
|
| 598 |
+
sparse_value=sparse_value,
|
| 599 |
+
sparse_mask=sparse_mask,
|
| 600 |
+
global_key=global_key,
|
| 601 |
+
global_value=global_value,
|
| 602 |
+
global_mask=global_mask
|
| 603 |
+
)
|
| 604 |
+
|
| 605 |
+
# Merge global and local-sparse tokens
|
| 606 |
+
context_layer = torch.cat([bos, context_layer], dim=-2)
|
| 607 |
+
if head_mask is not None:
|
| 608 |
+
context_layer = context_layer * head_mask[:, :, :1, :1]
|
| 609 |
+
context_layer = self.reshape_output(context_layer)
|
| 610 |
+
|
| 611 |
+
return context_layer
|
| 612 |
+
|
| 613 |
+
def chunk(self, x, chunk_size):
|
| 614 |
+
|
| 615 |
+
n, h, t, d = x.size()
|
| 616 |
+
return x.reshape(n, h, -1, chunk_size, d)
|
| 617 |
+
|
| 618 |
+
|
| 619 |
+
class LSGBartDecoderAttention(nn.Module):
|
| 620 |
+
|
| 621 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
| 622 |
+
|
| 623 |
+
def __init__(
|
| 624 |
+
self,
|
| 625 |
+
embed_dim,
|
| 626 |
+
num_heads,
|
| 627 |
+
dropout=0.0,
|
| 628 |
+
is_decoder=False,
|
| 629 |
+
bias=True,
|
| 630 |
+
):
|
| 631 |
+
|
| 632 |
+
super().__init__()
|
| 633 |
+
self.embed_dim = embed_dim
|
| 634 |
+
self.num_heads = num_heads
|
| 635 |
+
self.dropout = dropout
|
| 636 |
+
self.head_dim = embed_dim // num_heads
|
| 637 |
+
|
| 638 |
+
if (self.head_dim * num_heads) != self.embed_dim:
|
| 639 |
+
raise ValueError(
|
| 640 |
+
f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}"
|
| 641 |
+
f" and `num_heads`: {num_heads})."
|
| 642 |
+
)
|
| 643 |
+
self.scaling = self.head_dim ** -0.5
|
| 644 |
+
self.is_decoder = is_decoder
|
| 645 |
+
|
| 646 |
+
self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
|
| 647 |
+
self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
|
| 648 |
+
self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
|
| 649 |
+
self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
|
| 650 |
+
|
| 651 |
+
def _shape(self, tensor, seq_len, bsz):
|
| 652 |
+
return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
|
| 653 |
+
|
| 654 |
+
def forward(
|
| 655 |
+
self,
|
| 656 |
+
hidden_states,
|
| 657 |
+
key_value_states=None,
|
| 658 |
+
past_key_value=None,
|
| 659 |
+
attention_mask=None,
|
| 660 |
+
layer_head_mask=None,
|
| 661 |
+
output_attentions=False,
|
| 662 |
+
):
|
| 663 |
+
|
| 664 |
+
# if key_value_states are provided this layer is used as a cross-attention layer
|
| 665 |
+
# for the decoder
|
| 666 |
+
is_cross_attention = key_value_states is not None
|
| 667 |
+
|
| 668 |
+
bsz, tgt_len, _ = hidden_states.size()
|
| 669 |
+
|
| 670 |
+
# get query proj
|
| 671 |
+
query_states = self.q_proj(hidden_states) * self.scaling
|
| 672 |
+
# get key, value proj
|
| 673 |
+
if is_cross_attention and past_key_value is not None:
|
| 674 |
+
# reuse k,v, cross_attentions
|
| 675 |
+
key_states = past_key_value[0]
|
| 676 |
+
value_states = past_key_value[1]
|
| 677 |
+
elif is_cross_attention:
|
| 678 |
+
# cross_attentions
|
| 679 |
+
key_states = self._shape(self.k_proj(key_value_states), -1, bsz)
|
| 680 |
+
value_states = self._shape(self.v_proj(key_value_states), -1, bsz)
|
| 681 |
+
elif past_key_value is not None:
|
| 682 |
+
# reuse k, v, self_attention
|
| 683 |
+
key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
|
| 684 |
+
value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
|
| 685 |
+
key_states = torch.cat([past_key_value[0], key_states], dim=2)
|
| 686 |
+
value_states = torch.cat([past_key_value[1], value_states], dim=2)
|
| 687 |
+
else:
|
| 688 |
+
# self_attention
|
| 689 |
+
key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
|
| 690 |
+
value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
|
| 691 |
+
|
| 692 |
+
if self.is_decoder:
|
| 693 |
+
# if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states.
|
| 694 |
+
# Further calls to cross_attention layer can then reuse all cross-attention
|
| 695 |
+
# key/value_states (first "if" case)
|
| 696 |
+
# if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of
|
| 697 |
+
# all previous decoder key/value_states. Further calls to uni-directional self-attention
|
| 698 |
+
# can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
|
| 699 |
+
# if encoder bi-directional self-attention `past_key_value` is always `None`
|
| 700 |
+
past_key_value = (key_states, value_states)
|
| 701 |
+
|
| 702 |
+
proj_shape = (bsz * self.num_heads, -1, self.head_dim)
|
| 703 |
+
query_states = self._shape(query_states, tgt_len, bsz).view(*proj_shape)
|
| 704 |
+
key_states = key_states.view(*proj_shape)
|
| 705 |
+
value_states = value_states.view(*proj_shape)
|
| 706 |
+
|
| 707 |
+
src_len = key_states.size(1)
|
| 708 |
+
attn_weights = torch.bmm(query_states, key_states.transpose(1, 2))
|
| 709 |
+
|
| 710 |
+
if attn_weights.size() != (bsz * self.num_heads, tgt_len, src_len):
|
| 711 |
+
raise ValueError(
|
| 712 |
+
f"Attention weights should be of size {(bsz * self.num_heads, tgt_len, src_len)}, but is {attn_weights.size()}"
|
| 713 |
+
)
|
| 714 |
+
|
| 715 |
+
if attention_mask is not None:
|
| 716 |
+
if attention_mask.size() != (bsz, 1, tgt_len, src_len):
|
| 717 |
+
raise ValueError(
|
| 718 |
+
f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is {attention_mask.size()}"
|
| 719 |
+
)
|
| 720 |
+
attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + attention_mask
|
| 721 |
+
attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
|
| 722 |
+
|
| 723 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1)
|
| 724 |
+
|
| 725 |
+
if layer_head_mask is not None:
|
| 726 |
+
if layer_head_mask.size() != (self.num_heads,):
|
| 727 |
+
raise ValueError(
|
| 728 |
+
f"Head mask for a single layer should be of size {(self.num_heads,)}, but is {layer_head_mask.size()}"
|
| 729 |
+
)
|
| 730 |
+
attn_weights = layer_head_mask.view(1, -1, 1, 1) * attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
|
| 731 |
+
attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
|
| 732 |
+
|
| 733 |
+
if output_attentions:
|
| 734 |
+
# this operation is a bit awkward, but it's required to
|
| 735 |
+
# make sure that attn_weights keeps its gradient.
|
| 736 |
+
# In order to do so, attn_weights have to be reshaped
|
| 737 |
+
# twice and have to be reused in the following
|
| 738 |
+
attn_weights_reshaped = attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
|
| 739 |
+
attn_weights = attn_weights_reshaped.view(bsz * self.num_heads, tgt_len, src_len)
|
| 740 |
+
else:
|
| 741 |
+
attn_weights_reshaped = None
|
| 742 |
+
|
| 743 |
+
attn_probs = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
|
| 744 |
+
|
| 745 |
+
attn_output = torch.bmm(attn_probs, value_states)
|
| 746 |
+
|
| 747 |
+
if attn_output.size() != (bsz * self.num_heads, tgt_len, self.head_dim):
|
| 748 |
+
raise ValueError(
|
| 749 |
+
f"`attn_output` should be of size {(bsz, self.num_heads, tgt_len, self.head_dim)}, but is {attn_output.size()}"
|
| 750 |
+
)
|
| 751 |
+
|
| 752 |
+
attn_output = attn_output.view(bsz, self.num_heads, tgt_len, self.head_dim)
|
| 753 |
+
attn_output = attn_output.transpose(1, 2)
|
| 754 |
+
|
| 755 |
+
# Use the `embed_dim` from the config (stored in the class) rather than `hidden_state` because `attn_output` can be
|
| 756 |
+
# partitioned aross GPUs when using tensor-parallelism.
|
| 757 |
+
attn_output = attn_output.reshape(bsz, tgt_len, self.embed_dim)
|
| 758 |
+
|
| 759 |
+
attn_output = self.out_proj(attn_output)
|
| 760 |
+
|
| 761 |
+
return attn_output, attn_weights_reshaped, past_key_value
|
| 762 |
+
|
| 763 |
+
|
| 764 |
+
class LSGBartLearnedPositionalEmbedding(nn.Embedding):
|
| 765 |
+
"""
|
| 766 |
+
This module learns positional embeddings up to a fixed maximum size.
|
| 767 |
+
"""
|
| 768 |
+
|
| 769 |
+
def __init__(self, num_embeddings, embedding_dim):
|
| 770 |
+
# Bart is set up so that if padding_idx is specified then offset the embedding ids by 2
|
| 771 |
+
# and adjust num_embeddings appropriately. Other models don't have this hack
|
| 772 |
+
self.offset = 2
|
| 773 |
+
super().__init__(num_embeddings + self.offset, embedding_dim)
|
| 774 |
+
|
| 775 |
+
def forward(self, input_ids_shape, past_key_values_length=0):
|
| 776 |
+
|
| 777 |
+
"""`input_ids_shape` is expected to be [bsz x seqlen]."""
|
| 778 |
+
bsz, seq_len = input_ids_shape[:2]
|
| 779 |
+
positions = torch.arange(
|
| 780 |
+
past_key_values_length, past_key_values_length + seq_len, dtype=torch.long, device=self.weight.device
|
| 781 |
+
)
|
| 782 |
+
return super().forward(positions + self.offset)
|
| 783 |
+
|
| 784 |
+
|
| 785 |
+
class LSGBartEncoderLayer(nn.Module):
|
| 786 |
+
|
| 787 |
+
def __init__(self, config):
|
| 788 |
+
|
| 789 |
+
super().__init__()
|
| 790 |
+
self.embed_dim = config.d_model
|
| 791 |
+
self.self_attn = LSGBartEncoderAttention(
|
| 792 |
+
config=config,
|
| 793 |
+
embed_dim=self.embed_dim,
|
| 794 |
+
num_heads=config.encoder_attention_heads,
|
| 795 |
+
dropout=config.attention_dropout,
|
| 796 |
+
)
|
| 797 |
+
self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim)
|
| 798 |
+
self.dropout = config.dropout
|
| 799 |
+
self.activation_fn = ACT2FN[config.activation_function]
|
| 800 |
+
self.activation_dropout = config.activation_dropout
|
| 801 |
+
self.fc1 = nn.Linear(self.embed_dim, config.encoder_ffn_dim)
|
| 802 |
+
self.fc2 = nn.Linear(config.encoder_ffn_dim, self.embed_dim)
|
| 803 |
+
self.final_layer_norm = nn.LayerNorm(self.embed_dim)
|
| 804 |
+
|
| 805 |
+
def forward(
|
| 806 |
+
self,
|
| 807 |
+
hidden_states,
|
| 808 |
+
attention_mask,
|
| 809 |
+
layer_head_mask,
|
| 810 |
+
output_attentions=False,
|
| 811 |
+
):
|
| 812 |
+
"""
|
| 813 |
+
Args:
|
| 814 |
+
hidden_states (:obj:`torch.FloatTensor`): input to the layer of shape `(seq_len, batch, embed_dim)`
|
| 815 |
+
attention_mask (:obj:`torch.FloatTensor`): attention mask of size
|
| 816 |
+
`(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
|
| 817 |
+
layer_head_mask (:obj:`torch.FloatTensor`): mask for attention heads in a given layer of size
|
| 818 |
+
`(encoder_attention_heads,)`.
|
| 819 |
+
output_attentions (:obj:`bool`, `optional`):
|
| 820 |
+
Whether or not to return the attentions tensors of all attention layers. See ``attentions`` under
|
| 821 |
+
returned tensors for more detail.
|
| 822 |
+
"""
|
| 823 |
+
residual = hidden_states
|
| 824 |
+
hidden_states, attn_weights, _ = self.self_attn(
|
| 825 |
+
hidden_states=hidden_states,
|
| 826 |
+
attention_mask=attention_mask,
|
| 827 |
+
layer_head_mask=layer_head_mask,
|
| 828 |
+
output_attentions=output_attentions,
|
| 829 |
+
)
|
| 830 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
|
| 831 |
+
hidden_states = residual + hidden_states
|
| 832 |
+
hidden_states = self.self_attn_layer_norm(hidden_states)
|
| 833 |
+
|
| 834 |
+
residual = hidden_states
|
| 835 |
+
hidden_states = self.activation_fn(self.fc1(hidden_states))
|
| 836 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training)
|
| 837 |
+
hidden_states = self.fc2(hidden_states)
|
| 838 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
|
| 839 |
+
hidden_states = residual + hidden_states
|
| 840 |
+
hidden_states = self.final_layer_norm(hidden_states)
|
| 841 |
+
|
| 842 |
+
if hidden_states.dtype == torch.float16 and (
|
| 843 |
+
torch.isinf(hidden_states).any() or torch.isnan(hidden_states).any()
|
| 844 |
+
):
|
| 845 |
+
clamp_value = torch.finfo(hidden_states.dtype).max - 1000
|
| 846 |
+
hidden_states = torch.clamp(hidden_states, min=-clamp_value, max=clamp_value)
|
| 847 |
+
|
| 848 |
+
outputs = (hidden_states,)
|
| 849 |
+
|
| 850 |
+
if output_attentions:
|
| 851 |
+
outputs += (attn_weights,)
|
| 852 |
+
|
| 853 |
+
return outputs
|
| 854 |
+
|
| 855 |
+
|
| 856 |
+
class LSGBartDecoderLayer(nn.Module):
|
| 857 |
+
|
| 858 |
+
def __init__(self, config):
|
| 859 |
+
|
| 860 |
+
super().__init__()
|
| 861 |
+
self.embed_dim = config.d_model
|
| 862 |
+
|
| 863 |
+
self.self_attn = LSGBartDecoderAttention(
|
| 864 |
+
embed_dim=self.embed_dim,
|
| 865 |
+
num_heads=config.decoder_attention_heads,
|
| 866 |
+
dropout=config.attention_dropout,
|
| 867 |
+
is_decoder=True,
|
| 868 |
+
)
|
| 869 |
+
self.dropout = config.dropout
|
| 870 |
+
self.activation_fn = ACT2FN[config.activation_function]
|
| 871 |
+
self.activation_dropout = config.activation_dropout
|
| 872 |
+
|
| 873 |
+
self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim)
|
| 874 |
+
self.encoder_attn = LSGBartDecoderAttention(
|
| 875 |
+
self.embed_dim,
|
| 876 |
+
config.decoder_attention_heads,
|
| 877 |
+
dropout=config.attention_dropout,
|
| 878 |
+
is_decoder=True,
|
| 879 |
+
)
|
| 880 |
+
self.encoder_attn_layer_norm = nn.LayerNorm(self.embed_dim)
|
| 881 |
+
self.fc1 = nn.Linear(self.embed_dim, config.decoder_ffn_dim)
|
| 882 |
+
self.fc2 = nn.Linear(config.decoder_ffn_dim, self.embed_dim)
|
| 883 |
+
self.final_layer_norm = nn.LayerNorm(self.embed_dim)
|
| 884 |
+
|
| 885 |
+
def forward(
|
| 886 |
+
self,
|
| 887 |
+
hidden_states,
|
| 888 |
+
attention_mask=None,
|
| 889 |
+
encoder_hidden_states=None,
|
| 890 |
+
encoder_attention_mask=None,
|
| 891 |
+
layer_head_mask=None,
|
| 892 |
+
cross_attn_layer_head_mask=None,
|
| 893 |
+
past_key_value=None,
|
| 894 |
+
output_attentions=False,
|
| 895 |
+
use_cache=True,
|
| 896 |
+
):
|
| 897 |
+
"""
|
| 898 |
+
Args:
|
| 899 |
+
hidden_states (:obj:`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
|
| 900 |
+
attention_mask (:obj:`torch.FloatTensor`): attention mask of size
|
| 901 |
+
`(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
|
| 902 |
+
encoder_hidden_states (:obj:`torch.FloatTensor`): cross attention input to the layer of shape `(batch, seq_len, embed_dim)`
|
| 903 |
+
encoder_attention_mask (:obj:`torch.FloatTensor`): encoder attention mask of size
|
| 904 |
+
`(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
|
| 905 |
+
layer_head_mask (:obj:`torch.FloatTensor`): mask for attention heads in a given layer of size
|
| 906 |
+
`(encoder_attention_heads,)`.
|
| 907 |
+
cross_attn_layer_head_mask (:obj:`torch.FloatTensor`): mask for cross-attention heads in a given layer of
|
| 908 |
+
size `(decoder_attention_heads,)`.
|
| 909 |
+
past_key_value (:obj:`Tuple(torch.FloatTensor)`): cached past key and value projection states
|
| 910 |
+
output_attentions (:obj:`bool`, `optional`):
|
| 911 |
+
Whether or not to return the attentions tensors of all attention layers. See ``attentions`` under
|
| 912 |
+
returned tensors for more detail.
|
| 913 |
+
"""
|
| 914 |
+
residual = hidden_states
|
| 915 |
+
|
| 916 |
+
# Self Attention
|
| 917 |
+
# decoder uni-directional self-attention cached key/values tuple is at positions 1,2
|
| 918 |
+
self_attn_past_key_value = past_key_value[:2] if past_key_value is not None else None
|
| 919 |
+
# add present self-attn cache to positions 1,2 of present_key_value tuple
|
| 920 |
+
|
| 921 |
+
hidden_states, self_attn_weights, present_key_value = self.self_attn(
|
| 922 |
+
hidden_states=hidden_states,
|
| 923 |
+
past_key_value=self_attn_past_key_value,
|
| 924 |
+
attention_mask=attention_mask,
|
| 925 |
+
layer_head_mask=layer_head_mask,
|
| 926 |
+
output_attentions=output_attentions,
|
| 927 |
+
)
|
| 928 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
|
| 929 |
+
hidden_states = residual + hidden_states
|
| 930 |
+
hidden_states = self.self_attn_layer_norm(hidden_states)
|
| 931 |
+
|
| 932 |
+
# Cross-Attention Block
|
| 933 |
+
cross_attn_present_key_value = None
|
| 934 |
+
cross_attn_weights = None
|
| 935 |
+
if encoder_hidden_states is not None:
|
| 936 |
+
residual = hidden_states
|
| 937 |
+
|
| 938 |
+
# cross_attn cached key/values tuple is at positions 3,4 of present_key_value tuple
|
| 939 |
+
cross_attn_past_key_value = past_key_value[-2:] if past_key_value is not None else None
|
| 940 |
+
|
| 941 |
+
hidden_states, cross_attn_weights, cross_attn_present_key_value = self.encoder_attn(
|
| 942 |
+
hidden_states=hidden_states,
|
| 943 |
+
key_value_states=encoder_hidden_states,
|
| 944 |
+
attention_mask=encoder_attention_mask,
|
| 945 |
+
layer_head_mask=cross_attn_layer_head_mask,
|
| 946 |
+
past_key_value=cross_attn_past_key_value,
|
| 947 |
+
output_attentions=output_attentions,
|
| 948 |
+
)
|
| 949 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
|
| 950 |
+
hidden_states = residual + hidden_states
|
| 951 |
+
hidden_states = self.encoder_attn_layer_norm(hidden_states)
|
| 952 |
+
|
| 953 |
+
# add cross-attn to positions 3,4 of present_key_value tuple
|
| 954 |
+
present_key_value = present_key_value + cross_attn_present_key_value
|
| 955 |
+
|
| 956 |
+
# Fully Connected
|
| 957 |
+
residual = hidden_states
|
| 958 |
+
hidden_states = self.activation_fn(self.fc1(hidden_states))
|
| 959 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training)
|
| 960 |
+
hidden_states = self.fc2(hidden_states)
|
| 961 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
|
| 962 |
+
hidden_states = residual + hidden_states
|
| 963 |
+
hidden_states = self.final_layer_norm(hidden_states)
|
| 964 |
+
|
| 965 |
+
outputs = (hidden_states,)
|
| 966 |
+
|
| 967 |
+
if output_attentions:
|
| 968 |
+
outputs += (self_attn_weights, cross_attn_weights)
|
| 969 |
+
|
| 970 |
+
if use_cache:
|
| 971 |
+
outputs += (present_key_value,)
|
| 972 |
+
|
| 973 |
+
return outputs
|
| 974 |
+
|
| 975 |
+
|
| 976 |
+
class LSGBartClassificationHead(nn.Module):
|
| 977 |
+
"""Head for sentence-level classification tasks."""
|
| 978 |
+
|
| 979 |
+
def __init__(
|
| 980 |
+
self,
|
| 981 |
+
input_dim,
|
| 982 |
+
inner_dim,
|
| 983 |
+
num_classes,
|
| 984 |
+
pooler_dropout,
|
| 985 |
+
):
|
| 986 |
+
|
| 987 |
+
super().__init__()
|
| 988 |
+
self.dense = nn.Linear(input_dim, inner_dim)
|
| 989 |
+
self.dropout = nn.Dropout(p=pooler_dropout)
|
| 990 |
+
self.out_proj = nn.Linear(inner_dim, num_classes)
|
| 991 |
+
|
| 992 |
+
def forward(self, hidden_states):
|
| 993 |
+
|
| 994 |
+
hidden_states = self.dropout(hidden_states)
|
| 995 |
+
hidden_states = self.dense(hidden_states)
|
| 996 |
+
hidden_states = torch.tanh(hidden_states)
|
| 997 |
+
hidden_states = self.dropout(hidden_states)
|
| 998 |
+
hidden_states = self.out_proj(hidden_states)
|
| 999 |
+
return hidden_states
|
| 1000 |
+
|
| 1001 |
+
|
| 1002 |
+
class LSGBartPretrainedModel(PreTrainedModel):
|
| 1003 |
+
|
| 1004 |
+
config_class = LSGBartConfig
|
| 1005 |
+
base_model_prefix = "model"
|
| 1006 |
+
supports_gradient_checkpointing = True
|
| 1007 |
+
_keys_to_ignore_on_load_unexpected = [r"encoder\.version", r"decoder\.version"]
|
| 1008 |
+
|
| 1009 |
+
def _init_weights(self, module):
|
| 1010 |
+
|
| 1011 |
+
std = self.config.init_std
|
| 1012 |
+
if isinstance(module, nn.Linear):
|
| 1013 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
| 1014 |
+
if module.bias is not None:
|
| 1015 |
+
module.bias.data.zero_()
|
| 1016 |
+
elif isinstance(module, nn.Embedding):
|
| 1017 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
| 1018 |
+
if module.padding_idx is not None:
|
| 1019 |
+
module.weight.data[module.padding_idx].zero_()
|
| 1020 |
+
|
| 1021 |
+
def _set_gradient_checkpointing(self, module, value=False):
|
| 1022 |
+
|
| 1023 |
+
if isinstance(module, (LSGBartDecoder, LSGBartEncoder)):
|
| 1024 |
+
module.gradient_checkpointing = value
|
| 1025 |
+
|
| 1026 |
+
@property
|
| 1027 |
+
def dummy_inputs(self):
|
| 1028 |
+
pad_token = self.config.pad_token_id
|
| 1029 |
+
input_ids = torch.tensor([[0, 6, 10, 4, 2], [0, 8, 12, 2, pad_token]], device=self.device)
|
| 1030 |
+
dummy_inputs = {
|
| 1031 |
+
"attention_mask": input_ids.ne(pad_token),
|
| 1032 |
+
"input_ids": input_ids,
|
| 1033 |
+
}
|
| 1034 |
+
return dummy_inputs
|
| 1035 |
+
|
| 1036 |
+
|
| 1037 |
+
class PretrainedLSGBartModel(LSGBartPretrainedModel):
|
| 1038 |
+
|
| 1039 |
+
def __init_subclass__(self):
|
| 1040 |
+
warnings.warn(
|
| 1041 |
+
"The class `PretrainedBartModel` has been depreciated, please use `LSGBartPretrainedModel` instead.",
|
| 1042 |
+
FutureWarning,
|
| 1043 |
+
)
|
| 1044 |
+
|
| 1045 |
+
|
| 1046 |
+
class LSGBartEncoder(LSGBartPretrainedModel):
|
| 1047 |
+
"""
|
| 1048 |
+
Transformer encoder consisting of *config.encoder_layers* self attention layers. Each layer is a
|
| 1049 |
+
:class:`BartEncoderLayer`.
|
| 1050 |
+
Args:
|
| 1051 |
+
config: BartConfig
|
| 1052 |
+
embed_tokens (nn.Embedding): output embedding
|
| 1053 |
+
"""
|
| 1054 |
+
|
| 1055 |
+
def __init__(self, config, embed_tokens=None):
|
| 1056 |
+
|
| 1057 |
+
super().__init__(config)
|
| 1058 |
+
self.dropout = config.dropout
|
| 1059 |
+
self.layerdrop = config.encoder_layerdrop
|
| 1060 |
+
|
| 1061 |
+
embed_dim = config.d_model
|
| 1062 |
+
self.padding_idx = config.pad_token_id
|
| 1063 |
+
self.max_source_positions = config.max_position_embeddings
|
| 1064 |
+
self.embed_scale = math.sqrt(embed_dim) if config.scale_embedding else 1.0
|
| 1065 |
+
|
| 1066 |
+
if embed_tokens is not None:
|
| 1067 |
+
self.embed_tokens = embed_tokens
|
| 1068 |
+
else:
|
| 1069 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, embed_dim, self.padding_idx)
|
| 1070 |
+
|
| 1071 |
+
self.embed_positions = LSGBartLearnedPositionalEmbedding(
|
| 1072 |
+
config.max_position_embeddings,
|
| 1073 |
+
embed_dim,
|
| 1074 |
+
)
|
| 1075 |
+
self.layers = nn.ModuleList([LSGBartEncoderLayer(config) for _ in range(config.encoder_layers)])
|
| 1076 |
+
self.layernorm_embedding = nn.LayerNorm(embed_dim)
|
| 1077 |
+
|
| 1078 |
+
#
|
| 1079 |
+
assert hasattr(config, "num_global_tokens")
|
| 1080 |
+
self.num_global_tokens = config.num_global_tokens
|
| 1081 |
+
self.pad_idx = config.pad_token_id
|
| 1082 |
+
|
| 1083 |
+
assert hasattr(config, "block_size") and hasattr(config, "adaptive")
|
| 1084 |
+
self.block_size = config.block_size
|
| 1085 |
+
self.adaptive = config.adaptive
|
| 1086 |
+
self.pool_with_global = config.pool_with_global
|
| 1087 |
+
self.pass_global_tokens_to_decoder = config.pass_global_tokens_to_decoder
|
| 1088 |
+
|
| 1089 |
+
self.global_embeddings = nn.Embedding(512, embedding_dim=config.d_model)
|
| 1090 |
+
|
| 1091 |
+
self.gradient_checkpointing = False
|
| 1092 |
+
|
| 1093 |
+
# Initialize weights and apply final processing
|
| 1094 |
+
self.post_init()
|
| 1095 |
+
|
| 1096 |
+
def get_input_embeddings(self):
|
| 1097 |
+
return self.embed_tokens
|
| 1098 |
+
|
| 1099 |
+
def set_input_embeddings(self, value):
|
| 1100 |
+
self.embed_tokens = value
|
| 1101 |
+
|
| 1102 |
+
def forward(self,
|
| 1103 |
+
input_ids=None,
|
| 1104 |
+
attention_mask=None,
|
| 1105 |
+
head_mask=None,
|
| 1106 |
+
inputs_embeds=None,
|
| 1107 |
+
output_attentions=None,
|
| 1108 |
+
output_hidden_states=None,
|
| 1109 |
+
return_dict=None
|
| 1110 |
+
):
|
| 1111 |
+
|
| 1112 |
+
|
| 1113 |
+
inputs_ = input_ids if input_ids is not None else inputs_embeds
|
| 1114 |
+
n, t = inputs_.size()[:2]
|
| 1115 |
+
|
| 1116 |
+
if attention_mask is None:
|
| 1117 |
+
attention_mask = torch.ones(n, t, device=inputs_.device)
|
| 1118 |
+
|
| 1119 |
+
b = self.block_size * 2
|
| 1120 |
+
pad = t % self.block_size
|
| 1121 |
+
|
| 1122 |
+
# Check if t is multiple of block_size and pad
|
| 1123 |
+
if t > b and pad > 0:
|
| 1124 |
+
pad_length = self.block_size - pad
|
| 1125 |
+
if input_ids is not None:
|
| 1126 |
+
input_ids = torch.nn.functional.pad(input_ids, (0, pad_length), value=self.pad_idx)
|
| 1127 |
+
else:
|
| 1128 |
+
inputs_embeds = torch.nn.functional.pad(inputs_embeds.transpose(-1, -2), (0, pad_length), value=0.).transpose(-1, -2)
|
| 1129 |
+
attention_mask = torch.nn.functional.pad(attention_mask, (0, pad_length), value=0)
|
| 1130 |
+
|
| 1131 |
+
# else adaptive sequence length
|
| 1132 |
+
elif self.adaptive:
|
| 1133 |
+
s = int(torch.max(attention_mask.sum(dim=-1)))
|
| 1134 |
+
if s < t and self.block_size is not None:
|
| 1135 |
+
s = max(2, s // self.block_size + 1) * self.block_size if s > b else s
|
| 1136 |
+
if input_ids is not None:
|
| 1137 |
+
input_ids = input_ids[:, :s]
|
| 1138 |
+
else:
|
| 1139 |
+
inputs_embeds = inputs_embeds[:, :s]
|
| 1140 |
+
attention_mask = attention_mask[:, :s]
|
| 1141 |
+
|
| 1142 |
+
n, t_ = attention_mask.size()
|
| 1143 |
+
|
| 1144 |
+
encoder_outputs = self.forward_with_adaptive(
|
| 1145 |
+
input_ids=input_ids,
|
| 1146 |
+
attention_mask=attention_mask,
|
| 1147 |
+
head_mask=head_mask,
|
| 1148 |
+
inputs_embeds=inputs_embeds,
|
| 1149 |
+
output_attentions=output_attentions,
|
| 1150 |
+
output_hidden_states=output_hidden_states,
|
| 1151 |
+
return_dict=return_dict,
|
| 1152 |
+
)
|
| 1153 |
+
|
| 1154 |
+
context = encoder_outputs[0]
|
| 1155 |
+
diff = t - t_
|
| 1156 |
+
|
| 1157 |
+
if self.pass_global_tokens_to_decoder:
|
| 1158 |
+
offset = self.num_global_tokens
|
| 1159 |
+
else:
|
| 1160 |
+
if self.pool_with_global:
|
| 1161 |
+
context[:, self.num_global_tokens] = context[:, 0]
|
| 1162 |
+
context = context[..., self.num_global_tokens:, :]
|
| 1163 |
+
offset = 0
|
| 1164 |
+
|
| 1165 |
+
# Adapt sequence to initial shape
|
| 1166 |
+
if diff > 0:
|
| 1167 |
+
context = torch.nn.functional.pad(context.transpose(-1, -2), pad=(0, diff), value=0).transpose(-1, -2)
|
| 1168 |
+
elif diff < 0:
|
| 1169 |
+
context = context[:, :t + offset]
|
| 1170 |
+
|
| 1171 |
+
if return_dict:
|
| 1172 |
+
encoder_outputs.last_hidden_state = context
|
| 1173 |
+
else:
|
| 1174 |
+
encoder_outputs = (context, ) + encoder_outputs[1:]
|
| 1175 |
+
|
| 1176 |
+
return encoder_outputs
|
| 1177 |
+
|
| 1178 |
+
def forward_with_adaptive(
|
| 1179 |
+
self,
|
| 1180 |
+
input_ids=None,
|
| 1181 |
+
attention_mask=None,
|
| 1182 |
+
head_mask=None,
|
| 1183 |
+
inputs_embeds=None,
|
| 1184 |
+
output_attentions=None,
|
| 1185 |
+
output_hidden_states=None,
|
| 1186 |
+
return_dict=None,
|
| 1187 |
+
):
|
| 1188 |
+
|
| 1189 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 1190 |
+
output_hidden_states = (
|
| 1191 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 1192 |
+
)
|
| 1193 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1194 |
+
|
| 1195 |
+
# retrieve input_ids and inputs_embeds
|
| 1196 |
+
if input_ids is not None and inputs_embeds is not None:
|
| 1197 |
+
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
| 1198 |
+
elif input_ids is not None:
|
| 1199 |
+
input_shape = input_ids.size()
|
| 1200 |
+
input_ids = input_ids.view(-1, input_shape[-1])
|
| 1201 |
+
elif inputs_embeds is not None:
|
| 1202 |
+
input_shape = inputs_embeds.size()[:-1]
|
| 1203 |
+
else:
|
| 1204 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
| 1205 |
+
|
| 1206 |
+
if inputs_embeds is None:
|
| 1207 |
+
inputs_embeds = self.embed_tokens(input_ids) * self.embed_scale
|
| 1208 |
+
|
| 1209 |
+
embed_pos = self.embed_positions(input_shape)
|
| 1210 |
+
hidden_states = inputs_embeds + embed_pos
|
| 1211 |
+
|
| 1212 |
+
# Add global tokens
|
| 1213 |
+
n, t, d = hidden_states.size()
|
| 1214 |
+
global_idx = torch.arange(self.num_global_tokens, device=hidden_states.device).reshape(1, -1)
|
| 1215 |
+
hidden_states = torch.cat([self.global_embeddings(global_idx).expand(n, -1, -1), hidden_states], dim=-2)
|
| 1216 |
+
|
| 1217 |
+
hidden_states = self.layernorm_embedding(hidden_states)
|
| 1218 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
|
| 1219 |
+
|
| 1220 |
+
# expand attention_mask
|
| 1221 |
+
if attention_mask is not None:
|
| 1222 |
+
# [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
|
| 1223 |
+
attention_mask = _expand_mask(attention_mask, inputs_embeds.dtype)
|
| 1224 |
+
|
| 1225 |
+
encoder_states = () if output_hidden_states else None
|
| 1226 |
+
all_attentions = () if output_attentions else None
|
| 1227 |
+
|
| 1228 |
+
# check if head_mask has a correct number of layers specified if desired
|
| 1229 |
+
if head_mask is not None:
|
| 1230 |
+
if head_mask.size()[0] != (len(self.layers)):
|
| 1231 |
+
raise ValueError(
|
| 1232 |
+
f"The head_mask should be specified for {len(self.layers)} layers, but it is for {head_mask.size()[0]}."
|
| 1233 |
+
)
|
| 1234 |
+
|
| 1235 |
+
for idx, encoder_layer in enumerate(self.layers):
|
| 1236 |
+
if output_hidden_states:
|
| 1237 |
+
encoder_states = encoder_states + (hidden_states,)
|
| 1238 |
+
# add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
|
| 1239 |
+
dropout_probability = random.uniform(0, 1)
|
| 1240 |
+
if self.training and (dropout_probability < self.layerdrop): # skip the layer
|
| 1241 |
+
layer_outputs = (None, None)
|
| 1242 |
+
else:
|
| 1243 |
+
if self.gradient_checkpointing and self.training:
|
| 1244 |
+
|
| 1245 |
+
def create_custom_forward(module):
|
| 1246 |
+
def custom_forward(*inputs):
|
| 1247 |
+
return module(*inputs, output_attentions)
|
| 1248 |
+
|
| 1249 |
+
return custom_forward
|
| 1250 |
+
|
| 1251 |
+
layer_outputs = torch.utils.checkpoint.checkpoint(
|
| 1252 |
+
create_custom_forward(encoder_layer),
|
| 1253 |
+
hidden_states,
|
| 1254 |
+
attention_mask,
|
| 1255 |
+
(head_mask[idx] if head_mask is not None else None),
|
| 1256 |
+
)
|
| 1257 |
+
else:
|
| 1258 |
+
layer_outputs = encoder_layer(
|
| 1259 |
+
hidden_states,
|
| 1260 |
+
attention_mask,
|
| 1261 |
+
layer_head_mask=(head_mask[idx] if head_mask is not None else None),
|
| 1262 |
+
output_attentions=output_attentions,
|
| 1263 |
+
)
|
| 1264 |
+
|
| 1265 |
+
hidden_states = layer_outputs[0]
|
| 1266 |
+
|
| 1267 |
+
if output_attentions:
|
| 1268 |
+
all_attentions = all_attentions + (layer_outputs[1],)
|
| 1269 |
+
|
| 1270 |
+
if output_hidden_states:
|
| 1271 |
+
encoder_states = encoder_states + (hidden_states,)
|
| 1272 |
+
|
| 1273 |
+
if not return_dict:
|
| 1274 |
+
return tuple(v for v in [hidden_states, encoder_states, all_attentions] if v is not None)
|
| 1275 |
+
return BaseModelOutput(
|
| 1276 |
+
last_hidden_state=hidden_states, hidden_states=encoder_states, attentions=all_attentions
|
| 1277 |
+
)
|
| 1278 |
+
|
| 1279 |
+
|
| 1280 |
+
class LSGBartDecoder(LSGBartPretrainedModel):
|
| 1281 |
+
"""
|
| 1282 |
+
Transformer decoder consisting of *config.decoder_layers* layers. Each layer is a :class:`LSGBartDecoderLayer`
|
| 1283 |
+
Args:
|
| 1284 |
+
config: BartConfig
|
| 1285 |
+
embed_tokens (nn.Embedding): output embedding
|
| 1286 |
+
"""
|
| 1287 |
+
|
| 1288 |
+
def __init__(self, config, embed_tokens=None):
|
| 1289 |
+
|
| 1290 |
+
super().__init__(config)
|
| 1291 |
+
self.dropout = config.dropout
|
| 1292 |
+
self.layerdrop = config.decoder_layerdrop
|
| 1293 |
+
self.padding_idx = config.pad_token_id
|
| 1294 |
+
self.max_target_positions = config.max_position_embeddings
|
| 1295 |
+
self.embed_scale = math.sqrt(config.d_model) if config.scale_embedding else 1.0
|
| 1296 |
+
|
| 1297 |
+
if embed_tokens is not None:
|
| 1298 |
+
self.embed_tokens = embed_tokens
|
| 1299 |
+
else:
|
| 1300 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, config.d_model, self.padding_idx)
|
| 1301 |
+
|
| 1302 |
+
self.embed_positions = LSGBartLearnedPositionalEmbedding(
|
| 1303 |
+
config.max_position_embeddings,
|
| 1304 |
+
config.d_model,
|
| 1305 |
+
)
|
| 1306 |
+
self.layers = nn.ModuleList([LSGBartDecoderLayer(config) for _ in range(config.decoder_layers)])
|
| 1307 |
+
self.layernorm_embedding = nn.LayerNorm(config.d_model)
|
| 1308 |
+
|
| 1309 |
+
self.gradient_checkpointing = False
|
| 1310 |
+
|
| 1311 |
+
# Initialize weights and apply final processing
|
| 1312 |
+
self.post_init()
|
| 1313 |
+
|
| 1314 |
+
def get_input_embeddings(self):
|
| 1315 |
+
return self.embed_tokens
|
| 1316 |
+
|
| 1317 |
+
def set_input_embeddings(self, value):
|
| 1318 |
+
self.embed_tokens = value
|
| 1319 |
+
|
| 1320 |
+
def _prepare_decoder_attention_mask(self, attention_mask, input_shape, inputs_embeds, past_key_values_length):
|
| 1321 |
+
# create causal mask
|
| 1322 |
+
# [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
|
| 1323 |
+
combined_attention_mask = None
|
| 1324 |
+
if input_shape[-1] > 1:
|
| 1325 |
+
combined_attention_mask = _make_causal_mask(
|
| 1326 |
+
input_shape, inputs_embeds.dtype, past_key_values_length=past_key_values_length
|
| 1327 |
+
).to(self.device)
|
| 1328 |
+
|
| 1329 |
+
if attention_mask is not None:
|
| 1330 |
+
# [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
|
| 1331 |
+
expanded_attn_mask = _expand_mask(attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1])
|
| 1332 |
+
combined_attention_mask = (
|
| 1333 |
+
expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask + combined_attention_mask
|
| 1334 |
+
)
|
| 1335 |
+
|
| 1336 |
+
return combined_attention_mask
|
| 1337 |
+
|
| 1338 |
+
def forward(
|
| 1339 |
+
self,
|
| 1340 |
+
input_ids=None,
|
| 1341 |
+
attention_mask=None,
|
| 1342 |
+
encoder_hidden_states=None,
|
| 1343 |
+
encoder_attention_mask=None,
|
| 1344 |
+
head_mask=None,
|
| 1345 |
+
cross_attn_head_mask=None,
|
| 1346 |
+
past_key_values=None,
|
| 1347 |
+
inputs_embeds=None,
|
| 1348 |
+
use_cache=None,
|
| 1349 |
+
output_attentions=None,
|
| 1350 |
+
output_hidden_states=None,
|
| 1351 |
+
return_dict=None,
|
| 1352 |
+
):
|
| 1353 |
+
|
| 1354 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 1355 |
+
output_hidden_states = (
|
| 1356 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 1357 |
+
)
|
| 1358 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
| 1359 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1360 |
+
|
| 1361 |
+
# retrieve input_ids and inputs_embeds
|
| 1362 |
+
if input_ids is not None and inputs_embeds is not None:
|
| 1363 |
+
raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
|
| 1364 |
+
elif input_ids is not None:
|
| 1365 |
+
input_shape = input_ids.size()
|
| 1366 |
+
input_ids = input_ids.view(-1, input_shape[-1])
|
| 1367 |
+
elif inputs_embeds is not None:
|
| 1368 |
+
input_shape = inputs_embeds.size()[:-1]
|
| 1369 |
+
else:
|
| 1370 |
+
raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
|
| 1371 |
+
|
| 1372 |
+
# past_key_values_length
|
| 1373 |
+
past_key_values_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0
|
| 1374 |
+
|
| 1375 |
+
if inputs_embeds is None:
|
| 1376 |
+
inputs_embeds = self.embed_tokens(input_ids) * self.embed_scale
|
| 1377 |
+
|
| 1378 |
+
# Cut
|
| 1379 |
+
if attention_mask is not None:
|
| 1380 |
+
max_len = int(attention_mask.sum(dim=-1).max())
|
| 1381 |
+
inputs_embeds = inputs_embeds[:, :max_len]
|
| 1382 |
+
attention_mask = attention_mask[..., :max_len]
|
| 1383 |
+
input_shape = inputs_embeds.size()[:-1]
|
| 1384 |
+
|
| 1385 |
+
attention_mask = self._prepare_decoder_attention_mask(
|
| 1386 |
+
attention_mask, input_shape, inputs_embeds, past_key_values_length
|
| 1387 |
+
)
|
| 1388 |
+
|
| 1389 |
+
# expand encoder attention mask
|
| 1390 |
+
if encoder_hidden_states is not None and encoder_attention_mask is not None:
|
| 1391 |
+
# [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
|
| 1392 |
+
encoder_attention_mask = _expand_mask(encoder_attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1])
|
| 1393 |
+
|
| 1394 |
+
# embed positions
|
| 1395 |
+
positions = self.embed_positions(input_shape, past_key_values_length)
|
| 1396 |
+
|
| 1397 |
+
hidden_states = inputs_embeds + positions
|
| 1398 |
+
hidden_states = self.layernorm_embedding(hidden_states)
|
| 1399 |
+
|
| 1400 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
|
| 1401 |
+
|
| 1402 |
+
# decoder layers
|
| 1403 |
+
all_hidden_states = () if output_hidden_states else None
|
| 1404 |
+
all_self_attns = () if output_attentions else None
|
| 1405 |
+
all_cross_attentions = () if (output_attentions and encoder_hidden_states is not None) else None
|
| 1406 |
+
next_decoder_cache = () if use_cache else None
|
| 1407 |
+
|
| 1408 |
+
# check if head_mask/cross_attn_head_mask has a correct number of layers specified if desired
|
| 1409 |
+
for attn_mask, mask_name in zip([head_mask, cross_attn_head_mask], ["head_mask", "cross_attn_head_mask"]):
|
| 1410 |
+
if attn_mask is not None:
|
| 1411 |
+
if attn_mask.size()[0] != (len(self.layers)):
|
| 1412 |
+
raise ValueError(
|
| 1413 |
+
"The `{mask_name}` should be specified for {len(self.layers)} layers, but it is for {head_mask.size()[0]}."
|
| 1414 |
+
)
|
| 1415 |
+
|
| 1416 |
+
for idx, decoder_layer in enumerate(self.layers):
|
| 1417 |
+
# add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
|
| 1418 |
+
if output_hidden_states:
|
| 1419 |
+
all_hidden_states += (hidden_states,)
|
| 1420 |
+
dropout_probability = random.uniform(0, 1)
|
| 1421 |
+
if self.training and (dropout_probability < self.layerdrop):
|
| 1422 |
+
continue
|
| 1423 |
+
|
| 1424 |
+
past_key_value = past_key_values[idx] if past_key_values is not None else None
|
| 1425 |
+
|
| 1426 |
+
if self.gradient_checkpointing and self.training:
|
| 1427 |
+
|
| 1428 |
+
if use_cache:
|
| 1429 |
+
logger.warning(
|
| 1430 |
+
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
|
| 1431 |
+
)
|
| 1432 |
+
use_cache = False
|
| 1433 |
+
|
| 1434 |
+
def create_custom_forward(module):
|
| 1435 |
+
def custom_forward(*inputs):
|
| 1436 |
+
# None for past_key_value
|
| 1437 |
+
return module(*inputs, output_attentions, use_cache)
|
| 1438 |
+
|
| 1439 |
+
return custom_forward
|
| 1440 |
+
|
| 1441 |
+
layer_outputs = torch.utils.checkpoint.checkpoint(
|
| 1442 |
+
create_custom_forward(decoder_layer),
|
| 1443 |
+
hidden_states,
|
| 1444 |
+
attention_mask,
|
| 1445 |
+
encoder_hidden_states,
|
| 1446 |
+
encoder_attention_mask,
|
| 1447 |
+
head_mask[idx] if head_mask is not None else None,
|
| 1448 |
+
cross_attn_head_mask[idx] if cross_attn_head_mask is not None else None,
|
| 1449 |
+
None,
|
| 1450 |
+
)
|
| 1451 |
+
else:
|
| 1452 |
+
|
| 1453 |
+
layer_outputs = decoder_layer(
|
| 1454 |
+
hidden_states,
|
| 1455 |
+
attention_mask=attention_mask,
|
| 1456 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 1457 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 1458 |
+
layer_head_mask=(head_mask[idx] if head_mask is not None else None),
|
| 1459 |
+
cross_attn_layer_head_mask=(
|
| 1460 |
+
cross_attn_head_mask[idx] if cross_attn_head_mask is not None else None
|
| 1461 |
+
),
|
| 1462 |
+
past_key_value=past_key_value,
|
| 1463 |
+
output_attentions=output_attentions,
|
| 1464 |
+
use_cache=use_cache,
|
| 1465 |
+
)
|
| 1466 |
+
hidden_states = layer_outputs[0]
|
| 1467 |
+
|
| 1468 |
+
if use_cache:
|
| 1469 |
+
next_decoder_cache += (layer_outputs[3 if output_attentions else 1],)
|
| 1470 |
+
|
| 1471 |
+
if output_attentions:
|
| 1472 |
+
all_self_attns += (layer_outputs[1],)
|
| 1473 |
+
|
| 1474 |
+
if encoder_hidden_states is not None:
|
| 1475 |
+
all_cross_attentions += (layer_outputs[2],)
|
| 1476 |
+
|
| 1477 |
+
# add hidden states from the last decoder layer
|
| 1478 |
+
if output_hidden_states:
|
| 1479 |
+
all_hidden_states += (hidden_states,)
|
| 1480 |
+
|
| 1481 |
+
next_cache = next_decoder_cache if use_cache else None
|
| 1482 |
+
if not return_dict:
|
| 1483 |
+
return tuple(
|
| 1484 |
+
v
|
| 1485 |
+
for v in [hidden_states, next_cache, all_hidden_states, all_self_attns, all_cross_attentions]
|
| 1486 |
+
if v is not None
|
| 1487 |
+
)
|
| 1488 |
+
return BaseModelOutputWithPastAndCrossAttentions(
|
| 1489 |
+
last_hidden_state=hidden_states,
|
| 1490 |
+
past_key_values=next_cache,
|
| 1491 |
+
hidden_states=all_hidden_states,
|
| 1492 |
+
attentions=all_self_attns,
|
| 1493 |
+
cross_attentions=all_cross_attentions,
|
| 1494 |
+
)
|
| 1495 |
+
|
| 1496 |
+
|
| 1497 |
+
class LSGBartModel(LSGBartPretrainedModel):
|
| 1498 |
+
|
| 1499 |
+
def __init__(self, config):
|
| 1500 |
+
|
| 1501 |
+
super().__init__(config)
|
| 1502 |
+
|
| 1503 |
+
padding_idx, vocab_size = config.pad_token_id, config.vocab_size
|
| 1504 |
+
self.shared = nn.Embedding(vocab_size, config.d_model, padding_idx)
|
| 1505 |
+
self.pass_global_tokens_to_decoder = config.pass_global_tokens_to_decoder
|
| 1506 |
+
self.num_global_tokens = config.num_global_tokens
|
| 1507 |
+
self.encoder = LSGBartEncoder(config, self.shared)
|
| 1508 |
+
self.decoder = LSGBartDecoder(config, self.shared)
|
| 1509 |
+
|
| 1510 |
+
# Initialize weights and apply final processing
|
| 1511 |
+
self.post_init()
|
| 1512 |
+
|
| 1513 |
+
def get_input_embeddings(self):
|
| 1514 |
+
return self.shared
|
| 1515 |
+
|
| 1516 |
+
def set_input_embeddings(self, value):
|
| 1517 |
+
self.shared = value
|
| 1518 |
+
self.encoder.embed_tokens = self.shared
|
| 1519 |
+
self.decoder.embed_tokens = self.shared
|
| 1520 |
+
|
| 1521 |
+
def get_encoder(self):
|
| 1522 |
+
return self.encoder
|
| 1523 |
+
|
| 1524 |
+
def get_decoder(self):
|
| 1525 |
+
return self.decoder
|
| 1526 |
+
|
| 1527 |
+
def forward(
|
| 1528 |
+
self,
|
| 1529 |
+
input_ids=None,
|
| 1530 |
+
attention_mask=None,
|
| 1531 |
+
decoder_input_ids=None,
|
| 1532 |
+
decoder_attention_mask=None,
|
| 1533 |
+
head_mask=None,
|
| 1534 |
+
decoder_head_mask=None,
|
| 1535 |
+
cross_attn_head_mask=None,
|
| 1536 |
+
encoder_outputs=None,
|
| 1537 |
+
past_key_values=None,
|
| 1538 |
+
inputs_embeds=None,
|
| 1539 |
+
decoder_inputs_embeds=None,
|
| 1540 |
+
use_cache=None,
|
| 1541 |
+
output_attentions=None,
|
| 1542 |
+
output_hidden_states=None,
|
| 1543 |
+
return_dict=None,
|
| 1544 |
+
):
|
| 1545 |
+
|
| 1546 |
+
# different to other models, Bart automatically creates decoder_input_ids from
|
| 1547 |
+
# input_ids if no decoder_input_ids are provided
|
| 1548 |
+
if decoder_input_ids is None and decoder_inputs_embeds is None:
|
| 1549 |
+
decoder_input_ids = shift_tokens_right(
|
| 1550 |
+
input_ids, self.config.pad_token_id, self.config.decoder_start_token_id
|
| 1551 |
+
)
|
| 1552 |
+
|
| 1553 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 1554 |
+
output_hidden_states = (
|
| 1555 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 1556 |
+
)
|
| 1557 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
| 1558 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1559 |
+
|
| 1560 |
+
if encoder_outputs is None:
|
| 1561 |
+
encoder_outputs = self.encoder(
|
| 1562 |
+
input_ids=input_ids,
|
| 1563 |
+
attention_mask=attention_mask,
|
| 1564 |
+
head_mask=head_mask,
|
| 1565 |
+
inputs_embeds=inputs_embeds,
|
| 1566 |
+
output_attentions=output_attentions,
|
| 1567 |
+
output_hidden_states=output_hidden_states,
|
| 1568 |
+
return_dict=return_dict,
|
| 1569 |
+
)
|
| 1570 |
+
# If the user passed a tuple for encoder_outputs, we wrap it in a BaseModelOutput when return_dict=True
|
| 1571 |
+
elif return_dict and not isinstance(encoder_outputs, BaseModelOutput):
|
| 1572 |
+
encoder_outputs = BaseModelOutput(
|
| 1573 |
+
last_hidden_state=encoder_outputs[0],
|
| 1574 |
+
hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,
|
| 1575 |
+
attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,
|
| 1576 |
+
)
|
| 1577 |
+
|
| 1578 |
+
# Pad mask for global tokens
|
| 1579 |
+
if self.pass_global_tokens_to_decoder:
|
| 1580 |
+
attention_mask = torch.nn.functional.pad(attention_mask, pad=(self.num_global_tokens, 0), value=1)
|
| 1581 |
+
|
| 1582 |
+
# decoder outputs consists of (dec_features, past_key_value, dec_hidden, dec_attn)
|
| 1583 |
+
decoder_outputs = self.decoder(
|
| 1584 |
+
input_ids=decoder_input_ids,
|
| 1585 |
+
attention_mask=decoder_attention_mask,
|
| 1586 |
+
encoder_hidden_states=encoder_outputs[0],
|
| 1587 |
+
encoder_attention_mask=attention_mask,
|
| 1588 |
+
head_mask=decoder_head_mask,
|
| 1589 |
+
cross_attn_head_mask=cross_attn_head_mask,
|
| 1590 |
+
past_key_values=past_key_values,
|
| 1591 |
+
inputs_embeds=decoder_inputs_embeds,
|
| 1592 |
+
use_cache=use_cache,
|
| 1593 |
+
output_attentions=output_attentions,
|
| 1594 |
+
output_hidden_states=output_hidden_states,
|
| 1595 |
+
return_dict=return_dict,
|
| 1596 |
+
)
|
| 1597 |
+
|
| 1598 |
+
if not return_dict:
|
| 1599 |
+
return decoder_outputs + encoder_outputs
|
| 1600 |
+
|
| 1601 |
+
return Seq2SeqModelOutput(
|
| 1602 |
+
last_hidden_state=decoder_outputs.last_hidden_state,
|
| 1603 |
+
past_key_values=decoder_outputs.past_key_values,
|
| 1604 |
+
decoder_hidden_states=decoder_outputs.hidden_states,
|
| 1605 |
+
decoder_attentions=decoder_outputs.attentions,
|
| 1606 |
+
cross_attentions=decoder_outputs.cross_attentions,
|
| 1607 |
+
encoder_last_hidden_state=encoder_outputs.last_hidden_state,
|
| 1608 |
+
encoder_hidden_states=encoder_outputs.hidden_states,
|
| 1609 |
+
encoder_attentions=encoder_outputs.attentions,
|
| 1610 |
+
)
|
| 1611 |
+
|
| 1612 |
+
|
| 1613 |
+
class LSGBartForConditionalGeneration(LSGBartPretrainedModel):
|
| 1614 |
+
|
| 1615 |
+
base_model_prefix = "model"
|
| 1616 |
+
_keys_to_ignore_on_load_missing = [r"final_logits_bias", r"lm_head\.weight"]
|
| 1617 |
+
|
| 1618 |
+
def __init__(self, config):
|
| 1619 |
+
|
| 1620 |
+
super().__init__(config)
|
| 1621 |
+
self.model = LSGBartModel(config)
|
| 1622 |
+
self.register_buffer("final_logits_bias", torch.zeros((1, self.model.shared.num_embeddings)))
|
| 1623 |
+
self.lm_head = nn.Linear(config.d_model, self.model.shared.num_embeddings, bias=False)
|
| 1624 |
+
|
| 1625 |
+
# Initialize weights and apply final processing
|
| 1626 |
+
self.post_init()
|
| 1627 |
+
|
| 1628 |
+
def get_encoder(self):
|
| 1629 |
+
return self.model.get_encoder()
|
| 1630 |
+
|
| 1631 |
+
def get_decoder(self):
|
| 1632 |
+
return self.model.get_decoder()
|
| 1633 |
+
|
| 1634 |
+
def resize_token_embeddings(self, new_num_tokens):
|
| 1635 |
+
new_embeddings = super().resize_token_embeddings(new_num_tokens)
|
| 1636 |
+
self._resize_final_logits_bias(new_num_tokens)
|
| 1637 |
+
return new_embeddings
|
| 1638 |
+
|
| 1639 |
+
def _resize_final_logits_bias(self, new_num_tokens):
|
| 1640 |
+
old_num_tokens = self.final_logits_bias.shape[-1]
|
| 1641 |
+
if new_num_tokens <= old_num_tokens:
|
| 1642 |
+
new_bias = self.final_logits_bias[:, :new_num_tokens]
|
| 1643 |
+
else:
|
| 1644 |
+
extra_bias = torch.zeros((1, new_num_tokens - old_num_tokens), device=self.final_logits_bias.device)
|
| 1645 |
+
new_bias = torch.cat([self.final_logits_bias, extra_bias], dim=1)
|
| 1646 |
+
self.register_buffer("final_logits_bias", new_bias)
|
| 1647 |
+
|
| 1648 |
+
def get_output_embeddings(self):
|
| 1649 |
+
return self.lm_head
|
| 1650 |
+
|
| 1651 |
+
def set_output_embeddings(self, new_embeddings):
|
| 1652 |
+
self.lm_head = new_embeddings
|
| 1653 |
+
|
| 1654 |
+
def forward(
|
| 1655 |
+
self,
|
| 1656 |
+
input_ids=None,
|
| 1657 |
+
attention_mask=None,
|
| 1658 |
+
decoder_input_ids=None,
|
| 1659 |
+
decoder_attention_mask=None,
|
| 1660 |
+
head_mask=None,
|
| 1661 |
+
decoder_head_mask=None,
|
| 1662 |
+
cross_attn_head_mask=None,
|
| 1663 |
+
encoder_outputs=None,
|
| 1664 |
+
past_key_values=None,
|
| 1665 |
+
inputs_embeds=None,
|
| 1666 |
+
decoder_inputs_embeds=None,
|
| 1667 |
+
labels=None,
|
| 1668 |
+
use_cache=None,
|
| 1669 |
+
output_attentions=None,
|
| 1670 |
+
output_hidden_states=None,
|
| 1671 |
+
return_dict=None,
|
| 1672 |
+
):
|
| 1673 |
+
|
| 1674 |
+
r"""
|
| 1675 |
+
labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):
|
| 1676 |
+
Labels for computing the masked language modeling loss. Indices should either be in ``[0, ...,
|
| 1677 |
+
config.vocab_size]`` or -100 (see ``input_ids`` docstring). Tokens with indices set to ``-100`` are ignored
|
| 1678 |
+
(masked), the loss is only computed for the tokens with labels in ``[0, ..., config.vocab_size]``.
|
| 1679 |
+
Returns:
|
| 1680 |
+
"""
|
| 1681 |
+
|
| 1682 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1683 |
+
|
| 1684 |
+
if labels is not None:
|
| 1685 |
+
if decoder_input_ids is None and decoder_inputs_embeds is None:
|
| 1686 |
+
decoder_input_ids = shift_tokens_right(
|
| 1687 |
+
labels, self.config.pad_token_id, self.config.decoder_start_token_id
|
| 1688 |
+
)
|
| 1689 |
+
|
| 1690 |
+
outputs = self.model(
|
| 1691 |
+
input_ids,
|
| 1692 |
+
attention_mask=attention_mask,
|
| 1693 |
+
decoder_input_ids=decoder_input_ids,
|
| 1694 |
+
encoder_outputs=encoder_outputs,
|
| 1695 |
+
decoder_attention_mask=decoder_attention_mask,
|
| 1696 |
+
head_mask=head_mask,
|
| 1697 |
+
decoder_head_mask=decoder_head_mask,
|
| 1698 |
+
cross_attn_head_mask=cross_attn_head_mask,
|
| 1699 |
+
past_key_values=past_key_values,
|
| 1700 |
+
inputs_embeds=inputs_embeds,
|
| 1701 |
+
decoder_inputs_embeds=decoder_inputs_embeds,
|
| 1702 |
+
use_cache=use_cache,
|
| 1703 |
+
output_attentions=output_attentions,
|
| 1704 |
+
output_hidden_states=output_hidden_states,
|
| 1705 |
+
return_dict=return_dict,
|
| 1706 |
+
)
|
| 1707 |
+
|
| 1708 |
+
|
| 1709 |
+
lm_logits = self.lm_head(outputs[0]) + self.final_logits_bias
|
| 1710 |
+
|
| 1711 |
+
masked_lm_loss = None
|
| 1712 |
+
if labels is not None:
|
| 1713 |
+
loss_fct = CrossEntropyLoss()
|
| 1714 |
+
masked_lm_loss = loss_fct(lm_logits.view(-1, self.config.vocab_size), labels.view(-1))
|
| 1715 |
+
|
| 1716 |
+
if not return_dict:
|
| 1717 |
+
output = (lm_logits,) + outputs[1:]
|
| 1718 |
+
return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
|
| 1719 |
+
|
| 1720 |
+
return Seq2SeqLMOutput(
|
| 1721 |
+
loss=masked_lm_loss,
|
| 1722 |
+
logits=lm_logits,
|
| 1723 |
+
past_key_values=outputs.past_key_values,
|
| 1724 |
+
decoder_hidden_states=outputs.decoder_hidden_states,
|
| 1725 |
+
decoder_attentions=outputs.decoder_attentions,
|
| 1726 |
+
cross_attentions=outputs.cross_attentions,
|
| 1727 |
+
encoder_last_hidden_state=outputs.encoder_last_hidden_state,
|
| 1728 |
+
encoder_hidden_states=outputs.encoder_hidden_states,
|
| 1729 |
+
encoder_attentions=outputs.encoder_attentions,
|
| 1730 |
+
)
|
| 1731 |
+
|
| 1732 |
+
def prepare_inputs_for_generation(
|
| 1733 |
+
self,
|
| 1734 |
+
decoder_input_ids,
|
| 1735 |
+
past=None,
|
| 1736 |
+
attention_mask=None,
|
| 1737 |
+
head_mask=None,
|
| 1738 |
+
decoder_head_mask=None,
|
| 1739 |
+
cross_attn_head_mask=None,
|
| 1740 |
+
use_cache=None,
|
| 1741 |
+
encoder_outputs=None,
|
| 1742 |
+
**kwargs
|
| 1743 |
+
):
|
| 1744 |
+
# cut decoder_input_ids if past is used
|
| 1745 |
+
if past is not None:
|
| 1746 |
+
decoder_input_ids = decoder_input_ids[:, -1:]
|
| 1747 |
+
|
| 1748 |
+
return {
|
| 1749 |
+
"input_ids": None, # encoder_outputs is defined. input_ids not needed
|
| 1750 |
+
"encoder_outputs": encoder_outputs,
|
| 1751 |
+
"past_key_values": past,
|
| 1752 |
+
"decoder_input_ids": decoder_input_ids,
|
| 1753 |
+
"attention_mask": attention_mask,
|
| 1754 |
+
"head_mask": head_mask,
|
| 1755 |
+
"decoder_head_mask": decoder_head_mask,
|
| 1756 |
+
"cross_attn_head_mask": cross_attn_head_mask,
|
| 1757 |
+
"use_cache": use_cache, # change this to avoid caching (presumably for debugging)
|
| 1758 |
+
}
|
| 1759 |
+
|
| 1760 |
+
def prepare_decoder_input_ids_from_labels(self, labels):
|
| 1761 |
+
return shift_tokens_right(labels, self.config.pad_token_id, self.config.decoder_start_token_id)
|
| 1762 |
+
|
| 1763 |
+
@staticmethod
|
| 1764 |
+
def _reorder_cache(past, beam_idx):
|
| 1765 |
+
reordered_past = ()
|
| 1766 |
+
for layer_past in past:
|
| 1767 |
+
# cached cross_attention states don't have to be reordered -> they are always the same
|
| 1768 |
+
reordered_past += (
|
| 1769 |
+
tuple(past_state.index_select(0, beam_idx) for past_state in layer_past[:2]) + layer_past[2:],
|
| 1770 |
+
)
|
| 1771 |
+
return reordered_past
|
| 1772 |
+
|
| 1773 |
+
|
| 1774 |
+
class LSGBartForSequenceClassification(LSGBartPretrainedModel):
|
| 1775 |
+
|
| 1776 |
+
def __init__(self, config, **kwargs):
|
| 1777 |
+
|
| 1778 |
+
super().__init__(config, **kwargs)
|
| 1779 |
+
self.model = LSGBartModel(config)
|
| 1780 |
+
self.classification_head = LSGBartClassificationHead(
|
| 1781 |
+
config.d_model,
|
| 1782 |
+
config.d_model,
|
| 1783 |
+
config.num_labels,
|
| 1784 |
+
config.classifier_dropout,
|
| 1785 |
+
)
|
| 1786 |
+
self.model._init_weights(self.classification_head.dense)
|
| 1787 |
+
self.model._init_weights(self.classification_head.out_proj)
|
| 1788 |
+
|
| 1789 |
+
def forward(
|
| 1790 |
+
self,
|
| 1791 |
+
input_ids=None,
|
| 1792 |
+
attention_mask=None,
|
| 1793 |
+
decoder_input_ids=None,
|
| 1794 |
+
decoder_attention_mask=None,
|
| 1795 |
+
head_mask=None,
|
| 1796 |
+
decoder_head_mask=None,
|
| 1797 |
+
cross_attn_head_mask=None,
|
| 1798 |
+
encoder_outputs=None,
|
| 1799 |
+
inputs_embeds=None,
|
| 1800 |
+
decoder_inputs_embeds=None,
|
| 1801 |
+
labels=None,
|
| 1802 |
+
use_cache=None,
|
| 1803 |
+
output_attentions=None,
|
| 1804 |
+
output_hidden_states=None,
|
| 1805 |
+
return_dict=None,
|
| 1806 |
+
):
|
| 1807 |
+
|
| 1808 |
+
r"""
|
| 1809 |
+
labels (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`, `optional`):
|
| 1810 |
+
Labels for computing the sequence classification/regression loss. Indices should be in :obj:`[0, ...,
|
| 1811 |
+
config.num_labels - 1]`. If :obj:`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
| 1812 |
+
"""
|
| 1813 |
+
|
| 1814 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1815 |
+
if labels is not None:
|
| 1816 |
+
use_cache = False
|
| 1817 |
+
|
| 1818 |
+
if input_ids is None and inputs_embeds is not None:
|
| 1819 |
+
raise NotImplementedError(
|
| 1820 |
+
f"Passing input embeddings is currently not supported for {self.__class__.__name__}"
|
| 1821 |
+
)
|
| 1822 |
+
|
| 1823 |
+
outputs = self.model(
|
| 1824 |
+
input_ids,
|
| 1825 |
+
attention_mask=attention_mask,
|
| 1826 |
+
decoder_input_ids=decoder_input_ids,
|
| 1827 |
+
decoder_attention_mask=decoder_attention_mask,
|
| 1828 |
+
head_mask=head_mask,
|
| 1829 |
+
decoder_head_mask=decoder_head_mask,
|
| 1830 |
+
cross_attn_head_mask=cross_attn_head_mask,
|
| 1831 |
+
encoder_outputs=encoder_outputs,
|
| 1832 |
+
inputs_embeds=inputs_embeds,
|
| 1833 |
+
decoder_inputs_embeds=decoder_inputs_embeds,
|
| 1834 |
+
use_cache=use_cache,
|
| 1835 |
+
output_attentions=output_attentions,
|
| 1836 |
+
output_hidden_states=output_hidden_states,
|
| 1837 |
+
return_dict=return_dict,
|
| 1838 |
+
)
|
| 1839 |
+
hidden_states = outputs[0] # last hidden state
|
| 1840 |
+
|
| 1841 |
+
eos_mask = input_ids.eq(self.config.eos_token_id)
|
| 1842 |
+
|
| 1843 |
+
t, t_ = eos_mask.size()[-1], hidden_states.size()[-2]
|
| 1844 |
+
if t > t_:
|
| 1845 |
+
eos_mask = eos_mask[:, :t_]
|
| 1846 |
+
|
| 1847 |
+
if len(torch.unique_consecutive(eos_mask.sum(1))) > 1:
|
| 1848 |
+
raise ValueError("All examples must have the same number of <eos> tokens.")
|
| 1849 |
+
sentence_representation = hidden_states[eos_mask, :].view(hidden_states.size(0), -1, hidden_states.size(-1))[
|
| 1850 |
+
:, -1, :
|
| 1851 |
+
]
|
| 1852 |
+
logits = self.classification_head(sentence_representation)
|
| 1853 |
+
|
| 1854 |
+
loss = None
|
| 1855 |
+
if labels is not None:
|
| 1856 |
+
if self.config.problem_type is None:
|
| 1857 |
+
if self.config.num_labels == 1:
|
| 1858 |
+
self.config.problem_type = "regression"
|
| 1859 |
+
elif self.config.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
|
| 1860 |
+
self.config.problem_type = "single_label_classification"
|
| 1861 |
+
else:
|
| 1862 |
+
self.config.problem_type = "multi_label_classification"
|
| 1863 |
+
|
| 1864 |
+
if self.config.problem_type == "regression":
|
| 1865 |
+
loss_fct = MSELoss()
|
| 1866 |
+
if self.config.num_labels == 1:
|
| 1867 |
+
loss = loss_fct(logits.squeeze(), labels.squeeze())
|
| 1868 |
+
else:
|
| 1869 |
+
loss = loss_fct(logits, labels)
|
| 1870 |
+
elif self.config.problem_type == "single_label_classification":
|
| 1871 |
+
loss_fct = CrossEntropyLoss()
|
| 1872 |
+
loss = loss_fct(logits.view(-1, self.config.num_labels), labels.view(-1))
|
| 1873 |
+
elif self.config.problem_type == "multi_label_classification":
|
| 1874 |
+
loss_fct = BCEWithLogitsLoss()
|
| 1875 |
+
loss = loss_fct(logits, labels)
|
| 1876 |
+
if not return_dict:
|
| 1877 |
+
output = (logits,) + outputs[1:]
|
| 1878 |
+
return ((loss,) + output) if loss is not None else output
|
| 1879 |
+
|
| 1880 |
+
return Seq2SeqSequenceClassifierOutput(
|
| 1881 |
+
loss=loss,
|
| 1882 |
+
logits=logits,
|
| 1883 |
+
past_key_values=outputs.past_key_values,
|
| 1884 |
+
decoder_hidden_states=outputs.decoder_hidden_states,
|
| 1885 |
+
decoder_attentions=outputs.decoder_attentions,
|
| 1886 |
+
cross_attentions=outputs.cross_attentions,
|
| 1887 |
+
encoder_last_hidden_state=outputs.encoder_last_hidden_state,
|
| 1888 |
+
encoder_hidden_states=outputs.encoder_hidden_states,
|
| 1889 |
+
encoder_attentions=outputs.encoder_attentions,
|
| 1890 |
+
)
|
| 1891 |
+
|
| 1892 |
+
|
| 1893 |
+
class LSGBartForQuestionAnswering(LSGBartPretrainedModel):
|
| 1894 |
+
|
| 1895 |
+
def __init__(self, config):
|
| 1896 |
+
|
| 1897 |
+
super().__init__(config)
|
| 1898 |
+
|
| 1899 |
+
config.num_labels = 2
|
| 1900 |
+
self.num_labels = config.num_labels
|
| 1901 |
+
|
| 1902 |
+
self.model = LSGBartModel(config)
|
| 1903 |
+
self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
|
| 1904 |
+
|
| 1905 |
+
self.model._init_weights(self.qa_outputs)
|
| 1906 |
+
|
| 1907 |
+
def forward(
|
| 1908 |
+
self,
|
| 1909 |
+
input_ids=None,
|
| 1910 |
+
attention_mask=None,
|
| 1911 |
+
decoder_input_ids=None,
|
| 1912 |
+
decoder_attention_mask=None,
|
| 1913 |
+
head_mask=None,
|
| 1914 |
+
decoder_head_mask=None,
|
| 1915 |
+
cross_attn_head_mask=None,
|
| 1916 |
+
encoder_outputs=None,
|
| 1917 |
+
start_positions=None,
|
| 1918 |
+
end_positions=None,
|
| 1919 |
+
inputs_embeds=None,
|
| 1920 |
+
decoder_inputs_embeds=None,
|
| 1921 |
+
use_cache=None,
|
| 1922 |
+
output_attentions=None,
|
| 1923 |
+
output_hidden_states=None,
|
| 1924 |
+
return_dict=None,
|
| 1925 |
+
):
|
| 1926 |
+
|
| 1927 |
+
r"""
|
| 1928 |
+
start_positions (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`, `optional`):
|
| 1929 |
+
Labels for position (index) of the start of the labelled span for computing the token classification loss.
|
| 1930 |
+
Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
|
| 1931 |
+
are not taken into account for computing the loss.
|
| 1932 |
+
end_positions (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`, `optional`):
|
| 1933 |
+
Labels for position (index) of the end of the labelled span for computing the token classification loss.
|
| 1934 |
+
Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
|
| 1935 |
+
are not taken into account for computing the loss.
|
| 1936 |
+
"""
|
| 1937 |
+
|
| 1938 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 1939 |
+
if start_positions is not None and end_positions is not None:
|
| 1940 |
+
use_cache = False
|
| 1941 |
+
|
| 1942 |
+
outputs = self.model(
|
| 1943 |
+
input_ids,
|
| 1944 |
+
attention_mask=attention_mask,
|
| 1945 |
+
decoder_input_ids=decoder_input_ids,
|
| 1946 |
+
decoder_attention_mask=decoder_attention_mask,
|
| 1947 |
+
head_mask=head_mask,
|
| 1948 |
+
decoder_head_mask=decoder_head_mask,
|
| 1949 |
+
cross_attn_head_mask=cross_attn_head_mask,
|
| 1950 |
+
encoder_outputs=encoder_outputs,
|
| 1951 |
+
inputs_embeds=inputs_embeds,
|
| 1952 |
+
decoder_inputs_embeds=decoder_inputs_embeds,
|
| 1953 |
+
use_cache=use_cache,
|
| 1954 |
+
output_attentions=output_attentions,
|
| 1955 |
+
output_hidden_states=output_hidden_states,
|
| 1956 |
+
return_dict=return_dict,
|
| 1957 |
+
)
|
| 1958 |
+
|
| 1959 |
+
sequence_output = outputs[0]
|
| 1960 |
+
|
| 1961 |
+
logits = self.qa_outputs(sequence_output)
|
| 1962 |
+
start_logits, end_logits = logits.split(1, dim=-1)
|
| 1963 |
+
start_logits = start_logits.squeeze(-1).contiguous()
|
| 1964 |
+
end_logits = end_logits.squeeze(-1).contiguous()
|
| 1965 |
+
|
| 1966 |
+
total_loss = None
|
| 1967 |
+
if start_positions is not None and end_positions is not None:
|
| 1968 |
+
# If we are on multi-GPU, split add a dimension
|
| 1969 |
+
if len(start_positions.size()) > 1:
|
| 1970 |
+
start_positions = start_positions.squeeze(-1)
|
| 1971 |
+
if len(end_positions.size()) > 1:
|
| 1972 |
+
end_positions = end_positions.squeeze(-1)
|
| 1973 |
+
# sometimes the start/end positions are outside our model inputs, we ignore these terms
|
| 1974 |
+
ignored_index = start_logits.size(1)
|
| 1975 |
+
start_positions = start_positions.clamp(0, ignored_index)
|
| 1976 |
+
end_positions = end_positions.clamp(0, ignored_index)
|
| 1977 |
+
|
| 1978 |
+
loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
|
| 1979 |
+
start_loss = loss_fct(start_logits, start_positions)
|
| 1980 |
+
end_loss = loss_fct(end_logits, end_positions)
|
| 1981 |
+
total_loss = (start_loss + end_loss) / 2
|
| 1982 |
+
|
| 1983 |
+
if not return_dict:
|
| 1984 |
+
output = (
|
| 1985 |
+
start_logits,
|
| 1986 |
+
end_logits,
|
| 1987 |
+
) + outputs[1:]
|
| 1988 |
+
return ((total_loss,) + output) if total_loss is not None else output
|
| 1989 |
+
|
| 1990 |
+
return Seq2SeqQuestionAnsweringModelOutput(
|
| 1991 |
+
loss=total_loss,
|
| 1992 |
+
start_logits=start_logits,
|
| 1993 |
+
end_logits=end_logits,
|
| 1994 |
+
past_key_values=outputs.past_key_values,
|
| 1995 |
+
decoder_hidden_states=outputs.decoder_hidden_states,
|
| 1996 |
+
decoder_attentions=outputs.decoder_attentions,
|
| 1997 |
+
cross_attentions=outputs.cross_attentions,
|
| 1998 |
+
encoder_last_hidden_state=outputs.encoder_last_hidden_state,
|
| 1999 |
+
encoder_hidden_states=outputs.encoder_hidden_states,
|
| 2000 |
+
encoder_attentions=outputs.encoder_attentions,
|
| 2001 |
+
)
|
| 2002 |
+
|
| 2003 |
+
|
| 2004 |
+
class LSGBartDecoderWrapper(LSGBartPretrainedModel):
|
| 2005 |
+
"""
|
| 2006 |
+
This wrapper class is a helper class to correctly load pretrained checkpoints when the causal language model is
|
| 2007 |
+
used in combination with the :class:`~transformers.EncoderDecoderModel` framework.
|
| 2008 |
+
"""
|
| 2009 |
+
|
| 2010 |
+
def __init__(self, config):
|
| 2011 |
+
super().__init__(config)
|
| 2012 |
+
self.decoder = BartDecoder(config)
|
| 2013 |
+
|
| 2014 |
+
def forward(self, *args, **kwargs):
|
| 2015 |
+
return self.decoder(*args, **kwargs)
|
| 2016 |
+
|
| 2017 |
+
|
| 2018 |
+
class LSGBartForCausalLM(LSGBartPretrainedModel):
|
| 2019 |
+
|
| 2020 |
+
def __init__(self, config):
|
| 2021 |
+
|
| 2022 |
+
super().__init__(config)
|
| 2023 |
+
config = copy.deepcopy(config)
|
| 2024 |
+
config.is_decoder = True
|
| 2025 |
+
config.is_encoder_decoder = False
|
| 2026 |
+
self.model = LSGBartDecoderWrapper(config)
|
| 2027 |
+
|
| 2028 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
| 2029 |
+
|
| 2030 |
+
# Initialize weights and apply final processing
|
| 2031 |
+
self.post_init()
|
| 2032 |
+
|
| 2033 |
+
def get_input_embeddings(self):
|
| 2034 |
+
return self.model.decoder.embed_tokens
|
| 2035 |
+
|
| 2036 |
+
def set_input_embeddings(self, value):
|
| 2037 |
+
self.model.decoder.embed_tokens = value
|
| 2038 |
+
|
| 2039 |
+
def get_output_embeddings(self):
|
| 2040 |
+
return self.lm_head
|
| 2041 |
+
|
| 2042 |
+
def set_output_embeddings(self, new_embeddings):
|
| 2043 |
+
self.lm_head = new_embeddings
|
| 2044 |
+
|
| 2045 |
+
def set_decoder(self, decoder):
|
| 2046 |
+
self.model.decoder = decoder
|
| 2047 |
+
|
| 2048 |
+
def get_decoder(self):
|
| 2049 |
+
return self.model.decoder
|
| 2050 |
+
|
| 2051 |
+
def forward(
|
| 2052 |
+
self,
|
| 2053 |
+
input_ids=None,
|
| 2054 |
+
attention_mask=None,
|
| 2055 |
+
encoder_hidden_states=None,
|
| 2056 |
+
encoder_attention_mask=None,
|
| 2057 |
+
head_mask=None,
|
| 2058 |
+
cross_attn_head_mask=None,
|
| 2059 |
+
past_key_values=None,
|
| 2060 |
+
inputs_embeds=None,
|
| 2061 |
+
labels=None,
|
| 2062 |
+
use_cache=None,
|
| 2063 |
+
output_attentions=None,
|
| 2064 |
+
output_hidden_states=None,
|
| 2065 |
+
return_dict=None,
|
| 2066 |
+
):
|
| 2067 |
+
|
| 2068 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 2069 |
+
output_hidden_states = (
|
| 2070 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 2071 |
+
)
|
| 2072 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 2073 |
+
|
| 2074 |
+
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
| 2075 |
+
outputs = self.model.decoder(
|
| 2076 |
+
input_ids=input_ids,
|
| 2077 |
+
attention_mask=attention_mask,
|
| 2078 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 2079 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 2080 |
+
head_mask=head_mask,
|
| 2081 |
+
cross_attn_head_mask=cross_attn_head_mask,
|
| 2082 |
+
past_key_values=past_key_values,
|
| 2083 |
+
inputs_embeds=inputs_embeds,
|
| 2084 |
+
use_cache=use_cache,
|
| 2085 |
+
output_attentions=output_attentions,
|
| 2086 |
+
output_hidden_states=output_hidden_states,
|
| 2087 |
+
return_dict=return_dict,
|
| 2088 |
+
)
|
| 2089 |
+
|
| 2090 |
+
logits = self.lm_head(outputs[0])
|
| 2091 |
+
|
| 2092 |
+
loss = None
|
| 2093 |
+
if labels is not None:
|
| 2094 |
+
loss_fct = CrossEntropyLoss()
|
| 2095 |
+
loss = loss_fct(logits.view(-1, self.config.vocab_size), labels.view(-1))
|
| 2096 |
+
|
| 2097 |
+
if not return_dict:
|
| 2098 |
+
output = (logits,) + outputs[1:]
|
| 2099 |
+
return (loss,) + output if loss is not None else output
|
| 2100 |
+
|
| 2101 |
+
return CausalLMOutputWithCrossAttentions(
|
| 2102 |
+
loss=loss,
|
| 2103 |
+
logits=logits,
|
| 2104 |
+
past_key_values=outputs.past_key_values,
|
| 2105 |
+
hidden_states=outputs.hidden_states,
|
| 2106 |
+
attentions=outputs.attentions,
|
| 2107 |
+
cross_attentions=outputs.cross_attentions,
|
| 2108 |
+
)
|
| 2109 |
+
|
| 2110 |
+
def prepare_inputs_for_generation(self, input_ids, past=None, attention_mask=None, use_cache=None, **kwargs):
|
| 2111 |
+
# if model is used as a decoder in encoder-decoder model, the decoder attention mask is created on the fly
|
| 2112 |
+
if attention_mask is None:
|
| 2113 |
+
attention_mask = input_ids.new_ones(input_ids.shape)
|
| 2114 |
+
|
| 2115 |
+
if past:
|
| 2116 |
+
input_ids = input_ids[:, -1:]
|
| 2117 |
+
# first step, decoder_cached_states are empty
|
| 2118 |
+
return {
|
| 2119 |
+
"input_ids": input_ids, # encoder_outputs is defined. input_ids not needed
|
| 2120 |
+
"attention_mask": attention_mask,
|
| 2121 |
+
"past_key_values": past,
|
| 2122 |
+
"use_cache": use_cache,
|
| 2123 |
+
}
|
| 2124 |
+
|
| 2125 |
+
@staticmethod
|
| 2126 |
+
def _reorder_cache(past, beam_idx):
|
| 2127 |
+
reordered_past = ()
|
| 2128 |
+
for layer_past in past:
|
| 2129 |
+
reordered_past += (tuple(past_state.index_select(0, beam_idx) for past_state in layer_past),)
|
| 2130 |
+
return reordered_past
|
| 2131 |
+
|
| 2132 |
+
|
| 2133 |
+
def str_to_class(classname):
|
| 2134 |
+
return getattr(sys.modules[__name__], classname)
|
| 2135 |
+
|
| 2136 |
+
# Register model in Auto API
|
| 2137 |
+
try:
|
| 2138 |
+
LSGBartConfig.register_for_auto_class()
|
| 2139 |
+
for key, value in AUTO_MAP.items():
|
| 2140 |
+
str_to_class(value.split(".")[-1]).register_for_auto_class(key)
|
| 2141 |
+
except:
|
| 2142 |
+
warn("AutoRegister isn't available, you'll have to manually copy modeling.py after .save_pretrained(...).")
|
| 2143 |
+
warn("Update to transformers >= 4.17.0 to fix.")
|
pytorch_model.bin
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:0baa2aecffe0dc5c00cb4f23b89134663008055a409645e422850c2e5d78240f
|
| 3 |
+
size 578416695
|
special_tokens_map.json
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
{"bos_token": "<s>", "eos_token": "</s>", "unk_token": "<unk>", "sep_token": "</s>", "pad_token": "<pad>", "cls_token": "<s>", "mask_token": {"content": "<mask>", "single_word": false, "lstrip": true, "rstrip": false, "normalized": false}}
|
tokenizer.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
tokenizer_config.json
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
{"errors": "replace", "bos_token": "<s>", "eos_token": "</s>", "sep_token": "</s>", "cls_token": "<s>", "unk_token": "<unk>", "pad_token": "<pad>", "mask_token": "<mask>", "add_prefix_space": false, "trim_offsets": true, "model_max_length": 4096, "special_tokens_map_file": null, "name_or_path": "/data/ccondevaux/lsg/text-summarization/tmp/pubmed/lsg_local_large_lr", "tokenizer_class": "BartTokenizer"}
|
vocab.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|