Magurofg commited on
Commit
d55db56
·
verified ·
1 Parent(s): bc356c4

Upload model.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. model.py +137 -0
model.py ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """GPT char-level minúsculo (estilo nanoGPT), pra treinar em CPU.
2
+ Não é o modelo final do projeto — é o brinquedo que prova a esteira toda de graça.
3
+ O modelo "de verdade" (BPE, maior) roda na GPU alugada depois."""
4
+ from __future__ import annotations
5
+ import math
6
+ from dataclasses import dataclass
7
+ import torch
8
+ import torch.nn as nn
9
+ from torch.nn import functional as F
10
+
11
+
12
+ @dataclass
13
+ class GPTConfig:
14
+ vocab_size: int
15
+ block_size: int = 256
16
+ n_layer: int = 6
17
+ n_head: int = 6
18
+ n_embd: int = 192
19
+ dropout: float = 0.1
20
+
21
+
22
+ class CausalSelfAttention(nn.Module):
23
+ """Atencao causal com SDPA e QKV fundido.
24
+
25
+ Substitui nn.MultiheadAttention, que desliga o fast-path assim que recebe um
26
+ attn_mask explicito e cai no caminho lento — parte do motivo da MFU ter ficado em
27
+ ~11% na H200. F.scaled_dot_product_attention com is_causal=True usa o kernel
28
+ fundido e dispensa materializar a mascara TxT.
29
+
30
+ Os PARAMETROS mantem de proposito os nomes de nn.MultiheadAttention
31
+ (in_proj_weight, in_proj_bias, out_proj.weight, out_proj.bias): o state_dict fica
32
+ identico, entao checkpoint antigo — inclusive o de 219M do run pocket-h200-v2 —
33
+ carrega sem conversao nenhuma.
34
+
35
+ Bonus pra fase 3: o export pra NPU ja exigia SDPA decomposto no lugar do
36
+ nn.MultiheadAttention, entao treino e export passam a usar o mesmo caminho.
37
+ """
38
+
39
+ def __init__(self, c: GPTConfig):
40
+ super().__init__()
41
+ assert c.n_embd % c.n_head == 0
42
+ self.n_head = c.n_head
43
+ self.n_embd = c.n_embd
44
+ self.p_drop = c.dropout
45
+ self.in_proj_weight = nn.Parameter(torch.empty(3 * c.n_embd, c.n_embd))
46
+ self.in_proj_bias = nn.Parameter(torch.zeros(3 * c.n_embd))
47
+ self.out_proj = nn.Linear(c.n_embd, c.n_embd)
48
+ nn.init.xavier_uniform_(self.in_proj_weight) # mesmo init do MultiheadAttention
49
+
50
+ def forward(self, x):
51
+ B, T, C = x.shape
52
+ qkv = F.linear(x, self.in_proj_weight, self.in_proj_bias)
53
+ q, k, v = qkv.chunk(3, dim=-1)
54
+ hs = C // self.n_head
55
+ q = q.view(B, T, self.n_head, hs).transpose(1, 2)
56
+ k = k.view(B, T, self.n_head, hs).transpose(1, 2)
57
+ v = v.view(B, T, self.n_head, hs).transpose(1, 2)
58
+ y = F.scaled_dot_product_attention(
59
+ q, k, v, is_causal=True,
60
+ dropout_p=self.p_drop if self.training else 0.0)
61
+ y = y.transpose(1, 2).contiguous().view(B, T, C)
62
+ return self.out_proj(y)
63
+
64
+
65
+ class Block(nn.Module):
66
+ def __init__(self, c: GPTConfig):
67
+ super().__init__()
68
+ self.ln1 = nn.LayerNorm(c.n_embd)
69
+ self.attn = CausalSelfAttention(c)
70
+ self.ln2 = nn.LayerNorm(c.n_embd)
71
+ self.mlp = nn.Sequential(
72
+ nn.Linear(c.n_embd, 4 * c.n_embd),
73
+ nn.GELU(),
74
+ nn.Linear(4 * c.n_embd, c.n_embd),
75
+ nn.Dropout(c.dropout),
76
+ )
77
+
78
+ def forward(self, x):
79
+ x = x + self.attn(self.ln1(x))
80
+ x = x + self.mlp(self.ln2(x))
81
+ return x
82
+
83
+
84
+ class GPT(nn.Module):
85
+ def __init__(self, c: GPTConfig):
86
+ super().__init__()
87
+ self.c = c
88
+ self.tok = nn.Embedding(c.vocab_size, c.n_embd)
89
+ self.pos = nn.Embedding(c.block_size, c.n_embd)
90
+ self.drop = nn.Dropout(c.dropout)
91
+ self.blocks = nn.ModuleList([Block(c) for _ in range(c.n_layer)])
92
+ self.lnf = nn.LayerNorm(c.n_embd)
93
+ self.head = nn.Linear(c.n_embd, c.vocab_size, bias=False)
94
+ self.tok.weight = self.head.weight # weight tying
95
+ self.apply(self._init)
96
+
97
+ def _init(self, m):
98
+ if isinstance(m, nn.Linear):
99
+ nn.init.normal_(m.weight, mean=0.0, std=0.02)
100
+ if m.bias is not None:
101
+ nn.init.zeros_(m.bias)
102
+ elif isinstance(m, nn.Embedding):
103
+ nn.init.normal_(m.weight, mean=0.0, std=0.02)
104
+
105
+ def num_params(self) -> int:
106
+ return sum(p.numel() for p in self.parameters())
107
+
108
+ def forward(self, idx, targets=None):
109
+ T = idx.size(1)
110
+ pos = torch.arange(T, device=idx.device)
111
+ x = self.drop(self.tok(idx) + self.pos(pos))
112
+ for b in self.blocks:
113
+ x = b(x)
114
+ x = self.lnf(x)
115
+ logits = self.head(x)
116
+ loss = None
117
+ if targets is not None:
118
+ # reshape, nao view: o chamador costuma passar uma FATIA (lote[:, 1:]),
119
+ # que nao e contigua, e view falha nesse caso
120
+ loss = F.cross_entropy(logits.reshape(-1, logits.size(-1)),
121
+ targets.reshape(-1))
122
+ return logits, loss
123
+
124
+ @torch.no_grad()
125
+ def generate(self, idx, max_new_tokens, temperature=0.8, top_k=40):
126
+ self.eval()
127
+ for _ in range(max_new_tokens):
128
+ cond = idx[:, -self.c.block_size:]
129
+ logits, _ = self(cond)
130
+ logits = logits[:, -1, :] / temperature
131
+ if top_k:
132
+ v, _ = torch.topk(logits, min(top_k, logits.size(-1)))
133
+ logits[logits < v[:, [-1]]] = -float("inf")
134
+ probs = F.softmax(logits, dim=-1)
135
+ nxt = torch.multinomial(probs, num_samples=1)
136
+ idx = torch.cat((idx, nxt), dim=1)
137
+ return idx