Add new SentenceTransformer model.
Browse files- 1_Pooling/config.json +10 -0
- README.md +221 -0
- config.json +33 -0
- config_sentence_transformers.json +10 -0
- configuration_retrieva_bert.py +129 -0
- model.safetensors +3 -0
- modules.json +14 -0
- retrieva_modeling.py +1515 -0
- sentence_bert_config.json +4 -0
- special_tokens_map.json +54 -0
- tokenizer.json +0 -0
- tokenizer_config.json +91 -0
1_Pooling/config.json
ADDED
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"word_embedding_dimension": 768,
|
3 |
+
"pooling_mode_cls_token": false,
|
4 |
+
"pooling_mode_mean_tokens": true,
|
5 |
+
"pooling_mode_max_tokens": false,
|
6 |
+
"pooling_mode_mean_sqrt_len_tokens": false,
|
7 |
+
"pooling_mode_weightedmean_tokens": false,
|
8 |
+
"pooling_mode_lasttoken": false,
|
9 |
+
"include_prompt": true
|
10 |
+
}
|
README.md
ADDED
@@ -0,0 +1,221 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
---
|
2 |
+
language: []
|
3 |
+
library_name: sentence-transformers
|
4 |
+
tags:
|
5 |
+
- sentence-transformers
|
6 |
+
- sentence-similarity
|
7 |
+
- feature-extraction
|
8 |
+
base_model: yano0/my_rope_bert_v2
|
9 |
+
metrics:
|
10 |
+
- pearson_cosine
|
11 |
+
- spearman_cosine
|
12 |
+
- pearson_manhattan
|
13 |
+
- spearman_manhattan
|
14 |
+
- pearson_euclidean
|
15 |
+
- spearman_euclidean
|
16 |
+
- pearson_dot
|
17 |
+
- spearman_dot
|
18 |
+
- pearson_max
|
19 |
+
- spearman_max
|
20 |
+
widget: []
|
21 |
+
pipeline_tag: sentence-similarity
|
22 |
+
model-index:
|
23 |
+
- name: SentenceTransformer based on yano0/my_rope_bert_v2
|
24 |
+
results:
|
25 |
+
- task:
|
26 |
+
type: semantic-similarity
|
27 |
+
name: Semantic Similarity
|
28 |
+
dataset:
|
29 |
+
name: Unknown
|
30 |
+
type: unknown
|
31 |
+
metrics:
|
32 |
+
- type: pearson_cosine
|
33 |
+
value: 0.8363388345473755
|
34 |
+
name: Pearson Cosine
|
35 |
+
- type: spearman_cosine
|
36 |
+
value: 0.7829140815230603
|
37 |
+
name: Spearman Cosine
|
38 |
+
- type: pearson_manhattan
|
39 |
+
value: 0.8169134821588451
|
40 |
+
name: Pearson Manhattan
|
41 |
+
- type: spearman_manhattan
|
42 |
+
value: 0.7806182228552376
|
43 |
+
name: Spearman Manhattan
|
44 |
+
- type: pearson_euclidean
|
45 |
+
value: 0.8176194153920942
|
46 |
+
name: Pearson Euclidean
|
47 |
+
- type: spearman_euclidean
|
48 |
+
value: 0.7812646926795144
|
49 |
+
name: Spearman Euclidean
|
50 |
+
- type: pearson_dot
|
51 |
+
value: 0.790584312051173
|
52 |
+
name: Pearson Dot
|
53 |
+
- type: spearman_dot
|
54 |
+
value: 0.7341313863604967
|
55 |
+
name: Spearman Dot
|
56 |
+
- type: pearson_max
|
57 |
+
value: 0.8363388345473755
|
58 |
+
name: Pearson Max
|
59 |
+
- type: spearman_max
|
60 |
+
value: 0.7829140815230603
|
61 |
+
name: Spearman Max
|
62 |
+
---
|
63 |
+
|
64 |
+
# SentenceTransformer based on yano0/my_rope_bert_v2
|
65 |
+
|
66 |
+
This is a [sentence-transformers](https://www.SBERT.net) model finetuned from [yano0/my_rope_bert_v2](https://huggingface.co/yano0/my_rope_bert_v2). It maps sentences & paragraphs to a 768-dimensional dense vector space and can be used for semantic textual similarity, semantic search, paraphrase mining, text classification, clustering, and more.
|
67 |
+
|
68 |
+
## Model Details
|
69 |
+
|
70 |
+
### Model Description
|
71 |
+
- **Model Type:** Sentence Transformer
|
72 |
+
- **Base model:** [yano0/my_rope_bert_v2](https://huggingface.co/yano0/my_rope_bert_v2) <!-- at revision a392086c08b3bf3a9b9030267a8965af0552d7fb -->
|
73 |
+
- **Maximum Sequence Length:** 1024 tokens
|
74 |
+
- **Output Dimensionality:** 768 tokens
|
75 |
+
- **Similarity Function:** Cosine Similarity
|
76 |
+
<!-- - **Training Dataset:** Unknown -->
|
77 |
+
<!-- - **Language:** Unknown -->
|
78 |
+
<!-- - **License:** Unknown -->
|
79 |
+
|
80 |
+
### Model Sources
|
81 |
+
|
82 |
+
- **Documentation:** [Sentence Transformers Documentation](https://sbert.net)
|
83 |
+
- **Repository:** [Sentence Transformers on GitHub](https://github.com/UKPLab/sentence-transformers)
|
84 |
+
- **Hugging Face:** [Sentence Transformers on Hugging Face](https://huggingface.co/models?library=sentence-transformers)
|
85 |
+
|
86 |
+
### Full Model Architecture
|
87 |
+
|
88 |
+
```
|
89 |
+
SentenceTransformer(
|
90 |
+
(0): Transformer({'max_seq_length': 1024, 'do_lower_case': False}) with Transformer model: RetrievaBertModel
|
91 |
+
(1): Pooling({'word_embedding_dimension': 768, 'pooling_mode_cls_token': False, 'pooling_mode_mean_tokens': True, 'pooling_mode_max_tokens': False, 'pooling_mode_mean_sqrt_len_tokens': False, 'pooling_mode_weightedmean_tokens': False, 'pooling_mode_lasttoken': False, 'include_prompt': True})
|
92 |
+
)
|
93 |
+
```
|
94 |
+
|
95 |
+
## Usage
|
96 |
+
|
97 |
+
### Direct Usage (Sentence Transformers)
|
98 |
+
|
99 |
+
First install the Sentence Transformers library:
|
100 |
+
|
101 |
+
```bash
|
102 |
+
pip install -U sentence-transformers
|
103 |
+
```
|
104 |
+
|
105 |
+
Then you can load this model and run inference.
|
106 |
+
```python
|
107 |
+
from sentence_transformers import SentenceTransformer
|
108 |
+
|
109 |
+
# Download from the 🤗 Hub
|
110 |
+
model = SentenceTransformer("pkshatech/RoSEtta-base")
|
111 |
+
# Run inference
|
112 |
+
sentences = [
|
113 |
+
'The weather is lovely today.',
|
114 |
+
"It's so sunny outside!",
|
115 |
+
'He drove to the stadium.',
|
116 |
+
]
|
117 |
+
embeddings = model.encode(sentences)
|
118 |
+
print(embeddings.shape)
|
119 |
+
# [3, 768]
|
120 |
+
|
121 |
+
# Get the similarity scores for the embeddings
|
122 |
+
similarities = model.similarity(embeddings, embeddings)
|
123 |
+
print(similarities.shape)
|
124 |
+
# [3, 3]
|
125 |
+
```
|
126 |
+
|
127 |
+
<!--
|
128 |
+
### Direct Usage (Transformers)
|
129 |
+
|
130 |
+
<details><summary>Click to see the direct usage in Transformers</summary>
|
131 |
+
|
132 |
+
</details>
|
133 |
+
-->
|
134 |
+
|
135 |
+
<!--
|
136 |
+
### Downstream Usage (Sentence Transformers)
|
137 |
+
|
138 |
+
You can finetune this model on your own dataset.
|
139 |
+
|
140 |
+
<details><summary>Click to expand</summary>
|
141 |
+
|
142 |
+
</details>
|
143 |
+
-->
|
144 |
+
|
145 |
+
<!--
|
146 |
+
### Out-of-Scope Use
|
147 |
+
|
148 |
+
*List how the model may foreseeably be misused and address what users ought not to do with the model.*
|
149 |
+
-->
|
150 |
+
|
151 |
+
## Evaluation
|
152 |
+
|
153 |
+
### Metrics
|
154 |
+
|
155 |
+
#### Semantic Similarity
|
156 |
+
|
157 |
+
* Evaluated with [<code>EmbeddingSimilarityEvaluator</code>](https://sbert.net/docs/package_reference/sentence_transformer/evaluation.html#sentence_transformers.evaluation.EmbeddingSimilarityEvaluator)
|
158 |
+
|
159 |
+
| Metric | Value |
|
160 |
+
|:--------------------|:-----------|
|
161 |
+
| pearson_cosine | 0.8363 |
|
162 |
+
| **spearman_cosine** | **0.7829** |
|
163 |
+
| pearson_manhattan | 0.8169 |
|
164 |
+
| spearman_manhattan | 0.7806 |
|
165 |
+
| pearson_euclidean | 0.8176 |
|
166 |
+
| spearman_euclidean | 0.7813 |
|
167 |
+
| pearson_dot | 0.7906 |
|
168 |
+
| spearman_dot | 0.7341 |
|
169 |
+
| pearson_max | 0.8363 |
|
170 |
+
| spearman_max | 0.7829 |
|
171 |
+
|
172 |
+
<!--
|
173 |
+
## Bias, Risks and Limitations
|
174 |
+
|
175 |
+
*What are the known or foreseeable issues stemming from this model? You could also flag here known failure cases or weaknesses of the model.*
|
176 |
+
-->
|
177 |
+
|
178 |
+
<!--
|
179 |
+
### Recommendations
|
180 |
+
|
181 |
+
*What are recommendations with respect to the foreseeable issues? For example, filtering explicit content.*
|
182 |
+
-->
|
183 |
+
|
184 |
+
## Training Details
|
185 |
+
|
186 |
+
### Training Logs
|
187 |
+
| Epoch | Step | spearman_cosine |
|
188 |
+
|:-----:|:----:|:---------------:|
|
189 |
+
| 0 | 0 | 0.7829 |
|
190 |
+
|
191 |
+
|
192 |
+
### Framework Versions
|
193 |
+
- Python: 3.10.13
|
194 |
+
- Sentence Transformers: 3.0.0
|
195 |
+
- Transformers: 4.44.0
|
196 |
+
- PyTorch: 2.3.1+cu118
|
197 |
+
- Accelerate: 0.30.1
|
198 |
+
- Datasets: 2.19.2
|
199 |
+
- Tokenizers: 0.19.1
|
200 |
+
|
201 |
+
## Citation
|
202 |
+
|
203 |
+
### BibTeX
|
204 |
+
|
205 |
+
<!--
|
206 |
+
## Glossary
|
207 |
+
|
208 |
+
*Clearly define terms in order to be accessible across audiences.*
|
209 |
+
-->
|
210 |
+
|
211 |
+
<!--
|
212 |
+
## Model Card Authors
|
213 |
+
|
214 |
+
*Lists the people who create the model card, providing recognition and accountability for the detailed work that goes into its construction.*
|
215 |
+
-->
|
216 |
+
|
217 |
+
<!--
|
218 |
+
## Model Card Contact
|
219 |
+
|
220 |
+
*Provides a way for people who have updates to the Model Card, suggestions, or questions, to contact the Model Card authors.*
|
221 |
+
-->
|
config.json
ADDED
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"_name_or_path": "/workspace/store/outputs/step3/B2048E3LR3e-05_big-prefix/B2048E3LR3e-05_mir_mr-_jqa_bao_qui_qui_mqa-prefix/93",
|
3 |
+
"architectures": [
|
4 |
+
"RetrievaBertModel"
|
5 |
+
],
|
6 |
+
"attention_probs_dropout_prob": 0.1,
|
7 |
+
"auto_map": {
|
8 |
+
"AutoConfig": "configuration_retrieva_bert.RetrievaBertConfig",
|
9 |
+
"AutoModel": "retrieva_modeling.RetrievaBertModel"
|
10 |
+
},
|
11 |
+
"hidden_act": "silu",
|
12 |
+
"hidden_dropout_prob": 0.1,
|
13 |
+
"hidden_size": 768,
|
14 |
+
"initializer_range": 0.02,
|
15 |
+
"intermediate_size": 3072,
|
16 |
+
"layer_norm_eps": 1e-12,
|
17 |
+
"lm_head_hidden_act": "gelu",
|
18 |
+
"max_position_embeddings": 1024,
|
19 |
+
"mlp_bias": false,
|
20 |
+
"model_type": "retrieva-bert",
|
21 |
+
"num_attention_heads": 12,
|
22 |
+
"num_hidden_layers": 12,
|
23 |
+
"num_key_value_heads": 12,
|
24 |
+
"pad_token_id": 0,
|
25 |
+
"position_embedding_type": "rope",
|
26 |
+
"rope_theta": 10000.0,
|
27 |
+
"rotary_percent": 1.0,
|
28 |
+
"torch_dtype": "float32",
|
29 |
+
"transformers_version": "4.44.0",
|
30 |
+
"type_vocab_size": 0,
|
31 |
+
"use_cache": true,
|
32 |
+
"vocab_size": 99584
|
33 |
+
}
|
config_sentence_transformers.json
ADDED
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"__version__": {
|
3 |
+
"sentence_transformers": "3.0.1",
|
4 |
+
"transformers": "4.44.0",
|
5 |
+
"pytorch": "2.3.1+cu118"
|
6 |
+
},
|
7 |
+
"prompts": {},
|
8 |
+
"default_prompt_name": null,
|
9 |
+
"similarity_fn_name": null
|
10 |
+
}
|
configuration_retrieva_bert.py
ADDED
@@ -0,0 +1,129 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright 2021- NVIDIA Corporation and The HuggingFace Inc. team. All rights reserved.
|
3 |
+
#
|
4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
5 |
+
# you may not use this file except in compliance with the License.
|
6 |
+
# You may obtain a copy of the License at
|
7 |
+
#
|
8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
9 |
+
#
|
10 |
+
# Unless required by applicable law or agreed to in writing, software
|
11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
13 |
+
# See the License for the specific language governing permissions and
|
14 |
+
# limitations under the License.
|
15 |
+
"""RetrievaBERT model configuration"""
|
16 |
+
|
17 |
+
from transformers.configuration_utils import PretrainedConfig
|
18 |
+
from transformers.utils import logging
|
19 |
+
|
20 |
+
|
21 |
+
logger = logging.get_logger(__name__)
|
22 |
+
|
23 |
+
|
24 |
+
class RetrievaBertConfig(PretrainedConfig):
|
25 |
+
r"""
|
26 |
+
This is the configuration class to store the configuration of a [`RetrievaBertModel`]. It is used to instantiate a
|
27 |
+
RETRIEVA_BERT model according to the specified arguments, defining the model architecture. Instantiating a
|
28 |
+
configuration with the defaults will yield a similar configuration to that of the RETRIEVA_BERT
|
29 |
+
[nvidia/megatron-bert-uncased-345m](https://huggingface.co/nvidia/megatron-bert-uncased-345m) architecture.
|
30 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
31 |
+
documentation from [`PretrainedConfig`] for more information.
|
32 |
+
Args:
|
33 |
+
vocab_size (`int`, *optional*, defaults to 29056):
|
34 |
+
Vocabulary size of the RETRIEVA_BERT model. Defines the number of different tokens that can be represented
|
35 |
+
by the `inputs_ids` passed when calling [`RetrievaBertModel`].
|
36 |
+
hidden_size (`int`, *optional*, defaults to 1024):
|
37 |
+
Dimensionality of the encoder layers and the pooler layer.
|
38 |
+
num_hidden_layers (`int`, *optional*, defaults to 24):
|
39 |
+
Number of hidden layers in the Transformer encoder.
|
40 |
+
num_attention_heads (`int`, *optional*, defaults to 16):
|
41 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
42 |
+
intermediate_size (`int`, *optional*, defaults to 4096):
|
43 |
+
Dimensionality of the "intermediate" (often named feed-forward) layer in the Transformer encoder.
|
44 |
+
hidden_act (`str` or `Callable`, *optional*, defaults to `"gelu"`):
|
45 |
+
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
|
46 |
+
`"relu"`, `"silu"` and `"gelu_new"` are supported.
|
47 |
+
hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
|
48 |
+
The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
|
49 |
+
attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):
|
50 |
+
The dropout ratio for the attention probabilities.
|
51 |
+
max_position_embeddings (`int`, *optional*, defaults to 512):
|
52 |
+
The maximum sequence length that this model might ever be used with. Typically set this to something large
|
53 |
+
just in case (e.g., 512 or 1024 or 2048).
|
54 |
+
type_vocab_size (`int`, *optional*, defaults to 2):
|
55 |
+
The vocabulary size of the `token_type_ids` passed when calling [`RetrievaBertModel`].
|
56 |
+
If set 0, `token_type_ids` is not used.
|
57 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
58 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
59 |
+
layer_norm_eps (`float`, *optional*, defaults to 1e-12):
|
60 |
+
The epsilon used by the layer normalization layers.
|
61 |
+
position_embedding_type (`str`, *optional*, defaults to `"absolute"`):
|
62 |
+
Type of position embedding. Choose one of `"absolute"`, `"rope"`. For
|
63 |
+
positional embeddings use `"absolute"`.
|
64 |
+
is_decoder (`bool`, *optional*, defaults to `False`):
|
65 |
+
Whether the model is used as a decoder or not. If `False`, the model is used as an encoder.
|
66 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
67 |
+
Whether or not the model should return the last key/values attentions (not used by all models). Only
|
68 |
+
relevant if `config.is_decoder=True`.
|
69 |
+
Examples:
|
70 |
+
```python
|
71 |
+
>>> from models import RetrievaBertConfig, RetrievaBertModel
|
72 |
+
>>> # Initializing a RETRIEVA_BERT google-bert/bert-base-uncased style configuration
|
73 |
+
>>> configuration = RetrievaBertConfig()
|
74 |
+
>>> # Initializing a model (with random weights) from the google-bert/bert-base-uncased style configuration
|
75 |
+
>>> model = RetrievaBertModel(configuration)
|
76 |
+
>>> # Accessing the model configuration
|
77 |
+
>>> configuration = model.config
|
78 |
+
```"""
|
79 |
+
|
80 |
+
model_type = "retrieva-bert"
|
81 |
+
|
82 |
+
def __init__(
|
83 |
+
self,
|
84 |
+
vocab_size=99584,
|
85 |
+
hidden_size=768,
|
86 |
+
num_hidden_layers=12,
|
87 |
+
num_attention_heads=12,
|
88 |
+
intermediate_size=3072,
|
89 |
+
hidden_act="silu",
|
90 |
+
hidden_dropout_prob=0.1,
|
91 |
+
attention_probs_dropout_prob=0.1,
|
92 |
+
max_position_embeddings=1024,
|
93 |
+
type_vocab_size=0,
|
94 |
+
initializer_range=0.02,
|
95 |
+
layer_norm_eps=1e-12,
|
96 |
+
pad_token_id=0,
|
97 |
+
position_embedding_type="rope",
|
98 |
+
use_cache=True,
|
99 |
+
rope_theta=10000.0,
|
100 |
+
rotary_percent=1.0,
|
101 |
+
mlp_bias=False,
|
102 |
+
num_key_value_heads=None,
|
103 |
+
lm_head_hidden_act="gelu",
|
104 |
+
**kwargs,
|
105 |
+
):
|
106 |
+
super().__init__(pad_token_id=pad_token_id, **kwargs)
|
107 |
+
|
108 |
+
self.vocab_size = vocab_size
|
109 |
+
self.hidden_size = hidden_size
|
110 |
+
self.num_hidden_layers = num_hidden_layers
|
111 |
+
self.num_attention_heads = num_attention_heads
|
112 |
+
self.hidden_act = hidden_act
|
113 |
+
self.intermediate_size = intermediate_size
|
114 |
+
self.hidden_dropout_prob = hidden_dropout_prob
|
115 |
+
self.attention_probs_dropout_prob = attention_probs_dropout_prob
|
116 |
+
self.max_position_embeddings = max_position_embeddings
|
117 |
+
self.type_vocab_size = type_vocab_size
|
118 |
+
self.initializer_range = initializer_range
|
119 |
+
self.layer_norm_eps = layer_norm_eps
|
120 |
+
self.position_embedding_type = position_embedding_type
|
121 |
+
self.use_cache = use_cache
|
122 |
+
self.rope_theta = rope_theta
|
123 |
+
self.rotary_percent = rotary_percent
|
124 |
+
self.mlp_bias = mlp_bias
|
125 |
+
|
126 |
+
if num_key_value_heads is None:
|
127 |
+
num_key_value_heads = num_attention_heads
|
128 |
+
self.num_key_value_heads = num_key_value_heads
|
129 |
+
self.lm_head_hidden_act = lm_head_hidden_act
|
model.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:f2e0232fa4ea89bb96d318292133c725d7ab0616843bbbc8cb351cc37c64a282
|
3 |
+
size 761590704
|
modules.json
ADDED
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
[
|
2 |
+
{
|
3 |
+
"idx": 0,
|
4 |
+
"name": "0",
|
5 |
+
"path": "",
|
6 |
+
"type": "sentence_transformers.models.Transformer"
|
7 |
+
},
|
8 |
+
{
|
9 |
+
"idx": 1,
|
10 |
+
"name": "1",
|
11 |
+
"path": "1_Pooling",
|
12 |
+
"type": "sentence_transformers.models.Pooling"
|
13 |
+
}
|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google AI Language Team Authors and The HuggingFace Inc. team.
|
3 |
+
# Copyright (c) 2018-2021, NVIDIA CORPORATION. All rights reserved.
|
4 |
+
#
|
5 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
6 |
+
# you may not use this file except in compliance with the License.
|
7 |
+
# You may obtain a copy of the License at
|
8 |
+
#
|
9 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
10 |
+
#
|
11 |
+
# Unless required by applicable law or agreed to in writing, software
|
12 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
13 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
14 |
+
# See the License for the specific language governing permissions and
|
15 |
+
# limitations under the License.
|
16 |
+
"""PyTorch RetrievaBERT model.
|
17 |
+
The follwoing are the differences of the original huffingface/MegatronBERT model.
|
18 |
+
- Use RoPE instead of absolute position embeddings.
|
19 |
+
- Use Grouped Query Attention (GQA) instead of the standard self-attention.
|
20 |
+
- Use Swiglu activation function instead of GELU.
|
21 |
+
RoPE implementation is based on the huggingface's Llama and RoFormer model.
|
22 |
+
GQA/Swiglu implementation is based on the Llama model.
|
23 |
+
https://github.com/huggingface/transformers/blob/main/src/transformers/models/llama/modeling_llama.py
|
24 |
+
https://github.com/huggingface/transformers/blob/main/src/transformers/models/roformer/modeling_roformer.py
|
25 |
+
"""
|
26 |
+
|
27 |
+
import math
|
28 |
+
import os
|
29 |
+
import warnings
|
30 |
+
from dataclasses import dataclass
|
31 |
+
from typing import Optional, Tuple, Union
|
32 |
+
|
33 |
+
import torch
|
34 |
+
import torch.utils.checkpoint
|
35 |
+
from torch import nn
|
36 |
+
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
|
37 |
+
|
38 |
+
from transformers.activations import ACT2FN
|
39 |
+
from transformers.modeling_outputs import (
|
40 |
+
BaseModelOutputWithPastAndCrossAttentions,
|
41 |
+
BaseModelOutputWithPoolingAndCrossAttentions,
|
42 |
+
CausalLMOutputWithCrossAttentions,
|
43 |
+
MaskedLMOutput,
|
44 |
+
MultipleChoiceModelOutput,
|
45 |
+
NextSentencePredictorOutput,
|
46 |
+
QuestionAnsweringModelOutput,
|
47 |
+
SequenceClassifierOutput,
|
48 |
+
TokenClassifierOutput,
|
49 |
+
)
|
50 |
+
from transformers.modeling_utils import PreTrainedModel
|
51 |
+
from transformers.pytorch_utils import apply_chunking_to_forward, find_pruneable_heads_and_indices, prune_linear_layer
|
52 |
+
from transformers.utils import (
|
53 |
+
ModelOutput,
|
54 |
+
add_code_sample_docstrings,
|
55 |
+
add_start_docstrings,
|
56 |
+
add_start_docstrings_to_model_forward,
|
57 |
+
logging,
|
58 |
+
replace_return_docstrings,
|
59 |
+
)
|
60 |
+
from .configuration_retrieva_bert import RetrievaBertConfig
|
61 |
+
|
62 |
+
|
63 |
+
logger = logging.get_logger(__name__)
|
64 |
+
|
65 |
+
_CONFIG_FOR_DOC = "RetrievaBertConfig"
|
66 |
+
_CHECKPOINT_FOR_DOC = "retrieva-jp/bert-1.3b"
|
67 |
+
|
68 |
+
|
69 |
+
def load_tf_weights_in_megatron_bert(model, config, tf_checkpoint_path):
|
70 |
+
"""Load tf checkpoints in a pytorch model."""
|
71 |
+
try:
|
72 |
+
import re
|
73 |
+
|
74 |
+
import numpy as np
|
75 |
+
import tensorflow as tf
|
76 |
+
except ImportError:
|
77 |
+
logger.error(
|
78 |
+
"Loading a TensorFlow model in PyTorch, requires TensorFlow to be installed. Please see "
|
79 |
+
"https://www.tensorflow.org/install/ for installation instructions."
|
80 |
+
)
|
81 |
+
raise
|
82 |
+
tf_path = os.path.abspath(tf_checkpoint_path)
|
83 |
+
logger.info("Converting TensorFlow checkpoint from {}".format(tf_path))
|
84 |
+
# Load weights from TF model
|
85 |
+
init_vars = tf.train.list_variables(tf_path)
|
86 |
+
names = []
|
87 |
+
arrays = []
|
88 |
+
for name, shape in init_vars:
|
89 |
+
logger.info(f"Loading TF weight {name} with shape {shape}")
|
90 |
+
array = tf.train.load_variable(tf_path, name)
|
91 |
+
names.append(name)
|
92 |
+
arrays.append(array)
|
93 |
+
|
94 |
+
for name, array in zip(names, arrays):
|
95 |
+
name = name.split("/")
|
96 |
+
# adam_v and adam_m are variables used in AdamWeightDecayOptimizer to calculated m and v
|
97 |
+
# which are not required for using pretrained model
|
98 |
+
if any(n in ["adam_v", "adam_m", "AdamWeightDecayOptimizer", "AdamWeightDecayOptimizer_1", "global_step"] for n in name):
|
99 |
+
logger.info(f"Skipping {'/'.join(name)}")
|
100 |
+
continue
|
101 |
+
pointer = model
|
102 |
+
for m_name in name:
|
103 |
+
if re.fullmatch(r"[A-Za-z]+_\d+", m_name):
|
104 |
+
scope_names = re.split(r"_(\d+)", m_name)
|
105 |
+
else:
|
106 |
+
scope_names = [m_name]
|
107 |
+
if scope_names[0] == "kernel" or scope_names[0] == "gamma":
|
108 |
+
pointer = getattr(pointer, "weight")
|
109 |
+
elif scope_names[0] == "output_bias" or scope_names[0] == "beta":
|
110 |
+
pointer = getattr(pointer, "bias")
|
111 |
+
elif scope_names[0] == "output_weights":
|
112 |
+
pointer = getattr(pointer, "weight")
|
113 |
+
elif scope_names[0] == "squad":
|
114 |
+
pointer = getattr(pointer, "classifier")
|
115 |
+
else:
|
116 |
+
try:
|
117 |
+
pointer = getattr(pointer, scope_names[0])
|
118 |
+
except AttributeError:
|
119 |
+
logger.info(f"Skipping {'/'.join(name)}")
|
120 |
+
continue
|
121 |
+
if len(scope_names) >= 2:
|
122 |
+
num = int(scope_names[1])
|
123 |
+
pointer = pointer[num]
|
124 |
+
if m_name[-11:] == "_embeddings":
|
125 |
+
pointer = getattr(pointer, "weight")
|
126 |
+
elif m_name == "kernel":
|
127 |
+
array = np.transpose(array)
|
128 |
+
if pointer.shape != array.shape:
|
129 |
+
raise ValueError(f"Pointer shape {pointer.shape} and array shape {array.shape} mismatched")
|
130 |
+
logger.info("Initialize PyTorch weight {}".format(name))
|
131 |
+
pointer.data = torch.from_numpy(array)
|
132 |
+
return model
|
133 |
+
|
134 |
+
|
135 |
+
class RotaryEmbedding(nn.Module):
|
136 |
+
"""Rotary Embedding for positional encoding."""
|
137 |
+
|
138 |
+
def __init__(self, hidden_size, max_position_embeddings, theta, rotary_percent=1.0, device=None):
|
139 |
+
super().__init__()
|
140 |
+
if rotary_percent < 1.0:
|
141 |
+
hidden_size = int(hidden_size * rotary_percent)
|
142 |
+
self.hidden_size = hidden_size
|
143 |
+
self.max_position_embeddings = max_position_embeddings
|
144 |
+
self.theta = theta
|
145 |
+
inv_freq = 1.0 / (self.theta ** (torch.arange(0, hidden_size, 2, dtype=torch.int64).float().to(device) / hidden_size))
|
146 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
147 |
+
|
148 |
+
def forward(self, x, position_ids):
|
149 |
+
# x: [batch_size, num_attention_heads, seq_len, hidden_size]
|
150 |
+
inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
|
151 |
+
position_ids_expanded = position_ids[:, None, :].float()
|
152 |
+
device_type = x.device.type
|
153 |
+
device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
|
154 |
+
with torch.autocast(device_type=device_type, enabled=False):
|
155 |
+
freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
|
156 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
157 |
+
cos = emb.cos()
|
158 |
+
sin = emb.sin()
|
159 |
+
return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
|
160 |
+
|
161 |
+
|
162 |
+
def rotate_half(x):
|
163 |
+
"""Rotates half the hidden dims of the input."""
|
164 |
+
x1 = x[..., : x.shape[-1] // 2]
|
165 |
+
x2 = x[..., x.shape[-1] // 2 :]
|
166 |
+
return torch.cat((-x2, x1), dim=-1)
|
167 |
+
|
168 |
+
|
169 |
+
def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
|
170 |
+
"""Applies Rotary Position Embedding to the query and key tensors.
|
171 |
+
Args:
|
172 |
+
q (`torch.Tensor`): The query tensor.
|
173 |
+
k (`torch.Tensor`): The key tensor.
|
174 |
+
cos (`torch.Tensor`): The cosine part of the rotary embedding.
|
175 |
+
sin (`torch.Tensor`): The sine part of the rotary embedding.
|
176 |
+
position_ids (`torch.Tensor`, *optional*):
|
177 |
+
Deprecated and unused.
|
178 |
+
unsqueeze_dim (`int`, *optional*, defaults to 1):
|
179 |
+
The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
|
180 |
+
sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
|
181 |
+
that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
|
182 |
+
k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
|
183 |
+
cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
|
184 |
+
the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
|
185 |
+
Returns:
|
186 |
+
`tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
|
187 |
+
"""
|
188 |
+
cos = cos.unsqueeze(unsqueeze_dim)
|
189 |
+
sin = sin.unsqueeze(unsqueeze_dim)
|
190 |
+
q_embed = (q * cos) + (rotate_half(q) * sin)
|
191 |
+
k_embed = (k * cos) + (rotate_half(k) * sin)
|
192 |
+
return q_embed, k_embed
|
193 |
+
|
194 |
+
|
195 |
+
class RetrievaBertEmbeddings(nn.Module):
|
196 |
+
"""Construct the embeddings from word, position and token_type embeddings."""
|
197 |
+
|
198 |
+
def __init__(self, config):
|
199 |
+
super().__init__()
|
200 |
+
self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id)
|
201 |
+
if config.position_embedding_type == "absolute":
|
202 |
+
self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size)
|
203 |
+
else:
|
204 |
+
self.position_embeddings = None
|
205 |
+
if config.type_vocab_size > 0:
|
206 |
+
self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)
|
207 |
+
else:
|
208 |
+
self.token_type_embeddings = None
|
209 |
+
|
210 |
+
# self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load
|
211 |
+
# any TensorFlow checkpoint file
|
212 |
+
|
213 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
214 |
+
|
215 |
+
self.register_buffer("position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False)
|
216 |
+
self.position_embedding_type = getattr(config, "position_embedding_type", "absolute")
|
217 |
+
|
218 |
+
def forward(
|
219 |
+
self,
|
220 |
+
input_ids: Optional[torch.LongTensor] = None,
|
221 |
+
token_type_ids: Optional[torch.LongTensor] = None,
|
222 |
+
position_ids: Optional[torch.LongTensor] = None,
|
223 |
+
inputs_embeds: Optional[torch.LongTensor] = None,
|
224 |
+
past_key_values_length: int = 0,
|
225 |
+
) -> torch.Tensor:
|
226 |
+
if input_ids is not None:
|
227 |
+
input_shape = input_ids.size()
|
228 |
+
else:
|
229 |
+
input_shape = inputs_embeds.size()[:-1]
|
230 |
+
|
231 |
+
if inputs_embeds is None:
|
232 |
+
inputs_embeds = self.word_embeddings(input_ids)
|
233 |
+
|
234 |
+
if self.position_embeddings is not None:
|
235 |
+
if position_ids is None:
|
236 |
+
position_ids = self.position_ids[:, past_key_values_length : past_key_values_length + input_shape[1]]
|
237 |
+
position_embeddings = self.position_embeddings(position_ids)
|
238 |
+
else:
|
239 |
+
position_embeddings = None
|
240 |
+
|
241 |
+
if self.token_type_embeddings is not None:
|
242 |
+
if token_type_ids is None:
|
243 |
+
token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)
|
244 |
+
|
245 |
+
token_type_embeddings = self.token_type_embeddings(token_type_ids)
|
246 |
+
else:
|
247 |
+
token_type_embeddings = None
|
248 |
+
|
249 |
+
if position_embeddings is not None and token_type_embeddings is not None:
|
250 |
+
embeddings = inputs_embeds + position_embeddings + token_type_embeddings
|
251 |
+
elif position_embeddings is not None:
|
252 |
+
embeddings = inputs_embeds + position_embeddings
|
253 |
+
elif token_type_embeddings is not None:
|
254 |
+
embeddings = inputs_embeds + token_type_embeddings
|
255 |
+
else:
|
256 |
+
embeddings = inputs_embeds
|
257 |
+
|
258 |
+
embeddings = self.dropout(embeddings)
|
259 |
+
return embeddings
|
260 |
+
|
261 |
+
|
262 |
+
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
|
263 |
+
"""Repeat key/value weigts for GQA.
|
264 |
+
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
|
265 |
+
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
|
266 |
+
"""
|
267 |
+
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
|
268 |
+
if n_rep == 1:
|
269 |
+
return hidden_states
|
270 |
+
hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
|
271 |
+
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
|
272 |
+
|
273 |
+
|
274 |
+
# Copied from transformers.models.bert.modeling_bert.BertSelfAttention with Bert->MegatronBert->RetrievaBert
|
275 |
+
class RetrievaBertSelfAttention(nn.Module):
|
276 |
+
def __init__(self, config, position_embedding_type=None):
|
277 |
+
super().__init__()
|
278 |
+
if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
|
279 |
+
raise ValueError(
|
280 |
+
f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention " f"heads ({config.num_attention_heads})"
|
281 |
+
)
|
282 |
+
|
283 |
+
self.num_attention_heads = config.num_attention_heads
|
284 |
+
self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
|
285 |
+
self.all_head_size = self.num_attention_heads * self.attention_head_size
|
286 |
+
|
287 |
+
self.num_key_value_heads = config.num_key_value_heads
|
288 |
+
self.num_key_value_groups = self.num_attention_heads // self.num_key_value_heads
|
289 |
+
|
290 |
+
self.query = nn.Linear(config.hidden_size, self.all_head_size)
|
291 |
+
self.key = nn.Linear(config.hidden_size, self.num_key_value_heads * self.attention_head_size)
|
292 |
+
self.value = nn.Linear(config.hidden_size, self.num_key_value_heads * self.attention_head_size)
|
293 |
+
|
294 |
+
self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
|
295 |
+
|
296 |
+
if config.position_embedding_type == "rope":
|
297 |
+
self.rope_theta = config.rope_theta
|
298 |
+
self.rope_emb = RotaryEmbedding(self.attention_head_size, config.max_position_embeddings, self.rope_theta, config.rotary_percent)
|
299 |
+
else:
|
300 |
+
self.rope_theta = None
|
301 |
+
self.rope_emb = None
|
302 |
+
|
303 |
+
self.is_decoder = config.is_decoder
|
304 |
+
|
305 |
+
def transpose_for_scores(self, x: torch.Tensor, is_query: bool) -> torch.Tensor:
|
306 |
+
if is_query:
|
307 |
+
new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
|
308 |
+
else:
|
309 |
+
new_x_shape = x.size()[:-1] + (self.num_key_value_heads, self.attention_head_size)
|
310 |
+
x = x.view(new_x_shape)
|
311 |
+
return x.permute(0, 2, 1, 3)
|
312 |
+
|
313 |
+
def forward(
|
314 |
+
self,
|
315 |
+
hidden_states: torch.Tensor,
|
316 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
317 |
+
position_ids: Optional[torch.LongTensor] = None,
|
318 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
319 |
+
encoder_hidden_states: Optional[torch.FloatTensor] = None,
|
320 |
+
encoder_attention_mask: Optional[torch.FloatTensor] = None,
|
321 |
+
past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
|
322 |
+
output_attentions: Optional[bool] = False,
|
323 |
+
) -> Tuple[torch.Tensor]:
|
324 |
+
mixed_query_layer = self.query(hidden_states)
|
325 |
+
query_layer = self.transpose_for_scores(mixed_query_layer, is_query=True)
|
326 |
+
|
327 |
+
# If this is instantiated as a cross-attention module, the keys
|
328 |
+
# and values come from an encoder; the attention mask needs to be
|
329 |
+
# such that the encoder's padding tokens are not attended to.
|
330 |
+
is_cross_attention = encoder_hidden_states is not None
|
331 |
+
|
332 |
+
if is_cross_attention and past_key_value is not None:
|
333 |
+
# reuse k,v, cross_attentions
|
334 |
+
key_layer = past_key_value[0]
|
335 |
+
value_layer = past_key_value[1]
|
336 |
+
attention_mask = encoder_attention_mask
|
337 |
+
elif is_cross_attention:
|
338 |
+
key_layer = self.transpose_for_scores(self.key(encoder_hidden_states), is_query=False)
|
339 |
+
value_layer = self.transpose_for_scores(self.value(encoder_hidden_states), is_query=False)
|
340 |
+
attention_mask = encoder_attention_mask
|
341 |
+
else:
|
342 |
+
# https://github.com/huggingface/transformers/blob/main/src/transformers/models/roformer/modeling_roformer.py#L254-L265
|
343 |
+
key_layer = self.transpose_for_scores(self.key(hidden_states), is_query=False)
|
344 |
+
value_layer = self.transpose_for_scores(self.value(hidden_states), is_query=False)
|
345 |
+
|
346 |
+
# https://github.com/huggingface/transformers/blob/main/src/transformers/models/llama/modeling_llama.py#L335-L336
|
347 |
+
if self.rope_emb is not None:
|
348 |
+
cos, sin = self.rope_emb(hidden_states, position_ids)
|
349 |
+
query_layer, key_layer = apply_rotary_pos_emb(query_layer, key_layer, cos, sin)
|
350 |
+
|
351 |
+
if past_key_value is not None:
|
352 |
+
key_layer = torch.cat([past_key_value[0], key_layer], dim=2)
|
353 |
+
value_layer = torch.cat([past_key_value[1], value_layer], dim=2)
|
354 |
+
|
355 |
+
# For GQA, we repeat the key/value weights.
|
356 |
+
key_layer = repeat_kv(key_layer, self.num_key_value_groups)
|
357 |
+
value_layer = repeat_kv(value_layer, self.num_key_value_groups)
|
358 |
+
|
359 |
+
if self.is_decoder:
|
360 |
+
# if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states.
|
361 |
+
# Further calls to cross_attention layer can then reuse all cross-attention
|
362 |
+
# key/value_states (first "if" case)
|
363 |
+
# if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of
|
364 |
+
# all previous decoder key/value_states. Further calls to uni-directional self-attention
|
365 |
+
# can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
|
366 |
+
# if encoder bi-directional self-attention `past_key_value` is always `None`
|
367 |
+
past_key_value = (key_layer, value_layer)
|
368 |
+
|
369 |
+
# Take the dot product between "query" and "key" to get the raw attention scores.
|
370 |
+
attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
|
371 |
+
|
372 |
+
attention_scores = attention_scores / math.sqrt(self.attention_head_size)
|
373 |
+
if attention_mask is not None:
|
374 |
+
# Apply the attention mask is (precomputed for all layers in RetrievaBertModel forward() function)
|
375 |
+
attention_scores = attention_scores + attention_mask
|
376 |
+
|
377 |
+
# Normalize the attention scores to probabilities.
|
378 |
+
attention_probs = nn.functional.softmax(attention_scores, dim=-1)
|
379 |
+
|
380 |
+
# This is actually dropping out entire tokens to attend to, which might
|
381 |
+
# seem a bit unusual, but is taken from the original Transformer paper.
|
382 |
+
attention_probs = self.dropout(attention_probs)
|
383 |
+
|
384 |
+
# Mask heads if we want to
|
385 |
+
if head_mask is not None:
|
386 |
+
attention_probs = attention_probs * head_mask
|
387 |
+
|
388 |
+
context_layer = torch.matmul(attention_probs, value_layer)
|
389 |
+
|
390 |
+
context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
|
391 |
+
new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
|
392 |
+
context_layer = context_layer.view(new_context_layer_shape)
|
393 |
+
|
394 |
+
outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
|
395 |
+
|
396 |
+
if self.is_decoder:
|
397 |
+
outputs = outputs + (past_key_value,)
|
398 |
+
return outputs
|
399 |
+
|
400 |
+
|
401 |
+
# Based transformers.models.bert.modeling_bert.BertSelfOutput. Moved LayerNorm to RetrievaBertAttention below.
|
402 |
+
class RetrievaBertSelfOutput(nn.Module):
|
403 |
+
def __init__(self, config):
|
404 |
+
super().__init__()
|
405 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
406 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
407 |
+
|
408 |
+
def forward(self, hidden_states: torch.Tensor, residual: torch.Tensor) -> torch.Tensor:
|
409 |
+
hidden_states = self.dense(hidden_states)
|
410 |
+
hidden_states = self.dropout(hidden_states)
|
411 |
+
return residual + hidden_states
|
412 |
+
|
413 |
+
|
414 |
+
# Based transformers.models.bert.modeling_bert.BertAttention. Added LayerNorm.
|
415 |
+
class RetrievaBertAttention(nn.Module):
|
416 |
+
def __init__(self, config):
|
417 |
+
super().__init__()
|
418 |
+
self.ln = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
419 |
+
self.self = RetrievaBertSelfAttention(config)
|
420 |
+
self.output = RetrievaBertSelfOutput(config)
|
421 |
+
self.pruned_heads = set()
|
422 |
+
|
423 |
+
def prune_heads(self, heads):
|
424 |
+
if len(heads) == 0:
|
425 |
+
return
|
426 |
+
heads, index = find_pruneable_heads_and_indices(heads, self.self.num_attention_heads, self.self.attention_head_size, self.pruned_heads)
|
427 |
+
|
428 |
+
# Prune linear layers
|
429 |
+
self.self.query = prune_linear_layer(self.self.query, index)
|
430 |
+
self.self.key = prune_linear_layer(self.self.key, index)
|
431 |
+
self.self.value = prune_linear_layer(self.self.value, index)
|
432 |
+
self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
|
433 |
+
|
434 |
+
# Update hyper params and store pruned heads
|
435 |
+
self.self.num_attention_heads = self.self.num_attention_heads - len(heads)
|
436 |
+
self.self.all_head_size = self.self.attention_head_size * self.self.num_attention_heads
|
437 |
+
self.pruned_heads = self.pruned_heads.union(heads)
|
438 |
+
|
439 |
+
def forward(
|
440 |
+
self,
|
441 |
+
hidden_states: torch.Tensor,
|
442 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
443 |
+
position_ids: Optional[torch.LongTensor] = None,
|
444 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
445 |
+
encoder_hidden_states: Optional[torch.FloatTensor] = None,
|
446 |
+
encoder_attention_mask: Optional[torch.FloatTensor] = None,
|
447 |
+
past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
|
448 |
+
output_attentions: Optional[bool] = False,
|
449 |
+
) -> Tuple[torch.Tensor]:
|
450 |
+
ln_outputs = self.ln(hidden_states)
|
451 |
+
self_outputs = self.self(
|
452 |
+
ln_outputs,
|
453 |
+
attention_mask,
|
454 |
+
position_ids,
|
455 |
+
head_mask,
|
456 |
+
encoder_hidden_states,
|
457 |
+
encoder_attention_mask,
|
458 |
+
past_key_value,
|
459 |
+
output_attentions,
|
460 |
+
)
|
461 |
+
attention_output = self.output(self_outputs[0], hidden_states)
|
462 |
+
outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
|
463 |
+
return outputs
|
464 |
+
|
465 |
+
|
466 |
+
# Copied from transformers.models.bert.modeling_bert.BertIntermediate with Bert->MegatronBert->RetrievaBert
|
467 |
+
class RetrievaBertIntermediate(nn.Module):
|
468 |
+
def __init__(self, config):
|
469 |
+
super().__init__()
|
470 |
+
self.gate_proj = nn.Linear(config.hidden_size, config.intermediate_size, bias=config.mlp_bias)
|
471 |
+
self.up_proj = nn.Linear(config.hidden_size, config.intermediate_size, bias=config.mlp_bias)
|
472 |
+
if isinstance(config.hidden_act, str):
|
473 |
+
self.intermediate_act_fn = ACT2FN[config.hidden_act]
|
474 |
+
else:
|
475 |
+
self.intermediate_act_fn = config.hidden_act
|
476 |
+
|
477 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
478 |
+
gate_hidden_states = self.gate_proj(hidden_states)
|
479 |
+
gate_hidden_states = self.intermediate_act_fn(gate_hidden_states)
|
480 |
+
up_hidden_state = self.up_proj(hidden_states)
|
481 |
+
hidden_states = gate_hidden_states * up_hidden_state
|
482 |
+
return hidden_states
|
483 |
+
|
484 |
+
|
485 |
+
# Based on transformers.models.bert.modeling_bert.BertOutput. Moved LayerNorm to RetrievaBertLayer below.
|
486 |
+
class RetrievaBertOutput(nn.Module):
|
487 |
+
def __init__(self, config):
|
488 |
+
super().__init__()
|
489 |
+
self.dense = nn.Linear(config.intermediate_size, config.hidden_size, bias=config.mlp_bias) # down_proj
|
490 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
491 |
+
|
492 |
+
def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
|
493 |
+
hidden_states = self.dense(hidden_states)
|
494 |
+
hidden_states = self.dropout(hidden_states)
|
495 |
+
return input_tensor + hidden_states
|
496 |
+
|
497 |
+
|
498 |
+
# Based on transformers.models.bert.modeling_bert.BertLayer. Added LayerNorm.
|
499 |
+
class RetrievaBertLayer(nn.Module):
|
500 |
+
def __init__(self, config):
|
501 |
+
super().__init__()
|
502 |
+
self.chunk_size_feed_forward = config.chunk_size_feed_forward
|
503 |
+
self.seq_len_dim = 1
|
504 |
+
self.attention = RetrievaBertAttention(config)
|
505 |
+
self.is_decoder = config.is_decoder
|
506 |
+
self.add_cross_attention = config.add_cross_attention
|
507 |
+
if self.add_cross_attention:
|
508 |
+
if not self.is_decoder:
|
509 |
+
raise TypeError(f"{self} should be used as a decoder model if cross attention is added")
|
510 |
+
self.crossattention = RetrievaBertAttention(config)
|
511 |
+
self.ln = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
512 |
+
self.intermediate = RetrievaBertIntermediate(config)
|
513 |
+
self.output = RetrievaBertOutput(config)
|
514 |
+
|
515 |
+
def forward(
|
516 |
+
self,
|
517 |
+
hidden_states: torch.Tensor,
|
518 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
519 |
+
position_ids: Optional[torch.LongTensor] = None,
|
520 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
521 |
+
encoder_hidden_states: Optional[torch.FloatTensor] = None,
|
522 |
+
encoder_attention_mask: Optional[torch.FloatTensor] = None,
|
523 |
+
past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
|
524 |
+
output_attentions: Optional[bool] = False,
|
525 |
+
) -> Tuple[torch.Tensor]:
|
526 |
+
# decoder uni-directional self-attention cached key/values tuple is at positions 1,2
|
527 |
+
self_attn_past_key_value = past_key_value[:2] if past_key_value is not None else None
|
528 |
+
self_attention_outputs = self.attention(
|
529 |
+
hidden_states,
|
530 |
+
attention_mask,
|
531 |
+
position_ids,
|
532 |
+
head_mask,
|
533 |
+
output_attentions=output_attentions,
|
534 |
+
past_key_value=self_attn_past_key_value,
|
535 |
+
)
|
536 |
+
attention_output = self_attention_outputs[0]
|
537 |
+
|
538 |
+
# if decoder, the last output is tuple of self-attn cache
|
539 |
+
if self.is_decoder:
|
540 |
+
outputs = self_attention_outputs[1:-1]
|
541 |
+
present_key_value = self_attention_outputs[-1]
|
542 |
+
else:
|
543 |
+
outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
|
544 |
+
|
545 |
+
cross_attn_present_key_value = None
|
546 |
+
if self.is_decoder and encoder_hidden_states is not None:
|
547 |
+
if not hasattr(self, "crossattention"):
|
548 |
+
raise AttributeError(
|
549 |
+
f"If `encoder_hidden_states` are passed, {self} has to be instantiated with cross-attention layers"
|
550 |
+
" by setting `config.add_cross_attention=True`"
|
551 |
+
)
|
552 |
+
|
553 |
+
# cross_attn cached key/values tuple is at positions 3,4 of past_key_value tuple
|
554 |
+
cross_attn_past_key_value = past_key_value[-2:] if past_key_value is not None else None
|
555 |
+
cross_attention_outputs = self.crossattention(
|
556 |
+
attention_output,
|
557 |
+
attention_mask,
|
558 |
+
position_ids,
|
559 |
+
head_mask,
|
560 |
+
encoder_hidden_states,
|
561 |
+
encoder_attention_mask,
|
562 |
+
cross_attn_past_key_value,
|
563 |
+
output_attentions,
|
564 |
+
)
|
565 |
+
attention_output = cross_attention_outputs[0]
|
566 |
+
outputs = outputs + cross_attention_outputs[1:-1] # add cross attentions if we output attention weights
|
567 |
+
|
568 |
+
# add cross-attn cache to positions 3,4 of present_key_value tuple
|
569 |
+
cross_attn_present_key_value = cross_attention_outputs[-1]
|
570 |
+
present_key_value = present_key_value + cross_attn_present_key_value
|
571 |
+
|
572 |
+
layer_output = apply_chunking_to_forward(self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, attention_output)
|
573 |
+
outputs = (layer_output,) + outputs
|
574 |
+
|
575 |
+
# if decoder, return the attn key/values as the last output
|
576 |
+
if self.is_decoder:
|
577 |
+
outputs = outputs + (present_key_value,)
|
578 |
+
|
579 |
+
return outputs
|
580 |
+
|
581 |
+
def feed_forward_chunk(self, attention_output):
|
582 |
+
ln_output = self.ln(attention_output)
|
583 |
+
intermediate_output = self.intermediate(ln_output)
|
584 |
+
layer_output = self.output(intermediate_output, attention_output)
|
585 |
+
return layer_output
|
586 |
+
|
587 |
+
|
588 |
+
class RetrievaBertEncoder(nn.Module):
|
589 |
+
def __init__(self, config):
|
590 |
+
super().__init__()
|
591 |
+
self.config = config
|
592 |
+
self.layer = nn.ModuleList([RetrievaBertLayer(config) for _ in range(config.num_hidden_layers)])
|
593 |
+
|
594 |
+
# The final layer norm. We removed the 1st LN, moved LN to each hidden layer and this one
|
595 |
+
# is simply the final LN (Transformer's BERT has it attached to each hidden layer).
|
596 |
+
self.ln = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) # final_layernorm
|
597 |
+
self.gradient_checkpointing = False
|
598 |
+
|
599 |
+
def forward(
|
600 |
+
self,
|
601 |
+
hidden_states: torch.Tensor,
|
602 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
603 |
+
position_ids: Optional[torch.LongTensor] = None,
|
604 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
605 |
+
encoder_hidden_states: Optional[torch.FloatTensor] = None,
|
606 |
+
encoder_attention_mask: Optional[torch.FloatTensor] = None,
|
607 |
+
past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
|
608 |
+
use_cache: Optional[bool] = None,
|
609 |
+
output_attentions: Optional[bool] = False,
|
610 |
+
output_hidden_states: Optional[bool] = False,
|
611 |
+
return_dict: Optional[bool] = True,
|
612 |
+
) -> Union[Tuple, BaseModelOutputWithPastAndCrossAttentions]:
|
613 |
+
if self.gradient_checkpointing and self.training:
|
614 |
+
if use_cache:
|
615 |
+
logger.warning_once("`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...")
|
616 |
+
use_cache = False
|
617 |
+
all_hidden_states = () if output_hidden_states else None
|
618 |
+
all_self_attentions = () if output_attentions else None
|
619 |
+
all_cross_attentions = () if output_attentions and self.config.add_cross_attention else None
|
620 |
+
|
621 |
+
next_decoder_cache = () if use_cache else None
|
622 |
+
for i, layer_module in enumerate(self.layer):
|
623 |
+
if output_hidden_states:
|
624 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
625 |
+
|
626 |
+
layer_head_mask = head_mask[i] if head_mask is not None else None
|
627 |
+
past_key_value = past_key_values[i] if past_key_values is not None else None
|
628 |
+
|
629 |
+
if self.gradient_checkpointing and self.training:
|
630 |
+
layer_outputs = self._gradient_checkpointing_func(
|
631 |
+
layer_module.__call__,
|
632 |
+
hidden_states,
|
633 |
+
attention_mask,
|
634 |
+
position_ids,
|
635 |
+
layer_head_mask,
|
636 |
+
encoder_hidden_states,
|
637 |
+
encoder_attention_mask,
|
638 |
+
past_key_value,
|
639 |
+
output_attentions,
|
640 |
+
)
|
641 |
+
else:
|
642 |
+
layer_outputs = layer_module(
|
643 |
+
hidden_states,
|
644 |
+
attention_mask,
|
645 |
+
position_ids,
|
646 |
+
layer_head_mask,
|
647 |
+
encoder_hidden_states,
|
648 |
+
encoder_attention_mask,
|
649 |
+
past_key_value,
|
650 |
+
output_attentions,
|
651 |
+
)
|
652 |
+
|
653 |
+
# Because we moved the layer-norm at the end of the hidden layer, we have non-normali-
|
654 |
+
# zed data here. If that's really needed, we must apply LN to match Transformer's BERT.
|
655 |
+
|
656 |
+
hidden_states = layer_outputs[0]
|
657 |
+
if use_cache:
|
658 |
+
next_decoder_cache += (layer_outputs[-1],)
|
659 |
+
if output_attentions:
|
660 |
+
all_self_attentions = all_self_attentions + (layer_outputs[1],)
|
661 |
+
if self.config.add_cross_attention:
|
662 |
+
all_cross_attentions = all_cross_attentions + (layer_outputs[2],)
|
663 |
+
|
664 |
+
# Finalize the hidden states.
|
665 |
+
hidden_states = self.ln(hidden_states)
|
666 |
+
|
667 |
+
if output_hidden_states:
|
668 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
669 |
+
|
670 |
+
if not return_dict:
|
671 |
+
return tuple(
|
672 |
+
v
|
673 |
+
for v in [
|
674 |
+
hidden_states,
|
675 |
+
next_decoder_cache,
|
676 |
+
all_hidden_states,
|
677 |
+
all_self_attentions,
|
678 |
+
all_cross_attentions,
|
679 |
+
]
|
680 |
+
if v is not None
|
681 |
+
)
|
682 |
+
return BaseModelOutputWithPastAndCrossAttentions(
|
683 |
+
last_hidden_state=hidden_states,
|
684 |
+
past_key_values=next_decoder_cache,
|
685 |
+
hidden_states=all_hidden_states,
|
686 |
+
attentions=all_self_attentions,
|
687 |
+
cross_attentions=all_cross_attentions,
|
688 |
+
)
|
689 |
+
|
690 |
+
|
691 |
+
# Copied from transformers.models.bert.modeling_bert.BertPooler with Bert->MegatronBert->RetrievaBert
|
692 |
+
class RetrievaBertPooler(nn.Module):
|
693 |
+
def __init__(self, config):
|
694 |
+
super().__init__()
|
695 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
696 |
+
self.activation = nn.Tanh()
|
697 |
+
|
698 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
699 |
+
# We "pool" the model by simply taking the hidden state corresponding
|
700 |
+
# to the first token.
|
701 |
+
first_token_tensor = hidden_states[:, 0]
|
702 |
+
pooled_output = self.dense(first_token_tensor)
|
703 |
+
pooled_output = self.activation(pooled_output)
|
704 |
+
return pooled_output
|
705 |
+
|
706 |
+
|
707 |
+
# Copied from transformers.models.bert.modeling_bert.BertPredictionHeadTransform with Bert->MegatronBert->RetrievaBert
|
708 |
+
class RetrievaBertPredictionHeadTransform(nn.Module):
|
709 |
+
def __init__(self, config):
|
710 |
+
super().__init__()
|
711 |
+
# bertlmhead
|
712 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
713 |
+
if isinstance(config.lm_head_hidden_act, str):
|
714 |
+
self.transform_act_fn = ACT2FN[config.lm_head_hidden_act]
|
715 |
+
else:
|
716 |
+
self.transform_act_fn = config.lm_head_hidden_act
|
717 |
+
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
718 |
+
|
719 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
720 |
+
hidden_states = self.dense(hidden_states)
|
721 |
+
hidden_states = self.transform_act_fn(hidden_states)
|
722 |
+
hidden_states = self.LayerNorm(hidden_states)
|
723 |
+
return hidden_states
|
724 |
+
|
725 |
+
|
726 |
+
# Copied from transformers.models.bert.modeling_bert.BertLMPredictionHead with Bert->MegatronBert->RetrievaBert
|
727 |
+
class RetrievaBertLMPredictionHead(nn.Module):
|
728 |
+
def __init__(self, config):
|
729 |
+
super().__init__()
|
730 |
+
self.transform = RetrievaBertPredictionHeadTransform(config)
|
731 |
+
|
732 |
+
# The output weights are the same as the input embeddings, but there is
|
733 |
+
# an output-only bias for each token.
|
734 |
+
self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
735 |
+
|
736 |
+
# output_layer
|
737 |
+
self.bias = nn.Parameter(torch.zeros(config.vocab_size))
|
738 |
+
|
739 |
+
# Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings`
|
740 |
+
self.decoder.bias = self.bias
|
741 |
+
|
742 |
+
def _tie_weights(self):
|
743 |
+
self.decoder.bias = self.bias
|
744 |
+
|
745 |
+
def forward(self, hidden_states):
|
746 |
+
hidden_states = self.transform(hidden_states)
|
747 |
+
hidden_states = self.decoder(hidden_states)
|
748 |
+
return hidden_states
|
749 |
+
|
750 |
+
|
751 |
+
# Copied from transformers.models.bert.modeling_bert.BertOnlyMLMHead with Bert->MegatronBert->RetrievaBert
|
752 |
+
class RetrievaBertOnlyMLMHead(nn.Module):
|
753 |
+
def __init__(self, config):
|
754 |
+
super().__init__()
|
755 |
+
self.predictions = RetrievaBertLMPredictionHead(config)
|
756 |
+
|
757 |
+
def forward(self, sequence_output: torch.Tensor) -> torch.Tensor:
|
758 |
+
prediction_scores = self.predictions(sequence_output)
|
759 |
+
return prediction_scores
|
760 |
+
|
761 |
+
|
762 |
+
# Copied from transformers.models.bert.modeling_bert.BertOnlyNSPHead with Bert->MegatronBert->RetrievaBert
|
763 |
+
class RetrievaBertOnlyNSPHead(nn.Module):
|
764 |
+
def __init__(self, config):
|
765 |
+
super().__init__()
|
766 |
+
self.seq_relationship = nn.Linear(config.hidden_size, 2)
|
767 |
+
|
768 |
+
def forward(self, pooled_output):
|
769 |
+
seq_relationship_score = self.seq_relationship(pooled_output)
|
770 |
+
return seq_relationship_score
|
771 |
+
|
772 |
+
|
773 |
+
# Copied from transformers.models.bert.modeling_bert.BertPreTrainingHeads with Bert->MegatronBert->RetrievaBert
|
774 |
+
class RetrievaBertPreTrainingHeads(nn.Module):
|
775 |
+
def __init__(self, config):
|
776 |
+
super().__init__()
|
777 |
+
self.predictions = RetrievaBertLMPredictionHead(config)
|
778 |
+
self.seq_relationship = nn.Linear(config.hidden_size, 2)
|
779 |
+
|
780 |
+
def forward(self, sequence_output, pooled_output):
|
781 |
+
prediction_scores = self.predictions(sequence_output)
|
782 |
+
seq_relationship_score = self.seq_relationship(pooled_output)
|
783 |
+
return prediction_scores, seq_relationship_score
|
784 |
+
|
785 |
+
|
786 |
+
class RetrievaBertPreTrainedModel(PreTrainedModel):
|
787 |
+
"""
|
788 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
789 |
+
models.
|
790 |
+
"""
|
791 |
+
|
792 |
+
config_class = RetrievaBertConfig
|
793 |
+
load_tf_weights = load_tf_weights_in_megatron_bert
|
794 |
+
base_model_prefix = "bert"
|
795 |
+
supports_gradient_checkpointing = True
|
796 |
+
|
797 |
+
def _init_weights(self, module):
|
798 |
+
"""Initialize the weights"""
|
799 |
+
if isinstance(module, (nn.Linear, nn.Embedding)):
|
800 |
+
# Slightly different from the TF version which uses truncated_normal for initialization
|
801 |
+
# cf https://github.com/pytorch/pytorch/pull/5617
|
802 |
+
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
|
803 |
+
elif isinstance(module, nn.LayerNorm):
|
804 |
+
module.bias.data.zero_()
|
805 |
+
module.weight.data.fill_(1.0)
|
806 |
+
if isinstance(module, nn.Linear) and module.bias is not None:
|
807 |
+
module.bias.data.zero_()
|
808 |
+
|
809 |
+
|
810 |
+
@dataclass
|
811 |
+
# Copied from transformers.models.bert.modeling_bert.BertForPreTrainingOutput with Bert->MegatronBert->RetrievaBert
|
812 |
+
class RetrievaBertForPreTrainingOutput(ModelOutput):
|
813 |
+
"""
|
814 |
+
Output type of [`RetrievaBertForPreTraining`].
|
815 |
+
Args:
|
816 |
+
loss (*optional*, returned when `labels` is provided, `torch.FloatTensor` of shape `(1,)`):
|
817 |
+
Total loss as the sum of the masked language modeling loss and the next sequence prediction
|
818 |
+
(classification) loss.
|
819 |
+
prediction_logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
|
820 |
+
Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
|
821 |
+
seq_relationship_logits (`torch.FloatTensor` of shape `(batch_size, 2)`):
|
822 |
+
Prediction scores of the next sequence prediction (classification) head (scores of True/False continuation
|
823 |
+
before SoftMax).
|
824 |
+
hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
825 |
+
Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
|
826 |
+
shape `(batch_size, sequence_length, hidden_size)`.
|
827 |
+
Hidden-states of the model at the output of each layer plus the initial embedding outputs.
|
828 |
+
attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
829 |
+
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
830 |
+
sequence_length)`.
|
831 |
+
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
|
832 |
+
heads.
|
833 |
+
"""
|
834 |
+
|
835 |
+
loss: Optional[torch.FloatTensor] = None
|
836 |
+
prediction_logits: torch.FloatTensor = None
|
837 |
+
seq_relationship_logits: torch.FloatTensor = None
|
838 |
+
hidden_states: Optional[Tuple[torch.FloatTensor]] = None
|
839 |
+
attentions: Optional[Tuple[torch.FloatTensor]] = None
|
840 |
+
|
841 |
+
|
842 |
+
RETRIEVA_BERT_START_DOCSTRING = r"""
|
843 |
+
This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
|
844 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
845 |
+
etc.)
|
846 |
+
This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
|
847 |
+
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
|
848 |
+
and behavior.
|
849 |
+
Parameters:
|
850 |
+
config ([`RetrievaBertConfig`]): Model configuration class with all the parameters of the model.
|
851 |
+
Initializing with a config file does not load the weights associated with the model, only the
|
852 |
+
configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
853 |
+
"""
|
854 |
+
|
855 |
+
RETRIEVA_BERT_INPUTS_DOCSTRING = r"""
|
856 |
+
Args:
|
857 |
+
input_ids (`torch.LongTensor` of shape `({0})`):
|
858 |
+
Indices of input sequence tokens in the vocabulary.
|
859 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
860 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
861 |
+
[What are input IDs?](../glossary#input-ids)
|
862 |
+
attention_mask (`torch.FloatTensor` of shape `({0})`, *optional*):
|
863 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
864 |
+
- 1 for tokens that are **not masked**,
|
865 |
+
- 0 for tokens that are **masked**.
|
866 |
+
[What are attention masks?](../glossary#attention-mask)
|
867 |
+
token_type_ids (`torch.LongTensor` of shape `({0})`, *optional*):
|
868 |
+
Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
|
869 |
+
1]`:
|
870 |
+
- 0 corresponds to a *sentence A* token,
|
871 |
+
- 1 corresponds to a *sentence B* token.
|
872 |
+
[What are token type IDs?](../glossary#token-type-ids)
|
873 |
+
position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
|
874 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
875 |
+
config.max_position_embeddings - 1]`.
|
876 |
+
[What are position IDs?](../glossary#position-ids)
|
877 |
+
head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
|
878 |
+
Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
|
879 |
+
- 1 indicates the head is **not masked**,
|
880 |
+
- 0 indicates the head is **masked**.
|
881 |
+
inputs_embeds (`torch.FloatTensor` of shape `({0}, hidden_size)`, *optional*):
|
882 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
|
883 |
+
is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
|
884 |
+
model's internal embedding lookup matrix.
|
885 |
+
output_attentions (`bool`, *optional*):
|
886 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
887 |
+
tensors for more detail.
|
888 |
+
output_hidden_states (`bool`, *optional*):
|
889 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
890 |
+
more detail.
|
891 |
+
return_dict (`bool`, *optional*):
|
892 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
893 |
+
"""
|
894 |
+
|
895 |
+
|
896 |
+
@add_start_docstrings(
|
897 |
+
"The bare RetrievaBert Model transformer outputting raw hidden-states without any specific head on top.",
|
898 |
+
RETRIEVA_BERT_START_DOCSTRING,
|
899 |
+
)
|
900 |
+
class RetrievaBertModel(RetrievaBertPreTrainedModel):
|
901 |
+
"""
|
902 |
+
The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of
|
903 |
+
cross-attention is added between the self-attention layers, following the architecture described in [Attention is
|
904 |
+
all you need](https://arxiv.org/abs/1706.03762) by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit,
|
905 |
+
Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin.
|
906 |
+
To behave as an decoder the model needs to be initialized with the `is_decoder` argument of the configuration set
|
907 |
+
to `True`. To be used in a Seq2Seq model, the model needs to initialized with both `is_decoder` argument and
|
908 |
+
`add_cross_attention` set to `True`; an `encoder_hidden_states` is then expected as an input to the forward pass.
|
909 |
+
"""
|
910 |
+
|
911 |
+
def __init__(self, config, add_pooling_layer=True):
|
912 |
+
super().__init__(config)
|
913 |
+
self.config = config
|
914 |
+
|
915 |
+
self.embeddings = RetrievaBertEmbeddings(config)
|
916 |
+
self.encoder = RetrievaBertEncoder(config)
|
917 |
+
|
918 |
+
self.pooler = RetrievaBertPooler(config) if add_pooling_layer else None
|
919 |
+
|
920 |
+
self.register_buffer("position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False)
|
921 |
+
|
922 |
+
# Initialize weights and apply final processing
|
923 |
+
self.post_init()
|
924 |
+
|
925 |
+
def get_input_embeddings(self):
|
926 |
+
return self.embeddings.word_embeddings
|
927 |
+
|
928 |
+
def set_input_embeddings(self, value):
|
929 |
+
self.embeddings.word_embeddings = value
|
930 |
+
|
931 |
+
def _prune_heads(self, heads_to_prune):
|
932 |
+
"""
|
933 |
+
Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
|
934 |
+
class PreTrainedModel
|
935 |
+
"""
|
936 |
+
for layer, heads in heads_to_prune.items():
|
937 |
+
self.encoder.layer[layer].attention.prune_heads(heads)
|
938 |
+
|
939 |
+
@add_start_docstrings_to_model_forward(RETRIEVA_BERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
940 |
+
@add_code_sample_docstrings(
|
941 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
942 |
+
output_type=BaseModelOutputWithPoolingAndCrossAttentions,
|
943 |
+
config_class=_CONFIG_FOR_DOC,
|
944 |
+
)
|
945 |
+
def forward(
|
946 |
+
self,
|
947 |
+
input_ids: Optional[torch.LongTensor] = None,
|
948 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
949 |
+
token_type_ids: Optional[torch.LongTensor] = None,
|
950 |
+
position_ids: Optional[torch.LongTensor] = None,
|
951 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
952 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
953 |
+
encoder_hidden_states: Optional[torch.FloatTensor] = None,
|
954 |
+
encoder_attention_mask: Optional[torch.FloatTensor] = None,
|
955 |
+
past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
|
956 |
+
use_cache: Optional[bool] = None,
|
957 |
+
output_attentions: Optional[bool] = None,
|
958 |
+
output_hidden_states: Optional[bool] = None,
|
959 |
+
return_dict: Optional[bool] = None,
|
960 |
+
) -> Union[Tuple, BaseModelOutputWithPoolingAndCrossAttentions]:
|
961 |
+
r"""
|
962 |
+
encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
963 |
+
Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
|
964 |
+
the model is configured as a decoder.
|
965 |
+
encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
966 |
+
Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
|
967 |
+
the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
|
968 |
+
- 1 for tokens that are **not masked**,
|
969 |
+
- 0 for tokens that are **masked**.
|
970 |
+
past_key_values (`tuple(tuple(torch.FloatTensor))` of length `config.n_layers` with each tuple having 4 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
|
971 |
+
Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
|
972 |
+
If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
|
973 |
+
don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
|
974 |
+
`decoder_input_ids` of shape `(batch_size, sequence_length)`.
|
975 |
+
use_cache (`bool`, *optional*):
|
976 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
|
977 |
+
`past_key_values`).
|
978 |
+
"""
|
979 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
980 |
+
output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
981 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
982 |
+
|
983 |
+
if self.config.is_decoder:
|
984 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
985 |
+
else:
|
986 |
+
use_cache = False
|
987 |
+
|
988 |
+
if input_ids is not None and inputs_embeds is not None:
|
989 |
+
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
990 |
+
elif input_ids is not None:
|
991 |
+
self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
|
992 |
+
input_shape = input_ids.size()
|
993 |
+
elif inputs_embeds is not None:
|
994 |
+
input_shape = inputs_embeds.size()[:-1]
|
995 |
+
else:
|
996 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
997 |
+
|
998 |
+
batch_size, seq_length = input_shape
|
999 |
+
device = input_ids.device if input_ids is not None else inputs_embeds.device
|
1000 |
+
|
1001 |
+
# past_key_values_length
|
1002 |
+
past_key_values_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0
|
1003 |
+
|
1004 |
+
if attention_mask is None:
|
1005 |
+
attention_mask = torch.ones(((batch_size, seq_length + past_key_values_length)), device=device)
|
1006 |
+
if token_type_ids is None:
|
1007 |
+
token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
|
1008 |
+
if position_ids is None:
|
1009 |
+
position_ids = self.position_ids[:, past_key_values_length : seq_length + past_key_values_length]
|
1010 |
+
|
1011 |
+
# We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
|
1012 |
+
# ourselves in which case we just need to make it broadcastable to all heads.
|
1013 |
+
extended_attention_mask: torch.Tensor = self.get_extended_attention_mask(attention_mask, input_shape)
|
1014 |
+
|
1015 |
+
# If a 2D or 3D attention mask is provided for the cross-attention
|
1016 |
+
# we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
|
1017 |
+
if self.config.is_decoder and encoder_hidden_states is not None:
|
1018 |
+
encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size()
|
1019 |
+
encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
|
1020 |
+
if encoder_attention_mask is None:
|
1021 |
+
encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device)
|
1022 |
+
encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask)
|
1023 |
+
else:
|
1024 |
+
encoder_extended_attention_mask = None
|
1025 |
+
|
1026 |
+
# Prepare head mask if needed
|
1027 |
+
# 1.0 in head_mask indicate we keep the head
|
1028 |
+
# attention_probs has shape bsz x n_heads x N x N
|
1029 |
+
# input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
|
1030 |
+
# and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
|
1031 |
+
head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
|
1032 |
+
|
1033 |
+
embedding_output = self.embeddings(
|
1034 |
+
input_ids=input_ids,
|
1035 |
+
position_ids=position_ids,
|
1036 |
+
token_type_ids=token_type_ids,
|
1037 |
+
inputs_embeds=inputs_embeds,
|
1038 |
+
past_key_values_length=past_key_values_length,
|
1039 |
+
)
|
1040 |
+
encoder_outputs = self.encoder(
|
1041 |
+
embedding_output,
|
1042 |
+
attention_mask=extended_attention_mask,
|
1043 |
+
position_ids=position_ids,
|
1044 |
+
head_mask=head_mask,
|
1045 |
+
encoder_hidden_states=encoder_hidden_states,
|
1046 |
+
encoder_attention_mask=encoder_extended_attention_mask,
|
1047 |
+
past_key_values=past_key_values,
|
1048 |
+
use_cache=use_cache,
|
1049 |
+
output_attentions=output_attentions,
|
1050 |
+
output_hidden_states=output_hidden_states,
|
1051 |
+
return_dict=return_dict,
|
1052 |
+
)
|
1053 |
+
sequence_output = encoder_outputs[0]
|
1054 |
+
pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
|
1055 |
+
|
1056 |
+
if not return_dict:
|
1057 |
+
return (sequence_output, pooled_output) + encoder_outputs[1:]
|
1058 |
+
|
1059 |
+
return BaseModelOutputWithPoolingAndCrossAttentions(
|
1060 |
+
last_hidden_state=sequence_output,
|
1061 |
+
pooler_output=pooled_output,
|
1062 |
+
past_key_values=encoder_outputs.past_key_values,
|
1063 |
+
hidden_states=encoder_outputs.hidden_states,
|
1064 |
+
attentions=encoder_outputs.attentions,
|
1065 |
+
cross_attentions=encoder_outputs.cross_attentions,
|
1066 |
+
)
|
1067 |
+
|
1068 |
+
|
1069 |
+
@add_start_docstrings(
|
1070 |
+
"""
|
1071 |
+
MegatronBert Model with two heads on top as done during the pretraining: a `masked language modeling` head and a
|
1072 |
+
`next sentence prediction (classification)` head.
|
1073 |
+
RetrievaBert uses a `masked language modeling` only.
|
1074 |
+
""",
|
1075 |
+
RETRIEVA_BERT_START_DOCSTRING,
|
1076 |
+
)
|
1077 |
+
class RetrievaBertForPreTraining(RetrievaBertPreTrainedModel):
|
1078 |
+
_tied_weights_keys = ["cls.predictions.decoder"]
|
1079 |
+
|
1080 |
+
def __init__(self, config, add_binary_head=True):
|
1081 |
+
super().__init__(config)
|
1082 |
+
|
1083 |
+
self.bert = RetrievaBertModel(config)
|
1084 |
+
self.cls = RetrievaBertPreTrainingHeads(config)
|
1085 |
+
|
1086 |
+
# Initialize weights and apply final processing
|
1087 |
+
self.post_init()
|
1088 |
+
|
1089 |
+
def get_output_embeddings(self):
|
1090 |
+
return self.cls.predictions.decoder
|
1091 |
+
|
1092 |
+
def set_output_embeddings(self, new_embeddings):
|
1093 |
+
self.cls.predictions.decoder = new_embeddings
|
1094 |
+
self.cls.predictions.bias = new_embeddings.bias
|
1095 |
+
|
1096 |
+
@add_start_docstrings_to_model_forward(RETRIEVA_BERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
1097 |
+
@replace_return_docstrings(output_type=RetrievaBertForPreTrainingOutput, config_class=_CONFIG_FOR_DOC)
|
1098 |
+
def forward(
|
1099 |
+
self,
|
1100 |
+
input_ids: Optional[torch.LongTensor] = None,
|
1101 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
1102 |
+
token_type_ids: Optional[torch.LongTensor] = None,
|
1103 |
+
position_ids: Optional[torch.LongTensor] = None,
|
1104 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
1105 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
1106 |
+
labels: Optional[torch.LongTensor] = None,
|
1107 |
+
next_sentence_label: Optional[torch.LongTensor] = None,
|
1108 |
+
output_attentions: Optional[bool] = None,
|
1109 |
+
output_hidden_states: Optional[bool] = None,
|
1110 |
+
return_dict: Optional[bool] = None,
|
1111 |
+
) -> Union[Tuple, RetrievaBertForPreTrainingOutput]:
|
1112 |
+
r"""
|
1113 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
1114 |
+
Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
|
1115 |
+
config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
|
1116 |
+
loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
|
1117 |
+
next_sentence_label (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
1118 |
+
Labels for computing the next sequence prediction (classification) loss. Input should be a sequence pair
|
1119 |
+
(see `input_ids` docstring) Indices should be in `[0, 1]`:
|
1120 |
+
- 0 indicates sequence B is a continuation of sequence A,
|
1121 |
+
- 1 indicates sequence B is a random sequence.
|
1122 |
+
kwargs (`Dict[str, any]`, optional, defaults to *{}*):
|
1123 |
+
Used to hide legacy arguments that have been deprecated.
|
1124 |
+
Returns:
|
1125 |
+
Example:
|
1126 |
+
```python
|
1127 |
+
>>> from transformers import AutoTokenizer
|
1128 |
+
>>> from models import RetrievaBertForPreTraining
|
1129 |
+
>>> import torch
|
1130 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("retrieva-jp/bert-1.3b")
|
1131 |
+
>>> model = RetrievaBertForPreTraining.from_pretrained("retrieva-jp/bert-1.3b")
|
1132 |
+
>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
|
1133 |
+
>>> outputs = model(**inputs)
|
1134 |
+
>>> prediction_logits = outputs.prediction_logits
|
1135 |
+
>>> seq_relationship_logits = outputs.seq_relationship_logits
|
1136 |
+
```"""
|
1137 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1138 |
+
|
1139 |
+
outputs = self.bert(
|
1140 |
+
input_ids,
|
1141 |
+
attention_mask=attention_mask,
|
1142 |
+
token_type_ids=token_type_ids,
|
1143 |
+
position_ids=position_ids,
|
1144 |
+
head_mask=head_mask,
|
1145 |
+
inputs_embeds=inputs_embeds,
|
1146 |
+
output_attentions=output_attentions,
|
1147 |
+
output_hidden_states=output_hidden_states,
|
1148 |
+
return_dict=return_dict,
|
1149 |
+
)
|
1150 |
+
|
1151 |
+
sequence_output, pooled_output = outputs[:2]
|
1152 |
+
prediction_scores, seq_relationship_score = self.cls(sequence_output, pooled_output)
|
1153 |
+
|
1154 |
+
total_loss = None
|
1155 |
+
if labels is not None and next_sentence_label is not None:
|
1156 |
+
loss_fct = CrossEntropyLoss()
|
1157 |
+
masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
|
1158 |
+
next_sentence_loss = loss_fct(seq_relationship_score.view(-1, 2), next_sentence_label.view(-1))
|
1159 |
+
total_loss = masked_lm_loss + next_sentence_loss
|
1160 |
+
|
1161 |
+
if not return_dict:
|
1162 |
+
output = (prediction_scores, seq_relationship_score) + outputs[2:]
|
1163 |
+
return ((total_loss,) + output) if total_loss is not None else output
|
1164 |
+
|
1165 |
+
return RetrievaBertForPreTrainingOutput(
|
1166 |
+
loss=total_loss,
|
1167 |
+
prediction_logits=prediction_scores,
|
1168 |
+
seq_relationship_logits=seq_relationship_score,
|
1169 |
+
hidden_states=outputs.hidden_states,
|
1170 |
+
attentions=outputs.attentions,
|
1171 |
+
)
|
1172 |
+
|
1173 |
+
|
1174 |
+
@add_start_docstrings(
|
1175 |
+
"""RetrievaBert Model with a `language modeling` head on top for CLM fine-tuning.""",
|
1176 |
+
RETRIEVA_BERT_START_DOCSTRING,
|
1177 |
+
)
|
1178 |
+
class RetrievaBertForCausalLM(RetrievaBertPreTrainedModel):
|
1179 |
+
_tied_weights_keys = ["cls.predictions.decoder"]
|
1180 |
+
|
1181 |
+
def __init__(self, config):
|
1182 |
+
super().__init__(config)
|
1183 |
+
|
1184 |
+
if not config.is_decoder:
|
1185 |
+
logger.warning("If you want to use `RetrievaBertForCausalLM` as a standalone, add `is_decoder=True.`")
|
1186 |
+
|
1187 |
+
self.bert = RetrievaBertModel(config, add_pooling_layer=False)
|
1188 |
+
self.cls = RetrievaBertOnlyMLMHead(config)
|
1189 |
+
|
1190 |
+
# Initialize weights and apply final processing
|
1191 |
+
self.post_init()
|
1192 |
+
|
1193 |
+
def get_output_embeddings(self):
|
1194 |
+
return self.cls.predictions.decoder
|
1195 |
+
|
1196 |
+
def set_output_embeddings(self, new_embeddings):
|
1197 |
+
self.cls.predictions.decoder = new_embeddings
|
1198 |
+
self.cls.predictions.bias = new_embeddings.bias
|
1199 |
+
|
1200 |
+
@add_start_docstrings_to_model_forward(RETRIEVA_BERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
1201 |
+
@replace_return_docstrings(output_type=CausalLMOutputWithCrossAttentions, config_class=_CONFIG_FOR_DOC)
|
1202 |
+
def forward(
|
1203 |
+
self,
|
1204 |
+
input_ids: Optional[torch.LongTensor] = None,
|
1205 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
1206 |
+
token_type_ids: Optional[torch.LongTensor] = None,
|
1207 |
+
position_ids: Optional[torch.LongTensor] = None,
|
1208 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
1209 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
1210 |
+
encoder_hidden_states: Optional[torch.FloatTensor] = None,
|
1211 |
+
encoder_attention_mask: Optional[torch.FloatTensor] = None,
|
1212 |
+
labels: Optional[torch.LongTensor] = None,
|
1213 |
+
past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
|
1214 |
+
use_cache: Optional[bool] = None,
|
1215 |
+
output_attentions: Optional[bool] = None,
|
1216 |
+
output_hidden_states: Optional[bool] = None,
|
1217 |
+
return_dict: Optional[bool] = None,
|
1218 |
+
) -> Union[Tuple, CausalLMOutputWithCrossAttentions]:
|
1219 |
+
r"""
|
1220 |
+
encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
1221 |
+
Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
|
1222 |
+
the model is configured as a decoder.
|
1223 |
+
encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
1224 |
+
Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
|
1225 |
+
the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
|
1226 |
+
- 1 for tokens that are **not masked**,
|
1227 |
+
- 0 for tokens that are **masked**.
|
1228 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
1229 |
+
Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in
|
1230 |
+
`[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are
|
1231 |
+
ignored (masked), the loss is only computed for the tokens with labels n `[0, ..., config.vocab_size]`
|
1232 |
+
past_key_values (`tuple(tuple(torch.FloatTensor))` of length `config.n_layers` with each tuple having 4 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
|
1233 |
+
Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
|
1234 |
+
If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
|
1235 |
+
don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
|
1236 |
+
`decoder_input_ids` of shape `(batch_size, sequence_length)`.
|
1237 |
+
use_cache (`bool`, *optional*):
|
1238 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
|
1239 |
+
`past_key_values`).
|
1240 |
+
Returns:
|
1241 |
+
Example:
|
1242 |
+
```python
|
1243 |
+
>>> from transformers import AutoTokenizer
|
1244 |
+
>>> from models import RetrievaBertForCausalLM, RetrievaBertConfig
|
1245 |
+
>>> import torch
|
1246 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("retrieva-jp/bert-1.3b")
|
1247 |
+
>>> model = RetrievaBertForCausalLM.from_pretrained("retrieva-jp/bert-1.3b", is_decoder=True)
|
1248 |
+
>>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
|
1249 |
+
>>> outputs = model(**inputs)
|
1250 |
+
>>> prediction_logits = outputs.logits
|
1251 |
+
```"""
|
1252 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1253 |
+
if labels is not None:
|
1254 |
+
use_cache = False
|
1255 |
+
|
1256 |
+
outputs = self.bert(
|
1257 |
+
input_ids,
|
1258 |
+
attention_mask=attention_mask,
|
1259 |
+
token_type_ids=token_type_ids,
|
1260 |
+
position_ids=position_ids,
|
1261 |
+
head_mask=head_mask,
|
1262 |
+
inputs_embeds=inputs_embeds,
|
1263 |
+
encoder_hidden_states=encoder_hidden_states,
|
1264 |
+
encoder_attention_mask=encoder_attention_mask,
|
1265 |
+
past_key_values=past_key_values,
|
1266 |
+
use_cache=use_cache,
|
1267 |
+
output_attentions=output_attentions,
|
1268 |
+
output_hidden_states=output_hidden_states,
|
1269 |
+
return_dict=return_dict,
|
1270 |
+
)
|
1271 |
+
|
1272 |
+
sequence_output = outputs[0]
|
1273 |
+
prediction_scores = self.cls(sequence_output)
|
1274 |
+
|
1275 |
+
lm_loss = None
|
1276 |
+
if labels is not None:
|
1277 |
+
# we are doing next-token prediction; shift prediction scores and input ids by one
|
1278 |
+
shifted_prediction_scores = prediction_scores[:, :-1, :].contiguous()
|
1279 |
+
labels = labels[:, 1:].contiguous()
|
1280 |
+
loss_fct = CrossEntropyLoss()
|
1281 |
+
lm_loss = loss_fct(shifted_prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
|
1282 |
+
|
1283 |
+
if not return_dict:
|
1284 |
+
output = (prediction_scores,) + outputs[2:]
|
1285 |
+
return ((lm_loss,) + output) if lm_loss is not None else output
|
1286 |
+
|
1287 |
+
return CausalLMOutputWithCrossAttentions(
|
1288 |
+
loss=lm_loss,
|
1289 |
+
logits=prediction_scores,
|
1290 |
+
past_key_values=outputs.past_key_values,
|
1291 |
+
hidden_states=outputs.hidden_states,
|
1292 |
+
attentions=outputs.attentions,
|
1293 |
+
cross_attentions=outputs.cross_attentions,
|
1294 |
+
)
|
1295 |
+
|
1296 |
+
def prepare_inputs_for_generation(self, input_ids, past_key_values=None, attention_mask=None, **model_kwargs):
|
1297 |
+
input_shape = input_ids.shape
|
1298 |
+
# if model is used as a decoder in encoder-decoder model, the decoder attention mask is created on the fly
|
1299 |
+
if attention_mask is None:
|
1300 |
+
attention_mask = input_ids.new_ones(input_shape)
|
1301 |
+
|
1302 |
+
# cut decoder_input_ids if past_key_values is used
|
1303 |
+
if past_key_values is not None:
|
1304 |
+
past_length = past_key_values[0][0].shape[2]
|
1305 |
+
|
1306 |
+
# Some generation methods already pass only the last input ID
|
1307 |
+
if input_ids.shape[1] > past_length:
|
1308 |
+
remove_prefix_length = past_length
|
1309 |
+
else:
|
1310 |
+
# Default to old behavior: keep only final ID
|
1311 |
+
remove_prefix_length = input_ids.shape[1] - 1
|
1312 |
+
|
1313 |
+
input_ids = input_ids[:, remove_prefix_length:]
|
1314 |
+
|
1315 |
+
return {"input_ids": input_ids, "attention_mask": attention_mask, "past_key_values": past_key_values}
|
1316 |
+
|
1317 |
+
def _reorder_cache(self, past_key_values, beam_idx):
|
1318 |
+
reordered_past = ()
|
1319 |
+
for layer_past in past_key_values:
|
1320 |
+
reordered_past += (tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),)
|
1321 |
+
return reordered_past
|
1322 |
+
|
1323 |
+
|
1324 |
+
@add_start_docstrings("""RetrievaBert Model with a `language modeling` head on top.""", RETRIEVA_BERT_START_DOCSTRING)
|
1325 |
+
class RetrievaBertForMaskedLM(RetrievaBertPreTrainedModel):
|
1326 |
+
_tied_weights_keys = ["cls.predictions.decoder"]
|
1327 |
+
|
1328 |
+
def __init__(self, config):
|
1329 |
+
super().__init__(config)
|
1330 |
+
|
1331 |
+
if config.is_decoder:
|
1332 |
+
logger.warning("If you want to use `RetrievaBertForMaskedLM` make sure `config.is_decoder=False` for " "bi-directional self-attention.")
|
1333 |
+
|
1334 |
+
self.bert = RetrievaBertModel(config, add_pooling_layer=False)
|
1335 |
+
self.cls = RetrievaBertOnlyMLMHead(config)
|
1336 |
+
|
1337 |
+
# Initialize weights and apply final processing
|
1338 |
+
self.post_init()
|
1339 |
+
|
1340 |
+
def get_output_embeddings(self):
|
1341 |
+
return self.cls.predictions.decoder
|
1342 |
+
|
1343 |
+
def set_output_embeddings(self, new_embeddings):
|
1344 |
+
self.cls.predictions.decoder = new_embeddings
|
1345 |
+
self.cls.predictions.bias = new_embeddings.bias
|
1346 |
+
|
1347 |
+
@add_start_docstrings_to_model_forward(RETRIEVA_BERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
1348 |
+
@add_code_sample_docstrings(
|
1349 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
1350 |
+
output_type=MaskedLMOutput,
|
1351 |
+
config_class=_CONFIG_FOR_DOC,
|
1352 |
+
)
|
1353 |
+
def forward(
|
1354 |
+
self,
|
1355 |
+
input_ids: Optional[torch.LongTensor] = None,
|
1356 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
1357 |
+
token_type_ids: Optional[torch.LongTensor] = None,
|
1358 |
+
position_ids: Optional[torch.LongTensor] = None,
|
1359 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
1360 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
1361 |
+
encoder_hidden_states: Optional[torch.FloatTensor] = None,
|
1362 |
+
encoder_attention_mask: Optional[torch.FloatTensor] = None,
|
1363 |
+
labels: Optional[torch.LongTensor] = None,
|
1364 |
+
output_attentions: Optional[bool] = None,
|
1365 |
+
output_hidden_states: Optional[bool] = None,
|
1366 |
+
return_dict: Optional[bool] = None,
|
1367 |
+
) -> Union[Tuple, MaskedLMOutput]:
|
1368 |
+
r"""
|
1369 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
1370 |
+
Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
|
1371 |
+
config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
|
1372 |
+
loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
|
1373 |
+
"""
|
1374 |
+
|
1375 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1376 |
+
|
1377 |
+
outputs = self.bert(
|
1378 |
+
input_ids,
|
1379 |
+
attention_mask=attention_mask,
|
1380 |
+
token_type_ids=token_type_ids,
|
1381 |
+
position_ids=position_ids,
|
1382 |
+
head_mask=head_mask,
|
1383 |
+
inputs_embeds=inputs_embeds,
|
1384 |
+
encoder_hidden_states=encoder_hidden_states,
|
1385 |
+
encoder_attention_mask=encoder_attention_mask,
|
1386 |
+
output_attentions=output_attentions,
|
1387 |
+
output_hidden_states=output_hidden_states,
|
1388 |
+
return_dict=return_dict,
|
1389 |
+
)
|
1390 |
+
|
1391 |
+
sequence_output = outputs[0]
|
1392 |
+
prediction_scores = self.cls(sequence_output)
|
1393 |
+
|
1394 |
+
masked_lm_loss = None
|
1395 |
+
if labels is not None:
|
1396 |
+
loss_fct = CrossEntropyLoss() # -100 index = padding token
|
1397 |
+
masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1))
|
1398 |
+
|
1399 |
+
if not return_dict:
|
1400 |
+
output = (prediction_scores,) + outputs[2:]
|
1401 |
+
return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
|
1402 |
+
|
1403 |
+
return MaskedLMOutput(
|
1404 |
+
loss=masked_lm_loss,
|
1405 |
+
logits=prediction_scores,
|
1406 |
+
hidden_states=outputs.hidden_states,
|
1407 |
+
attentions=outputs.attentions,
|
1408 |
+
)
|
1409 |
+
|
1410 |
+
def prepare_inputs_for_generation(self, input_ids, attention_mask=None, **model_kwargs):
|
1411 |
+
input_shape = input_ids.shape
|
1412 |
+
effective_batch_size = input_shape[0]
|
1413 |
+
|
1414 |
+
# add a dummy token
|
1415 |
+
if self.config.pad_token_id is None:
|
1416 |
+
raise ValueError("The PAD token should be defined for generation")
|
1417 |
+
attention_mask = torch.cat([attention_mask, attention_mask.new_zeros((attention_mask.shape[0], 1))], dim=-1)
|
1418 |
+
dummy_token = torch.full((effective_batch_size, 1), self.config.pad_token_id, dtype=torch.long, device=input_ids.device)
|
1419 |
+
input_ids = torch.cat([input_ids, dummy_token], dim=1)
|
1420 |
+
|
1421 |
+
return {"input_ids": input_ids, "attention_mask": attention_mask}
|
1422 |
+
|
1423 |
+
|
1424 |
+
@add_start_docstrings(
|
1425 |
+
"""RetrievaBert Model with a `next sentence prediction (classification)` head on top.""",
|
1426 |
+
RETRIEVA_BERT_START_DOCSTRING,
|
1427 |
+
)
|
1428 |
+
class RetrievaBertForNextSentencePrediction(RetrievaBertPreTrainedModel):
|
1429 |
+
def __init__(self, config):
|
1430 |
+
super().__init__(config)
|
1431 |
+
|
1432 |
+
self.bert = RetrievaBertModel(config)
|
1433 |
+
self.cls = RetrievaBertOnlyNSPHead(config)
|
1434 |
+
|
1435 |
+
# Initialize weights and apply final processing
|
1436 |
+
self.post_init()
|
1437 |
+
|
1438 |
+
@add_start_docstrings_to_model_forward(RETRIEVA_BERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
1439 |
+
@replace_return_docstrings(output_type=NextSentencePredictorOutput, config_class=_CONFIG_FOR_DOC)
|
1440 |
+
def forward(
|
1441 |
+
self,
|
1442 |
+
input_ids: Optional[torch.LongTensor] = None,
|
1443 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
1444 |
+
token_type_ids: Optional[torch.LongTensor] = None,
|
1445 |
+
position_ids: Optional[torch.LongTensor] = None,
|
1446 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
1447 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
1448 |
+
labels: Optional[torch.LongTensor] = None,
|
1449 |
+
output_attentions: Optional[bool] = None,
|
1450 |
+
output_hidden_states: Optional[bool] = None,
|
1451 |
+
return_dict: Optional[bool] = None,
|
1452 |
+
**kwargs,
|
1453 |
+
) -> Union[Tuple, NextSentencePredictorOutput]:
|
1454 |
+
r"""
|
1455 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
1456 |
+
Labels for computing the next sequence prediction (classification) loss. Input should be a sequence pair
|
1457 |
+
(see `input_ids` docstring). Indices should be in `[0, 1]`:
|
1458 |
+
- 0 indicates sequence B is a continuation of sequence A,
|
1459 |
+
- 1 indicates sequence B is a random sequence.
|
1460 |
+
Returns:
|
1461 |
+
Example:
|
1462 |
+
```python
|
1463 |
+
>>> from transformers import AutoTokenizer
|
1464 |
+
>>> from models import RetrievaBertForNextSentencePrediction
|
1465 |
+
>>> import torch
|
1466 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("retrieva-jp/bert-1.3b")
|
1467 |
+
>>> model = RetrievaBertForNextSentencePrediction.from_pretrained("retrieva-jp/bert-1.3b")
|
1468 |
+
>>> prompt = "In Italy, pizza served in formal settings, such as at a restaurant, is presented unsliced."
|
1469 |
+
>>> next_sentence = "The sky is blue due to the shorter wavelength of blue light."
|
1470 |
+
>>> encoding = tokenizer(prompt, next_sentence, return_tensors="pt")
|
1471 |
+
>>> outputs = model(**encoding, labels=torch.LongTensor([1]))
|
1472 |
+
>>> logits = outputs.logits
|
1473 |
+
>>> assert logits[0, 0] < logits[0, 1] # next sentence was random
|
1474 |
+
```"""
|
1475 |
+
|
1476 |
+
if "next_sentence_label" in kwargs:
|
1477 |
+
warnings.warn(
|
1478 |
+
"The `next_sentence_label` argument is deprecated and will be removed in a future version, use" " `labels` instead.",
|
1479 |
+
FutureWarning,
|
1480 |
+
)
|
1481 |
+
labels = kwargs.pop("next_sentence_label")
|
1482 |
+
|
1483 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1484 |
+
|
1485 |
+
outputs = self.bert(
|
1486 |
+
input_ids,
|
1487 |
+
attention_mask=attention_mask,
|
1488 |
+
token_type_ids=token_type_ids,
|
1489 |
+
position_ids=position_ids,
|
1490 |
+
head_mask=head_mask,
|
1491 |
+
inputs_embeds=inputs_embeds,
|
1492 |
+
output_attentions=output_attentions,
|
1493 |
+
output_hidden_states=output_hidden_states,
|
1494 |
+
return_dict=return_dict,
|
1495 |
+
)
|
1496 |
+
|
1497 |
+
pooled_output = outputs[1]
|
1498 |
+
|
1499 |
+
seq_relationship_scores = self.cls(pooled_output)
|
1500 |
+
|
1501 |
+
next_sentence_loss = None
|
1502 |
+
if labels is not None:
|
1503 |
+
loss_fct = CrossEntropyLoss()
|
1504 |
+
next_sentence_loss = loss_fct(seq_relationship_scores.view(-1, 2), labels.view(-1))
|
1505 |
+
|
1506 |
+
if not return_dict:
|
1507 |
+
output = (seq_relationship_scores,) + outputs[2:]
|
1508 |
+
return ((next_sentence_loss,) + output) if next_sentence_loss is not None else output
|
1509 |
+
|
1510 |
+
return NextSentencePredictorOutput(
|
1511 |
+
loss=next_sentence_loss,
|
1512 |
+
logits=seq_relationship_scores,
|
1513 |
+
hidden_states=outputs.hidden_states,
|
1514 |
+
attentions=outputs.attentions,
|
1515 |
+
)
|
sentence_bert_config.json
ADDED
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"max_seq_length": 1024,
|
3 |
+
"do_lower_case": false
|
4 |
+
}
|
special_tokens_map.json
ADDED
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"additional_special_tokens": [
|
3 |
+
"<EOD|LLM-jp>"
|
4 |
+
],
|
5 |
+
"bos_token": {
|
6 |
+
"content": "<s|LLM-jp>",
|
7 |
+
"lstrip": false,
|
8 |
+
"normalized": false,
|
9 |
+
"rstrip": false,
|
10 |
+
"single_word": false
|
11 |
+
},
|
12 |
+
"cls_token": {
|
13 |
+
"content": "<CLS|LLM-jp>",
|
14 |
+
"lstrip": false,
|
15 |
+
"normalized": false,
|
16 |
+
"rstrip": false,
|
17 |
+
"single_word": false
|
18 |
+
},
|
19 |
+
"eos_token": {
|
20 |
+
"content": "</s|LLM-jp>",
|
21 |
+
"lstrip": false,
|
22 |
+
"normalized": false,
|
23 |
+
"rstrip": false,
|
24 |
+
"single_word": false
|
25 |
+
},
|
26 |
+
"mask_token": {
|
27 |
+
"content": "<MASK|LLM-jp>",
|
28 |
+
"lstrip": false,
|
29 |
+
"normalized": false,
|
30 |
+
"rstrip": false,
|
31 |
+
"single_word": false
|
32 |
+
},
|
33 |
+
"pad_token": {
|
34 |
+
"content": "<PAD|LLM-jp>",
|
35 |
+
"lstrip": false,
|
36 |
+
"normalized": false,
|
37 |
+
"rstrip": false,
|
38 |
+
"single_word": false
|
39 |
+
},
|
40 |
+
"sep_token": {
|
41 |
+
"content": "<SEP|LLM-jp>",
|
42 |
+
"lstrip": false,
|
43 |
+
"normalized": false,
|
44 |
+
"rstrip": false,
|
45 |
+
"single_word": false
|
46 |
+
},
|
47 |
+
"unk_token": {
|
48 |
+
"content": "<unk|LLM-jp>",
|
49 |
+
"lstrip": false,
|
50 |
+
"normalized": false,
|
51 |
+
"rstrip": false,
|
52 |
+
"single_word": false
|
53 |
+
}
|
54 |
+
}
|
tokenizer.json
ADDED
The diff for this file is too large to render.
See raw diff
|
|
tokenizer_config.json
ADDED
@@ -0,0 +1,91 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"added_tokens_decoder": {
|
3 |
+
"0": {
|
4 |
+
"content": "<unk|LLM-jp>",
|
5 |
+
"lstrip": false,
|
6 |
+
"normalized": false,
|
7 |
+
"rstrip": false,
|
8 |
+
"single_word": false,
|
9 |
+
"special": true
|
10 |
+
},
|
11 |
+
"1": {
|
12 |
+
"content": "<s|LLM-jp>",
|
13 |
+
"lstrip": false,
|
14 |
+
"normalized": false,
|
15 |
+
"rstrip": false,
|
16 |
+
"single_word": false,
|
17 |
+
"special": true
|
18 |
+
},
|
19 |
+
"2": {
|
20 |
+
"content": "</s|LLM-jp>",
|
21 |
+
"lstrip": false,
|
22 |
+
"normalized": false,
|
23 |
+
"rstrip": false,
|
24 |
+
"single_word": false,
|
25 |
+
"special": true
|
26 |
+
},
|
27 |
+
"3": {
|
28 |
+
"content": "<MASK|LLM-jp>",
|
29 |
+
"lstrip": false,
|
30 |
+
"normalized": false,
|
31 |
+
"rstrip": false,
|
32 |
+
"single_word": false,
|
33 |
+
"special": true
|
34 |
+
},
|
35 |
+
"4": {
|
36 |
+
"content": "<PAD|LLM-jp>",
|
37 |
+
"lstrip": false,
|
38 |
+
"normalized": false,
|
39 |
+
"rstrip": false,
|
40 |
+
"single_word": false,
|
41 |
+
"special": true
|
42 |
+
},
|
43 |
+
"5": {
|
44 |
+
"content": "<CLS|LLM-jp>",
|
45 |
+
"lstrip": false,
|
46 |
+
"normalized": false,
|
47 |
+
"rstrip": false,
|
48 |
+
"single_word": false,
|
49 |
+
"special": true
|
50 |
+
},
|
51 |
+
"6": {
|
52 |
+
"content": "<SEP|LLM-jp>",
|
53 |
+
"lstrip": false,
|
54 |
+
"normalized": false,
|
55 |
+
"rstrip": false,
|
56 |
+
"single_word": false,
|
57 |
+
"special": true
|
58 |
+
},
|
59 |
+
"7": {
|
60 |
+
"content": "<EOD|LLM-jp>",
|
61 |
+
"lstrip": false,
|
62 |
+
"normalized": false,
|
63 |
+
"rstrip": false,
|
64 |
+
"single_word": false,
|
65 |
+
"special": true
|
66 |
+
}
|
67 |
+
},
|
68 |
+
"additional_special_tokens": [
|
69 |
+
"<EOD|LLM-jp>"
|
70 |
+
],
|
71 |
+
"bos_token": "<s|LLM-jp>",
|
72 |
+
"clean_up_tokenization_spaces": false,
|
73 |
+
"cls_token": "<CLS|LLM-jp>",
|
74 |
+
"eod_token": "</s|LLM-jp>",
|
75 |
+
"eos_token": "</s|LLM-jp>",
|
76 |
+
"extra_ids": 0,
|
77 |
+
"mask_token": "<MASK|LLM-jp>",
|
78 |
+
"max_length": 1024,
|
79 |
+
"model_max_length": 1024,
|
80 |
+
"pad_to_multiple_of": null,
|
81 |
+
"pad_token": "<PAD|LLM-jp>",
|
82 |
+
"pad_token_type_id": 0,
|
83 |
+
"padding_side": "right",
|
84 |
+
"sep_token": "<SEP|LLM-jp>",
|
85 |
+
"sp_model_kwargs": {},
|
86 |
+
"stride": 0,
|
87 |
+
"tokenizer_class": "PreTrainedTokenizerFast",
|
88 |
+
"truncation_side": "right",
|
89 |
+
"truncation_strategy": "longest_first",
|
90 |
+
"unk_token": "<unk|LLM-jp>"
|
91 |
+
}
|