Instructions to use WesScivetti/GPT-BERT_Random_Seed1 with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use WesScivetti/GPT-BERT_Random_Seed1 with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("fill-mask", model="WesScivetti/GPT-BERT_Random_Seed1", trust_remote_code=True)# Load model directly from transformers import AutoModelForMaskedLM model = AutoModelForMaskedLM.from_pretrained("WesScivetti/GPT-BERT_Random_Seed1", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
Upload GPT-BERT checkpoint and custom loading code
Browse files- README.md +24 -0
- config.json +22 -0
- configuration_gpt_bert.py +57 -0
- modeling_gpt_bert_test.py +622 -0
- pytorch_model.bin +3 -0
- special_tokens_map.json +1 -0
- tokenizer.json +0 -0
- tokenizer_config.json +10 -0
README.md
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
library_name: transformers
|
| 3 |
+
pipeline_tag: fill-mask
|
| 4 |
+
tags:
|
| 5 |
+
- custom-code
|
| 6 |
+
- masked-language-modeling
|
| 7 |
+
---
|
| 8 |
+
|
| 9 |
+
# WesScivetti/GPT-BERT_Random_Seed1
|
| 10 |
+
|
| 11 |
+
Custom GPT-BERT checkpoint from the NPN filtered-corpus training experiments.
|
| 12 |
+
|
| 13 |
+
This repository includes the architecture code required by Transformers. Example:
|
| 14 |
+
|
| 15 |
+
```python
|
| 16 |
+
from transformers import AutoModelForMaskedLM, AutoTokenizer
|
| 17 |
+
|
| 18 |
+
repo_id = "WesScivetti/GPT-BERT_Random_Seed1"
|
| 19 |
+
tokenizer = AutoTokenizer.from_pretrained(repo_id)
|
| 20 |
+
model = AutoModelForMaskedLM.from_pretrained(repo_id, trust_remote_code=True)
|
| 21 |
+
model.eval()
|
| 22 |
+
```
|
| 23 |
+
|
| 24 |
+
|
config.json
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"attention_probs_dropout_prob": 0.1,
|
| 3 |
+
"hidden_dropout_prob": 0.1,
|
| 4 |
+
"hidden_size": 768,
|
| 5 |
+
"intermediate_size": 2560,
|
| 6 |
+
"max_position_embeddings": 512,
|
| 7 |
+
"position_bucket_size": 32,
|
| 8 |
+
"num_attention_heads": 12,
|
| 9 |
+
"num_hidden_layers": 12,
|
| 10 |
+
"vocab_size": 16384,
|
| 11 |
+
"layer_norm_eps": 1e-05,
|
| 12 |
+
"model_type": "gpt_bert",
|
| 13 |
+
"architectures": [
|
| 14 |
+
"GPTBERTForMaskedLM"
|
| 15 |
+
],
|
| 16 |
+
"auto_map": {
|
| 17 |
+
"AutoConfig": "configuration_gpt_bert.ModelConfig",
|
| 18 |
+
"AutoModel": "modeling_gpt_bert_test.GPTBERT",
|
| 19 |
+
"AutoModelForMaskedLM": "modeling_gpt_bert_test.GPTBERTForMaskedLM",
|
| 20 |
+
"AutoModelForCausalLM": "modeling_gpt_bert_test.GPTBERTForCausalLM"
|
| 21 |
+
}
|
| 22 |
+
}
|
configuration_gpt_bert.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
import pathlib
|
| 5 |
+
import copy
|
| 6 |
+
|
| 7 |
+
from typing import Any
|
| 8 |
+
from transformers.configuration_utils import PretrainedConfig
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class ModelConfig(PretrainedConfig):
|
| 12 |
+
# Unique identifier used by Hugging Face AutoConfig when this custom
|
| 13 |
+
# architecture is loaded from the Hub with trust_remote_code=True.
|
| 14 |
+
model_type = "gpt_bert"
|
| 15 |
+
|
| 16 |
+
def __init__(self, config_file=None, **kwargs):
|
| 17 |
+
super().__init__(**kwargs)
|
| 18 |
+
|
| 19 |
+
self.attention_probs_dropout_prob = kwargs.get("attention_probs_dropout_prob", 0.1)
|
| 20 |
+
self.hidden_dropout_prob = kwargs.get("hidden_dropout_prob", 0.1)
|
| 21 |
+
self.hidden_size = kwargs.get("hidden_size", 768)
|
| 22 |
+
self.intermediate_size = kwargs.get("intermediate_size", 2560)
|
| 23 |
+
self.max_position_embeddings = kwargs.get("max_position_embeddings", 512)
|
| 24 |
+
self.max_sequence_length = kwargs.get("max_sequence_length", self.max_position_embeddings)
|
| 25 |
+
self.position_bucket_size = kwargs.get("position_bucket_size", 32)
|
| 26 |
+
self.num_attention_heads = kwargs.get("num_attention_heads", 12)
|
| 27 |
+
self.num_hidden_layers = kwargs.get("num_hidden_layers", 12)
|
| 28 |
+
self.num_layers = kwargs.get("num_layers", self.num_hidden_layers)
|
| 29 |
+
self.vocab_size = kwargs.get("vocab_size", 16384)
|
| 30 |
+
self.layer_norm_eps = kwargs.get("layer_norm_eps", 1e-7)
|
| 31 |
+
|
| 32 |
+
if config_file is not None:
|
| 33 |
+
import json, pathlib
|
| 34 |
+
if isinstance(config_file, str):
|
| 35 |
+
config_file = pathlib.Path(config_file)
|
| 36 |
+
config = json.load(config_file.open("r"))
|
| 37 |
+
for key, value in config.items():
|
| 38 |
+
setattr(self, key, value)
|
| 39 |
+
|
| 40 |
+
def __repr__(self) -> str:
|
| 41 |
+
return str(self.to_json_string())
|
| 42 |
+
|
| 43 |
+
def to_dict(self) -> dict[str, Any]:
|
| 44 |
+
"""Serializes this instance to a Python dictionary."""
|
| 45 |
+
output: dict[str, Any] = copy.deepcopy(self.__dict__)
|
| 46 |
+
return output
|
| 47 |
+
|
| 48 |
+
# def to_json_string(self) -> str:
|
| 49 |
+
# """Serializes this instance to a JSON string."""
|
| 50 |
+
# return json.dumps(self.to_dict(), indent=2, sort_keys=True) + "\n"
|
| 51 |
+
|
| 52 |
+
def to_json_file(self, json_file_path: pathlib.Path | str) -> None:
|
| 53 |
+
"""Save this instance to a json file."""
|
| 54 |
+
if isinstance(json_file_path, str):
|
| 55 |
+
json_file_path: pathlib.Path = pathlib.Path(json_file_path)
|
| 56 |
+
with json_file_path.open("w", encoding='utf-8') as writer:
|
| 57 |
+
writer.write(self.to_json_string())
|
modeling_gpt_bert_test.py
ADDED
|
@@ -0,0 +1,622 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import math
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
import torch.nn as nn
|
| 7 |
+
import torch.nn.functional as F
|
| 8 |
+
from torch import _softmax_backward_data as _softmax_backward_data
|
| 9 |
+
try:
|
| 10 |
+
# Required when Transformers imports this file as Hub-hosted custom code.
|
| 11 |
+
from .configuration_gpt_bert import ModelConfig
|
| 12 |
+
except ImportError:
|
| 13 |
+
# Preserve direct use from this repository.
|
| 14 |
+
from configuration_gpt_bert import ModelConfig
|
| 15 |
+
|
| 16 |
+
from transformers.modeling_utils import PreTrainedModel
|
| 17 |
+
from transformers.modeling_outputs import (
|
| 18 |
+
BaseModelOutput,
|
| 19 |
+
CausalLMOutput
|
| 20 |
+
)
|
| 21 |
+
|
| 22 |
+
from typing import Optional, Union
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
# From https://github.com/epfml/DenseFormer
|
| 26 |
+
class InPlaceSetSlice(torch.autograd.Function):
|
| 27 |
+
@staticmethod
|
| 28 |
+
def forward(ctx, full_tensor, last_slice, x_idx, x_val):
|
| 29 |
+
full_tensor[x_idx] = x_val
|
| 30 |
+
ctx.x_idx = x_idx
|
| 31 |
+
ret = torch.Tensor().to(full_tensor.device)
|
| 32 |
+
ret.set_(full_tensor[:x_idx + 1])
|
| 33 |
+
return ret
|
| 34 |
+
|
| 35 |
+
@staticmethod
|
| 36 |
+
def backward(ctx, grad_out):
|
| 37 |
+
if ctx.x_idx == 0:
|
| 38 |
+
return None, None, None, grad_out[ctx.x_idx]
|
| 39 |
+
else:
|
| 40 |
+
return None, grad_out[:ctx.x_idx], None, grad_out[ctx.x_idx]
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def apply_inplace_set(x_acc, x_idx, x_val):
|
| 44 |
+
full_tensor, last_slice = x_acc
|
| 45 |
+
new_slice = InPlaceSetSlice.apply(full_tensor, last_slice, x_idx, x_val)
|
| 46 |
+
return full_tensor, new_slice
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
class DWAModules(torch.nn.Module):
|
| 50 |
+
def __init__(self, hidden_size, n_blocks):
|
| 51 |
+
super().__init__()
|
| 52 |
+
self.n_blocks = n_blocks
|
| 53 |
+
self.alphas = nn.ParameterList([nn.Parameter(torch.zeros(i + 2)) for i in range(n_blocks)])
|
| 54 |
+
self.accumulator = None
|
| 55 |
+
self._init_weights()
|
| 56 |
+
|
| 57 |
+
def _init_weights(self):
|
| 58 |
+
for module in self.alphas:
|
| 59 |
+
module.data.zero_()
|
| 60 |
+
module.data[-1] = 1.0
|
| 61 |
+
|
| 62 |
+
def init_accumulator(self, x):
|
| 63 |
+
self.accumulator = (torch.zeros((self.n_blocks + 1, *x.shape), device=x.device, dtype=x.dtype), None)
|
| 64 |
+
self.accumulator = apply_inplace_set(self.accumulator, 0, x)
|
| 65 |
+
|
| 66 |
+
def forward(self, x, block_idx):
|
| 67 |
+
assert self.accumulator is not None, "`init_accumulator(x)` needs to be called first"
|
| 68 |
+
self.accumulator = apply_inplace_set(
|
| 69 |
+
self.accumulator,
|
| 70 |
+
block_idx + 1,
|
| 71 |
+
x
|
| 72 |
+
)
|
| 73 |
+
x = torch.tensordot(self.alphas[block_idx], self.accumulator[1], dims=1)
|
| 74 |
+
return x
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
class Layer(nn.Module):
|
| 78 |
+
|
| 79 |
+
def __init__(self: Layer, config: ModelConfig, layer_idx: int = 0):
|
| 80 |
+
super().__init__()
|
| 81 |
+
self.attention = Attention(config)
|
| 82 |
+
self.mlp = FeedForward(config)
|
| 83 |
+
|
| 84 |
+
self.mlp.mlp[1].weight.data *= math.sqrt(1.0 / (2.0 * (1 + layer_idx)))
|
| 85 |
+
self.mlp.mlp[-2].weight.data *= math.sqrt(1.0 / (2.0 * (1 + layer_idx)))
|
| 86 |
+
|
| 87 |
+
def forward(self: Layer, x: torch.Tensor, attention_mask: torch.Tensor, relative_embedding: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
|
| 88 |
+
attention: torch.Tensor
|
| 89 |
+
attention_probs: torch.Tensor
|
| 90 |
+
attention, attention_probs = self.attention(x, attention_mask, relative_embedding)
|
| 91 |
+
x += attention
|
| 92 |
+
x += self.mlp(x)
|
| 93 |
+
|
| 94 |
+
return x, attention_probs
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
class MaskClassifier(nn.Module):
|
| 98 |
+
|
| 99 |
+
def __init__(self: MaskClassifier, config: ModelConfig, subword_embedding: nn.Parameter):
|
| 100 |
+
super().__init__()
|
| 101 |
+
self.nonlinearity = nn.Sequential(
|
| 102 |
+
nn.LayerNorm(config.hidden_size, config.layer_norm_eps, elementwise_affine=False),
|
| 103 |
+
nn.Linear(config.hidden_size, config.hidden_size),
|
| 104 |
+
nn.GELU(),
|
| 105 |
+
nn.LayerNorm(config.hidden_size, config.layer_norm_eps, elementwise_affine=False),
|
| 106 |
+
nn.Dropout(config.hidden_dropout_prob),
|
| 107 |
+
nn.Linear(subword_embedding.size(1), subword_embedding.size(0))
|
| 108 |
+
)
|
| 109 |
+
self.initialize(config.hidden_size, subword_embedding)
|
| 110 |
+
|
| 111 |
+
def initialize(self: MaskClassifier, hidden_size: int, embedding: nn.Parameter):
|
| 112 |
+
std: float = math.sqrt(2.0 / (5.0 * hidden_size))
|
| 113 |
+
nn.init.trunc_normal_(self.nonlinearity[1].weight, mean=0.0, std=std, a=-2*std, b=2*std)
|
| 114 |
+
self.nonlinearity[-1].weight = embedding
|
| 115 |
+
self.nonlinearity[1].bias.data.zero_()
|
| 116 |
+
self.nonlinearity[-1].bias.data.zero_()
|
| 117 |
+
|
| 118 |
+
def forward(self: MaskClassifier, x: torch.Tensor, masked_lm_labels: torch.Tensor | None = None) -> torch.Tensor:
|
| 119 |
+
if masked_lm_labels is not None:
|
| 120 |
+
x = torch.index_select(x.flatten(0, 1), 0, torch.nonzero(masked_lm_labels.flatten() != -100).squeeze())
|
| 121 |
+
x = self.nonlinearity(x)
|
| 122 |
+
|
| 123 |
+
return x
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
class GeGLU(nn.Module):
|
| 127 |
+
def forward(self: GeGLU, x: torch.Tensor) -> torch.Tensor:
|
| 128 |
+
gate: torch.Tensor
|
| 129 |
+
x, gate = x.chunk(2, dim=-1)
|
| 130 |
+
x = x * F.gelu(gate, approximate='tanh')
|
| 131 |
+
return x
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
class FeedForward(nn.Module):
|
| 135 |
+
def __init__(self: FeedForward, config: ModelConfig) -> None:
|
| 136 |
+
super().__init__()
|
| 137 |
+
self.mlp = nn.Sequential(
|
| 138 |
+
nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps, elementwise_affine=False),
|
| 139 |
+
nn.Linear(config.hidden_size, 2*config.intermediate_size, bias=False),
|
| 140 |
+
GeGLU(),
|
| 141 |
+
nn.LayerNorm(config.intermediate_size, eps=config.layer_norm_eps, elementwise_affine=False),
|
| 142 |
+
nn.Linear(config.intermediate_size, config.hidden_size, bias=False),
|
| 143 |
+
nn.Dropout(config.hidden_dropout_prob)
|
| 144 |
+
)
|
| 145 |
+
self.initialize(config.hidden_size)
|
| 146 |
+
|
| 147 |
+
def initialize(self: FeedForward, hidden_size: int) -> None:
|
| 148 |
+
std: float = math.sqrt(2.0 / (5.0 * hidden_size))
|
| 149 |
+
nn.init.trunc_normal_(self.mlp[1].weight, mean=0.0, std=std, a=-2*std, b=2*std)
|
| 150 |
+
nn.init.trunc_normal_(self.mlp[-2].weight, mean=0.0, std=std, a=-2*std, b=2*std)
|
| 151 |
+
|
| 152 |
+
def forward(self: FeedForward, x: torch.Tensor) -> torch.Tensor:
|
| 153 |
+
return self.mlp(x)
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
class MaskedSoftmax(torch.autograd.Function):
|
| 157 |
+
@staticmethod
|
| 158 |
+
def forward(self: MaskedSoftmax, x: torch.Tensor, mask: torch.Tensor, dim: int) -> torch.Tensor:
|
| 159 |
+
self.dim = dim
|
| 160 |
+
x.masked_fill_(mask, float('-inf'))
|
| 161 |
+
x = torch.softmax(x, self.dim)
|
| 162 |
+
x.masked_fill_(mask, 0.0)
|
| 163 |
+
self.save_for_backward(x)
|
| 164 |
+
return x
|
| 165 |
+
|
| 166 |
+
@staticmethod
|
| 167 |
+
def backward(self: MaskedSoftmax, grad_output: torch.Tensor) -> tuple[torch.Tensor, None, None]:
|
| 168 |
+
output: torch.Tensor
|
| 169 |
+
output, = self.saved_tensors
|
| 170 |
+
inputGrad: torch.Tensor = _softmax_backward_data(grad_output, output, self.dim, output.dtype)
|
| 171 |
+
return inputGrad, None, None
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
class Attention(nn.Module):
|
| 175 |
+
def __init__(self: Attention, config: ModelConfig) -> None:
|
| 176 |
+
super().__init__()
|
| 177 |
+
|
| 178 |
+
self.config: ModelConfig = config
|
| 179 |
+
|
| 180 |
+
if config.hidden_size % config.num_attention_heads != 0:
|
| 181 |
+
raise ValueError(f"The hidden size {config.hidden_size} is not a multiple of the number of attention heads {config.num_attention_heads}")
|
| 182 |
+
|
| 183 |
+
self.hidden_size: int = config.hidden_size
|
| 184 |
+
self.num_heads: int = config.num_attention_heads
|
| 185 |
+
self.head_size: int = config.hidden_size // config.num_attention_heads
|
| 186 |
+
|
| 187 |
+
self.in_proj_qk = nn.Linear(config.hidden_size, 2*config.hidden_size, bias=True)
|
| 188 |
+
self.in_proj_vg = nn.Linear(config.hidden_size, 2*config.hidden_size, bias=True)
|
| 189 |
+
self.out_proj = nn.Linear(config.hidden_size, config.hidden_size, bias=True)
|
| 190 |
+
|
| 191 |
+
self.pre_layer_norm = nn.LayerNorm(config.hidden_size, config.layer_norm_eps, elementwise_affine=False)
|
| 192 |
+
self.post_layer_norm = nn.LayerNorm(config.hidden_size, config.layer_norm_eps, elementwise_affine=False)
|
| 193 |
+
|
| 194 |
+
position_indices: torch.Tensor = torch.arange(config.max_position_embeddings, dtype=torch.long).unsqueeze(1) \
|
| 195 |
+
- torch.arange(config.max_position_embeddings, dtype=torch.long).unsqueeze(0)
|
| 196 |
+
position_indices: torch.Tensor = self.make_log_bucket_position(position_indices, config.position_bucket_size, config.max_position_embeddings)
|
| 197 |
+
position_indices = config.position_bucket_size - 1 + position_indices
|
| 198 |
+
self.register_buffer("position_indices", position_indices, persistent=False)
|
| 199 |
+
|
| 200 |
+
self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
|
| 201 |
+
self.scale: float = 1.0 / math.sqrt(3 * self.head_size)
|
| 202 |
+
self.initialize()
|
| 203 |
+
|
| 204 |
+
def make_log_bucket_position(self: Attention, relative_pos: torch.Tensor, bucket_size: int, max_position: int) -> torch.Tensor:
|
| 205 |
+
sign: torch.Tensor = torch.sign(relative_pos)
|
| 206 |
+
mid: int = bucket_size // 2
|
| 207 |
+
abs_pos: torch.Tensor = torch.where((relative_pos < mid) & (relative_pos > -mid), mid - 1, torch.abs(relative_pos).clamp(max=max_position - 1))
|
| 208 |
+
log_pos: torch.Tensor = torch.ceil(torch.log(abs_pos / mid) / math.log((max_position-1) / mid) * (mid - 1)).int() + mid
|
| 209 |
+
bucket_pos: torch.Tensor = torch.where(abs_pos <= mid, relative_pos, log_pos * sign).long()
|
| 210 |
+
return bucket_pos
|
| 211 |
+
|
| 212 |
+
def initialize(self: Attention) -> None:
|
| 213 |
+
std: float = math.sqrt(2.0 / (5.0 * self.hidden_size))
|
| 214 |
+
nn.init.trunc_normal_(self.in_proj_qk.weight, mean=0.0, std=std, a=-2*std, b=2*std)
|
| 215 |
+
nn.init.trunc_normal_(self.in_proj_vg.weight, mean=0.0, std=std, a=-2*std, b=2*std)
|
| 216 |
+
nn.init.trunc_normal_(self.out_proj.weight, mean=0.0, std=std, a=-2*std, b=2*std)
|
| 217 |
+
self.in_proj_qk.bias.data.zero_()
|
| 218 |
+
self.in_proj_vg.bias.data.zero_()
|
| 219 |
+
self.out_proj.bias.data.zero_()
|
| 220 |
+
|
| 221 |
+
def _create_position_tensors(self: Attention, relative_embedding: torch.Tensor, query_len: int, key_len: int) -> tuple[torch.Tensor, torch.Tensor]:
|
| 222 |
+
pos = self.in_proj_qk(self.dropout(relative_embedding)) # shape: [2T-1, 2D]
|
| 223 |
+
pos = F.embedding(self.position_indices[:query_len, :key_len], pos) # shape: [T, T, 2D]
|
| 224 |
+
query_pos, key_pos = pos.chunk(2, dim=-1)
|
| 225 |
+
query_pos = query_pos.view(query_len, key_len, self.num_heads, self.head_size)
|
| 226 |
+
key_pos = key_pos.view(query_len, key_len, self.num_heads, self.head_size)
|
| 227 |
+
|
| 228 |
+
return query_pos, key_pos
|
| 229 |
+
|
| 230 |
+
def attention_operation(self: Attention, query: torch.Tensor, key: torch.Tensor, value: torch.Tensor, attention_mask: torch.Tensor, query_pos: torch.Tensor, key_pos: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
|
| 231 |
+
key_len: int
|
| 232 |
+
batch_size: int
|
| 233 |
+
key_len, batch_size, _ = key.size()
|
| 234 |
+
query_len: int
|
| 235 |
+
query_len, _, _ = query.size()
|
| 236 |
+
|
| 237 |
+
query = query.reshape(query_len, batch_size * self.num_heads, self.head_size).transpose(0, 1)
|
| 238 |
+
key = key.reshape(key_len, batch_size * self.num_heads, self.head_size).transpose(0, 1)
|
| 239 |
+
value = value.reshape(key_len, batch_size * self.num_heads, self.head_size).transpose(0, 1)
|
| 240 |
+
|
| 241 |
+
attention_probs: torch.Tensor = torch.bmm(query, key.transpose(1, 2) * self.scale)
|
| 242 |
+
|
| 243 |
+
query = query.view(batch_size, self.num_heads, query_len, self.head_size)
|
| 244 |
+
key = key.view(batch_size, self.num_heads, query_len, self.head_size)
|
| 245 |
+
attention_probs = attention_probs.view(batch_size, self.num_heads, query_len, key_len)
|
| 246 |
+
attention_probs.add_(torch.einsum("bhqd,qkhd->bhqk", query, key_pos * self.scale))
|
| 247 |
+
attention_probs.add_(torch.einsum("bhkd,qkhd->bhqk", key * self.scale, query_pos))
|
| 248 |
+
|
| 249 |
+
attention_probs = MaskedSoftmax.apply(attention_probs, attention_mask, -1)
|
| 250 |
+
|
| 251 |
+
attention_probs = self.dropout(attention_probs)
|
| 252 |
+
attention_output: torch.Tensor = torch.bmm(attention_probs.flatten(0, 1), value) # shape: [B*H, Q, D]
|
| 253 |
+
attention_output = attention_output.transpose(0, 1).reshape(query_len, batch_size, self.hidden_size) # shape: [Q, B, H*D]
|
| 254 |
+
|
| 255 |
+
return attention_output, attention_probs
|
| 256 |
+
|
| 257 |
+
def forward(self: Attention, hidden_states: torch.Tensor, attention_mask: torch.Tensor, relative_embedding: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
|
| 258 |
+
key_len: int
|
| 259 |
+
batch_size: int
|
| 260 |
+
key_len, batch_size, _ = hidden_states.size()
|
| 261 |
+
query_len: int = key_len
|
| 262 |
+
|
| 263 |
+
if self.position_indices.size(0) < query_len:
|
| 264 |
+
position_indices = torch.arange(query_len, dtype=torch.long).unsqueeze(1) \
|
| 265 |
+
- torch.arange(query_len, dtype=torch.long).unsqueeze(0)
|
| 266 |
+
position_indices = self.make_log_bucket_position(position_indices, self.config.position_bucket_size, 512)
|
| 267 |
+
position_indices = self.config.position_bucket_size - 1 + position_indices
|
| 268 |
+
self.register_buffer("position_indices", position_indices.to(hidden_states.device), persistent=True)
|
| 269 |
+
|
| 270 |
+
hidden_states = self.pre_layer_norm(hidden_states)
|
| 271 |
+
query, key = self.in_proj_qk(hidden_states).chunk(2, dim=2) # shape: [T, B, D]
|
| 272 |
+
value, gate = self.in_proj_vg(hidden_states).chunk(2, dim=2) # shape: [T, B, D]
|
| 273 |
+
gate = F.gelu(gate)
|
| 274 |
+
|
| 275 |
+
query_pos: torch.Tensor
|
| 276 |
+
key_pos: torch.Tensor
|
| 277 |
+
query_pos, key_pos = self._create_position_tensors(relative_embedding, query_len, key_len)
|
| 278 |
+
|
| 279 |
+
attention_output: torch.Tensor
|
| 280 |
+
attention_probs: torch.Tensor
|
| 281 |
+
attention_output, attention_probs = self.attention_operation(query, key, value, attention_mask, query_pos, key_pos)
|
| 282 |
+
attention_output = attention_output * gate
|
| 283 |
+
attention_output = self.post_layer_norm(attention_output)
|
| 284 |
+
attention_output = self.out_proj(attention_output)
|
| 285 |
+
attention_output = self.dropout(attention_output)
|
| 286 |
+
|
| 287 |
+
return attention_output, attention_probs
|
| 288 |
+
|
| 289 |
+
|
| 290 |
+
class Embedding(nn.Module):
|
| 291 |
+
def __init__(self: Embedding, config: ModelConfig):
|
| 292 |
+
super().__init__()
|
| 293 |
+
self.hidden_size: int = config.hidden_size
|
| 294 |
+
|
| 295 |
+
self.word_embedding = nn.Embedding(config.vocab_size, config.hidden_size)
|
| 296 |
+
self.word_layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps, elementwise_affine=False)
|
| 297 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 298 |
+
|
| 299 |
+
self.relative_embedding = nn.Parameter(torch.empty(2 * config.position_bucket_size - 1, config.hidden_size))
|
| 300 |
+
self.relative_layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
| 301 |
+
|
| 302 |
+
self.initialize()
|
| 303 |
+
|
| 304 |
+
def initialize(self: Embedding):
|
| 305 |
+
std: float = math.sqrt(2.0 / (5.0 * self.hidden_size))
|
| 306 |
+
nn.init.trunc_normal_(self.relative_embedding, mean=0.0, std=std, a=-2*std, b=2*std)
|
| 307 |
+
nn.init.trunc_normal_(self.word_embedding.weight, mean=0.0, std=std, a=-2*std, b=2*std)
|
| 308 |
+
|
| 309 |
+
def forward(self: Embedding, input_ids: torch.Tensor):
|
| 310 |
+
word_embedding: torch.Tensor = self.dropout(self.word_layer_norm(self.word_embedding(input_ids)))
|
| 311 |
+
relative_embeddings: torch.Tensor = self.relative_layer_norm(self.relative_embedding)
|
| 312 |
+
return word_embedding, relative_embeddings
|
| 313 |
+
|
| 314 |
+
|
| 315 |
+
class GPTBERTPreTrainedModel(PreTrainedModel):
|
| 316 |
+
config_class = ModelConfig
|
| 317 |
+
supports_gradient_checkpointing = False
|
| 318 |
+
base_model_prefix = "model"
|
| 319 |
+
|
| 320 |
+
def _set_gradient_checkpointing(self, module, value=False):
|
| 321 |
+
raise NotImplementedError("Gradient checkpointing is not supported by this model")
|
| 322 |
+
|
| 323 |
+
def _init_weights(self, module):
|
| 324 |
+
std = math.sqrt(2.0 / (5.0 * self.hidden_size))
|
| 325 |
+
|
| 326 |
+
if isinstance(module, nn.Linear):
|
| 327 |
+
nn.init.trunc_normal_(module.weight.data, mean=0.0, std=std, a=-2*std, b=2*std)
|
| 328 |
+
if module.bias is not None:
|
| 329 |
+
module.bias.data.zero_()
|
| 330 |
+
elif isinstance(module, nn.Embedding):
|
| 331 |
+
nn.init.trunc_normal_(module.weight.data, mean=0.0, std=std, a=-2*std, b=2*std)
|
| 332 |
+
elif isinstance(module, nn.LayerNorm):
|
| 333 |
+
module.bias.data.zero_()
|
| 334 |
+
module.weight.data.fill_(1.0)
|
| 335 |
+
|
| 336 |
+
|
| 337 |
+
class GPTBERT(GPTBERTPreTrainedModel):
|
| 338 |
+
|
| 339 |
+
def __init__(self, config: ModelConfig, is_causal: bool = False, **kwargs):
|
| 340 |
+
super().__init__(config, **kwargs)
|
| 341 |
+
self.config = config
|
| 342 |
+
self.hidden_size = config.hidden_size
|
| 343 |
+
|
| 344 |
+
self.embedding = Embedding(config)
|
| 345 |
+
self.attention_layers = nn.ModuleList([Attention(config) for _ in range(config.num_layers)])
|
| 346 |
+
self.mlp_layers = nn.ModuleList([FeedForward(config) for _ in range(config.num_layers)])
|
| 347 |
+
self.dwa_modules = DWAModules(config.hidden_size, config.num_hidden_layers * 2)
|
| 348 |
+
|
| 349 |
+
for i, layer in enumerate(self.mlp_layers):
|
| 350 |
+
layer.mlp[1].weight.data *= math.sqrt(1.0 / (2.0 * (1 + i)))
|
| 351 |
+
layer.mlp[-2].weight.data *= math.sqrt(1.0 / (2.0 * (1 + i)))
|
| 352 |
+
|
| 353 |
+
self.is_causal = is_causal
|
| 354 |
+
|
| 355 |
+
def get_input_embeddings(self):
|
| 356 |
+
return self.embedding.word_embedding
|
| 357 |
+
|
| 358 |
+
def set_input_embeddings(self, value):
|
| 359 |
+
self.embedding.word_embedding = value
|
| 360 |
+
|
| 361 |
+
def get_contextualized_embeddings(self, input_ids: torch.Tensor, attention_mask: Optional[torch.Tensor] = None) -> list[torch.Tensor]:
|
| 362 |
+
"""
|
| 363 |
+
"""
|
| 364 |
+
input_shape = input_ids.size()
|
| 365 |
+
|
| 366 |
+
batch_size, seq_length = input_shape
|
| 367 |
+
|
| 368 |
+
if attention_mask is None:
|
| 369 |
+
attention_mask = input_ids.new_zeros((batch_size, seq_length), dtype=torch.bool).unsqueeze(1).unsqueeze(2)
|
| 370 |
+
else:
|
| 371 |
+
attention_mask = ~attention_mask.bool()
|
| 372 |
+
|
| 373 |
+
if len(attention_mask.size()) == 2:
|
| 374 |
+
attention_mask = attention_mask.unsqueeze(1).unsqueeze(2)
|
| 375 |
+
elif len(attention_mask.size()) == 3:
|
| 376 |
+
attention_mask = attention_mask.unsqueeze(1)
|
| 377 |
+
|
| 378 |
+
if self.is_causal:
|
| 379 |
+
attention_mask = attention_mask | input_ids.new_ones((seq_length, seq_length), dtype=torch.bool).triu(1).unsqueeze(0).unsqueeze(0)
|
| 380 |
+
|
| 381 |
+
static_embeddings, relative_embeddings = self.embedding(input_ids.t())
|
| 382 |
+
contextualized_embeddings = [static_embeddings]
|
| 383 |
+
attention_probs = []
|
| 384 |
+
self.dwa_modules.init_accumulator(static_embeddings)
|
| 385 |
+
for i, (attention_layer, mlp_layer) in enumerate(zip(self.attention_layers, self.mlp_layers)):
|
| 386 |
+
attention, layer_attention_probs = attention_layer(contextualized_embeddings[-1], attention_mask, relative_embeddings)
|
| 387 |
+
layer_embeddings = contextualized_embeddings[-1] + attention
|
| 388 |
+
layer_embeddings = self.dwa_modules(layer_embeddings, block_idx=i * 2)
|
| 389 |
+
layer_embeddings = layer_embeddings + mlp_layer(layer_embeddings)
|
| 390 |
+
layer_embeddings = self.dwa_modules(layer_embeddings, block_idx=i * 2 + 1)
|
| 391 |
+
contextualized_embeddings.append(layer_embeddings)
|
| 392 |
+
attention_probs.append(layer_attention_probs)
|
| 393 |
+
contextualized_embeddings = [emb.transpose(0, 1) for emb in contextualized_embeddings]
|
| 394 |
+
last_layer = contextualized_embeddings[-1]
|
| 395 |
+
return last_layer, contextualized_embeddings, attention_probs
|
| 396 |
+
|
| 397 |
+
def forward(
|
| 398 |
+
self,
|
| 399 |
+
input_ids: torch.Tensor,
|
| 400 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 401 |
+
token_type_ids: Optional[torch.Tensor] = None,
|
| 402 |
+
position_ids: Optional[torch.Tensor] = None,
|
| 403 |
+
output_hidden_states: Optional[bool] = None,
|
| 404 |
+
output_attentions: Optional[bool] = None,
|
| 405 |
+
return_dict: Optional[bool] = None,
|
| 406 |
+
**kwargs
|
| 407 |
+
) -> Union[tuple[torch.Tensor], BaseModelOutput]:
|
| 408 |
+
"""
|
| 409 |
+
"""
|
| 410 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 411 |
+
|
| 412 |
+
sequence_output, contextualized_embeddings, attention_probs = self.get_contextualized_embeddings(input_ids, attention_mask)
|
| 413 |
+
|
| 414 |
+
if not return_dict:
|
| 415 |
+
return (
|
| 416 |
+
sequence_output,
|
| 417 |
+
*([contextualized_embeddings] if output_hidden_states else []),
|
| 418 |
+
*([attention_probs] if output_attentions else [])
|
| 419 |
+
)
|
| 420 |
+
|
| 421 |
+
return BaseModelOutput(
|
| 422 |
+
last_hidden_state=sequence_output,
|
| 423 |
+
hidden_states=contextualized_embeddings if output_hidden_states else None,
|
| 424 |
+
attentions=attention_probs if output_attentions else None
|
| 425 |
+
)
|
| 426 |
+
|
| 427 |
+
# To do Masked Language Modeling instead, you can replace MyModelForCausalLM by MyModelForMaskedLM
|
| 428 |
+
# and change the output type from CausalLMOutput to MaskedLMOutput.
|
| 429 |
+
|
| 430 |
+
|
| 431 |
+
class GPTBERTForCausalLM(GPTBERTPreTrainedModel):
|
| 432 |
+
_keys_to_ignore_on_load_unexpected = ["head"]
|
| 433 |
+
|
| 434 |
+
def __init__(self, config, **kwargs):
|
| 435 |
+
super().__init__(config, **kwargs)
|
| 436 |
+
self.model = GPTBERT(config, is_causal=True, **kwargs)
|
| 437 |
+
self.vocab_size = config.vocab_size
|
| 438 |
+
self.lm_head = MaskClassifier(config, self.model.embedding.word_embedding.weight)
|
| 439 |
+
self.hidden_size = config.hidden_size
|
| 440 |
+
|
| 441 |
+
def get_output_embeddings(self):
|
| 442 |
+
return self.lm_head.nonlinearity[-1].weight
|
| 443 |
+
|
| 444 |
+
def set_output_embeddings(self, new_embeddings):
|
| 445 |
+
self.lm_head.nonlinearity[-1].weight = new_embeddings
|
| 446 |
+
|
| 447 |
+
def get_input_embeddings(self):
|
| 448 |
+
return self.model.embedding.word_embedding
|
| 449 |
+
|
| 450 |
+
def set_input_embeddings(self, value):
|
| 451 |
+
self.model.embedding.word_embedding = value
|
| 452 |
+
|
| 453 |
+
def set_decoder(self, decoder):
|
| 454 |
+
self.model = decoder
|
| 455 |
+
|
| 456 |
+
def get_decoder(self):
|
| 457 |
+
return self.model
|
| 458 |
+
|
| 459 |
+
def can_generate(self):
|
| 460 |
+
return True
|
| 461 |
+
|
| 462 |
+
def forward(
|
| 463 |
+
self,
|
| 464 |
+
input_ids: torch.Tensor,
|
| 465 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 466 |
+
token_type_ids: Optional[torch.Tensor] = None,
|
| 467 |
+
position_ids: Optional[torch.Tensor] = None,
|
| 468 |
+
output_hidden_states: Optional[bool] = None,
|
| 469 |
+
output_attentions: Optional[bool] = None,
|
| 470 |
+
return_dict: Optional[bool] = None,
|
| 471 |
+
labels: Optional[torch.LongTensor] = None,
|
| 472 |
+
**kwargs
|
| 473 |
+
) -> Union[tuple, CausalLMOutput]:
|
| 474 |
+
|
| 475 |
+
|
| 476 |
+
|
| 477 |
+
sequence_output, contextualized_embeddings, attention_probs = self.model.get_contextualized_embeddings(input_ids, attention_mask)
|
| 478 |
+
subword_prediction = self.lm_head(sequence_output)
|
| 479 |
+
|
| 480 |
+
loss = None
|
| 481 |
+
if labels is not None:
|
| 482 |
+
gold_labels = labels.flatten()
|
| 483 |
+
gold_labels = gold_labels[gold_labels != -100]
|
| 484 |
+
|
| 485 |
+
loss = F.cross_entropy(subword_prediction, gold_labels)
|
| 486 |
+
|
| 487 |
+
return_dict = True if return_dict is None else return_dict
|
| 488 |
+
if not return_dict:
|
| 489 |
+
output = (
|
| 490 |
+
subword_prediction,
|
| 491 |
+
*([contextualized_embeddings] if output_hidden_states else []),
|
| 492 |
+
*([attention_probs] if output_attentions else [])
|
| 493 |
+
)
|
| 494 |
+
return ((loss,) + output) if loss is not None else output
|
| 495 |
+
|
| 496 |
+
return CausalLMOutput(
|
| 497 |
+
loss=loss,
|
| 498 |
+
logits=subword_prediction,
|
| 499 |
+
hidden_states=contextualized_embeddings if output_hidden_states else None,
|
| 500 |
+
attentions=attention_probs if output_attentions else None
|
| 501 |
+
)
|
| 502 |
+
|
| 503 |
+
def prepare_inputs_for_generation(
|
| 504 |
+
self,
|
| 505 |
+
input_ids: torch.Tensor,
|
| 506 |
+
past_key_values: Optional[torch.Tensor] = None,
|
| 507 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 508 |
+
inputs_embeds: Optional[torch.Tensor] = None,
|
| 509 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 510 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 511 |
+
use_cache: bool = True,
|
| 512 |
+
num_logits_to_keep: Optional[int] = None,
|
| 513 |
+
**kwargs,
|
| 514 |
+
):
|
| 515 |
+
# If we have cache: let's slice `input_ids` through `cache_position`, to keep only the unprocessed tokens
|
| 516 |
+
# Exception 1: when passing input_embeds, input_ids may be missing entries
|
| 517 |
+
# Exception 2: some generation methods do special slicing of input_ids, so we don't need to do it here
|
| 518 |
+
if past_key_values is not None:
|
| 519 |
+
if inputs_embeds is not None: # Exception 1
|
| 520 |
+
input_ids = input_ids[:, -cache_position.shape[0] :]
|
| 521 |
+
elif input_ids.shape[1] != cache_position.shape[0]: # Default case (the "else", a no op, is Exception 2)
|
| 522 |
+
input_ids = input_ids[:, cache_position]
|
| 523 |
+
|
| 524 |
+
if attention_mask is not None and position_ids is None:
|
| 525 |
+
# create position_ids on the fly for batch generation
|
| 526 |
+
position_ids = attention_mask.long().cumsum(-1) - 1
|
| 527 |
+
position_ids.masked_fill_(attention_mask == 0, 1)
|
| 528 |
+
if past_key_values:
|
| 529 |
+
position_ids = position_ids[:, -input_ids.shape[1] :]
|
| 530 |
+
|
| 531 |
+
# 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.
|
| 532 |
+
position_ids = position_ids.clone(memory_format=torch.contiguous_format)
|
| 533 |
+
|
| 534 |
+
# if `inputs_embeds` are passed, we only want to use them in the 1st generation step
|
| 535 |
+
if inputs_embeds is not None and cache_position[0] == 0:
|
| 536 |
+
model_inputs = {"inputs_embeds": inputs_embeds}
|
| 537 |
+
else:
|
| 538 |
+
model_inputs = {"input_ids": input_ids.contiguous()} # `contiguous()` needed for compilation use cases
|
| 539 |
+
|
| 540 |
+
if num_logits_to_keep is not None:
|
| 541 |
+
model_inputs["num_logits_to_keep"] = num_logits_to_keep
|
| 542 |
+
|
| 543 |
+
model_inputs.update(
|
| 544 |
+
{
|
| 545 |
+
"position_ids": position_ids,
|
| 546 |
+
"cache_position": cache_position,
|
| 547 |
+
"past_key_values": past_key_values,
|
| 548 |
+
"use_cache": use_cache,
|
| 549 |
+
"attention_mask": attention_mask,
|
| 550 |
+
}
|
| 551 |
+
)
|
| 552 |
+
return model_inputs
|
| 553 |
+
|
| 554 |
+
|
| 555 |
+
class GPTBERTForMaskedLM(GPTBERTPreTrainedModel):
|
| 556 |
+
_keys_to_ignore_on_load_unexpected = ["head"]
|
| 557 |
+
|
| 558 |
+
def __init__(self, config, **kwargs):
|
| 559 |
+
super().__init__(config, **kwargs)
|
| 560 |
+
self.model = GPTBERT(config, is_causal=False, **kwargs)
|
| 561 |
+
self.vocab_size = config.vocab_size
|
| 562 |
+
self.lm_head = MaskClassifier(config, self.model.embedding.word_embedding.weight)
|
| 563 |
+
self.hidden_size = config.hidden_size
|
| 564 |
+
|
| 565 |
+
def get_output_embeddings(self):
|
| 566 |
+
return self.lm_head.nonlinearity[-1].weight
|
| 567 |
+
|
| 568 |
+
def set_output_embeddings(self, new_embeddings):
|
| 569 |
+
self.lm_head.nonlinearity[-1].weight = new_embeddings
|
| 570 |
+
|
| 571 |
+
def get_input_embeddings(self):
|
| 572 |
+
return self.model.embedding.word_embedding
|
| 573 |
+
|
| 574 |
+
def set_input_embeddings(self, value):
|
| 575 |
+
self.model.embedding.word_embedding = value
|
| 576 |
+
|
| 577 |
+
def set_encoder(self, encoder):
|
| 578 |
+
self.model = encoder
|
| 579 |
+
|
| 580 |
+
def get_encoder(self):
|
| 581 |
+
return self.model
|
| 582 |
+
|
| 583 |
+
def can_generate(self):
|
| 584 |
+
return True
|
| 585 |
+
|
| 586 |
+
def forward(
|
| 587 |
+
self,
|
| 588 |
+
input_ids: torch.Tensor,
|
| 589 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 590 |
+
token_type_ids: Optional[torch.Tensor] = None,
|
| 591 |
+
position_ids: Optional[torch.Tensor] = None,
|
| 592 |
+
output_hidden_states: Optional[bool] = None,
|
| 593 |
+
output_attentions: Optional[bool] = None,
|
| 594 |
+
return_dict: Optional[bool] = None,
|
| 595 |
+
labels: Optional[torch.LongTensor] = None,
|
| 596 |
+
**kwargs
|
| 597 |
+
) -> Union[tuple, CausalLMOutput]:
|
| 598 |
+
|
| 599 |
+
sequence_output, contextualized_embeddings, attention_probs = self.model.get_contextualized_embeddings(input_ids, attention_mask)
|
| 600 |
+
subword_prediction = self.lm_head(sequence_output)
|
| 601 |
+
|
| 602 |
+
loss = None
|
| 603 |
+
if labels is not None:
|
| 604 |
+
gold_labels = labels.flatten()
|
| 605 |
+
gold_labels = gold_labels[gold_labels != -100]
|
| 606 |
+
|
| 607 |
+
loss = F.cross_entropy(subword_prediction, gold_labels)
|
| 608 |
+
|
| 609 |
+
if not return_dict:
|
| 610 |
+
output = (
|
| 611 |
+
subword_prediction,
|
| 612 |
+
*([contextualized_embeddings] if output_hidden_states else []),
|
| 613 |
+
*([attention_probs] if output_attentions else [])
|
| 614 |
+
)
|
| 615 |
+
return ((loss,) + output) if loss is not None else output
|
| 616 |
+
|
| 617 |
+
return CausalLMOutput(
|
| 618 |
+
loss=loss,
|
| 619 |
+
logits=subword_prediction,
|
| 620 |
+
hidden_states=contextualized_embeddings if output_hidden_states else None,
|
| 621 |
+
attentions=attention_probs if output_attentions else None
|
| 622 |
+
)
|
pytorch_model.bin
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:5b96fec17eb64135f3c51853ca79a1e8a19f639bfb021ff71ac13c3b476a134c
|
| 3 |
+
size 503028431
|
special_tokens_map.json
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
{"bos_token": "<s>", "eos_token": "</s>", "unk_token": "<unk>", "sep_token": "</s>", "pad_token": "<pad>", "cls_token": "<s>", "mask_token": "<mask>"}
|
tokenizer.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
tokenizer_config.json
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"tokenizer_class": "PreTrainedTokenizerFast",
|
| 3 |
+
"bos_token": "<s>",
|
| 4 |
+
"eos_token": "</s>",
|
| 5 |
+
"unk_token": "<unk>",
|
| 6 |
+
"sep_token": "</s>",
|
| 7 |
+
"pad_token": "<pad>",
|
| 8 |
+
"cls_token": "<s>",
|
| 9 |
+
"mask_token": "<mask>"
|
| 10 |
+
}
|