Upload folder using huggingface_hub
Browse files- config.json +29 -0
- configuration_gpt_bert.py +51 -0
- model.safetensors +3 -0
- modeling_gpt_bert.py +492 -0
- special_tokens_map.json +37 -0
- tokenizer.json +0 -0
- tokenizer_config.json +54 -0
config.json
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"architectures": [
|
| 3 |
+
"GPTBertForMaskedLM"
|
| 4 |
+
],
|
| 5 |
+
"attention_probs_dropout_prob": 0.1,
|
| 6 |
+
"auto_map": {
|
| 7 |
+
"AutoConfig": "configuration_gpt_bert.GPTBertConfig",
|
| 8 |
+
"AutoModel": "modeling_gpt_bert.GPTBertModel",
|
| 9 |
+
"AutoModelForCausalLM": "modeling_gpt_bert.GPTBertForCausalLM",
|
| 10 |
+
"AutoModelForMaskedLM": "modeling_gpt_bert.GPTBertForMaskedLM"
|
| 11 |
+
},
|
| 12 |
+
"bos_token_id": 0,
|
| 13 |
+
"dtype": "float32",
|
| 14 |
+
"eos_token_id": 2,
|
| 15 |
+
"hidden_dropout_prob": 0.1,
|
| 16 |
+
"hidden_size": 720,
|
| 17 |
+
"intermediate_size": 2048,
|
| 18 |
+
"layer_norm_eps": 1e-05,
|
| 19 |
+
"mask_token_id": 4,
|
| 20 |
+
"max_position_embeddings": 512,
|
| 21 |
+
"model_type": "gpt_bert_mntp",
|
| 22 |
+
"num_attention_heads": 12,
|
| 23 |
+
"num_hidden_layers": 12,
|
| 24 |
+
"pad_token_id": 1,
|
| 25 |
+
"position_bucket_size": 32,
|
| 26 |
+
"transformers_version": "4.57.6",
|
| 27 |
+
"unk_token_id": 3,
|
| 28 |
+
"vocab_size": 16000
|
| 29 |
+
}
|
configuration_gpt_bert.py
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from transformers import PretrainedConfig
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
class GPTBertConfig(PretrainedConfig):
|
| 5 |
+
model_type = "gpt_bert_mntp"
|
| 6 |
+
|
| 7 |
+
def __init__(
|
| 8 |
+
self,
|
| 9 |
+
vocab_size=16000,
|
| 10 |
+
hidden_size=720,
|
| 11 |
+
intermediate_size=2048,
|
| 12 |
+
num_hidden_layers=12,
|
| 13 |
+
num_attention_heads=12,
|
| 14 |
+
max_position_embeddings=512,
|
| 15 |
+
position_bucket_size=32,
|
| 16 |
+
hidden_dropout_prob=0.1,
|
| 17 |
+
attention_probs_dropout_prob=0.1,
|
| 18 |
+
layer_norm_eps=1e-5,
|
| 19 |
+
pad_token_id=1,
|
| 20 |
+
bos_token_id=0,
|
| 21 |
+
eos_token_id=2,
|
| 22 |
+
unk_token_id=3,
|
| 23 |
+
mask_token_id=4,
|
| 24 |
+
**kwargs,
|
| 25 |
+
):
|
| 26 |
+
super().__init__(
|
| 27 |
+
pad_token_id=pad_token_id,
|
| 28 |
+
bos_token_id=bos_token_id,
|
| 29 |
+
eos_token_id=eos_token_id,
|
| 30 |
+
**kwargs,
|
| 31 |
+
)
|
| 32 |
+
self.vocab_size = vocab_size
|
| 33 |
+
self.hidden_size = hidden_size
|
| 34 |
+
self.intermediate_size = intermediate_size
|
| 35 |
+
self.num_hidden_layers = num_hidden_layers
|
| 36 |
+
self.num_attention_heads = num_attention_heads
|
| 37 |
+
self.max_position_embeddings = max_position_embeddings
|
| 38 |
+
self.position_bucket_size = position_bucket_size
|
| 39 |
+
self.hidden_dropout_prob = hidden_dropout_prob
|
| 40 |
+
self.attention_probs_dropout_prob = attention_probs_dropout_prob
|
| 41 |
+
self.layer_norm_eps = layer_norm_eps
|
| 42 |
+
self.unk_token_id = unk_token_id
|
| 43 |
+
self.mask_token_id = mask_token_id
|
| 44 |
+
self.tie_word_embeddings = True
|
| 45 |
+
self.architectures = ["GPTBertForMaskedLM"]
|
| 46 |
+
self.auto_map = {
|
| 47 |
+
"AutoConfig": "configuration_gpt_bert.GPTBertConfig",
|
| 48 |
+
"AutoModel": "modeling_gpt_bert.GPTBertModel",
|
| 49 |
+
"AutoModelForMaskedLM": "modeling_gpt_bert.GPTBertForMaskedLM",
|
| 50 |
+
"AutoModelForCausalLM": "modeling_gpt_bert.GPTBertForCausalLM",
|
| 51 |
+
}
|
model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:7159b2e4b9f841c6e72ce1c1b1e9e210e34ac8d10a2cd3f72bec62b47b731269
|
| 3 |
+
size 385344608
|
modeling_gpt_bert.py
ADDED
|
@@ -0,0 +1,492 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
from dataclasses import dataclass
|
| 3 |
+
from typing import Optional, Tuple
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
import torch.nn as nn
|
| 7 |
+
import torch.nn.functional as F
|
| 8 |
+
from transformers import PreTrainedModel
|
| 9 |
+
from transformers.modeling_outputs import BaseModelOutput, CausalLMOutput, MaskedLMOutput
|
| 10 |
+
from transformers.utils import ModelOutput
|
| 11 |
+
|
| 12 |
+
try:
|
| 13 |
+
from .configuration_gpt_bert import GPTBertConfig
|
| 14 |
+
except ImportError:
|
| 15 |
+
from configuration_gpt_bert import GPTBertConfig
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
@dataclass
|
| 19 |
+
class GPTBertTrainingOutput(ModelOutput):
|
| 20 |
+
loss: Optional[torch.Tensor] = None
|
| 21 |
+
logits: Optional[torch.Tensor] = None
|
| 22 |
+
ce_loss: Optional[torch.Tensor] = None
|
| 23 |
+
z_loss: Optional[torch.Tensor] = None
|
| 24 |
+
accuracy: Optional[torch.Tensor] = None
|
| 25 |
+
num_tokens: Optional[torch.Tensor] = None
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class GeGLU(nn.Module):
|
| 29 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 30 |
+
value, gate = x.chunk(2, dim=-1)
|
| 31 |
+
return value * F.gelu(gate, approximate="tanh")
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def _relative_position_buckets(
|
| 35 |
+
relative_position: torch.Tensor,
|
| 36 |
+
bucket_size: int,
|
| 37 |
+
max_position: int,
|
| 38 |
+
) -> torch.Tensor:
|
| 39 |
+
sign = torch.sign(relative_position)
|
| 40 |
+
mid = bucket_size // 2
|
| 41 |
+
abs_pos = torch.where(
|
| 42 |
+
(relative_position < mid) & (relative_position > -mid),
|
| 43 |
+
torch.full_like(relative_position, mid - 1),
|
| 44 |
+
torch.abs(relative_position).clamp(max=max_position - 1),
|
| 45 |
+
)
|
| 46 |
+
safe = abs_pos.clamp(min=mid)
|
| 47 |
+
log_pos = (
|
| 48 |
+
torch.ceil(
|
| 49 |
+
torch.log(safe.float() / mid)
|
| 50 |
+
/ math.log((max_position - 1) / mid)
|
| 51 |
+
* (mid - 1)
|
| 52 |
+
).long()
|
| 53 |
+
+ mid
|
| 54 |
+
)
|
| 55 |
+
bucket_pos = torch.where(abs_pos <= mid, relative_position, log_pos * sign)
|
| 56 |
+
return bucket_size - 1 + bucket_pos.long()
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
class GPTBertEmbeddings(nn.Module):
|
| 60 |
+
def __init__(self, config: GPTBertConfig):
|
| 61 |
+
super().__init__()
|
| 62 |
+
self.hidden_size = config.hidden_size
|
| 63 |
+
self.word_embeddings = nn.Embedding(
|
| 64 |
+
config.vocab_size,
|
| 65 |
+
config.hidden_size,
|
| 66 |
+
padding_idx=config.pad_token_id,
|
| 67 |
+
)
|
| 68 |
+
self.word_norm = nn.LayerNorm(
|
| 69 |
+
config.hidden_size,
|
| 70 |
+
eps=config.layer_norm_eps,
|
| 71 |
+
elementwise_affine=False,
|
| 72 |
+
)
|
| 73 |
+
self.relative_embeddings = nn.Parameter(
|
| 74 |
+
torch.empty(2 * config.position_bucket_size - 1, config.hidden_size)
|
| 75 |
+
)
|
| 76 |
+
self.relative_norm = nn.LayerNorm(
|
| 77 |
+
config.hidden_size,
|
| 78 |
+
eps=config.layer_norm_eps,
|
| 79 |
+
)
|
| 80 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 81 |
+
self.reset_parameters()
|
| 82 |
+
|
| 83 |
+
def reset_parameters(self):
|
| 84 |
+
std = math.sqrt(2.0 / (5.0 * self.hidden_size))
|
| 85 |
+
nn.init.trunc_normal_(
|
| 86 |
+
self.word_embeddings.weight, mean=0.0, std=std, a=-2 * std, b=2 * std
|
| 87 |
+
)
|
| 88 |
+
nn.init.trunc_normal_(
|
| 89 |
+
self.relative_embeddings, mean=0.0, std=std, a=-2 * std, b=2 * std
|
| 90 |
+
)
|
| 91 |
+
if self.word_embeddings.padding_idx is not None:
|
| 92 |
+
with torch.no_grad():
|
| 93 |
+
self.word_embeddings.weight[self.word_embeddings.padding_idx].zero_()
|
| 94 |
+
|
| 95 |
+
def forward(self, input_ids: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
|
| 96 |
+
x = self.dropout(self.word_norm(self.word_embeddings(input_ids)))
|
| 97 |
+
rel = self.relative_norm(self.relative_embeddings)
|
| 98 |
+
return x, rel
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
class GPTBertAttention(nn.Module):
|
| 102 |
+
def __init__(self, config: GPTBertConfig):
|
| 103 |
+
super().__init__()
|
| 104 |
+
if config.hidden_size % config.num_attention_heads != 0:
|
| 105 |
+
raise ValueError("hidden_size must be divisible by num_attention_heads")
|
| 106 |
+
self.config = config
|
| 107 |
+
self.hidden_size = config.hidden_size
|
| 108 |
+
self.num_heads = config.num_attention_heads
|
| 109 |
+
self.head_dim = config.hidden_size // config.num_attention_heads
|
| 110 |
+
|
| 111 |
+
self.qk_proj = nn.Linear(config.hidden_size, 2 * config.hidden_size)
|
| 112 |
+
self.vg_proj = nn.Linear(config.hidden_size, 2 * config.hidden_size)
|
| 113 |
+
self.out_proj = nn.Linear(config.hidden_size, config.hidden_size)
|
| 114 |
+
self.pre_norm = nn.LayerNorm(
|
| 115 |
+
config.hidden_size,
|
| 116 |
+
eps=config.layer_norm_eps,
|
| 117 |
+
elementwise_affine=False,
|
| 118 |
+
)
|
| 119 |
+
self.post_norm = nn.LayerNorm(
|
| 120 |
+
config.hidden_size,
|
| 121 |
+
eps=config.layer_norm_eps,
|
| 122 |
+
elementwise_affine=False,
|
| 123 |
+
)
|
| 124 |
+
self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
|
| 125 |
+
self.out_dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 126 |
+
self.scale = 1.0 / math.sqrt(3.0 * self.head_dim)
|
| 127 |
+
|
| 128 |
+
positions = (
|
| 129 |
+
torch.arange(config.max_position_embeddings).unsqueeze(1)
|
| 130 |
+
- torch.arange(config.max_position_embeddings).unsqueeze(0)
|
| 131 |
+
)
|
| 132 |
+
buckets = _relative_position_buckets(
|
| 133 |
+
positions,
|
| 134 |
+
config.position_bucket_size,
|
| 135 |
+
config.max_position_embeddings,
|
| 136 |
+
)
|
| 137 |
+
self.register_buffer("position_indices", buckets, persistent=False)
|
| 138 |
+
self.reset_parameters()
|
| 139 |
+
|
| 140 |
+
def reset_parameters(self):
|
| 141 |
+
std = math.sqrt(2.0 / (5.0 * self.hidden_size))
|
| 142 |
+
for layer in (self.qk_proj, self.vg_proj, self.out_proj):
|
| 143 |
+
nn.init.trunc_normal_(
|
| 144 |
+
layer.weight, mean=0.0, std=std, a=-2 * std, b=2 * std
|
| 145 |
+
)
|
| 146 |
+
if layer.bias is not None:
|
| 147 |
+
nn.init.zeros_(layer.bias)
|
| 148 |
+
|
| 149 |
+
def forward(
|
| 150 |
+
self,
|
| 151 |
+
hidden_states: torch.Tensor,
|
| 152 |
+
blocked_mask: torch.Tensor,
|
| 153 |
+
relative_embeddings: torch.Tensor,
|
| 154 |
+
) -> torch.Tensor:
|
| 155 |
+
batch_size, seq_len, _ = hidden_states.shape
|
| 156 |
+
x = self.pre_norm(hidden_states)
|
| 157 |
+
|
| 158 |
+
query, key = self.qk_proj(x).chunk(2, dim=-1)
|
| 159 |
+
value, gate = self.vg_proj(x).chunk(2, dim=-1)
|
| 160 |
+
gate = F.gelu(gate)
|
| 161 |
+
|
| 162 |
+
query = query.view(batch_size, seq_len, self.num_heads, self.head_dim)
|
| 163 |
+
key = key.view(batch_size, seq_len, self.num_heads, self.head_dim)
|
| 164 |
+
value = value.view(batch_size, seq_len, self.num_heads, self.head_dim)
|
| 165 |
+
query = query.permute(0, 2, 1, 3)
|
| 166 |
+
key = key.permute(0, 2, 1, 3)
|
| 167 |
+
value = value.permute(0, 2, 1, 3)
|
| 168 |
+
|
| 169 |
+
scores = torch.matmul(query, key.transpose(-1, -2)) * self.scale
|
| 170 |
+
|
| 171 |
+
rel_qk = self.qk_proj(self.dropout(relative_embeddings))
|
| 172 |
+
rel_q, rel_k = rel_qk.chunk(2, dim=-1)
|
| 173 |
+
indices = self.position_indices[:seq_len, :seq_len]
|
| 174 |
+
rel_q = F.embedding(indices, rel_q).view(
|
| 175 |
+
seq_len, seq_len, self.num_heads, self.head_dim
|
| 176 |
+
)
|
| 177 |
+
rel_k = F.embedding(indices, rel_k).view(
|
| 178 |
+
seq_len, seq_len, self.num_heads, self.head_dim
|
| 179 |
+
)
|
| 180 |
+
|
| 181 |
+
scores = scores + torch.einsum(
|
| 182 |
+
"bhqd,qkhd->bhqk", query, rel_k * self.scale
|
| 183 |
+
)
|
| 184 |
+
scores = scores + torch.einsum(
|
| 185 |
+
"bhkd,qkhd->bhqk", key * self.scale, rel_q
|
| 186 |
+
)
|
| 187 |
+
|
| 188 |
+
scores = scores.masked_fill(blocked_mask, torch.finfo(scores.dtype).min)
|
| 189 |
+
probs = torch.softmax(scores.float(), dim=-1).to(scores.dtype)
|
| 190 |
+
probs = self.dropout(probs)
|
| 191 |
+
|
| 192 |
+
context = torch.matmul(probs, value)
|
| 193 |
+
context = context.permute(0, 2, 1, 3).contiguous().view(
|
| 194 |
+
batch_size, seq_len, self.hidden_size
|
| 195 |
+
)
|
| 196 |
+
context = context * gate
|
| 197 |
+
context = self.post_norm(context)
|
| 198 |
+
context = self.out_proj(context)
|
| 199 |
+
return self.out_dropout(context)
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
class GPTBertFeedForward(nn.Module):
|
| 203 |
+
def __init__(self, config: GPTBertConfig, layer_index: int):
|
| 204 |
+
super().__init__()
|
| 205 |
+
self.norm1 = nn.LayerNorm(
|
| 206 |
+
config.hidden_size,
|
| 207 |
+
eps=config.layer_norm_eps,
|
| 208 |
+
elementwise_affine=False,
|
| 209 |
+
)
|
| 210 |
+
self.fc1 = nn.Linear(
|
| 211 |
+
config.hidden_size,
|
| 212 |
+
2 * config.intermediate_size,
|
| 213 |
+
bias=False,
|
| 214 |
+
)
|
| 215 |
+
self.act = GeGLU()
|
| 216 |
+
self.norm2 = nn.LayerNorm(
|
| 217 |
+
config.intermediate_size,
|
| 218 |
+
eps=config.layer_norm_eps,
|
| 219 |
+
elementwise_affine=False,
|
| 220 |
+
)
|
| 221 |
+
self.fc2 = nn.Linear(
|
| 222 |
+
config.intermediate_size,
|
| 223 |
+
config.hidden_size,
|
| 224 |
+
bias=False,
|
| 225 |
+
)
|
| 226 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
| 227 |
+
self.reset_parameters(layer_index)
|
| 228 |
+
|
| 229 |
+
def reset_parameters(self, layer_index: int):
|
| 230 |
+
std = math.sqrt(2.0 / (5.0 * self.fc2.out_features))
|
| 231 |
+
nn.init.trunc_normal_(self.fc1.weight, mean=0.0, std=std, a=-2 * std, b=2 * std)
|
| 232 |
+
nn.init.trunc_normal_(self.fc2.weight, mean=0.0, std=std, a=-2 * std, b=2 * std)
|
| 233 |
+
scale = math.sqrt(1.0 / (2.0 * (1 + layer_index)))
|
| 234 |
+
with torch.no_grad():
|
| 235 |
+
self.fc1.weight.mul_(scale)
|
| 236 |
+
self.fc2.weight.mul_(scale)
|
| 237 |
+
|
| 238 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 239 |
+
x = self.norm1(hidden_states)
|
| 240 |
+
x = self.fc1(x)
|
| 241 |
+
x = self.act(x)
|
| 242 |
+
x = self.norm2(x)
|
| 243 |
+
x = self.fc2(x)
|
| 244 |
+
return self.dropout(x)
|
| 245 |
+
|
| 246 |
+
|
| 247 |
+
class GPTBertLayer(nn.Module):
|
| 248 |
+
def __init__(self, config: GPTBertConfig, layer_index: int):
|
| 249 |
+
super().__init__()
|
| 250 |
+
self.attention = GPTBertAttention(config)
|
| 251 |
+
self.ffn = GPTBertFeedForward(config, layer_index)
|
| 252 |
+
|
| 253 |
+
def forward(
|
| 254 |
+
self,
|
| 255 |
+
hidden_states: torch.Tensor,
|
| 256 |
+
blocked_mask: torch.Tensor,
|
| 257 |
+
relative_embeddings: torch.Tensor,
|
| 258 |
+
) -> torch.Tensor:
|
| 259 |
+
hidden_states = hidden_states + self.attention(
|
| 260 |
+
hidden_states, blocked_mask, relative_embeddings
|
| 261 |
+
)
|
| 262 |
+
hidden_states = hidden_states + self.ffn(hidden_states)
|
| 263 |
+
return hidden_states
|
| 264 |
+
|
| 265 |
+
|
| 266 |
+
class GPTBertPreTrainedModel(PreTrainedModel):
|
| 267 |
+
config_class = GPTBertConfig
|
| 268 |
+
base_model_prefix = "gpt_bert"
|
| 269 |
+
supports_gradient_checkpointing = False
|
| 270 |
+
|
| 271 |
+
def _init_weights(self, module):
|
| 272 |
+
# Components initialize themselves to match the LTG/GPT-BERT recipe.
|
| 273 |
+
return
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
class GPTBertModel(GPTBertPreTrainedModel):
|
| 277 |
+
def __init__(self, config: GPTBertConfig):
|
| 278 |
+
super().__init__(config)
|
| 279 |
+
self.embeddings = GPTBertEmbeddings(config)
|
| 280 |
+
self.layers = nn.ModuleList(
|
| 281 |
+
[GPTBertLayer(config, i) for i in range(config.num_hidden_layers)]
|
| 282 |
+
)
|
| 283 |
+
self.post_init()
|
| 284 |
+
|
| 285 |
+
def get_input_embeddings(self):
|
| 286 |
+
return self.embeddings.word_embeddings
|
| 287 |
+
|
| 288 |
+
def set_input_embeddings(self, value):
|
| 289 |
+
self.embeddings.word_embeddings = value
|
| 290 |
+
|
| 291 |
+
def _build_blocked_mask(
|
| 292 |
+
self,
|
| 293 |
+
input_ids: torch.Tensor,
|
| 294 |
+
attention_mask: Optional[torch.Tensor],
|
| 295 |
+
is_causal: bool,
|
| 296 |
+
) -> torch.Tensor:
|
| 297 |
+
batch_size, seq_len = input_ids.shape
|
| 298 |
+
if attention_mask is None:
|
| 299 |
+
attention_mask = torch.ones(
|
| 300 |
+
batch_size, seq_len, device=input_ids.device, dtype=torch.long
|
| 301 |
+
)
|
| 302 |
+
key_padding = attention_mask.eq(0)[:, None, None, :]
|
| 303 |
+
if is_causal:
|
| 304 |
+
causal = torch.ones(
|
| 305 |
+
seq_len, seq_len, device=input_ids.device, dtype=torch.bool
|
| 306 |
+
).triu(diagonal=1)[None, None, :, :]
|
| 307 |
+
return key_padding | causal
|
| 308 |
+
return key_padding.expand(batch_size, 1, seq_len, seq_len)
|
| 309 |
+
|
| 310 |
+
def forward(
|
| 311 |
+
self,
|
| 312 |
+
input_ids: torch.Tensor,
|
| 313 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 314 |
+
is_causal: bool = False,
|
| 315 |
+
return_dict: bool = True,
|
| 316 |
+
**kwargs,
|
| 317 |
+
):
|
| 318 |
+
blocked_mask = self._build_blocked_mask(
|
| 319 |
+
input_ids, attention_mask, is_causal=is_causal
|
| 320 |
+
)
|
| 321 |
+
hidden_states, relative_embeddings = self.embeddings(input_ids)
|
| 322 |
+
for layer in self.layers:
|
| 323 |
+
hidden_states = layer(
|
| 324 |
+
hidden_states, blocked_mask, relative_embeddings
|
| 325 |
+
)
|
| 326 |
+
if not return_dict:
|
| 327 |
+
return (hidden_states,)
|
| 328 |
+
return BaseModelOutput(last_hidden_state=hidden_states)
|
| 329 |
+
|
| 330 |
+
|
| 331 |
+
class GPTBertLMHead(nn.Module):
|
| 332 |
+
def __init__(self, config: GPTBertConfig, embedding_weight: nn.Parameter):
|
| 333 |
+
super().__init__()
|
| 334 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
| 335 |
+
self.activation = nn.GELU()
|
| 336 |
+
self.norm = nn.LayerNorm(
|
| 337 |
+
config.hidden_size,
|
| 338 |
+
eps=config.layer_norm_eps,
|
| 339 |
+
elementwise_affine=False,
|
| 340 |
+
)
|
| 341 |
+
self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
| 342 |
+
self.decoder.weight = embedding_weight
|
| 343 |
+
self.bias = nn.Parameter(torch.zeros(config.vocab_size))
|
| 344 |
+
self.reset_parameters(config.hidden_size)
|
| 345 |
+
|
| 346 |
+
def reset_parameters(self, hidden_size: int):
|
| 347 |
+
std = math.sqrt(2.0 / (5.0 * hidden_size))
|
| 348 |
+
nn.init.trunc_normal_(
|
| 349 |
+
self.dense.weight, mean=0.0, std=std, a=-2 * std, b=2 * std
|
| 350 |
+
)
|
| 351 |
+
nn.init.zeros_(self.dense.bias)
|
| 352 |
+
|
| 353 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 354 |
+
x = self.dense(hidden_states)
|
| 355 |
+
x = self.activation(x)
|
| 356 |
+
x = self.norm(x)
|
| 357 |
+
return self.decoder(x) + self.bias
|
| 358 |
+
|
| 359 |
+
|
| 360 |
+
class GPTBertForMaskedLM(GPTBertPreTrainedModel):
|
| 361 |
+
_tied_weights_keys = ["lm_head.decoder.weight"]
|
| 362 |
+
|
| 363 |
+
def __init__(self, config: GPTBertConfig):
|
| 364 |
+
super().__init__(config)
|
| 365 |
+
self.gpt_bert = GPTBertModel(config)
|
| 366 |
+
self.lm_head = GPTBertLMHead(
|
| 367 |
+
config, self.gpt_bert.embeddings.word_embeddings.weight
|
| 368 |
+
)
|
| 369 |
+
self.post_init()
|
| 370 |
+
|
| 371 |
+
def get_input_embeddings(self):
|
| 372 |
+
return self.gpt_bert.get_input_embeddings()
|
| 373 |
+
|
| 374 |
+
def set_input_embeddings(self, value):
|
| 375 |
+
self.gpt_bert.set_input_embeddings(value)
|
| 376 |
+
self.lm_head.decoder.weight = value.weight
|
| 377 |
+
|
| 378 |
+
def get_output_embeddings(self):
|
| 379 |
+
return self.lm_head.decoder
|
| 380 |
+
|
| 381 |
+
def set_output_embeddings(self, new_embeddings):
|
| 382 |
+
self.lm_head.decoder = new_embeddings
|
| 383 |
+
|
| 384 |
+
def _selected_stats(
|
| 385 |
+
self,
|
| 386 |
+
logits: torch.Tensor,
|
| 387 |
+
labels: torch.Tensor,
|
| 388 |
+
):
|
| 389 |
+
ce_loss = F.cross_entropy(logits.float(), labels)
|
| 390 |
+
z_loss = torch.logsumexp(logits.float(), dim=-1).pow(2).mean()
|
| 391 |
+
accuracy = (logits.argmax(dim=-1) == labels).float().mean()
|
| 392 |
+
return ce_loss, z_loss, accuracy
|
| 393 |
+
|
| 394 |
+
def forward(
|
| 395 |
+
self,
|
| 396 |
+
input_ids: torch.Tensor,
|
| 397 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 398 |
+
labels: Optional[torch.Tensor] = None,
|
| 399 |
+
mode: str = "mntp",
|
| 400 |
+
z_loss_weight: float = 0.0,
|
| 401 |
+
return_dict: bool = True,
|
| 402 |
+
**kwargs,
|
| 403 |
+
):
|
| 404 |
+
if mode not in {"mntp", "masked", "causal"}:
|
| 405 |
+
raise ValueError(f"Unsupported mode: {mode}")
|
| 406 |
+
is_causal = mode == "causal"
|
| 407 |
+
hidden = self.gpt_bert(
|
| 408 |
+
input_ids=input_ids,
|
| 409 |
+
attention_mask=attention_mask,
|
| 410 |
+
is_causal=is_causal,
|
| 411 |
+
return_dict=True,
|
| 412 |
+
).last_hidden_state
|
| 413 |
+
|
| 414 |
+
if labels is not None and mode in {"mntp", "masked"}:
|
| 415 |
+
# MNTP: the hidden state at position i-1 predicts a masked token at i.
|
| 416 |
+
valid = labels[:, 1:].ne(-100)
|
| 417 |
+
selected_hidden = hidden[:, :-1][valid]
|
| 418 |
+
selected_labels = labels[:, 1:][valid]
|
| 419 |
+
if selected_labels.numel() == 0:
|
| 420 |
+
raise RuntimeError("MNTP batch contains no prediction targets")
|
| 421 |
+
selected_logits = self.lm_head(selected_hidden)
|
| 422 |
+
ce_loss, z_loss, accuracy = self._selected_stats(
|
| 423 |
+
selected_logits, selected_labels
|
| 424 |
+
)
|
| 425 |
+
loss = ce_loss + z_loss_weight * z_loss
|
| 426 |
+
return GPTBertTrainingOutput(
|
| 427 |
+
loss=loss,
|
| 428 |
+
logits=None,
|
| 429 |
+
ce_loss=ce_loss.detach(),
|
| 430 |
+
z_loss=z_loss.detach(),
|
| 431 |
+
accuracy=accuracy.detach(),
|
| 432 |
+
num_tokens=torch.tensor(
|
| 433 |
+
selected_labels.numel(), device=input_ids.device
|
| 434 |
+
),
|
| 435 |
+
)
|
| 436 |
+
|
| 437 |
+
if labels is not None and mode == "causal":
|
| 438 |
+
# Training input is [BOS] + tokens[:-1]; labels are tokens.
|
| 439 |
+
logits = self.lm_head(hidden)
|
| 440 |
+
valid = labels.ne(-100)
|
| 441 |
+
selected_logits = logits[valid]
|
| 442 |
+
selected_labels = labels[valid]
|
| 443 |
+
ce_loss, z_loss, accuracy = self._selected_stats(
|
| 444 |
+
selected_logits, selected_labels
|
| 445 |
+
)
|
| 446 |
+
loss = ce_loss + z_loss_weight * z_loss
|
| 447 |
+
return GPTBertTrainingOutput(
|
| 448 |
+
loss=loss,
|
| 449 |
+
logits=None,
|
| 450 |
+
ce_loss=ce_loss.detach(),
|
| 451 |
+
z_loss=z_loss.detach(),
|
| 452 |
+
accuracy=accuracy.detach(),
|
| 453 |
+
num_tokens=torch.tensor(
|
| 454 |
+
selected_labels.numel(), device=input_ids.device
|
| 455 |
+
),
|
| 456 |
+
)
|
| 457 |
+
|
| 458 |
+
raw_logits = self.lm_head(hidden)
|
| 459 |
+
# The BabyLM MNTP backend selects target_position - 1 itself.
|
| 460 |
+
if not return_dict:
|
| 461 |
+
return (raw_logits,)
|
| 462 |
+
return MaskedLMOutput(logits=raw_logits)
|
| 463 |
+
|
| 464 |
+
|
| 465 |
+
class GPTBertForCausalLM(GPTBertForMaskedLM):
|
| 466 |
+
def forward(
|
| 467 |
+
self,
|
| 468 |
+
input_ids: torch.Tensor,
|
| 469 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 470 |
+
labels: Optional[torch.Tensor] = None,
|
| 471 |
+
return_dict: bool = True,
|
| 472 |
+
**kwargs,
|
| 473 |
+
):
|
| 474 |
+
hidden = self.gpt_bert(
|
| 475 |
+
input_ids=input_ids,
|
| 476 |
+
attention_mask=attention_mask,
|
| 477 |
+
is_causal=True,
|
| 478 |
+
return_dict=True,
|
| 479 |
+
).last_hidden_state
|
| 480 |
+
logits = self.lm_head(hidden)
|
| 481 |
+
loss = None
|
| 482 |
+
if labels is not None:
|
| 483 |
+
shift_logits = logits[:, :-1].contiguous()
|
| 484 |
+
shift_labels = labels[:, 1:].contiguous()
|
| 485 |
+
loss = F.cross_entropy(
|
| 486 |
+
shift_logits.view(-1, shift_logits.size(-1)).float(),
|
| 487 |
+
shift_labels.view(-1),
|
| 488 |
+
ignore_index=-100,
|
| 489 |
+
)
|
| 490 |
+
if not return_dict:
|
| 491 |
+
return (loss, logits) if loss is not None else (logits,)
|
| 492 |
+
return CausalLMOutput(loss=loss, logits=logits)
|
special_tokens_map.json
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"bos_token": {
|
| 3 |
+
"content": "<s>",
|
| 4 |
+
"lstrip": false,
|
| 5 |
+
"normalized": false,
|
| 6 |
+
"rstrip": false,
|
| 7 |
+
"single_word": false
|
| 8 |
+
},
|
| 9 |
+
"eos_token": {
|
| 10 |
+
"content": "</s>",
|
| 11 |
+
"lstrip": false,
|
| 12 |
+
"normalized": false,
|
| 13 |
+
"rstrip": false,
|
| 14 |
+
"single_word": false
|
| 15 |
+
},
|
| 16 |
+
"mask_token": {
|
| 17 |
+
"content": "<mask>",
|
| 18 |
+
"lstrip": false,
|
| 19 |
+
"normalized": false,
|
| 20 |
+
"rstrip": false,
|
| 21 |
+
"single_word": false
|
| 22 |
+
},
|
| 23 |
+
"pad_token": {
|
| 24 |
+
"content": "<pad>",
|
| 25 |
+
"lstrip": false,
|
| 26 |
+
"normalized": false,
|
| 27 |
+
"rstrip": false,
|
| 28 |
+
"single_word": false
|
| 29 |
+
},
|
| 30 |
+
"unk_token": {
|
| 31 |
+
"content": "<unk>",
|
| 32 |
+
"lstrip": false,
|
| 33 |
+
"normalized": false,
|
| 34 |
+
"rstrip": false,
|
| 35 |
+
"single_word": false
|
| 36 |
+
}
|
| 37 |
+
}
|
tokenizer.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
tokenizer_config.json
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"added_tokens_decoder": {
|
| 3 |
+
"0": {
|
| 4 |
+
"content": "<s>",
|
| 5 |
+
"lstrip": false,
|
| 6 |
+
"normalized": false,
|
| 7 |
+
"rstrip": false,
|
| 8 |
+
"single_word": false,
|
| 9 |
+
"special": true
|
| 10 |
+
},
|
| 11 |
+
"1": {
|
| 12 |
+
"content": "<pad>",
|
| 13 |
+
"lstrip": false,
|
| 14 |
+
"normalized": false,
|
| 15 |
+
"rstrip": false,
|
| 16 |
+
"single_word": false,
|
| 17 |
+
"special": true
|
| 18 |
+
},
|
| 19 |
+
"2": {
|
| 20 |
+
"content": "</s>",
|
| 21 |
+
"lstrip": false,
|
| 22 |
+
"normalized": false,
|
| 23 |
+
"rstrip": false,
|
| 24 |
+
"single_word": false,
|
| 25 |
+
"special": true
|
| 26 |
+
},
|
| 27 |
+
"3": {
|
| 28 |
+
"content": "<unk>",
|
| 29 |
+
"lstrip": false,
|
| 30 |
+
"normalized": false,
|
| 31 |
+
"rstrip": false,
|
| 32 |
+
"single_word": false,
|
| 33 |
+
"special": true
|
| 34 |
+
},
|
| 35 |
+
"4": {
|
| 36 |
+
"content": "<mask>",
|
| 37 |
+
"lstrip": false,
|
| 38 |
+
"normalized": false,
|
| 39 |
+
"rstrip": false,
|
| 40 |
+
"single_word": false,
|
| 41 |
+
"special": true
|
| 42 |
+
}
|
| 43 |
+
},
|
| 44 |
+
"backend": "tokenizers",
|
| 45 |
+
"bos_token": "<s>",
|
| 46 |
+
"clean_up_tokenization_spaces": false,
|
| 47 |
+
"eos_token": "</s>",
|
| 48 |
+
"extra_special_tokens": {},
|
| 49 |
+
"mask_token": "<mask>",
|
| 50 |
+
"model_max_length": 512,
|
| 51 |
+
"pad_token": "<pad>",
|
| 52 |
+
"tokenizer_class": "PreTrainedTokenizerFast",
|
| 53 |
+
"unk_token": "<unk>"
|
| 54 |
+
}
|