Commit
·
98c7bce
0
Parent(s):
readme
Browse files- .gitattributes +27 -0
- README.md +155 -0
- attn.png +0 -0
- config.json +93 -0
- merges.txt +0 -0
- modeling_lsg_bart.py +1117 -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
.gitattributes
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
*.7z filter=lfs diff=lfs merge=lfs -text
|
| 2 |
+
*.arrow filter=lfs diff=lfs merge=lfs -text
|
| 3 |
+
*.bin filter=lfs diff=lfs merge=lfs -text
|
| 4 |
+
*.bin.* filter=lfs diff=lfs merge=lfs -text
|
| 5 |
+
*.bz2 filter=lfs diff=lfs merge=lfs -text
|
| 6 |
+
*.ftz filter=lfs diff=lfs merge=lfs -text
|
| 7 |
+
*.gz filter=lfs diff=lfs merge=lfs -text
|
| 8 |
+
*.h5 filter=lfs diff=lfs merge=lfs -text
|
| 9 |
+
*.joblib filter=lfs diff=lfs merge=lfs -text
|
| 10 |
+
*.lfs.* filter=lfs diff=lfs merge=lfs -text
|
| 11 |
+
*.model filter=lfs diff=lfs merge=lfs -text
|
| 12 |
+
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
| 13 |
+
*.onnx filter=lfs diff=lfs merge=lfs -text
|
| 14 |
+
*.ot filter=lfs diff=lfs merge=lfs -text
|
| 15 |
+
*.parquet filter=lfs diff=lfs merge=lfs -text
|
| 16 |
+
*.pb filter=lfs diff=lfs merge=lfs -text
|
| 17 |
+
*.pt filter=lfs diff=lfs merge=lfs -text
|
| 18 |
+
*.pth filter=lfs diff=lfs merge=lfs -text
|
| 19 |
+
*.rar filter=lfs diff=lfs merge=lfs -text
|
| 20 |
+
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
| 21 |
+
*.tar.* filter=lfs diff=lfs merge=lfs -text
|
| 22 |
+
*.tflite filter=lfs diff=lfs merge=lfs -text
|
| 23 |
+
*.tgz filter=lfs diff=lfs merge=lfs -text
|
| 24 |
+
*.xz filter=lfs diff=lfs merge=lfs -text
|
| 25 |
+
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 26 |
+
*.zstandard filter=lfs diff=lfs merge=lfs -text
|
| 27 |
+
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
README.md
ADDED
|
@@ -0,0 +1,155 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
tags:
|
| 3 |
+
- summarization
|
| 4 |
+
- bart
|
| 5 |
+
- long context
|
| 6 |
+
language:
|
| 7 |
+
- en
|
| 8 |
+
pipeline_tag: fill-mask
|
| 9 |
+
---
|
| 10 |
+
|
| 11 |
+
# LSG model
|
| 12 |
+
**Transformers >= 4.18.0**\
|
| 13 |
+
**This model relies on a custom modeling file, you need to add trust_remote_code=True**\
|
| 14 |
+
**See [\#13467](https://github.com/huggingface/transformers/pull/13467)**
|
| 15 |
+
|
| 16 |
+
* [Usage](#usage)
|
| 17 |
+
* [Parameters](#parameters)
|
| 18 |
+
* [Sparse selection type](#sparse-selection-type)
|
| 19 |
+
* [Tasks](#tasks)
|
| 20 |
+
|
| 21 |
+
This model is adapted from [BART-base](https://huggingface.co/facebook/bart-base) for encoder-decoder tasks without additional pretraining. It uses the same number of parameters/layers and the same tokenizer.
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
This model can handle long sequences but faster and more efficiently than Longformer (LED) or BigBird (Pegasus) from the hub and relies on Local + Sparse + Global attention (LSG).
|
| 25 |
+
|
| 26 |
+
The model requires sequences whose length is a multiple of the block size. The model is "adaptive" and automatically pads the sequences if needed (adaptive=True in config). It is however recommended, thanks to the tokenizer, to truncate the inputs (truncation=True) and optionally to pad with a multiple of the block size (pad_to_multiple_of=...). \
|
| 27 |
+
|
| 28 |
+
Implemented in PyTorch.
|
| 29 |
+
|
| 30 |
+

|
| 31 |
+
|
| 32 |
+
## Usage
|
| 33 |
+
The model relies on a custom modeling file, you need to add trust_remote_code=True to use it.
|
| 34 |
+
|
| 35 |
+
```python:
|
| 36 |
+
from transformers import AutoModel, AutoTokenizer
|
| 37 |
+
|
| 38 |
+
model = AutoModel.from_pretrained("ccdv/lsg-bart-base-4096", trust_remote_code=True)
|
| 39 |
+
tokenizer = AutoTokenizer.from_pretrained("ccdv/lsg-bart-base-4096")
|
| 40 |
+
```
|
| 41 |
+
|
| 42 |
+
## Parameters
|
| 43 |
+
You can change various parameters like :
|
| 44 |
+
* the number of global tokens (num_global_tokens=1)
|
| 45 |
+
* local block size (block_size=128)
|
| 46 |
+
* sparse block size (sparse_block_size=128)
|
| 47 |
+
* sparsity factor (sparsity_factor=2)
|
| 48 |
+
* see config.json file
|
| 49 |
+
|
| 50 |
+
Default parameters work well in practice. If you are short on memory, reduce block sizes, increase sparsity factor and remove dropout in the attention score matrix.
|
| 51 |
+
|
| 52 |
+
```python:
|
| 53 |
+
model = AutoModel.from_pretrained("ccdv/lsg-bart-base-4096",
|
| 54 |
+
trust_remote_code=True,
|
| 55 |
+
num_global_tokens=16,
|
| 56 |
+
block_size=64,
|
| 57 |
+
sparse_block_size=64,
|
| 58 |
+
sparsity_factor=4,
|
| 59 |
+
attention_probs_dropout_prob=0.0
|
| 60 |
+
)
|
| 61 |
+
```
|
| 62 |
+
|
| 63 |
+
## Sparse selection type
|
| 64 |
+
|
| 65 |
+
There are 5 different sparse selection patterns. The best type is task dependent. \
|
| 66 |
+
Note that for sequences with length < 2*block_size, the type has no effect.
|
| 67 |
+
|
| 68 |
+
* sparsity_type="norm", select highest norm tokens
|
| 69 |
+
* Works best for a small sparsity_factor (2 to 4)
|
| 70 |
+
* Additional parameters:
|
| 71 |
+
* None
|
| 72 |
+
* sparsity_type="pooling", use average pooling to merge tokens
|
| 73 |
+
* Works best for a small sparsity_factor (2 to 4)
|
| 74 |
+
* Additional parameters:
|
| 75 |
+
* None
|
| 76 |
+
* sparsity_type="lsh", use the LSH algorithm to cluster similar tokens
|
| 77 |
+
* Works best for a large sparsity_factor (4+)
|
| 78 |
+
* LSH relies on random projections, thus inference may differ slightly with different seeds
|
| 79 |
+
* Additional parameters:
|
| 80 |
+
* lsg_num_pre_rounds=1, pre merge tokens n times before computing centroids
|
| 81 |
+
* sparsity_type="stride", use a striding mecanism per head
|
| 82 |
+
* Each head will use different tokens strided by sparsify_factor
|
| 83 |
+
* Not recommended if sparsify_factor > num_heads
|
| 84 |
+
* sparsity_type="block_stride", use a striding mecanism per head
|
| 85 |
+
* Each head will use block of tokens strided by sparsify_factor
|
| 86 |
+
* Not recommended if sparsify_factor > num_heads
|
| 87 |
+
|
| 88 |
+
## Tasks
|
| 89 |
+
Seq2Seq example for summarization:
|
| 90 |
+
```python:
|
| 91 |
+
from transformers import AutoModelForSeq2SeqLM, AutoTokenizer
|
| 92 |
+
|
| 93 |
+
model = AutoModelForSeq2SeqLM.from_pretrained("ccdv/lsg-bart-base-4096",
|
| 94 |
+
trust_remote_code=True,
|
| 95 |
+
pass_global_tokens_to_decoder=True, # Pass encoder global tokens to decoder
|
| 96 |
+
)
|
| 97 |
+
tokenizer = AutoTokenizer.from_pretrained("ccdv/lsg-bart-base-4096")
|
| 98 |
+
|
| 99 |
+
SENTENCE = "This is a test sequence to test the model. " * 300
|
| 100 |
+
token_ids = tokenizer(
|
| 101 |
+
SENTENCE,
|
| 102 |
+
return_tensors="pt",
|
| 103 |
+
padding="max_length", # Optional but recommended
|
| 104 |
+
truncation=True # Optional but recommended
|
| 105 |
+
)
|
| 106 |
+
output = model(**token_ids)
|
| 107 |
+
```
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
Classification example:
|
| 111 |
+
```python:
|
| 112 |
+
from transformers import AutoModelForSequenceClassification, AutoTokenizer
|
| 113 |
+
|
| 114 |
+
model = AutoModelForSequenceClassification.from_pretrained("ccdv/lsg-bart-base-4096",
|
| 115 |
+
trust_remote_code=True,
|
| 116 |
+
pass_global_tokens_to_decoder=True, # Pass encoder global tokens to decoder
|
| 117 |
+
)
|
| 118 |
+
tokenizer = AutoTokenizer.from_pretrained("ccdv/lsg-bart-base-4096")
|
| 119 |
+
|
| 120 |
+
SENTENCE = "This is a test sequence to test the model. " * 300
|
| 121 |
+
token_ids = tokenizer(
|
| 122 |
+
SENTENCE,
|
| 123 |
+
return_tensors="pt",
|
| 124 |
+
#pad_to_multiple_of=... # Optional
|
| 125 |
+
truncation=True
|
| 126 |
+
)
|
| 127 |
+
output = model(**token_ids)
|
| 128 |
+
|
| 129 |
+
> SequenceClassifierOutput(loss=None, logits=tensor([[-0.3051, -0.1762]], grad_fn=<AddmmBackward>), hidden_states=None, attentions=None)
|
| 130 |
+
```
|
| 131 |
+
|
| 132 |
+
**BART**
|
| 133 |
+
```
|
| 134 |
+
@article{DBLP:journals/corr/abs-1910-13461,
|
| 135 |
+
author = {Mike Lewis and
|
| 136 |
+
Yinhan Liu and
|
| 137 |
+
Naman Goyal and
|
| 138 |
+
Marjan Ghazvininejad and
|
| 139 |
+
Abdelrahman Mohamed and
|
| 140 |
+
Omer Levy and
|
| 141 |
+
Veselin Stoyanov and
|
| 142 |
+
Luke Zettlemoyer},
|
| 143 |
+
title = {{BART:} Denoising Sequence-to-Sequence Pre-training for Natural Language
|
| 144 |
+
Generation, Translation, and Comprehension},
|
| 145 |
+
journal = {CoRR},
|
| 146 |
+
volume = {abs/1910.13461},
|
| 147 |
+
year = {2019},
|
| 148 |
+
url = {http://arxiv.org/abs/1910.13461},
|
| 149 |
+
eprinttype = {arXiv},
|
| 150 |
+
eprint = {1910.13461},
|
| 151 |
+
timestamp = {Thu, 31 Oct 2019 14:02:26 +0100},
|
| 152 |
+
biburl = {https://dblp.org/rec/journals/corr/abs-1910-13461.bib},
|
| 153 |
+
bibsource = {dblp computer science bibliography, https://dblp.org}
|
| 154 |
+
}
|
| 155 |
+
```
|
attn.png
ADDED
|
config.json
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"_name_or_path": "ccdv/lsg-bart-base-4096",
|
| 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": 128,
|
| 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 |
+
"lsh_num_pre_rounds": 1,
|
| 54 |
+
"max_position_embeddings": 4096,
|
| 55 |
+
"model_type": "bart",
|
| 56 |
+
"no_repeat_ngram_size": 3,
|
| 57 |
+
"normalize_before": false,
|
| 58 |
+
"normalize_embedding": true,
|
| 59 |
+
"num_beams": 4,
|
| 60 |
+
"num_global_tokens": 1,
|
| 61 |
+
"num_hidden_layers": 6,
|
| 62 |
+
"pad_token_id": 1,
|
| 63 |
+
"pass_global_tokens_to_decoder": true,
|
| 64 |
+
"pool_with_global": true,
|
| 65 |
+
"scale_embedding": false,
|
| 66 |
+
"sparse_block_size": 128,
|
| 67 |
+
"sparsity_factor": 2,
|
| 68 |
+
"sparsity_type": "norm",
|
| 69 |
+
"task_specific_params": {
|
| 70 |
+
"summarization": {
|
| 71 |
+
"length_penalty": 1.0,
|
| 72 |
+
"max_length": 128,
|
| 73 |
+
"min_length": 12,
|
| 74 |
+
"num_beams": 4
|
| 75 |
+
},
|
| 76 |
+
"summarization_cnn": {
|
| 77 |
+
"length_penalty": 2.0,
|
| 78 |
+
"max_length": 142,
|
| 79 |
+
"min_length": 56,
|
| 80 |
+
"num_beams": 4
|
| 81 |
+
},
|
| 82 |
+
"summarization_xsum": {
|
| 83 |
+
"length_penalty": 1.0,
|
| 84 |
+
"max_length": 62,
|
| 85 |
+
"min_length": 11,
|
| 86 |
+
"num_beams": 6
|
| 87 |
+
}
|
| 88 |
+
},
|
| 89 |
+
"torch_dtype": "float32",
|
| 90 |
+
"transformers_version": "4.19.2",
|
| 91 |
+
"use_cache": true,
|
| 92 |
+
"vocab_size": 50265
|
| 93 |
+
}
|
merges.txt
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
modeling_lsg_bart.py
ADDED
|
@@ -0,0 +1,1117 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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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 |
+
self.adaptive = adaptive
|
| 46 |
+
self.auto_map = AUTO_MAP
|
| 47 |
+
self.base_model_prefix = base_model_prefix
|
| 48 |
+
self.block_size = block_size
|
| 49 |
+
self.lsh_num_pre_rounds = lsh_num_pre_rounds
|
| 50 |
+
self.num_global_tokens = num_global_tokens
|
| 51 |
+
self.pass_global_tokens_to_decoder = pass_global_tokens_to_decoder
|
| 52 |
+
self.pool_with_global = pool_with_global
|
| 53 |
+
self.sparse_block_size = sparse_block_size
|
| 54 |
+
self.sparsity_factor = sparsity_factor
|
| 55 |
+
self.sparsity_type = sparsity_type
|
| 56 |
+
|
| 57 |
+
if sparsity_type not in [None, "none", "norm", "lsh", "pooling", "stride", "block_stride"]:
|
| 58 |
+
logger.warning(
|
| 59 |
+
"[WARNING CONFIG]: sparsity_mode not in [None, 'none', 'norm', 'lsh', 'pooling', 'stride', 'block_stride'], setting sparsity_type=None, computation will skip sparse attention")
|
| 60 |
+
self.sparsity_type = None
|
| 61 |
+
|
| 62 |
+
if self.sparsity_type in ["stride", "block_stride"]:
|
| 63 |
+
if self.sparsity_factor > self.encoder_attention_heads:
|
| 64 |
+
logger.warning(
|
| 65 |
+
"[WARNING CONFIG]: sparsity_factor > encoder_attention_heads is not recommended for stride/block_stride sparsity"
|
| 66 |
+
)
|
| 67 |
+
|
| 68 |
+
if self.num_global_tokens < 1:
|
| 69 |
+
logger.warning(
|
| 70 |
+
"[WARNING CONFIG]: num_global_tokens < 1 is not compatible, setting num_global_tokens=1"
|
| 71 |
+
)
|
| 72 |
+
self.num_global_tokens = 1
|
| 73 |
+
elif self.num_global_tokens > 512:
|
| 74 |
+
logger.warning(
|
| 75 |
+
"[WARNING CONFIG]: num_global_tokens > 512 is not compatible, setting num_global_tokens=512"
|
| 76 |
+
)
|
| 77 |
+
self.num_global_tokens = 512
|
| 78 |
+
|
| 79 |
+
if self.sparsity_factor > 0:
|
| 80 |
+
assert self.block_size % self.sparsity_factor == 0, "[ERROR CONFIG]: block_size must be divisible by sparsity_factor"
|
| 81 |
+
assert self.block_size//self.sparsity_factor >= 1, "[ERROR CONFIG]: make sure block_size >= sparsity_factor"
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
class BaseSelfAttention(nn.Module):
|
| 85 |
+
|
| 86 |
+
def __init__(
|
| 87 |
+
self,
|
| 88 |
+
embed_dim,
|
| 89 |
+
num_heads,
|
| 90 |
+
dropout=0.0,
|
| 91 |
+
is_decoder=False,
|
| 92 |
+
bias=True,
|
| 93 |
+
):
|
| 94 |
+
|
| 95 |
+
super().__init__()
|
| 96 |
+
self.embed_dim = embed_dim
|
| 97 |
+
self.num_heads = num_heads
|
| 98 |
+
self.dropout = dropout
|
| 99 |
+
self.head_dim = embed_dim // num_heads
|
| 100 |
+
|
| 101 |
+
if (self.head_dim * num_heads) != self.embed_dim:
|
| 102 |
+
raise ValueError(
|
| 103 |
+
f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}"
|
| 104 |
+
f" and `num_heads`: {num_heads})."
|
| 105 |
+
)
|
| 106 |
+
self.scaling = self.head_dim ** -0.5
|
| 107 |
+
self.is_decoder = is_decoder
|
| 108 |
+
|
| 109 |
+
self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
|
| 110 |
+
self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
|
| 111 |
+
self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
|
| 112 |
+
self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
|
| 113 |
+
|
| 114 |
+
def transpose_for_scores(self, x):
|
| 115 |
+
new_x_shape = x.size()[:-1] + (
|
| 116 |
+
self.num_heads,
|
| 117 |
+
self.head_dim,
|
| 118 |
+
)
|
| 119 |
+
x = x.view(*new_x_shape)
|
| 120 |
+
return x.permute(0, 2, 1, 3)
|
| 121 |
+
|
| 122 |
+
def reshape_output(self, context_layer):
|
| 123 |
+
context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
|
| 124 |
+
new_context_layer_shape = context_layer.size()[:-2] + (self.embed_dim,)
|
| 125 |
+
return context_layer.view(*new_context_layer_shape)
|
| 126 |
+
|
| 127 |
+
def project_QKV(self, hidden_states):
|
| 128 |
+
|
| 129 |
+
query_layer = self.transpose_for_scores(self.q_proj(hidden_states))
|
| 130 |
+
key_layer = self.transpose_for_scores(self.k_proj(hidden_states))
|
| 131 |
+
value_layer = self.transpose_for_scores(self.v_proj(hidden_states))
|
| 132 |
+
return query_layer, key_layer, value_layer
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
class BaseAttentionProduct(nn.Module):
|
| 136 |
+
|
| 137 |
+
def __init__(self, config):
|
| 138 |
+
"""
|
| 139 |
+
Compute attention: softmax(Q @ K.T) @ V
|
| 140 |
+
"""
|
| 141 |
+
super().__init__()
|
| 142 |
+
self.dropout = nn.Dropout(config.attention_dropout)
|
| 143 |
+
|
| 144 |
+
def forward(self, query_layer, key_layer, value_layer, attention_mask=None):
|
| 145 |
+
|
| 146 |
+
d = query_layer.shape[-1]
|
| 147 |
+
|
| 148 |
+
# Take the dot product between "query" and "key" to get the raw attention scores.
|
| 149 |
+
attention_scores = query_layer @ key_layer.transpose(-1, -2) / math.sqrt(d)
|
| 150 |
+
|
| 151 |
+
del query_layer
|
| 152 |
+
del key_layer
|
| 153 |
+
|
| 154 |
+
if attention_mask is not None:
|
| 155 |
+
# Apply the attention mask is (precomputed for all layers in RobertaModel forward() function)
|
| 156 |
+
attention_scores = attention_scores + attention_mask
|
| 157 |
+
del attention_mask
|
| 158 |
+
|
| 159 |
+
# Normalize the attention scores to probabilities.
|
| 160 |
+
attention_probs = nn.Softmax(dim=-1)(attention_scores)
|
| 161 |
+
|
| 162 |
+
# This is actually dropping out entire tokens to attend to, which might
|
| 163 |
+
# seem a bit unusual, but is taken from the original Transformer paper.
|
| 164 |
+
context_layer = self.dropout(attention_probs) @ value_layer
|
| 165 |
+
|
| 166 |
+
return context_layer
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
class LSGAttentionProduct(nn.Module):
|
| 170 |
+
|
| 171 |
+
def __init__(self, config, block_size=None, sparse_block_size=None, sparsity_factor=4):
|
| 172 |
+
"""
|
| 173 |
+
Compute block or overlapping blocks attention products
|
| 174 |
+
"""
|
| 175 |
+
super().__init__()
|
| 176 |
+
|
| 177 |
+
self.block_size = block_size
|
| 178 |
+
self.sparse_block_size = sparse_block_size
|
| 179 |
+
self.sparsity_factor = sparsity_factor
|
| 180 |
+
|
| 181 |
+
if self.block_size is None:
|
| 182 |
+
self.block_size = config.block_size
|
| 183 |
+
|
| 184 |
+
if self.sparse_block_size is None:
|
| 185 |
+
self.sparse_block_size = config.sparse_block_size
|
| 186 |
+
|
| 187 |
+
# Shape of blocks
|
| 188 |
+
self.local_shapes = (self.block_size*3, self.block_size)
|
| 189 |
+
if self.sparse_block_size and self.sparsity_factor > 0:
|
| 190 |
+
self.sparse_shapes = (self.sparse_block_size*3, self.block_size//self.sparsity_factor)
|
| 191 |
+
|
| 192 |
+
self.attention = BaseAttentionProduct(config)
|
| 193 |
+
|
| 194 |
+
def build_lsg_inputs(self, hidden_states, sparse_hidden_states, global_hidden_states, is_attn_mask=False):
|
| 195 |
+
|
| 196 |
+
# Build local tokens
|
| 197 |
+
local_hidden_states = self.reshape_to_local_block(hidden_states, is_attn_mask)
|
| 198 |
+
del hidden_states
|
| 199 |
+
|
| 200 |
+
# Build sparse tokens
|
| 201 |
+
if sparse_hidden_states is not None:
|
| 202 |
+
sparse_hidden_states = self.reshape_to_sparse_block(sparse_hidden_states, is_attn_mask)
|
| 203 |
+
|
| 204 |
+
return self.cat_global_sparse_local_tokens(global_hidden_states, sparse_hidden_states, local_hidden_states)
|
| 205 |
+
|
| 206 |
+
def forward(
|
| 207 |
+
self,
|
| 208 |
+
query_layer,
|
| 209 |
+
key_layer,
|
| 210 |
+
value_layer,
|
| 211 |
+
attention_mask=None,
|
| 212 |
+
sparse_key=None,
|
| 213 |
+
sparse_value=None,
|
| 214 |
+
sparse_mask=None,
|
| 215 |
+
global_key=None,
|
| 216 |
+
global_value=None,
|
| 217 |
+
global_mask=None
|
| 218 |
+
):
|
| 219 |
+
|
| 220 |
+
# Input batch, heads, length, hidden_size
|
| 221 |
+
n, h, t, d = query_layer.size()
|
| 222 |
+
n_blocks = t // self.block_size
|
| 223 |
+
assert t % self.block_size == 0
|
| 224 |
+
|
| 225 |
+
key_layer = self.build_lsg_inputs(
|
| 226 |
+
key_layer,
|
| 227 |
+
sparse_key,
|
| 228 |
+
global_key
|
| 229 |
+
)
|
| 230 |
+
del sparse_key
|
| 231 |
+
del global_key
|
| 232 |
+
|
| 233 |
+
value_layer = self.build_lsg_inputs(
|
| 234 |
+
value_layer,
|
| 235 |
+
sparse_value,
|
| 236 |
+
global_value
|
| 237 |
+
)
|
| 238 |
+
del sparse_value
|
| 239 |
+
del global_value
|
| 240 |
+
|
| 241 |
+
attention_mask = self.build_lsg_inputs(
|
| 242 |
+
attention_mask,
|
| 243 |
+
sparse_mask,
|
| 244 |
+
global_mask.transpose(-1, -2),
|
| 245 |
+
is_attn_mask=True
|
| 246 |
+
).transpose(-1, -2)
|
| 247 |
+
del sparse_mask
|
| 248 |
+
del global_mask
|
| 249 |
+
|
| 250 |
+
# expect (..., t, d) shape
|
| 251 |
+
# Compute attention
|
| 252 |
+
context_layer = self.attention(
|
| 253 |
+
query_layer=self.chunk(query_layer, n_blocks),
|
| 254 |
+
key_layer=key_layer,
|
| 255 |
+
value_layer=value_layer,
|
| 256 |
+
attention_mask=attention_mask
|
| 257 |
+
)
|
| 258 |
+
|
| 259 |
+
return context_layer.reshape(n, h, -1, d)
|
| 260 |
+
|
| 261 |
+
def reshape_to_local_block(self, hidden_states, is_attn_mask=False):
|
| 262 |
+
|
| 263 |
+
size, step = self.local_shapes
|
| 264 |
+
s = (size - step) // 2
|
| 265 |
+
|
| 266 |
+
# Pad before block reshaping
|
| 267 |
+
if is_attn_mask:
|
| 268 |
+
pad_value = -10000
|
| 269 |
+
hidden_states = hidden_states.transpose(-1, -2)
|
| 270 |
+
else:
|
| 271 |
+
pad_value = 0
|
| 272 |
+
|
| 273 |
+
hidden_states = torch.nn.functional.pad(
|
| 274 |
+
hidden_states.transpose(-1, -2),
|
| 275 |
+
pad=(s, s),
|
| 276 |
+
value=pad_value
|
| 277 |
+
).transpose(-1, -2)
|
| 278 |
+
|
| 279 |
+
# Make blocks
|
| 280 |
+
hidden_states = hidden_states.unfold(-2, size=size, step=step).transpose(-1, -2)
|
| 281 |
+
|
| 282 |
+
return hidden_states
|
| 283 |
+
|
| 284 |
+
def reshape_to_sparse_block(self, hidden_states, is_attn_mask=False):
|
| 285 |
+
|
| 286 |
+
size, step = self.sparse_shapes
|
| 287 |
+
|
| 288 |
+
# In case of odd case
|
| 289 |
+
odd_offset = (step % 2)
|
| 290 |
+
|
| 291 |
+
# n, h, t, d*2 + 1
|
| 292 |
+
size = size*2
|
| 293 |
+
s = (size - step) // 2 + odd_offset
|
| 294 |
+
|
| 295 |
+
# Pad before block reshaping
|
| 296 |
+
if is_attn_mask:
|
| 297 |
+
pad_value = -10000
|
| 298 |
+
hidden_states = hidden_states.transpose(-1, -2)
|
| 299 |
+
else:
|
| 300 |
+
pad_value = 0
|
| 301 |
+
|
| 302 |
+
hidden_states = torch.nn.functional.pad(
|
| 303 |
+
hidden_states.transpose(-1, -2),
|
| 304 |
+
pad=(s, s),
|
| 305 |
+
value=pad_value
|
| 306 |
+
).transpose(-1, -2)
|
| 307 |
+
|
| 308 |
+
# Make blocks
|
| 309 |
+
hidden_states = hidden_states.unfold(-2, size=size, step=step).transpose(-1, -2)
|
| 310 |
+
|
| 311 |
+
# Fix case where block_size == sparsify_factor
|
| 312 |
+
if odd_offset:
|
| 313 |
+
hidden_states = hidden_states[..., :-1, :, :]
|
| 314 |
+
|
| 315 |
+
# Indexes for selection
|
| 316 |
+
u = (size - self.block_size * 3 // self.sparsity_factor) // 2 + odd_offset
|
| 317 |
+
s = self.sparse_block_size
|
| 318 |
+
|
| 319 |
+
u_ = u + odd_offset
|
| 320 |
+
return torch.cat([hidden_states[..., u-s:u, :], hidden_states[..., -u_:-u_+s, :]], dim=-2)
|
| 321 |
+
|
| 322 |
+
def cat_global_sparse_local_tokens(self, x_global, x_sparse=None, x_local=None, dim=-2):
|
| 323 |
+
|
| 324 |
+
n, h, b, t, d = x_local.size()
|
| 325 |
+
x_global = x_global.unsqueeze(-3).expand(-1, -1, b, -1, -1)
|
| 326 |
+
if x_sparse is not None:
|
| 327 |
+
return torch.cat([x_global, x_sparse, x_local], dim=dim)
|
| 328 |
+
return torch.cat([x_global, x_local], dim=dim)
|
| 329 |
+
|
| 330 |
+
def chunk(self, x, n_blocks):
|
| 331 |
+
|
| 332 |
+
t, d = x.size()[-2:]
|
| 333 |
+
return x.reshape(*x.size()[:-2], n_blocks, -1, d)
|
| 334 |
+
|
| 335 |
+
|
| 336 |
+
class LSGBartEncoderAttention(BaseSelfAttention):
|
| 337 |
+
'''
|
| 338 |
+
Compute local attention with overlapping blocs
|
| 339 |
+
Use global attention for tokens with highest norm
|
| 340 |
+
'''
|
| 341 |
+
def __init__(
|
| 342 |
+
self,
|
| 343 |
+
config,
|
| 344 |
+
embed_dim,
|
| 345 |
+
num_heads,
|
| 346 |
+
dropout
|
| 347 |
+
):
|
| 348 |
+
|
| 349 |
+
super().__init__(embed_dim, num_heads, dropout)
|
| 350 |
+
|
| 351 |
+
self.block_size = config.block_size
|
| 352 |
+
self.sparse_block_size = config.sparse_block_size
|
| 353 |
+
self.num_global_tokens = config.num_global_tokens
|
| 354 |
+
self.sparsity_factor = config.sparsity_factor
|
| 355 |
+
|
| 356 |
+
self.attention = LSGAttentionProduct(
|
| 357 |
+
config,
|
| 358 |
+
block_size=config.block_size,
|
| 359 |
+
sparse_block_size=config.sparse_block_size,
|
| 360 |
+
sparsity_factor=self.sparsity_factor,
|
| 361 |
+
)
|
| 362 |
+
|
| 363 |
+
self.full_attention = BaseAttentionProduct(config)
|
| 364 |
+
|
| 365 |
+
sparse_functions = {
|
| 366 |
+
"norm": self.get_sparse_tokens_with_norm,
|
| 367 |
+
"pooling": self.get_sparse_tokens_with_pooling,
|
| 368 |
+
"lsh": self.get_sparse_tokens_with_lsh,
|
| 369 |
+
"stride": self.get_sparse_tokens_with_stride,
|
| 370 |
+
"block_stride": self.get_sparse_tokens_with_block_stride,
|
| 371 |
+
}
|
| 372 |
+
|
| 373 |
+
self.sparsity_type = config.sparsity_type
|
| 374 |
+
self.get_sparse_elements = sparse_functions.get(self.sparsity_type, lambda x, y, z: (None, None, None))
|
| 375 |
+
|
| 376 |
+
if config.sparsity_type == "lsh":
|
| 377 |
+
self.lsh_num_pre_rounds = config.lsh_num_pre_rounds
|
| 378 |
+
|
| 379 |
+
def get_sparse_tokens_with_norm(self, keys, values, mask):
|
| 380 |
+
|
| 381 |
+
if self.sparsity_factor == 1:
|
| 382 |
+
return keys, values, mask.expand(-1, keys.size()[1], -1, -1)
|
| 383 |
+
|
| 384 |
+
with torch.no_grad():
|
| 385 |
+
|
| 386 |
+
block_size = min(self.block_size, self.sparse_block_size)
|
| 387 |
+
key_norm = keys.detach().norm(dim=-1, keepdim=True)
|
| 388 |
+
key_norm = key_norm * ~mask.transpose(-1, -2).bool()
|
| 389 |
+
key_norm = self.chunk(key_norm, block_size)
|
| 390 |
+
|
| 391 |
+
n, h, b, t, d = key_norm.size()
|
| 392 |
+
|
| 393 |
+
idx = key_norm.argsort(dim=-2)
|
| 394 |
+
del key_norm
|
| 395 |
+
idx += (torch.arange(b, device=keys.device)*t).reshape(1, 1, b, 1, 1)
|
| 396 |
+
|
| 397 |
+
split = (t - block_size // self.sparsity_factor, block_size // self.sparsity_factor)
|
| 398 |
+
sparse_idx = idx.split(split, -2)[-1].reshape(n, h, -1, 1)
|
| 399 |
+
|
| 400 |
+
d = keys.size()[-1]
|
| 401 |
+
keys = keys.gather(dim=-2, index=sparse_idx.expand(-1, -1, -1, d))
|
| 402 |
+
values = values.gather(dim=-2, index=sparse_idx.expand(-1, -1, -1, d))
|
| 403 |
+
mask = mask.expand(-1, h, -1, -1).transpose(-1, -2).gather(dim=-2, index=sparse_idx).transpose(-1, -2)
|
| 404 |
+
|
| 405 |
+
return keys, values, mask
|
| 406 |
+
|
| 407 |
+
def get_sparse_tokens_with_pooling(self, keys, values, mask):
|
| 408 |
+
|
| 409 |
+
if self.sparsity_factor == 1:
|
| 410 |
+
return keys, values, mask.expand(-1, keys.size()[1], -1, -1)
|
| 411 |
+
|
| 412 |
+
keys = self.chunk(keys, self.sparsity_factor)
|
| 413 |
+
values = self.chunk(values, self.sparsity_factor)
|
| 414 |
+
|
| 415 |
+
n, h, b, t, d = keys.size()
|
| 416 |
+
mask = mask.reshape(n, 1, b, 1, t)
|
| 417 |
+
mask = ~mask.transpose(-1, -2).bool()
|
| 418 |
+
|
| 419 |
+
keys = keys * mask
|
| 420 |
+
values = values * mask
|
| 421 |
+
|
| 422 |
+
mask = mask.sum(dim=-2)
|
| 423 |
+
keys = keys.sum(dim=-2) / (mask + 1e-6)
|
| 424 |
+
values = values.sum(dim=-2) / (mask + 1e-6)
|
| 425 |
+
|
| 426 |
+
mask = - (1. - mask.clamp(0, 1)) * 1e4
|
| 427 |
+
return keys.reshape(n, h, -1, d), values.reshape(n, h, -1, d), mask.expand(-1, h, -1, -1).transpose(-1, -2)
|
| 428 |
+
|
| 429 |
+
def get_sparse_tokens_with_stride(self, keys, values, mask):
|
| 430 |
+
|
| 431 |
+
if self.sparsity_factor == 1:
|
| 432 |
+
return keys, values, mask.expand(-1, keys.size()[1], -1, -1)
|
| 433 |
+
|
| 434 |
+
n, h, t, d = keys.size()
|
| 435 |
+
sparse_idx = torch.arange(t // self.sparsity_factor, device=keys.device) * self.sparsity_factor
|
| 436 |
+
sparse_idx = sparse_idx.reshape(1, 1, -1, 1) + (torch.arange(h, device=keys.device) % self.sparsity_factor).reshape(1, h, 1, 1)
|
| 437 |
+
sparse_idx = sparse_idx.expand(n, h, -1, 1)
|
| 438 |
+
|
| 439 |
+
keys = keys.gather(dim=-2, index=sparse_idx.expand(-1, -1, -1, d))
|
| 440 |
+
values = values.gather(dim=-2, index=sparse_idx.expand(-1, -1, -1, d))
|
| 441 |
+
mask = mask.expand(-1, h, -1, -1).transpose(-1, -2).gather(dim=-2, index=sparse_idx).transpose(-1, -2)
|
| 442 |
+
|
| 443 |
+
return keys, values, mask
|
| 444 |
+
|
| 445 |
+
def get_sparse_tokens_with_block_stride(self, keys, values, mask):
|
| 446 |
+
|
| 447 |
+
if self.sparsity_factor == 1:
|
| 448 |
+
return keys, values, mask.expand(-1, keys.size()[1], -1, -1)
|
| 449 |
+
|
| 450 |
+
n, h, t, d = keys.size()
|
| 451 |
+
|
| 452 |
+
t, b = self.block_size, t // self.block_size
|
| 453 |
+
sparse_idx = torch.arange(t // self.sparsity_factor, device=keys.device)
|
| 454 |
+
sparse_idx = sparse_idx.reshape(1, 1, 1, -1, 1) + torch.arange(h, device=keys.device).reshape(1, h, 1, 1, 1) * (t // self.sparsity_factor)
|
| 455 |
+
sparse_idx = (sparse_idx % t)
|
| 456 |
+
sparse_idx = sparse_idx + torch.arange(b, device=keys.device).reshape(1, 1, -1, 1, 1) * t
|
| 457 |
+
sparse_idx = sparse_idx.reshape(1, h, -1, 1).expand(n, h, -1, 1)
|
| 458 |
+
|
| 459 |
+
keys = keys.gather(dim=-2, index=sparse_idx.expand(-1, -1, -1, d))
|
| 460 |
+
values = values.gather(dim=-2, index=sparse_idx.expand(-1, -1, -1, d))
|
| 461 |
+
mask = mask.expand(-1, h, -1, -1).transpose(-1, -2).gather(dim=-2, index=sparse_idx).transpose(-1, -2)
|
| 462 |
+
|
| 463 |
+
return keys, values, mask
|
| 464 |
+
|
| 465 |
+
def get_sparse_tokens_with_lsh(self, keys, values, mask):
|
| 466 |
+
|
| 467 |
+
if self.sparsity_factor == 1:
|
| 468 |
+
return keys, values, mask.expand(-1, keys.size()[1], -1, -1)
|
| 469 |
+
|
| 470 |
+
block_size = min(self.block_size, self.sparse_block_size)
|
| 471 |
+
keys = self.chunk(keys, block_size)
|
| 472 |
+
values = self.chunk(values, block_size)
|
| 473 |
+
|
| 474 |
+
n, h, b, t, d = keys.size()
|
| 475 |
+
mask = mask.reshape(n, 1, b, 1, t)
|
| 476 |
+
mask = ~mask.transpose(-1, -2).bool()
|
| 477 |
+
|
| 478 |
+
keys = keys * mask
|
| 479 |
+
values = values * mask
|
| 480 |
+
mask = mask.expand(-1, h, -1, -1, -1).float()
|
| 481 |
+
|
| 482 |
+
extra_factor = 1
|
| 483 |
+
|
| 484 |
+
for _ in range(self.lsh_num_pre_rounds):
|
| 485 |
+
keys, values, mask = self.lsh_round(keys, values, mask, t*extra_factor)
|
| 486 |
+
|
| 487 |
+
keys, values, mask = self.lsh_round(keys, values, mask, t//self.sparsity_factor)
|
| 488 |
+
keys /= mask + 1e-8
|
| 489 |
+
values /= mask + 1e-8
|
| 490 |
+
|
| 491 |
+
mask = -10000 * (1. - mask.clamp(0, 1))
|
| 492 |
+
|
| 493 |
+
return keys.reshape(n, h, -1, d), values.reshape(n, h, -1, d), mask.transpose(-1, -2).reshape(n, h, 1, -1)
|
| 494 |
+
|
| 495 |
+
def lsh_round(self, keys, values, mask, output_size):
|
| 496 |
+
|
| 497 |
+
with torch.no_grad():
|
| 498 |
+
|
| 499 |
+
n_hashes = output_size // 2
|
| 500 |
+
n, h, b, t, d = keys.size()
|
| 501 |
+
binary_mask = mask.clamp(0, 1)
|
| 502 |
+
|
| 503 |
+
indexes = (torch.nn.functional.normalize(keys, dim=-1) * binary_mask) @ torch.randn(1, h, 1, d, n_hashes, device=keys.device)
|
| 504 |
+
indexes = torch.cat([indexes, -indexes], dim=-1).argmax(dim=-1, keepdim=True)
|
| 505 |
+
|
| 506 |
+
n, h, b, t, d = keys.size()
|
| 507 |
+
|
| 508 |
+
x_ = torch.zeros(n, h, b, output_size, d, device=keys.device)
|
| 509 |
+
mask_ = torch.zeros(n, h, b, output_size, 1, device=keys.device)
|
| 510 |
+
keys = torch.scatter_add(x_, dim=-2, index=indexes.expand(-1, -1, -1, -1, d), src=keys)
|
| 511 |
+
values = torch.scatter_add(x_, dim=-2, index=indexes.expand(-1, -1, -1, -1, d), src=values)
|
| 512 |
+
mask = torch.scatter_add(mask_, dim=-2, index=indexes, src=mask)
|
| 513 |
+
|
| 514 |
+
return keys[..., :output_size, :], values[..., :output_size, :], mask[..., :output_size, :]
|
| 515 |
+
|
| 516 |
+
def forward(
|
| 517 |
+
self,
|
| 518 |
+
hidden_states,
|
| 519 |
+
attention_mask=None,
|
| 520 |
+
layer_head_mask=None,
|
| 521 |
+
output_attentions=False
|
| 522 |
+
):
|
| 523 |
+
|
| 524 |
+
query_layer, key_layer, value_layer = self.project_QKV(hidden_states)
|
| 525 |
+
outputs = self.not_causal_forward(
|
| 526 |
+
query_layer,
|
| 527 |
+
key_layer,
|
| 528 |
+
value_layer,
|
| 529 |
+
attention_mask=attention_mask[:, :, :1, :],
|
| 530 |
+
head_mask=layer_head_mask,
|
| 531 |
+
output_attentions=output_attentions
|
| 532 |
+
)
|
| 533 |
+
|
| 534 |
+
return self.out_proj(outputs), None, None
|
| 535 |
+
|
| 536 |
+
def not_causal_forward(
|
| 537 |
+
self,
|
| 538 |
+
query_layer,
|
| 539 |
+
key_layer,
|
| 540 |
+
value_layer,
|
| 541 |
+
attention_mask=None,
|
| 542 |
+
head_mask=None,
|
| 543 |
+
output_attentions=False,
|
| 544 |
+
):
|
| 545 |
+
|
| 546 |
+
n, h, t, d = query_layer.size()
|
| 547 |
+
|
| 548 |
+
# Cat global mask
|
| 549 |
+
attention_mask = torch.nn.functional.pad(attention_mask, (self.num_global_tokens, 0), value=0)
|
| 550 |
+
|
| 551 |
+
# Use normal attention if local attention covers every tokens
|
| 552 |
+
if t <= 2 * self.block_size + self.num_global_tokens:
|
| 553 |
+
context_layer = self.full_attention(
|
| 554 |
+
query_layer=query_layer,
|
| 555 |
+
key_layer=key_layer,
|
| 556 |
+
value_layer=value_layer,
|
| 557 |
+
attention_mask=attention_mask
|
| 558 |
+
)
|
| 559 |
+
|
| 560 |
+
if head_mask is not None:
|
| 561 |
+
context_layer = context_layer * head_mask[:, :, :1, :1]
|
| 562 |
+
return self.reshape_output(context_layer)
|
| 563 |
+
|
| 564 |
+
# Split input into global tokens and other tokens
|
| 565 |
+
split = (self.num_global_tokens, t - self.num_global_tokens)
|
| 566 |
+
global_query, query_layer = query_layer.split(split, dim=-2)
|
| 567 |
+
|
| 568 |
+
# Get global_attention
|
| 569 |
+
bos = self.full_attention(
|
| 570 |
+
query_layer=global_query,
|
| 571 |
+
key_layer=key_layer,
|
| 572 |
+
value_layer=value_layer,
|
| 573 |
+
attention_mask=attention_mask
|
| 574 |
+
)
|
| 575 |
+
|
| 576 |
+
# Split K Q M on global and non global
|
| 577 |
+
global_key, key_layer = key_layer.split(split, dim=-2)
|
| 578 |
+
global_value, value_layer = value_layer.split(split, dim=-2)
|
| 579 |
+
global_mask, attention_mask = attention_mask.split(split, dim=-1)
|
| 580 |
+
|
| 581 |
+
n, h, t, d = key_layer.size()
|
| 582 |
+
|
| 583 |
+
# Get sparse idx
|
| 584 |
+
sparse_key, sparse_value, sparse_mask = (None, None, None)
|
| 585 |
+
|
| 586 |
+
if self.sparse_block_size and self.sparsity_factor > 0:
|
| 587 |
+
sparse_key, sparse_value, sparse_mask = self.get_sparse_elements(key_layer, value_layer, attention_mask)
|
| 588 |
+
|
| 589 |
+
# Expand masks on heads
|
| 590 |
+
attention_mask = attention_mask.expand(-1, h, -1, -1)
|
| 591 |
+
global_mask = global_mask.expand(-1, h, -1, -1)
|
| 592 |
+
|
| 593 |
+
# Compute dot product attention
|
| 594 |
+
context_layer = self.attention(
|
| 595 |
+
query_layer,
|
| 596 |
+
key_layer,
|
| 597 |
+
value_layer,
|
| 598 |
+
attention_mask,
|
| 599 |
+
sparse_key=sparse_key,
|
| 600 |
+
sparse_value=sparse_value,
|
| 601 |
+
sparse_mask=sparse_mask,
|
| 602 |
+
global_key=global_key,
|
| 603 |
+
global_value=global_value,
|
| 604 |
+
global_mask=global_mask
|
| 605 |
+
)
|
| 606 |
+
|
| 607 |
+
# Merge global and local-sparse tokens
|
| 608 |
+
context_layer = torch.cat([bos, context_layer], dim=-2)
|
| 609 |
+
if head_mask is not None:
|
| 610 |
+
context_layer = context_layer * head_mask[:, :, :1, :1]
|
| 611 |
+
context_layer = self.reshape_output(context_layer)
|
| 612 |
+
|
| 613 |
+
return context_layer
|
| 614 |
+
|
| 615 |
+
def chunk(self, x, chunk_size):
|
| 616 |
+
|
| 617 |
+
n, h, t, d = x.size()
|
| 618 |
+
return x.reshape(n, h, -1, chunk_size, d)
|
| 619 |
+
|
| 620 |
+
|
| 621 |
+
class LSGBartEncoderLayer(BartEncoderLayer):
|
| 622 |
+
|
| 623 |
+
def __init__(self, config):
|
| 624 |
+
|
| 625 |
+
super().__init__(config)
|
| 626 |
+
self.self_attn = LSGBartEncoderAttention(
|
| 627 |
+
config=config,
|
| 628 |
+
embed_dim=self.embed_dim,
|
| 629 |
+
num_heads=config.encoder_attention_heads,
|
| 630 |
+
dropout=config.attention_dropout,
|
| 631 |
+
)
|
| 632 |
+
|
| 633 |
+
|
| 634 |
+
class LSGBartDecoderLayer(BartDecoderLayer):
|
| 635 |
+
|
| 636 |
+
def __init__(self, config):
|
| 637 |
+
|
| 638 |
+
super().__init__(config)
|
| 639 |
+
|
| 640 |
+
|
| 641 |
+
class LSGBartClassificationHead(BartClassificationHead):
|
| 642 |
+
"""Head for sentence-level classification tasks."""
|
| 643 |
+
|
| 644 |
+
def __init__(
|
| 645 |
+
self,
|
| 646 |
+
input_dim,
|
| 647 |
+
inner_dim,
|
| 648 |
+
num_classes,
|
| 649 |
+
pooler_dropout,
|
| 650 |
+
):
|
| 651 |
+
|
| 652 |
+
super().__init__(input_dim, inner_dim, num_classes, pooler_dropout)
|
| 653 |
+
|
| 654 |
+
|
| 655 |
+
class LSGBartPretrainedModel(BartPretrainedModel):
|
| 656 |
+
|
| 657 |
+
config_class = LSGBartConfig
|
| 658 |
+
|
| 659 |
+
def _set_gradient_checkpointing(self, module, value=False):
|
| 660 |
+
|
| 661 |
+
if isinstance(module, (BartDecoder, BartEncoder, LSGBartDecoder, LSGBartEncoder)):
|
| 662 |
+
module.gradient_checkpointing = value
|
| 663 |
+
|
| 664 |
+
|
| 665 |
+
class PretrainedLSGBartModel(LSGBartPretrainedModel):
|
| 666 |
+
|
| 667 |
+
def __init_subclass__(self):
|
| 668 |
+
warnings.warn(
|
| 669 |
+
"The class `PretrainedBartModel` has been depreciated, please use `LSGBartPretrainedModel` instead.",
|
| 670 |
+
FutureWarning,
|
| 671 |
+
)
|
| 672 |
+
|
| 673 |
+
|
| 674 |
+
class LSGBartEncoder(LSGBartPretrainedModel, BartEncoder):
|
| 675 |
+
"""
|
| 676 |
+
Transformer encoder consisting of *config.encoder_layers* self attention layers. Each layer is a
|
| 677 |
+
:class:`BartEncoderLayer`.
|
| 678 |
+
Args:
|
| 679 |
+
config: BartConfig
|
| 680 |
+
embed_tokens (nn.Embedding): output embedding
|
| 681 |
+
"""
|
| 682 |
+
|
| 683 |
+
def __init__(self, config, embed_tokens=None):
|
| 684 |
+
|
| 685 |
+
super().__init__(config)
|
| 686 |
+
self.dropout = config.dropout
|
| 687 |
+
self.layerdrop = config.encoder_layerdrop
|
| 688 |
+
|
| 689 |
+
embed_dim = config.d_model
|
| 690 |
+
self.padding_idx = config.pad_token_id
|
| 691 |
+
self.max_source_positions = config.max_position_embeddings
|
| 692 |
+
self.embed_scale = math.sqrt(embed_dim) if config.scale_embedding else 1.0
|
| 693 |
+
|
| 694 |
+
if embed_tokens is not None:
|
| 695 |
+
self.embed_tokens = embed_tokens
|
| 696 |
+
else:
|
| 697 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, embed_dim, self.padding_idx)
|
| 698 |
+
|
| 699 |
+
self.embed_positions = BartLearnedPositionalEmbedding(
|
| 700 |
+
config.max_position_embeddings,
|
| 701 |
+
embed_dim,
|
| 702 |
+
)
|
| 703 |
+
self.layers = nn.ModuleList([LSGBartEncoderLayer(config) for _ in range(config.encoder_layers)])
|
| 704 |
+
self.layernorm_embedding = nn.LayerNorm(embed_dim)
|
| 705 |
+
|
| 706 |
+
#
|
| 707 |
+
assert hasattr(config, "num_global_tokens")
|
| 708 |
+
self.num_global_tokens = config.num_global_tokens
|
| 709 |
+
self.pad_idx = config.pad_token_id
|
| 710 |
+
|
| 711 |
+
assert hasattr(config, "block_size") and hasattr(config, "adaptive")
|
| 712 |
+
self.block_size = config.block_size
|
| 713 |
+
self.adaptive = config.adaptive
|
| 714 |
+
self.pool_with_global = config.pool_with_global
|
| 715 |
+
self.pass_global_tokens_to_decoder = config.pass_global_tokens_to_decoder
|
| 716 |
+
|
| 717 |
+
self.global_embeddings = nn.Embedding(512, embedding_dim=config.d_model)
|
| 718 |
+
|
| 719 |
+
self.gradient_checkpointing = False
|
| 720 |
+
|
| 721 |
+
# Initialize weights and apply final processing
|
| 722 |
+
self.post_init()
|
| 723 |
+
|
| 724 |
+
def forward(self,
|
| 725 |
+
input_ids=None,
|
| 726 |
+
attention_mask=None,
|
| 727 |
+
head_mask=None,
|
| 728 |
+
inputs_embeds=None,
|
| 729 |
+
output_attentions=None,
|
| 730 |
+
output_hidden_states=None,
|
| 731 |
+
return_dict=None
|
| 732 |
+
):
|
| 733 |
+
|
| 734 |
+
|
| 735 |
+
inputs_ = input_ids if input_ids is not None else inputs_embeds
|
| 736 |
+
n, t = inputs_.size()[:2]
|
| 737 |
+
|
| 738 |
+
if attention_mask is None:
|
| 739 |
+
attention_mask = torch.ones(n, t, device=inputs_.device)
|
| 740 |
+
|
| 741 |
+
b = self.block_size * 2
|
| 742 |
+
pad = t % self.block_size
|
| 743 |
+
|
| 744 |
+
# Check if t is multiple of block_size and pad
|
| 745 |
+
if self.adaptive and t > b and pad > 0:
|
| 746 |
+
pad_length = self.block_size - pad
|
| 747 |
+
if input_ids is not None:
|
| 748 |
+
input_ids = torch.nn.functional.pad(input_ids, (0, pad_length), value=self.pad_idx)
|
| 749 |
+
else:
|
| 750 |
+
inputs_embeds = torch.nn.functional.pad(inputs_embeds.transpose(-1, -2), (0, pad_length), value=0.).transpose(-1, -2)
|
| 751 |
+
attention_mask = torch.nn.functional.pad(attention_mask, (0, pad_length), value=0)
|
| 752 |
+
|
| 753 |
+
n, t_ = attention_mask.size()
|
| 754 |
+
|
| 755 |
+
encoder_outputs = self.forward_with_adaptive(
|
| 756 |
+
input_ids=input_ids,
|
| 757 |
+
attention_mask=attention_mask,
|
| 758 |
+
head_mask=head_mask,
|
| 759 |
+
inputs_embeds=inputs_embeds,
|
| 760 |
+
output_attentions=output_attentions,
|
| 761 |
+
output_hidden_states=output_hidden_states,
|
| 762 |
+
return_dict=return_dict,
|
| 763 |
+
)
|
| 764 |
+
|
| 765 |
+
context = encoder_outputs[0]
|
| 766 |
+
diff = t - t_
|
| 767 |
+
|
| 768 |
+
if self.pass_global_tokens_to_decoder:
|
| 769 |
+
offset = self.num_global_tokens
|
| 770 |
+
else:
|
| 771 |
+
if self.pool_with_global:
|
| 772 |
+
context[:, self.num_global_tokens] = context[:, 0]
|
| 773 |
+
context = context[..., self.num_global_tokens:, :]
|
| 774 |
+
offset = 0
|
| 775 |
+
|
| 776 |
+
# Adapt sequence to initial shape
|
| 777 |
+
if diff < 0:
|
| 778 |
+
context = context[:, :t + offset]
|
| 779 |
+
|
| 780 |
+
if return_dict:
|
| 781 |
+
encoder_outputs.last_hidden_state = context
|
| 782 |
+
else:
|
| 783 |
+
encoder_outputs = (context, ) + encoder_outputs[1:]
|
| 784 |
+
|
| 785 |
+
return encoder_outputs
|
| 786 |
+
|
| 787 |
+
def forward_with_adaptive(
|
| 788 |
+
self,
|
| 789 |
+
input_ids=None,
|
| 790 |
+
attention_mask=None,
|
| 791 |
+
head_mask=None,
|
| 792 |
+
inputs_embeds=None,
|
| 793 |
+
output_attentions=None,
|
| 794 |
+
output_hidden_states=None,
|
| 795 |
+
return_dict=None,
|
| 796 |
+
):
|
| 797 |
+
|
| 798 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 799 |
+
output_hidden_states = (
|
| 800 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 801 |
+
)
|
| 802 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 803 |
+
|
| 804 |
+
# retrieve input_ids and inputs_embeds
|
| 805 |
+
if input_ids is not None and inputs_embeds is not None:
|
| 806 |
+
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
| 807 |
+
elif input_ids is not None:
|
| 808 |
+
input_shape = input_ids.size()
|
| 809 |
+
input_ids = input_ids.view(-1, input_shape[-1])
|
| 810 |
+
elif inputs_embeds is not None:
|
| 811 |
+
input_shape = inputs_embeds.size()[:-1]
|
| 812 |
+
else:
|
| 813 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
| 814 |
+
|
| 815 |
+
if inputs_embeds is None:
|
| 816 |
+
inputs_embeds = self.embed_tokens(input_ids) * self.embed_scale
|
| 817 |
+
|
| 818 |
+
embed_pos = self.embed_positions(input_shape)
|
| 819 |
+
hidden_states = inputs_embeds + embed_pos
|
| 820 |
+
|
| 821 |
+
# Add global tokens
|
| 822 |
+
n, t, d = hidden_states.size()
|
| 823 |
+
global_idx = torch.arange(self.num_global_tokens, device=hidden_states.device).reshape(1, -1)
|
| 824 |
+
hidden_states = torch.cat([self.global_embeddings(global_idx).expand(n, -1, -1), hidden_states], dim=-2)
|
| 825 |
+
|
| 826 |
+
hidden_states = self.layernorm_embedding(hidden_states)
|
| 827 |
+
hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
|
| 828 |
+
|
| 829 |
+
# expand attention_mask
|
| 830 |
+
if attention_mask is not None:
|
| 831 |
+
# [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
|
| 832 |
+
attention_mask = _expand_mask(attention_mask, inputs_embeds.dtype)
|
| 833 |
+
|
| 834 |
+
encoder_states = () if output_hidden_states else None
|
| 835 |
+
all_attentions = () if output_attentions else None
|
| 836 |
+
|
| 837 |
+
# check if head_mask has a correct number of layers specified if desired
|
| 838 |
+
if head_mask is not None:
|
| 839 |
+
if head_mask.size()[0] != (len(self.layers)):
|
| 840 |
+
raise ValueError(
|
| 841 |
+
f"The head_mask should be specified for {len(self.layers)} layers, but it is for {head_mask.size()[0]}."
|
| 842 |
+
)
|
| 843 |
+
|
| 844 |
+
for idx, encoder_layer in enumerate(self.layers):
|
| 845 |
+
if output_hidden_states:
|
| 846 |
+
encoder_states = encoder_states + (hidden_states,)
|
| 847 |
+
# add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
|
| 848 |
+
dropout_probability = random.uniform(0, 1)
|
| 849 |
+
if self.training and (dropout_probability < self.layerdrop): # skip the layer
|
| 850 |
+
layer_outputs = (None, None)
|
| 851 |
+
else:
|
| 852 |
+
if self.gradient_checkpointing and self.training:
|
| 853 |
+
|
| 854 |
+
def create_custom_forward(module):
|
| 855 |
+
def custom_forward(*inputs):
|
| 856 |
+
return module(*inputs, output_attentions)
|
| 857 |
+
|
| 858 |
+
return custom_forward
|
| 859 |
+
|
| 860 |
+
layer_outputs = torch.utils.checkpoint.checkpoint(
|
| 861 |
+
create_custom_forward(encoder_layer),
|
| 862 |
+
hidden_states,
|
| 863 |
+
attention_mask,
|
| 864 |
+
(head_mask[idx] if head_mask is not None else None),
|
| 865 |
+
)
|
| 866 |
+
else:
|
| 867 |
+
layer_outputs = encoder_layer(
|
| 868 |
+
hidden_states,
|
| 869 |
+
attention_mask,
|
| 870 |
+
layer_head_mask=(head_mask[idx] if head_mask is not None else None),
|
| 871 |
+
output_attentions=output_attentions,
|
| 872 |
+
)
|
| 873 |
+
|
| 874 |
+
hidden_states = layer_outputs[0]
|
| 875 |
+
|
| 876 |
+
if output_attentions:
|
| 877 |
+
all_attentions = all_attentions + (layer_outputs[1],)
|
| 878 |
+
|
| 879 |
+
if output_hidden_states:
|
| 880 |
+
encoder_states = encoder_states + (hidden_states,)
|
| 881 |
+
|
| 882 |
+
if not return_dict:
|
| 883 |
+
return tuple(v for v in [hidden_states, encoder_states, all_attentions] if v is not None)
|
| 884 |
+
return BaseModelOutput(
|
| 885 |
+
last_hidden_state=hidden_states, hidden_states=encoder_states, attentions=all_attentions
|
| 886 |
+
)
|
| 887 |
+
|
| 888 |
+
|
| 889 |
+
class LSGBartDecoder(BartDecoder, LSGBartPretrainedModel):
|
| 890 |
+
"""
|
| 891 |
+
Transformer decoder consisting of *config.decoder_layers* layers. Each layer is a :class:`LSGBartDecoderLayer`
|
| 892 |
+
Args:
|
| 893 |
+
config: BartConfig
|
| 894 |
+
embed_tokens (nn.Embedding): output embedding
|
| 895 |
+
"""
|
| 896 |
+
|
| 897 |
+
def __init__(self, config, embed_tokens=None):
|
| 898 |
+
|
| 899 |
+
LSGBartPretrainedModel.__init__(self, config)
|
| 900 |
+
|
| 901 |
+
self.dropout = config.dropout
|
| 902 |
+
self.layerdrop = config.decoder_layerdrop
|
| 903 |
+
self.padding_idx = config.pad_token_id
|
| 904 |
+
self.max_target_positions = config.max_position_embeddings
|
| 905 |
+
self.embed_scale = math.sqrt(config.d_model) if config.scale_embedding else 1.0
|
| 906 |
+
self.adaptive = config.adaptive
|
| 907 |
+
|
| 908 |
+
if embed_tokens is not None:
|
| 909 |
+
self.embed_tokens = embed_tokens
|
| 910 |
+
else:
|
| 911 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, config.d_model, self.padding_idx)
|
| 912 |
+
|
| 913 |
+
self.embed_positions = BartLearnedPositionalEmbedding(
|
| 914 |
+
config.max_position_embeddings,
|
| 915 |
+
config.d_model,
|
| 916 |
+
)
|
| 917 |
+
self.layers = nn.ModuleList([LSGBartDecoderLayer(config) for _ in range(config.decoder_layers)])
|
| 918 |
+
self.layernorm_embedding = nn.LayerNorm(config.d_model)
|
| 919 |
+
|
| 920 |
+
self.gradient_checkpointing = False
|
| 921 |
+
|
| 922 |
+
# Initialize weights and apply final processing
|
| 923 |
+
self.post_init()
|
| 924 |
+
|
| 925 |
+
|
| 926 |
+
class LSGBartModel(LSGBartPretrainedModel, BartModel):
|
| 927 |
+
|
| 928 |
+
def __init__(self, config):
|
| 929 |
+
|
| 930 |
+
LSGBartPretrainedModel.__init__(self, config)
|
| 931 |
+
|
| 932 |
+
padding_idx, vocab_size = config.pad_token_id, config.vocab_size
|
| 933 |
+
self.shared = nn.Embedding(vocab_size, config.d_model, padding_idx)
|
| 934 |
+
|
| 935 |
+
self.pass_global_tokens_to_decoder = config.pass_global_tokens_to_decoder
|
| 936 |
+
self.num_global_tokens = config.num_global_tokens
|
| 937 |
+
|
| 938 |
+
self.encoder = LSGBartEncoder(config, self.shared)
|
| 939 |
+
self.decoder = LSGBartDecoder(config, self.shared)
|
| 940 |
+
|
| 941 |
+
# Initialize weights and apply final processing
|
| 942 |
+
self.post_init()
|
| 943 |
+
|
| 944 |
+
def forward(
|
| 945 |
+
self,
|
| 946 |
+
input_ids=None,
|
| 947 |
+
attention_mask=None,
|
| 948 |
+
decoder_input_ids=None,
|
| 949 |
+
decoder_attention_mask=None,
|
| 950 |
+
head_mask=None,
|
| 951 |
+
decoder_head_mask=None,
|
| 952 |
+
cross_attn_head_mask=None,
|
| 953 |
+
encoder_outputs=None,
|
| 954 |
+
past_key_values=None,
|
| 955 |
+
inputs_embeds=None,
|
| 956 |
+
decoder_inputs_embeds=None,
|
| 957 |
+
use_cache=None,
|
| 958 |
+
output_attentions=None,
|
| 959 |
+
output_hidden_states=None,
|
| 960 |
+
return_dict=None,
|
| 961 |
+
):
|
| 962 |
+
|
| 963 |
+
# different to other models, Bart automatically creates decoder_input_ids from
|
| 964 |
+
# input_ids if no decoder_input_ids are provided
|
| 965 |
+
if decoder_input_ids is None and decoder_inputs_embeds is None:
|
| 966 |
+
decoder_input_ids = shift_tokens_right(
|
| 967 |
+
input_ids, self.config.pad_token_id, self.config.decoder_start_token_id
|
| 968 |
+
)
|
| 969 |
+
|
| 970 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
| 971 |
+
output_hidden_states = (
|
| 972 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 973 |
+
)
|
| 974 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
| 975 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 976 |
+
|
| 977 |
+
if encoder_outputs is None:
|
| 978 |
+
encoder_outputs = self.encoder(
|
| 979 |
+
input_ids=input_ids,
|
| 980 |
+
attention_mask=attention_mask,
|
| 981 |
+
head_mask=head_mask,
|
| 982 |
+
inputs_embeds=inputs_embeds,
|
| 983 |
+
output_attentions=output_attentions,
|
| 984 |
+
output_hidden_states=output_hidden_states,
|
| 985 |
+
return_dict=return_dict,
|
| 986 |
+
)
|
| 987 |
+
# If the user passed a tuple for encoder_outputs, we wrap it in a BaseModelOutput when return_dict=True
|
| 988 |
+
elif return_dict and not isinstance(encoder_outputs, BaseModelOutput):
|
| 989 |
+
encoder_outputs = BaseModelOutput(
|
| 990 |
+
last_hidden_state=encoder_outputs[0],
|
| 991 |
+
hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,
|
| 992 |
+
attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,
|
| 993 |
+
)
|
| 994 |
+
|
| 995 |
+
# Pad mask for global tokens
|
| 996 |
+
if self.pass_global_tokens_to_decoder:
|
| 997 |
+
attention_mask = torch.nn.functional.pad(attention_mask, pad=(self.num_global_tokens, 0), value=1)
|
| 998 |
+
|
| 999 |
+
# decoder outputs consists of (dec_features, past_key_value, dec_hidden, dec_attn)
|
| 1000 |
+
decoder_outputs = self.decoder(
|
| 1001 |
+
input_ids=decoder_input_ids,
|
| 1002 |
+
attention_mask=decoder_attention_mask,
|
| 1003 |
+
encoder_hidden_states=encoder_outputs[0],
|
| 1004 |
+
encoder_attention_mask=attention_mask,
|
| 1005 |
+
head_mask=decoder_head_mask,
|
| 1006 |
+
cross_attn_head_mask=cross_attn_head_mask,
|
| 1007 |
+
past_key_values=past_key_values,
|
| 1008 |
+
inputs_embeds=decoder_inputs_embeds,
|
| 1009 |
+
use_cache=use_cache,
|
| 1010 |
+
output_attentions=output_attentions,
|
| 1011 |
+
output_hidden_states=output_hidden_states,
|
| 1012 |
+
return_dict=return_dict,
|
| 1013 |
+
)
|
| 1014 |
+
|
| 1015 |
+
if not return_dict:
|
| 1016 |
+
return decoder_outputs + encoder_outputs
|
| 1017 |
+
|
| 1018 |
+
return Seq2SeqModelOutput(
|
| 1019 |
+
last_hidden_state=decoder_outputs.last_hidden_state,
|
| 1020 |
+
past_key_values=decoder_outputs.past_key_values,
|
| 1021 |
+
decoder_hidden_states=decoder_outputs.hidden_states,
|
| 1022 |
+
decoder_attentions=decoder_outputs.attentions,
|
| 1023 |
+
cross_attentions=decoder_outputs.cross_attentions,
|
| 1024 |
+
encoder_last_hidden_state=encoder_outputs.last_hidden_state,
|
| 1025 |
+
encoder_hidden_states=encoder_outputs.hidden_states,
|
| 1026 |
+
encoder_attentions=encoder_outputs.attentions,
|
| 1027 |
+
)
|
| 1028 |
+
|
| 1029 |
+
|
| 1030 |
+
class LSGBartForConditionalGeneration(BartForConditionalGeneration, LSGBartPretrainedModel):
|
| 1031 |
+
|
| 1032 |
+
base_model_prefix = "model"
|
| 1033 |
+
_keys_to_ignore_on_load_missing = [r"final_logits_bias", r"lm_head\.weight"]
|
| 1034 |
+
|
| 1035 |
+
def __init__(self, config):
|
| 1036 |
+
|
| 1037 |
+
LSGBartPretrainedModel.__init__(self, config)
|
| 1038 |
+
self.model = LSGBartModel(config)
|
| 1039 |
+
self.register_buffer("final_logits_bias", torch.zeros((1, self.model.shared.num_embeddings)))
|
| 1040 |
+
self.lm_head = nn.Linear(config.d_model, self.model.shared.num_embeddings, bias=False)
|
| 1041 |
+
|
| 1042 |
+
# Initialize weights and apply final processing
|
| 1043 |
+
self.post_init()
|
| 1044 |
+
|
| 1045 |
+
|
| 1046 |
+
class LSGBartForSequenceClassification(BartForSequenceClassification, LSGBartPretrainedModel):
|
| 1047 |
+
|
| 1048 |
+
def __init__(self, config: LSGBartConfig, **kwargs):
|
| 1049 |
+
|
| 1050 |
+
LSGBartPretrainedModel.__init__(self, config, **kwargs)
|
| 1051 |
+
self.model = LSGBartModel(config)
|
| 1052 |
+
self.classification_head = LSGBartClassificationHead(
|
| 1053 |
+
config.d_model,
|
| 1054 |
+
config.d_model,
|
| 1055 |
+
config.num_labels,
|
| 1056 |
+
config.classifier_dropout,
|
| 1057 |
+
)
|
| 1058 |
+
self.model._init_weights(self.classification_head.dense)
|
| 1059 |
+
self.model._init_weights(self.classification_head.out_proj)
|
| 1060 |
+
|
| 1061 |
+
|
| 1062 |
+
class LSGBartForQuestionAnswering(BartForQuestionAnswering, LSGBartPretrainedModel):
|
| 1063 |
+
|
| 1064 |
+
def __init__(self, config: LSGBartConfig):
|
| 1065 |
+
|
| 1066 |
+
LSGBartPretrainedModel.__init__(self, config)
|
| 1067 |
+
|
| 1068 |
+
config.num_labels = 2
|
| 1069 |
+
self.num_labels = config.num_labels
|
| 1070 |
+
|
| 1071 |
+
self.model = LSGBartModel(config)
|
| 1072 |
+
self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
|
| 1073 |
+
|
| 1074 |
+
self.model._init_weights(self.qa_outputs)
|
| 1075 |
+
|
| 1076 |
+
|
| 1077 |
+
class LSGBartDecoderWrapper(LSGBartPretrainedModel):
|
| 1078 |
+
"""
|
| 1079 |
+
This wrapper class is a helper class to correctly load pretrained checkpoints when the causal language model is
|
| 1080 |
+
used in combination with the :class:`~transformers.EncoderDecoderModel` framework.
|
| 1081 |
+
"""
|
| 1082 |
+
|
| 1083 |
+
def __init__(self, config: LSGBartConfig):
|
| 1084 |
+
super().__init__(config)
|
| 1085 |
+
self.decoder = LSGBartDecoder(config)
|
| 1086 |
+
|
| 1087 |
+
def forward(self, *args, **kwargs):
|
| 1088 |
+
return self.decoder(*args, **kwargs)
|
| 1089 |
+
|
| 1090 |
+
|
| 1091 |
+
class LSGBartForCausalLM(BartForCausalLM, LSGBartPretrainedModel):
|
| 1092 |
+
|
| 1093 |
+
def __init__(self, config: LSGBartConfig):
|
| 1094 |
+
|
| 1095 |
+
config = copy.deepcopy(config)
|
| 1096 |
+
config.is_decoder = True
|
| 1097 |
+
config.is_encoder_decoder = False
|
| 1098 |
+
LSGBartPretrainedModel.__init__(self, config)
|
| 1099 |
+
self.model = LSGBartDecoderWrapper(config)
|
| 1100 |
+
|
| 1101 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
| 1102 |
+
|
| 1103 |
+
# Initialize weights and apply final processing
|
| 1104 |
+
self.post_init()
|
| 1105 |
+
|
| 1106 |
+
|
| 1107 |
+
def str_to_class(classname):
|
| 1108 |
+
return getattr(sys.modules[__name__], classname)
|
| 1109 |
+
|
| 1110 |
+
# Register model in Auto API
|
| 1111 |
+
try:
|
| 1112 |
+
LSGBartConfig.register_for_auto_class()
|
| 1113 |
+
for key, value in AUTO_MAP.items():
|
| 1114 |
+
str_to_class(value.split(".")[-1]).register_for_auto_class(key)
|
| 1115 |
+
except:
|
| 1116 |
+
warn("AutoRegister isn't available, you'll have to manually copy modeling.py after .save_pretrained(...).")
|
| 1117 |
+
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:846341901417061086a1539604133c238fc62e05b5ace694f6c755c15a3fe6b8
|
| 3 |
+
size 578412983
|
special_tokens_map.json
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
{"bos_token": "<s>", "eos_token": "</s>", "unk_token": "<unk>", "sep_token": "</s>", "pad_token": "<pad>", "cls_token": "<s>", "mask_token": {"content": "<mask>", "single_word": false, "lstrip": true, "rstrip": false, "normalized": false}}
|
tokenizer.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
tokenizer_config.json
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
{"errors": "replace", "bos_token": "<s>", "eos_token": "</s>", "sep_token": "</s>", "cls_token": "<s>", "unk_token": "<unk>", "pad_token": "<pad>", "mask_token": "<mask>", "add_prefix_space": false, "trim_offsets": true, "model_max_length": 4096, "special_tokens_map_file": null, "name_or_path": "facebook/bart-base", "tokenizer_class": "BartTokenizer"}
|
vocab.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|