Spaces:
Running on Zero
Running on Zero
Delete files custom_model/* with huggingface_hub
Browse files
custom_model/__init__.py
DELETED
|
File without changes
|
custom_model/configuration_tiny_gpt.py
DELETED
|
@@ -1,56 +0,0 @@
|
|
| 1 |
-
from transformers import PretrainedConfig
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
class TinyGPTConfig(PretrainedConfig):
|
| 5 |
-
model_type = "slm"
|
| 6 |
-
|
| 7 |
-
def __init__(
|
| 8 |
-
self,
|
| 9 |
-
vocab_size=32768,
|
| 10 |
-
ctx_len=512,
|
| 11 |
-
n_layer=4,
|
| 12 |
-
n_head=4,
|
| 13 |
-
n_embd=384,
|
| 14 |
-
dropout=0.0,
|
| 15 |
-
attention_backend="torch",
|
| 16 |
-
torch_fallback=False,
|
| 17 |
-
rope_base=10000.0,
|
| 18 |
-
positional_encoding="rope",
|
| 19 |
-
pad_token_id=None,
|
| 20 |
-
bos_token_id=None,
|
| 21 |
-
eos_token_id=None,
|
| 22 |
-
sep_token_id=None,
|
| 23 |
-
unk_token_id=None,
|
| 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 |
-
sep_token_id=sep_token_id,
|
| 31 |
-
unk_token_id=unk_token_id,
|
| 32 |
-
**kwargs,
|
| 33 |
-
)
|
| 34 |
-
|
| 35 |
-
if attention_backend not in ("sage", "torch", "flash2", "flash3"):
|
| 36 |
-
raise ValueError("attention_backend must be sage, torch, flash2 or flash3")
|
| 37 |
-
|
| 38 |
-
self.vocab_size = int(vocab_size)
|
| 39 |
-
self.ctx_len = int(ctx_len)
|
| 40 |
-
self.max_position_embeddings = int(ctx_len)
|
| 41 |
-
|
| 42 |
-
self.n_layer = int(n_layer)
|
| 43 |
-
self.n_head = int(n_head)
|
| 44 |
-
self.n_embd = int(n_embd)
|
| 45 |
-
|
| 46 |
-
self.num_hidden_layers = int(n_layer)
|
| 47 |
-
self.num_attention_heads = int(n_head)
|
| 48 |
-
self.hidden_size = int(n_embd)
|
| 49 |
-
|
| 50 |
-
self.dropout = float(dropout)
|
| 51 |
-
self.attention_backend = str(attention_backend)
|
| 52 |
-
self.available_attention_backends = ["sage", "torch", "flash2", "flash3"]
|
| 53 |
-
self.torch_fallback = bool(torch_fallback)
|
| 54 |
-
|
| 55 |
-
self.rope_base = float(rope_base)
|
| 56 |
-
self.positional_encoding = str(positional_encoding)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
custom_model/modeling_tiny_gpt.py
DELETED
|
@@ -1,520 +0,0 @@
|
|
| 1 |
-
import importlib
|
| 2 |
-
import math
|
| 3 |
-
|
| 4 |
-
import torch
|
| 5 |
-
import torch.nn as nn
|
| 6 |
-
import torch.nn.functional as F
|
| 7 |
-
from transformers import PreTrainedModel
|
| 8 |
-
from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
|
| 9 |
-
|
| 10 |
-
from .configuration_tiny_gpt import TinyGPTConfig
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
_FLASH2_KERNEL = None
|
| 14 |
-
_FLASH3_KERNEL = None
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
def _get_flash2_kernel():
|
| 18 |
-
global _FLASH2_KERNEL
|
| 19 |
-
|
| 20 |
-
if _FLASH2_KERNEL is None:
|
| 21 |
-
kernels = importlib.import_module("kernels")
|
| 22 |
-
_FLASH2_KERNEL = kernels.get_kernel("kernels-community/flash-attn2", version=1)
|
| 23 |
-
|
| 24 |
-
return _FLASH2_KERNEL
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
def _get_flash3_kernel():
|
| 28 |
-
global _FLASH3_KERNEL
|
| 29 |
-
|
| 30 |
-
if _FLASH3_KERNEL is None:
|
| 31 |
-
kernels = importlib.import_module("kernels")
|
| 32 |
-
_FLASH3_KERNEL = kernels.get_kernel("kernels-community/flash-attn3", version=1)
|
| 33 |
-
|
| 34 |
-
return _FLASH3_KERNEL
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
def _get_sageattn():
|
| 38 |
-
module = importlib.import_module("sageattention")
|
| 39 |
-
return module.sageattn
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
def rotate_half(x):
|
| 43 |
-
x_even = x[..., ::2]
|
| 44 |
-
x_odd = x[..., 1::2]
|
| 45 |
-
x_rot = torch.stack((-x_odd, x_even), dim=-1)
|
| 46 |
-
return x_rot.flatten(start_dim=-2)
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
def apply_rope(x, cos, sin):
|
| 50 |
-
return (x * cos) + (rotate_half(x) * sin)
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
class RotaryEmbedding(nn.Module):
|
| 54 |
-
def __init__(self, dim, max_position_embeddings, base=10000.0):
|
| 55 |
-
super().__init__()
|
| 56 |
-
|
| 57 |
-
if dim % 2 != 0:
|
| 58 |
-
raise ValueError(f"RoPE dim must be even, got {dim}")
|
| 59 |
-
|
| 60 |
-
self.dim = int(dim)
|
| 61 |
-
self.max_position_embeddings = int(max_position_embeddings)
|
| 62 |
-
self.base = float(base)
|
| 63 |
-
|
| 64 |
-
inv_freq = 1.0 / (
|
| 65 |
-
self.base
|
| 66 |
-
** (
|
| 67 |
-
torch.arange(
|
| 68 |
-
0,
|
| 69 |
-
self.dim,
|
| 70 |
-
2,
|
| 71 |
-
dtype=torch.float32,
|
| 72 |
-
)
|
| 73 |
-
/ self.dim
|
| 74 |
-
)
|
| 75 |
-
)
|
| 76 |
-
|
| 77 |
-
self.register_buffer(
|
| 78 |
-
"inv_freq",
|
| 79 |
-
inv_freq,
|
| 80 |
-
persistent=False,
|
| 81 |
-
)
|
| 82 |
-
|
| 83 |
-
self._cos_cached = None
|
| 84 |
-
self._sin_cached = None
|
| 85 |
-
self._seq_len_cached = 0
|
| 86 |
-
self._device_cached = None
|
| 87 |
-
self._dtype_cached = None
|
| 88 |
-
|
| 89 |
-
def _build_cache(self, seq_len, device, dtype):
|
| 90 |
-
t = torch.arange(
|
| 91 |
-
seq_len,
|
| 92 |
-
device=device,
|
| 93 |
-
dtype=torch.float32,
|
| 94 |
-
)
|
| 95 |
-
|
| 96 |
-
freqs = torch.einsum(
|
| 97 |
-
"i,j->ij",
|
| 98 |
-
t,
|
| 99 |
-
self.inv_freq.to(device=device, dtype=torch.float32),
|
| 100 |
-
)
|
| 101 |
-
|
| 102 |
-
emb = torch.repeat_interleave(freqs, repeats=2, dim=-1)
|
| 103 |
-
|
| 104 |
-
cos = emb.cos().to(dtype=dtype).view(1, 1, seq_len, self.dim)
|
| 105 |
-
sin = emb.sin().to(dtype=dtype).view(1, 1, seq_len, self.dim)
|
| 106 |
-
|
| 107 |
-
self._cos_cached = cos
|
| 108 |
-
self._sin_cached = sin
|
| 109 |
-
self._seq_len_cached = int(seq_len)
|
| 110 |
-
self._device_cached = device
|
| 111 |
-
self._dtype_cached = dtype
|
| 112 |
-
|
| 113 |
-
def forward(self, seq_len, device, dtype):
|
| 114 |
-
if (
|
| 115 |
-
self._cos_cached is None
|
| 116 |
-
or self._sin_cached is None
|
| 117 |
-
or self._seq_len_cached < seq_len
|
| 118 |
-
or self._device_cached != device
|
| 119 |
-
or self._dtype_cached != dtype
|
| 120 |
-
):
|
| 121 |
-
self._build_cache(
|
| 122 |
-
seq_len=seq_len,
|
| 123 |
-
device=device,
|
| 124 |
-
dtype=dtype,
|
| 125 |
-
)
|
| 126 |
-
|
| 127 |
-
return (
|
| 128 |
-
self._cos_cached[:, :, :seq_len, :],
|
| 129 |
-
self._sin_cached[:, :, :seq_len, :],
|
| 130 |
-
)
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
class CausalSelfAttention(nn.Module):
|
| 134 |
-
def __init__(self, config: TinyGPTConfig):
|
| 135 |
-
super().__init__()
|
| 136 |
-
|
| 137 |
-
if config.n_embd % config.n_head != 0:
|
| 138 |
-
raise ValueError("n_embd must be divisible by n_head")
|
| 139 |
-
|
| 140 |
-
self.n_head = int(config.n_head)
|
| 141 |
-
self.head_dim = int(config.n_embd // config.n_head)
|
| 142 |
-
self.attention_backend = str(getattr(config, "attention_backend", "torch"))
|
| 143 |
-
self.torch_fallback = bool(getattr(config, "torch_fallback", False))
|
| 144 |
-
self.dropout_p = float(config.dropout)
|
| 145 |
-
|
| 146 |
-
if self.head_dim % 2 != 0:
|
| 147 |
-
raise ValueError(f"RoPE requires even head_dim, got {self.head_dim}")
|
| 148 |
-
|
| 149 |
-
if self.attention_backend not in ("sage", "torch", "flash2", "flash3"):
|
| 150 |
-
raise ValueError("attention_backend must be sage, torch, flash2 or flash3")
|
| 151 |
-
|
| 152 |
-
if self.attention_backend == "sage" and self.head_dim not in (64, 96, 128):
|
| 153 |
-
raise ValueError(f"SageAttention requires head_dim in [64, 96, 128], got {self.head_dim}")
|
| 154 |
-
|
| 155 |
-
if self.attention_backend == "sage" and self.dropout_p != 0.0:
|
| 156 |
-
raise ValueError("SageAttention requires dropout=0.0")
|
| 157 |
-
|
| 158 |
-
if self.attention_backend == "flash3" and self.dropout_p != 0.0:
|
| 159 |
-
raise ValueError("FlashAttention3 requires dropout=0.0")
|
| 160 |
-
|
| 161 |
-
if self.attention_backend in ("flash2", "flash3") and self.head_dim % 8 != 0:
|
| 162 |
-
raise ValueError(f"FlashAttention requires head_dim multiple of 8, got {self.head_dim}")
|
| 163 |
-
|
| 164 |
-
self.qkv = nn.Linear(config.n_embd, 3 * config.n_embd, bias=False)
|
| 165 |
-
self.proj = nn.Linear(config.n_embd, config.n_embd, bias=False)
|
| 166 |
-
self.dropout = nn.Dropout(config.dropout)
|
| 167 |
-
|
| 168 |
-
self.rope = RotaryEmbedding(
|
| 169 |
-
dim=self.head_dim,
|
| 170 |
-
max_position_embeddings=config.ctx_len,
|
| 171 |
-
base=float(getattr(config, "rope_base", 10000.0)),
|
| 172 |
-
)
|
| 173 |
-
|
| 174 |
-
mask = torch.tril(torch.ones(config.ctx_len, config.ctx_len, dtype=torch.bool))
|
| 175 |
-
self.register_buffer(
|
| 176 |
-
"mask",
|
| 177 |
-
mask.view(1, 1, config.ctx_len, config.ctx_len),
|
| 178 |
-
persistent=False,
|
| 179 |
-
)
|
| 180 |
-
|
| 181 |
-
self.sageattn = None
|
| 182 |
-
self.flash_kernel = None
|
| 183 |
-
|
| 184 |
-
if self.attention_backend == "sage":
|
| 185 |
-
try:
|
| 186 |
-
self.sageattn = _get_sageattn()
|
| 187 |
-
except Exception:
|
| 188 |
-
if self.torch_fallback:
|
| 189 |
-
self.attention_backend = "torch"
|
| 190 |
-
else:
|
| 191 |
-
raise
|
| 192 |
-
|
| 193 |
-
if self.attention_backend == "flash2":
|
| 194 |
-
try:
|
| 195 |
-
self.flash_kernel = _get_flash2_kernel()
|
| 196 |
-
except Exception:
|
| 197 |
-
if self.torch_fallback:
|
| 198 |
-
self.attention_backend = "torch"
|
| 199 |
-
else:
|
| 200 |
-
raise
|
| 201 |
-
|
| 202 |
-
if self.attention_backend == "flash3":
|
| 203 |
-
try:
|
| 204 |
-
self.flash_kernel = _get_flash3_kernel()
|
| 205 |
-
except Exception:
|
| 206 |
-
if self.torch_fallback:
|
| 207 |
-
self.attention_backend = "torch"
|
| 208 |
-
else:
|
| 209 |
-
raise
|
| 210 |
-
|
| 211 |
-
def _torch_attention(self, q, k, v, t):
|
| 212 |
-
scores = (q @ k.transpose(-2, -1)) / math.sqrt(self.head_dim)
|
| 213 |
-
scores = scores.masked_fill(self.mask[:, :, :t, :t] == 0, float("-inf"))
|
| 214 |
-
|
| 215 |
-
att = F.softmax(scores.float(), dim=-1).to(q.dtype)
|
| 216 |
-
att = self.dropout(att)
|
| 217 |
-
|
| 218 |
-
return att @ v
|
| 219 |
-
|
| 220 |
-
def _sage_attention(self, q, k, v):
|
| 221 |
-
if self.sageattn is None or not q.is_cuda:
|
| 222 |
-
if self.torch_fallback:
|
| 223 |
-
return None
|
| 224 |
-
raise RuntimeError("SageAttention requires CUDA + sageattention")
|
| 225 |
-
|
| 226 |
-
return self.sageattn(
|
| 227 |
-
q.contiguous(),
|
| 228 |
-
k.contiguous(),
|
| 229 |
-
v.contiguous(),
|
| 230 |
-
tensor_layout="HND",
|
| 231 |
-
is_causal=True,
|
| 232 |
-
)
|
| 233 |
-
|
| 234 |
-
def _flash2_attention(self, q, k, v):
|
| 235 |
-
if self.flash_kernel is None or not q.is_cuda:
|
| 236 |
-
if self.torch_fallback:
|
| 237 |
-
return None
|
| 238 |
-
raise RuntimeError("FlashAttention2 requires CUDA + kernels")
|
| 239 |
-
|
| 240 |
-
q = q.transpose(1, 2).contiguous()
|
| 241 |
-
k = k.transpose(1, 2).contiguous()
|
| 242 |
-
v = v.transpose(1, 2).contiguous()
|
| 243 |
-
|
| 244 |
-
dropout_p = self.dropout_p if self.training else 0.0
|
| 245 |
-
|
| 246 |
-
y = self.flash_kernel.flash_attn_func(
|
| 247 |
-
q,
|
| 248 |
-
k,
|
| 249 |
-
v,
|
| 250 |
-
dropout_p=dropout_p,
|
| 251 |
-
causal=True,
|
| 252 |
-
)
|
| 253 |
-
|
| 254 |
-
return y.transpose(1, 2).contiguous()
|
| 255 |
-
|
| 256 |
-
def _flash3_attention(self, q, k, v):
|
| 257 |
-
if self.flash_kernel is None or not q.is_cuda:
|
| 258 |
-
if self.torch_fallback:
|
| 259 |
-
return None
|
| 260 |
-
raise RuntimeError("FlashAttention3 requires CUDA + kernels")
|
| 261 |
-
|
| 262 |
-
q = q.transpose(1, 2).contiguous()
|
| 263 |
-
k = k.transpose(1, 2).contiguous()
|
| 264 |
-
v = v.transpose(1, 2).contiguous()
|
| 265 |
-
|
| 266 |
-
y = self.flash_kernel.flash_attn_func(
|
| 267 |
-
q,
|
| 268 |
-
k,
|
| 269 |
-
v,
|
| 270 |
-
causal=True,
|
| 271 |
-
)
|
| 272 |
-
|
| 273 |
-
return y.transpose(1, 2).contiguous()
|
| 274 |
-
|
| 275 |
-
def forward(self, x):
|
| 276 |
-
b, t, c = x.shape
|
| 277 |
-
|
| 278 |
-
qkv = self.qkv(x)
|
| 279 |
-
q, k, v = qkv.chunk(3, dim=-1)
|
| 280 |
-
|
| 281 |
-
q = q.view(b, t, self.n_head, self.head_dim).transpose(1, 2).contiguous()
|
| 282 |
-
k = k.view(b, t, self.n_head, self.head_dim).transpose(1, 2).contiguous()
|
| 283 |
-
v = v.view(b, t, self.n_head, self.head_dim).transpose(1, 2).contiguous()
|
| 284 |
-
|
| 285 |
-
cos, sin = self.rope(
|
| 286 |
-
seq_len=t,
|
| 287 |
-
device=q.device,
|
| 288 |
-
dtype=q.dtype,
|
| 289 |
-
)
|
| 290 |
-
|
| 291 |
-
q = apply_rope(q, cos, sin)
|
| 292 |
-
k = apply_rope(k, cos, sin)
|
| 293 |
-
|
| 294 |
-
if self.attention_backend == "sage":
|
| 295 |
-
y = self._sage_attention(q, k, v)
|
| 296 |
-
if y is None:
|
| 297 |
-
y = self._torch_attention(q, k, v, t)
|
| 298 |
-
elif self.attention_backend == "flash2":
|
| 299 |
-
y = self._flash2_attention(q, k, v)
|
| 300 |
-
if y is None:
|
| 301 |
-
y = self._torch_attention(q, k, v, t)
|
| 302 |
-
elif self.attention_backend == "flash3":
|
| 303 |
-
y = self._flash3_attention(q, k, v)
|
| 304 |
-
if y is None:
|
| 305 |
-
y = self._torch_attention(q, k, v, t)
|
| 306 |
-
else:
|
| 307 |
-
y = self._torch_attention(q, k, v, t)
|
| 308 |
-
|
| 309 |
-
y = y.transpose(1, 2).contiguous().view(b, t, c)
|
| 310 |
-
|
| 311 |
-
return self.proj(y)
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
class MLP(nn.Module):
|
| 315 |
-
def __init__(self, config: TinyGPTConfig):
|
| 316 |
-
super().__init__()
|
| 317 |
-
|
| 318 |
-
self.fc = nn.Linear(config.n_embd, 4 * config.n_embd, bias=False)
|
| 319 |
-
self.proj = nn.Linear(4 * config.n_embd, config.n_embd, bias=False)
|
| 320 |
-
self.dropout = nn.Dropout(config.dropout)
|
| 321 |
-
|
| 322 |
-
def forward(self, x):
|
| 323 |
-
x = self.fc(x)
|
| 324 |
-
x = F.gelu(x)
|
| 325 |
-
x = self.proj(x)
|
| 326 |
-
x = self.dropout(x)
|
| 327 |
-
|
| 328 |
-
return x
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
class Block(nn.Module):
|
| 332 |
-
def __init__(self, config: TinyGPTConfig):
|
| 333 |
-
super().__init__()
|
| 334 |
-
|
| 335 |
-
self.ln1 = nn.LayerNorm(config.n_embd)
|
| 336 |
-
self.attn = CausalSelfAttention(config)
|
| 337 |
-
self.ln2 = nn.LayerNorm(config.n_embd)
|
| 338 |
-
self.mlp = MLP(config)
|
| 339 |
-
|
| 340 |
-
def forward(self, x):
|
| 341 |
-
x = x + self.attn(self.ln1(x))
|
| 342 |
-
x = x + self.mlp(self.ln2(x))
|
| 343 |
-
|
| 344 |
-
return x
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
class TinyGPTPreTrainedModel(PreTrainedModel):
|
| 348 |
-
config_class = TinyGPTConfig
|
| 349 |
-
base_model_prefix = "tiny_gpt"
|
| 350 |
-
supports_gradient_checkpointing = False
|
| 351 |
-
|
| 352 |
-
@staticmethod
|
| 353 |
-
def _tie_or_clone_weights(output_embeddings, input_embeddings):
|
| 354 |
-
output_embeddings.weight = input_embeddings.weight
|
| 355 |
-
if getattr(output_embeddings, "out_features", None) is not None:
|
| 356 |
-
output_embeddings.out_features = input_embeddings.num_embeddings
|
| 357 |
-
|
| 358 |
-
def _init_weights(self, module):
|
| 359 |
-
if isinstance(module, nn.Linear):
|
| 360 |
-
nn.init.normal_(module.weight, mean=0.0, std=0.02)
|
| 361 |
-
if module.bias is not None:
|
| 362 |
-
nn.init.zeros_(module.bias)
|
| 363 |
-
|
| 364 |
-
elif isinstance(module, nn.Embedding):
|
| 365 |
-
nn.init.normal_(module.weight, mean=0.0, std=0.02)
|
| 366 |
-
|
| 367 |
-
|
| 368 |
-
class TinyGPTModel(TinyGPTPreTrainedModel):
|
| 369 |
-
_tied_weights_keys = ["head.weight"]
|
| 370 |
-
|
| 371 |
-
def __init__(self, config: TinyGPTConfig):
|
| 372 |
-
super().__init__(config)
|
| 373 |
-
|
| 374 |
-
self.tok_emb = nn.Embedding(config.vocab_size, config.n_embd)
|
| 375 |
-
self.drop = nn.Dropout(config.dropout)
|
| 376 |
-
|
| 377 |
-
self.blocks = nn.ModuleList(
|
| 378 |
-
[Block(config) for _ in range(config.n_layer)]
|
| 379 |
-
)
|
| 380 |
-
|
| 381 |
-
self.ln_f = nn.LayerNorm(config.n_embd)
|
| 382 |
-
self.head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
|
| 383 |
-
|
| 384 |
-
self.post_init()
|
| 385 |
-
self.tie_weights()
|
| 386 |
-
|
| 387 |
-
def get_input_embeddings(self):
|
| 388 |
-
return self.tok_emb
|
| 389 |
-
|
| 390 |
-
def set_input_embeddings(self, value):
|
| 391 |
-
self.tok_emb = value
|
| 392 |
-
self.tie_weights()
|
| 393 |
-
|
| 394 |
-
def get_output_embeddings(self):
|
| 395 |
-
return self.head
|
| 396 |
-
|
| 397 |
-
def set_output_embeddings(self, new_embeddings):
|
| 398 |
-
self.head = new_embeddings
|
| 399 |
-
|
| 400 |
-
def tie_weights(self, *args, **kwargs):
|
| 401 |
-
kwargs.pop("recompute_mapping", None)
|
| 402 |
-
kwargs.pop("missing_keys", None)
|
| 403 |
-
self._tie_or_clone_weights(self.head, self.tok_emb)
|
| 404 |
-
|
| 405 |
-
@staticmethod
|
| 406 |
-
def _tie_or_clone_weights(output_embeddings, input_embeddings):
|
| 407 |
-
output_embeddings.weight = input_embeddings.weight
|
| 408 |
-
if getattr(output_embeddings, "out_features", None) is not None:
|
| 409 |
-
output_embeddings.out_features = input_embeddings.num_embeddings
|
| 410 |
-
|
| 411 |
-
def forward(
|
| 412 |
-
self,
|
| 413 |
-
input_ids,
|
| 414 |
-
attention_mask=None,
|
| 415 |
-
return_dict=True,
|
| 416 |
-
return_logits=False,
|
| 417 |
-
**kwargs,
|
| 418 |
-
):
|
| 419 |
-
b, t = input_ids.shape
|
| 420 |
-
|
| 421 |
-
if t > self.config.ctx_len:
|
| 422 |
-
raise ValueError(
|
| 423 |
-
f"Input length {t} > ctx_len {self.config.ctx_len}. "
|
| 424 |
-
"Truncate before calling the model."
|
| 425 |
-
)
|
| 426 |
-
|
| 427 |
-
x = self.tok_emb(input_ids)
|
| 428 |
-
x = self.drop(x)
|
| 429 |
-
|
| 430 |
-
for block in self.blocks:
|
| 431 |
-
x = block(x)
|
| 432 |
-
|
| 433 |
-
hidden = self.ln_f(x)
|
| 434 |
-
logits = self.head(hidden) if return_logits else None
|
| 435 |
-
|
| 436 |
-
if not return_dict:
|
| 437 |
-
return (hidden, logits) if return_logits else (hidden,)
|
| 438 |
-
|
| 439 |
-
if return_logits:
|
| 440 |
-
return hidden, logits
|
| 441 |
-
|
| 442 |
-
return BaseModelOutputWithPast(
|
| 443 |
-
last_hidden_state=hidden,
|
| 444 |
-
past_key_values=None,
|
| 445 |
-
hidden_states=None,
|
| 446 |
-
attentions=None,
|
| 447 |
-
)
|
| 448 |
-
|
| 449 |
-
|
| 450 |
-
class TinyGPTForCausalLM(TinyGPTPreTrainedModel):
|
| 451 |
-
_tied_weights_keys = ["tiny_gpt.head.weight"]
|
| 452 |
-
|
| 453 |
-
def __init__(self, config: TinyGPTConfig):
|
| 454 |
-
super().__init__(config)
|
| 455 |
-
|
| 456 |
-
self.tiny_gpt = TinyGPTModel(config)
|
| 457 |
-
|
| 458 |
-
self.post_init()
|
| 459 |
-
self.tie_weights()
|
| 460 |
-
|
| 461 |
-
def get_input_embeddings(self):
|
| 462 |
-
return self.tiny_gpt.tok_emb
|
| 463 |
-
|
| 464 |
-
def set_input_embeddings(self, value):
|
| 465 |
-
self.tiny_gpt.tok_emb = value
|
| 466 |
-
self.tie_weights()
|
| 467 |
-
|
| 468 |
-
def get_output_embeddings(self):
|
| 469 |
-
return self.tiny_gpt.head
|
| 470 |
-
|
| 471 |
-
def set_output_embeddings(self, new_embeddings):
|
| 472 |
-
self.tiny_gpt.head = new_embeddings
|
| 473 |
-
|
| 474 |
-
def tie_weights(self, *args, **kwargs):
|
| 475 |
-
kwargs.pop("recompute_mapping", None)
|
| 476 |
-
kwargs.pop("missing_keys", None)
|
| 477 |
-
self._tie_or_clone_weights(
|
| 478 |
-
self.tiny_gpt.head,
|
| 479 |
-
self.tiny_gpt.tok_emb,
|
| 480 |
-
)
|
| 481 |
-
|
| 482 |
-
def prepare_inputs_for_generation(self, input_ids, **kwargs):
|
| 483 |
-
return {"input_ids": input_ids}
|
| 484 |
-
|
| 485 |
-
def forward(
|
| 486 |
-
self,
|
| 487 |
-
input_ids,
|
| 488 |
-
attention_mask=None,
|
| 489 |
-
labels=None,
|
| 490 |
-
return_dict=True,
|
| 491 |
-
**kwargs,
|
| 492 |
-
):
|
| 493 |
-
hidden, logits = self.tiny_gpt(
|
| 494 |
-
input_ids=input_ids,
|
| 495 |
-
attention_mask=attention_mask,
|
| 496 |
-
return_dict=True,
|
| 497 |
-
return_logits=True,
|
| 498 |
-
)
|
| 499 |
-
|
| 500 |
-
loss = None
|
| 501 |
-
|
| 502 |
-
if labels is not None:
|
| 503 |
-
shift_logits = logits[:, :-1, :].contiguous()
|
| 504 |
-
shift_labels = labels[:, 1:].contiguous()
|
| 505 |
-
|
| 506 |
-
loss = F.cross_entropy(
|
| 507 |
-
shift_logits.view(-1, shift_logits.size(-1)).float(),
|
| 508 |
-
shift_labels.view(-1),
|
| 509 |
-
)
|
| 510 |
-
|
| 511 |
-
if not return_dict:
|
| 512 |
-
return ((loss, logits) if loss is not None else (logits,))
|
| 513 |
-
|
| 514 |
-
return CausalLMOutputWithPast(
|
| 515 |
-
loss=loss,
|
| 516 |
-
logits=logits,
|
| 517 |
-
past_key_values=None,
|
| 518 |
-
hidden_states=None,
|
| 519 |
-
attentions=None,
|
| 520 |
-
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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