aynetdia commited on
Commit
6bcf851
·
verified ·
1 Parent(s): 9d658ee

Upload folder using huggingface_hub

Browse files
.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ tokenizer.json filter=lfs diff=lfs merge=lfs -text
1_Pooling/config.json ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "word_embedding_dimension": 768,
3
+ "pooling_mode_cls_token": true,
4
+ "pooling_mode_mean_tokens": false,
5
+ "pooling_mode_max_tokens": false,
6
+ "pooling_mode_mean_sqrt_len_tokens": false,
7
+ "pooling_mode_weightedmean_tokens": false,
8
+ "pooling_mode_lasttoken": false,
9
+ "include_prompt": true
10
+ }
README.md ADDED
The diff for this file is too large to render. See raw diff
 
config.json ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "GteModel"
4
+ ],
5
+ "attention_probs_dropout_prob": 0.0,
6
+ "auto_map": {
7
+ "AutoConfig": "configuration_hf_alibaba_nlp_gte.GteConfig",
8
+ "AutoModel": "modeling_hf_alibaba_nlp_gte.GteModel",
9
+ "AutoModelForSequenceClassification": "modeling_hf_alibaba_nlp_gte.GteForSequenceClassification"
10
+ },
11
+ "classifier_dropout": 0.1,
12
+ "hidden_act": "gelu",
13
+ "hidden_dropout_prob": 0.1,
14
+ "hidden_size": 768,
15
+ "initializer_range": 0.02,
16
+ "intermediate_size": 3072,
17
+ "layer_norm_eps": 1e-12,
18
+ "layer_norm_type": "layer_norm",
19
+ "logn_attention_clip1": false,
20
+ "logn_attention_scale": false,
21
+ "max_position_embeddings": 8192,
22
+ "model_type": "gte",
23
+ "num_attention_heads": 12,
24
+ "num_hidden_layers": 12,
25
+ "pack_qkv": true,
26
+ "pad_token_id": 1,
27
+ "position_embedding_type": "rope",
28
+ "rope_scaling": null,
29
+ "rope_theta": 160000,
30
+ "torch_dtype": "float32",
31
+ "transformers_version": "4.39.3",
32
+ "type_vocab_size": 1,
33
+ "unpad_inputs": "true",
34
+ "use_memory_efficient_attention": "true",
35
+ "matryoshka_dimensions": [256],
36
+ "vocab_size": 250048
37
+ }
config_sentence_transformers.json ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "__version__": {
3
+ "sentence_transformers": "2.7.0.dev0",
4
+ "transformers": "4.39.3",
5
+ "pytorch": "2.1.0+cu121"
6
+ },
7
+ "prompts": {
8
+ "query": "query: "
9
+ },
10
+ "default_prompt_name": null
11
+ }
configuration_hf_alibaba_nlp_gte.py ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The GTE Team Authors and Alibaba Group.
3
+ # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ """ GTE model configuration"""
17
+ from transformers.configuration_utils import PretrainedConfig
18
+ from transformers.utils import logging
19
+
20
+ logger = logging.get_logger(__name__)
21
+
22
+
23
+ class GteConfig(PretrainedConfig):
24
+ r"""
25
+ This is the configuration class to store the configuration of a [`NewModel`] or a [`TFNewModel`]. It is used to
26
+ instantiate a NEW model according to the specified arguments, defining the model architecture. Instantiating a
27
+ configuration with the defaults will yield a similar configuration to that of the NEW
28
+ [izhx/new-base-en](https://huggingface.co/izhx/new-base-en) architecture.
29
+
30
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
31
+ documentation from [`PretrainedConfig`] for more information.
32
+
33
+
34
+ Args:
35
+ vocab_size (`int`, *optional*, defaults to 30522):
36
+ Vocabulary size of the NEW model. Defines the number of different tokens that can be represented by the
37
+ `inputs_ids` passed when calling [`NewModel`] or [`TFNewModel`].
38
+ hidden_size (`int`, *optional*, defaults to 768):
39
+ Dimensionality of the encoder layers and the pooler layer.
40
+ num_hidden_layers (`int`, *optional*, defaults to 12):
41
+ Number of hidden layers in the Transformer encoder.
42
+ num_attention_heads (`int`, *optional*, defaults to 12):
43
+ Number of attention heads for each attention layer in the Transformer encoder.
44
+ intermediate_size (`int`, *optional*, defaults to 3072):
45
+ Dimensionality of the "intermediate" (often named feed-forward) layer in the Transformer encoder.
46
+ hidden_act (`str` or `Callable`, *optional*, defaults to `"gelu"`):
47
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
48
+ `"relu"`, `"silu"` and `"gelu_new"` are supported.
49
+ hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
50
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
51
+ attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):
52
+ The dropout ratio for the attention probabilities.
53
+ max_position_embeddings (`int`, *optional*, defaults to 512):
54
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
55
+ just in case (e.g., 512 or 1024 or 2048).
56
+ type_vocab_size (`int`, *optional*, defaults to 2):
57
+ The vocabulary size of the `token_type_ids` passed when calling [`NewModel`] or [`TFNewModel`].
58
+ initializer_range (`float`, *optional*, defaults to 0.02):
59
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
60
+ layer_norm_eps (`float`, *optional*, defaults to 1e-12):
61
+ The epsilon used by the layer normalization layers.
62
+ position_embedding_type (`str`, *optional*, defaults to `"rope"`):
63
+ Type of position embedding. Choose one of `"absolute"`, `"rope"`.
64
+ rope_theta (`float`, *optional*, defaults to 10000.0):
65
+ The base period of the RoPE embeddings.
66
+ rope_scaling (`Dict`, *optional*):
67
+ Dictionary containing the scaling configuration for the RoPE embeddings. Currently supports two scaling
68
+ strategies: linear and dynamic. Their scaling factor must be a float greater than 1. The expected format is
69
+ `{"type": strategy name, "factor": scaling factor}`. When using this flag, don't update
70
+ `max_position_embeddings` to the expected new maximum. See the following thread for more information on how
71
+ these scaling strategies behave:
72
+ https://www.reddit.com/r/LocalLLaMA/comments/14mrgpr/dynamically_scaled_rope_further_increases/. This is an
73
+ experimental feature, subject to breaking API changes in future versions.
74
+ classifier_dropout (`float`, *optional*):
75
+ The dropout ratio for the classification head.
76
+
77
+ Examples:
78
+
79
+ ```python
80
+ >>> from transformers import NewConfig, NewModel
81
+
82
+ >>> # Initializing a NEW izhx/new-base-en style configuration
83
+ >>> configuration = NewConfig()
84
+
85
+ >>> # Initializing a model (with random weights) from the izhx/new-base-en style configuration
86
+ >>> model = NewModel(configuration)
87
+
88
+ >>> # Accessing the model configuration
89
+ >>> configuration = model.config
90
+ ```"""
91
+
92
+ model_type = "gte"
93
+
94
+ def __init__(
95
+ self,
96
+ vocab_size=30528,
97
+ hidden_size=768,
98
+ num_hidden_layers=12,
99
+ num_attention_heads=12,
100
+ intermediate_size=3072,
101
+ hidden_act="gelu",
102
+ hidden_dropout_prob=0.1,
103
+ attention_probs_dropout_prob=0.0,
104
+ max_position_embeddings=2048,
105
+ type_vocab_size=1,
106
+ initializer_range=0.02,
107
+ layer_norm_type='layer_norm',
108
+ layer_norm_eps=1e-12,
109
+ # pad_token_id=0,
110
+ position_embedding_type="rope",
111
+ rope_theta=10000.0,
112
+ rope_scaling=None,
113
+ classifier_dropout=None,
114
+ pack_qkv=True,
115
+ unpad_inputs=False,
116
+ use_memory_efficient_attention=False,
117
+ logn_attention_scale=False,
118
+ logn_attention_clip1=False,
119
+ add_pooling_layer=True,
120
+ num_labels=0,
121
+ **kwargs,
122
+ ):
123
+ super().__init__(**kwargs)
124
+
125
+ self.vocab_size = vocab_size
126
+ self.hidden_size = hidden_size
127
+ self.num_hidden_layers = num_hidden_layers
128
+ self.num_attention_heads = num_attention_heads
129
+ self.hidden_act = hidden_act
130
+ self.intermediate_size = intermediate_size
131
+ self.hidden_dropout_prob = hidden_dropout_prob
132
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
133
+ self.max_position_embeddings = max_position_embeddings
134
+ self.type_vocab_size = type_vocab_size
135
+ self.initializer_range = initializer_range
136
+ self.layer_norm_type = layer_norm_type
137
+ self.layer_norm_eps = layer_norm_eps
138
+ self.position_embedding_type = position_embedding_type
139
+ self.rope_theta = rope_theta
140
+ self.rope_scaling = rope_scaling
141
+ self.classifier_dropout = classifier_dropout
142
+
143
+ self.pack_qkv = pack_qkv
144
+ self.unpad_inputs = unpad_inputs
145
+ self.use_memory_efficient_attention = use_memory_efficient_attention
146
+ self.logn_attention_scale = logn_attention_scale
147
+ self.logn_attention_clip1 = logn_attention_clip1
148
+
149
+ self.add_pooling_layer = add_pooling_layer
150
+ self.num_labels = num_labels
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3d80d4727ac8759fb8624b690697c053a3d1992120111dc4a71178e608c26604
3
+ size 1221487872
modeling_hf_alibaba_nlp_gte.py ADDED
@@ -0,0 +1,1036 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The GTE Team Authors and Alibaba Group.
3
+ # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+
17
+ import math
18
+ from dataclasses import dataclass
19
+ from typing import Any, List, Optional, Tuple, Union
20
+
21
+ import torch
22
+ import torch.utils.checkpoint
23
+ from torch import nn
24
+
25
+ from transformers.activations import ACT2FN
26
+ from transformers.modeling_outputs import (
27
+ BaseModelOutput,
28
+ BaseModelOutputWithPooling,
29
+ SequenceClassifierOutputWithPast,
30
+ )
31
+ from transformers.modeling_utils import PreTrainedModel
32
+ from transformers.utils import logging
33
+
34
+ try:
35
+ import xformers.ops as xops
36
+ except ImportError as e:
37
+ xops = None
38
+
39
+ from .configuration_hf_alibaba_nlp_gte import GteConfig
40
+
41
+
42
+ logger = logging.get_logger(__name__)
43
+
44
+
45
+ # Adapted from https://github.com/HazyResearch/flash-attention/blob/main/flash_attn/bert_padding.py
46
+ # Which was adapted from https://github.com/mlcommons/training_results_v1.1/blob/main/NVIDIA/benchmarks/bert/implementations/pytorch/padding.py
47
+ class IndexFirstAxis(torch.autograd.Function):
48
+ @staticmethod
49
+ def forward(ctx, input, indices):
50
+ ctx.save_for_backward(indices)
51
+ assert input.ndim >= 2
52
+ ctx.first_axis_dim, other_shape = input.shape[0], input.shape[1:]
53
+ second_dim = other_shape.numel()
54
+ # TD [2022-03-04] For some reason torch.gather is a bit faster than indexing.
55
+ # return input[indices]
56
+ # return torch.gather(
57
+ # rearrange(input, "b ... -> b (...)"), 0, repeat(indices, "z -> z d", d=second_dim)
58
+ # ).reshape(-1, *other_shape)
59
+ return torch.gather(
60
+ input.view(ctx.first_axis_dim, second_dim),
61
+ 0,
62
+ indices.unsqueeze(-1).expand(indices.size(0), second_dim)
63
+ ).reshape(-1, *other_shape)
64
+
65
+ @staticmethod
66
+ def backward(ctx, grad_output):
67
+ (indices,) = ctx.saved_tensors
68
+ assert grad_output.ndim >= 2
69
+ other_shape = grad_output.shape[1:]
70
+ # grad_output = rearrange(grad_output, "b ... -> b (...)")
71
+ grad_output = grad_output.view(grad_output.size(0), other_shape.numel())
72
+ grad_input = torch.zeros(
73
+ [ctx.first_axis_dim, grad_output.shape[1]],
74
+ device=grad_output.device,
75
+ dtype=grad_output.dtype,
76
+ )
77
+ # TD [2022-03-04] For some reason torch.scatter is a bit faster than indexing.
78
+ # grad_input[indices] = grad_output
79
+ # grad_input.scatter_(0, repeat(indices, "z -> z d", d=grad_output.shape[1]), grad_output)
80
+ grad_input.scatter_(
81
+ 0, indices.unsqueeze(-1).expand(indices.size(0), grad_output.size(1)), grad_output
82
+ )
83
+ return grad_input.reshape(ctx.first_axis_dim, *other_shape), None
84
+
85
+
86
+ index_first_axis = IndexFirstAxis.apply
87
+
88
+
89
+ def unpad_input(hidden_states, attention_mask=None, indices=None):
90
+ """
91
+ Arguments:
92
+ hidden_states: (batch, seqlen, ...)
93
+ attention_mask: (batch, seqlen), bool / int, 1 means valid and 0 means not valid.
94
+ indices: (total_nnz), the indices of non-masked tokens from the flattened input sequence.
95
+ Return:
96
+ hidden_states: (total_nnz, ...), where total_nnz = number of tokens in selected in attention_mask.
97
+ """
98
+ if indices is None:
99
+ assert attention_mask is not None
100
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
101
+
102
+ # TD [2022-03-04] We don't want to index with a bool mask, because Pytorch will expand the
103
+ # bool mask, then call nonzero to get the indices, then index with those. The indices is @dim
104
+ # times larger than it needs to be, wasting memory. It's faster and more memory-efficient to
105
+ # index with integer indices. Moreover, torch's index is a bit slower than it needs to be,
106
+ # so we write custom forward and backward to make it a bit faster.
107
+ hidden_states = hidden_states.view(-1, *hidden_states.shape[2:])
108
+ return index_first_axis(hidden_states, indices)
109
+
110
+
111
+ class IndexPutFirstAxis(torch.autograd.Function):
112
+ @staticmethod
113
+ def forward(
114
+ ctx,
115
+ values: torch.Tensor,
116
+ indices: torch.Tensor,
117
+ first_axis_dim
118
+ ) -> torch.Tensor:
119
+ ctx.save_for_backward(indices)
120
+ assert indices.ndim == 1
121
+ assert values.ndim >= 2
122
+ output = torch.zeros(
123
+ first_axis_dim, *values.shape[1:], device=values.device, dtype=values.dtype
124
+ )
125
+ output[indices] = values
126
+ return output
127
+
128
+ @staticmethod
129
+ def backward(ctx, grad_output: torch.Tensor) -> Tuple[torch.Tensor, None, None]:
130
+ indices, = ctx.saved_tensors
131
+ grad_values = grad_output[indices]
132
+ return grad_values, None, None
133
+
134
+
135
+ index_put_first_axis = IndexPutFirstAxis.apply
136
+
137
+
138
+ def pad_input(inputs: torch.Tensor, indices: torch.Tensor, batch: int, seqlen: int) -> torch.Tensor:
139
+ """Add padding to sequences.
140
+
141
+ Arguments:
142
+ inputs: (total_nnz, ...), where total_nnz = number of tokens in selected in attention_mask.
143
+ indices: (total_nnz), `indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()`
144
+ batch: int batch_size
145
+ seqlen: int max sequence length
146
+
147
+ Returns:
148
+ inputs: (batch, seqlen, ...)
149
+ """
150
+ output = index_put_first_axis(inputs, indices, batch * seqlen)
151
+ return output.view(batch, seqlen, *inputs.shape[1:])
152
+
153
+
154
+ def rotate_half(x):
155
+ """Rotates half the hidden dims of the input."""
156
+ x1 = x[..., : x.shape[-1] // 2]
157
+ x2 = x[..., x.shape[-1] // 2 :]
158
+ return torch.cat((-x2, x1), dim=-1)
159
+
160
+
161
+ def apply_rotary_pos_emb(q, k, cos, sin):
162
+ """Applies Rotary Position Embedding to the query and key tensors.
163
+
164
+ Args:
165
+ q (`torch.Tensor`): The query tensor.
166
+ k (`torch.Tensor`): The key tensor.
167
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
168
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
169
+ Returns:
170
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
171
+ """
172
+ cos, sin = cos.to(q.dtype), sin.to(q.dtype)
173
+ q_embed = (q * cos) + (rotate_half(q) * sin)
174
+ k_embed = (k * cos) + (rotate_half(k) * sin)
175
+ return q_embed, k_embed
176
+
177
+
178
+ class RotaryEmbedding(torch.nn.Module):
179
+ def __init__(self, dim, max_position_embeddings=512, base=10000.0, device=None):
180
+ super().__init__()
181
+
182
+ self.dim = dim
183
+ self.max_position_embeddings = max_position_embeddings
184
+ self.base = base
185
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
186
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
187
+
188
+ # Build here to make `torch.jit.trace` work.
189
+ self._set_cos_sin_cache(
190
+ seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
191
+ )
192
+
193
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
194
+ self.max_seq_len_cached = seq_len
195
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=torch.float32)
196
+
197
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
198
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
199
+ emb = torch.cat((freqs, freqs), dim=-1)
200
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
201
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
202
+
203
+ def forward(self, x, seq_len=None):
204
+ # x: [bs, num_attention_heads, seq_len, head_size]
205
+ if seq_len > self.max_seq_len_cached:
206
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
207
+
208
+ return (
209
+ self.cos_cached[:seq_len, ...].to(dtype=x.dtype),
210
+ self.sin_cached[:seq_len, ...].to(dtype=x.dtype),
211
+ )
212
+
213
+
214
+ class NTKScalingRotaryEmbedding(RotaryEmbedding):
215
+ """RotaryEmbedding extended with fixed and mixed NTK scaling. https://kexue.fm/archives/9706 """
216
+
217
+ def __init__(self, dim, max_position_embeddings=512, base=10000, device=None, scaling_factor=1.0, mixed_b=None):
218
+ self.scaling_factor = scaling_factor
219
+ self.mixed_b = mixed_b
220
+ super().__init__(dim, max_position_embeddings, base, device)
221
+ max_position_embeddings = max_position_embeddings * self.scaling_factor
222
+ self._set_cos_sin_cache(max_position_embeddings, self.inv_freq.device, torch.get_default_dtype())
223
+
224
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
225
+ self.max_seq_len_cached = seq_len
226
+
227
+ if seq_len > self.max_position_embeddings:
228
+ base = self.base * (self.scaling_factor if self.mixed_b is None else 1)
229
+ inv_freq = 1.0 / (base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
230
+
231
+ if self.mixed_b is None:
232
+ inv_freq = inv_freq / self.scaling_factor ** (2 / self.dim) # (6)
233
+ else:
234
+ a = torch.tensor(self.scaling_factor).log() / (self.dim / 2) ** self.mixed_b # (13)
235
+ lambda_1_m = (a * torch.arange(1, self.dim // 2 + 1).float().to(device) ** self.mixed_b).exp() # (12)
236
+ inv_freq = inv_freq / lambda_1_m # (10)
237
+
238
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
239
+
240
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=torch.float32)
241
+
242
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
243
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
244
+ emb = torch.cat((freqs, freqs), dim=-1)
245
+ self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
246
+ self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
247
+
248
+
249
+ class RMSNorm(nn.Module):
250
+ def __init__(self, hidden_size, eps=1e-6):
251
+ """
252
+ RMSNorm is equivalent to T5LayerNorm
253
+ """
254
+ super().__init__()
255
+ self.weight = nn.Parameter(torch.ones(hidden_size))
256
+ self.variance_epsilon = eps
257
+
258
+ def forward(self, hidden_states):
259
+ input_dtype = hidden_states.dtype
260
+ hidden_states = hidden_states.to(torch.float32)
261
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
262
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
263
+ return self.weight * hidden_states.to(input_dtype)
264
+
265
+
266
+ LAYER_NORM = {
267
+ 'layer_norm': nn.LayerNorm,
268
+ 'rms_norm': RMSNorm
269
+ }
270
+
271
+
272
+ class GteEmbeddings(nn.Module):
273
+ """
274
+ Embedding and Unpadding.
275
+ """
276
+
277
+ def __init__(self, config: GteConfig):
278
+ super().__init__()
279
+ self.padding_idx = config.pad_token_id
280
+ self.word_embeddings = nn.Embedding(
281
+ config.vocab_size, config.hidden_size, padding_idx=self.padding_idx
282
+ )
283
+
284
+ self.position_embedding_type = config.position_embedding_type
285
+ if self.position_embedding_type == 'absolute':
286
+ self.position_embeddings = nn.Embedding(
287
+ config.max_position_embeddings, config.hidden_size, padding_idx=self.padding_idx
288
+ )
289
+ elif self.position_embedding_type == 'rope':
290
+ self._init_rope(config)
291
+ else:
292
+ raise ValueError
293
+
294
+ self.type_vocab_size = config.type_vocab_size
295
+ if self.type_vocab_size > 0:
296
+ self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size)
297
+
298
+ # self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load
299
+ # any TensorFlow checkpoint file
300
+ self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
301
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
302
+ # position_ids is contiguous in memory and excluded when serialized
303
+ self.register_buffer(
304
+ "position_ids", torch.arange(config.max_position_embeddings), persistent=False
305
+ )
306
+
307
+ def _init_rope(self, config):
308
+ kwargs = dict(
309
+ dim=int(config.hidden_size / config.num_attention_heads),
310
+ max_position_embeddings=config.max_position_embeddings,
311
+ base=config.rope_theta
312
+ )
313
+ if config.rope_scaling is None:
314
+ self.rotary_emb = RotaryEmbedding(**kwargs)
315
+ else:
316
+ kwargs.update(scaling_factor=config.rope_scaling["factor"])
317
+ scaling_type = config.rope_scaling["type"]
318
+ if scaling_type == 'ntk':
319
+ kwargs.update(mixed_b=config.rope_scaling.get('mixed_b', None))
320
+ self.rotary_emb = NTKScalingRotaryEmbedding(**kwargs)
321
+ # elif scaling_type == "linear":
322
+ # self.rotary_emb = LinearScalingRotaryEmbedding(**kwargs)
323
+ # elif scaling_type == "dynamic":
324
+ # self.rotary_emb = DynamicNTKScalingRotaryEmbedding(**kwargs)
325
+ else:
326
+ raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
327
+
328
+ def forward(
329
+ self,
330
+ unpad_inputs: bool,
331
+ input_ids: Optional[torch.Tensor] = None,
332
+ attention_mask: Optional[torch.Tensor] = None,
333
+ length: Optional[List[int]] = None,
334
+ token_type_ids: Optional[torch.Tensor] = None,
335
+ position_ids: Optional[torch.Tensor] = None,
336
+ inputs_embeds: Optional[torch.Tensor] = None,
337
+ ) -> Tuple[torch.Tensor, torch.Tensor, Optional[Tuple], Optional[List[int]]]:
338
+ """
339
+ """
340
+ if inputs_embeds is None:
341
+ device, input_shape = input_ids.device, input_ids.shape
342
+ else:
343
+ device, input_shape = inputs_embeds.device, inputs_embeds.shape[:2]
344
+ batch_size, seq_length = input_shape
345
+
346
+ # Set attention_mask if it's None
347
+ if attention_mask is None:
348
+ attention_mask = torch.ones(input_shape, device=device)
349
+ if length is not None:
350
+ for i, l in enumerate(length):
351
+ attention_mask[i, l:] = 0
352
+
353
+ # Set attention_mask_bool for unpadding
354
+ if unpad_inputs:
355
+ attention_mask_bool = attention_mask.bool()
356
+ if length is None:
357
+ length = attention_mask.sum(-1).tolist()
358
+
359
+ # Get word embeddings
360
+ if inputs_embeds is None:
361
+ if unpad_inputs:
362
+ input_ids = input_ids[attention_mask_bool].unsqueeze(0)
363
+ inputs_embeds = self.word_embeddings(input_ids)
364
+ else:
365
+ if unpad_inputs:
366
+ inputs_embeds = inputs_embeds[attention_mask_bool].unsqueeze(0)
367
+ embeddings = inputs_embeds
368
+
369
+ # Set and unpad position_ids
370
+ if position_ids is None:
371
+ if seq_length > self.position_ids.size(0):
372
+ self.register_buffer(
373
+ "position_ids", torch.arange(seq_length, device=embeddings.device), persistent=False
374
+ )
375
+ if unpad_inputs:
376
+ # [1, cumsum_seq_len]
377
+ position_ids = torch.cat([self.position_ids[:l] for l in length]).unsqueeze(0)
378
+ else:
379
+ # [bs, seq_len]
380
+ position_ids = self.position_ids[:seq_length].expand(batch_size, -1)
381
+ elif unpad_inputs:
382
+ position_ids = position_ids[attention_mask_bool].unsqueeze(0) # [1, cumsum_seq_len]
383
+
384
+ # Compute rotary embedding
385
+ if self.position_embedding_type == 'rope':
386
+ rope_cos, rope_sin = self.rotary_emb(inputs_embeds, seq_len=seq_length)
387
+ rope_cos = rope_cos[position_ids].unsqueeze(2) # [bs, seq_len, 1, dim]
388
+ rope_sin = rope_sin[position_ids].unsqueeze(2) # [bs, seq_len, 1, dim]
389
+ rope_embeds = rope_cos, rope_sin
390
+ else:
391
+ rope_embeds = None
392
+
393
+ if self.type_vocab_size > 0:
394
+ if token_type_ids is None:
395
+ token_type_ids = position_ids.mul(0)
396
+ else:
397
+ if self.type_vocab_size < 2:
398
+ token_type_ids.mul_(0)
399
+ if unpad_inputs:
400
+ token_type_ids = token_type_ids[attention_mask_bool].unsqueeze(0)
401
+
402
+ token_type_embeddings = self.token_type_embeddings(token_type_ids)
403
+ embeddings = embeddings + token_type_embeddings
404
+
405
+ # BERT position
406
+ if self.position_embedding_type == "absolute":
407
+ position_embeddings = self.position_embeddings(position_ids)
408
+ embeddings = embeddings + position_embeddings
409
+
410
+ embeddings = self.LayerNorm(embeddings)
411
+ embeddings = self.dropout(embeddings)
412
+
413
+ return embeddings, attention_mask, rope_embeds, length
414
+
415
+
416
+ class GteAttention(nn.Module):
417
+ def __init__(self, config: GteConfig, pack_qkv=None, use_memory_efficient_attention=None):
418
+ super().__init__()
419
+ self.config = config
420
+ if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
421
+ raise ValueError(
422
+ f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention "
423
+ f"heads ({config.num_attention_heads})"
424
+ )
425
+
426
+ self.hidden_size = config.hidden_size
427
+ self.num_attention_heads = config.num_attention_heads
428
+ self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
429
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
430
+
431
+ if pack_qkv is None:
432
+ pack_qkv = config.pack_qkv
433
+ self.pack_qkv = pack_qkv
434
+
435
+ if self.pack_qkv:
436
+ self.qkv_proj = nn.Linear(config.hidden_size, self.all_head_size * 3, bias=True)
437
+ else:
438
+ self.q_proj = nn.Linear(config.hidden_size, self.all_head_size, bias=True)
439
+ self.k_proj = nn.Linear(config.hidden_size, self.all_head_size, bias=True)
440
+ self.v_proj = nn.Linear(config.hidden_size, self.all_head_size, bias=True)
441
+
442
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
443
+ self.o_proj = nn.Linear(config.hidden_size, config.hidden_size, bias=True)
444
+
445
+ if use_memory_efficient_attention is None:
446
+ use_memory_efficient_attention = self.config.use_memory_efficient_attention
447
+ self.use_memory_efficient_attention = use_memory_efficient_attention
448
+ self.memory_efficient_attention = None if xops is None else xops.memory_efficient_attention
449
+ if self.use_memory_efficient_attention:
450
+ assert self.memory_efficient_attention is not None, 'please install xformers'
451
+
452
+ def forward(
453
+ self,
454
+ hidden_states: torch.Tensor,
455
+ attention_bias: torch.FloatTensor,
456
+ rope_embeds: Optional[Tuple[torch.FloatTensor, torch.FloatTensor]] = None,
457
+ padding_inputs: Optional[Tuple] = None, # indices, batch, seqlen
458
+ attention_scale: Optional[torch.FloatTensor] = None,
459
+ head_mask: Optional[torch.FloatTensor] = None,
460
+ output_attentions: Optional[bool] = False,
461
+ qkv_inputs: Optional[Tuple] = None, # For RetroMAE
462
+ ) -> Tuple[torch.Tensor, ...]:
463
+ shape_hd = (self.num_attention_heads, self.attention_head_size)
464
+ # qkv
465
+ if self.pack_qkv and qkv_inputs is None:
466
+ qkv_pack = self.qkv_proj(hidden_states).split(self.all_head_size, dim=-1)
467
+ else:
468
+ if qkv_inputs is None:
469
+ qkv_inputs = (hidden_states, hidden_states, hidden_states)
470
+ qkv_pack = [
471
+ getattr(self, n + '_proj')(s) for s, n in zip(qkv_inputs, 'qkv')
472
+ ]
473
+ query_states, key_states, value_states = [t.view(t.shape[:-1] + shape_hd) for t in qkv_pack]
474
+
475
+ if self.config.position_embedding_type == 'rope':
476
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, *rope_embeds)
477
+
478
+ dtype = query_states.dtype
479
+
480
+ if self.config.logn_attention_scale and attention_scale is not None:
481
+ # https://kexue.fm/archives/8823
482
+ query_states = query_states * attention_scale.to(dtype)
483
+
484
+ if padding_inputs is not None:
485
+ query_states = pad_input(query_states.squeeze(), *padding_inputs)
486
+ key_states = pad_input(key_states.squeeze(), *padding_inputs)
487
+ value_states = pad_input(value_states.squeeze(), *padding_inputs)
488
+
489
+ if self.use_memory_efficient_attention:
490
+ assert self.memory_efficient_attention is not None, "xformers is not loaded"
491
+ assert output_attentions is False, "memory_efficient_attention do not output attentions"
492
+ assert head_mask is None, "Not support yet"
493
+ attention_probs = None
494
+ if torch.is_tensor(attention_bias):
495
+ attention_bias = attention_bias.to(dtype)
496
+ context_layer = self.memory_efficient_attention(
497
+ query_states,
498
+ key_states,
499
+ value_states,
500
+ attn_bias=attention_bias,
501
+ p=self.dropout.p
502
+ )
503
+ else:
504
+ if output_attentions and isinstance(self, GteSdpaAttention):
505
+ raise RuntimeError("SDPA do not output attentions")
506
+ context_layer, attention_probs = self._attention(
507
+ query_states, key_states, value_states, attention_bias, head_mask
508
+ )
509
+
510
+ if padding_inputs is not None:
511
+ context_layer = unpad_input(context_layer, indices=padding_inputs[0])
512
+
513
+ gte_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
514
+ context_layer = context_layer.view(gte_context_layer_shape)
515
+
516
+ # output proj
517
+ attn_output = self.o_proj(context_layer)
518
+
519
+ # add attentions if we output them
520
+ outputs = (attn_output, attention_probs) if output_attentions else (attn_output,)
521
+ return outputs
522
+
523
+ def _attention(self, query_states, key_states, value_states, attention_bias, head_mask):
524
+ """
525
+ Args:
526
+ q/k/v: (B, L, n_head, head_dim),
527
+ Returns:
528
+ attn_output: (B L, n_head, head_dim)
529
+ """
530
+ query_states = query_states.transpose(1, 2)
531
+ key_states = key_states.transpose(1, 2)
532
+ value_states = value_states.transpose(1, 2)
533
+ # Take the dot product between "query" and "key" to get the raw attention scores.
534
+ attention_scores = torch.matmul(query_states, key_states.transpose(-1, -2))
535
+
536
+ attention_scores = attention_scores / math.sqrt(self.attention_head_size)
537
+ if attention_bias is not None:
538
+ # Apply the attention mask is (precomputed for all layers in BertModel forward() function)
539
+ attention_scores = attention_scores + attention_bias
540
+
541
+ # Normalize the attention scores to probabilities.
542
+ attention_probs = nn.functional.softmax(attention_scores, dim=-1)
543
+
544
+ # This is actually dropping out entire tokens to attend to, which might
545
+ # seem a bit unusual, but is taken from the original Transformer paper.
546
+ if self.dropout.p > 0:
547
+ attention_probs = self.dropout(attention_probs)
548
+
549
+ # Mask heads if we want to
550
+ if head_mask is not None:
551
+ attention_probs = attention_probs * head_mask
552
+
553
+ context_layer = torch.matmul(attention_probs, value_states)
554
+
555
+ context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
556
+ return context_layer, attention_probs
557
+
558
+
559
+ class GteSdpaAttention(GteAttention):
560
+ """
561
+ Gte attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
562
+ `GteAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
563
+ SDPA API.
564
+ """
565
+ def __init__(self, config: GteConfig, **kwargs):
566
+ super().__init__(config, **kwargs)
567
+ # torch.backends.cuda.enable_mem_efficient_sdp(False)
568
+ # logger.warning(
569
+ # "Disable memory efficient attention kernel for `GteSdpaAttention`, you can set "
570
+ # "`use_memory_efficient_attention=True` if it expected to use."
571
+ # )
572
+
573
+ def _attention(self, query_states, key_states, value_states, attention_bias, head_mask):
574
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
575
+ query_states.transpose(1, 2),
576
+ key_states.transpose(1, 2),
577
+ value_states.transpose(1, 2),
578
+ attn_mask=attention_bias,
579
+ dropout_p=self.dropout.p if self.training else 0.0,
580
+ )
581
+ attn_output = attn_output.permute(0, 2, 1, 3).contiguous()
582
+ return attn_output, None
583
+
584
+
585
+ GTE_ATTENTION_CLASSES = {
586
+ "eager": GteAttention,
587
+ # "flash_attention_2": , # TODO
588
+ "sdpa": GteSdpaAttention,
589
+ }
590
+
591
+
592
+ class GteGatedMLP(nn.Module):
593
+ """
594
+ GLU Variants Improve Transformer.
595
+ """
596
+
597
+ def __init__(self, config: GteConfig):
598
+ super().__init__()
599
+ self.intermediate_size = config.intermediate_size
600
+ self.up_gate_proj = nn.Linear(config.hidden_size, self.intermediate_size * 2, bias=False)
601
+ self.down_proj = nn.Linear(self.intermediate_size, config.hidden_size, bias=True)
602
+ self.act_fn = ACT2FN[config.hidden_act]
603
+ if config.hidden_dropout_prob > 0:
604
+ self.hidden_dropout = nn.Dropout(config.hidden_dropout_prob)
605
+ else:
606
+ self.hidden_dropout = None
607
+
608
+ def forward(self, hidden_states):
609
+ up_gate = self.up_gate_proj(hidden_states)
610
+ up_states, gate = torch.split(up_gate, self.intermediate_size, dim=-1)
611
+ gate = self.act_fn(gate)
612
+ gated_states = gate * up_states
613
+ if self.hidden_dropout is not None:
614
+ gated_states = self.hidden_dropout(gated_states)
615
+ down_states = self.down_proj(gated_states)
616
+ return down_states
617
+
618
+
619
+ class GteLayer(nn.Module):
620
+ def __init__(
621
+ self,
622
+ config: GteConfig,
623
+ pack_qkv=None,
624
+ use_memory_efficient_attention=None,
625
+ attn_implementation=None
626
+ ):
627
+ super().__init__()
628
+ if attn_implementation is None:
629
+ attn_implementation = config._attn_implementation
630
+ if use_memory_efficient_attention is None:
631
+ use_memory_efficient_attention = config.use_memory_efficient_attention
632
+ if use_memory_efficient_attention:
633
+ if attn_implementation != 'eager':
634
+ logger.warning_once(f"Override {attn_implementation=} to 'eager' as {use_memory_efficient_attention=}")
635
+ attn_implementation = 'eager' # Since it will be SDPA by default for torch>=2.1.1
636
+ self.attention = GTE_ATTENTION_CLASSES[attn_implementation](
637
+ config, pack_qkv=pack_qkv, use_memory_efficient_attention=use_memory_efficient_attention
638
+ )
639
+ self.mlp = GteGatedMLP(config)
640
+
641
+ ln_class = LAYER_NORM[config.layer_norm_type]
642
+ self.attn_ln = ln_class(config.hidden_size, eps=config.layer_norm_eps)
643
+ self.mlp_ln = ln_class(config.hidden_size, eps=config.layer_norm_eps)
644
+
645
+ if config.hidden_dropout_prob > 0:
646
+ self.hidden_dropout = nn.Dropout(config.hidden_dropout_prob)
647
+ else:
648
+ self.hidden_dropout = None
649
+
650
+ def forward(
651
+ self,
652
+ hidden_states: torch.Tensor,
653
+ attention_bias: torch.FloatTensor,
654
+ rope_embeds: Optional[Tuple[torch.FloatTensor, torch.FloatTensor]] = None,
655
+ padding_inputs: Optional[Tuple] = None, # indices, batch, seqlen
656
+ attention_scale: Optional[torch.FloatTensor] = None,
657
+ subset_indices: Optional[torch.LongTensor] = None,
658
+ head_mask: Optional[torch.FloatTensor] = None,
659
+ output_attentions: Optional[bool] = False,
660
+ qkv_inputs: Optional[Tuple] = None, # For RetroMAE
661
+ ) -> Tuple[torch.Tensor, ...]:
662
+ # Multi head self attention
663
+ residual = hidden_states if qkv_inputs is None else qkv_inputs[0]
664
+ attention_outputs = self.attention(
665
+ hidden_states,
666
+ attention_bias,
667
+ rope_embeds,
668
+ padding_inputs,
669
+ attention_scale,
670
+ head_mask,
671
+ output_attentions=output_attentions,
672
+ qkv_inputs=qkv_inputs,
673
+ )
674
+ hidden_states = attention_outputs[0]
675
+ if self.hidden_dropout is not None:
676
+ hidden_states = self.hidden_dropout(hidden_states)
677
+ hidden_states = residual + hidden_states
678
+
679
+ # In pretraining, after the attention of last layer, we only need the masked tokens.
680
+ if subset_indices is not None:
681
+ hidden_states = hidden_states[subset_indices]
682
+
683
+ hidden_states = self.attn_ln(hidden_states)
684
+
685
+ # Fully Connected
686
+ residual = hidden_states
687
+ hidden_states = self.mlp(hidden_states)
688
+ if self.hidden_dropout is not None:
689
+ hidden_states = self.hidden_dropout(hidden_states)
690
+ hidden_states = residual + hidden_states
691
+ hidden_states = self.mlp_ln(hidden_states)
692
+
693
+ # add self attentions if we output attention weights
694
+ outputs = (hidden_states,) + attention_outputs[1:]
695
+ return outputs
696
+
697
+
698
+ class GteEncoder(nn.Module):
699
+ def __init__(self, config):
700
+ super().__init__()
701
+ self.config = config
702
+ self.layer = nn.ModuleList([GteLayer(config) for _ in range(config.num_hidden_layers)])
703
+ self.gradient_checkpointing = False
704
+
705
+ def forward(
706
+ self,
707
+ hidden_states: torch.Tensor,
708
+ attention_bias: Optional[torch.FloatTensor] = None,
709
+ rope_embeds: Optional[Tuple[torch.FloatTensor, torch.FloatTensor]] = None,
710
+ padding_inputs: Optional[Tuple] = None, # indices, batch, seqlen
711
+ attention_scale: Optional[torch.FloatTensor] = None,
712
+ subset_indices: Optional[torch.LongTensor] = None,
713
+ head_mask: Optional[torch.FloatTensor] = None,
714
+ output_attentions: Optional[bool] = False,
715
+ output_hidden_states: Optional[bool] = False,
716
+ return_dict: Optional[bool] = True,
717
+ ) -> Union[Tuple[torch.Tensor], BaseModelOutput]:
718
+ all_hidden_states = () if output_hidden_states else None
719
+ all_self_attentions = () if output_attentions else None
720
+
721
+ for i, layer_module in enumerate(self.layer):
722
+ if output_hidden_states:
723
+ all_hidden_states = all_hidden_states + (hidden_states,)
724
+
725
+ if i >= len(self.layer) - 1:
726
+ layer_subset_indices = subset_indices
727
+ else:
728
+ layer_subset_indices = None
729
+
730
+ layer_head_mask = head_mask[i] if head_mask is not None else None
731
+
732
+ if self.gradient_checkpointing and self.training:
733
+ layer_outputs = self._gradient_checkpointing_func(
734
+ layer_module.__call__,
735
+ hidden_states,
736
+ attention_bias,
737
+ rope_embeds,
738
+ padding_inputs,
739
+ attention_scale,
740
+ layer_subset_indices,
741
+ layer_head_mask,
742
+ )
743
+ else:
744
+ layer_outputs = layer_module(
745
+ hidden_states,
746
+ attention_bias,
747
+ rope_embeds,
748
+ padding_inputs,
749
+ attention_scale,
750
+ layer_subset_indices,
751
+ layer_head_mask,
752
+ output_attentions,
753
+ )
754
+
755
+ hidden_states = layer_outputs[0]
756
+ if output_attentions:
757
+ all_self_attentions = all_self_attentions + (layer_outputs[1],)
758
+
759
+ if output_hidden_states:
760
+ all_hidden_states = all_hidden_states + (hidden_states,)
761
+
762
+ if not return_dict:
763
+ return tuple(
764
+ v
765
+ for v in [
766
+ hidden_states,
767
+ all_hidden_states,
768
+ all_self_attentions,
769
+ ]
770
+ if v is not None
771
+ )
772
+ return BaseModelOutput(
773
+ last_hidden_state=hidden_states,
774
+ hidden_states=all_hidden_states,
775
+ attentions=all_self_attentions,
776
+ )
777
+
778
+
779
+ # Copied from transformers.models.bert.modeling_bert.BertPooler with Bert->Gte
780
+ class GtePooler(nn.Module):
781
+ def __init__(self, config):
782
+ super().__init__()
783
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
784
+ self.activation = nn.Tanh()
785
+
786
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
787
+ # We "pool" the model by simply taking the hidden state corresponding
788
+ # to the first token.
789
+ first_token_tensor = hidden_states[:, 0]
790
+ pooled_output = self.dense(first_token_tensor)
791
+ pooled_output = self.activation(pooled_output)
792
+ return pooled_output
793
+
794
+
795
+ class GtePreTrainedModel(PreTrainedModel):
796
+ """
797
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
798
+ models.
799
+ """
800
+
801
+ config_class = GteConfig
802
+ base_model_prefix = "gte"
803
+ supports_gradient_checkpointing = True
804
+ _supports_sdpa = True
805
+
806
+ def _init_weights(self, module):
807
+ """Initialize the weights"""
808
+ if isinstance(module, nn.Linear):
809
+ # Slightly different from the TF version which uses truncated_normal for initialization
810
+ # cf https://github.com/pytorch/pytorch/pull/5617
811
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
812
+ if module.bias is not None:
813
+ module.bias.data.zero_()
814
+ elif isinstance(module, nn.Embedding):
815
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
816
+ if module.padding_idx is not None:
817
+ module.weight.data[module.padding_idx].zero_()
818
+ elif isinstance(module, nn.LayerNorm):
819
+ module.bias.data.zero_()
820
+ module.weight.data.fill_(1.0)
821
+
822
+
823
+ class GteModel(GtePreTrainedModel):
824
+ """
825
+ The bare Gte Model transformer outputting raw hidden-states without any specific head on top.
826
+ """
827
+
828
+ def __init__(self, config: GteConfig, add_pooling_layer=False):
829
+ super().__init__(config)
830
+ self.config = config
831
+
832
+ self.embeddings = GteEmbeddings(config)
833
+ self.encoder = GteEncoder(config)
834
+
835
+ self.pooler = GtePooler(config) if add_pooling_layer else None
836
+
837
+ # Initialize weights and apply final processing
838
+ self.post_init()
839
+
840
+ def get_input_embeddings(self):
841
+ return self.embeddings.word_embeddings
842
+
843
+ def set_input_embeddings(self, value):
844
+ self.embeddings.word_embeddings = value
845
+
846
+ def forward(
847
+ self,
848
+ input_ids: Optional[torch.Tensor] = None,
849
+ attention_mask: Optional[torch.Tensor] = None,
850
+ length: Optional[List[int]] = None,
851
+ subset_indices: Optional[torch.LongTensor] = None,
852
+ token_type_ids: Optional[torch.Tensor] = None,
853
+ position_ids: Optional[torch.Tensor] = None,
854
+ head_mask: Optional[torch.Tensor] = None,
855
+ inputs_embeds: Optional[torch.Tensor] = None,
856
+ output_attentions: Optional[bool] = None,
857
+ output_hidden_states: Optional[bool] = None,
858
+ return_dict: Optional[bool] = None,
859
+ unpad_inputs: Optional[bool] = None,
860
+ **kwargs
861
+ ) -> Union[Tuple[torch.Tensor], BaseModelOutputWithPooling]:
862
+ r"""
863
+ length (`list` of length `batch_size`, *optional*):
864
+ If is `None`, return padded `last_hidden_state`.
865
+ subset_indices ():
866
+ pass
867
+ unpad_inputs (`bool`, *optional*):
868
+ pass
869
+ """
870
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
871
+ output_hidden_states = (
872
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
873
+ )
874
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
875
+ unpad_inputs = unpad_inputs if unpad_inputs is not None else self.config.unpad_inputs
876
+ output_padded = length is None
877
+
878
+ if input_ids is not None and inputs_embeds is not None:
879
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
880
+ elif input_ids is not None:
881
+ self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
882
+ input_shape = input_ids.size()
883
+ elif inputs_embeds is not None:
884
+ input_shape = inputs_embeds.size()[:-1]
885
+ else:
886
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
887
+
888
+ # TODO: not used
889
+ # # Prepare head mask if needed
890
+ # # 1.0 in head_mask indicate we keep the head
891
+ # # attention_probs has shape bsz x n_heads x N x N
892
+ # # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
893
+ # # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
894
+ # head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
895
+
896
+ # Get embeddings, may unpad them
897
+ (embedding_output, attention_mask, rope_embeds, length) = self.embeddings(
898
+ unpad_inputs,
899
+ input_ids=input_ids,
900
+ attention_mask=attention_mask,
901
+ length=length,
902
+ token_type_ids=token_type_ids,
903
+ position_ids=position_ids,
904
+ inputs_embeds=inputs_embeds
905
+ )
906
+
907
+ batch_size, seq_length = input_shape
908
+ if unpad_inputs and self.config.use_memory_efficient_attention:
909
+ attention_bias = xops.fmha.attn_bias.BlockDiagonalMask.from_seqlens(length)
910
+ else:
911
+ # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
912
+ # ourselves in which case we just need to make it broadcastable to all heads.
913
+ attention_bias = self.get_extended_attention_mask(attention_mask, input_shape)
914
+ if self.config.use_memory_efficient_attention:
915
+ # Invalid shape for attention bias: torch.Size([48, 1, 1, 512]) (expected (48, 12, 512, 512))
916
+ attention_bias = attention_bias.expand(-1, self.config.num_attention_heads, seq_length, -1)
917
+
918
+ padding_inputs = None
919
+ if unpad_inputs and (output_padded or not self.config.use_memory_efficient_attention):
920
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
921
+ if not self.config.use_memory_efficient_attention:
922
+ padding_inputs = (indices, *input_shape)
923
+
924
+ attention_scale = None
925
+ if self.config.logn_attention_scale:
926
+ logger.warning_once("TODO: logn_attention_scale")
927
+ # # attention scale log_512(input_len)
928
+ # attention_scale = attention_mask.sum(1).log() / torch.tensor(self.config.max_position_embeddings).log()
929
+ # # inference-time logn scale need clip 1
930
+ # if self.config.logn_attention_clip1:
931
+ # attention_scale.clip_(1)
932
+ # attention_scale = attention_scale[:, None, None, None]
933
+ # else:
934
+ # attention_scale = None
935
+
936
+ encoder_outputs = self.encoder(
937
+ embedding_output,
938
+ attention_bias=attention_bias,
939
+ rope_embeds=rope_embeds,
940
+ padding_inputs=padding_inputs,
941
+ attention_scale=attention_scale,
942
+ subset_indices=subset_indices,
943
+ head_mask=head_mask,
944
+ output_attentions=output_attentions,
945
+ output_hidden_states=output_hidden_states,
946
+ return_dict=return_dict,
947
+ )
948
+ sequence_output = encoder_outputs[0]
949
+ if unpad_inputs and output_padded:
950
+ sequence_output = pad_input(
951
+ sequence_output.squeeze(), indices, batch_size, seq_length
952
+ )
953
+
954
+ pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
955
+
956
+ if not return_dict:
957
+ return (sequence_output, pooled_output) + encoder_outputs[1:]
958
+
959
+ return BaseModelOutputWithPooling(
960
+ last_hidden_state=sequence_output,
961
+ pooler_output=pooled_output,
962
+ hidden_states=encoder_outputs.hidden_states,
963
+ attentions=encoder_outputs.attentions,
964
+ )
965
+
966
+
967
+ class GteForSequenceClassification(GtePreTrainedModel):
968
+
969
+ base_model_prefix = "model"
970
+
971
+ def __init__(self, config: GteConfig):
972
+ super().__init__(config)
973
+ self.config = config
974
+ self.num_labels = config.num_labels
975
+ assert config.num_labels > 0, "num_labels should be greater than 0 for sequence classification"
976
+ self.model = GteModel(config, add_pooling_layer=config.add_pooling_layer)
977
+
978
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
979
+ self.post_init()
980
+
981
+ def get_input_embeddings(self):
982
+ return self.model.embed_tokens
983
+
984
+ def set_input_embeddings(self, value):
985
+ self.model.embed_tokens = value
986
+
987
+ def forward(
988
+ self,
989
+ input_ids: Optional[torch.LongTensor] = None,
990
+ attention_mask: Optional[torch.Tensor] = None,
991
+ position_ids: Optional[torch.LongTensor] = None,
992
+ past_key_values = None,
993
+ inputs_embeds: Optional[torch.FloatTensor] = None,
994
+ labels: Optional[torch.LongTensor] = None,
995
+ use_cache: Optional[bool] = None,
996
+ output_attentions: Optional[bool] = None,
997
+ output_hidden_states: Optional[bool] = None,
998
+ **kwargs: Any,
999
+ ) -> SequenceClassifierOutputWithPast:
1000
+ r"""
1001
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1002
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1003
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1004
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1005
+ """
1006
+
1007
+ transformer_outputs = self.model(
1008
+ input_ids,
1009
+ attention_mask=attention_mask,
1010
+ position_ids=position_ids,
1011
+ inputs_embeds=inputs_embeds,
1012
+ output_attentions=output_attentions,
1013
+ output_hidden_states=output_hidden_states,
1014
+ **kwargs
1015
+ )
1016
+ if self.config.add_pooling_layer:
1017
+ hidden_states = transformer_outputs.pooler_output
1018
+ else:
1019
+ hidden_states = transformer_outputs.last_hidden_state[:, 0]
1020
+
1021
+ logits = self.score(hidden_states)
1022
+
1023
+ loss = None
1024
+ if labels is not None:
1025
+ loss = self.loss_function(labels, logits, self.config)
1026
+
1027
+ # if not return_dict:
1028
+ # output = (logits,) + transformer_outputs[1:]
1029
+ # return ((loss,) + output) if loss is not None else output
1030
+
1031
+ return SequenceClassifierOutputWithPast(
1032
+ loss=loss,
1033
+ logits=logits,
1034
+ hidden_states=transformer_outputs.hidden_states,
1035
+ attentions=transformer_outputs.attentions,
1036
+ )
modules.json ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [
2
+ {
3
+ "idx": 0,
4
+ "name": "0",
5
+ "path": "",
6
+ "type": "sentence_transformers.models.Transformer"
7
+ },
8
+ {
9
+ "idx": 1,
10
+ "name": "1",
11
+ "path": "1_Pooling",
12
+ "type": "sentence_transformers.models.Pooling"
13
+ },
14
+ {
15
+ "idx": 2,
16
+ "name": "2",
17
+ "path": "2_Normalize",
18
+ "type": "sentence_transformers.models.Normalize"
19
+ }
20
+ ]
onnx/model.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c0c53d7f49a2db60761b92b7bbf5be87a7b3cf5d92dbbd7f1b5028bd5a40aa39
3
+ size 1226099913
onnx/model_bnb4.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:042dc3b22eb47b760eb9e95aff681baf2901c919e6bea2280678d7863ee2f10d
3
+ size 836823604
onnx/model_fp16.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f27ab40ab6e230265ba49a202a37f1ad031556256cbbc105d0ca9c0bdc7ec42e
3
+ size 613266244
onnx/model_int8.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:03d923bb1850ebdccb068e2f3abd8aa43fe81c50d07d037ef103fe3d0fb78e3b
3
+ size 310916060
onnx/model_q4.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f8ee62d8f4d2f00fc456b1bc5efff8fb2084642844d8835d1ecffce420ae3c51
3
+ size 843901108
onnx/model_q4f16.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3cabedcefa1a1c1a8f8c6bb46bad75219f23ef73892580bcf59e96b03b941e5c
3
+ size 450481991
onnx/model_quantized.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:03d923bb1850ebdccb068e2f3abd8aa43fe81c50d07d037ef103fe3d0fb78e3b
3
+ size 310916060
onnx/model_uint8.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:22299d6d7d9ce6969a3b6bea9e0c828b92b7f4124c3ecb401ad6291f7171f406
3
+ size 310916060
special_tokens_map.json ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": {
3
+ "content": "<s>",
4
+ "lstrip": false,
5
+ "normalized": false,
6
+ "rstrip": false,
7
+ "single_word": false
8
+ },
9
+ "cls_token": {
10
+ "content": "<s>",
11
+ "lstrip": false,
12
+ "normalized": false,
13
+ "rstrip": false,
14
+ "single_word": false
15
+ },
16
+ "eos_token": {
17
+ "content": "</s>",
18
+ "lstrip": false,
19
+ "normalized": false,
20
+ "rstrip": false,
21
+ "single_word": false
22
+ },
23
+ "mask_token": {
24
+ "content": "<mask>",
25
+ "lstrip": true,
26
+ "normalized": false,
27
+ "rstrip": false,
28
+ "single_word": false
29
+ },
30
+ "pad_token": {
31
+ "content": "<pad>",
32
+ "lstrip": false,
33
+ "normalized": false,
34
+ "rstrip": false,
35
+ "single_word": false
36
+ },
37
+ "sep_token": {
38
+ "content": "</s>",
39
+ "lstrip": false,
40
+ "normalized": false,
41
+ "rstrip": false,
42
+ "single_word": false
43
+ },
44
+ "unk_token": {
45
+ "content": "<unk>",
46
+ "lstrip": false,
47
+ "normalized": false,
48
+ "rstrip": false,
49
+ "single_word": false
50
+ }
51
+ }
tokenizer.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f1cc44ad7faaeec47241864835473fd5403f2da94673f3f764a77ebcb0a803ec
3
+ size 17083009
tokenizer_config.json ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "added_tokens_decoder": {
3
+ "0": {
4
+ "content": "<s>",
5
+ "lstrip": false,
6
+ "normalized": false,
7
+ "rstrip": false,
8
+ "single_word": false,
9
+ "special": true
10
+ },
11
+ "1": {
12
+ "content": "<pad>",
13
+ "lstrip": false,
14
+ "normalized": false,
15
+ "rstrip": false,
16
+ "single_word": false,
17
+ "special": true
18
+ },
19
+ "2": {
20
+ "content": "</s>",
21
+ "lstrip": false,
22
+ "normalized": false,
23
+ "rstrip": false,
24
+ "single_word": false,
25
+ "special": true
26
+ },
27
+ "3": {
28
+ "content": "<unk>",
29
+ "lstrip": false,
30
+ "normalized": false,
31
+ "rstrip": false,
32
+ "single_word": false,
33
+ "special": true
34
+ },
35
+ "250001": {
36
+ "content": "<mask>",
37
+ "lstrip": true,
38
+ "normalized": false,
39
+ "rstrip": false,
40
+ "single_word": false,
41
+ "special": true
42
+ }
43
+ },
44
+ "bos_token": "<s>",
45
+ "clean_up_tokenization_spaces": true,
46
+ "cls_token": "<s>",
47
+ "eos_token": "</s>",
48
+ "mask_token": "<mask>",
49
+ "max_length": 512,
50
+ "model_max_length": 32768,
51
+ "pad_to_multiple_of": null,
52
+ "pad_token": "<pad>",
53
+ "pad_token_type_id": 0,
54
+ "padding_side": "right",
55
+ "sep_token": "</s>",
56
+ "stride": 0,
57
+ "tokenizer_class": "XLMRobertaTokenizer",
58
+ "truncation_side": "right",
59
+ "truncation_strategy": "longest_first",
60
+ "unk_token": "<unk>"
61
+ }