Upload model
Browse files- config.json +46 -0
- modeling_lsg_bert.py +1204 -0
- pytorch_model.bin +3 -0
config.json
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"_name_or_path": "thenlper/gte-small",
|
| 3 |
+
"adaptive": true,
|
| 4 |
+
"architectures": [
|
| 5 |
+
"LSGBertModel"
|
| 6 |
+
],
|
| 7 |
+
"attention_probs_dropout_prob": 0.1,
|
| 8 |
+
"auto_map": {
|
| 9 |
+
"AutoConfig": "modeling_lsg_bert.LSGBertConfig",
|
| 10 |
+
"AutoModel": "modeling_lsg_bert.LSGBertModel",
|
| 11 |
+
"AutoModelForCausalLM": "modeling_lsg_bert.LSGBertLMHeadModel",
|
| 12 |
+
"AutoModelForMaskedLM": "modeling_lsg_bert.LSGBertForMaskedLM",
|
| 13 |
+
"AutoModelForMultipleChoice": "modeling_lsg_bert.LSGBertForMultipleChoice",
|
| 14 |
+
"AutoModelForPreTraining": "modeling_lsg_bert.LSGBertForPreTraining",
|
| 15 |
+
"AutoModelForQuestionAnswering": "modeling_lsg_bert.LSGBertForQuestionAnswering",
|
| 16 |
+
"AutoModelForSequenceClassification": "modeling_lsg_bert.LSGBertForSequenceClassification",
|
| 17 |
+
"AutoModelForTokenClassification": "modeling_lsg_bert.LSGBertForTokenClassification"
|
| 18 |
+
},
|
| 19 |
+
"base_model_prefix": "lsg",
|
| 20 |
+
"block_size": 128,
|
| 21 |
+
"classifier_dropout": null,
|
| 22 |
+
"hidden_act": "gelu",
|
| 23 |
+
"hidden_dropout_prob": 0.1,
|
| 24 |
+
"hidden_size": 384,
|
| 25 |
+
"initializer_range": 0.02,
|
| 26 |
+
"intermediate_size": 1536,
|
| 27 |
+
"layer_norm_eps": 1e-12,
|
| 28 |
+
"lsh_num_pre_rounds": 1,
|
| 29 |
+
"mask_first_token": false,
|
| 30 |
+
"max_position_embeddings": 4096,
|
| 31 |
+
"model_type": "bert",
|
| 32 |
+
"num_attention_heads": 12,
|
| 33 |
+
"num_global_tokens": 1,
|
| 34 |
+
"num_hidden_layers": 12,
|
| 35 |
+
"pad_token_id": 0,
|
| 36 |
+
"pool_with_global": true,
|
| 37 |
+
"position_embedding_type": "absolute",
|
| 38 |
+
"sparse_block_size": 128,
|
| 39 |
+
"sparsity_factor": 2,
|
| 40 |
+
"sparsity_type": "norm",
|
| 41 |
+
"torch_dtype": "float32",
|
| 42 |
+
"transformers_version": "4.31.0",
|
| 43 |
+
"type_vocab_size": 2,
|
| 44 |
+
"use_cache": true,
|
| 45 |
+
"vocab_size": 30522
|
| 46 |
+
}
|
modeling_lsg_bert.py
ADDED
|
@@ -0,0 +1,1204 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from logging import warn
|
| 2 |
+
from transformers.models.bert.modeling_bert import *
|
| 3 |
+
import torch
|
| 4 |
+
import torch.nn as nn
|
| 5 |
+
from transformers.models.bert.configuration_bert import BertConfig
|
| 6 |
+
import sys
|
| 7 |
+
|
| 8 |
+
AUTO_MAP = {
|
| 9 |
+
"AutoModel": "modeling_lsg_bert.LSGBertModel",
|
| 10 |
+
"AutoModelForCausalLM": "modeling_lsg_bert.LSGBertLMHeadModel",
|
| 11 |
+
"AutoModelForMaskedLM": "modeling_lsg_bert.LSGBertForMaskedLM",
|
| 12 |
+
"AutoModelForPreTraining": "modeling_lsg_bert.LSGBertForPreTraining",
|
| 13 |
+
"AutoModelForMultipleChoice": "modeling_lsg_bert.LSGBertForMultipleChoice",
|
| 14 |
+
"AutoModelForQuestionAnswering": "modeling_lsg_bert.LSGBertForQuestionAnswering",
|
| 15 |
+
"AutoModelForSequenceClassification": "modeling_lsg_bert.LSGBertForSequenceClassification",
|
| 16 |
+
"AutoModelForTokenClassification": "modeling_lsg_bert.LSGBertForTokenClassification"
|
| 17 |
+
}
|
| 18 |
+
|
| 19 |
+
class LSGBertConfig(BertConfig):
|
| 20 |
+
"""
|
| 21 |
+
This class overrides :class:`~transformers.BertConfig`. Please check the superclass for the appropriate
|
| 22 |
+
documentation alongside usage examples.
|
| 23 |
+
"""
|
| 24 |
+
|
| 25 |
+
base_model_prefix = "lsg"
|
| 26 |
+
model_type = "bert"
|
| 27 |
+
|
| 28 |
+
def __init__(
|
| 29 |
+
self,
|
| 30 |
+
adaptive=True,
|
| 31 |
+
base_model_prefix="lsg",
|
| 32 |
+
block_size=128,
|
| 33 |
+
lsh_num_pre_rounds=1,
|
| 34 |
+
mask_first_token=False,
|
| 35 |
+
num_global_tokens=1,
|
| 36 |
+
pool_with_global=True,
|
| 37 |
+
sparse_block_size=128,
|
| 38 |
+
sparsity_factor=2,
|
| 39 |
+
sparsity_type="norm",
|
| 40 |
+
**kwargs
|
| 41 |
+
):
|
| 42 |
+
"""Constructs LSGBertConfig."""
|
| 43 |
+
super().__init__(**kwargs)
|
| 44 |
+
|
| 45 |
+
self.adaptive = adaptive
|
| 46 |
+
self.auto_map = AUTO_MAP
|
| 47 |
+
self.base_model_prefix = base_model_prefix
|
| 48 |
+
self.block_size = block_size
|
| 49 |
+
self.lsh_num_pre_rounds = lsh_num_pre_rounds
|
| 50 |
+
self.mask_first_token = mask_first_token
|
| 51 |
+
self.num_global_tokens = num_global_tokens
|
| 52 |
+
self.pool_with_global = pool_with_global
|
| 53 |
+
self.sparse_block_size = sparse_block_size
|
| 54 |
+
self.sparsity_factor = sparsity_factor
|
| 55 |
+
self.sparsity_type = sparsity_type
|
| 56 |
+
|
| 57 |
+
if sparsity_type not in [None, "none", "norm", "lsh", "pooling", "stride", "block_stride"]:
|
| 58 |
+
logger.warning(
|
| 59 |
+
"[WARNING CONFIG]: sparsity_mode not in [None, 'none', 'norm', 'lsh', 'pooling', 'stride', 'block_stride'], \
|
| 60 |
+
setting sparsity_type=None, computation will skip sparse attention")
|
| 61 |
+
self.sparsity_type = None
|
| 62 |
+
|
| 63 |
+
if self.sparsity_type in ["stride", "block_stride"]:
|
| 64 |
+
if self.sparsity_factor > self.encoder_attention_heads:
|
| 65 |
+
logger.warning(
|
| 66 |
+
"[WARNING CONFIG]: sparsity_factor > encoder_attention_heads is not recommended for stride/block_stride sparsity"
|
| 67 |
+
)
|
| 68 |
+
|
| 69 |
+
if self.num_global_tokens < 1:
|
| 70 |
+
logger.warning(
|
| 71 |
+
"[WARNING CONFIG]: num_global_tokens < 1 is not compatible, setting num_global_tokens=1"
|
| 72 |
+
)
|
| 73 |
+
self.num_global_tokens = 1
|
| 74 |
+
elif self.num_global_tokens > 512:
|
| 75 |
+
logger.warning(
|
| 76 |
+
"[WARNING CONFIG]: num_global_tokens > 512 is not allowed, setting num_global_tokens=512"
|
| 77 |
+
)
|
| 78 |
+
self.num_global_tokens = 512
|
| 79 |
+
|
| 80 |
+
if self.sparsity_factor > 0:
|
| 81 |
+
assert self.block_size % self.sparsity_factor == 0, "[ERROR CONFIG]: block_size must be divisible by sparsity_factor"
|
| 82 |
+
assert self.block_size//self.sparsity_factor >= 1, "[ERROR CONFIG]: make sure block_size >= sparsity_factor"
|
| 83 |
+
|
| 84 |
+
if self.mask_first_token and not pool_with_global:
|
| 85 |
+
logger.warning(
|
| 86 |
+
"[WARNING CONFIG]: pool_with_global==False is not compatible with mask_first_token==True. Setting pool_with_global to True.")
|
| 87 |
+
self.pool_with_global = True
|
| 88 |
+
|
| 89 |
+
if hasattr(self, "position_embedding_type"):
|
| 90 |
+
if self.position_embedding_type != "absolute":
|
| 91 |
+
logger.warning(
|
| 92 |
+
"[WARNING CONFIG]: LSG Attention is not compatible with relative positional embedding and will skip its computation. Set position_embedding_type='absolute' to remove this warning.")
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
class BaseSelfAttention(nn.Module):
|
| 96 |
+
|
| 97 |
+
def init_modules(self, config):
|
| 98 |
+
if config.hidden_size % config.num_attention_heads != 0 and not hasattr(
|
| 99 |
+
config, "embedding_size"
|
| 100 |
+
):
|
| 101 |
+
raise ValueError(
|
| 102 |
+
"The hidden size (%d) is not a multiple of the number of attention "
|
| 103 |
+
"heads (%d)" % (config.hidden_size, config.num_attention_heads)
|
| 104 |
+
)
|
| 105 |
+
|
| 106 |
+
self.num_attention_heads = config.num_attention_heads
|
| 107 |
+
self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
|
| 108 |
+
self.all_head_size = self.num_attention_heads * self.attention_head_size
|
| 109 |
+
|
| 110 |
+
self.query = nn.Linear(config.hidden_size, self.all_head_size)
|
| 111 |
+
self.key = nn.Linear(config.hidden_size, self.all_head_size)
|
| 112 |
+
self.value = nn.Linear(config.hidden_size, self.all_head_size)
|
| 113 |
+
|
| 114 |
+
self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
|
| 115 |
+
|
| 116 |
+
def transpose_for_scores(self, x):
|
| 117 |
+
new_x_shape = x.size()[:-1] + (
|
| 118 |
+
self.num_attention_heads,
|
| 119 |
+
self.attention_head_size,
|
| 120 |
+
)
|
| 121 |
+
x = x.view(*new_x_shape)
|
| 122 |
+
return x.permute(0, 2, 1, 3)
|
| 123 |
+
|
| 124 |
+
def reshape_output(self, context_layer):
|
| 125 |
+
context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
|
| 126 |
+
new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
|
| 127 |
+
return context_layer.view(*new_context_layer_shape)
|
| 128 |
+
|
| 129 |
+
def project_QKV(self, hidden_states):
|
| 130 |
+
|
| 131 |
+
query_layer = self.transpose_for_scores(self.query(hidden_states))
|
| 132 |
+
key_layer = self.transpose_for_scores(self.key(hidden_states))
|
| 133 |
+
value_layer = self.transpose_for_scores(self.value(hidden_states))
|
| 134 |
+
return query_layer, key_layer, value_layer
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
class BaseAttentionProduct(nn.Module):
|
| 138 |
+
|
| 139 |
+
def __init__(self, config):
|
| 140 |
+
"""
|
| 141 |
+
Compute attention: softmax(Q @ K.T) @ V
|
| 142 |
+
"""
|
| 143 |
+
super().__init__()
|
| 144 |
+
self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
|
| 145 |
+
|
| 146 |
+
def forward(self, query_layer, key_layer, value_layer, attention_mask=None):
|
| 147 |
+
|
| 148 |
+
d = query_layer.shape[-1]
|
| 149 |
+
|
| 150 |
+
# Take the dot product between "query" and "key" to get the raw attention scores.
|
| 151 |
+
attention_scores = query_layer @ key_layer.transpose(-1, -2) / math.sqrt(d)
|
| 152 |
+
|
| 153 |
+
del query_layer
|
| 154 |
+
del key_layer
|
| 155 |
+
|
| 156 |
+
if attention_mask is not None:
|
| 157 |
+
# Apply the attention mask is (precomputed for all layers in BertModel forward() function)
|
| 158 |
+
attention_scores = attention_scores + attention_mask
|
| 159 |
+
del attention_mask
|
| 160 |
+
|
| 161 |
+
# Normalize the attention scores to probabilities.
|
| 162 |
+
attention_probs = nn.Softmax(dim=-1)(attention_scores)
|
| 163 |
+
|
| 164 |
+
# This is actually dropping out entire tokens to attend to, which might
|
| 165 |
+
# seem a bit unusual, but is taken from the original Transformer paper.
|
| 166 |
+
context_layer = self.dropout(attention_probs) @ value_layer
|
| 167 |
+
|
| 168 |
+
return context_layer
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
class CausalAttentionProduct(nn.Module):
|
| 172 |
+
|
| 173 |
+
def __init__(self, config):
|
| 174 |
+
"""
|
| 175 |
+
Compute attention: softmax(Q @ K.T) @ V
|
| 176 |
+
"""
|
| 177 |
+
super().__init__()
|
| 178 |
+
self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
|
| 179 |
+
self.block_size = config.block_size
|
| 180 |
+
|
| 181 |
+
def forward(self, query_layer, key_layer, value_layer, attention_mask=None, causal_shape=None):
|
| 182 |
+
|
| 183 |
+
d = query_layer.shape[-1]
|
| 184 |
+
|
| 185 |
+
# Take the dot product between "query" and "key" to get the raw attention scores.
|
| 186 |
+
attention_scores = query_layer @ key_layer.transpose(-1, -2) / math.sqrt(d)
|
| 187 |
+
|
| 188 |
+
del query_layer
|
| 189 |
+
del key_layer
|
| 190 |
+
|
| 191 |
+
if attention_mask is not None:
|
| 192 |
+
# Add causal mask
|
| 193 |
+
causal_shape = (self.block_size, self.block_size) if causal_shape is None else causal_shape
|
| 194 |
+
causal_mask = torch.tril(
|
| 195 |
+
torch.ones(*causal_shape, device=attention_mask.device, dtype=attention_scores.dtype),
|
| 196 |
+
diagonal=-1
|
| 197 |
+
)
|
| 198 |
+
|
| 199 |
+
# Min value
|
| 200 |
+
dtype_min = torch.tensor(
|
| 201 |
+
torch.finfo(attention_scores.dtype).min, device=attention_scores.device, dtype=attention_scores.dtype
|
| 202 |
+
)
|
| 203 |
+
|
| 204 |
+
# Build causal + attention_mask
|
| 205 |
+
causal_mask = torch.nn.functional.pad(causal_mask.T * dtype_min, (attention_mask.size()[-1] - self.block_size, 0), value=0)
|
| 206 |
+
attention_mask = torch.max(attention_mask + causal_mask.unsqueeze(0).unsqueeze(0).unsqueeze(0), dtype_min)
|
| 207 |
+
|
| 208 |
+
attention_scores = attention_scores + attention_mask
|
| 209 |
+
del attention_mask
|
| 210 |
+
del causal_mask
|
| 211 |
+
|
| 212 |
+
# Normalize the attention scores to probabilities.
|
| 213 |
+
attention_probs = nn.Softmax(dim=-1)(attention_scores)
|
| 214 |
+
|
| 215 |
+
# This is actually dropping out entire tokens to attend to, which might
|
| 216 |
+
# seem a bit unusual, but is taken from the original Transformer paper.
|
| 217 |
+
context_layer = self.dropout(attention_probs) @ value_layer
|
| 218 |
+
|
| 219 |
+
return context_layer
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
class LSGAttentionProduct(nn.Module):
|
| 223 |
+
|
| 224 |
+
def __init__(self, config, block_size=None, sparse_block_size=None, sparsity_factor=4, is_causal=False):
|
| 225 |
+
"""
|
| 226 |
+
Compute block or overlapping blocks attention products
|
| 227 |
+
"""
|
| 228 |
+
super().__init__()
|
| 229 |
+
|
| 230 |
+
self.block_size = block_size
|
| 231 |
+
self.sparse_block_size = sparse_block_size
|
| 232 |
+
self.sparsity_factor = sparsity_factor
|
| 233 |
+
self.is_causal = is_causal
|
| 234 |
+
|
| 235 |
+
if self.block_size is None:
|
| 236 |
+
self.block_size = config.block_size
|
| 237 |
+
|
| 238 |
+
if self.sparse_block_size is None:
|
| 239 |
+
self.sparse_block_size = config.sparse_block_size
|
| 240 |
+
|
| 241 |
+
# Shape of blocks
|
| 242 |
+
self.local_shapes = (self.block_size*3, self.block_size)
|
| 243 |
+
if self.sparse_block_size and self.sparsity_factor > 0:
|
| 244 |
+
self.sparse_shapes = (self.sparse_block_size*3, self.block_size//self.sparsity_factor)
|
| 245 |
+
|
| 246 |
+
if is_causal:
|
| 247 |
+
self.attention = CausalAttentionProduct(config)
|
| 248 |
+
else:
|
| 249 |
+
self.attention = BaseAttentionProduct(config)
|
| 250 |
+
|
| 251 |
+
def build_lsg_inputs(self, hidden_states, sparse_hidden_states, global_hidden_states, is_attn_mask=False):
|
| 252 |
+
|
| 253 |
+
# Build local tokens
|
| 254 |
+
local_hidden_states = self.reshape_to_local_block(hidden_states, is_attn_mask)
|
| 255 |
+
del hidden_states
|
| 256 |
+
|
| 257 |
+
# Build sparse tokens
|
| 258 |
+
if sparse_hidden_states is not None:
|
| 259 |
+
sparse_hidden_states = self.reshape_to_sparse_block(sparse_hidden_states, is_attn_mask)
|
| 260 |
+
|
| 261 |
+
return self.cat_global_sparse_local_tokens(global_hidden_states, sparse_hidden_states, local_hidden_states)
|
| 262 |
+
|
| 263 |
+
def forward(
|
| 264 |
+
self,
|
| 265 |
+
query_layer,
|
| 266 |
+
key_layer,
|
| 267 |
+
value_layer,
|
| 268 |
+
attention_mask=None,
|
| 269 |
+
sparse_key=None,
|
| 270 |
+
sparse_value=None,
|
| 271 |
+
sparse_mask=None,
|
| 272 |
+
global_key=None,
|
| 273 |
+
global_value=None,
|
| 274 |
+
global_mask=None
|
| 275 |
+
):
|
| 276 |
+
|
| 277 |
+
# Input batch, heads, length, hidden_size
|
| 278 |
+
n, h, t, d = query_layer.size()
|
| 279 |
+
n_blocks = t // self.block_size
|
| 280 |
+
assert t % self.block_size == 0
|
| 281 |
+
|
| 282 |
+
key_layer = self.build_lsg_inputs(
|
| 283 |
+
key_layer,
|
| 284 |
+
sparse_key,
|
| 285 |
+
global_key
|
| 286 |
+
)
|
| 287 |
+
del sparse_key
|
| 288 |
+
del global_key
|
| 289 |
+
|
| 290 |
+
value_layer = self.build_lsg_inputs(
|
| 291 |
+
value_layer,
|
| 292 |
+
sparse_value,
|
| 293 |
+
global_value
|
| 294 |
+
)
|
| 295 |
+
del sparse_value
|
| 296 |
+
del global_value
|
| 297 |
+
|
| 298 |
+
attention_mask = self.build_lsg_inputs(
|
| 299 |
+
attention_mask,
|
| 300 |
+
sparse_mask,
|
| 301 |
+
global_mask.transpose(-1, -2),
|
| 302 |
+
is_attn_mask=True
|
| 303 |
+
).transpose(-1, -2)
|
| 304 |
+
del sparse_mask
|
| 305 |
+
del global_mask
|
| 306 |
+
|
| 307 |
+
# expect (..., t, d) shape
|
| 308 |
+
# Compute attention
|
| 309 |
+
context_layer = self.attention(
|
| 310 |
+
query_layer=self.chunk(query_layer, n_blocks),
|
| 311 |
+
key_layer=key_layer,
|
| 312 |
+
value_layer=value_layer,
|
| 313 |
+
attention_mask=attention_mask
|
| 314 |
+
)
|
| 315 |
+
|
| 316 |
+
return context_layer.reshape(n, h, -1, d)
|
| 317 |
+
|
| 318 |
+
def reshape_to_local_block(self, hidden_states, is_attn_mask=False):
|
| 319 |
+
|
| 320 |
+
size, step = self.local_shapes
|
| 321 |
+
s = (size - step) // 2
|
| 322 |
+
|
| 323 |
+
# Pad before block reshaping
|
| 324 |
+
if is_attn_mask:
|
| 325 |
+
pad_value = torch.finfo(hidden_states.dtype).min
|
| 326 |
+
hidden_states = hidden_states.transpose(-1, -2)
|
| 327 |
+
else:
|
| 328 |
+
pad_value = 0
|
| 329 |
+
|
| 330 |
+
hidden_states = torch.nn.functional.pad(
|
| 331 |
+
hidden_states.transpose(-1, -2),
|
| 332 |
+
pad=(s, s),
|
| 333 |
+
value=pad_value
|
| 334 |
+
).transpose(-1, -2)
|
| 335 |
+
|
| 336 |
+
# Make blocks
|
| 337 |
+
hidden_states = hidden_states.unfold(-2, size=size, step=step).transpose(-1, -2)
|
| 338 |
+
|
| 339 |
+
# Skip third block if causal
|
| 340 |
+
if self.is_causal:
|
| 341 |
+
return hidden_states[..., :size*2//3, :]
|
| 342 |
+
|
| 343 |
+
return hidden_states
|
| 344 |
+
|
| 345 |
+
def reshape_to_sparse_block(self, hidden_states, is_attn_mask=False):
|
| 346 |
+
|
| 347 |
+
size, step = self.sparse_shapes
|
| 348 |
+
|
| 349 |
+
# In case of odd case
|
| 350 |
+
odd_offset = (step % 2)
|
| 351 |
+
|
| 352 |
+
# n, h, t, d*2 + 1
|
| 353 |
+
size = size*2
|
| 354 |
+
s = (size - step) // 2 + odd_offset
|
| 355 |
+
|
| 356 |
+
# Pad before block reshaping
|
| 357 |
+
if is_attn_mask:
|
| 358 |
+
pad_value = torch.finfo(hidden_states.dtype).min
|
| 359 |
+
hidden_states = hidden_states.transpose(-1, -2)
|
| 360 |
+
else:
|
| 361 |
+
pad_value = 0
|
| 362 |
+
|
| 363 |
+
hidden_states = torch.nn.functional.pad(
|
| 364 |
+
hidden_states.transpose(-1, -2),
|
| 365 |
+
pad=(s, s),
|
| 366 |
+
value=pad_value
|
| 367 |
+
).transpose(-1, -2)
|
| 368 |
+
|
| 369 |
+
# Make blocks
|
| 370 |
+
hidden_states = hidden_states.unfold(-2, size=size, step=step).transpose(-1, -2)
|
| 371 |
+
|
| 372 |
+
# Fix case where block_size == sparsify_factor
|
| 373 |
+
if odd_offset:
|
| 374 |
+
hidden_states = hidden_states[..., :-1, :, :]
|
| 375 |
+
|
| 376 |
+
# Indexes for selection
|
| 377 |
+
u = (size - self.block_size * 3 // self.sparsity_factor) // 2 + odd_offset
|
| 378 |
+
s = self.sparse_block_size
|
| 379 |
+
|
| 380 |
+
# Skip right block if causal
|
| 381 |
+
if self.is_causal:
|
| 382 |
+
return hidden_states[..., u-s:u, :]
|
| 383 |
+
|
| 384 |
+
u_ = u + odd_offset
|
| 385 |
+
return torch.cat([hidden_states[..., u-s:u, :], hidden_states[..., -u_:-u_+s, :]], dim=-2)
|
| 386 |
+
|
| 387 |
+
def cat_global_sparse_local_tokens(self, x_global, x_sparse=None, x_local=None, dim=-2):
|
| 388 |
+
|
| 389 |
+
n, h, b, t, d = x_local.size()
|
| 390 |
+
x_global = x_global.unsqueeze(-3).expand(-1, -1, b, -1, -1)
|
| 391 |
+
if x_sparse is not None:
|
| 392 |
+
return torch.cat([x_global, x_sparse, x_local], dim=dim)
|
| 393 |
+
return torch.cat([x_global, x_local], dim=dim)
|
| 394 |
+
|
| 395 |
+
def chunk(self, x, n_blocks):
|
| 396 |
+
|
| 397 |
+
t, d = x.size()[-2:]
|
| 398 |
+
return x.reshape(*x.size()[:-2], n_blocks, -1, d)
|
| 399 |
+
|
| 400 |
+
|
| 401 |
+
class LSGBertEmbeddings(BertEmbeddings):
|
| 402 |
+
|
| 403 |
+
def __init__(self, config):
|
| 404 |
+
super().__init__(config)
|
| 405 |
+
|
| 406 |
+
self.num_global_tokens = config.num_global_tokens
|
| 407 |
+
|
| 408 |
+
# Hardcoded but partially trained
|
| 409 |
+
self.global_embeddings = nn.Embedding(512, embedding_dim=config.hidden_size, )
|
| 410 |
+
|
| 411 |
+
self.block_size = config.block_size
|
| 412 |
+
|
| 413 |
+
def forward(
|
| 414 |
+
self, input_ids=None, token_type_ids=None, position_ids=None, inputs_embeds=None, past_key_values_length=0
|
| 415 |
+
):
|
| 416 |
+
if input_ids is not None:
|
| 417 |
+
input_shape = input_ids.size()
|
| 418 |
+
else:
|
| 419 |
+
input_shape = inputs_embeds.size()[:-1]
|
| 420 |
+
|
| 421 |
+
seq_length = input_shape[1]
|
| 422 |
+
|
| 423 |
+
if position_ids is None:
|
| 424 |
+
position_ids = self.position_ids[:, past_key_values_length : seq_length + past_key_values_length]
|
| 425 |
+
|
| 426 |
+
# Setting the token_type_ids to the registered buffer in constructor where it is all zeros, which usually occurs
|
| 427 |
+
# when its auto-generated, registered buffer helps users when tracing the model without passing token_type_ids, solves
|
| 428 |
+
# issue #5664
|
| 429 |
+
if token_type_ids is None:
|
| 430 |
+
if hasattr(self, "token_type_ids"):
|
| 431 |
+
buffered_token_type_ids = self.token_type_ids[:, :seq_length]
|
| 432 |
+
buffered_token_type_ids_expanded = buffered_token_type_ids.expand(input_shape[0], seq_length)
|
| 433 |
+
token_type_ids = buffered_token_type_ids_expanded
|
| 434 |
+
else:
|
| 435 |
+
token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device)
|
| 436 |
+
|
| 437 |
+
if inputs_embeds is None:
|
| 438 |
+
inputs_embeds = self.word_embeddings(input_ids)
|
| 439 |
+
token_type_embeddings = self.token_type_embeddings(token_type_ids[:, :seq_length])
|
| 440 |
+
|
| 441 |
+
embeddings = inputs_embeds + token_type_embeddings
|
| 442 |
+
if self.position_embedding_type == "absolute":
|
| 443 |
+
position_embeddings = self.position_embeddings(position_ids[:, :seq_length])
|
| 444 |
+
embeddings += position_embeddings
|
| 445 |
+
|
| 446 |
+
#if self.num_global_tokens < 0:
|
| 447 |
+
n, t, d = embeddings.size()
|
| 448 |
+
|
| 449 |
+
# Add global_tokens
|
| 450 |
+
indexes = torch.arange(self.num_global_tokens, device=embeddings.device).reshape(1, -1)
|
| 451 |
+
global_embeddings = self.global_embeddings(indexes)
|
| 452 |
+
embeddings = torch.cat([global_embeddings.expand(n, -1, d), embeddings], dim=-2)
|
| 453 |
+
|
| 454 |
+
embeddings = self.LayerNorm(embeddings)
|
| 455 |
+
embeddings = self.dropout(embeddings)
|
| 456 |
+
return embeddings
|
| 457 |
+
|
| 458 |
+
|
| 459 |
+
class LSGSelfAttention(BaseSelfAttention):
|
| 460 |
+
'''
|
| 461 |
+
Compute local attention with overlapping blocs
|
| 462 |
+
Use global attention for tokens with highest norm
|
| 463 |
+
'''
|
| 464 |
+
def __init__(self, config):
|
| 465 |
+
super().__init__()
|
| 466 |
+
|
| 467 |
+
self.init_modules(config)
|
| 468 |
+
|
| 469 |
+
self.block_size = config.block_size
|
| 470 |
+
self.sparse_block_size = config.sparse_block_size
|
| 471 |
+
self.num_global_tokens = config.num_global_tokens
|
| 472 |
+
self.sparsity_factor = config.sparsity_factor
|
| 473 |
+
self.is_causal = config.is_decoder
|
| 474 |
+
self.is_decoder = config.is_decoder
|
| 475 |
+
|
| 476 |
+
self.attention = LSGAttentionProduct(
|
| 477 |
+
config,
|
| 478 |
+
block_size=config.block_size,
|
| 479 |
+
sparse_block_size=config.sparse_block_size,
|
| 480 |
+
sparsity_factor=self.sparsity_factor,
|
| 481 |
+
is_causal=self.is_causal
|
| 482 |
+
)
|
| 483 |
+
|
| 484 |
+
if self.is_causal:
|
| 485 |
+
self.causal_attention = CausalAttentionProduct(config)
|
| 486 |
+
self.full_attention = BaseAttentionProduct(config)
|
| 487 |
+
|
| 488 |
+
sparse_functions = {
|
| 489 |
+
"norm": self.get_sparse_tokens_with_norm,
|
| 490 |
+
"pooling": self.get_sparse_tokens_with_pooling,
|
| 491 |
+
"lsh": self.get_sparse_tokens_with_lsh,
|
| 492 |
+
"stride": self.get_sparse_tokens_with_stride,
|
| 493 |
+
"block_stride": self.get_sparse_tokens_with_block_stride,
|
| 494 |
+
}
|
| 495 |
+
|
| 496 |
+
self.sparsity_type = config.sparsity_type
|
| 497 |
+
self.get_sparse_elements = sparse_functions.get(self.sparsity_type, lambda x, y, z: (None, None, None))
|
| 498 |
+
|
| 499 |
+
if config.sparsity_type == "lsh":
|
| 500 |
+
self.lsh_num_pre_rounds = config.lsh_num_pre_rounds
|
| 501 |
+
|
| 502 |
+
def get_sparse_tokens_with_norm(self, keys, values, mask):
|
| 503 |
+
|
| 504 |
+
if self.sparsity_factor == 1:
|
| 505 |
+
return keys, values, mask.expand(-1, keys.size()[1], -1, -1)
|
| 506 |
+
|
| 507 |
+
with torch.no_grad():
|
| 508 |
+
|
| 509 |
+
block_size = min(self.block_size, self.sparse_block_size)
|
| 510 |
+
key_norm = keys.detach().norm(dim=-1, keepdim=True)
|
| 511 |
+
key_norm = key_norm * ~mask.transpose(-1, -2).bool()
|
| 512 |
+
key_norm = self.chunk(key_norm, block_size)
|
| 513 |
+
|
| 514 |
+
n, h, b, t, d = key_norm.size()
|
| 515 |
+
|
| 516 |
+
idx = key_norm.argsort(dim=-2)
|
| 517 |
+
del key_norm
|
| 518 |
+
idx += (torch.arange(b, device=keys.device)*t).reshape(1, 1, b, 1, 1)
|
| 519 |
+
|
| 520 |
+
split = (t - block_size // self.sparsity_factor, block_size // self.sparsity_factor)
|
| 521 |
+
sparse_idx = idx.split(split, -2)[-1].reshape(n, h, -1, 1)
|
| 522 |
+
|
| 523 |
+
d = keys.size()[-1]
|
| 524 |
+
keys = keys.gather(dim=-2, index=sparse_idx.expand(-1, -1, -1, d))
|
| 525 |
+
values = values.gather(dim=-2, index=sparse_idx.expand(-1, -1, -1, d))
|
| 526 |
+
mask = mask.expand(-1, h, -1, -1).transpose(-1, -2).gather(dim=-2, index=sparse_idx).transpose(-1, -2)
|
| 527 |
+
|
| 528 |
+
return keys, values, mask
|
| 529 |
+
|
| 530 |
+
def get_sparse_tokens_with_pooling(self, keys, values, mask):
|
| 531 |
+
|
| 532 |
+
if self.sparsity_factor == 1:
|
| 533 |
+
return keys, values, mask.expand(-1, keys.size()[1], -1, -1)
|
| 534 |
+
|
| 535 |
+
keys = self.chunk(keys, self.sparsity_factor)
|
| 536 |
+
values = self.chunk(values, self.sparsity_factor)
|
| 537 |
+
|
| 538 |
+
n, h, b, t, d = keys.size()
|
| 539 |
+
mask = mask.reshape(n, 1, b, 1, t)
|
| 540 |
+
mask = ~mask.transpose(-1, -2).bool()
|
| 541 |
+
|
| 542 |
+
keys = keys * mask
|
| 543 |
+
values = values * mask
|
| 544 |
+
|
| 545 |
+
mask = mask.sum(dim=-2)
|
| 546 |
+
keys = keys.sum(dim=-2) / (mask + 1e-6)
|
| 547 |
+
values = values.sum(dim=-2) / (mask + 1e-6)
|
| 548 |
+
|
| 549 |
+
mask = (1. - mask.clamp(0, 1))
|
| 550 |
+
mask *= torch.finfo(mask.dtype).min
|
| 551 |
+
return keys.reshape(n, h, -1, d), values.reshape(n, h, -1, d), mask.expand(-1, h, -1, -1).transpose(-1, -2)
|
| 552 |
+
|
| 553 |
+
def get_sparse_tokens_with_stride(self, keys, values, mask):
|
| 554 |
+
|
| 555 |
+
if self.sparsity_factor == 1:
|
| 556 |
+
return keys, values, mask.expand(-1, keys.size()[1], -1, -1)
|
| 557 |
+
|
| 558 |
+
n, h, t, d = keys.size()
|
| 559 |
+
sparse_idx = torch.arange(t // self.sparsity_factor, device=keys.device) * self.sparsity_factor
|
| 560 |
+
sparse_idx = sparse_idx.reshape(1, 1, -1, 1) + (torch.arange(h, device=keys.device) % self.sparsity_factor).reshape(1, h, 1, 1)
|
| 561 |
+
sparse_idx = sparse_idx.expand(n, h, -1, 1)
|
| 562 |
+
|
| 563 |
+
keys = keys.gather(dim=-2, index=sparse_idx.expand(-1, -1, -1, d))
|
| 564 |
+
values = values.gather(dim=-2, index=sparse_idx.expand(-1, -1, -1, d))
|
| 565 |
+
mask = mask.expand(-1, h, -1, -1).transpose(-1, -2).gather(dim=-2, index=sparse_idx).transpose(-1, -2)
|
| 566 |
+
|
| 567 |
+
return keys, values, mask
|
| 568 |
+
|
| 569 |
+
def get_sparse_tokens_with_block_stride(self, keys, values, mask):
|
| 570 |
+
|
| 571 |
+
if self.sparsity_factor == 1:
|
| 572 |
+
return keys, values, mask.expand(-1, keys.size()[1], -1, -1)
|
| 573 |
+
|
| 574 |
+
n, h, t, d = keys.size()
|
| 575 |
+
|
| 576 |
+
t, b = self.block_size, t // self.block_size
|
| 577 |
+
sparse_idx = torch.arange(t // self.sparsity_factor, device=keys.device)
|
| 578 |
+
sparse_idx = sparse_idx.reshape(1, 1, 1, -1, 1) + torch.arange(h, device=keys.device).reshape(1, h, 1, 1, 1) * (t // self.sparsity_factor)
|
| 579 |
+
sparse_idx = (sparse_idx % t)
|
| 580 |
+
sparse_idx = sparse_idx + torch.arange(b, device=keys.device).reshape(1, 1, -1, 1, 1) * t
|
| 581 |
+
sparse_idx = sparse_idx.reshape(1, h, -1, 1).expand(n, h, -1, 1)
|
| 582 |
+
|
| 583 |
+
keys = keys.gather(dim=-2, index=sparse_idx.expand(-1, -1, -1, d))
|
| 584 |
+
values = values.gather(dim=-2, index=sparse_idx.expand(-1, -1, -1, d))
|
| 585 |
+
mask = mask.expand(-1, h, -1, -1).transpose(-1, -2).gather(dim=-2, index=sparse_idx).transpose(-1, -2)
|
| 586 |
+
|
| 587 |
+
return keys, values, mask
|
| 588 |
+
|
| 589 |
+
def get_sparse_tokens_with_lsh(self, keys, values, mask):
|
| 590 |
+
|
| 591 |
+
if self.sparsity_factor == 1:
|
| 592 |
+
return keys, values, mask.expand(-1, keys.size()[1], -1, -1)
|
| 593 |
+
|
| 594 |
+
block_size = min(self.block_size, self.sparse_block_size)
|
| 595 |
+
keys = self.chunk(keys, block_size)
|
| 596 |
+
values = self.chunk(values, block_size)
|
| 597 |
+
|
| 598 |
+
n, h, b, t, d = keys.size()
|
| 599 |
+
mask = mask.reshape(n, 1, b, 1, t)
|
| 600 |
+
mask = ~mask.transpose(-1, -2).bool()
|
| 601 |
+
|
| 602 |
+
keys = keys * mask
|
| 603 |
+
values = values * mask
|
| 604 |
+
mask = mask.expand(-1, h, -1, -1, -1).float()
|
| 605 |
+
|
| 606 |
+
extra_factor = 1
|
| 607 |
+
|
| 608 |
+
for _ in range(self.lsh_num_pre_rounds):
|
| 609 |
+
keys, values, mask = self.lsh_round(keys, values, mask, t*extra_factor)
|
| 610 |
+
|
| 611 |
+
keys, values, mask = self.lsh_round(keys, values, mask, t//self.sparsity_factor)
|
| 612 |
+
keys /= mask + 1e-8
|
| 613 |
+
values /= mask + 1e-8
|
| 614 |
+
|
| 615 |
+
mask = (1. - mask.clamp(0, 1))
|
| 616 |
+
mask *= torch.finfo(mask.dtype).min
|
| 617 |
+
|
| 618 |
+
return keys.reshape(n, h, -1, d), values.reshape(n, h, -1, d), mask.transpose(-1, -2).reshape(n, h, 1, -1)
|
| 619 |
+
|
| 620 |
+
def lsh_round(self, keys, values, mask, output_size):
|
| 621 |
+
|
| 622 |
+
with torch.no_grad():
|
| 623 |
+
|
| 624 |
+
n_hashes = output_size // 2
|
| 625 |
+
n, h, b, t, d = keys.size()
|
| 626 |
+
binary_mask = mask.clamp(0, 1)
|
| 627 |
+
|
| 628 |
+
indexes = (torch.nn.functional.normalize(keys, dim=-1) * binary_mask) @ torch.randn(1, h, 1, d, n_hashes, device=keys.device)
|
| 629 |
+
indexes = torch.cat([indexes, -indexes], dim=-1).argmax(dim=-1, keepdim=True)
|
| 630 |
+
|
| 631 |
+
n, h, b, t, d = keys.size()
|
| 632 |
+
|
| 633 |
+
x_ = torch.zeros(n, h, b, output_size, d, device=keys.device)
|
| 634 |
+
mask_ = torch.zeros(n, h, b, output_size, 1, device=keys.device)
|
| 635 |
+
keys = torch.scatter_add(x_, dim=-2, index=indexes.expand(-1, -1, -1, -1, d), src=keys)
|
| 636 |
+
values = torch.scatter_add(x_, dim=-2, index=indexes.expand(-1, -1, -1, -1, d), src=values)
|
| 637 |
+
mask = torch.scatter_add(mask_, dim=-2, index=indexes, src=mask)
|
| 638 |
+
|
| 639 |
+
return keys[..., :output_size, :], values[..., :output_size, :], mask[..., :output_size, :]
|
| 640 |
+
|
| 641 |
+
def forward(
|
| 642 |
+
self,
|
| 643 |
+
hidden_states,
|
| 644 |
+
attention_mask=None,
|
| 645 |
+
head_mask=None,
|
| 646 |
+
encoder_hidden_states=None,
|
| 647 |
+
encoder_attention_mask=None,
|
| 648 |
+
past_key_value=None,
|
| 649 |
+
output_attentions=False,
|
| 650 |
+
):
|
| 651 |
+
|
| 652 |
+
query_layer = self.query(hidden_states)
|
| 653 |
+
|
| 654 |
+
# If this is instantiated as a cross-attention module, the keys
|
| 655 |
+
# and values come from an encoder; the attention mask needs to be
|
| 656 |
+
# such that the encoder's padding tokens are not attended to.
|
| 657 |
+
is_cross_attention = encoder_hidden_states is not None
|
| 658 |
+
|
| 659 |
+
if is_cross_attention and past_key_value is not None:
|
| 660 |
+
# reuse k,v, cross_attentions
|
| 661 |
+
key_layer = past_key_value[0]
|
| 662 |
+
value_layer = past_key_value[1]
|
| 663 |
+
attention_mask = encoder_attention_mask
|
| 664 |
+
elif is_cross_attention:
|
| 665 |
+
key_layer = self.transpose_for_scores(self.key(encoder_hidden_states))
|
| 666 |
+
value_layer = self.transpose_for_scores(self.value(encoder_hidden_states))
|
| 667 |
+
attention_mask = encoder_attention_mask
|
| 668 |
+
elif past_key_value is not None:
|
| 669 |
+
key_layer = self.transpose_for_scores(self.key(hidden_states))
|
| 670 |
+
value_layer = self.transpose_for_scores(self.value(hidden_states))
|
| 671 |
+
key_layer = torch.cat([past_key_value[0], key_layer], dim=2)
|
| 672 |
+
value_layer = torch.cat([past_key_value[1], value_layer], dim=2)
|
| 673 |
+
else:
|
| 674 |
+
key_layer = self.transpose_for_scores(self.key(hidden_states))
|
| 675 |
+
value_layer = self.transpose_for_scores(self.value(hidden_states))
|
| 676 |
+
|
| 677 |
+
query_layer = self.transpose_for_scores(query_layer)
|
| 678 |
+
|
| 679 |
+
if self.is_decoder:
|
| 680 |
+
# if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states.
|
| 681 |
+
# Further calls to cross_attention layer can then reuse all cross-attention
|
| 682 |
+
# key/value_states (first "if" case)
|
| 683 |
+
# if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of
|
| 684 |
+
# all previous decoder key/value_states. Further calls to uni-directional self-attention
|
| 685 |
+
# can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
|
| 686 |
+
# if encoder bi-directional self-attention `past_key_value` is always `None`
|
| 687 |
+
past_key_value = (key_layer, value_layer)
|
| 688 |
+
|
| 689 |
+
if is_cross_attention:
|
| 690 |
+
outputs = self.cross_attention_forward(
|
| 691 |
+
query_layer=query_layer,
|
| 692 |
+
key_layer=key_layer,
|
| 693 |
+
value_layer=value_layer,
|
| 694 |
+
attention_mask=attention_mask,
|
| 695 |
+
output_attentions=output_attentions
|
| 696 |
+
)
|
| 697 |
+
else:
|
| 698 |
+
outputs = self.causal_forward(
|
| 699 |
+
query_layer,
|
| 700 |
+
key_layer,
|
| 701 |
+
value_layer,
|
| 702 |
+
attention_mask=attention_mask,
|
| 703 |
+
output_attentions=output_attentions,
|
| 704 |
+
)
|
| 705 |
+
|
| 706 |
+
outputs = outputs + ((key_layer, value_layer),)
|
| 707 |
+
|
| 708 |
+
else:
|
| 709 |
+
outputs = self.not_causal_forward(
|
| 710 |
+
query_layer,
|
| 711 |
+
key_layer,
|
| 712 |
+
value_layer,
|
| 713 |
+
attention_mask=attention_mask,
|
| 714 |
+
output_attentions=output_attentions
|
| 715 |
+
)
|
| 716 |
+
|
| 717 |
+
return outputs
|
| 718 |
+
|
| 719 |
+
def causal_forward(
|
| 720 |
+
self,
|
| 721 |
+
query_layer,
|
| 722 |
+
key_layer,
|
| 723 |
+
value_layer,
|
| 724 |
+
attention_mask=None,
|
| 725 |
+
output_attentions=False,
|
| 726 |
+
):
|
| 727 |
+
|
| 728 |
+
n, h, t, d = key_layer.size()
|
| 729 |
+
|
| 730 |
+
# Cat global mask
|
| 731 |
+
attention_mask = torch.nn.functional.pad(attention_mask, (self.num_global_tokens, 0), value=0)
|
| 732 |
+
|
| 733 |
+
# Split input into global tokens and other tokens
|
| 734 |
+
split = (self.num_global_tokens, t - self.num_global_tokens)
|
| 735 |
+
global_query, query_layer = query_layer.split(split, dim=-2)
|
| 736 |
+
|
| 737 |
+
# Use normal causal attention if local attention covers every tokens
|
| 738 |
+
if t <= 2 * self.block_size + self.num_global_tokens:
|
| 739 |
+
context_layer = self.causal_attention(
|
| 740 |
+
query_layer=query_layer,
|
| 741 |
+
key_layer=key_layer,
|
| 742 |
+
value_layer=value_layer,
|
| 743 |
+
attention_mask=attention_mask,
|
| 744 |
+
causal_shape=(t - self.num_global_tokens, t - self.num_global_tokens)
|
| 745 |
+
)
|
| 746 |
+
|
| 747 |
+
context_layer = torch.cat([global_query, context_layer], dim=-2)
|
| 748 |
+
return (self.reshape_output(context_layer), )
|
| 749 |
+
|
| 750 |
+
# Split K Q M on global and non global
|
| 751 |
+
global_key, key_layer = key_layer.split(split, dim=-2)
|
| 752 |
+
global_value, value_layer = value_layer.split(split, dim=-2)
|
| 753 |
+
global_mask, attention_mask = attention_mask.split(split, dim=-1)
|
| 754 |
+
|
| 755 |
+
n, h, t, d = key_layer.size()
|
| 756 |
+
|
| 757 |
+
# Get sparse idx
|
| 758 |
+
sparse_key, sparse_value, sparse_mask = (None, None, None)
|
| 759 |
+
if self.sparse_block_size and self.sparsity_factor > 0:
|
| 760 |
+
sparse_key, sparse_value, sparse_mask = self.get_sparse_elements(key_layer, value_layer, attention_mask)
|
| 761 |
+
|
| 762 |
+
# Expand masks on heads
|
| 763 |
+
attention_mask = attention_mask.expand(-1, h, -1, -1)
|
| 764 |
+
global_mask = global_mask.expand(-1, h, -1, -1)
|
| 765 |
+
|
| 766 |
+
# Compute dot product attention
|
| 767 |
+
context_layer = self.attention(
|
| 768 |
+
query_layer,
|
| 769 |
+
key_layer,
|
| 770 |
+
value_layer,
|
| 771 |
+
attention_mask,
|
| 772 |
+
sparse_key=sparse_key,
|
| 773 |
+
sparse_value=sparse_value,
|
| 774 |
+
sparse_mask=sparse_mask,
|
| 775 |
+
global_key=global_key,
|
| 776 |
+
global_value=global_value,
|
| 777 |
+
global_mask=global_mask
|
| 778 |
+
)
|
| 779 |
+
|
| 780 |
+
# Merge pseudo global (causal) and local-sparse tokens
|
| 781 |
+
context_layer = torch.cat([global_query, context_layer], dim=-2)
|
| 782 |
+
context_layer = self.reshape_output(context_layer)
|
| 783 |
+
|
| 784 |
+
return (context_layer,)
|
| 785 |
+
|
| 786 |
+
def not_causal_forward(
|
| 787 |
+
self,
|
| 788 |
+
query_layer,
|
| 789 |
+
key_layer,
|
| 790 |
+
value_layer,
|
| 791 |
+
attention_mask=None,
|
| 792 |
+
output_attentions=False,
|
| 793 |
+
):
|
| 794 |
+
|
| 795 |
+
n, h, t, d = query_layer.size()
|
| 796 |
+
|
| 797 |
+
# Cat global mask
|
| 798 |
+
attention_mask = torch.nn.functional.pad(attention_mask, (self.num_global_tokens, 0), value=0)
|
| 799 |
+
|
| 800 |
+
# Use normal attention if local attention covers every tokens
|
| 801 |
+
if t <= 2 * self.block_size + self.num_global_tokens:
|
| 802 |
+
context_layer = self.full_attention(
|
| 803 |
+
query_layer=query_layer,
|
| 804 |
+
key_layer=key_layer,
|
| 805 |
+
value_layer=value_layer,
|
| 806 |
+
attention_mask=attention_mask
|
| 807 |
+
)
|
| 808 |
+
return (self.reshape_output(context_layer), )
|
| 809 |
+
|
| 810 |
+
# Split input into global tokens and other tokens
|
| 811 |
+
split = (self.num_global_tokens, t - self.num_global_tokens)
|
| 812 |
+
global_query, query_layer = query_layer.split(split, dim=-2)
|
| 813 |
+
|
| 814 |
+
# Get global_attention
|
| 815 |
+
bos = self.full_attention(
|
| 816 |
+
query_layer=global_query,
|
| 817 |
+
key_layer=key_layer,
|
| 818 |
+
value_layer=value_layer,
|
| 819 |
+
attention_mask=attention_mask
|
| 820 |
+
)
|
| 821 |
+
|
| 822 |
+
# Split K Q M on global and non global
|
| 823 |
+
global_key, key_layer = key_layer.split(split, dim=-2)
|
| 824 |
+
global_value, value_layer = value_layer.split(split, dim=-2)
|
| 825 |
+
global_mask, attention_mask = attention_mask.split(split, dim=-1)
|
| 826 |
+
|
| 827 |
+
n, h, t, d = key_layer.size()
|
| 828 |
+
|
| 829 |
+
# Get sparse idx
|
| 830 |
+
sparse_key, sparse_value, sparse_mask = (None, None, None)
|
| 831 |
+
|
| 832 |
+
if self.sparse_block_size and self.sparsity_factor > 0:
|
| 833 |
+
sparse_key, sparse_value, sparse_mask = self.get_sparse_elements(key_layer, value_layer, attention_mask)
|
| 834 |
+
|
| 835 |
+
# Expand masks on heads
|
| 836 |
+
attention_mask = attention_mask.expand(-1, h, -1, -1)
|
| 837 |
+
global_mask = global_mask.expand(-1, h, -1, -1)
|
| 838 |
+
|
| 839 |
+
# Compute dot product attention
|
| 840 |
+
context_layer = self.attention(
|
| 841 |
+
query_layer,
|
| 842 |
+
key_layer,
|
| 843 |
+
value_layer,
|
| 844 |
+
attention_mask,
|
| 845 |
+
sparse_key=sparse_key,
|
| 846 |
+
sparse_value=sparse_value,
|
| 847 |
+
sparse_mask=sparse_mask,
|
| 848 |
+
global_key=global_key,
|
| 849 |
+
global_value=global_value,
|
| 850 |
+
global_mask=global_mask
|
| 851 |
+
)
|
| 852 |
+
|
| 853 |
+
# Merge global and local-sparse tokens
|
| 854 |
+
context_layer = torch.cat([bos, context_layer], dim=-2)
|
| 855 |
+
context_layer = self.reshape_output(context_layer)
|
| 856 |
+
|
| 857 |
+
return (context_layer,)
|
| 858 |
+
|
| 859 |
+
def cross_attention_forward(
|
| 860 |
+
self,
|
| 861 |
+
query_layer,
|
| 862 |
+
key_layer,
|
| 863 |
+
value_layer,
|
| 864 |
+
attention_mask=None,
|
| 865 |
+
output_attentions=False,
|
| 866 |
+
):
|
| 867 |
+
|
| 868 |
+
context_layer = self.full_attention(
|
| 869 |
+
query_layer=query_layer,
|
| 870 |
+
key_layer=key_layer,
|
| 871 |
+
value_layer=value_layer,
|
| 872 |
+
attention_mask=attention_mask
|
| 873 |
+
)
|
| 874 |
+
return (self.reshape_output(context_layer), )
|
| 875 |
+
|
| 876 |
+
def chunk(self, x, chunk_size):
|
| 877 |
+
|
| 878 |
+
n, h, t, d = x.size()
|
| 879 |
+
return x.reshape(n, h, -1, chunk_size, d)
|
| 880 |
+
|
| 881 |
+
|
| 882 |
+
class LSGAttention(BertAttention):
|
| 883 |
+
|
| 884 |
+
def __init__(self, config):
|
| 885 |
+
|
| 886 |
+
nn.Module.__init__(self)
|
| 887 |
+
|
| 888 |
+
self.self = LSGSelfAttention(config)
|
| 889 |
+
self.output = BertSelfOutput(config)
|
| 890 |
+
self.pruned_heads = set()
|
| 891 |
+
|
| 892 |
+
|
| 893 |
+
class LSGBertLayer(BertLayer):
|
| 894 |
+
|
| 895 |
+
def __init__(self, config):
|
| 896 |
+
|
| 897 |
+
super().__init__(config)
|
| 898 |
+
|
| 899 |
+
self.attention = LSGAttention(config)
|
| 900 |
+
if self.add_cross_attention:
|
| 901 |
+
if not self.is_decoder:
|
| 902 |
+
assert self.is_decoder, f"{self} should be used as a decoder model if cross attention is added"
|
| 903 |
+
self.crossattention = LSGAttention(config)
|
| 904 |
+
|
| 905 |
+
|
| 906 |
+
class LSGBertEncoder(BertEncoder):
|
| 907 |
+
|
| 908 |
+
def __init__(self, config):
|
| 909 |
+
|
| 910 |
+
super().__init__(config)
|
| 911 |
+
|
| 912 |
+
self.layer = nn.ModuleList([LSGBertLayer(config) for _ in range(config.num_hidden_layers)])
|
| 913 |
+
|
| 914 |
+
assert hasattr(config, "num_global_tokens")
|
| 915 |
+
self.num_global_tokens = config.num_global_tokens
|
| 916 |
+
self.pad_idx = config.pad_token_id
|
| 917 |
+
|
| 918 |
+
assert hasattr(config, "block_size") and hasattr(config, "adaptive")
|
| 919 |
+
self.block_size = config.block_size
|
| 920 |
+
self.adaptive = config.adaptive
|
| 921 |
+
self.mask_first_token = config.mask_first_token
|
| 922 |
+
self.pool_with_global = config.pool_with_global
|
| 923 |
+
|
| 924 |
+
def forward(
|
| 925 |
+
self,
|
| 926 |
+
hidden_states: torch.Tensor,
|
| 927 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
| 928 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
| 929 |
+
encoder_hidden_states: Optional[torch.FloatTensor] = None,
|
| 930 |
+
encoder_attention_mask: Optional[torch.FloatTensor] = None,
|
| 931 |
+
past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
|
| 932 |
+
use_cache: Optional[bool] = None,
|
| 933 |
+
output_attentions: Optional[bool] = False,
|
| 934 |
+
output_hidden_states: Optional[bool] = False,
|
| 935 |
+
return_dict: Optional[bool] = True,
|
| 936 |
+
) -> Union[Tuple[torch.Tensor], BaseModelOutputWithPastAndCrossAttentions]:
|
| 937 |
+
|
| 938 |
+
mask_value = torch.finfo(attention_mask.dtype).min
|
| 939 |
+
n, _, __, t = attention_mask.size()
|
| 940 |
+
|
| 941 |
+
if not (self.config.is_decoder and encoder_hidden_states is not None):
|
| 942 |
+
|
| 943 |
+
b = self.block_size * 2
|
| 944 |
+
pad = t % self.block_size
|
| 945 |
+
|
| 946 |
+
# Check if t is multiple of block_size and pad
|
| 947 |
+
if self.adaptive and t > b and pad > 0:
|
| 948 |
+
pad_length = self.block_size - pad
|
| 949 |
+
hidden_states = torch.nn.functional.pad(hidden_states.transpose(-1, -2), (0, pad_length), value=0.).transpose(-1, -2)
|
| 950 |
+
attention_mask = torch.nn.functional.pad(attention_mask, (0, pad_length), value=mask_value)
|
| 951 |
+
|
| 952 |
+
if self.mask_first_token:
|
| 953 |
+
attention_mask[..., 0] = mask_value
|
| 954 |
+
|
| 955 |
+
encoder_outputs = super().forward(
|
| 956 |
+
hidden_states=hidden_states,
|
| 957 |
+
attention_mask=attention_mask,
|
| 958 |
+
head_mask=head_mask,
|
| 959 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 960 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 961 |
+
past_key_values=past_key_values,
|
| 962 |
+
use_cache=use_cache,
|
| 963 |
+
output_attentions=output_attentions,
|
| 964 |
+
output_hidden_states=output_hidden_states,
|
| 965 |
+
return_dict=return_dict
|
| 966 |
+
)
|
| 967 |
+
|
| 968 |
+
sequence_output = encoder_outputs[0]
|
| 969 |
+
if self.pool_with_global:
|
| 970 |
+
sequence_output[:, self.num_global_tokens] = sequence_output[:, 0]
|
| 971 |
+
|
| 972 |
+
# Adapt sequence to initial shape
|
| 973 |
+
sequence_output = sequence_output[..., self.num_global_tokens: t + self.num_global_tokens, :]
|
| 974 |
+
|
| 975 |
+
if not return_dict:
|
| 976 |
+
return (sequence_output, ) + encoder_outputs[1:]
|
| 977 |
+
|
| 978 |
+
encoder_outputs.last_hidden_state = sequence_output
|
| 979 |
+
return encoder_outputs
|
| 980 |
+
|
| 981 |
+
class LSGBertPreTrainedModel(BertPreTrainedModel):
|
| 982 |
+
"""
|
| 983 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
| 984 |
+
models.
|
| 985 |
+
"""
|
| 986 |
+
|
| 987 |
+
config_class = LSGBertConfig
|
| 988 |
+
|
| 989 |
+
def _set_gradient_checkpointing(self, module, value=False):
|
| 990 |
+
if isinstance(module, (BertEncoder, LSGBertEncoder)):
|
| 991 |
+
module.gradient_checkpointing = value
|
| 992 |
+
|
| 993 |
+
|
| 994 |
+
class LSGBertModel(LSGBertPreTrainedModel, BertModel):
|
| 995 |
+
"""
|
| 996 |
+
This class overrides :class:`~transformers.BertModel`. Please check the superclass for the appropriate
|
| 997 |
+
documentation alongside usage examples.
|
| 998 |
+
"""
|
| 999 |
+
|
| 1000 |
+
def __init__(self, config, add_pooling_layer=True):
|
| 1001 |
+
|
| 1002 |
+
LSGBertPreTrainedModel.__init__(self, config)
|
| 1003 |
+
|
| 1004 |
+
self.config = config
|
| 1005 |
+
|
| 1006 |
+
self.embeddings = LSGBertEmbeddings(config)
|
| 1007 |
+
self.encoder = LSGBertEncoder(config)
|
| 1008 |
+
self.pooler = BertPooler(config) if add_pooling_layer else None
|
| 1009 |
+
|
| 1010 |
+
if config.add_cross_attention:
|
| 1011 |
+
logger.warning(
|
| 1012 |
+
"Cross attention is computed using full attention since it is not LSG compatible."
|
| 1013 |
+
)
|
| 1014 |
+
|
| 1015 |
+
# Initialize weights and apply final processing
|
| 1016 |
+
self.post_init()
|
| 1017 |
+
|
| 1018 |
+
def get_extended_attention_mask(self, attention_mask, input_shape, device=None):
|
| 1019 |
+
|
| 1020 |
+
# Do not rely on original triangular mask from BERT/RoBERTa for causalLM
|
| 1021 |
+
if attention_mask.dim() == 3:
|
| 1022 |
+
extended_attention_mask = attention_mask[:, None, :, :]
|
| 1023 |
+
elif attention_mask.dim() == 2:
|
| 1024 |
+
extended_attention_mask = attention_mask[:, None, None, :]
|
| 1025 |
+
else:
|
| 1026 |
+
raise ValueError(
|
| 1027 |
+
f"Wrong shape for input_ids (shape {input_shape}) or attention_mask (shape {attention_mask.shape})"
|
| 1028 |
+
)
|
| 1029 |
+
|
| 1030 |
+
extended_attention_mask = extended_attention_mask.to(dtype=self.dtype) # fp16 compatibility
|
| 1031 |
+
extended_attention_mask = (1.0 - extended_attention_mask) * torch.finfo(extended_attention_mask.dtype).min
|
| 1032 |
+
|
| 1033 |
+
return extended_attention_mask
|
| 1034 |
+
|
| 1035 |
+
|
| 1036 |
+
class LSGBertForPreTraining(LSGBertPreTrainedModel, BertForPreTraining):
|
| 1037 |
+
|
| 1038 |
+
_tied_weights_keys = ["predictions.decoder.bias", "cls.predictions.decoder.weight"]
|
| 1039 |
+
|
| 1040 |
+
def __init__(self, config):
|
| 1041 |
+
|
| 1042 |
+
LSGBertPreTrainedModel.__init__(self, config)
|
| 1043 |
+
|
| 1044 |
+
self.bert = LSGBertModel(config)
|
| 1045 |
+
self.cls = BertPreTrainingHeads(config)
|
| 1046 |
+
|
| 1047 |
+
# Initialize weights and apply final processing
|
| 1048 |
+
self.post_init()
|
| 1049 |
+
|
| 1050 |
+
|
| 1051 |
+
class LSGBertLMHeadModel(LSGBertPreTrainedModel, BertLMHeadModel):
|
| 1052 |
+
|
| 1053 |
+
_tied_weights_keys = ["predictions.decoder.bias", "cls.predictions.decoder.weight"]
|
| 1054 |
+
|
| 1055 |
+
def __init__(self, config):
|
| 1056 |
+
|
| 1057 |
+
LSGBertPreTrainedModel.__init__(self, config)
|
| 1058 |
+
|
| 1059 |
+
if not config.is_decoder:
|
| 1060 |
+
logger.warning("If you want to use `BertLMHeadModel` as a standalone, add `is_decoder=True.`")
|
| 1061 |
+
|
| 1062 |
+
self.bert = LSGBertModel(config, add_pooling_layer=False)
|
| 1063 |
+
self.cls = BertOnlyMLMHead(config)
|
| 1064 |
+
|
| 1065 |
+
# Initialize weights and apply final processing
|
| 1066 |
+
self.post_init()
|
| 1067 |
+
|
| 1068 |
+
|
| 1069 |
+
class LSGBertForMaskedLM(LSGBertPreTrainedModel, BertForMaskedLM):
|
| 1070 |
+
"""
|
| 1071 |
+
This class overrides :class:`~transformers.BertForMaskedLM`. Please check the superclass for the appropriate
|
| 1072 |
+
documentation alongside usage examples.
|
| 1073 |
+
"""
|
| 1074 |
+
|
| 1075 |
+
_tied_weights_keys = ["predictions.decoder.bias", "cls.predictions.decoder.weight"]
|
| 1076 |
+
|
| 1077 |
+
def __init__(self, config):
|
| 1078 |
+
|
| 1079 |
+
LSGBertPreTrainedModel.__init__(self, config)
|
| 1080 |
+
|
| 1081 |
+
if config.is_decoder:
|
| 1082 |
+
logger.warning(
|
| 1083 |
+
"If you want to use `LSGBertForMaskedLM` make sure `config.is_decoder=False` for "
|
| 1084 |
+
"bi-directional self-attention."
|
| 1085 |
+
)
|
| 1086 |
+
|
| 1087 |
+
self.bert = LSGBertModel(config, add_pooling_layer=False)
|
| 1088 |
+
self.cls = BertOnlyMLMHead(config)
|
| 1089 |
+
|
| 1090 |
+
# Initialize weights and apply final processing
|
| 1091 |
+
self.post_init()
|
| 1092 |
+
|
| 1093 |
+
|
| 1094 |
+
class LSGBertForNextSentencePrediction(LSGBertPreTrainedModel, BertForNextSentencePrediction):
|
| 1095 |
+
|
| 1096 |
+
def __init__(self, config):
|
| 1097 |
+
|
| 1098 |
+
LSGBertPreTrainedModel.__init__(self, config)
|
| 1099 |
+
|
| 1100 |
+
self.bert = LSGBertModel(config)
|
| 1101 |
+
self.cls = BertOnlyNSPHead(config)
|
| 1102 |
+
|
| 1103 |
+
# Initialize weights and apply final processing
|
| 1104 |
+
self.post_init()
|
| 1105 |
+
|
| 1106 |
+
|
| 1107 |
+
class LSGBertForSequenceClassification(LSGBertPreTrainedModel, BertForSequenceClassification):
|
| 1108 |
+
"""
|
| 1109 |
+
This class overrides :class:`~transformers.BertForSequenceClassification`. Please check the superclass for the
|
| 1110 |
+
appropriate documentation alongside usage examples.
|
| 1111 |
+
"""
|
| 1112 |
+
|
| 1113 |
+
def __init__(self, config):
|
| 1114 |
+
|
| 1115 |
+
LSGBertPreTrainedModel.__init__(self, config)
|
| 1116 |
+
|
| 1117 |
+
self.num_labels = config.num_labels
|
| 1118 |
+
self.config = config
|
| 1119 |
+
|
| 1120 |
+
self.bert = LSGBertModel(config)
|
| 1121 |
+
classifier_dropout = (
|
| 1122 |
+
config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
|
| 1123 |
+
)
|
| 1124 |
+
self.dropout = nn.Dropout(classifier_dropout)
|
| 1125 |
+
self.classifier = nn.Linear(config.hidden_size, config.num_labels)
|
| 1126 |
+
|
| 1127 |
+
# Initialize weights and apply final processing
|
| 1128 |
+
self.post_init()
|
| 1129 |
+
|
| 1130 |
+
|
| 1131 |
+
class LSGBertForMultipleChoice(LSGBertPreTrainedModel, BertForMultipleChoice):
|
| 1132 |
+
"""
|
| 1133 |
+
This class overrides :class:`~transformers.BertForMultipleChoice`. Please check the superclass for the
|
| 1134 |
+
appropriate documentation alongside usage examples.
|
| 1135 |
+
"""
|
| 1136 |
+
|
| 1137 |
+
def __init__(self, config):
|
| 1138 |
+
|
| 1139 |
+
LSGBertPreTrainedModel.__init__(self, config)
|
| 1140 |
+
|
| 1141 |
+
self.bert = LSGBertModel(config)
|
| 1142 |
+
classifier_dropout = (
|
| 1143 |
+
config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
|
| 1144 |
+
)
|
| 1145 |
+
self.dropout = nn.Dropout(classifier_dropout)
|
| 1146 |
+
self.classifier = nn.Linear(config.hidden_size, 1)
|
| 1147 |
+
|
| 1148 |
+
# Initialize weights and apply final processing
|
| 1149 |
+
self.post_init()
|
| 1150 |
+
|
| 1151 |
+
|
| 1152 |
+
class LSGBertForTokenClassification(LSGBertPreTrainedModel, BertForTokenClassification):
|
| 1153 |
+
"""
|
| 1154 |
+
This class overrides :class:`~transformers.BertForTokenClassification`. Please check the superclass for the
|
| 1155 |
+
appropriate documentation alongside usage examples.
|
| 1156 |
+
"""
|
| 1157 |
+
|
| 1158 |
+
def __init__(self, config):
|
| 1159 |
+
|
| 1160 |
+
LSGBertPreTrainedModel.__init__(self, config)
|
| 1161 |
+
|
| 1162 |
+
self.num_labels = config.num_labels
|
| 1163 |
+
|
| 1164 |
+
self.bert = LSGBertModel(config, add_pooling_layer=False)
|
| 1165 |
+
classifier_dropout = (
|
| 1166 |
+
config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob
|
| 1167 |
+
)
|
| 1168 |
+
self.dropout = nn.Dropout(classifier_dropout)
|
| 1169 |
+
self.classifier = nn.Linear(config.hidden_size, config.num_labels)
|
| 1170 |
+
|
| 1171 |
+
# Initialize weights and apply final processing
|
| 1172 |
+
self.post_init()
|
| 1173 |
+
|
| 1174 |
+
|
| 1175 |
+
class LSGBertForQuestionAnswering(LSGBertPreTrainedModel, BertForQuestionAnswering):
|
| 1176 |
+
"""
|
| 1177 |
+
This class overrides :class:`~transformers.BertForQuestionAnswering`. Please check the superclass for the
|
| 1178 |
+
appropriate documentation alongside usage examples.
|
| 1179 |
+
"""
|
| 1180 |
+
|
| 1181 |
+
def __init__(self, config):
|
| 1182 |
+
|
| 1183 |
+
LSGBertPreTrainedModel.__init__(self, config)
|
| 1184 |
+
|
| 1185 |
+
self.num_labels = config.num_labels
|
| 1186 |
+
|
| 1187 |
+
self.bert = LSGBertModel(config, add_pooling_layer=False)
|
| 1188 |
+
self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
|
| 1189 |
+
|
| 1190 |
+
# Initialize weights and apply final processing
|
| 1191 |
+
self.post_init()
|
| 1192 |
+
|
| 1193 |
+
|
| 1194 |
+
def str_to_class(classname):
|
| 1195 |
+
return getattr(sys.modules[__name__], classname)
|
| 1196 |
+
|
| 1197 |
+
# Register model in Auto API
|
| 1198 |
+
try:
|
| 1199 |
+
LSGBertConfig.register_for_auto_class()
|
| 1200 |
+
for key, value in AUTO_MAP.items():
|
| 1201 |
+
str_to_class(value.split(".")[-1]).register_for_auto_class(key)
|
| 1202 |
+
except:
|
| 1203 |
+
warn("AutoRegister isn't available, you'll have to manually copy modeling.py after .save_pretrained(...).")
|
| 1204 |
+
warn("Update to transformers >= 4.23.1 to fix.")
|
pytorch_model.bin
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:9ddb95405e22a7e194606f2958de402632e8cccab87c66fa0ac0514170b76e55
|
| 3 |
+
size 140582189
|