chegde commited on
Commit
bbbee58
·
verified ·
1 Parent(s): 19f7ea9

Add model implementation files for trust_remote_code support

Browse files
Files changed (2) hide show
  1. configuration_nanogpt.py +26 -0
  2. modeling_nanogpt.py +155 -0
configuration_nanogpt.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """NanoGPT model configuration"""
2
+
3
+ from transformers import PretrainedConfig
4
+
5
+ class NanoGPTConfig(PretrainedConfig):
6
+ model_type = "nanogpt"
7
+
8
+ def __init__(
9
+ self,
10
+ vocab_size=50257,
11
+ n_embd=768,
12
+ n_head=12,
13
+ n_layer=12,
14
+ block_size=1024,
15
+ bias=True,
16
+ dropout=0.0,
17
+ **kwargs
18
+ ):
19
+ super().__init__(**kwargs)
20
+ self.vocab_size = vocab_size
21
+ self.n_embd = n_embd
22
+ self.n_head = n_head
23
+ self.n_layer = n_layer
24
+ self.block_size = block_size
25
+ self.bias = bias
26
+ self.dropout = dropout
modeling_nanogpt.py ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """NanoGPT model implementation"""
2
+
3
+ import torch
4
+ import torch.nn as nn
5
+ import torch.nn.functional as F
6
+ import math
7
+ from transformers import PreTrainedModel
8
+ from transformers.modeling_outputs import CausalLMOutputWithCrossAttentions
9
+ from .configuration_nanogpt import NanoGPTConfig
10
+
11
+ class ExactNanoGPTAttention(nn.Module):
12
+ def __init__(self, config):
13
+ super().__init__()
14
+ assert config.n_embd % config.n_head == 0
15
+
16
+ self.c_attn = nn.Linear(config.n_embd, 3 * config.n_embd, bias=config.bias)
17
+ self.c_proj = nn.Linear(config.n_embd, config.n_embd, bias=config.bias)
18
+ self.attn_dropout = nn.Dropout(config.dropout)
19
+ self.resid_dropout = nn.Dropout(config.dropout)
20
+ self.n_head = config.n_head
21
+ self.n_embd = config.n_embd
22
+ self.dropout = config.dropout
23
+
24
+ self.flash = hasattr(torch.nn.functional, 'scaled_dot_product_attention')
25
+ if not self.flash:
26
+ self.register_buffer("bias", torch.tril(torch.ones(config.block_size, config.block_size))
27
+ .view(1, 1, config.block_size, config.block_size))
28
+
29
+ def forward(self, x):
30
+ B, T, C = x.size()
31
+
32
+ q, k, v = self.c_attn(x).split(self.n_embd, dim=2)
33
+ k = k.view(B, T, self.n_head, C // self.n_head).transpose(1, 2)
34
+ q = q.view(B, T, self.n_head, C // self.n_head).transpose(1, 2)
35
+ v = v.view(B, T, self.n_head, C // self.n_head).transpose(1, 2)
36
+
37
+ if self.flash:
38
+ y = torch.nn.functional.scaled_dot_product_attention(
39
+ q, k, v,
40
+ attn_mask=None,
41
+ dropout_p=self.dropout if self.training else 0,
42
+ is_causal=True
43
+ )
44
+ else:
45
+ att = (q @ k.transpose(-2, -1)) * (1.0 / math.sqrt(k.size(-1)))
46
+ att = att.masked_fill(self.bias[:, :, :T, :T] == 0, float('-inf'))
47
+ att = F.softmax(att, dim=-1)
48
+ att = self.attn_dropout(att)
49
+ y = att @ v
50
+
51
+ y = y.transpose(1, 2).contiguous().view(B, T, C)
52
+ y = self.resid_dropout(self.c_proj(y))
53
+ return y
54
+
55
+ class ExactNanoGPTMLP(nn.Module):
56
+ def __init__(self, config):
57
+ super().__init__()
58
+ self.c_fc = nn.Linear(config.n_embd, 4 * config.n_embd, bias=config.bias)
59
+ self.gelu = nn.GELU()
60
+ self.c_proj = nn.Linear(4 * config.n_embd, config.n_embd, bias=config.bias)
61
+ self.dropout = nn.Dropout(config.dropout)
62
+
63
+ def forward(self, x):
64
+ x = self.c_fc(x)
65
+ x = self.gelu(x)
66
+ x = self.c_proj(x)
67
+ x = self.dropout(x)
68
+ return x
69
+
70
+ class ExactNanoGPTBlock(nn.Module):
71
+ def __init__(self, config):
72
+ super().__init__()
73
+ self.ln_1 = nn.LayerNorm(config.n_embd, bias=config.bias)
74
+ self.attn = ExactNanoGPTAttention(config)
75
+ self.ln_2 = nn.LayerNorm(config.n_embd, bias=config.bias)
76
+ self.mlp = ExactNanoGPTMLP(config)
77
+
78
+ def forward(self, x):
79
+ x = x + self.attn(self.ln_1(x))
80
+ x = x + self.mlp(self.ln_2(x))
81
+ return x
82
+
83
+ class NanoGPTModel(PreTrainedModel):
84
+ config_class = NanoGPTConfig
85
+
86
+ def __init__(self, config):
87
+ super().__init__(config)
88
+ self.config = config
89
+
90
+ self.transformer = nn.ModuleDict(dict(
91
+ wte = nn.Embedding(config.vocab_size, config.n_embd),
92
+ wpe = nn.Embedding(config.block_size, config.n_embd),
93
+ drop = nn.Dropout(config.dropout),
94
+ h = nn.ModuleList([ExactNanoGPTBlock(config) for _ in range(config.n_layer)]),
95
+ ln_f = nn.LayerNorm(config.n_embd, bias=config.bias),
96
+ ))
97
+ self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
98
+
99
+ self.post_init()
100
+
101
+ def forward(self, input_ids, attention_mask=None, **kwargs):
102
+ device = input_ids.device
103
+ b, t = input_ids.size()
104
+ assert t <= self.config.block_size, f"Cannot forward sequence of length {t}, block size is only {self.config.block_size}"
105
+ pos = torch.arange(0, t, dtype=torch.long, device=device)
106
+
107
+ tok_emb = self.transformer.wte(input_ids)
108
+ pos_emb = self.transformer.wpe(pos)
109
+ x = self.transformer.drop(tok_emb + pos_emb)
110
+ for block in self.transformer.h:
111
+ x = block(x)
112
+ x = self.transformer.ln_f(x)
113
+
114
+ logits = self.lm_head(x)
115
+
116
+ return CausalLMOutputWithCrossAttentions(logits=logits)
117
+
118
+ def generate(self, input_ids, max_length=None, max_new_tokens=None, temperature=1.0, top_k=None, do_sample=True, top_p=None, **kwargs):
119
+ if max_new_tokens is None:
120
+ max_new_tokens = max_length - input_ids.shape[1] if max_length else 50
121
+
122
+ for _ in range(max_new_tokens):
123
+ idx_cond = input_ids if input_ids.size(1) <= self.config.block_size else input_ids[:, -self.config.block_size:]
124
+
125
+ with torch.no_grad():
126
+ outputs = self(idx_cond)
127
+ logits = outputs.logits
128
+
129
+ logits = logits[:, -1, :] / temperature
130
+
131
+ if top_k is not None:
132
+ v, _ = torch.topk(logits, min(top_k, logits.size(-1)))
133
+ logits[logits < v[:, [-1]]] = -float('Inf')
134
+
135
+ if top_p is not None:
136
+ sorted_logits, sorted_indices = torch.sort(logits, descending=True)
137
+ cumulative_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1)
138
+
139
+ sorted_indices_to_remove = cumulative_probs > top_p
140
+ sorted_indices_to_remove[..., 1:] = sorted_indices_to_remove[..., :-1].clone()
141
+ sorted_indices_to_remove[..., 0] = 0
142
+
143
+ indices_to_remove = sorted_indices_to_remove.scatter(1, sorted_indices, sorted_indices_to_remove)
144
+ logits[indices_to_remove] = -float('Inf')
145
+
146
+ probs = F.softmax(logits, dim=-1)
147
+
148
+ if do_sample:
149
+ idx_next = torch.multinomial(probs, num_samples=1)
150
+ else:
151
+ _, idx_next = torch.topk(probs, k=1, dim=-1)
152
+
153
+ input_ids = torch.cat((input_ids, idx_next), dim=1)
154
+
155
+ return input_ids