KingNish commited on
Commit
ce266dc
·
verified ·
1 Parent(s): 5f4bbff

Upload your_model_module.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. your_model_module.py +149 -0
your_model_module.py ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import torch
3
+ import torch.nn as nn
4
+ import torch.nn.functional as F
5
+ import math
6
+ from dataclasses import dataclass
7
+
8
+ # Define the LayerNorm class
9
+ class LayerNorm(nn.Module):
10
+ def __init__(self, ndim, bias):
11
+ super().__init__()
12
+ self.weight = nn.Parameter(torch.ones(ndim))
13
+ self.bias = nn.Parameter(torch.zeros(ndim)) if bias else None
14
+ def forward(self, x):
15
+ return F.layer_norm(x, self.weight.shape, self.weight, self.bias, 1e-5)
16
+
17
+ # Define the CausalSelfAttention class
18
+ class CausalSelfAttention(nn.Module):
19
+ def __init__(self, config):
20
+ super().__init__()
21
+ assert config.n_embd % config.n_head == 0
22
+ self.c_attn = nn.Linear(config.n_embd, 3 * config.n_embd, bias=config.bias)
23
+ self.c_proj = nn.Linear(config.n_embd, config.n_embd, bias=config.bias)
24
+ self.attn_dropout = nn.Dropout(config.dropout)
25
+ self.resid_dropout = nn.Dropout(config.dropout)
26
+ self.n_head = config.n_head
27
+ self.n_embd = config.n_embd
28
+ self.flash = hasattr(F, 'scaled_dot_product_attention')
29
+ if not self.flash:
30
+ self.register_buffer("bias", torch.tril(torch.ones(config.block_size, config.block_size))
31
+ .view(1, 1, config.block_size, config.block_size))
32
+
33
+ def forward(self, x):
34
+ B, T, C = x.size()
35
+ q, k, v = self.c_attn(x).split(self.n_embd, dim=2)
36
+ k = k.view(B, T, self.n_head, C // self.n_head).transpose(1, 2)
37
+ q = q.view(B, T, self.n_head, C // self.n_head).transpose(1, 2)
38
+ v = v.view(B, T, self.n_head, C // self.n_head).transpose(1, 2)
39
+
40
+ if self.flash:
41
+ y = F.scaled_dot_product_attention(q, k, v, attn_mask=None, dropout_p=self.attn_dropout.p if self.training else 0.0, is_causal=True)
42
+ else:
43
+ att = (q @ k.transpose(-2, -1)) * (1.0 / math.sqrt(k.size(-1)))
44
+ att = att.masked_fill(self.bias[:, :, :T, :T] == 0, float('-inf'))
45
+ att = F.softmax(att, dim=-1)
46
+ att = self.attn_dropout(att)
47
+ y = att @ v
48
+
49
+ y = y.transpose(1, 2).contiguous().view(B, T, C)
50
+ y = self.resid_dropout(self.c_proj(y))
51
+ return y
52
+
53
+ # Define the MLP class
54
+ class MLP(nn.Module):
55
+ def __init__(self, config):
56
+ super().__init__()
57
+ self.c_fc = nn.Linear(config.n_embd, 4 * config.n_embd, bias=config.bias)
58
+ self.gelu = nn.GELU()
59
+ self.c_proj = nn.Linear(4 * config.n_embd, config.n_embd, bias=config.bias)
60
+ self.dropout = nn.Dropout(config.dropout)
61
+ def forward(self, x):
62
+ return self.dropout(self.c_proj(self.gelu(self.c_fc(x))))
63
+
64
+ # Define the Block class
65
+ class Block(nn.Module):
66
+ def __init__(self, config):
67
+ super().__init__()
68
+ self.ln1 = LayerNorm(config.n_embd, config.bias)
69
+ self.attn = CausalSelfAttention(config)
70
+ self.ln2 = LayerNorm(config.n_embd, config.bias)
71
+ self.mlp = MLP(config)
72
+ def forward(self, x):
73
+ x = x + self.attn(self.ln1(x))
74
+ x = x + self.mlp(self.ln2(x))
75
+ return x
76
+
77
+ # Define the GPTConfig dataclass
78
+ @dataclass
79
+ class GPTConfig:
80
+ block_size: int
81
+ vocab_size: int
82
+ n_layer: int
83
+ n_head: int
84
+ n_embd: int
85
+ dropout: float = 0.0
86
+ bias: bool = True
87
+
88
+ # Define the GPT model class
89
+ class GPT(nn.Module):
90
+ def __init__(self, config):
91
+ super().__init__()
92
+ self.config = config
93
+ self.transformer = nn.ModuleDict(dict(
94
+ wte=nn.Embedding(config.vocab_size, config.n_embd),
95
+ wpe=nn.Embedding(config.block_size, config.n_embd),
96
+ drop=nn.Dropout(config.dropout),
97
+ h=nn.ModuleList([Block(config) for _ in range(config.n_layer)]),
98
+ ln_f=LayerNorm(config.n_embd, config.bias),
99
+ ))
100
+ self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
101
+ self.transformer.wte.weight = self.lm_head.weight # weight tying
102
+
103
+ self.apply(self._init_weights)
104
+ for pn, p in self.named_parameters():
105
+ if pn.endswith('c_proj.weight'):
106
+ nn.init.normal_(p, mean=0.0, std=0.02 / math.sqrt(2 * config.n_layer))
107
+
108
+ def _init_weights(self, module):
109
+ if isinstance(module, nn.Linear):
110
+ nn.init.normal_(module.weight, mean=0.0, std=0.02)
111
+ if module.bias is not None:
112
+ nn.init.zeros_(module.bias)
113
+ elif isinstance(module, nn.Embedding):
114
+ nn.init.normal_(module.weight, mean=0.0, std=0.02)
115
+
116
+ def forward(self, idx, targets=None):
117
+ device = idx.device
118
+ b, t = idx.size()
119
+ assert t <= self.config.block_size
120
+ pos = torch.arange(0, t, dtype=torch.long, device=device)
121
+
122
+ tok_emb = self.transformer.wte(idx)
123
+ pos_emb = self.transformer.wpe(pos)
124
+ x = self.transformer.drop(tok_emb + pos_emb)
125
+ for block in self.transformer.h:
126
+ x = block(x)
127
+ x = self.transformer.ln_f(x)
128
+
129
+ if targets is not None:
130
+ logits = self.lm_head(x)
131
+ loss = F.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1), ignore_index=-1)
132
+ return logits, loss
133
+ else:
134
+ logits = self.lm_head(x[:, [-1], :])
135
+ return logits, None
136
+
137
+ @torch.no_grad()
138
+ def generate(self, idx, max_new_tokens, temperature=1.0, top_k=None):
139
+ for _ in range(max_new_tokens):
140
+ idx_cond = idx if idx.size(1) <= self.config.block_size else idx[:, -self.config.block_size:]
141
+ logits, _ = self(idx_cond)
142
+ logits = logits[:, -1, :] / temperature
143
+ if top_k is not None:
144
+ v, _ = torch.topk(logits, min(top_k, logits.size(-1)))
145
+ logits[logits < v[:, [-1]]] = -float('Inf')
146
+ probs = F.softmax(logits, dim=-1)
147
+ idx_next = torch.multinomial(probs, num_samples=1)
148
+ idx = torch.cat((idx, idx_next), dim=1)
149
+ return idx