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
+
import torch.nn as nn
|
| 6 |
+
import torch.nn.functional as F
|
| 7 |
+
from torch.utils import checkpoint
|
| 8 |
+
|
| 9 |
+
from .configuration_ltgbert import LtgbertConfig
|
| 10 |
+
from transformers.modeling_utils import PreTrainedModel
|
| 11 |
+
from transformers.activations import gelu_new
|
| 12 |
+
from transformers.modeling_outputs import (
|
| 13 |
+
MaskedLMOutput,
|
| 14 |
+
MultipleChoiceModelOutput,
|
| 15 |
+
QuestionAnsweringModelOutput,
|
| 16 |
+
SequenceClassifierOutput,
|
| 17 |
+
TokenClassifierOutput,
|
| 18 |
+
BaseModelOutput,
|
| 19 |
+
CausalLMOutput
|
| 20 |
+
)
|
| 21 |
+
from transformers.pytorch_utils import softmax_backward_data
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class InPlaceSetSlice(torch.autograd.Function):
|
| 25 |
+
@staticmethod
|
| 26 |
+
def forward(ctx, full_tensor, last_slice, x_idx, x_val):
|
| 27 |
+
full_tensor[x_idx] = x_val
|
| 28 |
+
ctx.x_idx = x_idx
|
| 29 |
+
ret = torch.Tensor().to(full_tensor.device)
|
| 30 |
+
ret.set_(full_tensor[:x_idx + 1])
|
| 31 |
+
return ret
|
| 32 |
+
|
| 33 |
+
@staticmethod
|
| 34 |
+
def backward(ctx, grad_out):
|
| 35 |
+
if ctx.x_idx == 0:
|
| 36 |
+
return None, None, None, grad_out[ctx.x_idx]
|
| 37 |
+
else:
|
| 38 |
+
return None, grad_out[:ctx.x_idx], None, grad_out[ctx.x_idx]
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def apply_inplace_set(x_acc, x_idx, x_val):
|
| 42 |
+
full_tensor, last_slice = x_acc
|
| 43 |
+
new_slice = InPlaceSetSlice.apply(full_tensor, last_slice, x_idx, x_val)
|
| 44 |
+
return full_tensor, new_slice
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
class DWAModules(torch.nn.Module):
|
| 48 |
+
def __init__(self, hidden_size, n_blocks):
|
| 49 |
+
super().__init__()
|
| 50 |
+
self.n_blocks = n_blocks
|
| 51 |
+
self.alphas = nn.ParameterList([nn.Parameter(torch.zeros(i + 2)) for i in range(n_blocks)])
|
| 52 |
+
self.accumulator = None
|
| 53 |
+
self._init_weights()
|
| 54 |
+
|
| 55 |
+
def _init_weights(self):
|
| 56 |
+
for module in self.alphas:
|
| 57 |
+
module.data.zero_()
|
| 58 |
+
module.data[-1] = 1.0
|
| 59 |
+
|
| 60 |
+
def init_accumulator(self, x):
|
| 61 |
+
self.accumulator = (torch.zeros((self.n_blocks + 1, *x.shape), device=x.device, dtype=x.dtype), None)
|
| 62 |
+
self.accumulator = apply_inplace_set(self.accumulator, 0, x)
|
| 63 |
+
|
| 64 |
+
def forward(self, x, block_idx):
|
| 65 |
+
assert self.accumulator is not None, "`init_accumulator(x)` needs to be called first"
|
| 66 |
+
self.accumulator = apply_inplace_set(
|
| 67 |
+
self.accumulator,
|
| 68 |
+
block_idx + 1,
|
| 69 |
+
x
|
| 70 |
+
)
|
| 71 |
+
x = torch.tensordot(self.alphas[block_idx], self.accumulator[1], dims=1)
|
| 72 |
+
return x
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
class Encoder(nn.Module):
|
| 76 |
+
def __init__(self, config):
|
| 77 |
+
super().__init__()
|
| 78 |
+
self.attention_layers = nn.ModuleList([Attention(config) for _ in range(config.num_hidden_layers)])
|
| 79 |
+
self.mlp_layers = nn.ModuleList([FeedForward(config) for _ in range(config.num_hidden_layers)])
|
| 80 |
+
self.dwa_modules = DWAModules(config.hidden_size, config.num_hidden_layers * 2)
|
| 81 |
+
|
| 82 |
+
for i, layer in enumerate(self.mlp_layers):
|
| 83 |
+
layer.mlp[1].weight.data *= math.sqrt(1.0 / (2.0 * (1 + i)))
|
| 84 |
+
layer.mlp[-2].weight.data *= math.sqrt(1.0 / (2.0 * (1 + i)))
|
| 85 |
+
|
| 86 |
+
def forward(self, x, attention_mask, relative_embedding):
|
| 87 |
+
hidden_states, attention_probs = [x], []
|
| 88 |
+
|
| 89 |
+
self.dwa_modules.init_accumulator(x)
|
| 90 |
+
for i, (attention_layer, mlp_layer) in enumerate(zip(self.attention_layers, self.mlp_layers)):
|
| 91 |
+
attention_output, attention_p = attention_layer(x, attention_mask, relative_embedding)
|
| 92 |
+
x = x + attention_output
|
| 93 |
+
x = self.dwa_modules(x, block_idx=i * 2)
|
| 94 |
+
|
| 95 |
+
x = x + mlp_layer(x)
|
| 96 |
+
x = self.dwa_modules(x, block_idx=i * 2 + 1)
|
| 97 |
+
|
| 98 |
+
hidden_states.append(x)
|
| 99 |
+
attention_probs.append(attention_p)
|
| 100 |
+
|
| 101 |
+
return hidden_states, attention_probs
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
class MaskClassifier(nn.Module):
|
| 105 |
+
def __init__(self, config, subword_embedding):
|
| 106 |
+
super().__init__()
|
| 107 |
+
self.nonlinearity = nn.Sequential(
|
| 108 |
+
nn.LayerNorm(config.hidden_size, config.layer_norm_eps, elementwise_affine=False),
|
| 109 |
+
nn.Linear(config.hidden_size, config.hidden_size),
|
| 110 |
+
nn.GELU(),
|
| 111 |
+
nn.LayerNorm(config.hidden_size, config.layer_norm_eps, elementwise_affine=False),
|
| 112 |
+
nn.Dropout(config.hidden_dropout_prob),
|
| 113 |
+
nn.Linear(subword_embedding.size(1), subword_embedding.size(0))
|
| 114 |
+
)
|
| 115 |
+
|
| 116 |
+
def forward(self, x, masked_lm_labels=None):
|
| 117 |
+
if masked_lm_labels is not None:
|
| 118 |
+
x = torch.index_select(x.flatten(0, 1), 0, torch.nonzero(masked_lm_labels.flatten() != -100).squeeze())
|
| 119 |
+
x = self.nonlinearity(x)
|
| 120 |
+
return x
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
# class EncoderLayer(nn.Module):
|
| 124 |
+
# def __init__(self, config):
|
| 125 |
+
# super().__init__()
|
| 126 |
+
# self.attention = Attention(config)
|
| 127 |
+
# self.mlp = FeedForward(config)
|
| 128 |
+
|
| 129 |
+
# def forward(self, x, padding_mask, relative_embedding):
|
| 130 |
+
# attention_output, attention_probs = self.attention(x, padding_mask, relative_embedding)
|
| 131 |
+
# x = x + attention_output
|
| 132 |
+
# x = x + self.mlp(x)
|
| 133 |
+
# return x, attention_probs
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
class GeGLU(nn.Module):
|
| 137 |
+
def forward(self, x):
|
| 138 |
+
x, gate = x.chunk(2, dim=-1)
|
| 139 |
+
x = x * gelu_new(gate)
|
| 140 |
+
return x
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
class FeedForward(nn.Module):
|
| 144 |
+
def __init__(self, config):
|
| 145 |
+
super().__init__()
|
| 146 |
+
self.mlp = nn.Sequential(
|
| 147 |
+
nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps, elementwise_affine=False),
|
| 148 |
+
nn.Linear(config.hidden_size, 2*config.intermediate_size, bias=False),
|
| 149 |
+
GeGLU(),
|
| 150 |
+
nn.LayerNorm(config.intermediate_size, eps=config.layer_norm_eps, elementwise_affine=False),
|
| 151 |
+
nn.Linear(config.intermediate_size, config.hidden_size, bias=False),
|
| 152 |
+
nn.Dropout(config.hidden_dropout_prob)
|
| 153 |
+
)
|
| 154 |
+
|
| 155 |
+
def forward(self, x):
|
| 156 |
+
return self.mlp(x)
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
class MaskedSoftmax(torch.autograd.Function):
|
| 160 |
+
@staticmethod
|
| 161 |
+
def forward(self, x, mask, dim):
|
| 162 |
+
self.dim = dim
|
| 163 |
+
|
| 164 |
+
x.masked_fill_(mask, float('-inf'))
|
| 165 |
+
x = torch.softmax(x, self.dim)
|
| 166 |
+
x.masked_fill_(mask, 0.0)
|
| 167 |
+
self.save_for_backward(x)
|
| 168 |
+
return x
|
| 169 |
+
|
| 170 |
+
@staticmethod
|
| 171 |
+
def backward(self, grad_output):
|
| 172 |
+
output, = self.saved_tensors
|
| 173 |
+
input_grad = softmax_backward_data(self, grad_output, output, self.dim, output)
|
| 174 |
+
return input_grad, None, None
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
class Attention(nn.Module):
|
| 178 |
+
def __init__(self, config):
|
| 179 |
+
super().__init__()
|
| 180 |
+
|
| 181 |
+
self.config = config
|
| 182 |
+
|
| 183 |
+
if config.hidden_size % config.num_attention_heads != 0:
|
| 184 |
+
raise ValueError(f"The hidden size {config.hidden_size} is not a multiple of the number of attention heads {config.num_attention_heads}")
|
| 185 |
+
|
| 186 |
+
self.hidden_size = config.hidden_size
|
| 187 |
+
self.num_heads = config.num_attention_heads
|
| 188 |
+
self.head_size = config.hidden_size // config.num_attention_heads
|
| 189 |
+
|
| 190 |
+
self.in_proj_qk = nn.Linear(config.hidden_size, 2*config.hidden_size, bias=True)
|
| 191 |
+
self.in_proj_vg = nn.Linear(config.hidden_size, 2*config.hidden_size, bias=True)
|
| 192 |
+
self.out_proj = nn.Linear(config.hidden_size, config.hidden_size, bias=True)
|
| 193 |
+
|
| 194 |
+
self.pre_layer_norm = nn.LayerNorm(config.hidden_size, config.layer_norm_eps, elementwise_affine=False)
|
| 195 |
+
self.post_layer_norm = nn.LayerNorm(config.hidden_size, config.layer_norm_eps, elementwise_affine=False)
|
| 196 |
+
|
| 197 |
+
position_indices = torch.arange(config.max_position_embeddings, dtype=torch.long).unsqueeze(1) \
|
| 198 |
+
- torch.arange(config.max_position_embeddings, dtype=torch.long).unsqueeze(0)
|
| 199 |
+
position_indices = self.make_log_bucket_position(position_indices, config.position_bucket_size, config.max_position_embeddings)
|
| 200 |
+
position_indices = config.position_bucket_size - 1 + position_indices
|
| 201 |
+
self.register_buffer("position_indices", position_indices, persistent=True)
|
| 202 |
+
|
| 203 |
+
self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
|
| 204 |
+
self.scale = 1.0 / math.sqrt(3 * self.head_size)
|
| 205 |
+
|
| 206 |
+
def make_log_bucket_position(self, relative_pos, bucket_size, max_position):
|
| 207 |
+
sign = torch.sign(relative_pos)
|
| 208 |
+
mid = bucket_size // 2
|
| 209 |
+
abs_pos = torch.where((relative_pos < mid) & (relative_pos > -mid), mid - 1, torch.abs(relative_pos).clamp(max=max_position - 1))
|
| 210 |
+
log_pos = torch.ceil(torch.log(abs_pos / mid) / math.log((max_position-1) / mid) * (mid - 1)).int() + mid
|
| 211 |
+
bucket_pos = torch.where(abs_pos <= mid, relative_pos, log_pos * sign).long()
|
| 212 |
+
return bucket_pos
|
| 213 |
+
|
| 214 |
+
def forward(self, hidden_states, attention_mask, relative_embedding):
|
| 215 |
+
key_len, batch_size, _ = hidden_states.size()
|
| 216 |
+
query_len = key_len
|
| 217 |
+
|
| 218 |
+
if self.position_indices.size(0) < query_len:
|
| 219 |
+
position_indices = torch.arange(query_len, dtype=torch.long).unsqueeze(1) \
|
| 220 |
+
- torch.arange(query_len, dtype=torch.long).unsqueeze(0)
|
| 221 |
+
position_indices = self.make_log_bucket_position(position_indices, self.config.position_bucket_size, 512)
|
| 222 |
+
position_indices = self.config.position_bucket_size - 1 + position_indices
|
| 223 |
+
self.position_indices = position_indices.to(hidden_states.device)
|
| 224 |
+
|
| 225 |
+
hidden_states = self.pre_layer_norm(hidden_states)
|
| 226 |
+
|
| 227 |
+
query, key = self.in_proj_qk(hidden_states).chunk(2, dim=2) # shape: [T, B, D]
|
| 228 |
+
value, gate = self.in_proj_vg(hidden_states).chunk(2, dim=2) # shape: [T, B, D]
|
| 229 |
+
gate = F.gelu(gate)
|
| 230 |
+
|
| 231 |
+
query = query.reshape(query_len, batch_size * self.num_heads, self.head_size).transpose(0, 1)
|
| 232 |
+
key = key.reshape(key_len, batch_size * self.num_heads, self.head_size).transpose(0, 1)
|
| 233 |
+
value = value.reshape(key_len, batch_size * self.num_heads, self.head_size).transpose(0, 1)
|
| 234 |
+
|
| 235 |
+
attention_scores = torch.bmm(query, key.transpose(1, 2) * self.scale)
|
| 236 |
+
|
| 237 |
+
query_pos, key_pos = self.in_proj_qk(self.dropout(relative_embedding)).chunk(2, dim=-1) # shape: [2T-1, D]
|
| 238 |
+
query_pos = query_pos.view(-1, self.num_heads, self.head_size) # shape: [2T-1, H, D]
|
| 239 |
+
key_pos = key_pos.view(-1, self.num_heads, self.head_size) # shape: [2T-1, H, D]
|
| 240 |
+
|
| 241 |
+
query = query.view(batch_size, self.num_heads, query_len, self.head_size)
|
| 242 |
+
key = key.view(batch_size, self.num_heads, query_len, self.head_size)
|
| 243 |
+
|
| 244 |
+
attention_c_p = torch.einsum("bhqd,khd->bhqk", query, key_pos.squeeze(1) * self.scale)
|
| 245 |
+
attention_p_c = torch.einsum("bhkd,qhd->bhqk", key * self.scale, query_pos.squeeze(1))
|
| 246 |
+
|
| 247 |
+
position_indices = self.position_indices[:query_len, :key_len].expand(batch_size, self.num_heads, -1, -1)
|
| 248 |
+
attention_c_p = attention_c_p.gather(3, position_indices)
|
| 249 |
+
attention_p_c = attention_p_c.gather(2, position_indices)
|
| 250 |
+
|
| 251 |
+
attention_scores = attention_scores.view(batch_size, self.num_heads, query_len, key_len)
|
| 252 |
+
attention_scores.add_(attention_c_p)
|
| 253 |
+
attention_scores.add_(attention_p_c)
|
| 254 |
+
|
| 255 |
+
attention_probs = MaskedSoftmax.apply(attention_scores, attention_mask, -1)
|
| 256 |
+
|
| 257 |
+
attention_probs = self.dropout(attention_probs)
|
| 258 |
+
context = torch.bmm(attention_probs.flatten(0, 1), value) # shape: [B*H, Q, D]
|
| 259 |
+
context = context.transpose(0, 1).reshape(context.size(1), -1, self.hidden_size) # shape: [Q, B, H*D]
|
| 260 |
+
context = context * gate
|
| 261 |
+
context = self.post_layer_norm(context)
|
| 262 |
+
context = self.out_proj(context)
|
| 263 |
+
context = self.dropout(context)
|
| 264 |
+
|
| 265 |
+
return context, attention_probs.detach()
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
class Embedding(nn.Module):
|
| 269 |
+
def __init__(self, config):
|
| 270 |
+
super().__init__()
|
| 271 |
+
self.hidden_size = config.hidden_size
|
| 272 |
+
|
| 273 |
+
self.word_embedding = nn.Embedding(config.vocab_size, config.hidden_size)
|
| 274 |
+
self.word_layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps, elementwise_affine=False)
|
| 275 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 276 |
+
|
| 277 |
+
self.relative_embedding = nn.Parameter(torch.empty(2 * config.position_bucket_size - 1, config.hidden_size))
|
| 278 |
+
self.relative_layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 279 |
+
|
| 280 |
+
def forward(self, input_ids):
|
| 281 |
+
word_embedding = self.dropout(self.word_layer_norm(self.word_embedding(input_ids)))
|
| 282 |
+
relative_embeddings = self.relative_layer_norm(self.relative_embedding)
|
| 283 |
+
return word_embedding, relative_embeddings
|
| 284 |
+
|
| 285 |
+
|
| 286 |
+
#
|
| 287 |
+
# HuggingFace wrappers
|
| 288 |
+
#
|
| 289 |
+
|
| 290 |
+
class LtgbertPreTrainedModel(PreTrainedModel):
|
| 291 |
+
config_class = LtgbertConfig
|
| 292 |
+
supports_gradient_checkpointing = False
|
| 293 |
+
|
| 294 |
+
def _set_gradient_checkpointing(self, module, value=False):
|
| 295 |
+
raise NotImplementedError("Gradient checkpointing is not supported by this model")
|
| 296 |
+
|
| 297 |
+
def _init_weights(self, module):
|
| 298 |
+
std = math.sqrt(2.0 / (5.0 * self.hidden_size))
|
| 299 |
+
|
| 300 |
+
if isinstance(module, nn.Linear):
|
| 301 |
+
nn.init.trunc_normal_(module.weight.data, mean=0.0, std=std, a=-2*std, b=2*std)
|
| 302 |
+
if module.bias is not None:
|
| 303 |
+
module.bias.data.zero_()
|
| 304 |
+
elif isinstance(module, nn.Embedding):
|
| 305 |
+
nn.init.trunc_normal_(module.weight.data, mean=0.0, std=std, a=-2*std, b=2*std)
|
| 306 |
+
elif isinstance(module, nn.LayerNorm):
|
| 307 |
+
module.bias.data.zero_()
|
| 308 |
+
module.weight.data.fill_(1.0)
|
| 309 |
+
|
| 310 |
+
|
| 311 |
+
class LtgbertModel(LtgbertPreTrainedModel):
|
| 312 |
+
def __init__(self, config, add_mlm_layer=False, **kwargs):
|
| 313 |
+
super().__init__(config, **kwargs)
|
| 314 |
+
self.config = config
|
| 315 |
+
self.hidden_size = config.hidden_size
|
| 316 |
+
|
| 317 |
+
self.embedding = Embedding(config)
|
| 318 |
+
self.transformer = Encoder(config)
|
| 319 |
+
self.classifier = MaskClassifier(config, self.embedding.word_embedding.weight) if add_mlm_layer else None
|
| 320 |
+
|
| 321 |
+
|
| 322 |
+
def get_input_embeddings(self):
|
| 323 |
+
return self.embedding.word_embedding
|
| 324 |
+
|
| 325 |
+
def set_input_embeddings(self, value):
|
| 326 |
+
self.embedding.word_embedding = value
|
| 327 |
+
|
| 328 |
+
def get_contextualized_embeddings(
|
| 329 |
+
self,
|
| 330 |
+
input_ids: Optional[torch.Tensor] = None,
|
| 331 |
+
attention_mask: Optional[torch.Tensor] = None
|
| 332 |
+
) -> List[torch.Tensor]:
|
| 333 |
+
if input_ids is not None:
|
| 334 |
+
input_shape = input_ids.size()
|
| 335 |
+
else:
|
| 336 |
+
raise ValueError("You have to specify input_ids")
|
| 337 |
+
|
| 338 |
+
batch_size, seq_length = input_shape
|
| 339 |
+
device = input_ids.device
|
| 340 |
+
|
| 341 |
+
if attention_mask is None:
|
| 342 |
+
attention_mask = torch.zeros(batch_size, seq_length, dtype=torch.bool, device=device)
|
| 343 |
+
else:
|
| 344 |
+
attention_mask = ~attention_mask.bool()
|
| 345 |
+
|
| 346 |
+
if self.config.is_decoder:
|
| 347 |
+
attention_mask = attention_mask.unsqueeze(1).unsqueeze(2) | torch.triu(torch.ones(seq_length, seq_length, dtype=torch.bool, device=device), 1).unsqueeze(0).unsqueeze(0)
|
| 348 |
+
else:
|
| 349 |
+
if len(attention_mask.size()) == 2:
|
| 350 |
+
attention_mask = attention_mask.unsqueeze(1).unsqueeze(2)
|
| 351 |
+
elif len(attention_mask.size()) == 3:
|
| 352 |
+
attention_mask = attention_mask.unsqueeze(1)
|
| 353 |
+
|
| 354 |
+
static_embeddings, relative_embedding = self.embedding(input_ids.t())
|
| 355 |
+
contextualized_embeddings, attention_probs = self.transformer(static_embeddings, attention_mask, relative_embedding)
|
| 356 |
+
contextualized_embeddings = [e.transpose(0, 1) for e in contextualized_embeddings]
|
| 357 |
+
last_layer = contextualized_embeddings[-1]
|
| 358 |
+
contextualized_embeddings = [contextualized_embeddings[0]] + [
|
| 359 |
+
contextualized_embeddings[i] - contextualized_embeddings[i - 1]
|
| 360 |
+
for i in range(1, len(contextualized_embeddings))
|
| 361 |
+
]
|
| 362 |
+
return last_layer, contextualized_embeddings, attention_probs
|
| 363 |
+
|
| 364 |
+
def forward(
|
| 365 |
+
self,
|
| 366 |
+
input_ids: Optional[torch.Tensor] = None,
|
| 367 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 368 |
+
token_type_ids: Optional[torch.Tensor] = None,
|
| 369 |
+
position_ids: Optional[torch.Tensor] = None,
|
| 370 |
+
output_hidden_states: Optional[bool] = None,
|
| 371 |
+
output_attentions: Optional[bool] = None,
|
| 372 |
+
return_dict: Optional[bool] = None,
|
| 373 |
+
**kwargs
|
| 374 |
+
) -> Union[Tuple[torch.Tensor], BaseModelOutput]:
|
| 375 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 376 |
+
|
| 377 |
+
sequence_output, contextualized_embeddings, attention_probs = self.get_contextualized_embeddings(input_ids, attention_mask)
|
| 378 |
+
|
| 379 |
+
if not return_dict:
|
| 380 |
+
return (
|
| 381 |
+
sequence_output,
|
| 382 |
+
*([contextualized_embeddings] if output_hidden_states else []),
|
| 383 |
+
*([attention_probs] if output_attentions else [])
|
| 384 |
+
)
|
| 385 |
+
|
| 386 |
+
return BaseModelOutput(
|
| 387 |
+
last_hidden_state=sequence_output,
|
| 388 |
+
hidden_states=contextualized_embeddings if output_hidden_states else None,
|
| 389 |
+
attentions=attention_probs if output_attentions else None
|
| 390 |
+
)
|
| 391 |
+
|
| 392 |
+
|
| 393 |
+
class LtgbertForMaskedLM(LtgbertModel):
|
| 394 |
+
_keys_to_ignore_on_load_unexpected = ["head"]
|
| 395 |
+
|
| 396 |
+
def __init__(self, config, **kwargs):
|
| 397 |
+
super().__init__(config, add_mlm_layer=True, **kwargs)
|
| 398 |
+
|
| 399 |
+
def get_output_embeddings(self):
|
| 400 |
+
return self.classifier.nonlinearity[-1].weight
|
| 401 |
+
|
| 402 |
+
def set_output_embeddings(self, new_embeddings):
|
| 403 |
+
self.classifier.nonlinearity[-1].weight = new_embeddings
|
| 404 |
+
|
| 405 |
+
def forward(
|
| 406 |
+
self,
|
| 407 |
+
input_ids: Optional[torch.Tensor] = None,
|
| 408 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 409 |
+
token_type_ids: Optional[torch.Tensor] = None,
|
| 410 |
+
position_ids: Optional[torch.Tensor] = None,
|
| 411 |
+
output_hidden_states: Optional[bool] = None,
|
| 412 |
+
output_attentions: Optional[bool] = None,
|
| 413 |
+
return_dict: Optional[bool] = None,
|
| 414 |
+
labels: Optional[torch.LongTensor] = None,
|
| 415 |
+
**kwargs
|
| 416 |
+
) -> Union[Tuple[torch.Tensor], MaskedLMOutput]:
|
| 417 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 418 |
+
|
| 419 |
+
sequence_output, contextualized_embeddings, attention_probs = self.get_contextualized_embeddings(input_ids, attention_mask)
|
| 420 |
+
subword_prediction = self.classifier(sequence_output)
|
| 421 |
+
# subword_prediction[:, :, :16+1] = float("-inf")
|
| 422 |
+
|
| 423 |
+
masked_lm_loss = None
|
| 424 |
+
if labels is not None:
|
| 425 |
+
labels_flatten = labels[:, 1:].flatten()
|
| 426 |
+
subword_prediction_flatten = subword_prediction[:, :-1].flatten(0, 1)
|
| 427 |
+
masked_lm_loss = F.cross_entropy(subword_prediction_flatten, labels_flatten)
|
| 428 |
+
|
| 429 |
+
if not return_dict:
|
| 430 |
+
output = (
|
| 431 |
+
subword_prediction,
|
| 432 |
+
*([contextualized_embeddings] if output_hidden_states else []),
|
| 433 |
+
*([attention_probs] if output_attentions else [])
|
| 434 |
+
)
|
| 435 |
+
return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
|
| 436 |
+
|
| 437 |
+
return MaskedLMOutput(
|
| 438 |
+
loss=masked_lm_loss,
|
| 439 |
+
logits=subword_prediction,
|
| 440 |
+
hidden_states=contextualized_embeddings if output_hidden_states else None,
|
| 441 |
+
attentions=attention_probs if output_attentions else None
|
| 442 |
+
)
|
| 443 |
+
|
| 444 |
+
|
| 445 |
+
class Classifier(nn.Module):
|
| 446 |
+
def __init__(self, config, num_labels: int):
|
| 447 |
+
super().__init__()
|
| 448 |
+
|
| 449 |
+
self.temperature = config.temperature
|
| 450 |
+
drop_out = getattr(config, "cls_dropout", None)
|
| 451 |
+
drop_out = config.hidden_dropout_prob if drop_out is None else drop_out
|
| 452 |
+
|
| 453 |
+
self.nonlinearity = nn.Sequential(
|
| 454 |
+
nn.LayerNorm(config.hidden_size, config.layer_norm_eps, elementwise_affine=False),
|
| 455 |
+
nn.Linear(config.hidden_size, config.hidden_size),
|
| 456 |
+
nn.GELU(),
|
| 457 |
+
nn.LayerNorm(config.hidden_size, config.layer_norm_eps, elementwise_affine=False),
|
| 458 |
+
nn.Dropout(drop_out),
|
| 459 |
+
nn.Linear(config.hidden_size, num_labels)
|
| 460 |
+
)
|
| 461 |
+
|
| 462 |
+
def forward(self, x):
|
| 463 |
+
x = self.nonlinearity(x) / self.temperature
|
| 464 |
+
return x
|
| 465 |
+
|
| 466 |
+
|
| 467 |
+
class LtgbertForCausalLM(LtgbertModel):
|
| 468 |
+
_keys_to_ignore_on_load_unexpected = ["head"]
|
| 469 |
+
|
| 470 |
+
def __init__(self, config, **kwargs):
|
| 471 |
+
config.is_decoder = True
|
| 472 |
+
super().__init__(config, add_mlm_layer=True, **kwargs)
|
| 473 |
+
|
| 474 |
+
def get_output_embeddings(self):
|
| 475 |
+
return self.classifier.nonlinearity[-1].weight
|
| 476 |
+
|
| 477 |
+
def set_output_embeddings(self, new_embeddings):
|
| 478 |
+
self.classifier.nonlinearity[-1].weight = new_embeddings
|
| 479 |
+
|
| 480 |
+
def get_input_embeddings(self):
|
| 481 |
+
return self.embedding.word_embedding
|
| 482 |
+
|
| 483 |
+
def set_input_embeddings(self, value):
|
| 484 |
+
self.embedding.word_embedding = value
|
| 485 |
+
|
| 486 |
+
def set_decoder(self, decoder):
|
| 487 |
+
self.transformer = decoder
|
| 488 |
+
|
| 489 |
+
def get_decoder(self):
|
| 490 |
+
return self.transformer
|
| 491 |
+
|
| 492 |
+
def can_generate(self):
|
| 493 |
+
return True
|
| 494 |
+
|
| 495 |
+
def forward(
|
| 496 |
+
self,
|
| 497 |
+
input_ids: torch.LongTensor = None,
|
| 498 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 499 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 500 |
+
token_type_ids: Optional[torch.Tensor] = None,
|
| 501 |
+
past_key_values = None,
|
| 502 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 503 |
+
labels: Optional[torch.LongTensor] = None,
|
| 504 |
+
use_cache: Optional[bool] = None,
|
| 505 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 506 |
+
output_attentions: Optional[bool] = None,
|
| 507 |
+
output_hidden_states: Optional[bool] = None,
|
| 508 |
+
return_dict: Optional[bool] = None
|
| 509 |
+
) -> Union[Tuple, CausalLMOutput]:
|
| 510 |
+
|
| 511 |
+
assert inputs_embeds is None, "inputs_embeds is not supported for now"
|
| 512 |
+
assert past_key_values is None, "past_key_values is not supported for now"
|
| 513 |
+
assert not use_cache, "use_cache is not supported for now"
|
| 514 |
+
# assert cache_position is None, "cache_position is not supported for now"
|
| 515 |
+
|
| 516 |
+
sequence_output, contextualized_embeddings, attention_probs = self.get_contextualized_embeddings(input_ids, attention_mask)
|
| 517 |
+
subword_prediction = self.classifier(sequence_output)
|
| 518 |
+
# subword_prediction[:, :, :16+1] = float("-inf")
|
| 519 |
+
|
| 520 |
+
masked_lm_loss = None
|
| 521 |
+
if labels is not None:
|
| 522 |
+
labels_flatten = labels[:, 1:].flatten()
|
| 523 |
+
subword_prediction_flatten = subword_prediction[:, :-1].flatten(0, 1)
|
| 524 |
+
masked_lm_loss = F.cross_entropy(subword_prediction_flatten, labels_flatten)
|
| 525 |
+
|
| 526 |
+
if not return_dict:
|
| 527 |
+
output = (
|
| 528 |
+
subword_prediction,
|
| 529 |
+
*([contextualized_embeddings] if output_hidden_states else []),
|
| 530 |
+
*([attention_probs] if output_attentions else [])
|
| 531 |
+
)
|
| 532 |
+
return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
|
| 533 |
+
|
| 534 |
+
return CausalLMOutput(
|
| 535 |
+
loss=masked_lm_loss,
|
| 536 |
+
logits=subword_prediction,
|
| 537 |
+
hidden_states=contextualized_embeddings if output_hidden_states else None,
|
| 538 |
+
attentions=attention_probs if output_attentions else None
|
| 539 |
+
)
|
| 540 |
+
|
| 541 |
+
|
| 542 |
+
def prepare_inputs_for_generation(
|
| 543 |
+
self,
|
| 544 |
+
input_ids,
|
| 545 |
+
past_key_values=None,
|
| 546 |
+
attention_mask=None,
|
| 547 |
+
inputs_embeds=None,
|
| 548 |
+
cache_position=None,
|
| 549 |
+
position_ids=None,
|
| 550 |
+
use_cache=True,
|
| 551 |
+
num_logits_to_keep=None,
|
| 552 |
+
**kwargs,
|
| 553 |
+
):
|
| 554 |
+
# If we have cache: let's slice `input_ids` through `cache_position`, to keep only the unprocessed tokens
|
| 555 |
+
# Exception 1: when passing input_embeds, input_ids may be missing entries
|
| 556 |
+
# Exception 2: some generation methods do special slicing of input_ids, so we don't need to do it here
|
| 557 |
+
if past_key_values is not None:
|
| 558 |
+
if inputs_embeds is not None: # Exception 1
|
| 559 |
+
input_ids = input_ids[:, -cache_position.shape[0] :]
|
| 560 |
+
elif input_ids.shape[1] != cache_position.shape[0]: # Default case (the "else", a no op, is Exception 2)
|
| 561 |
+
input_ids = input_ids[:, cache_position]
|
| 562 |
+
|
| 563 |
+
if attention_mask is not None and position_ids is None:
|
| 564 |
+
# create position_ids on the fly for batch generation
|
| 565 |
+
position_ids = attention_mask.long().cumsum(-1) - 1
|
| 566 |
+
position_ids.masked_fill_(attention_mask == 0, 1)
|
| 567 |
+
if past_key_values:
|
| 568 |
+
position_ids = position_ids[:, -input_ids.shape[1] :]
|
| 569 |
+
|
| 570 |
+
# This `clone` call is needed to avoid recapturing cuda graphs with `torch.compile`'s `mode="reduce-overhead`, as otherwise the input `position_ids` would have various stride during the decoding. Here, simply using `.contiguous()` is not sufficient as in the batch size = 1 case, `position_ids` is already contiguous but with varying stride which retriggers a capture.
|
| 571 |
+
position_ids = position_ids.clone(memory_format=torch.contiguous_format)
|
| 572 |
+
|
| 573 |
+
# if `inputs_embeds` are passed, we only want to use them in the 1st generation step
|
| 574 |
+
if inputs_embeds is not None and cache_position[0] == 0:
|
| 575 |
+
model_inputs = {"inputs_embeds": inputs_embeds}
|
| 576 |
+
else:
|
| 577 |
+
model_inputs = {"input_ids": input_ids.contiguous()} # `contiguous()` needed for compilation use cases
|
| 578 |
+
|
| 579 |
+
if num_logits_to_keep is not None:
|
| 580 |
+
model_inputs["num_logits_to_keep"] = num_logits_to_keep
|
| 581 |
+
|
| 582 |
+
model_inputs.update(
|
| 583 |
+
{
|
| 584 |
+
"position_ids": position_ids,
|
| 585 |
+
"cache_position": cache_position,
|
| 586 |
+
"past_key_values": past_key_values,
|
| 587 |
+
"use_cache": use_cache,
|
| 588 |
+
"attention_mask": attention_mask,
|
| 589 |
+
}
|
| 590 |
+
)
|
| 591 |
+
return model_inputs
|
| 592 |
+
|
| 593 |
+
|
| 594 |
+
|
| 595 |
+
class LtgbertForSequenceClassification(LtgbertModel):
|
| 596 |
+
_keys_to_ignore_on_load_unexpected = ["classifier"]
|
| 597 |
+
_keys_to_ignore_on_load_missing = ["head"]
|
| 598 |
+
|
| 599 |
+
def __init__(self, config, **kwargs):
|
| 600 |
+
super().__init__(config, add_mlm_layer=False, **kwargs)
|
| 601 |
+
|
| 602 |
+
self.num_labels = config.num_labels
|
| 603 |
+
self.head = Classifier(config, self.num_labels)
|
| 604 |
+
|
| 605 |
+
def forward(
|
| 606 |
+
self,
|
| 607 |
+
input_ids: Optional[torch.Tensor] = None,
|
| 608 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 609 |
+
token_type_ids: Optional[torch.Tensor] = None,
|
| 610 |
+
position_ids: Optional[torch.Tensor] = None,
|
| 611 |
+
output_attentions: Optional[bool] = None,
|
| 612 |
+
output_hidden_states: Optional[bool] = None,
|
| 613 |
+
return_dict: Optional[bool] = None,
|
| 614 |
+
labels: Optional[torch.LongTensor] = None,
|
| 615 |
+
**kwargs
|
| 616 |
+
) -> Union[Tuple[torch.Tensor], SequenceClassifierOutput]:
|
| 617 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 618 |
+
|
| 619 |
+
sequence_output, contextualized_embeddings, attention_probs = self.get_contextualized_embeddings(input_ids, attention_mask)
|
| 620 |
+
logits = self.head(sequence_output[:, 0, :])
|
| 621 |
+
|
| 622 |
+
loss = None
|
| 623 |
+
if labels is not None:
|
| 624 |
+
if self.config.problem_type is None:
|
| 625 |
+
if self.num_labels == 1:
|
| 626 |
+
self.config.problem_type = "regression"
|
| 627 |
+
elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
|
| 628 |
+
self.config.problem_type = "single_label_classification"
|
| 629 |
+
else:
|
| 630 |
+
self.config.problem_type = "multi_label_classification"
|
| 631 |
+
|
| 632 |
+
if self.config.problem_type == "regression":
|
| 633 |
+
loss_fct = nn.MSELoss()
|
| 634 |
+
if self.num_labels == 1:
|
| 635 |
+
loss = loss_fct(logits.squeeze(), labels.squeeze())
|
| 636 |
+
else:
|
| 637 |
+
loss = loss_fct(logits, labels)
|
| 638 |
+
elif self.config.problem_type == "single_label_classification":
|
| 639 |
+
loss_fct = nn.CrossEntropyLoss()
|
| 640 |
+
loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
|
| 641 |
+
elif self.config.problem_type == "multi_label_classification":
|
| 642 |
+
loss_fct = nn.BCEWithLogitsLoss()
|
| 643 |
+
loss = loss_fct(logits, labels)
|
| 644 |
+
|
| 645 |
+
if not return_dict:
|
| 646 |
+
output = (
|
| 647 |
+
logits,
|
| 648 |
+
*([contextualized_embeddings] if output_hidden_states else []),
|
| 649 |
+
*([attention_probs] if output_attentions else [])
|
| 650 |
+
)
|
| 651 |
+
return ((loss,) + output) if loss is not None else output
|
| 652 |
+
|
| 653 |
+
return SequenceClassifierOutput(
|
| 654 |
+
loss=loss,
|
| 655 |
+
logits=logits,
|
| 656 |
+
hidden_states=contextualized_embeddings if output_hidden_states else None,
|
| 657 |
+
attentions=attention_probs if output_attentions else None
|
| 658 |
+
)
|
| 659 |
+
|
| 660 |
+
|
| 661 |
+
class LtgbertForTokenClassification(LtgbertModel):
|
| 662 |
+
_keys_to_ignore_on_load_unexpected = ["classifier"]
|
| 663 |
+
_keys_to_ignore_on_load_missing = ["head"]
|
| 664 |
+
|
| 665 |
+
def __init__(self, config, **kwargs):
|
| 666 |
+
super().__init__(config, add_mlm_layer=False, **kwargs)
|
| 667 |
+
|
| 668 |
+
self.num_labels = config.num_labels
|
| 669 |
+
self.head = Classifier(config, self.num_labels)
|
| 670 |
+
|
| 671 |
+
def forward(
|
| 672 |
+
self,
|
| 673 |
+
input_ids: Optional[torch.Tensor] = None,
|
| 674 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 675 |
+
token_type_ids: Optional[torch.Tensor] = None,
|
| 676 |
+
position_ids: Optional[torch.Tensor] = None,
|
| 677 |
+
output_attentions: Optional[bool] = None,
|
| 678 |
+
output_hidden_states: Optional[bool] = None,
|
| 679 |
+
return_dict: Optional[bool] = None,
|
| 680 |
+
labels: Optional[torch.LongTensor] = None,
|
| 681 |
+
**kwargs
|
| 682 |
+
) -> Union[Tuple[torch.Tensor], TokenClassifierOutput]:
|
| 683 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 684 |
+
|
| 685 |
+
sequence_output, contextualized_embeddings, attention_probs = self.get_contextualized_embeddings(input_ids, attention_mask)
|
| 686 |
+
logits = self.head(sequence_output)
|
| 687 |
+
|
| 688 |
+
loss = None
|
| 689 |
+
if labels is not None:
|
| 690 |
+
loss_fct = nn.CrossEntropyLoss()
|
| 691 |
+
loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
|
| 692 |
+
|
| 693 |
+
if not return_dict:
|
| 694 |
+
output = (
|
| 695 |
+
logits,
|
| 696 |
+
*([contextualized_embeddings] if output_hidden_states else []),
|
| 697 |
+
*([attention_probs] if output_attentions else [])
|
| 698 |
+
)
|
| 699 |
+
return ((loss,) + output) if loss is not None else output
|
| 700 |
+
|
| 701 |
+
return TokenClassifierOutput(
|
| 702 |
+
loss=loss,
|
| 703 |
+
logits=logits,
|
| 704 |
+
hidden_states=contextualized_embeddings if output_hidden_states else None,
|
| 705 |
+
attentions=attention_probs if output_attentions else None
|
| 706 |
+
)
|
| 707 |
+
|
| 708 |
+
|
| 709 |
+
class LtgbertForQuestionAnswering(LtgbertModel):
|
| 710 |
+
_keys_to_ignore_on_load_unexpected = ["classifier"]
|
| 711 |
+
_keys_to_ignore_on_load_missing = ["head"]
|
| 712 |
+
|
| 713 |
+
def __init__(self, config, **kwargs):
|
| 714 |
+
super().__init__(config, add_mlm_layer=False, **kwargs)
|
| 715 |
+
|
| 716 |
+
self.num_labels = config.num_labels
|
| 717 |
+
self.head = Classifier(config, self.num_labels)
|
| 718 |
+
|
| 719 |
+
def forward(
|
| 720 |
+
self,
|
| 721 |
+
input_ids: Optional[torch.Tensor] = None,
|
| 722 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 723 |
+
token_type_ids: Optional[torch.Tensor] = None,
|
| 724 |
+
position_ids: Optional[torch.Tensor] = None,
|
| 725 |
+
output_attentions: Optional[bool] = None,
|
| 726 |
+
output_hidden_states: Optional[bool] = None,
|
| 727 |
+
return_dict: Optional[bool] = None,
|
| 728 |
+
start_positions: Optional[torch.Tensor] = None,
|
| 729 |
+
end_positions: Optional[torch.Tensor] = None,
|
| 730 |
+
**kwargs
|
| 731 |
+
) -> Union[Tuple[torch.Tensor], QuestionAnsweringModelOutput]:
|
| 732 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 733 |
+
|
| 734 |
+
sequence_output, contextualized_embeddings, attention_probs = self.get_contextualized_embeddings(input_ids, attention_mask)
|
| 735 |
+
logits = self.head(sequence_output)
|
| 736 |
+
|
| 737 |
+
start_logits, end_logits = logits.split(1, dim=-1)
|
| 738 |
+
start_logits = start_logits.squeeze(-1).contiguous()
|
| 739 |
+
end_logits = end_logits.squeeze(-1).contiguous()
|
| 740 |
+
|
| 741 |
+
total_loss = None
|
| 742 |
+
if start_positions is not None and end_positions is not None:
|
| 743 |
+
# If we are on multi-GPU, split add a dimension
|
| 744 |
+
if len(start_positions.size()) > 1:
|
| 745 |
+
start_positions = start_positions.squeeze(-1)
|
| 746 |
+
if len(end_positions.size()) > 1:
|
| 747 |
+
end_positions = end_positions.squeeze(-1)
|
| 748 |
+
|
| 749 |
+
# sometimes the start/end positions are outside our model inputs, we ignore these terms
|
| 750 |
+
ignored_index = start_logits.size(1)
|
| 751 |
+
start_positions = start_positions.clamp(0, ignored_index)
|
| 752 |
+
end_positions = end_positions.clamp(0, ignored_index)
|
| 753 |
+
|
| 754 |
+
loss_fct = nn.CrossEntropyLoss(ignore_index=ignored_index)
|
| 755 |
+
start_loss = loss_fct(start_logits, start_positions)
|
| 756 |
+
end_loss = loss_fct(end_logits, end_positions)
|
| 757 |
+
total_loss = (start_loss + end_loss) / 2
|
| 758 |
+
|
| 759 |
+
if not return_dict:
|
| 760 |
+
output = (
|
| 761 |
+
start_logits,
|
| 762 |
+
end_logits,
|
| 763 |
+
*([contextualized_embeddings] if output_hidden_states else []),
|
| 764 |
+
*([attention_probs] if output_attentions else [])
|
| 765 |
+
)
|
| 766 |
+
return ((total_loss,) + output) if total_loss is not None else output
|
| 767 |
+
|
| 768 |
+
return QuestionAnsweringModelOutput(
|
| 769 |
+
loss=total_loss,
|
| 770 |
+
start_logits=start_logits,
|
| 771 |
+
end_logits=end_logits,
|
| 772 |
+
hidden_states=contextualized_embeddings if output_hidden_states else None,
|
| 773 |
+
attentions=attention_probs if output_attentions else None
|
| 774 |
+
)
|
| 775 |
+
|
| 776 |
+
|
| 777 |
+
class LtgbertForMultipleChoice(LtgbertModel):
|
| 778 |
+
_keys_to_ignore_on_load_unexpected = ["classifier"]
|
| 779 |
+
_keys_to_ignore_on_load_missing = ["head"]
|
| 780 |
+
|
| 781 |
+
def __init__(self, config, **kwargs):
|
| 782 |
+
super().__init__(config, add_mlm_layer=False, **kwargs)
|
| 783 |
+
|
| 784 |
+
self.num_labels = getattr(config, "num_labels", 2)
|
| 785 |
+
self.head = Classifier(config, self.num_labels)
|
| 786 |
+
|
| 787 |
+
def forward(
|
| 788 |
+
self,
|
| 789 |
+
input_ids: Optional[torch.Tensor] = None,
|
| 790 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 791 |
+
token_type_ids: Optional[torch.Tensor] = None,
|
| 792 |
+
position_ids: Optional[torch.Tensor] = None,
|
| 793 |
+
labels: Optional[torch.Tensor] = None,
|
| 794 |
+
output_attentions: Optional[bool] = None,
|
| 795 |
+
output_hidden_states: Optional[bool] = None,
|
| 796 |
+
return_dict: Optional[bool] = None,
|
| 797 |
+
**kwargs
|
| 798 |
+
) -> Union[Tuple[torch.Tensor], MultipleChoiceModelOutput]:
|
| 799 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 800 |
+
num_choices = input_ids.shape[1]
|
| 801 |
+
|
| 802 |
+
flat_input_ids = input_ids.view(-1, input_ids.size(-1))
|
| 803 |
+
flat_attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None
|
| 804 |
+
|
| 805 |
+
sequence_output, contextualized_embeddings, attention_probs = self.get_contextualized_embeddings(flat_input_ids, flat_attention_mask)
|
| 806 |
+
logits = self.head(sequence_output)
|
| 807 |
+
reshaped_logits = logits.view(-1, num_choices)
|
| 808 |
+
|
| 809 |
+
loss = None
|
| 810 |
+
if labels is not None:
|
| 811 |
+
loss_fct = nn.CrossEntropyLoss()
|
| 812 |
+
loss = loss_fct(reshaped_logits, labels)
|
| 813 |
+
|
| 814 |
+
if not return_dict:
|
| 815 |
+
output = (
|
| 816 |
+
reshaped_logits,
|
| 817 |
+
*([contextualized_embeddings] if output_hidden_states else []),
|
| 818 |
+
*([attention_probs] if output_attentions else [])
|
| 819 |
+
)
|
| 820 |
+
return ((loss,) + output) if loss is not None else output
|
| 821 |
+
|
| 822 |
+
return MultipleChoiceModelOutput(
|
| 823 |
+
loss=loss,
|
| 824 |
+
logits=reshaped_logits,
|
| 825 |
+
hidden_states=contextualized_embeddings if output_hidden_states else None,
|
| 826 |
+
attentions=attention_probs if output_attentions else None
|
| 827 |
+
)
|