Commit
•
7eedd24
1
Parent(s):
affd7fa
feat: push custom model
Browse files- 1_Pooling/config.json +10 -0
- README.md +41 -0
- config.json +36 -0
- config_sentence_transformers.json +9 -0
- configuration_bert.py +177 -0
- merges.txt +0 -0
- model.safetensors +3 -0
- modeling_bert.py +2312 -0
- modules.json +20 -0
- sentence_bert_config.json +4 -0
- special_tokens_map.json +51 -0
- tokenizer.json +0 -0
- tokenizer_config.json +57 -0
- training_args.bin +3 -0
- vocab.json +0 -0
1_Pooling/config.json
ADDED
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"word_embedding_dimension": 768,
|
3 |
+
"pooling_mode_cls_token": true,
|
4 |
+
"pooling_mode_mean_tokens": false,
|
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,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
---
|
2 |
+
license: apache-2.0
|
3 |
+
datasets:
|
4 |
+
- fine-tuned/jinaai_jina-embeddings-v2-base-code-stackoverflow
|
5 |
+
- allenai/c4
|
6 |
+
language:
|
7 |
+
- en
|
8 |
+
pipeline_tag: feature-extraction
|
9 |
+
tags:
|
10 |
+
- sentence-transformers
|
11 |
+
- feature-extraction
|
12 |
+
- sentence-similarity
|
13 |
+
- mteb
|
14 |
+
- Programming
|
15 |
+
- Development
|
16 |
+
- Coding
|
17 |
+
- Software
|
18 |
+
- Tech
|
19 |
+
---
|
20 |
+
This model is a fine-tuned version of [**jinaai/jina-embeddings-v2-base-code**](https://huggingface.co/jinaai/jina-embeddings-v2-base-code) designed for the following use case:
|
21 |
+
|
22 |
+
code snippet search engine
|
23 |
+
|
24 |
+
## How to Use
|
25 |
+
This model can be easily integrated into your NLP pipeline for tasks such as text classification, sentiment analysis, entity recognition, and more. Here's a simple example to get you started:
|
26 |
+
|
27 |
+
```python
|
28 |
+
from sentence_transformers import SentenceTransformer
|
29 |
+
from sentence_transformers.util import cos_sim
|
30 |
+
|
31 |
+
model = SentenceTransformer(
|
32 |
+
'fine-tuned/jinaai_jina-embeddings-v2-base-code-stackoverflow',
|
33 |
+
trust_remote_code=True
|
34 |
+
)
|
35 |
+
|
36 |
+
embeddings = model.encode([
|
37 |
+
'first text to embed',
|
38 |
+
'second text to embed'
|
39 |
+
])
|
40 |
+
print(cos_sim(embeddings[0], embeddings[1]))
|
41 |
+
```
|
config.json
ADDED
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"_name_or_path": "mytmp/finetuned_model",
|
3 |
+
"architectures": [
|
4 |
+
"JinaBertModel"
|
5 |
+
],
|
6 |
+
"attention_probs_dropout_prob": 0.0,
|
7 |
+
"attn_implementation": null,
|
8 |
+
"auto_map": {
|
9 |
+
"AutoConfig": "configuration_bert.JinaBertConfig",
|
10 |
+
"AutoModel": "modeling_bert.JinaBertModel",
|
11 |
+
"AutoModelForMaskedLM": "jinaai/jina-bert-v2-qk-post-norm--modeling_bert.JinaBertForMaskedLM",
|
12 |
+
"AutoModelForSequenceClassification": "jinaai/jina-bert-v2-qk-post-norm--modeling_bert.JinaBertForSequenceClassification"
|
13 |
+
},
|
14 |
+
"classifier_dropout": null,
|
15 |
+
"emb_pooler": "mean",
|
16 |
+
"feed_forward_type": "geglu",
|
17 |
+
"gradient_checkpointing": false,
|
18 |
+
"hidden_act": "gelu",
|
19 |
+
"hidden_dropout_prob": 0.0,
|
20 |
+
"hidden_size": 768,
|
21 |
+
"initializer_range": 0.02,
|
22 |
+
"intermediate_size": 3072,
|
23 |
+
"layer_norm_eps": 1e-12,
|
24 |
+
"max_position_embeddings": 8192,
|
25 |
+
"model_max_length": 8192,
|
26 |
+
"model_type": "bert",
|
27 |
+
"num_attention_heads": 12,
|
28 |
+
"num_hidden_layers": 12,
|
29 |
+
"pad_token_id": 0,
|
30 |
+
"position_embedding_type": "alibi",
|
31 |
+
"torch_dtype": "float32",
|
32 |
+
"transformers_version": "4.40.2",
|
33 |
+
"type_vocab_size": 2,
|
34 |
+
"use_cache": true,
|
35 |
+
"vocab_size": 61056
|
36 |
+
}
|
config_sentence_transformers.json
ADDED
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"__version__": {
|
3 |
+
"sentence_transformers": "2.7.0",
|
4 |
+
"transformers": "4.40.2",
|
5 |
+
"pytorch": "1.11.0+cpu"
|
6 |
+
},
|
7 |
+
"prompts": {},
|
8 |
+
"default_prompt_name": null
|
9 |
+
}
|
configuration_bert.py
ADDED
@@ -0,0 +1,177 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
|
3 |
+
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
|
4 |
+
# Copyright (c) 2023 Jina AI GmbH. All rights reserved.
|
5 |
+
#
|
6 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
7 |
+
# you may not use this file except in compliance with the License.
|
8 |
+
# You may obtain a copy of the License at
|
9 |
+
#
|
10 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
11 |
+
#
|
12 |
+
# Unless required by applicable law or agreed to in writing, software
|
13 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
14 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
15 |
+
# See the License for the specific language governing permissions and
|
16 |
+
# limitations under the License.
|
17 |
+
""" BERT model configuration"""
|
18 |
+
from collections import OrderedDict
|
19 |
+
from typing import Mapping
|
20 |
+
import warnings
|
21 |
+
|
22 |
+
from transformers.configuration_utils import PretrainedConfig
|
23 |
+
from transformers.utils import logging
|
24 |
+
|
25 |
+
try:
|
26 |
+
from optimum.exporters.onnx.model_configs import BertOnnxConfig
|
27 |
+
OPTIMUM_INSTALLED = True
|
28 |
+
except ImportError:
|
29 |
+
warnings.warn("optimum is not installed. To use OnnxConfig and BertOnnxConfig, make sure that `optimum` package is installed")
|
30 |
+
OPTIMUM_INSTALLED = False
|
31 |
+
|
32 |
+
|
33 |
+
logger = logging.get_logger(__name__)
|
34 |
+
|
35 |
+
|
36 |
+
class JinaBertConfig(PretrainedConfig):
|
37 |
+
r"""
|
38 |
+
This is the configuration class to store the configuration of a [`JinaBertModel`]. It is used to
|
39 |
+
instantiate a BERT model according to the specified arguments, defining the model architecture. Instantiating a
|
40 |
+
configuration with the defaults will yield a similar configuration to that of the BERT
|
41 |
+
[bert-base-uncased](https://huggingface.co/bert-base-uncased) architecture.
|
42 |
+
|
43 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
44 |
+
documentation from [`PretrainedConfig`] for more information.
|
45 |
+
|
46 |
+
|
47 |
+
Args:
|
48 |
+
vocab_size (`int`, *optional*, defaults to 30522):
|
49 |
+
Vocabulary size of the BERT model. Defines the number of different tokens that can be represented by the
|
50 |
+
`inputs_ids` passed when calling [`BertModel`] or [`TFBertModel`].
|
51 |
+
hidden_size (`int`, *optional*, defaults to 768):
|
52 |
+
Dimensionality of the encoder layers and the pooler layer.
|
53 |
+
num_hidden_layers (`int`, *optional*, defaults to 12):
|
54 |
+
Number of hidden layers in the Transformer encoder.
|
55 |
+
num_attention_heads (`int`, *optional*, defaults to 12):
|
56 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
57 |
+
intermediate_size (`int`, *optional*, defaults to 3072):
|
58 |
+
Dimensionality of the "intermediate" (often named feed-forward) layer in the Transformer encoder.
|
59 |
+
hidden_act (`str` or `Callable`, *optional*, defaults to `"gelu"`):
|
60 |
+
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
|
61 |
+
`"relu"`, `"silu"` and `"gelu_new"` are supported.
|
62 |
+
hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
|
63 |
+
The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
|
64 |
+
attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):
|
65 |
+
The dropout ratio for the attention probabilities.
|
66 |
+
max_position_embeddings (`int`, *optional*, defaults to 512):
|
67 |
+
The maximum sequence length that this model might ever be used with. Typically set this to something large
|
68 |
+
just in case (e.g., 512 or 1024 or 2048).
|
69 |
+
type_vocab_size (`int`, *optional*, defaults to 2):
|
70 |
+
The vocabulary size of the `token_type_ids` passed when calling [`BertModel`] or [`TFBertModel`].
|
71 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
72 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
73 |
+
layer_norm_eps (`float`, *optional*, defaults to 1e-12):
|
74 |
+
The epsilon used by the layer normalization layers.
|
75 |
+
position_embedding_type (`str`, *optional*, defaults to `"absolute"`):
|
76 |
+
Type of position embedding. Choose one of `"absolute"`, `"relative_key"`, `"relative_key_query"`. For
|
77 |
+
positional embeddings use `"absolute"`. For more information on `"relative_key"`, please refer to
|
78 |
+
[Self-Attention with Relative Position Representations (Shaw et al.)](https://arxiv.org/abs/1803.02155).
|
79 |
+
For more information on `"relative_key_query"`, please refer to *Method 4* in [Improve Transformer Models
|
80 |
+
with Better Relative Position Embeddings (Huang et al.)](https://arxiv.org/abs/2009.13658).
|
81 |
+
is_decoder (`bool`, *optional*, defaults to `False`):
|
82 |
+
Whether the model is used as a decoder or not. If `False`, the model is used as an encoder.
|
83 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
84 |
+
Whether or not the model should return the last key/values attentions (not used by all models). Only
|
85 |
+
relevant if `config.is_decoder=True`.
|
86 |
+
classifier_dropout (`float`, *optional*):
|
87 |
+
The dropout ratio for the classification head.
|
88 |
+
feed_forward_type (`str`, *optional*, defaults to `"original"`):
|
89 |
+
The type of feed forward layer to use in the bert layers.
|
90 |
+
Can be one of GLU variants, e.g. `"reglu"`, `"geglu"`
|
91 |
+
emb_pooler (`str`, *optional*, defaults to `None`):
|
92 |
+
The function to use for pooling the last layer embeddings to get the sentence embeddings.
|
93 |
+
Should be one of `None`, `"mean"`.
|
94 |
+
attn_implementation (`str`, *optional*, defaults to `"torch"`):
|
95 |
+
The implementation of the self-attention layer. Can be one of:
|
96 |
+
- `None` for the original implementation,
|
97 |
+
- `torch` for the PyTorch SDPA implementation,
|
98 |
+
|
99 |
+
Examples:
|
100 |
+
|
101 |
+
```python
|
102 |
+
>>> from transformers import JinaBertConfig, JinaBertModel
|
103 |
+
|
104 |
+
>>> # Initializing a JinaBert configuration
|
105 |
+
>>> configuration = JinaBertConfig()
|
106 |
+
|
107 |
+
>>> # Initializing a model (with random weights) from the configuration
|
108 |
+
>>> model = JinaBertModel(configuration)
|
109 |
+
|
110 |
+
>>> # Accessing the model configuration
|
111 |
+
>>> configuration = model.config
|
112 |
+
|
113 |
+
>>> # Encode text inputs
|
114 |
+
>>> embeddings = model.encode(text_inputs)
|
115 |
+
```"""
|
116 |
+
model_type = "bert"
|
117 |
+
|
118 |
+
def __init__(
|
119 |
+
self,
|
120 |
+
vocab_size=30522,
|
121 |
+
hidden_size=768,
|
122 |
+
num_hidden_layers=12,
|
123 |
+
num_attention_heads=12,
|
124 |
+
intermediate_size=3072,
|
125 |
+
hidden_act="gelu",
|
126 |
+
hidden_dropout_prob=0.1,
|
127 |
+
attention_probs_dropout_prob=0.1,
|
128 |
+
max_position_embeddings=512,
|
129 |
+
type_vocab_size=2,
|
130 |
+
initializer_range=0.02,
|
131 |
+
layer_norm_eps=1e-12,
|
132 |
+
pad_token_id=0,
|
133 |
+
position_embedding_type="absolute",
|
134 |
+
use_cache=True,
|
135 |
+
classifier_dropout=None,
|
136 |
+
feed_forward_type="original",
|
137 |
+
emb_pooler=None,
|
138 |
+
attn_implementation=None,
|
139 |
+
**kwargs,
|
140 |
+
):
|
141 |
+
super().__init__(pad_token_id=pad_token_id, **kwargs)
|
142 |
+
|
143 |
+
self.vocab_size = vocab_size
|
144 |
+
self.hidden_size = hidden_size
|
145 |
+
self.num_hidden_layers = num_hidden_layers
|
146 |
+
self.num_attention_heads = num_attention_heads
|
147 |
+
self.hidden_act = hidden_act
|
148 |
+
self.intermediate_size = intermediate_size
|
149 |
+
self.hidden_dropout_prob = hidden_dropout_prob
|
150 |
+
self.attention_probs_dropout_prob = attention_probs_dropout_prob
|
151 |
+
self.max_position_embeddings = max_position_embeddings
|
152 |
+
self.type_vocab_size = type_vocab_size
|
153 |
+
self.initializer_range = initializer_range
|
154 |
+
self.layer_norm_eps = layer_norm_eps
|
155 |
+
self.position_embedding_type = position_embedding_type
|
156 |
+
self.use_cache = use_cache
|
157 |
+
self.classifier_dropout = classifier_dropout
|
158 |
+
self.feed_forward_type = feed_forward_type
|
159 |
+
self.emb_pooler = emb_pooler
|
160 |
+
self.attn_implementation = attn_implementation
|
161 |
+
|
162 |
+
if OPTIMUM_INSTALLED:
|
163 |
+
|
164 |
+
class JinaBertOnnxConfig(BertOnnxConfig):
|
165 |
+
|
166 |
+
@property
|
167 |
+
def inputs(self) -> Mapping[str, Mapping[int, str]]:
|
168 |
+
if self.task == "multiple-choice":
|
169 |
+
dynamic_axis = {0: "batch", 1: "choice", 2: "sequence"}
|
170 |
+
else:
|
171 |
+
dynamic_axis = {0: "batch", 1: "sequence"}
|
172 |
+
return OrderedDict(
|
173 |
+
[
|
174 |
+
("input_ids", dynamic_axis),
|
175 |
+
("attention_mask", dynamic_axis),
|
176 |
+
]
|
177 |
+
)
|
merges.txt
ADDED
The diff for this file is too large to render.
See raw diff
|
|
model.safetensors
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:923cb8357c246175e47ae2f643a9cf8c84b132ccbad67cd6d4eb5b3f0d426543
|
3 |
+
size 643505600
|
modeling_bert.py
ADDED
@@ -0,0 +1,2312 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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=utf-8
|
2 |
+
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
|
3 |
+
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
|
4 |
+
# Copyright (c) 2023 Jina AI GmbH. All rights reserved.
|
5 |
+
#
|
6 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
7 |
+
# you may not use this file except in compliance with the License.
|
8 |
+
# You may obtain a copy of the License at
|
9 |
+
#
|
10 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
11 |
+
#
|
12 |
+
# Unless required by applicable law or agreed to in writing, software
|
13 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
14 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
15 |
+
# See the License for the specific language governing permissions and
|
16 |
+
# limitations under the License.
|
17 |
+
"""PyTorch BERT model."""
|
18 |
+
|
19 |
+
|
20 |
+
import math
|
21 |
+
import os
|
22 |
+
import warnings
|
23 |
+
from dataclasses import dataclass
|
24 |
+
from typing import List, Optional, Tuple, Union
|
25 |
+
import numpy as np
|
26 |
+
|
27 |
+
import torch
|
28 |
+
import torch.utils.checkpoint
|
29 |
+
from torch import nn
|
30 |
+
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
|
31 |
+
|
32 |
+
from transformers.activations import ACT2FN
|
33 |
+
from transformers.modeling_outputs import (
|
34 |
+
BaseModelOutputWithPastAndCrossAttentions,
|
35 |
+
BaseModelOutputWithPoolingAndCrossAttentions,
|
36 |
+
CausalLMOutputWithCrossAttentions,
|
37 |
+
MaskedLMOutput,
|
38 |
+
MultipleChoiceModelOutput,
|
39 |
+
NextSentencePredictorOutput,
|
40 |
+
QuestionAnsweringModelOutput,
|
41 |
+
SequenceClassifierOutput,
|
42 |
+
TokenClassifierOutput,
|
43 |
+
)
|
44 |
+
from transformers.modeling_utils import PreTrainedModel
|
45 |
+
from transformers.pytorch_utils import (
|
46 |
+
apply_chunking_to_forward,
|
47 |
+
find_pruneable_heads_and_indices,
|
48 |
+
prune_linear_layer,
|
49 |
+
)
|
50 |
+
from transformers.utils import (
|
51 |
+
ModelOutput,
|
52 |
+
add_code_sample_docstrings,
|
53 |
+
add_start_docstrings,
|
54 |
+
add_start_docstrings_to_model_forward,
|
55 |
+
logging,
|
56 |
+
replace_return_docstrings,
|
57 |
+
)
|
58 |
+
from .configuration_bert import JinaBertConfig
|
59 |
+
|
60 |
+
# Torch implementation
|
61 |
+
try:
|
62 |
+
from torch.nn.functional import scaled_dot_product_attention
|
63 |
+
except ImportError:
|
64 |
+
scaled_dot_product_attention = None
|
65 |
+
|
66 |
+
# This is used by encode but user may not have it installed
|
67 |
+
try:
|
68 |
+
from tqdm.autonotebook import trange
|
69 |
+
|
70 |
+
has_tqdm = True
|
71 |
+
except ImportError:
|
72 |
+
has_tqdm = False
|
73 |
+
|
74 |
+
logger = logging.get_logger(__name__)
|
75 |
+
|
76 |
+
_CHECKPOINT_FOR_DOC = "bert-base-uncased"
|
77 |
+
_CONFIG_FOR_DOC = "JinaBertConfig"
|
78 |
+
|
79 |
+
# TokenClassification docstring
|
80 |
+
_CHECKPOINT_FOR_TOKEN_CLASSIFICATION = (
|
81 |
+
"dbmdz/bert-large-cased-finetuned-conll03-english"
|
82 |
+
)
|
83 |
+
_TOKEN_CLASS_EXPECTED_OUTPUT = "['O', 'I-ORG', 'I-ORG', 'I-ORG', 'O', 'O', 'O', 'O', 'O', 'I-LOC', 'O', 'I-LOC', 'I-LOC'] "
|
84 |
+
_TOKEN_CLASS_EXPECTED_LOSS = 0.01
|
85 |
+
|
86 |
+
# QuestionAnswering docstring
|
87 |
+
_CHECKPOINT_FOR_QA = "deepset/bert-base-cased-squad2"
|
88 |
+
_QA_EXPECTED_OUTPUT = "'a nice puppet'"
|
89 |
+
_QA_EXPECTED_LOSS = 7.41
|
90 |
+
_QA_TARGET_START_INDEX = 14
|
91 |
+
_QA_TARGET_END_INDEX = 15
|
92 |
+
|
93 |
+
# SequenceClassification docstring
|
94 |
+
_CHECKPOINT_FOR_SEQUENCE_CLASSIFICATION = "textattack/bert-base-uncased-yelp-polarity"
|
95 |
+
_SEQ_CLASS_EXPECTED_OUTPUT = "'LABEL_1'"
|
96 |
+
_SEQ_CLASS_EXPECTED_LOSS = 0.01
|
97 |
+
|
98 |
+
|
99 |
+
def load_tf_weights_in_bert(model, config, tf_checkpoint_path):
|
100 |
+
"""Load tf checkpoints in a pytorch model."""
|
101 |
+
try:
|
102 |
+
import re
|
103 |
+
|
104 |
+
import numpy as np
|
105 |
+
import tensorflow as tf
|
106 |
+
except ImportError:
|
107 |
+
logger.error(
|
108 |
+
"Loading a TensorFlow model in PyTorch, requires TensorFlow to be installed. Please see "
|
109 |
+
"https://www.tensorflow.org/install/ for installation instructions."
|
110 |
+
)
|
111 |
+
raise
|
112 |
+
tf_path = os.path.abspath(tf_checkpoint_path)
|
113 |
+
logger.info(f"Converting TensorFlow checkpoint from {tf_path}")
|
114 |
+
# Load weights from TF model
|
115 |
+
init_vars = tf.train.list_variables(tf_path)
|
116 |
+
names = []
|
117 |
+
arrays = []
|
118 |
+
for name, shape in init_vars:
|
119 |
+
logger.info(f"Loading TF weight {name} with shape {shape}")
|
120 |
+
array = tf.train.load_variable(tf_path, name)
|
121 |
+
names.append(name)
|
122 |
+
arrays.append(array)
|
123 |
+
|
124 |
+
for name, array in zip(names, arrays):
|
125 |
+
name = name.split("/")
|
126 |
+
# adam_v and adam_m are variables used in AdamWeightDecayOptimizer to calculated m and v
|
127 |
+
# which are not required for using pretrained model
|
128 |
+
if any(
|
129 |
+
n
|
130 |
+
in [
|
131 |
+
"adam_v",
|
132 |
+
"adam_m",
|
133 |
+
"AdamWeightDecayOptimizer",
|
134 |
+
"AdamWeightDecayOptimizer_1",
|
135 |
+
"global_step",
|
136 |
+
]
|
137 |
+
for n in name
|
138 |
+
):
|
139 |
+
logger.info(f"Skipping {'/'.join(name)}")
|
140 |
+
continue
|
141 |
+
pointer = model
|
142 |
+
for m_name in name:
|
143 |
+
if re.fullmatch(r"[A-Za-z]+_\d+", m_name):
|
144 |
+
scope_names = re.split(r"_(\d+)", m_name)
|
145 |
+
else:
|
146 |
+
scope_names = [m_name]
|
147 |
+
if scope_names[0] == "kernel" or scope_names[0] == "gamma":
|
148 |
+
pointer = getattr(pointer, "weight")
|
149 |
+
elif scope_names[0] == "output_bias" or scope_names[0] == "beta":
|
150 |
+
pointer = getattr(pointer, "bias")
|
151 |
+
elif scope_names[0] == "output_weights":
|
152 |
+
pointer = getattr(pointer, "weight")
|
153 |
+
elif scope_names[0] == "squad":
|
154 |
+
pointer = getattr(pointer, "classifier")
|
155 |
+
else:
|
156 |
+
try:
|
157 |
+
pointer = getattr(pointer, scope_names[0])
|
158 |
+
except AttributeError:
|
159 |
+
logger.info(f"Skipping {'/'.join(name)}")
|
160 |
+
continue
|
161 |
+
if len(scope_names) >= 2:
|
162 |
+
num = int(scope_names[1])
|
163 |
+
pointer = pointer[num]
|
164 |
+
if m_name[-11:] == "_embeddings":
|
165 |
+
pointer = getattr(pointer, "weight")
|
166 |
+
elif m_name == "kernel":
|
167 |
+
array = np.transpose(array)
|
168 |
+
try:
|
169 |
+
if pointer.shape != array.shape:
|
170 |
+
raise ValueError(
|
171 |
+
f"Pointer shape {pointer.shape} and array shape {array.shape} mismatched"
|
172 |
+
)
|
173 |
+
except ValueError as e:
|
174 |
+
e.args += (pointer.shape, array.shape)
|
175 |
+
raise
|
176 |
+
logger.info(f"Initialize PyTorch weight {name}")
|
177 |
+
pointer.data = torch.from_numpy(array)
|
178 |
+
return model
|
179 |
+
|
180 |
+
|
181 |
+
class JinaBertEmbeddings(nn.Module):
|
182 |
+
"""Construct the embeddings from word, position and token_type embeddings."""
|
183 |
+
|
184 |
+
def __init__(self, config: JinaBertConfig):
|
185 |
+
super().__init__()
|
186 |
+
self.word_embeddings = nn.Embedding(
|
187 |
+
config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id
|
188 |
+
)
|
189 |
+
if config.position_embedding_type != "alibi":
|
190 |
+
self.position_embeddings = nn.Embedding(
|
191 |
+
config.max_position_embeddings, config.hidden_size
|
192 |
+
)
|
193 |
+
self.token_type_embeddings = nn.Embedding(
|
194 |
+
config.type_vocab_size, config.hidden_size
|
195 |
+
)
|
196 |
+
|
197 |
+
# self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load
|
198 |
+
# any TensorFlow checkpoint file
|
199 |
+
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
200 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
201 |
+
# position_ids (1, len position emb) is contiguous in memory and exported when serialized
|
202 |
+
self.position_embedding_type = getattr(
|
203 |
+
config, "position_embedding_type", "absolute"
|
204 |
+
)
|
205 |
+
self.register_buffer(
|
206 |
+
"position_ids",
|
207 |
+
torch.arange(config.max_position_embeddings).expand((1, -1)),
|
208 |
+
persistent=False,
|
209 |
+
)
|
210 |
+
self.register_buffer(
|
211 |
+
"token_type_ids",
|
212 |
+
torch.zeros(self.position_ids.size(), dtype=torch.long),
|
213 |
+
persistent=False,
|
214 |
+
)
|
215 |
+
|
216 |
+
def forward(
|
217 |
+
self,
|
218 |
+
input_ids: Optional[torch.LongTensor] = None,
|
219 |
+
token_type_ids: Optional[torch.LongTensor] = None,
|
220 |
+
position_ids: Optional[torch.LongTensor] = None,
|
221 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
222 |
+
past_key_values_length: int = 0,
|
223 |
+
) -> torch.Tensor:
|
224 |
+
if input_ids is not None:
|
225 |
+
input_shape = input_ids.size()
|
226 |
+
else:
|
227 |
+
input_shape = inputs_embeds.size()[:-1]
|
228 |
+
|
229 |
+
seq_length = input_shape[1]
|
230 |
+
|
231 |
+
if position_ids is None:
|
232 |
+
position_ids = self.position_ids[
|
233 |
+
:, past_key_values_length : seq_length + past_key_values_length
|
234 |
+
]
|
235 |
+
|
236 |
+
# Setting the token_type_ids to the registered buffer in constructor where it is all zeros, which usually occurs
|
237 |
+
# when its auto-generated, registered buffer helps users when tracing the model without passing token_type_ids, solves
|
238 |
+
# issue #5664
|
239 |
+
if token_type_ids is None:
|
240 |
+
if hasattr(self, "token_type_ids"):
|
241 |
+
buffered_token_type_ids = self.token_type_ids[:, :seq_length]
|
242 |
+
buffered_token_type_ids_expanded = buffered_token_type_ids.expand(
|
243 |
+
input_shape[0], seq_length
|
244 |
+
)
|
245 |
+
token_type_ids = buffered_token_type_ids_expanded
|
246 |
+
else:
|
247 |
+
token_type_ids = torch.zeros(
|
248 |
+
input_shape, dtype=torch.long, device=self.position_ids.device
|
249 |
+
)
|
250 |
+
|
251 |
+
if inputs_embeds is None:
|
252 |
+
inputs_embeds = self.word_embeddings(input_ids)
|
253 |
+
token_type_embeddings = self.token_type_embeddings(token_type_ids)
|
254 |
+
|
255 |
+
embeddings = inputs_embeds + token_type_embeddings
|
256 |
+
if self.position_embedding_type == "absolute":
|
257 |
+
position_embeddings = self.position_embeddings(position_ids)
|
258 |
+
embeddings += position_embeddings
|
259 |
+
embeddings = self.LayerNorm(embeddings)
|
260 |
+
embeddings = self.dropout(embeddings)
|
261 |
+
return embeddings
|
262 |
+
|
263 |
+
|
264 |
+
class JinaBertSelfAttention(nn.Module):
|
265 |
+
def __init__(self, config: JinaBertConfig, position_embedding_type=None):
|
266 |
+
super().__init__()
|
267 |
+
if config.hidden_size % config.num_attention_heads != 0 and not hasattr(
|
268 |
+
config, "embedding_size"
|
269 |
+
):
|
270 |
+
raise ValueError(
|
271 |
+
f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
|
272 |
+
f"heads ({config.num_attention_heads})"
|
273 |
+
)
|
274 |
+
|
275 |
+
self.attn_implementation = config.attn_implementation
|
276 |
+
self.num_attention_heads = config.num_attention_heads
|
277 |
+
self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
|
278 |
+
self.all_head_size = self.num_attention_heads * self.attention_head_size
|
279 |
+
|
280 |
+
self.query = nn.Linear(config.hidden_size, self.all_head_size)
|
281 |
+
self.key = nn.Linear(config.hidden_size, self.all_head_size)
|
282 |
+
self.value = nn.Linear(config.hidden_size, self.all_head_size)
|
283 |
+
self.layer_norm_q = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
284 |
+
self.layer_norm_k = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
285 |
+
|
286 |
+
self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
|
287 |
+
self.position_embedding_type = position_embedding_type or getattr(
|
288 |
+
config, "position_embedding_type", "absolute"
|
289 |
+
)
|
290 |
+
if (
|
291 |
+
self.position_embedding_type == "relative_key"
|
292 |
+
or self.position_embedding_type == "relative_key_query"
|
293 |
+
):
|
294 |
+
self.max_position_embeddings = config.max_position_embeddings
|
295 |
+
self.distance_embedding = nn.Embedding(
|
296 |
+
2 * config.max_position_embeddings - 1, self.attention_head_size
|
297 |
+
)
|
298 |
+
|
299 |
+
self.is_decoder = config.is_decoder
|
300 |
+
|
301 |
+
def transpose_for_scores(self, x: torch.Tensor) -> torch.Tensor:
|
302 |
+
new_x_shape = x.size()[:-1] + (
|
303 |
+
self.num_attention_heads,
|
304 |
+
self.attention_head_size,
|
305 |
+
)
|
306 |
+
x = x.view(new_x_shape)
|
307 |
+
return x.permute(0, 2, 1, 3)
|
308 |
+
|
309 |
+
def forward(
|
310 |
+
self,
|
311 |
+
hidden_states: torch.Tensor,
|
312 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
313 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
314 |
+
encoder_hidden_states: Optional[torch.FloatTensor] = None,
|
315 |
+
encoder_attention_mask: Optional[torch.FloatTensor] = None,
|
316 |
+
past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
|
317 |
+
output_attentions: Optional[bool] = False,
|
318 |
+
bias: Optional[torch.FloatTensor] = None,
|
319 |
+
) -> Tuple[torch.Tensor]:
|
320 |
+
mixed_query_layer = self.layer_norm_q(self.query(hidden_states))
|
321 |
+
|
322 |
+
# If this is instantiated as a cross-attention module, the keys
|
323 |
+
# and values come from an encoder; the attention mask needs to be
|
324 |
+
# such that the encoder's padding tokens are not attended to.
|
325 |
+
is_cross_attention = encoder_hidden_states is not None
|
326 |
+
|
327 |
+
if is_cross_attention and past_key_value is not None:
|
328 |
+
# reuse k,v, cross_attentions
|
329 |
+
key_layer = past_key_value[0]
|
330 |
+
value_layer = past_key_value[1]
|
331 |
+
attention_mask = encoder_attention_mask
|
332 |
+
elif is_cross_attention:
|
333 |
+
key_layer = self.transpose_for_scores(self.layer_norm_k(self.key(encoder_hidden_states)))
|
334 |
+
value_layer = self.transpose_for_scores(self.value(encoder_hidden_states))
|
335 |
+
attention_mask = encoder_attention_mask
|
336 |
+
elif past_key_value is not None:
|
337 |
+
key_layer = self.transpose_for_scores(self.layer_norm_k(self.key(hidden_states)))
|
338 |
+
value_layer = self.transpose_for_scores(self.value(hidden_states))
|
339 |
+
key_layer = torch.cat([past_key_value[0], key_layer], dim=2)
|
340 |
+
value_layer = torch.cat([past_key_value[1], value_layer], dim=2)
|
341 |
+
else:
|
342 |
+
key_layer = self.transpose_for_scores(self.layer_norm_k(self.key(hidden_states)))
|
343 |
+
value_layer = self.transpose_for_scores(self.value(hidden_states))
|
344 |
+
|
345 |
+
query_layer = self.transpose_for_scores(mixed_query_layer)
|
346 |
+
|
347 |
+
use_cache = past_key_value is not None
|
348 |
+
if self.is_decoder:
|
349 |
+
# if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states.
|
350 |
+
# Further calls to cross_attention layer can then reuse all cross-attention
|
351 |
+
# key/value_states (first "if" case)
|
352 |
+
# if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of
|
353 |
+
# all previous decoder key/value_states. Further calls to uni-directional self-attention
|
354 |
+
# can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
|
355 |
+
# if encoder bi-directional self-attention `past_key_value` is always `None`
|
356 |
+
past_key_value = (key_layer, value_layer)
|
357 |
+
|
358 |
+
if self.attn_implementation == 'torch' and scaled_dot_product_attention is not None:
|
359 |
+
b, _, s, _ = query_layer.shape
|
360 |
+
new_bias = attention_mask + bias
|
361 |
+
attn = scaled_dot_product_attention(query_layer, key_layer, value_layer, new_bias)
|
362 |
+
attn = attn.permute(0, 2, 1, 3).contiguous()
|
363 |
+
return (attn.view(b, s, self.all_head_size),)
|
364 |
+
|
365 |
+
# Take the dot product between "query" and "key" to get the raw attention scores.
|
366 |
+
attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
|
367 |
+
|
368 |
+
if (
|
369 |
+
self.position_embedding_type == "relative_key"
|
370 |
+
or self.position_embedding_type == "relative_key_query"
|
371 |
+
):
|
372 |
+
query_length, key_length = query_layer.shape[2], key_layer.shape[2]
|
373 |
+
if use_cache:
|
374 |
+
position_ids_l = torch.tensor(
|
375 |
+
key_length - 1, dtype=torch.long, device=hidden_states.device
|
376 |
+
).view(-1, 1)
|
377 |
+
else:
|
378 |
+
position_ids_l = torch.arange(
|
379 |
+
query_length, dtype=torch.long, device=hidden_states.device
|
380 |
+
).view(-1, 1)
|
381 |
+
position_ids_r = torch.arange(
|
382 |
+
key_length, dtype=torch.long, device=hidden_states.device
|
383 |
+
).view(1, -1)
|
384 |
+
distance = position_ids_l - position_ids_r
|
385 |
+
|
386 |
+
positional_embedding = self.distance_embedding(
|
387 |
+
distance + self.max_position_embeddings - 1
|
388 |
+
)
|
389 |
+
positional_embedding = positional_embedding.to(
|
390 |
+
dtype=query_layer.dtype
|
391 |
+
) # fp16 compatibility
|
392 |
+
|
393 |
+
if self.position_embedding_type == "relative_key":
|
394 |
+
relative_position_scores = torch.einsum(
|
395 |
+
"bhld,lrd->bhlr", query_layer, positional_embedding
|
396 |
+
)
|
397 |
+
attention_scores = attention_scores + relative_position_scores
|
398 |
+
elif self.position_embedding_type == "relative_key_query":
|
399 |
+
relative_position_scores_query = torch.einsum(
|
400 |
+
"bhld,lrd->bhlr", query_layer, positional_embedding
|
401 |
+
)
|
402 |
+
relative_position_scores_key = torch.einsum(
|
403 |
+
"bhrd,lrd->bhlr", key_layer, positional_embedding
|
404 |
+
)
|
405 |
+
attention_scores = (
|
406 |
+
attention_scores
|
407 |
+
+ relative_position_scores_query
|
408 |
+
+ relative_position_scores_key
|
409 |
+
)
|
410 |
+
|
411 |
+
attention_scores = attention_scores / math.sqrt(self.attention_head_size)
|
412 |
+
if attention_mask is not None:
|
413 |
+
# Apply the attention mask is (precomputed for all layers in BertModel forward() function)
|
414 |
+
attention_scores = attention_scores + attention_mask
|
415 |
+
|
416 |
+
# Normalize the attention scores to probabilities.
|
417 |
+
attention_probs = nn.functional.softmax(attention_scores + bias, dim=-1)
|
418 |
+
|
419 |
+
# This is actually dropping out entire tokens to attend to, which might
|
420 |
+
# seem a bit unusual, but is taken from the original Transformer paper.
|
421 |
+
attention_probs = self.dropout(attention_probs)
|
422 |
+
|
423 |
+
# Mask heads if we want to
|
424 |
+
if head_mask is not None:
|
425 |
+
attention_probs = attention_probs * head_mask
|
426 |
+
|
427 |
+
context_layer = torch.matmul(attention_probs, value_layer)
|
428 |
+
|
429 |
+
context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
|
430 |
+
new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
|
431 |
+
context_layer = context_layer.view(new_context_layer_shape)
|
432 |
+
|
433 |
+
outputs = (
|
434 |
+
(context_layer, attention_scores) if output_attentions else (context_layer,)
|
435 |
+
)
|
436 |
+
|
437 |
+
if self.is_decoder:
|
438 |
+
outputs = outputs + (past_key_value,)
|
439 |
+
return outputs
|
440 |
+
|
441 |
+
|
442 |
+
class JinaBertSelfOutput(nn.Module):
|
443 |
+
def __init__(self, config):
|
444 |
+
super().__init__()
|
445 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
446 |
+
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
447 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
448 |
+
|
449 |
+
def forward(
|
450 |
+
self, hidden_states: torch.Tensor, input_tensor: torch.Tensor
|
451 |
+
) -> torch.Tensor:
|
452 |
+
hidden_states = self.dense(hidden_states)
|
453 |
+
hidden_states = self.dropout(hidden_states)
|
454 |
+
hidden_states = self.LayerNorm(hidden_states + input_tensor)
|
455 |
+
return hidden_states
|
456 |
+
|
457 |
+
|
458 |
+
class JinaBertAttention(nn.Module):
|
459 |
+
def __init__(self, config, position_embedding_type=None):
|
460 |
+
super().__init__()
|
461 |
+
self.self = JinaBertSelfAttention(
|
462 |
+
config, position_embedding_type=position_embedding_type
|
463 |
+
)
|
464 |
+
self.output = JinaBertSelfOutput(config)
|
465 |
+
self.pruned_heads = set()
|
466 |
+
|
467 |
+
def prune_heads(self, heads):
|
468 |
+
if len(heads) == 0:
|
469 |
+
return
|
470 |
+
heads, index = find_pruneable_heads_and_indices(
|
471 |
+
heads,
|
472 |
+
self.self.num_attention_heads,
|
473 |
+
self.self.attention_head_size,
|
474 |
+
self.pruned_heads,
|
475 |
+
)
|
476 |
+
|
477 |
+
# Prune linear layers
|
478 |
+
self.self.query = prune_linear_layer(self.self.query, index)
|
479 |
+
self.self.key = prune_linear_layer(self.self.key, index)
|
480 |
+
self.self.value = prune_linear_layer(self.self.value, index)
|
481 |
+
self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
|
482 |
+
|
483 |
+
# Update hyper params and store pruned heads
|
484 |
+
self.self.num_attention_heads = self.self.num_attention_heads - len(heads)
|
485 |
+
self.self.all_head_size = (
|
486 |
+
self.self.attention_head_size * self.self.num_attention_heads
|
487 |
+
)
|
488 |
+
self.pruned_heads = self.pruned_heads.union(heads)
|
489 |
+
|
490 |
+
def forward(
|
491 |
+
self,
|
492 |
+
hidden_states: torch.Tensor,
|
493 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
494 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
495 |
+
encoder_hidden_states: Optional[torch.FloatTensor] = None,
|
496 |
+
encoder_attention_mask: Optional[torch.FloatTensor] = None,
|
497 |
+
past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
|
498 |
+
output_attentions: Optional[bool] = False,
|
499 |
+
bias: Optional[torch.FloatTensor] = None,
|
500 |
+
) -> Tuple[torch.Tensor]:
|
501 |
+
self_outputs = self.self(
|
502 |
+
hidden_states,
|
503 |
+
attention_mask,
|
504 |
+
head_mask,
|
505 |
+
encoder_hidden_states,
|
506 |
+
encoder_attention_mask,
|
507 |
+
past_key_value,
|
508 |
+
output_attentions,
|
509 |
+
bias,
|
510 |
+
)
|
511 |
+
attention_output = self.output(self_outputs[0], hidden_states)
|
512 |
+
outputs = (attention_output,) + self_outputs[
|
513 |
+
1:
|
514 |
+
] # add attentions if we output them
|
515 |
+
return outputs
|
516 |
+
|
517 |
+
|
518 |
+
class JinaBertMLP(nn.Module):
|
519 |
+
def __init__(self, config: JinaBertConfig):
|
520 |
+
super().__init__()
|
521 |
+
self.config = config
|
522 |
+
self.act = ACT2FN[config.hidden_act]
|
523 |
+
self.up_layer = nn.Linear(
|
524 |
+
config.hidden_size, config.intermediate_size, bias=False
|
525 |
+
)
|
526 |
+
self.down_layer = nn.Linear(config.intermediate_size, config.hidden_size)
|
527 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
528 |
+
|
529 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
530 |
+
# Up
|
531 |
+
hidden_mlp_states = self.act(self.up_layer(hidden_states))
|
532 |
+
hidden_mlp_states = self.dropout(hidden_mlp_states)
|
533 |
+
# Down
|
534 |
+
return self.down_layer(hidden_mlp_states)
|
535 |
+
|
536 |
+
|
537 |
+
class JinaBertGLUMLP(nn.Module):
|
538 |
+
def __init__(self, config: JinaBertConfig):
|
539 |
+
super().__init__()
|
540 |
+
self.config = config
|
541 |
+
if config.feed_forward_type == 'reglu':
|
542 |
+
self.act = nn.ReLU()
|
543 |
+
elif config.feed_forward_type == 'geglu':
|
544 |
+
self.act = nn.GELU()
|
545 |
+
else:
|
546 |
+
raise ValueError(
|
547 |
+
f"feed_forward_type {config.feed_forward_type} not supported"
|
548 |
+
)
|
549 |
+
self.up_gated_layer = nn.Linear(
|
550 |
+
config.hidden_size, config.intermediate_size * 2, bias=False
|
551 |
+
)
|
552 |
+
self.down_layer = nn.Linear(config.intermediate_size, config.hidden_size)
|
553 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
554 |
+
|
555 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
556 |
+
# Up with gate
|
557 |
+
hidden_mlp_states = self.up_gated_layer(hidden_states)
|
558 |
+
up = hidden_mlp_states[:, :, :self.config.intermediate_size]
|
559 |
+
gated = hidden_mlp_states[:, :, self.config.intermediate_size:]
|
560 |
+
hidden_mlp_states = up * self.act(gated)
|
561 |
+
hidden_mlp_states = self.dropout(hidden_mlp_states)
|
562 |
+
# Down
|
563 |
+
return self.down_layer(hidden_mlp_states)
|
564 |
+
|
565 |
+
|
566 |
+
class JinaBertLayer(nn.Module):
|
567 |
+
def __init__(self, config: JinaBertConfig):
|
568 |
+
super().__init__()
|
569 |
+
self.chunk_size_feed_forward = config.chunk_size_feed_forward
|
570 |
+
self.seq_len_dim = 1
|
571 |
+
self.attention = JinaBertAttention(config)
|
572 |
+
self.is_decoder = config.is_decoder
|
573 |
+
self.add_cross_attention = config.add_cross_attention
|
574 |
+
self.feed_forward_type = config.feed_forward_type
|
575 |
+
self.layer_norm_1 = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
576 |
+
self.layer_norm_2 = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
577 |
+
if self.add_cross_attention:
|
578 |
+
if not self.is_decoder:
|
579 |
+
raise ValueError(
|
580 |
+
f"{self} should be used as a decoder model if cross attention is added"
|
581 |
+
)
|
582 |
+
self.crossattention = JinaBertAttention(
|
583 |
+
config, position_embedding_type="absolute"
|
584 |
+
)
|
585 |
+
if self.feed_forward_type.endswith('glu'):
|
586 |
+
self.mlp = JinaBertGLUMLP(config)
|
587 |
+
else:
|
588 |
+
self.mlp = JinaBertMLP(config)
|
589 |
+
|
590 |
+
def forward(
|
591 |
+
self,
|
592 |
+
hidden_states: torch.Tensor,
|
593 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
594 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
595 |
+
encoder_hidden_states: Optional[torch.FloatTensor] = None,
|
596 |
+
encoder_attention_mask: Optional[torch.FloatTensor] = None,
|
597 |
+
bias: Optional[torch.FloatTensor] = None,
|
598 |
+
past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
|
599 |
+
output_attentions: Optional[bool] = False,
|
600 |
+
) -> Tuple[torch.Tensor]:
|
601 |
+
# Pre-Norm
|
602 |
+
residual = hidden_states
|
603 |
+
|
604 |
+
# decoder uni-directional self-attention cached key/values tuple is at positions 1,2
|
605 |
+
self_attn_past_key_value = (
|
606 |
+
past_key_value[:2] if past_key_value is not None else None
|
607 |
+
)
|
608 |
+
self_attention_outputs = self.attention(
|
609 |
+
hidden_states,
|
610 |
+
attention_mask,
|
611 |
+
head_mask,
|
612 |
+
output_attentions=output_attentions,
|
613 |
+
past_key_value=self_attn_past_key_value,
|
614 |
+
bias=bias,
|
615 |
+
)
|
616 |
+
attention_output = self_attention_outputs[0]
|
617 |
+
|
618 |
+
# if decoder, the last output is tuple of self-attn cache
|
619 |
+
if self.is_decoder:
|
620 |
+
outputs = self_attention_outputs[1:-1]
|
621 |
+
present_key_value = self_attention_outputs[-1]
|
622 |
+
else:
|
623 |
+
outputs = self_attention_outputs[
|
624 |
+
1:
|
625 |
+
] # add self attentions if we output attention weights
|
626 |
+
|
627 |
+
cross_attn_present_key_value = None
|
628 |
+
if self.is_decoder and encoder_hidden_states is not None:
|
629 |
+
if not hasattr(self, "crossattention"):
|
630 |
+
raise ValueError(
|
631 |
+
f"If `encoder_hidden_states` are passed, {self} has to be instantiated with cross-attention layers"
|
632 |
+
" by setting `config.add_cross_attention=True`"
|
633 |
+
)
|
634 |
+
|
635 |
+
# cross_attn cached key/values tuple is at positions 3,4 of past_key_value tuple
|
636 |
+
cross_attn_past_key_value = (
|
637 |
+
past_key_value[-2:] if past_key_value is not None else None
|
638 |
+
)
|
639 |
+
cross_attention_outputs = self.crossattention(
|
640 |
+
attention_output,
|
641 |
+
attention_mask,
|
642 |
+
head_mask,
|
643 |
+
encoder_hidden_states,
|
644 |
+
encoder_attention_mask,
|
645 |
+
cross_attn_past_key_value,
|
646 |
+
output_attentions,
|
647 |
+
)
|
648 |
+
attention_output = cross_attention_outputs[0]
|
649 |
+
outputs = (
|
650 |
+
outputs + cross_attention_outputs[1:-1]
|
651 |
+
) # add cross attentions if we output attention weights
|
652 |
+
|
653 |
+
# add cross-attn cache to positions 3,4 of present_key_value tuple
|
654 |
+
cross_attn_present_key_value = cross_attention_outputs[-1]
|
655 |
+
present_key_value = present_key_value + cross_attn_present_key_value
|
656 |
+
|
657 |
+
residual = self.layer_norm_1(residual + attention_output)
|
658 |
+
mlp_output = self.mlp(residual)
|
659 |
+
layer_output = self.layer_norm_2(residual + mlp_output)
|
660 |
+
outputs = (layer_output,) + outputs
|
661 |
+
|
662 |
+
# if decoder, return the attn key/values as the last output
|
663 |
+
if self.is_decoder:
|
664 |
+
outputs = outputs + (present_key_value,)
|
665 |
+
|
666 |
+
return outputs
|
667 |
+
|
668 |
+
|
669 |
+
class JinaBertEncoder(nn.Module):
|
670 |
+
def __init__(self, config: JinaBertConfig):
|
671 |
+
super().__init__()
|
672 |
+
self.config = config
|
673 |
+
self.layer = nn.ModuleList(
|
674 |
+
[JinaBertLayer(config) for _ in range(config.num_hidden_layers)]
|
675 |
+
)
|
676 |
+
self.gradient_checkpointing = False
|
677 |
+
self.num_attention_heads = config.num_attention_heads
|
678 |
+
|
679 |
+
def rebuild_alibi_tensor(
|
680 |
+
self, size: int, device: Optional[Union[torch.device, str]] = None
|
681 |
+
):
|
682 |
+
# Alibi
|
683 |
+
# Following https://github.com/ofirpress/attention_with_linear_biases/issues/5 (Implementation 1)
|
684 |
+
# In the causal case, you can exploit the fact that softmax is invariant to a uniform translation
|
685 |
+
# of the logits, which makes the math work out *after* applying causal masking. If no causal masking
|
686 |
+
# will be applied, it is necessary to construct the diagonal mask.
|
687 |
+
n_heads = self.num_attention_heads
|
688 |
+
|
689 |
+
def _get_alibi_head_slopes(n_heads: int) -> List[float]:
|
690 |
+
def get_slopes_power_of_2(n):
|
691 |
+
start = 2 ** (-(2 ** -(math.log2(n) - 3)))
|
692 |
+
ratio = start
|
693 |
+
return [start * ratio**i for i in range(n)]
|
694 |
+
|
695 |
+
if math.log2(n_heads).is_integer():
|
696 |
+
return get_slopes_power_of_2(
|
697 |
+
n_heads
|
698 |
+
) # In the paper, we only train models that have 2^a heads for some a. This function has
|
699 |
+
else: # some good properties that only occur when the input is a power of 2. To maintain that even
|
700 |
+
closest_power_of_2 = 2 ** math.floor(
|
701 |
+
math.log2(n_heads)
|
702 |
+
) # when the number of heads is not a power of 2, we use this workaround.
|
703 |
+
return (
|
704 |
+
get_slopes_power_of_2(closest_power_of_2)
|
705 |
+
+ _get_alibi_head_slopes(2 * closest_power_of_2)[0::2][
|
706 |
+
: n_heads - closest_power_of_2
|
707 |
+
]
|
708 |
+
)
|
709 |
+
|
710 |
+
context_position = torch.arange(size, device=device)[:, None]
|
711 |
+
memory_position = torch.arange(size, device=device)[None, :]
|
712 |
+
relative_position = torch.abs(memory_position - context_position)
|
713 |
+
# [n_heads, max_token_length, max_token_length]
|
714 |
+
relative_position = relative_position.unsqueeze(0).expand(n_heads, -1, -1)
|
715 |
+
slopes = torch.Tensor(_get_alibi_head_slopes(n_heads)).to(device) * -1
|
716 |
+
alibi = slopes.unsqueeze(1).unsqueeze(1) * relative_position
|
717 |
+
# [1, n_heads, max_token_length, max_token_length]
|
718 |
+
alibi = alibi.unsqueeze(0)
|
719 |
+
assert alibi.shape == torch.Size([1, n_heads, size, size])
|
720 |
+
|
721 |
+
self._current_alibi_size = size
|
722 |
+
return alibi
|
723 |
+
|
724 |
+
def forward(
|
725 |
+
self,
|
726 |
+
hidden_states: torch.Tensor,
|
727 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
728 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
729 |
+
encoder_hidden_states: Optional[torch.FloatTensor] = None,
|
730 |
+
encoder_attention_mask: Optional[torch.FloatTensor] = None,
|
731 |
+
past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
|
732 |
+
use_cache: Optional[bool] = None,
|
733 |
+
output_attentions: Optional[bool] = False,
|
734 |
+
output_hidden_states: Optional[bool] = False,
|
735 |
+
return_dict: Optional[bool] = True,
|
736 |
+
) -> Union[Tuple[torch.Tensor], BaseModelOutputWithPastAndCrossAttentions]:
|
737 |
+
all_hidden_states = () if output_hidden_states else None
|
738 |
+
all_self_attentions = () if output_attentions else None
|
739 |
+
all_cross_attentions = (
|
740 |
+
() if output_attentions and self.config.add_cross_attention else None
|
741 |
+
)
|
742 |
+
|
743 |
+
# Add alibi matrix to extended_attention_mask
|
744 |
+
_, seqlen, _ = hidden_states.size()
|
745 |
+
alibi_bias = self.rebuild_alibi_tensor(size=seqlen, device=hidden_states.device).to(hidden_states.dtype)
|
746 |
+
if self.gradient_checkpointing and self.training:
|
747 |
+
if use_cache:
|
748 |
+
logger.warning_once(
|
749 |
+
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
|
750 |
+
)
|
751 |
+
use_cache = False
|
752 |
+
|
753 |
+
next_decoder_cache = () if use_cache else None
|
754 |
+
for i, layer_module in enumerate(self.layer):
|
755 |
+
if output_hidden_states:
|
756 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
757 |
+
|
758 |
+
layer_head_mask = head_mask[i] if head_mask is not None else None
|
759 |
+
past_key_value = past_key_values[i] if past_key_values is not None else None
|
760 |
+
|
761 |
+
if self.gradient_checkpointing and self.training:
|
762 |
+
|
763 |
+
def create_custom_forward(module):
|
764 |
+
def custom_forward(*inputs):
|
765 |
+
return module(*inputs, past_key_value, output_attentions)
|
766 |
+
|
767 |
+
return custom_forward
|
768 |
+
|
769 |
+
layer_outputs = torch.utils.checkpoint.checkpoint(
|
770 |
+
create_custom_forward(layer_module),
|
771 |
+
hidden_states,
|
772 |
+
attention_mask,
|
773 |
+
layer_head_mask,
|
774 |
+
encoder_hidden_states,
|
775 |
+
encoder_attention_mask,
|
776 |
+
alibi_bias,
|
777 |
+
)
|
778 |
+
else:
|
779 |
+
layer_outputs = layer_module(
|
780 |
+
hidden_states,
|
781 |
+
attention_mask,
|
782 |
+
layer_head_mask,
|
783 |
+
encoder_hidden_states,
|
784 |
+
encoder_attention_mask,
|
785 |
+
alibi_bias,
|
786 |
+
past_key_value,
|
787 |
+
output_attentions,
|
788 |
+
)
|
789 |
+
|
790 |
+
hidden_states = layer_outputs[0]
|
791 |
+
if use_cache:
|
792 |
+
next_decoder_cache += (layer_outputs[-1],)
|
793 |
+
if output_attentions:
|
794 |
+
all_self_attentions = all_self_attentions + (layer_outputs[1],)
|
795 |
+
if self.config.add_cross_attention:
|
796 |
+
all_cross_attentions = all_cross_attentions + (layer_outputs[2],)
|
797 |
+
|
798 |
+
if output_hidden_states:
|
799 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
800 |
+
|
801 |
+
if not return_dict:
|
802 |
+
return tuple(
|
803 |
+
v
|
804 |
+
for v in [
|
805 |
+
hidden_states,
|
806 |
+
next_decoder_cache,
|
807 |
+
all_hidden_states,
|
808 |
+
all_self_attentions,
|
809 |
+
all_cross_attentions,
|
810 |
+
]
|
811 |
+
if v is not None
|
812 |
+
)
|
813 |
+
return BaseModelOutputWithPastAndCrossAttentions(
|
814 |
+
last_hidden_state=hidden_states,
|
815 |
+
past_key_values=next_decoder_cache,
|
816 |
+
hidden_states=all_hidden_states,
|
817 |
+
attentions=all_self_attentions,
|
818 |
+
cross_attentions=all_cross_attentions,
|
819 |
+
)
|
820 |
+
|
821 |
+
|
822 |
+
class JinaBertPooler(nn.Module):
|
823 |
+
def __init__(self, config):
|
824 |
+
super().__init__()
|
825 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
826 |
+
self.activation = nn.Tanh()
|
827 |
+
|
828 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
829 |
+
# We "pool" the model by simply taking the hidden state corresponding
|
830 |
+
# to the first token.
|
831 |
+
first_token_tensor = hidden_states[:, 0]
|
832 |
+
pooled_output = self.dense(first_token_tensor)
|
833 |
+
pooled_output = self.activation(pooled_output)
|
834 |
+
return pooled_output
|
835 |
+
|
836 |
+
|
837 |
+
class JinaBertPredictionHeadTransform(nn.Module):
|
838 |
+
def __init__(self, config):
|
839 |
+
super().__init__()
|
840 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
841 |
+
if isinstance(config.hidden_act, str):
|
842 |
+
self.transform_act_fn = ACT2FN[config.hidden_act]
|
843 |
+
else:
|
844 |
+
self.transform_act_fn = config.hidden_act
|
845 |
+
self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
846 |
+
|
847 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
848 |
+
hidden_states = self.dense(hidden_states)
|
849 |
+
hidden_states = self.transform_act_fn(hidden_states)
|
850 |
+
hidden_states = self.LayerNorm(hidden_states)
|
851 |
+
return hidden_states
|
852 |
+
|
853 |
+
|
854 |
+
class JinaBertLMPredictionHead(nn.Module):
|
855 |
+
def __init__(self, config):
|
856 |
+
super().__init__()
|
857 |
+
self.transform = JinaBertPredictionHeadTransform(config)
|
858 |
+
|
859 |
+
# The output weights are the same as the input embeddings, but there is
|
860 |
+
# an output-only bias for each token.
|
861 |
+
self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
862 |
+
|
863 |
+
self.bias = nn.Parameter(torch.zeros(config.vocab_size))
|
864 |
+
|
865 |
+
# Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings`
|
866 |
+
self.decoder.bias = self.bias
|
867 |
+
|
868 |
+
def forward(self, hidden_states):
|
869 |
+
hidden_states = self.transform(hidden_states)
|
870 |
+
hidden_states = self.decoder(hidden_states)
|
871 |
+
return hidden_states
|
872 |
+
|
873 |
+
|
874 |
+
class JinaBertOnlyMLMHead(nn.Module):
|
875 |
+
def __init__(self, config):
|
876 |
+
super().__init__()
|
877 |
+
self.predictions = JinaBertLMPredictionHead(config)
|
878 |
+
|
879 |
+
def forward(self, sequence_output: torch.Tensor) -> torch.Tensor:
|
880 |
+
prediction_scores = self.predictions(sequence_output)
|
881 |
+
return prediction_scores
|
882 |
+
|
883 |
+
|
884 |
+
class JinaBertOnlyNSPHead(nn.Module):
|
885 |
+
def __init__(self, config):
|
886 |
+
super().__init__()
|
887 |
+
self.seq_relationship = nn.Linear(config.hidden_size, 2)
|
888 |
+
|
889 |
+
def forward(self, pooled_output):
|
890 |
+
seq_relationship_score = self.seq_relationship(pooled_output)
|
891 |
+
return seq_relationship_score
|
892 |
+
|
893 |
+
|
894 |
+
class JinaBertPreTrainingHeads(nn.Module):
|
895 |
+
def __init__(self, config):
|
896 |
+
super().__init__()
|
897 |
+
self.predictions = JinaBertLMPredictionHead(config)
|
898 |
+
self.seq_relationship = nn.Linear(config.hidden_size, 2)
|
899 |
+
|
900 |
+
def forward(self, sequence_output, pooled_output):
|
901 |
+
prediction_scores = self.predictions(sequence_output)
|
902 |
+
seq_relationship_score = self.seq_relationship(pooled_output)
|
903 |
+
return prediction_scores, seq_relationship_score
|
904 |
+
|
905 |
+
|
906 |
+
class JinaBertPreTrainedModel(PreTrainedModel):
|
907 |
+
"""
|
908 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
909 |
+
models.
|
910 |
+
"""
|
911 |
+
|
912 |
+
config_class = JinaBertConfig
|
913 |
+
load_tf_weights = load_tf_weights_in_bert
|
914 |
+
base_model_prefix = "bert"
|
915 |
+
supports_gradient_checkpointing = True
|
916 |
+
_no_split_modules = ["JinaBertLayer"]
|
917 |
+
|
918 |
+
def _init_weights(self, module):
|
919 |
+
"""Initialize the weights"""
|
920 |
+
if isinstance(module, nn.Linear):
|
921 |
+
# Slightly different from the TF version which uses truncated_normal for initialization
|
922 |
+
# cf https://github.com/pytorch/pytorch/pull/5617
|
923 |
+
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
|
924 |
+
if module.bias is not None:
|
925 |
+
module.bias.data.zero_()
|
926 |
+
elif isinstance(module, nn.Embedding):
|
927 |
+
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
|
928 |
+
if module.padding_idx is not None:
|
929 |
+
module.weight.data[module.padding_idx].zero_()
|
930 |
+
elif isinstance(module, nn.LayerNorm):
|
931 |
+
module.bias.data.zero_()
|
932 |
+
module.weight.data.fill_(1.0)
|
933 |
+
|
934 |
+
def _set_gradient_checkpointing(self, module, value=False):
|
935 |
+
if isinstance(module, JinaBertEncoder):
|
936 |
+
module.gradient_checkpointing = value
|
937 |
+
|
938 |
+
|
939 |
+
@dataclass
|
940 |
+
class JinaBertForPreTrainingOutput(ModelOutput):
|
941 |
+
"""
|
942 |
+
Output type of [`BertForPreTraining`].
|
943 |
+
|
944 |
+
Args:
|
945 |
+
loss (*optional*, returned when `labels` is provided, `torch.FloatTensor` of shape `(1,)`):
|
946 |
+
Total loss as the sum of the masked language modeling loss and the next sequence prediction
|
947 |
+
(classification) loss.
|
948 |
+
prediction_logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
|
949 |
+
Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
|
950 |
+
seq_relationship_logits (`torch.FloatTensor` of shape `(batch_size, 2)`):
|
951 |
+
Prediction scores of the next sequence prediction (classification) head (scores of True/False continuation
|
952 |
+
before SoftMax).
|
953 |
+
hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
|
954 |
+
Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
|
955 |
+
shape `(batch_size, sequence_length, hidden_size)`.
|
956 |
+
|
957 |
+
Hidden-states of the model at the output of each layer plus the initial embedding outputs.
|
958 |
+
attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
|
959 |
+
Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
|
960 |
+
sequence_length)`.
|
961 |
+
|
962 |
+
Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
|
963 |
+
heads.
|
964 |
+
"""
|
965 |
+
|
966 |
+
loss: Optional[torch.FloatTensor] = None
|
967 |
+
prediction_logits: torch.FloatTensor = None
|
968 |
+
seq_relationship_logits: torch.FloatTensor = None
|
969 |
+
hidden_states: Optional[Tuple[torch.FloatTensor]] = None
|
970 |
+
attentions: Optional[Tuple[torch.FloatTensor]] = None
|
971 |
+
|
972 |
+
|
973 |
+
BERT_START_DOCSTRING = r"""
|
974 |
+
|
975 |
+
This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
|
976 |
+
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
|
977 |
+
etc.)
|
978 |
+
|
979 |
+
This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
|
980 |
+
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
|
981 |
+
and behavior.
|
982 |
+
|
983 |
+
Parameters:
|
984 |
+
config ([`BertConfig`]): Model configuration class with all the parameters of the model.
|
985 |
+
Initializing with a config file does not load the weights associated with the model, only the
|
986 |
+
configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
987 |
+
"""
|
988 |
+
|
989 |
+
BERT_INPUTS_DOCSTRING = r"""
|
990 |
+
Args:
|
991 |
+
input_ids (`torch.LongTensor` of shape `({0})`):
|
992 |
+
Indices of input sequence tokens in the vocabulary.
|
993 |
+
|
994 |
+
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
|
995 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
996 |
+
|
997 |
+
[What are input IDs?](../glossary#input-ids)
|
998 |
+
attention_mask (`torch.FloatTensor` of shape `({0})`, *optional*):
|
999 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
1000 |
+
|
1001 |
+
- 1 for tokens that are **not masked**,
|
1002 |
+
- 0 for tokens that are **masked**.
|
1003 |
+
|
1004 |
+
[What are attention masks?](../glossary#attention-mask)
|
1005 |
+
token_type_ids (`torch.LongTensor` of shape `({0})`, *optional*):
|
1006 |
+
Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
|
1007 |
+
1]`:
|
1008 |
+
|
1009 |
+
- 0 corresponds to a *sentence A* token,
|
1010 |
+
- 1 corresponds to a *sentence B* token.
|
1011 |
+
|
1012 |
+
[What are token type IDs?](../glossary#token-type-ids)
|
1013 |
+
position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
|
1014 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
1015 |
+
config.max_position_embeddings - 1]`.
|
1016 |
+
|
1017 |
+
[What are position IDs?](../glossary#position-ids)
|
1018 |
+
head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
|
1019 |
+
Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
|
1020 |
+
|
1021 |
+
- 1 indicates the head is **not masked**,
|
1022 |
+
- 0 indicates the head is **masked**.
|
1023 |
+
|
1024 |
+
inputs_embeds (`torch.FloatTensor` of shape `({0}, hidden_size)`, *optional*):
|
1025 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
|
1026 |
+
is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
|
1027 |
+
model's internal embedding lookup matrix.
|
1028 |
+
output_attentions (`bool`, *optional*):
|
1029 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
1030 |
+
tensors for more detail.
|
1031 |
+
output_hidden_states (`bool`, *optional*):
|
1032 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
1033 |
+
more detail.
|
1034 |
+
return_dict (`bool`, *optional*):
|
1035 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
1036 |
+
"""
|
1037 |
+
|
1038 |
+
|
1039 |
+
@add_start_docstrings(
|
1040 |
+
"The bare Bert Model transformer outputting raw hidden-states without any specific head on top.",
|
1041 |
+
BERT_START_DOCSTRING,
|
1042 |
+
)
|
1043 |
+
class JinaBertModel(JinaBertPreTrainedModel):
|
1044 |
+
"""
|
1045 |
+
|
1046 |
+
The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of
|
1047 |
+
cross-attention is added between the self-attention layers, following the architecture described in [Attention is
|
1048 |
+
all you need](https://arxiv.org/abs/1706.03762) by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit,
|
1049 |
+
Llion Jones, Aidan N. Gomez, Lukasz Kaiser and Illia Polosukhin.
|
1050 |
+
|
1051 |
+
To behave as an decoder the model needs to be initialized with the `is_decoder` argument of the configuration set
|
1052 |
+
to `True`. To be used in a Seq2Seq model, the model needs to initialized with both `is_decoder` argument and
|
1053 |
+
`add_cross_attention` set to `True`; an `encoder_hidden_states` is then expected as an input to the forward pass.
|
1054 |
+
"""
|
1055 |
+
|
1056 |
+
def __init__(self, config: JinaBertConfig, add_pooling_layer=True):
|
1057 |
+
super().__init__(config)
|
1058 |
+
self.config = config
|
1059 |
+
|
1060 |
+
self.emb_pooler = config.emb_pooler
|
1061 |
+
self._name_or_path = config._name_or_path
|
1062 |
+
if self.emb_pooler:
|
1063 |
+
from transformers import AutoTokenizer
|
1064 |
+
|
1065 |
+
self.tokenizer = AutoTokenizer.from_pretrained(config._name_or_path)
|
1066 |
+
|
1067 |
+
self.embeddings = JinaBertEmbeddings(config)
|
1068 |
+
self.encoder = JinaBertEncoder(config)
|
1069 |
+
|
1070 |
+
self.pooler = JinaBertPooler(config) if add_pooling_layer else None
|
1071 |
+
|
1072 |
+
# Initialize weights and apply final processing
|
1073 |
+
self.post_init()
|
1074 |
+
|
1075 |
+
@torch.inference_mode()
|
1076 |
+
def encode(
|
1077 |
+
self: 'JinaBertModel',
|
1078 |
+
sentences: Union[str, List[str]],
|
1079 |
+
batch_size: int = 32,
|
1080 |
+
show_progress_bar: Optional[bool] = None,
|
1081 |
+
output_value: str = 'sentence_embedding',
|
1082 |
+
convert_to_numpy: bool = True,
|
1083 |
+
convert_to_tensor: bool = False,
|
1084 |
+
device: Optional[torch.device] = None,
|
1085 |
+
normalize_embeddings: bool = False,
|
1086 |
+
**tokenizer_kwargs,
|
1087 |
+
) -> Union[List[torch.Tensor], np.ndarray, torch.Tensor]:
|
1088 |
+
"""
|
1089 |
+
Computes sentence embeddings
|
1090 |
+
|
1091 |
+
Args:
|
1092 |
+
sentences(`str` or `List[str]`):
|
1093 |
+
Sentence or sentences to be encoded
|
1094 |
+
batch_size(`int`, *optional*, defaults to 32):
|
1095 |
+
Batch size for the computation
|
1096 |
+
show_progress_bar(`bool`, *optional*, defaults to None):
|
1097 |
+
Show a progress bar when encoding sentences.
|
1098 |
+
If set to None, progress bar is only shown when `logger.level == logging.INFO` or `logger.level == logging.DEBUG`.
|
1099 |
+
output_value(`str`, *optional*, defaults to 'sentence_embedding'):
|
1100 |
+
Default sentence_embedding, to get sentence embeddings.
|
1101 |
+
Can be set to token_embeddings to get wordpiece token embeddings.
|
1102 |
+
Set to None, to get all output values
|
1103 |
+
convert_to_numpy(`bool`, *optional*, defaults to True):
|
1104 |
+
If true, the output is a list of numpy vectors.
|
1105 |
+
Else, it is a list of pytorch tensors.
|
1106 |
+
convert_to_tensor(`bool`, *optional*, defaults to False):
|
1107 |
+
If true, you get one large tensor as return.
|
1108 |
+
Overwrites any setting from convert_to_numpy
|
1109 |
+
device(`torch.device`, *optional*, defaults to None):
|
1110 |
+
Which torch.device to use for the computation
|
1111 |
+
normalize_embeddings(`bool`, *optional*, defaults to False):
|
1112 |
+
If set to true, returned vectors will have length 1. In that case, the faster dot-product (util.dot_score) instead of cosine similarity can be used.
|
1113 |
+
tokenizer_kwargs(`Dict[str, Any]`, *optional*, defaults to {}):
|
1114 |
+
Keyword arguments for the tokenizer
|
1115 |
+
|
1116 |
+
Returns:
|
1117 |
+
By default, a list of tensors is returned.
|
1118 |
+
If convert_to_tensor, a stacked tensor is returned.
|
1119 |
+
If convert_to_numpy, a numpy matrix is returned.
|
1120 |
+
"""
|
1121 |
+
if not self.emb_pooler:
|
1122 |
+
warnings.warn("No emb_pooler specified, defaulting to mean pooling.")
|
1123 |
+
self.emb_pooler = 'mean'
|
1124 |
+
from transformers import AutoTokenizer
|
1125 |
+
|
1126 |
+
self.tokenizer = AutoTokenizer.from_pretrained(self._name_or_path)
|
1127 |
+
is_training = self.training
|
1128 |
+
self.eval()
|
1129 |
+
|
1130 |
+
if show_progress_bar is None:
|
1131 |
+
show_progress_bar = (
|
1132 |
+
logger.getEffectiveLevel() == logging.INFO
|
1133 |
+
or logger.getEffectiveLevel() == logging.DEBUG
|
1134 |
+
)
|
1135 |
+
|
1136 |
+
if convert_to_tensor:
|
1137 |
+
convert_to_numpy = False
|
1138 |
+
|
1139 |
+
if output_value != 'sentence_embedding':
|
1140 |
+
convert_to_tensor = False
|
1141 |
+
convert_to_numpy = False
|
1142 |
+
|
1143 |
+
input_was_string = False
|
1144 |
+
if isinstance(sentences, str) or not hasattr(sentences, '__len__'):
|
1145 |
+
sentences = [sentences]
|
1146 |
+
input_was_string = True
|
1147 |
+
|
1148 |
+
if device is not None:
|
1149 |
+
self.to(device)
|
1150 |
+
|
1151 |
+
# TODO: Maybe use better length heuristic?
|
1152 |
+
permutation = np.argsort([-len(i) for i in sentences])
|
1153 |
+
inverse_permutation = np.argsort(permutation)
|
1154 |
+
sentences = [sentences[idx] for idx in permutation]
|
1155 |
+
|
1156 |
+
tokenizer_kwargs['padding'] = tokenizer_kwargs.get('padding', True)
|
1157 |
+
tokenizer_kwargs['max_length'] = tokenizer_kwargs.get('max_length', 8192)
|
1158 |
+
tokenizer_kwargs['truncation'] = tokenizer_kwargs.get('truncation', True)
|
1159 |
+
|
1160 |
+
all_embeddings = []
|
1161 |
+
|
1162 |
+
if has_tqdm:
|
1163 |
+
range_iter = trange(
|
1164 |
+
0,
|
1165 |
+
len(sentences),
|
1166 |
+
batch_size,
|
1167 |
+
desc="Encoding",
|
1168 |
+
disable=not show_progress_bar,
|
1169 |
+
)
|
1170 |
+
else:
|
1171 |
+
range_iter = range(0, len(sentences), batch_size)
|
1172 |
+
|
1173 |
+
for i in range_iter:
|
1174 |
+
encoded_input = self.tokenizer(
|
1175 |
+
sentences[i : i + batch_size],
|
1176 |
+
return_tensors='pt',
|
1177 |
+
**tokenizer_kwargs,
|
1178 |
+
).to(self.device)
|
1179 |
+
token_embs = self.forward(**encoded_input)[0]
|
1180 |
+
|
1181 |
+
# Accumulate in fp32 to avoid overflow
|
1182 |
+
token_embs = token_embs.float()
|
1183 |
+
|
1184 |
+
if output_value == 'token_embeddings':
|
1185 |
+
raise NotImplementedError
|
1186 |
+
elif output_value is None:
|
1187 |
+
raise NotImplementedError
|
1188 |
+
else:
|
1189 |
+
embeddings = self.mean_pooling(
|
1190 |
+
token_embs, encoded_input['attention_mask']
|
1191 |
+
)
|
1192 |
+
|
1193 |
+
if normalize_embeddings:
|
1194 |
+
embeddings = torch.nn.functional.normalize(embeddings, p=2, dim=1)
|
1195 |
+
|
1196 |
+
if convert_to_numpy:
|
1197 |
+
embeddings = embeddings.cpu()
|
1198 |
+
all_embeddings.extend(embeddings)
|
1199 |
+
|
1200 |
+
all_embeddings = [all_embeddings[idx] for idx in inverse_permutation]
|
1201 |
+
|
1202 |
+
if convert_to_tensor:
|
1203 |
+
all_embeddings = torch.stack(all_embeddings)
|
1204 |
+
elif convert_to_numpy:
|
1205 |
+
all_embeddings = np.asarray([emb.numpy() for emb in all_embeddings])
|
1206 |
+
|
1207 |
+
if input_was_string:
|
1208 |
+
all_embeddings = all_embeddings[0]
|
1209 |
+
|
1210 |
+
self.train(is_training)
|
1211 |
+
return all_embeddings
|
1212 |
+
|
1213 |
+
def mean_pooling(
|
1214 |
+
self, token_embeddings: torch.Tensor, attention_mask: torch.Tensor
|
1215 |
+
):
|
1216 |
+
input_mask_expanded = (
|
1217 |
+
attention_mask.unsqueeze(-1).expand(token_embeddings.size()).float()
|
1218 |
+
)
|
1219 |
+
return torch.sum(token_embeddings * input_mask_expanded, 1) / torch.clamp(
|
1220 |
+
input_mask_expanded.sum(1), min=1e-9
|
1221 |
+
)
|
1222 |
+
|
1223 |
+
def get_input_embeddings(self):
|
1224 |
+
return self.embeddings.word_embeddings
|
1225 |
+
|
1226 |
+
def set_input_embeddings(self, value):
|
1227 |
+
self.embeddings.word_embeddings = value
|
1228 |
+
|
1229 |
+
def _prune_heads(self, heads_to_prune):
|
1230 |
+
"""
|
1231 |
+
Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
|
1232 |
+
class PreTrainedModel
|
1233 |
+
"""
|
1234 |
+
for layer, heads in heads_to_prune.items():
|
1235 |
+
self.encoder.layer[layer].attention.prune_heads(heads)
|
1236 |
+
|
1237 |
+
@add_start_docstrings_to_model_forward(
|
1238 |
+
BERT_INPUTS_DOCSTRING.format("batch_size, sequence_length")
|
1239 |
+
)
|
1240 |
+
@add_code_sample_docstrings(
|
1241 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
1242 |
+
output_type=BaseModelOutputWithPoolingAndCrossAttentions,
|
1243 |
+
config_class=_CONFIG_FOR_DOC,
|
1244 |
+
)
|
1245 |
+
def forward(
|
1246 |
+
self,
|
1247 |
+
input_ids: Optional[torch.Tensor] = None,
|
1248 |
+
attention_mask: Optional[torch.Tensor] = None,
|
1249 |
+
token_type_ids: Optional[torch.Tensor] = None,
|
1250 |
+
position_ids: Optional[torch.Tensor] = None,
|
1251 |
+
head_mask: Optional[torch.Tensor] = None,
|
1252 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
1253 |
+
encoder_hidden_states: Optional[torch.Tensor] = None,
|
1254 |
+
encoder_attention_mask: Optional[torch.Tensor] = None,
|
1255 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
1256 |
+
use_cache: Optional[bool] = None,
|
1257 |
+
output_attentions: Optional[bool] = None,
|
1258 |
+
output_hidden_states: Optional[bool] = None,
|
1259 |
+
return_dict: Optional[bool] = None,
|
1260 |
+
) -> Union[Tuple[torch.Tensor], BaseModelOutputWithPoolingAndCrossAttentions]:
|
1261 |
+
r"""
|
1262 |
+
encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
1263 |
+
Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
|
1264 |
+
the model is configured as a decoder.
|
1265 |
+
encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
1266 |
+
Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
|
1267 |
+
the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
|
1268 |
+
|
1269 |
+
- 1 for tokens that are **not masked**,
|
1270 |
+
- 0 for tokens that are **masked**.
|
1271 |
+
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)`):
|
1272 |
+
Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
|
1273 |
+
|
1274 |
+
If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
|
1275 |
+
don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
|
1276 |
+
`decoder_input_ids` of shape `(batch_size, sequence_length)`.
|
1277 |
+
use_cache (`bool`, *optional*):
|
1278 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
|
1279 |
+
`past_key_values`).
|
1280 |
+
"""
|
1281 |
+
output_attentions = (
|
1282 |
+
output_attentions
|
1283 |
+
if output_attentions is not None
|
1284 |
+
else self.config.output_attentions
|
1285 |
+
)
|
1286 |
+
output_hidden_states = (
|
1287 |
+
output_hidden_states
|
1288 |
+
if output_hidden_states is not None
|
1289 |
+
else self.config.output_hidden_states
|
1290 |
+
)
|
1291 |
+
return_dict = (
|
1292 |
+
return_dict if return_dict is not None else self.config.use_return_dict
|
1293 |
+
)
|
1294 |
+
|
1295 |
+
if self.config.is_decoder:
|
1296 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
1297 |
+
else:
|
1298 |
+
use_cache = False
|
1299 |
+
|
1300 |
+
if input_ids is not None and inputs_embeds is not None:
|
1301 |
+
raise ValueError(
|
1302 |
+
"You cannot specify both input_ids and inputs_embeds at the same time"
|
1303 |
+
)
|
1304 |
+
elif input_ids is not None:
|
1305 |
+
# self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
|
1306 |
+
input_shape = input_ids.size()
|
1307 |
+
elif inputs_embeds is not None:
|
1308 |
+
input_shape = inputs_embeds.size()[:-1]
|
1309 |
+
else:
|
1310 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
1311 |
+
|
1312 |
+
batch_size, seq_length = input_shape
|
1313 |
+
device = input_ids.device if input_ids is not None else inputs_embeds.device
|
1314 |
+
|
1315 |
+
# past_key_values_length
|
1316 |
+
past_key_values_length = (
|
1317 |
+
past_key_values[0][0].shape[2] if past_key_values is not None else 0
|
1318 |
+
)
|
1319 |
+
|
1320 |
+
if attention_mask is None:
|
1321 |
+
attention_mask = torch.ones(
|
1322 |
+
((batch_size, seq_length + past_key_values_length)), device=device
|
1323 |
+
)
|
1324 |
+
|
1325 |
+
if token_type_ids is None:
|
1326 |
+
if hasattr(self.embeddings, "token_type_ids"):
|
1327 |
+
buffered_token_type_ids = self.embeddings.token_type_ids[:, :seq_length]
|
1328 |
+
buffered_token_type_ids_expanded = buffered_token_type_ids.expand(
|
1329 |
+
batch_size, seq_length
|
1330 |
+
)
|
1331 |
+
token_type_ids = buffered_token_type_ids_expanded
|
1332 |
+
else:
|
1333 |
+
token_type_ids = torch.zeros(
|
1334 |
+
input_shape, dtype=torch.long, device=device
|
1335 |
+
)
|
1336 |
+
|
1337 |
+
# We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
|
1338 |
+
# ourselves in which case we just need to make it broadcastable to all heads.
|
1339 |
+
extended_attention_mask: torch.Tensor = self.get_extended_attention_mask(
|
1340 |
+
attention_mask, input_shape
|
1341 |
+
)
|
1342 |
+
|
1343 |
+
# If a 2D or 3D attention mask is provided for the cross-attention
|
1344 |
+
# we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
|
1345 |
+
if self.config.is_decoder and encoder_hidden_states is not None:
|
1346 |
+
(
|
1347 |
+
encoder_batch_size,
|
1348 |
+
encoder_sequence_length,
|
1349 |
+
_,
|
1350 |
+
) = encoder_hidden_states.size()
|
1351 |
+
encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
|
1352 |
+
if encoder_attention_mask is None:
|
1353 |
+
encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device)
|
1354 |
+
encoder_extended_attention_mask = self.invert_attention_mask(
|
1355 |
+
encoder_attention_mask
|
1356 |
+
)
|
1357 |
+
else:
|
1358 |
+
encoder_extended_attention_mask = None
|
1359 |
+
|
1360 |
+
# Prepare head mask if needed
|
1361 |
+
# 1.0 in head_mask indicate we keep the head
|
1362 |
+
# attention_probs has shape bsz x n_heads x N x N
|
1363 |
+
# input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
|
1364 |
+
# and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
|
1365 |
+
head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
|
1366 |
+
|
1367 |
+
embedding_output = self.embeddings(
|
1368 |
+
input_ids=input_ids,
|
1369 |
+
position_ids=position_ids,
|
1370 |
+
token_type_ids=token_type_ids,
|
1371 |
+
inputs_embeds=inputs_embeds,
|
1372 |
+
past_key_values_length=past_key_values_length,
|
1373 |
+
)
|
1374 |
+
encoder_outputs = self.encoder(
|
1375 |
+
embedding_output,
|
1376 |
+
attention_mask=extended_attention_mask,
|
1377 |
+
head_mask=head_mask,
|
1378 |
+
encoder_hidden_states=encoder_hidden_states,
|
1379 |
+
encoder_attention_mask=encoder_extended_attention_mask,
|
1380 |
+
past_key_values=past_key_values,
|
1381 |
+
use_cache=use_cache,
|
1382 |
+
output_attentions=output_attentions,
|
1383 |
+
output_hidden_states=output_hidden_states,
|
1384 |
+
return_dict=return_dict,
|
1385 |
+
)
|
1386 |
+
sequence_output = encoder_outputs[0]
|
1387 |
+
pooled_output = (
|
1388 |
+
self.pooler(sequence_output) if self.pooler is not None else None
|
1389 |
+
)
|
1390 |
+
|
1391 |
+
if not return_dict:
|
1392 |
+
return (sequence_output, pooled_output) + encoder_outputs[1:]
|
1393 |
+
|
1394 |
+
return BaseModelOutputWithPoolingAndCrossAttentions(
|
1395 |
+
last_hidden_state=sequence_output,
|
1396 |
+
pooler_output=pooled_output,
|
1397 |
+
past_key_values=encoder_outputs.past_key_values,
|
1398 |
+
hidden_states=encoder_outputs.hidden_states,
|
1399 |
+
attentions=encoder_outputs.attentions,
|
1400 |
+
cross_attentions=encoder_outputs.cross_attentions,
|
1401 |
+
)
|
1402 |
+
|
1403 |
+
|
1404 |
+
@add_start_docstrings(
|
1405 |
+
"""
|
1406 |
+
Bert Model with two heads on top as done during the pretraining: a `masked language modeling` head and a `next
|
1407 |
+
sentence prediction (classification)` head.
|
1408 |
+
""",
|
1409 |
+
BERT_START_DOCSTRING,
|
1410 |
+
)
|
1411 |
+
class JinaBertForPreTraining(JinaBertPreTrainedModel):
|
1412 |
+
_tied_weights_keys = ["predictions.decoder.bias", "cls.predictions.decoder.weight"]
|
1413 |
+
|
1414 |
+
def __init__(self, config):
|
1415 |
+
super().__init__(config)
|
1416 |
+
|
1417 |
+
self.bert = JinaBertModel(config)
|
1418 |
+
self.cls = JinaBertPreTrainingHeads(config)
|
1419 |
+
|
1420 |
+
# Initialize weights and apply final processing
|
1421 |
+
self.post_init()
|
1422 |
+
|
1423 |
+
def get_output_embeddings(self):
|
1424 |
+
return self.cls.predictions.decoder
|
1425 |
+
|
1426 |
+
def set_output_embeddings(self, new_embeddings):
|
1427 |
+
self.cls.predictions.decoder = new_embeddings
|
1428 |
+
|
1429 |
+
@add_start_docstrings_to_model_forward(
|
1430 |
+
BERT_INPUTS_DOCSTRING.format("batch_size, sequence_length")
|
1431 |
+
)
|
1432 |
+
@replace_return_docstrings(
|
1433 |
+
output_type=JinaBertForPreTrainingOutput, config_class=_CONFIG_FOR_DOC
|
1434 |
+
)
|
1435 |
+
def forward(
|
1436 |
+
self,
|
1437 |
+
input_ids: Optional[torch.Tensor] = None,
|
1438 |
+
attention_mask: Optional[torch.Tensor] = None,
|
1439 |
+
token_type_ids: Optional[torch.Tensor] = None,
|
1440 |
+
position_ids: Optional[torch.Tensor] = None,
|
1441 |
+
head_mask: Optional[torch.Tensor] = None,
|
1442 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
1443 |
+
labels: Optional[torch.Tensor] = None,
|
1444 |
+
next_sentence_label: Optional[torch.Tensor] = None,
|
1445 |
+
output_attentions: Optional[bool] = None,
|
1446 |
+
output_hidden_states: Optional[bool] = None,
|
1447 |
+
return_dict: Optional[bool] = None,
|
1448 |
+
) -> Union[Tuple[torch.Tensor], JinaBertForPreTrainingOutput]:
|
1449 |
+
r"""
|
1450 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
1451 |
+
Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
|
1452 |
+
config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked),
|
1453 |
+
the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
|
1454 |
+
next_sentence_label (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
1455 |
+
Labels for computing the next sequence prediction (classification) loss. Input should be a sequence
|
1456 |
+
pair (see `input_ids` docstring) Indices should be in `[0, 1]`:
|
1457 |
+
|
1458 |
+
- 0 indicates sequence B is a continuation of sequence A,
|
1459 |
+
- 1 indicates sequence B is a random sequence.
|
1460 |
+
kwargs (`Dict[str, any]`, optional, defaults to *{}*):
|
1461 |
+
Used to hide legacy arguments that have been deprecated.
|
1462 |
+
|
1463 |
+
Returns:
|
1464 |
+
"""
|
1465 |
+
return_dict = (
|
1466 |
+
return_dict if return_dict is not None else self.config.use_return_dict
|
1467 |
+
)
|
1468 |
+
|
1469 |
+
outputs = self.bert(
|
1470 |
+
input_ids,
|
1471 |
+
attention_mask=attention_mask,
|
1472 |
+
token_type_ids=token_type_ids,
|
1473 |
+
position_ids=position_ids,
|
1474 |
+
head_mask=head_mask,
|
1475 |
+
inputs_embeds=inputs_embeds,
|
1476 |
+
output_attentions=output_attentions,
|
1477 |
+
output_hidden_states=output_hidden_states,
|
1478 |
+
return_dict=return_dict,
|
1479 |
+
)
|
1480 |
+
|
1481 |
+
sequence_output, pooled_output = outputs[:2]
|
1482 |
+
prediction_scores, seq_relationship_score = self.cls(
|
1483 |
+
sequence_output, pooled_output
|
1484 |
+
)
|
1485 |
+
|
1486 |
+
total_loss = None
|
1487 |
+
if labels is not None and next_sentence_label is not None:
|
1488 |
+
loss_fct = CrossEntropyLoss()
|
1489 |
+
masked_lm_loss = loss_fct(
|
1490 |
+
prediction_scores.view(-1, self.config.vocab_size), labels.view(-1)
|
1491 |
+
)
|
1492 |
+
next_sentence_loss = loss_fct(
|
1493 |
+
seq_relationship_score.view(-1, 2), next_sentence_label.view(-1)
|
1494 |
+
)
|
1495 |
+
total_loss = masked_lm_loss + next_sentence_loss
|
1496 |
+
|
1497 |
+
if not return_dict:
|
1498 |
+
output = (prediction_scores, seq_relationship_score) + outputs[2:]
|
1499 |
+
return ((total_loss,) + output) if total_loss is not None else output
|
1500 |
+
|
1501 |
+
return JinaBertForPreTrainingOutput(
|
1502 |
+
loss=total_loss,
|
1503 |
+
prediction_logits=prediction_scores,
|
1504 |
+
seq_relationship_logits=seq_relationship_score,
|
1505 |
+
hidden_states=outputs.hidden_states,
|
1506 |
+
attentions=outputs.attentions,
|
1507 |
+
)
|
1508 |
+
|
1509 |
+
|
1510 |
+
@add_start_docstrings(
|
1511 |
+
"""JinaBert Model with a `language modeling` head on top for CLM fine-tuning.""",
|
1512 |
+
BERT_START_DOCSTRING,
|
1513 |
+
)
|
1514 |
+
class JinaBertLMHeadModel(JinaBertPreTrainedModel):
|
1515 |
+
_tied_weights_keys = ["predictions.decoder.bias", "cls.predictions.decoder.weight"]
|
1516 |
+
|
1517 |
+
def __init__(self, config):
|
1518 |
+
super().__init__(config)
|
1519 |
+
|
1520 |
+
if not config.is_decoder:
|
1521 |
+
logger.warning(
|
1522 |
+
"If you want to use `JinaBertLMHeadModel` as a standalone, add `is_decoder=True.`"
|
1523 |
+
)
|
1524 |
+
|
1525 |
+
self.bert = JinaBertModel(config, add_pooling_layer=False)
|
1526 |
+
self.cls = JinaBertOnlyMLMHead(config)
|
1527 |
+
|
1528 |
+
# Initialize weights and apply final processing
|
1529 |
+
self.post_init()
|
1530 |
+
|
1531 |
+
def get_output_embeddings(self):
|
1532 |
+
return self.cls.predictions.decoder
|
1533 |
+
|
1534 |
+
def set_output_embeddings(self, new_embeddings):
|
1535 |
+
self.cls.predictions.decoder = new_embeddings
|
1536 |
+
|
1537 |
+
@add_start_docstrings_to_model_forward(
|
1538 |
+
BERT_INPUTS_DOCSTRING.format("batch_size, sequence_length")
|
1539 |
+
)
|
1540 |
+
@add_code_sample_docstrings(
|
1541 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
1542 |
+
output_type=CausalLMOutputWithCrossAttentions,
|
1543 |
+
config_class=_CONFIG_FOR_DOC,
|
1544 |
+
)
|
1545 |
+
def forward(
|
1546 |
+
self,
|
1547 |
+
input_ids: Optional[torch.Tensor] = None,
|
1548 |
+
attention_mask: Optional[torch.Tensor] = None,
|
1549 |
+
token_type_ids: Optional[torch.Tensor] = None,
|
1550 |
+
position_ids: Optional[torch.Tensor] = None,
|
1551 |
+
head_mask: Optional[torch.Tensor] = None,
|
1552 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
1553 |
+
encoder_hidden_states: Optional[torch.Tensor] = None,
|
1554 |
+
encoder_attention_mask: Optional[torch.Tensor] = None,
|
1555 |
+
labels: Optional[torch.Tensor] = None,
|
1556 |
+
past_key_values: Optional[List[torch.Tensor]] = None,
|
1557 |
+
use_cache: Optional[bool] = None,
|
1558 |
+
output_attentions: Optional[bool] = None,
|
1559 |
+
output_hidden_states: Optional[bool] = None,
|
1560 |
+
return_dict: Optional[bool] = None,
|
1561 |
+
) -> Union[Tuple[torch.Tensor], CausalLMOutputWithCrossAttentions]:
|
1562 |
+
r"""
|
1563 |
+
encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
|
1564 |
+
Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
|
1565 |
+
the model is configured as a decoder.
|
1566 |
+
encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
1567 |
+
Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
|
1568 |
+
the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
|
1569 |
+
|
1570 |
+
- 1 for tokens that are **not masked**,
|
1571 |
+
- 0 for tokens that are **masked**.
|
1572 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
1573 |
+
Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in
|
1574 |
+
`[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are
|
1575 |
+
ignored (masked), the loss is only computed for the tokens with labels n `[0, ..., config.vocab_size]`
|
1576 |
+
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)`):
|
1577 |
+
Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
|
1578 |
+
|
1579 |
+
If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
|
1580 |
+
don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
|
1581 |
+
`decoder_input_ids` of shape `(batch_size, sequence_length)`.
|
1582 |
+
use_cache (`bool`, *optional*):
|
1583 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
|
1584 |
+
`past_key_values`).
|
1585 |
+
"""
|
1586 |
+
return_dict = (
|
1587 |
+
return_dict if return_dict is not None else self.config.use_return_dict
|
1588 |
+
)
|
1589 |
+
if labels is not None:
|
1590 |
+
use_cache = False
|
1591 |
+
|
1592 |
+
outputs = self.bert(
|
1593 |
+
input_ids,
|
1594 |
+
attention_mask=attention_mask,
|
1595 |
+
token_type_ids=token_type_ids,
|
1596 |
+
position_ids=position_ids,
|
1597 |
+
head_mask=head_mask,
|
1598 |
+
inputs_embeds=inputs_embeds,
|
1599 |
+
encoder_hidden_states=encoder_hidden_states,
|
1600 |
+
encoder_attention_mask=encoder_attention_mask,
|
1601 |
+
past_key_values=past_key_values,
|
1602 |
+
use_cache=use_cache,
|
1603 |
+
output_attentions=output_attentions,
|
1604 |
+
output_hidden_states=output_hidden_states,
|
1605 |
+
return_dict=return_dict,
|
1606 |
+
)
|
1607 |
+
|
1608 |
+
sequence_output = outputs[0]
|
1609 |
+
prediction_scores = self.cls(sequence_output)
|
1610 |
+
|
1611 |
+
lm_loss = None
|
1612 |
+
if labels is not None:
|
1613 |
+
# we are doing next-token prediction; shift prediction scores and input ids by one
|
1614 |
+
shifted_prediction_scores = prediction_scores[:, :-1, :].contiguous()
|
1615 |
+
labels = labels[:, 1:].contiguous()
|
1616 |
+
loss_fct = CrossEntropyLoss()
|
1617 |
+
lm_loss = loss_fct(
|
1618 |
+
shifted_prediction_scores.view(-1, self.config.vocab_size),
|
1619 |
+
labels.view(-1),
|
1620 |
+
)
|
1621 |
+
|
1622 |
+
if not return_dict:
|
1623 |
+
output = (prediction_scores,) + outputs[2:]
|
1624 |
+
return ((lm_loss,) + output) if lm_loss is not None else output
|
1625 |
+
|
1626 |
+
return CausalLMOutputWithCrossAttentions(
|
1627 |
+
loss=lm_loss,
|
1628 |
+
logits=prediction_scores,
|
1629 |
+
past_key_values=outputs.past_key_values,
|
1630 |
+
hidden_states=outputs.hidden_states,
|
1631 |
+
attentions=outputs.attentions,
|
1632 |
+
cross_attentions=outputs.cross_attentions,
|
1633 |
+
)
|
1634 |
+
|
1635 |
+
def prepare_inputs_for_generation(
|
1636 |
+
self,
|
1637 |
+
input_ids,
|
1638 |
+
past_key_values=None,
|
1639 |
+
attention_mask=None,
|
1640 |
+
use_cache=True,
|
1641 |
+
**model_kwargs,
|
1642 |
+
):
|
1643 |
+
input_shape = input_ids.shape
|
1644 |
+
# if model is used as a decoder in encoder-decoder model, the decoder attention mask is created on the fly
|
1645 |
+
if attention_mask is None:
|
1646 |
+
attention_mask = input_ids.new_ones(input_shape)
|
1647 |
+
|
1648 |
+
# cut decoder_input_ids if past_key_values is used
|
1649 |
+
if past_key_values is not None:
|
1650 |
+
input_ids = input_ids[:, -1:]
|
1651 |
+
|
1652 |
+
return {
|
1653 |
+
"input_ids": input_ids,
|
1654 |
+
"attention_mask": attention_mask,
|
1655 |
+
"past_key_values": past_key_values,
|
1656 |
+
"use_cache": use_cache,
|
1657 |
+
}
|
1658 |
+
|
1659 |
+
def _reorder_cache(self, past_key_values, beam_idx):
|
1660 |
+
reordered_past = ()
|
1661 |
+
for layer_past in past_key_values:
|
1662 |
+
reordered_past += (
|
1663 |
+
tuple(
|
1664 |
+
past_state.index_select(0, beam_idx) for past_state in layer_past
|
1665 |
+
),
|
1666 |
+
)
|
1667 |
+
return reordered_past
|
1668 |
+
|
1669 |
+
|
1670 |
+
@add_start_docstrings(
|
1671 |
+
"""JinaBert Model with a `language modeling` head on top.""", BERT_START_DOCSTRING
|
1672 |
+
)
|
1673 |
+
class JinaBertForMaskedLM(JinaBertPreTrainedModel):
|
1674 |
+
_tied_weights_keys = ["predictions.decoder.bias", "cls.predictions.decoder.weight"]
|
1675 |
+
|
1676 |
+
def __init__(self, config):
|
1677 |
+
super().__init__(config)
|
1678 |
+
|
1679 |
+
if config.is_decoder:
|
1680 |
+
logger.warning(
|
1681 |
+
"If you want to use `JinaBertForMaskedLM` make sure `config.is_decoder=False` for "
|
1682 |
+
"bi-directional self-attention."
|
1683 |
+
)
|
1684 |
+
|
1685 |
+
self.bert = JinaBertModel(config, add_pooling_layer=False)
|
1686 |
+
self.cls = JinaBertOnlyMLMHead(config)
|
1687 |
+
|
1688 |
+
# Initialize weights and apply final processing
|
1689 |
+
self.post_init()
|
1690 |
+
|
1691 |
+
def get_output_embeddings(self):
|
1692 |
+
return self.cls.predictions.decoder
|
1693 |
+
|
1694 |
+
def set_output_embeddings(self, new_embeddings):
|
1695 |
+
self.cls.predictions.decoder = new_embeddings
|
1696 |
+
|
1697 |
+
@add_start_docstrings_to_model_forward(
|
1698 |
+
BERT_INPUTS_DOCSTRING.format("batch_size, sequence_length")
|
1699 |
+
)
|
1700 |
+
@add_code_sample_docstrings(
|
1701 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
1702 |
+
output_type=MaskedLMOutput,
|
1703 |
+
config_class=_CONFIG_FOR_DOC,
|
1704 |
+
expected_output="'paris'",
|
1705 |
+
expected_loss=0.88,
|
1706 |
+
)
|
1707 |
+
def forward(
|
1708 |
+
self,
|
1709 |
+
input_ids: Optional[torch.Tensor] = None,
|
1710 |
+
attention_mask: Optional[torch.Tensor] = None,
|
1711 |
+
token_type_ids: Optional[torch.Tensor] = None,
|
1712 |
+
position_ids: Optional[torch.Tensor] = None,
|
1713 |
+
head_mask: Optional[torch.Tensor] = None,
|
1714 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
1715 |
+
encoder_hidden_states: Optional[torch.Tensor] = None,
|
1716 |
+
encoder_attention_mask: Optional[torch.Tensor] = None,
|
1717 |
+
labels: Optional[torch.Tensor] = None,
|
1718 |
+
output_attentions: Optional[bool] = None,
|
1719 |
+
output_hidden_states: Optional[bool] = None,
|
1720 |
+
return_dict: Optional[bool] = None,
|
1721 |
+
) -> Union[Tuple[torch.Tensor], MaskedLMOutput]:
|
1722 |
+
r"""
|
1723 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
1724 |
+
Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
|
1725 |
+
config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
|
1726 |
+
loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`
|
1727 |
+
"""
|
1728 |
+
|
1729 |
+
return_dict = (
|
1730 |
+
return_dict if return_dict is not None else self.config.use_return_dict
|
1731 |
+
)
|
1732 |
+
|
1733 |
+
outputs = self.bert(
|
1734 |
+
input_ids,
|
1735 |
+
attention_mask=attention_mask,
|
1736 |
+
token_type_ids=token_type_ids,
|
1737 |
+
position_ids=position_ids,
|
1738 |
+
head_mask=head_mask,
|
1739 |
+
inputs_embeds=inputs_embeds,
|
1740 |
+
encoder_hidden_states=encoder_hidden_states,
|
1741 |
+
encoder_attention_mask=encoder_attention_mask,
|
1742 |
+
output_attentions=output_attentions,
|
1743 |
+
output_hidden_states=output_hidden_states,
|
1744 |
+
return_dict=return_dict,
|
1745 |
+
)
|
1746 |
+
|
1747 |
+
sequence_output = outputs[0]
|
1748 |
+
prediction_scores = self.cls(sequence_output)
|
1749 |
+
|
1750 |
+
masked_lm_loss = None
|
1751 |
+
if labels is not None:
|
1752 |
+
loss_fct = CrossEntropyLoss() # -100 index = padding token
|
1753 |
+
masked_lm_loss = loss_fct(
|
1754 |
+
prediction_scores.view(-1, self.config.vocab_size), labels.view(-1)
|
1755 |
+
)
|
1756 |
+
|
1757 |
+
if not return_dict:
|
1758 |
+
output = (prediction_scores,) + outputs[2:]
|
1759 |
+
return (
|
1760 |
+
((masked_lm_loss,) + output) if masked_lm_loss is not None else output
|
1761 |
+
)
|
1762 |
+
|
1763 |
+
return MaskedLMOutput(
|
1764 |
+
loss=masked_lm_loss,
|
1765 |
+
logits=prediction_scores,
|
1766 |
+
hidden_states=outputs.hidden_states,
|
1767 |
+
attentions=outputs.attentions,
|
1768 |
+
)
|
1769 |
+
|
1770 |
+
def prepare_inputs_for_generation(
|
1771 |
+
self, input_ids, attention_mask=None, **model_kwargs
|
1772 |
+
):
|
1773 |
+
input_shape = input_ids.shape
|
1774 |
+
effective_batch_size = input_shape[0]
|
1775 |
+
|
1776 |
+
# add a dummy token
|
1777 |
+
if self.config.pad_token_id is None:
|
1778 |
+
raise ValueError("The PAD token should be defined for generation")
|
1779 |
+
|
1780 |
+
attention_mask = torch.cat(
|
1781 |
+
[attention_mask, attention_mask.new_zeros((attention_mask.shape[0], 1))],
|
1782 |
+
dim=-1,
|
1783 |
+
)
|
1784 |
+
dummy_token = torch.full(
|
1785 |
+
(effective_batch_size, 1),
|
1786 |
+
self.config.pad_token_id,
|
1787 |
+
dtype=torch.long,
|
1788 |
+
device=input_ids.device,
|
1789 |
+
)
|
1790 |
+
input_ids = torch.cat([input_ids, dummy_token], dim=1)
|
1791 |
+
|
1792 |
+
return {"input_ids": input_ids, "attention_mask": attention_mask}
|
1793 |
+
|
1794 |
+
|
1795 |
+
@add_start_docstrings(
|
1796 |
+
"""JinaBert Model with a `next sentence prediction (classification)` head on top.""",
|
1797 |
+
BERT_START_DOCSTRING,
|
1798 |
+
)
|
1799 |
+
class JinaBertForNextSentencePrediction(JinaBertPreTrainedModel):
|
1800 |
+
def __init__(self, config):
|
1801 |
+
super().__init__(config)
|
1802 |
+
|
1803 |
+
self.bert = JinaBertModel(config)
|
1804 |
+
self.cls = JinaBertOnlyNSPHead(config)
|
1805 |
+
|
1806 |
+
# Initialize weights and apply final processing
|
1807 |
+
self.post_init()
|
1808 |
+
|
1809 |
+
@add_start_docstrings_to_model_forward(
|
1810 |
+
BERT_INPUTS_DOCSTRING.format("batch_size, sequence_length")
|
1811 |
+
)
|
1812 |
+
@replace_return_docstrings(
|
1813 |
+
output_type=NextSentencePredictorOutput, config_class=_CONFIG_FOR_DOC
|
1814 |
+
)
|
1815 |
+
def forward(
|
1816 |
+
self,
|
1817 |
+
input_ids: Optional[torch.Tensor] = None,
|
1818 |
+
attention_mask: Optional[torch.Tensor] = None,
|
1819 |
+
token_type_ids: Optional[torch.Tensor] = None,
|
1820 |
+
position_ids: Optional[torch.Tensor] = None,
|
1821 |
+
head_mask: Optional[torch.Tensor] = None,
|
1822 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
1823 |
+
labels: Optional[torch.Tensor] = None,
|
1824 |
+
output_attentions: Optional[bool] = None,
|
1825 |
+
output_hidden_states: Optional[bool] = None,
|
1826 |
+
return_dict: Optional[bool] = None,
|
1827 |
+
**kwargs,
|
1828 |
+
) -> Union[Tuple[torch.Tensor], NextSentencePredictorOutput]:
|
1829 |
+
r"""
|
1830 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
1831 |
+
Labels for computing the next sequence prediction (classification) loss. Input should be a sequence pair
|
1832 |
+
(see `input_ids` docstring). Indices should be in `[0, 1]`:
|
1833 |
+
|
1834 |
+
- 0 indicates sequence B is a continuation of sequence A,
|
1835 |
+
- 1 indicates sequence B is a random sequence.
|
1836 |
+
|
1837 |
+
Returns:
|
1838 |
+
"""
|
1839 |
+
|
1840 |
+
if "next_sentence_label" in kwargs:
|
1841 |
+
warnings.warn(
|
1842 |
+
"The `next_sentence_label` argument is deprecated and will be removed in a future version, use"
|
1843 |
+
" `labels` instead.",
|
1844 |
+
FutureWarning,
|
1845 |
+
)
|
1846 |
+
labels = kwargs.pop("next_sentence_label")
|
1847 |
+
|
1848 |
+
return_dict = (
|
1849 |
+
return_dict if return_dict is not None else self.config.use_return_dict
|
1850 |
+
)
|
1851 |
+
|
1852 |
+
outputs = self.bert(
|
1853 |
+
input_ids,
|
1854 |
+
attention_mask=attention_mask,
|
1855 |
+
token_type_ids=token_type_ids,
|
1856 |
+
position_ids=position_ids,
|
1857 |
+
head_mask=head_mask,
|
1858 |
+
inputs_embeds=inputs_embeds,
|
1859 |
+
output_attentions=output_attentions,
|
1860 |
+
output_hidden_states=output_hidden_states,
|
1861 |
+
return_dict=return_dict,
|
1862 |
+
)
|
1863 |
+
|
1864 |
+
pooled_output = outputs[1]
|
1865 |
+
|
1866 |
+
seq_relationship_scores = self.cls(pooled_output)
|
1867 |
+
|
1868 |
+
next_sentence_loss = None
|
1869 |
+
if labels is not None:
|
1870 |
+
loss_fct = CrossEntropyLoss()
|
1871 |
+
next_sentence_loss = loss_fct(
|
1872 |
+
seq_relationship_scores.view(-1, 2), labels.view(-1)
|
1873 |
+
)
|
1874 |
+
|
1875 |
+
if not return_dict:
|
1876 |
+
output = (seq_relationship_scores,) + outputs[2:]
|
1877 |
+
return (
|
1878 |
+
((next_sentence_loss,) + output)
|
1879 |
+
if next_sentence_loss is not None
|
1880 |
+
else output
|
1881 |
+
)
|
1882 |
+
|
1883 |
+
return NextSentencePredictorOutput(
|
1884 |
+
loss=next_sentence_loss,
|
1885 |
+
logits=seq_relationship_scores,
|
1886 |
+
hidden_states=outputs.hidden_states,
|
1887 |
+
attentions=outputs.attentions,
|
1888 |
+
)
|
1889 |
+
|
1890 |
+
|
1891 |
+
@add_start_docstrings(
|
1892 |
+
"""
|
1893 |
+
JinaBert Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled
|
1894 |
+
output) e.g. for GLUE tasks.
|
1895 |
+
""",
|
1896 |
+
BERT_START_DOCSTRING,
|
1897 |
+
)
|
1898 |
+
class JinaBertForSequenceClassification(JinaBertPreTrainedModel):
|
1899 |
+
def __init__(self, config):
|
1900 |
+
super().__init__(config)
|
1901 |
+
self.num_labels = config.num_labels
|
1902 |
+
self.config = config
|
1903 |
+
|
1904 |
+
self.bert = JinaBertModel(config)
|
1905 |
+
classifier_dropout = (
|
1906 |
+
config.classifier_dropout
|
1907 |
+
if config.classifier_dropout is not None
|
1908 |
+
else config.hidden_dropout_prob
|
1909 |
+
)
|
1910 |
+
self.dropout = nn.Dropout(classifier_dropout)
|
1911 |
+
self.classifier = nn.Linear(config.hidden_size, config.num_labels)
|
1912 |
+
|
1913 |
+
# Initialize weights and apply final processing
|
1914 |
+
self.post_init()
|
1915 |
+
|
1916 |
+
@add_start_docstrings_to_model_forward(
|
1917 |
+
BERT_INPUTS_DOCSTRING.format("batch_size, sequence_length")
|
1918 |
+
)
|
1919 |
+
@add_code_sample_docstrings(
|
1920 |
+
checkpoint=_CHECKPOINT_FOR_SEQUENCE_CLASSIFICATION,
|
1921 |
+
output_type=SequenceClassifierOutput,
|
1922 |
+
config_class=_CONFIG_FOR_DOC,
|
1923 |
+
expected_output=_SEQ_CLASS_EXPECTED_OUTPUT,
|
1924 |
+
expected_loss=_SEQ_CLASS_EXPECTED_LOSS,
|
1925 |
+
)
|
1926 |
+
def forward(
|
1927 |
+
self,
|
1928 |
+
input_ids: Optional[torch.Tensor] = None,
|
1929 |
+
attention_mask: Optional[torch.Tensor] = None,
|
1930 |
+
token_type_ids: Optional[torch.Tensor] = None,
|
1931 |
+
position_ids: Optional[torch.Tensor] = None,
|
1932 |
+
head_mask: Optional[torch.Tensor] = None,
|
1933 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
1934 |
+
labels: Optional[torch.Tensor] = None,
|
1935 |
+
output_attentions: Optional[bool] = None,
|
1936 |
+
output_hidden_states: Optional[bool] = None,
|
1937 |
+
return_dict: Optional[bool] = None,
|
1938 |
+
) -> Union[Tuple[torch.Tensor], SequenceClassifierOutput]:
|
1939 |
+
r"""
|
1940 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
1941 |
+
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
|
1942 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
1943 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
1944 |
+
"""
|
1945 |
+
return_dict = (
|
1946 |
+
return_dict if return_dict is not None else self.config.use_return_dict
|
1947 |
+
)
|
1948 |
+
|
1949 |
+
outputs = self.bert(
|
1950 |
+
input_ids,
|
1951 |
+
attention_mask=attention_mask,
|
1952 |
+
token_type_ids=token_type_ids,
|
1953 |
+
position_ids=position_ids,
|
1954 |
+
head_mask=head_mask,
|
1955 |
+
inputs_embeds=inputs_embeds,
|
1956 |
+
output_attentions=output_attentions,
|
1957 |
+
output_hidden_states=output_hidden_states,
|
1958 |
+
return_dict=return_dict,
|
1959 |
+
)
|
1960 |
+
|
1961 |
+
pooled_output = outputs[1]
|
1962 |
+
|
1963 |
+
pooled_output = self.dropout(pooled_output)
|
1964 |
+
logits = self.classifier(pooled_output)
|
1965 |
+
|
1966 |
+
loss = None
|
1967 |
+
if labels is not None:
|
1968 |
+
if self.config.problem_type is None:
|
1969 |
+
if self.num_labels == 1:
|
1970 |
+
self.config.problem_type = "regression"
|
1971 |
+
elif self.num_labels > 1 and (
|
1972 |
+
labels.dtype == torch.long or labels.dtype == torch.int
|
1973 |
+
):
|
1974 |
+
self.config.problem_type = "single_label_classification"
|
1975 |
+
else:
|
1976 |
+
self.config.problem_type = "multi_label_classification"
|
1977 |
+
|
1978 |
+
if self.config.problem_type == "regression":
|
1979 |
+
loss_fct = MSELoss()
|
1980 |
+
if self.num_labels == 1:
|
1981 |
+
loss = loss_fct(logits.squeeze(), labels.squeeze())
|
1982 |
+
else:
|
1983 |
+
loss = loss_fct(logits, labels)
|
1984 |
+
elif self.config.problem_type == "single_label_classification":
|
1985 |
+
loss_fct = CrossEntropyLoss()
|
1986 |
+
loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
|
1987 |
+
elif self.config.problem_type == "multi_label_classification":
|
1988 |
+
loss_fct = BCEWithLogitsLoss()
|
1989 |
+
loss = loss_fct(logits, labels)
|
1990 |
+
if not return_dict:
|
1991 |
+
output = (logits,) + outputs[2:]
|
1992 |
+
return ((loss,) + output) if loss is not None else output
|
1993 |
+
|
1994 |
+
return SequenceClassifierOutput(
|
1995 |
+
loss=loss,
|
1996 |
+
logits=logits,
|
1997 |
+
hidden_states=outputs.hidden_states,
|
1998 |
+
attentions=outputs.attentions,
|
1999 |
+
)
|
2000 |
+
|
2001 |
+
|
2002 |
+
@add_start_docstrings(
|
2003 |
+
"""
|
2004 |
+
JinaBert Model with a multiple choice classification head on top (a linear layer on top of the pooled output and a
|
2005 |
+
softmax) e.g. for RocStories/SWAG tasks.
|
2006 |
+
""",
|
2007 |
+
BERT_START_DOCSTRING,
|
2008 |
+
)
|
2009 |
+
class JinaBertForMultipleChoice(JinaBertPreTrainedModel):
|
2010 |
+
def __init__(self, config):
|
2011 |
+
super().__init__(config)
|
2012 |
+
|
2013 |
+
self.bert = JinaBertModel(config)
|
2014 |
+
classifier_dropout = (
|
2015 |
+
config.classifier_dropout
|
2016 |
+
if config.classifier_dropout is not None
|
2017 |
+
else config.hidden_dropout_prob
|
2018 |
+
)
|
2019 |
+
self.dropout = nn.Dropout(classifier_dropout)
|
2020 |
+
self.classifier = nn.Linear(config.hidden_size, 1)
|
2021 |
+
|
2022 |
+
# Initialize weights and apply final processing
|
2023 |
+
self.post_init()
|
2024 |
+
|
2025 |
+
@add_start_docstrings_to_model_forward(
|
2026 |
+
BERT_INPUTS_DOCSTRING.format("batch_size, num_choices, sequence_length")
|
2027 |
+
)
|
2028 |
+
@add_code_sample_docstrings(
|
2029 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
2030 |
+
output_type=MultipleChoiceModelOutput,
|
2031 |
+
config_class=_CONFIG_FOR_DOC,
|
2032 |
+
)
|
2033 |
+
def forward(
|
2034 |
+
self,
|
2035 |
+
input_ids: Optional[torch.Tensor] = None,
|
2036 |
+
attention_mask: Optional[torch.Tensor] = None,
|
2037 |
+
token_type_ids: Optional[torch.Tensor] = None,
|
2038 |
+
position_ids: Optional[torch.Tensor] = None,
|
2039 |
+
head_mask: Optional[torch.Tensor] = None,
|
2040 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
2041 |
+
labels: Optional[torch.Tensor] = None,
|
2042 |
+
output_attentions: Optional[bool] = None,
|
2043 |
+
output_hidden_states: Optional[bool] = None,
|
2044 |
+
return_dict: Optional[bool] = None,
|
2045 |
+
) -> Union[Tuple[torch.Tensor], MultipleChoiceModelOutput]:
|
2046 |
+
r"""
|
2047 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
2048 |
+
Labels for computing the multiple choice classification loss. Indices should be in `[0, ...,
|
2049 |
+
num_choices-1]` where `num_choices` is the size of the second dimension of the input tensors. (See
|
2050 |
+
`input_ids` above)
|
2051 |
+
"""
|
2052 |
+
return_dict = (
|
2053 |
+
return_dict if return_dict is not None else self.config.use_return_dict
|
2054 |
+
)
|
2055 |
+
num_choices = (
|
2056 |
+
input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1]
|
2057 |
+
)
|
2058 |
+
|
2059 |
+
input_ids = (
|
2060 |
+
input_ids.view(-1, input_ids.size(-1)) if input_ids is not None else None
|
2061 |
+
)
|
2062 |
+
attention_mask = (
|
2063 |
+
attention_mask.view(-1, attention_mask.size(-1))
|
2064 |
+
if attention_mask is not None
|
2065 |
+
else None
|
2066 |
+
)
|
2067 |
+
token_type_ids = (
|
2068 |
+
token_type_ids.view(-1, token_type_ids.size(-1))
|
2069 |
+
if token_type_ids is not None
|
2070 |
+
else None
|
2071 |
+
)
|
2072 |
+
position_ids = (
|
2073 |
+
position_ids.view(-1, position_ids.size(-1))
|
2074 |
+
if position_ids is not None
|
2075 |
+
else None
|
2076 |
+
)
|
2077 |
+
inputs_embeds = (
|
2078 |
+
inputs_embeds.view(-1, inputs_embeds.size(-2), inputs_embeds.size(-1))
|
2079 |
+
if inputs_embeds is not None
|
2080 |
+
else None
|
2081 |
+
)
|
2082 |
+
|
2083 |
+
outputs = self.bert(
|
2084 |
+
input_ids,
|
2085 |
+
attention_mask=attention_mask,
|
2086 |
+
token_type_ids=token_type_ids,
|
2087 |
+
position_ids=position_ids,
|
2088 |
+
head_mask=head_mask,
|
2089 |
+
inputs_embeds=inputs_embeds,
|
2090 |
+
output_attentions=output_attentions,
|
2091 |
+
output_hidden_states=output_hidden_states,
|
2092 |
+
return_dict=return_dict,
|
2093 |
+
)
|
2094 |
+
|
2095 |
+
pooled_output = outputs[1]
|
2096 |
+
|
2097 |
+
pooled_output = self.dropout(pooled_output)
|
2098 |
+
logits = self.classifier(pooled_output)
|
2099 |
+
reshaped_logits = logits.view(-1, num_choices)
|
2100 |
+
|
2101 |
+
loss = None
|
2102 |
+
if labels is not None:
|
2103 |
+
loss_fct = CrossEntropyLoss()
|
2104 |
+
loss = loss_fct(reshaped_logits, labels)
|
2105 |
+
|
2106 |
+
if not return_dict:
|
2107 |
+
output = (reshaped_logits,) + outputs[2:]
|
2108 |
+
return ((loss,) + output) if loss is not None else output
|
2109 |
+
|
2110 |
+
return MultipleChoiceModelOutput(
|
2111 |
+
loss=loss,
|
2112 |
+
logits=reshaped_logits,
|
2113 |
+
hidden_states=outputs.hidden_states,
|
2114 |
+
attentions=outputs.attentions,
|
2115 |
+
)
|
2116 |
+
|
2117 |
+
|
2118 |
+
@add_start_docstrings(
|
2119 |
+
"""
|
2120 |
+
JinaBert Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for
|
2121 |
+
Named-Entity-Recognition (NER) tasks.
|
2122 |
+
""",
|
2123 |
+
BERT_START_DOCSTRING,
|
2124 |
+
)
|
2125 |
+
class JinaBertForTokenClassification(JinaBertPreTrainedModel):
|
2126 |
+
def __init__(self, config):
|
2127 |
+
super().__init__(config)
|
2128 |
+
self.num_labels = config.num_labels
|
2129 |
+
|
2130 |
+
self.bert = JinaBertModel(config, add_pooling_layer=False)
|
2131 |
+
classifier_dropout = (
|
2132 |
+
config.classifier_dropout
|
2133 |
+
if config.classifier_dropout is not None
|
2134 |
+
else config.hidden_dropout_prob
|
2135 |
+
)
|
2136 |
+
self.dropout = nn.Dropout(classifier_dropout)
|
2137 |
+
self.classifier = nn.Linear(config.hidden_size, config.num_labels)
|
2138 |
+
|
2139 |
+
# Initialize weights and apply final processing
|
2140 |
+
self.post_init()
|
2141 |
+
|
2142 |
+
@add_start_docstrings_to_model_forward(
|
2143 |
+
BERT_INPUTS_DOCSTRING.format("batch_size, sequence_length")
|
2144 |
+
)
|
2145 |
+
@add_code_sample_docstrings(
|
2146 |
+
checkpoint=_CHECKPOINT_FOR_TOKEN_CLASSIFICATION,
|
2147 |
+
output_type=TokenClassifierOutput,
|
2148 |
+
config_class=_CONFIG_FOR_DOC,
|
2149 |
+
expected_output=_TOKEN_CLASS_EXPECTED_OUTPUT,
|
2150 |
+
expected_loss=_TOKEN_CLASS_EXPECTED_LOSS,
|
2151 |
+
)
|
2152 |
+
def forward(
|
2153 |
+
self,
|
2154 |
+
input_ids: Optional[torch.Tensor] = None,
|
2155 |
+
attention_mask: Optional[torch.Tensor] = None,
|
2156 |
+
token_type_ids: Optional[torch.Tensor] = None,
|
2157 |
+
position_ids: Optional[torch.Tensor] = None,
|
2158 |
+
head_mask: Optional[torch.Tensor] = None,
|
2159 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
2160 |
+
labels: Optional[torch.Tensor] = None,
|
2161 |
+
output_attentions: Optional[bool] = None,
|
2162 |
+
output_hidden_states: Optional[bool] = None,
|
2163 |
+
return_dict: Optional[bool] = None,
|
2164 |
+
) -> Union[Tuple[torch.Tensor], TokenClassifierOutput]:
|
2165 |
+
r"""
|
2166 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
2167 |
+
Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
|
2168 |
+
"""
|
2169 |
+
return_dict = (
|
2170 |
+
return_dict if return_dict is not None else self.config.use_return_dict
|
2171 |
+
)
|
2172 |
+
|
2173 |
+
outputs = self.bert(
|
2174 |
+
input_ids,
|
2175 |
+
attention_mask=attention_mask,
|
2176 |
+
token_type_ids=token_type_ids,
|
2177 |
+
position_ids=position_ids,
|
2178 |
+
head_mask=head_mask,
|
2179 |
+
inputs_embeds=inputs_embeds,
|
2180 |
+
output_attentions=output_attentions,
|
2181 |
+
output_hidden_states=output_hidden_states,
|
2182 |
+
return_dict=return_dict,
|
2183 |
+
)
|
2184 |
+
|
2185 |
+
sequence_output = outputs[0]
|
2186 |
+
|
2187 |
+
sequence_output = self.dropout(sequence_output)
|
2188 |
+
logits = self.classifier(sequence_output)
|
2189 |
+
|
2190 |
+
loss = None
|
2191 |
+
if labels is not None:
|
2192 |
+
loss_fct = CrossEntropyLoss()
|
2193 |
+
loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
|
2194 |
+
|
2195 |
+
if not return_dict:
|
2196 |
+
output = (logits,) + outputs[2:]
|
2197 |
+
return ((loss,) + output) if loss is not None else output
|
2198 |
+
|
2199 |
+
return TokenClassifierOutput(
|
2200 |
+
loss=loss,
|
2201 |
+
logits=logits,
|
2202 |
+
hidden_states=outputs.hidden_states,
|
2203 |
+
attentions=outputs.attentions,
|
2204 |
+
)
|
2205 |
+
|
2206 |
+
|
2207 |
+
@add_start_docstrings(
|
2208 |
+
"""
|
2209 |
+
JinaBert Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear
|
2210 |
+
layers on top of the hidden-states output to compute `span start logits` and `span end logits`).
|
2211 |
+
""",
|
2212 |
+
BERT_START_DOCSTRING,
|
2213 |
+
)
|
2214 |
+
class JinaBertForQuestionAnswering(JinaBertPreTrainedModel):
|
2215 |
+
def __init__(self, config):
|
2216 |
+
super().__init__(config)
|
2217 |
+
self.num_labels = config.num_labels
|
2218 |
+
|
2219 |
+
self.bert = JinaBertModel(config, add_pooling_layer=False)
|
2220 |
+
self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
|
2221 |
+
|
2222 |
+
# Initialize weights and apply final processing
|
2223 |
+
self.post_init()
|
2224 |
+
|
2225 |
+
@add_start_docstrings_to_model_forward(
|
2226 |
+
BERT_INPUTS_DOCSTRING.format("batch_size, sequence_length")
|
2227 |
+
)
|
2228 |
+
@add_code_sample_docstrings(
|
2229 |
+
checkpoint=_CHECKPOINT_FOR_QA,
|
2230 |
+
output_type=QuestionAnsweringModelOutput,
|
2231 |
+
config_class=_CONFIG_FOR_DOC,
|
2232 |
+
qa_target_start_index=_QA_TARGET_START_INDEX,
|
2233 |
+
qa_target_end_index=_QA_TARGET_END_INDEX,
|
2234 |
+
expected_output=_QA_EXPECTED_OUTPUT,
|
2235 |
+
expected_loss=_QA_EXPECTED_LOSS,
|
2236 |
+
)
|
2237 |
+
def forward(
|
2238 |
+
self,
|
2239 |
+
input_ids: Optional[torch.Tensor] = None,
|
2240 |
+
attention_mask: Optional[torch.Tensor] = None,
|
2241 |
+
token_type_ids: Optional[torch.Tensor] = None,
|
2242 |
+
position_ids: Optional[torch.Tensor] = None,
|
2243 |
+
head_mask: Optional[torch.Tensor] = None,
|
2244 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
2245 |
+
start_positions: Optional[torch.Tensor] = None,
|
2246 |
+
end_positions: Optional[torch.Tensor] = None,
|
2247 |
+
output_attentions: Optional[bool] = None,
|
2248 |
+
output_hidden_states: Optional[bool] = None,
|
2249 |
+
return_dict: Optional[bool] = None,
|
2250 |
+
) -> Union[Tuple[torch.Tensor], QuestionAnsweringModelOutput]:
|
2251 |
+
r"""
|
2252 |
+
start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
2253 |
+
Labels for position (index) of the start of the labelled span for computing the token classification loss.
|
2254 |
+
Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
|
2255 |
+
are not taken into account for computing the loss.
|
2256 |
+
end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
2257 |
+
Labels for position (index) of the end of the labelled span for computing the token classification loss.
|
2258 |
+
Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
|
2259 |
+
are not taken into account for computing the loss.
|
2260 |
+
"""
|
2261 |
+
return_dict = (
|
2262 |
+
return_dict if return_dict is not None else self.config.use_return_dict
|
2263 |
+
)
|
2264 |
+
|
2265 |
+
outputs = self.bert(
|
2266 |
+
input_ids,
|
2267 |
+
attention_mask=attention_mask,
|
2268 |
+
token_type_ids=token_type_ids,
|
2269 |
+
position_ids=position_ids,
|
2270 |
+
head_mask=head_mask,
|
2271 |
+
inputs_embeds=inputs_embeds,
|
2272 |
+
output_attentions=output_attentions,
|
2273 |
+
output_hidden_states=output_hidden_states,
|
2274 |
+
return_dict=return_dict,
|
2275 |
+
)
|
2276 |
+
|
2277 |
+
sequence_output = outputs[0]
|
2278 |
+
|
2279 |
+
logits = self.qa_outputs(sequence_output)
|
2280 |
+
start_logits, end_logits = logits.split(1, dim=-1)
|
2281 |
+
start_logits = start_logits.squeeze(-1).contiguous()
|
2282 |
+
end_logits = end_logits.squeeze(-1).contiguous()
|
2283 |
+
|
2284 |
+
total_loss = None
|
2285 |
+
if start_positions is not None and end_positions is not None:
|
2286 |
+
# If we are on multi-GPU, split add a dimension
|
2287 |
+
if len(start_positions.size()) > 1:
|
2288 |
+
start_positions = start_positions.squeeze(-1)
|
2289 |
+
if len(end_positions.size()) > 1:
|
2290 |
+
end_positions = end_positions.squeeze(-1)
|
2291 |
+
# sometimes the start/end positions are outside our model inputs, we ignore these terms
|
2292 |
+
ignored_index = start_logits.size(1)
|
2293 |
+
start_positions = start_positions.clamp(0, ignored_index)
|
2294 |
+
end_positions = end_positions.clamp(0, ignored_index)
|
2295 |
+
|
2296 |
+
loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
|
2297 |
+
start_loss = loss_fct(start_logits, start_positions)
|
2298 |
+
end_loss = loss_fct(end_logits, end_positions)
|
2299 |
+
total_loss = (start_loss + end_loss) / 2
|
2300 |
+
|
2301 |
+
if not return_dict:
|
2302 |
+
output = (start_logits, end_logits) + outputs[2:]
|
2303 |
+
return ((total_loss,) + output) if total_loss is not None else output
|
2304 |
+
|
2305 |
+
return QuestionAnsweringModelOutput(
|
2306 |
+
loss=total_loss,
|
2307 |
+
start_logits=start_logits,
|
2308 |
+
end_logits=end_logits,
|
2309 |
+
hidden_states=outputs.hidden_states,
|
2310 |
+
attentions=outputs.attentions,
|
2311 |
+
)
|
2312 |
+
|
modules.json
ADDED
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
},
|
14 |
+
{
|
15 |
+
"idx": 2,
|
16 |
+
"name": "2",
|
17 |
+
"path": "2_Normalize",
|
18 |
+
"type": "sentence_transformers.models.Normalize"
|
19 |
+
}
|
20 |
+
]
|
sentence_bert_config.json
ADDED
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"max_seq_length": 8192,
|
3 |
+
"do_lower_case": false
|
4 |
+
}
|
special_tokens_map.json
ADDED
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"bos_token": {
|
3 |
+
"content": "<s>",
|
4 |
+
"lstrip": false,
|
5 |
+
"normalized": false,
|
6 |
+
"rstrip": false,
|
7 |
+
"single_word": false
|
8 |
+
},
|
9 |
+
"cls_token": {
|
10 |
+
"content": "<s>",
|
11 |
+
"lstrip": false,
|
12 |
+
"normalized": false,
|
13 |
+
"rstrip": false,
|
14 |
+
"single_word": false
|
15 |
+
},
|
16 |
+
"eos_token": {
|
17 |
+
"content": "</s>",
|
18 |
+
"lstrip": false,
|
19 |
+
"normalized": false,
|
20 |
+
"rstrip": false,
|
21 |
+
"single_word": false
|
22 |
+
},
|
23 |
+
"mask_token": {
|
24 |
+
"content": "<mask>",
|
25 |
+
"lstrip": true,
|
26 |
+
"normalized": false,
|
27 |
+
"rstrip": false,
|
28 |
+
"single_word": false
|
29 |
+
},
|
30 |
+
"pad_token": {
|
31 |
+
"content": "<pad>",
|
32 |
+
"lstrip": false,
|
33 |
+
"normalized": false,
|
34 |
+
"rstrip": false,
|
35 |
+
"single_word": false
|
36 |
+
},
|
37 |
+
"sep_token": {
|
38 |
+
"content": "</s>",
|
39 |
+
"lstrip": false,
|
40 |
+
"normalized": false,
|
41 |
+
"rstrip": false,
|
42 |
+
"single_word": false
|
43 |
+
},
|
44 |
+
"unk_token": {
|
45 |
+
"content": "<unk>",
|
46 |
+
"lstrip": false,
|
47 |
+
"normalized": false,
|
48 |
+
"rstrip": false,
|
49 |
+
"single_word": false
|
50 |
+
}
|
51 |
+
}
|
tokenizer.json
ADDED
The diff for this file is too large to render.
See raw diff
|
|
tokenizer_config.json
ADDED
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"add_prefix_space": false,
|
3 |
+
"added_tokens_decoder": {
|
4 |
+
"0": {
|
5 |
+
"content": "<s>",
|
6 |
+
"lstrip": false,
|
7 |
+
"normalized": false,
|
8 |
+
"rstrip": false,
|
9 |
+
"single_word": false,
|
10 |
+
"special": true
|
11 |
+
},
|
12 |
+
"1": {
|
13 |
+
"content": "<pad>",
|
14 |
+
"lstrip": false,
|
15 |
+
"normalized": false,
|
16 |
+
"rstrip": false,
|
17 |
+
"single_word": false,
|
18 |
+
"special": true
|
19 |
+
},
|
20 |
+
"2": {
|
21 |
+
"content": "</s>",
|
22 |
+
"lstrip": false,
|
23 |
+
"normalized": false,
|
24 |
+
"rstrip": false,
|
25 |
+
"single_word": false,
|
26 |
+
"special": true
|
27 |
+
},
|
28 |
+
"3": {
|
29 |
+
"content": "<unk>",
|
30 |
+
"lstrip": false,
|
31 |
+
"normalized": false,
|
32 |
+
"rstrip": false,
|
33 |
+
"single_word": false,
|
34 |
+
"special": true
|
35 |
+
},
|
36 |
+
"4": {
|
37 |
+
"content": "<mask>",
|
38 |
+
"lstrip": true,
|
39 |
+
"normalized": false,
|
40 |
+
"rstrip": false,
|
41 |
+
"single_word": false,
|
42 |
+
"special": true
|
43 |
+
}
|
44 |
+
},
|
45 |
+
"bos_token": "<s>",
|
46 |
+
"clean_up_tokenization_spaces": true,
|
47 |
+
"cls_token": "<s>",
|
48 |
+
"eos_token": "</s>",
|
49 |
+
"errors": "replace",
|
50 |
+
"mask_token": "<mask>",
|
51 |
+
"model_max_length": 8192,
|
52 |
+
"pad_token": "<pad>",
|
53 |
+
"sep_token": "</s>",
|
54 |
+
"tokenizer_class": "RobertaTokenizer",
|
55 |
+
"trim_offsets": true,
|
56 |
+
"unk_token": "<unk>"
|
57 |
+
}
|
training_args.bin
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:9f83cd717a0286b9aaa9e9501b565616632b464c95104c84e6a1bf4f6e84c50d
|
3 |
+
size 4719
|
vocab.json
ADDED
The diff for this file is too large to render.
See raw diff
|
|