Upload 11 files
Browse files- config.json +41 -0
- configuration_tiny_gpt.py +56 -0
- generation_config.json +6 -0
- merges.txt +0 -0
- model.safetensors +3 -0
- modeling_tiny_gpt.py +504 -0
- requirements.txt +5 -0
- special_tokens_map.json +9 -0
- tokenizer.json +0 -0
- tokenizer_config.json +14 -0
- vocab.json +0 -0
config.json
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"model_type": "slm",
|
| 3 |
+
"model_name": "slm",
|
| 4 |
+
"architectures": [
|
| 5 |
+
"TinyGPTForCausalLM"
|
| 6 |
+
],
|
| 7 |
+
"auto_map": {
|
| 8 |
+
"AutoConfig": "configuration_tiny_gpt.TinyGPTConfig",
|
| 9 |
+
"AutoModel": "modeling_tiny_gpt.TinyGPTModel",
|
| 10 |
+
"AutoModelForCausalLM": "modeling_tiny_gpt.TinyGPTForCausalLM"
|
| 11 |
+
},
|
| 12 |
+
"vocab_size": 32000,
|
| 13 |
+
"ctx_len": 2048,
|
| 14 |
+
"max_position_embeddings": 2048,
|
| 15 |
+
"n_layer": 4,
|
| 16 |
+
"num_hidden_layers": 4,
|
| 17 |
+
"n_head": 4,
|
| 18 |
+
"num_attention_heads": 4,
|
| 19 |
+
"n_embd": 384,
|
| 20 |
+
"hidden_size": 384,
|
| 21 |
+
"dropout": 0.0,
|
| 22 |
+
"attention_backend": "torch",
|
| 23 |
+
"available_attention_backends": [
|
| 24 |
+
"sage",
|
| 25 |
+
"torch",
|
| 26 |
+
"flash2",
|
| 27 |
+
"flash3"
|
| 28 |
+
],
|
| 29 |
+
"trained_attention_backend": "flash2",
|
| 30 |
+
"torch_fallback": true,
|
| 31 |
+
"positional_encoding": "rope",
|
| 32 |
+
"trained_positional_encoding": "rope",
|
| 33 |
+
"rope_base": 10000.0,
|
| 34 |
+
"torch_dtype": "bfloat16",
|
| 35 |
+
"transformers_version": "custom",
|
| 36 |
+
"pad_token_id": 0,
|
| 37 |
+
"bos_token_id": 5,
|
| 38 |
+
"eos_token_id": 6,
|
| 39 |
+
"sep_token_id": 2,
|
| 40 |
+
"unk_token_id": 1
|
| 41 |
+
}
|
configuration_tiny_gpt.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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)
|
generation_config.json
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"pad_token_id": 0,
|
| 3 |
+
"bos_token_id": 5,
|
| 4 |
+
"eos_token_id": 6,
|
| 5 |
+
"sep_token_id": 2
|
| 6 |
+
}
|
merges.txt
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:3f56e91f93ad42f3ec204c36de19ecbb2aa88edcaada3787659b2fbf44b8c35a
|
| 3 |
+
size 63325200
|
modeling_tiny_gpt.py
ADDED
|
@@ -0,0 +1,504 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
def _init_weights(self, module):
|
| 353 |
+
if isinstance(module, nn.Linear):
|
| 354 |
+
nn.init.normal_(module.weight, mean=0.0, std=0.02)
|
| 355 |
+
if module.bias is not None:
|
| 356 |
+
nn.init.zeros_(module.bias)
|
| 357 |
+
|
| 358 |
+
elif isinstance(module, nn.Embedding):
|
| 359 |
+
nn.init.normal_(module.weight, mean=0.0, std=0.02)
|
| 360 |
+
|
| 361 |
+
|
| 362 |
+
class TinyGPTModel(TinyGPTPreTrainedModel):
|
| 363 |
+
_tied_weights_keys = ["head.weight"]
|
| 364 |
+
|
| 365 |
+
def __init__(self, config: TinyGPTConfig):
|
| 366 |
+
super().__init__(config)
|
| 367 |
+
|
| 368 |
+
self.tok_emb = nn.Embedding(config.vocab_size, config.n_embd)
|
| 369 |
+
self.drop = nn.Dropout(config.dropout)
|
| 370 |
+
|
| 371 |
+
self.blocks = nn.ModuleList(
|
| 372 |
+
[Block(config) for _ in range(config.n_layer)]
|
| 373 |
+
)
|
| 374 |
+
|
| 375 |
+
self.ln_f = nn.LayerNorm(config.n_embd)
|
| 376 |
+
self.head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
|
| 377 |
+
|
| 378 |
+
self.post_init()
|
| 379 |
+
self.tie_weights()
|
| 380 |
+
|
| 381 |
+
def get_input_embeddings(self):
|
| 382 |
+
return self.tok_emb
|
| 383 |
+
|
| 384 |
+
def set_input_embeddings(self, value):
|
| 385 |
+
self.tok_emb = value
|
| 386 |
+
self.tie_weights()
|
| 387 |
+
|
| 388 |
+
def get_output_embeddings(self):
|
| 389 |
+
return self.head
|
| 390 |
+
|
| 391 |
+
def set_output_embeddings(self, new_embeddings):
|
| 392 |
+
self.head = new_embeddings
|
| 393 |
+
|
| 394 |
+
def tie_weights(self):
|
| 395 |
+
self._tie_or_clone_weights(self.head, self.tok_emb)
|
| 396 |
+
|
| 397 |
+
def forward(
|
| 398 |
+
self,
|
| 399 |
+
input_ids,
|
| 400 |
+
attention_mask=None,
|
| 401 |
+
return_dict=True,
|
| 402 |
+
return_logits=False,
|
| 403 |
+
**kwargs,
|
| 404 |
+
):
|
| 405 |
+
b, t = input_ids.shape
|
| 406 |
+
|
| 407 |
+
if t > self.config.ctx_len:
|
| 408 |
+
raise ValueError(
|
| 409 |
+
f"Input length {t} > ctx_len {self.config.ctx_len}. "
|
| 410 |
+
"Truncate before calling the model."
|
| 411 |
+
)
|
| 412 |
+
|
| 413 |
+
x = self.tok_emb(input_ids)
|
| 414 |
+
x = self.drop(x)
|
| 415 |
+
|
| 416 |
+
for block in self.blocks:
|
| 417 |
+
x = block(x)
|
| 418 |
+
|
| 419 |
+
hidden = self.ln_f(x)
|
| 420 |
+
logits = self.head(hidden) if return_logits else None
|
| 421 |
+
|
| 422 |
+
if not return_dict:
|
| 423 |
+
return (hidden, logits) if return_logits else (hidden,)
|
| 424 |
+
|
| 425 |
+
if return_logits:
|
| 426 |
+
return hidden, logits
|
| 427 |
+
|
| 428 |
+
return BaseModelOutputWithPast(
|
| 429 |
+
last_hidden_state=hidden,
|
| 430 |
+
past_key_values=None,
|
| 431 |
+
hidden_states=None,
|
| 432 |
+
attentions=None,
|
| 433 |
+
)
|
| 434 |
+
|
| 435 |
+
|
| 436 |
+
class TinyGPTForCausalLM(TinyGPTPreTrainedModel):
|
| 437 |
+
_tied_weights_keys = ["tiny_gpt.head.weight"]
|
| 438 |
+
|
| 439 |
+
def __init__(self, config: TinyGPTConfig):
|
| 440 |
+
super().__init__(config)
|
| 441 |
+
|
| 442 |
+
self.tiny_gpt = TinyGPTModel(config)
|
| 443 |
+
|
| 444 |
+
self.post_init()
|
| 445 |
+
self.tie_weights()
|
| 446 |
+
|
| 447 |
+
def get_input_embeddings(self):
|
| 448 |
+
return self.tiny_gpt.tok_emb
|
| 449 |
+
|
| 450 |
+
def set_input_embeddings(self, value):
|
| 451 |
+
self.tiny_gpt.tok_emb = value
|
| 452 |
+
self.tie_weights()
|
| 453 |
+
|
| 454 |
+
def get_output_embeddings(self):
|
| 455 |
+
return self.tiny_gpt.head
|
| 456 |
+
|
| 457 |
+
def set_output_embeddings(self, new_embeddings):
|
| 458 |
+
self.tiny_gpt.head = new_embeddings
|
| 459 |
+
|
| 460 |
+
def tie_weights(self):
|
| 461 |
+
self._tie_or_clone_weights(
|
| 462 |
+
self.tiny_gpt.head,
|
| 463 |
+
self.tiny_gpt.tok_emb,
|
| 464 |
+
)
|
| 465 |
+
|
| 466 |
+
def prepare_inputs_for_generation(self, input_ids, **kwargs):
|
| 467 |
+
return {"input_ids": input_ids}
|
| 468 |
+
|
| 469 |
+
def forward(
|
| 470 |
+
self,
|
| 471 |
+
input_ids,
|
| 472 |
+
attention_mask=None,
|
| 473 |
+
labels=None,
|
| 474 |
+
return_dict=True,
|
| 475 |
+
**kwargs,
|
| 476 |
+
):
|
| 477 |
+
hidden, logits = self.tiny_gpt(
|
| 478 |
+
input_ids=input_ids,
|
| 479 |
+
attention_mask=attention_mask,
|
| 480 |
+
return_dict=True,
|
| 481 |
+
return_logits=True,
|
| 482 |
+
)
|
| 483 |
+
|
| 484 |
+
loss = None
|
| 485 |
+
|
| 486 |
+
if labels is not None:
|
| 487 |
+
shift_logits = logits[:, :-1, :].contiguous()
|
| 488 |
+
shift_labels = labels[:, 1:].contiguous()
|
| 489 |
+
|
| 490 |
+
loss = F.cross_entropy(
|
| 491 |
+
shift_logits.view(-1, shift_logits.size(-1)).float(),
|
| 492 |
+
shift_labels.view(-1),
|
| 493 |
+
)
|
| 494 |
+
|
| 495 |
+
if not return_dict:
|
| 496 |
+
return ((loss, logits) if loss is not None else (logits,))
|
| 497 |
+
|
| 498 |
+
return CausalLMOutputWithPast(
|
| 499 |
+
loss=loss,
|
| 500 |
+
logits=logits,
|
| 501 |
+
past_key_values=None,
|
| 502 |
+
hidden_states=None,
|
| 503 |
+
attentions=None,
|
| 504 |
+
)
|
requirements.txt
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
torch
|
| 2 |
+
transformers
|
| 3 |
+
safetensors
|
| 4 |
+
tokenizers
|
| 5 |
+
kernels
|
special_tokens_map.json
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"unk_token": "[UNK]",
|
| 3 |
+
"pad_token": "[PAD]",
|
| 4 |
+
"sep_token": "[SEP]",
|
| 5 |
+
"cls_token": "[CLS]",
|
| 6 |
+
"mask_token": "[MASK]",
|
| 7 |
+
"bos_token": "[BOS]",
|
| 8 |
+
"eos_token": "[EOS]"
|
| 9 |
+
}
|
tokenizer.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
tokenizer_config.json
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"tokenizer_class": "PreTrainedTokenizerFast",
|
| 3 |
+
"clean_up_tokenization_spaces": false,
|
| 4 |
+
"padding_side": "right",
|
| 5 |
+
"truncation_side": "right",
|
| 6 |
+
"unk_token": "[UNK]",
|
| 7 |
+
"pad_token": "[PAD]",
|
| 8 |
+
"sep_token": "[SEP]",
|
| 9 |
+
"cls_token": "[CLS]",
|
| 10 |
+
"mask_token": "[MASK]",
|
| 11 |
+
"bos_token": "[BOS]",
|
| 12 |
+
"eos_token": "[EOS]",
|
| 13 |
+
"model_max_length": 2048
|
| 14 |
+
}
|
vocab.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|