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