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