burtenshaw HF Staff commited on
Commit
2f4fdec
·
verified ·
1 Parent(s): 8423d41

Upload folder using huggingface_hub

Browse files
__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ from .configuration_nanogpt import NanoGPTConfig
2
+ from .modeling_nanogpt import NanoGPTModel
3
+ from .tokenizer_nanogpt import NanoGPTTokenizer
4
+
5
+
config.json ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model_type": "nanogpt",
3
+ "architectures": [
4
+ "NanoGPTModel"
5
+ ],
6
+ "auto_map": {
7
+ "AutoConfig": "configuration_nanogpt.NanoGPTConfig",
8
+ "AutoModel": "modeling_nanogpt.NanoGPTModel",
9
+ "AutoTokenizer": "tokenizer_nanogpt.NanoGPTTokenizer"
10
+ },
11
+ "sequence_len": 2048,
12
+ "vocab_size": 65536,
13
+ "n_layer": 20,
14
+ "n_head": 10,
15
+ "n_kv_head": 10,
16
+ "n_embd": 1280
17
+ }
configuration_nanogpt.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import PretrainedConfig
2
+
3
+
4
+ class NanoGPTConfig(PretrainedConfig):
5
+ model_type = "nanogpt"
6
+
7
+ def __init__(
8
+ self,
9
+ sequence_len: int = 1024,
10
+ vocab_size: int = 50304,
11
+ n_layer: int = 12,
12
+ n_head: int = 6,
13
+ n_kv_head: int = 6,
14
+ n_embd: int = 768,
15
+ **kwargs,
16
+ ):
17
+ self.sequence_len = sequence_len
18
+ self.vocab_size = vocab_size
19
+ self.n_layer = n_layer
20
+ self.n_head = n_head
21
+ self.n_kv_head = n_kv_head
22
+ self.n_embd = n_embd
23
+ super().__init__(**kwargs)
24
+
25
+
26
+
modeling_nanogpt.py ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ from dataclasses import dataclass
3
+
4
+ import torch
5
+ import torch.nn as nn
6
+ import torch.nn.functional as F
7
+ from transformers import PreTrainedModel
8
+
9
+ from .configuration_nanogpt import NanoGPTConfig
10
+
11
+
12
+ def _rms_norm(x: torch.Tensor) -> torch.Tensor:
13
+ return F.rms_norm(x, (x.size(-1),))
14
+
15
+
16
+ def _apply_rotary_emb(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:
17
+ assert x.ndim == 4
18
+ d = x.shape[3] // 2
19
+ x1, x2 = x[..., :d], x[..., d:]
20
+ y1 = x1 * cos + x2 * sin
21
+ y2 = x1 * (-sin) + x2 * cos
22
+ out = torch.cat([y1, y2], 3)
23
+ return out.to(x.dtype)
24
+
25
+
26
+ def _repeat_kv(x: torch.Tensor, n_rep: int) -> torch.Tensor:
27
+ if n_rep == 1:
28
+ return x
29
+ bs, n_kv_heads, slen, head_dim = x.shape
30
+ return (
31
+ x[:, :, None, :, :]
32
+ .expand(bs, n_kv_heads, n_rep, slen, head_dim)
33
+ .reshape(bs, n_kv_heads * n_rep, slen, head_dim)
34
+ )
35
+
36
+
37
+ class CausalSelfAttention(nn.Module):
38
+ def __init__(self, config: NanoGPTConfig, layer_idx: int):
39
+ super().__init__()
40
+ self.layer_idx = layer_idx
41
+ self.n_head = config.n_head
42
+ self.n_kv_head = config.n_kv_head
43
+ self.n_embd = config.n_embd
44
+ self.head_dim = self.n_embd // self.n_head
45
+ assert self.n_embd % self.n_head == 0
46
+ assert self.n_kv_head <= self.n_head and self.n_head % self.n_kv_head == 0
47
+ self.c_q = nn.Linear(self.n_embd, self.n_head * self.head_dim, bias=False)
48
+ self.c_k = nn.Linear(self.n_embd, self.n_kv_head * self.head_dim, bias=False)
49
+ self.c_v = nn.Linear(self.n_embd, self.n_kv_head * self.head_dim, bias=False)
50
+ self.c_proj = nn.Linear(self.n_embd, self.n_embd, bias=False)
51
+
52
+ def forward(self, x: torch.Tensor, cos_sin, kv_cache=None) -> torch.Tensor:
53
+ B, T, C = x.size()
54
+ q = self.c_q(x).view(B, T, self.n_head, self.head_dim)
55
+ k = self.c_k(x).view(B, T, self.n_kv_head, self.head_dim)
56
+ v = self.c_v(x).view(B, T, self.n_kv_head, self.head_dim)
57
+ cos, sin = cos_sin
58
+ q, k = _apply_rotary_emb(q, cos, sin), _apply_rotary_emb(k, cos, sin)
59
+ q, k = _rms_norm(q), _rms_norm(k)
60
+ q, k, v = q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2)
61
+ Tq = q.size(2)
62
+ Tk = k.size(2)
63
+ nrep = self.n_head // self.n_kv_head
64
+ k, v = _repeat_kv(k, nrep), _repeat_kv(v, nrep)
65
+ if Tq == Tk:
66
+ y = F.scaled_dot_product_attention(q, k, v, is_causal=True)
67
+ elif Tq == 1:
68
+ y = F.scaled_dot_product_attention(q, k, v, is_causal=False)
69
+ else:
70
+ attn_mask = torch.zeros((Tq, Tk), dtype=torch.bool, device=q.device)
71
+ prefix_len = Tk - Tq
72
+ if prefix_len > 0:
73
+ attn_mask[:, :prefix_len] = True
74
+ attn_mask[:, prefix_len:] = torch.tril(torch.ones((Tq, Tq), dtype=torch.bool, device=q.device))
75
+ y = F.scaled_dot_product_attention(q, k, v, attn_mask=attn_mask)
76
+ y = y.transpose(1, 2).contiguous().view(B, T, -1)
77
+ y = self.c_proj(y)
78
+ return y
79
+
80
+
81
+ class MLP(nn.Module):
82
+ def __init__(self, config: NanoGPTConfig):
83
+ super().__init__()
84
+ self.c_fc = nn.Linear(config.n_embd, 4 * config.n_embd, bias=False)
85
+ self.c_proj = nn.Linear(4 * config.n_embd, config.n_embd, bias=False)
86
+
87
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
88
+ x = self.c_fc(x)
89
+ x = F.relu(x).square()
90
+ x = self.c_proj(x)
91
+ return x
92
+
93
+
94
+ class Block(nn.Module):
95
+ def __init__(self, config: NanoGPTConfig, layer_idx: int):
96
+ super().__init__()
97
+ self.attn = CausalSelfAttention(config, layer_idx)
98
+ self.mlp = MLP(config)
99
+
100
+ def forward(self, x: torch.Tensor, cos_sin, kv_cache=None) -> torch.Tensor:
101
+ x = x + self.attn(_rms_norm(x), cos_sin, kv_cache)
102
+ x = x + self.mlp(_rms_norm(x))
103
+ return x
104
+
105
+
106
+ class NanoGPTModel(PreTrainedModel):
107
+ config_class = NanoGPTConfig
108
+
109
+ def __init__(self, config: NanoGPTConfig):
110
+ super().__init__(config)
111
+ self.transformer = nn.ModuleDict({
112
+ "wte": nn.Embedding(config.vocab_size, config.n_embd),
113
+ "h": nn.ModuleList([Block(config, layer_idx) for layer_idx in range(config.n_layer)]),
114
+ })
115
+ self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
116
+ self.rotary_seq_len = config.sequence_len * 10
117
+ head_dim = config.n_embd // config.n_head
118
+ cos, sin = self._precompute_rotary_embeddings(self.rotary_seq_len, head_dim)
119
+ self.register_buffer("cos", cos, persistent=False)
120
+ self.register_buffer("sin", sin, persistent=False)
121
+ # ensure fp32 activations
122
+ self.transformer.wte.to(dtype=torch.bfloat16)
123
+
124
+ # following HF API expectations
125
+ self.post_init()
126
+
127
+ def _init_weights(self, module: nn.Module):
128
+ if isinstance(module, nn.Linear):
129
+ fan_out = module.weight.size(0)
130
+ fan_in = module.weight.size(1)
131
+ std = 1.0 / math.sqrt(fan_in) * min(1.0, math.sqrt(fan_out / fan_in))
132
+ torch.nn.init.normal_(module.weight, mean=0.0, std=std)
133
+ if module.bias is not None:
134
+ torch.nn.init.zeros_(module.bias)
135
+ elif isinstance(module, nn.Embedding):
136
+ torch.nn.init.normal_(module.weight, mean=0.0, std=1.0)
137
+
138
+ def _precompute_rotary_embeddings(self, seq_len: int, head_dim: int, base: int = 10000, device=None):
139
+ if device is None:
140
+ device = self.transformer.wte.weight.device
141
+ # Handle meta device case - use CPU as fallback
142
+ if device.type == 'meta':
143
+ device = torch.device('cpu')
144
+ channel_range = torch.arange(0, head_dim, 2, dtype=torch.float32, device=device)
145
+ inv_freq = 1.0 / (base ** (channel_range / head_dim))
146
+ t = torch.arange(seq_len, dtype=torch.float32, device=device)
147
+ freqs = torch.outer(t, inv_freq)
148
+ cos, sin = freqs.cos(), freqs.sin()
149
+ cos, sin = cos.bfloat16(), sin.bfloat16()
150
+ cos, sin = cos[None, :, None, :], sin[None, :, None, :]
151
+ return cos, sin
152
+
153
+ def forward(self, input_ids: torch.Tensor, labels=None, **kwargs):
154
+ idx = input_ids
155
+ B, T = idx.size()
156
+ T0 = 0
157
+ cos_sin = self.cos[:, T0:T0+T], self.sin[:, T0:T0+T]
158
+ x = self.transformer.wte(idx)
159
+ x = x.float()
160
+ x = _rms_norm(x)
161
+ for block in self.transformer.h:
162
+ x = block(x, cos_sin, None)
163
+ x = _rms_norm(x)
164
+
165
+ softcap = 15
166
+ logits = self.lm_head(x)
167
+ logits = softcap * torch.tanh(logits / softcap)
168
+ loss = None
169
+ if labels is not None:
170
+ loss = F.cross_entropy(logits.view(-1, logits.size(-1)), labels.view(-1), ignore_index=-1, reduction='mean')
171
+ return {"loss": loss, "logits": logits}
172
+
173
+
174
+
pytorch_model.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:574670de45c667a98fe72c2d145f24007ecc1778721e2481e41500842dd3ba13
3
+ size 2076230219
token_bytes.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e1b6cdee5d02fe1018b2b1d2ae5b736be665f9c0e7d10c81dcf935e7efaf8cb5
3
+ size 263721
tokenizer.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8467414b90511a50c4dac438af25c075817e9d62d799a5ef613b186c977f5d1b
3
+ size 846518
tokenizer_config.json ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "auto_map": {
3
+ "AutoTokenizer": [
4
+ "tokenizer_nanogpt.NanoGPTTokenizer",
5
+ null
6
+ ]
7
+ },
8
+ "tokenizer_class": "NanoGPTTokenizer"
9
+ }
tokenizer_nanogpt.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import pickle
3
+
4
+
5
+ class NanoGPTTokenizer:
6
+ """Lightweight wrapper over a tiktoken Encoding stored in tokenizer.pkl.
7
+
8
+ Provides minimal encode/decode needed for inference and a from_pretrained
9
+ constructor so it can be loaded via AutoTokenizer with trust_remote_code.
10
+ """
11
+
12
+ def __init__(self, enc):
13
+ self.enc = enc
14
+ self.bos_token_id = enc.encode_single_token("<|bos|>")
15
+
16
+ @classmethod
17
+ def register_for_auto_class(cls, auto_class="AutoTokenizer"):
18
+ """Required for AutoTokenizer registration."""
19
+ pass
20
+
21
+ @classmethod
22
+ def from_pretrained(cls, pretrained_model_name_or_path, *args, **kwargs):
23
+ tok_path = os.path.join(pretrained_model_name_or_path, "tokenizer.pkl")
24
+ with open(tok_path, "rb") as f:
25
+ enc = pickle.load(f)
26
+ return cls(enc)
27
+
28
+ def encode(self, text, prepend=None):
29
+ ids = self.enc.encode_ordinary(text)
30
+ if prepend is not None:
31
+ prepend_id = prepend if isinstance(prepend, int) else self.enc.encode_single_token(prepend)
32
+ ids.insert(0, prepend_id)
33
+ return ids
34
+
35
+ def decode(self, ids):
36
+ return self.enc.decode(ids)
37
+
38
+ def get_bos_token_id(self):
39
+ return self.bos_token_id
40
+
41
+
42
+