vukrosic commited on
Commit
d63cd68
·
verified ·
1 Parent(s): d3497b5

Upload modeling_nano_proofread.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. modeling_nano_proofread.py +179 -0
modeling_nano_proofread.py ADDED
@@ -0,0 +1,179 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Self-contained nano-proofread model — no dependencies beyond torch + safetensors.
2
+
3
+ A ~1M-parameter byte-level decoder-only transformer (RMSNorm, RoPE, GQA, SwiGLU)
4
+ that fixes common, CONTEXT-DEPENDENT writing errors: `their going to win` ->
5
+ `they're going to win`, `its raining` -> `it's raining`, `the the cat` -> `the cat`.
6
+ Which of `their/there/they're` (etc.) is right depends on the surrounding words — a
7
+ lookup table can't tell, but the model reads the context. This single file vendors the
8
+ exact architecture the model was trained with, so you can load and run the published
9
+ weights without the training lab.
10
+
11
+ python modeling_nano_proofread.py # runs a few examples
12
+ # or, from your own code:
13
+ from modeling_nano_proofread import load, proofread
14
+ m = load("model.safetensors", "config.json")
15
+ print(proofread(m, "their going to win")) # -> they're going to win
16
+ print(proofread(m, "its raining again")) # -> it's raining again
17
+
18
+ Prompt format the model was trained on (byte-for-byte):
19
+
20
+ <phrase with an error> => <corrected phrase><newline>
21
+
22
+ The answer ends at the first newline (byte 10), the supervised EOS — `proofread()`
23
+ decodes a fixed budget and cuts there.
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ import json
29
+
30
+ import torch
31
+ import torch.nn as nn
32
+ import torch.nn.functional as F
33
+
34
+
35
+ class RMSNorm(nn.Module):
36
+ def __init__(self, dim: int, eps: float = 1e-5):
37
+ super().__init__()
38
+ self.eps = eps
39
+ self.weight = nn.Parameter(torch.ones(dim))
40
+
41
+ def forward(self, x):
42
+ rms = x.float().pow(2).mean(-1, keepdim=True).add(self.eps).rsqrt()
43
+ return (x.float() * rms).type_as(x) * self.weight
44
+
45
+
46
+ class RoPE(nn.Module):
47
+ def __init__(self, head_dim: int, max_seq_len: int, theta: float = 10000.0):
48
+ super().__init__()
49
+ inv_freq = 1.0 / (theta ** (torch.arange(0, head_dim, 2).float() / head_dim))
50
+ freqs = torch.outer(torch.arange(max_seq_len).float(), inv_freq)
51
+ self.register_buffer("cos", freqs.cos(), persistent=False)
52
+ self.register_buffer("sin", freqs.sin(), persistent=False)
53
+
54
+ def apply(self, x, offset: int = 0):
55
+ seq = x.size(-2)
56
+ cos = self.cos[offset:offset + seq]
57
+ sin = self.sin[offset:offset + seq]
58
+ x1, x2 = x[..., 0::2], x[..., 1::2]
59
+ rot1 = x1 * cos - x2 * sin
60
+ rot2 = x1 * sin + x2 * cos
61
+ return torch.stack((rot1, rot2), dim=-1).flatten(-2).type_as(x)
62
+
63
+
64
+ class GQA(nn.Module):
65
+ def __init__(self, dim, n_heads, n_kv_heads, head_dim, positional):
66
+ super().__init__()
67
+ self.n_heads, self.n_kv_heads, self.head_dim = n_heads, n_kv_heads, head_dim
68
+ self.n_rep = n_heads // n_kv_heads
69
+ self.positional = positional
70
+ self.q_proj = nn.Linear(dim, n_heads * head_dim, bias=False)
71
+ self.k_proj = nn.Linear(dim, n_kv_heads * head_dim, bias=False)
72
+ self.v_proj = nn.Linear(dim, n_kv_heads * head_dim, bias=False)
73
+ self.o_proj = nn.Linear(n_heads * head_dim, dim, bias=False)
74
+
75
+ def forward(self, x, mask):
76
+ b, seq, _ = x.shape
77
+ q = self.q_proj(x).view(b, seq, self.n_heads, self.head_dim).transpose(1, 2)
78
+ k = self.k_proj(x).view(b, seq, self.n_kv_heads, self.head_dim).transpose(1, 2)
79
+ v = self.v_proj(x).view(b, seq, self.n_kv_heads, self.head_dim).transpose(1, 2)
80
+ q = self.positional.apply(q)
81
+ k = self.positional.apply(k)
82
+ if self.n_rep > 1:
83
+ k = k.repeat_interleave(self.n_rep, dim=1)
84
+ v = v.repeat_interleave(self.n_rep, dim=1)
85
+ scores = (q @ k.transpose(-2, -1)) / (self.head_dim ** 0.5)
86
+ if mask is not None:
87
+ scores = scores + mask
88
+ out = F.softmax(scores, dim=-1) @ v
89
+ out = out.transpose(1, 2).reshape(b, seq, self.n_heads * self.head_dim)
90
+ return self.o_proj(out)
91
+
92
+
93
+ class SwiGLU(nn.Module):
94
+ def __init__(self, dim: int, hidden: int):
95
+ super().__init__()
96
+ self.gate = nn.Linear(dim, hidden, bias=False)
97
+ self.up = nn.Linear(dim, hidden, bias=False)
98
+ self.down = nn.Linear(hidden, dim, bias=False)
99
+
100
+ def forward(self, x):
101
+ return self.down(F.silu(self.gate(x)) * self.up(x))
102
+
103
+
104
+ class Block(nn.Module):
105
+ def __init__(self, cfg, positional):
106
+ super().__init__()
107
+ hidden = int(cfg["dim"] * cfg["ffn_mult"])
108
+ self.attn_norm = RMSNorm(cfg["dim"], cfg["norm_eps"])
109
+ self.attn = GQA(cfg["dim"], cfg["n_heads"], cfg["n_kv_heads"], cfg["head_dim"], positional)
110
+ self.ffn_norm = RMSNorm(cfg["dim"], cfg["norm_eps"])
111
+ self.ffn = SwiGLU(cfg["dim"], hidden)
112
+
113
+ def forward(self, x, mask):
114
+ x = x + self.attn(self.attn_norm(x), mask)
115
+ x = x + self.ffn(self.ffn_norm(x))
116
+ return x
117
+
118
+
119
+ class NanoProofread(nn.Module):
120
+ def __init__(self, cfg: dict):
121
+ super().__init__()
122
+ self.cfg = cfg
123
+ self.tok_emb = nn.Embedding(cfg["vocab_size"], cfg["dim"])
124
+ self.positional = RoPE(cfg["head_dim"], cfg["max_seq_len"], cfg["rope_theta"])
125
+ self.blocks = nn.ModuleList([Block(cfg, self.positional) for _ in range(cfg["n_layers"])])
126
+ self.final_norm = RMSNorm(cfg["dim"], cfg["norm_eps"])
127
+ self.lm_head = nn.Linear(cfg["dim"], cfg["vocab_size"], bias=False)
128
+ self.lm_head.weight = self.tok_emb.weight # tied
129
+
130
+ def forward(self, tokens):
131
+ seq = tokens.size(1)
132
+ x = self.tok_emb(tokens)
133
+ mask = torch.triu(torch.full((seq, seq), float("-inf"), device=tokens.device), diagonal=1)
134
+ for block in self.blocks:
135
+ x = block(x, mask)
136
+ return self.lm_head(self.final_norm(x))
137
+
138
+
139
+ def load(weights="model.safetensors", config="config.json", device="cpu"):
140
+ from safetensors.torch import load_file
141
+ with open(config) as f:
142
+ cfg = json.load(f)
143
+ model = NanoProofread(cfg).to(device)
144
+ sd = load_file(weights)
145
+ sd["lm_head.weight"] = sd["tok_emb.weight"] # restore tied weight
146
+ model.load_state_dict(sd)
147
+ model.eval()
148
+ return model
149
+
150
+
151
+ _EOS = 10 # newline terminates the answer
152
+
153
+
154
+ @torch.no_grad()
155
+ def proofread(model, phrase: str, device="cpu", max_new: int = 48) -> str:
156
+ """`phrase` is a short phrase that may contain one common error. Returns the
157
+ corrected phrase. Decodes greedily and stops at the newline EOS. A correct phrase
158
+ is returned unchanged (the model was trained with identity examples)."""
159
+ prompt = f"{phrase} => "
160
+ toks = torch.tensor([list(prompt.encode("utf-8"))], dtype=torch.long, device=device)
161
+ max_seq = model.cfg["max_seq_len"]
162
+ out = []
163
+ for _ in range(max_new):
164
+ nxt = int(model(toks[:, -max_seq:])[:, -1, :].argmax(-1))
165
+ if nxt == _EOS:
166
+ break
167
+ out.append(nxt)
168
+ toks = torch.cat([toks, torch.tensor([[nxt]], device=device)], dim=1)
169
+ return bytes(b & 0xFF for b in out).decode("utf-8", "replace")
170
+
171
+
172
+ if __name__ == "__main__":
173
+ m = load()
174
+ # context-dependent fixes, doubled words, and a correct phrase (left alone)
175
+ for phrase in ["their going to win", "your the best", "its raining again",
176
+ "the the cat sat", "i could of helped", "we went they're",
177
+ "this is bigger then that", "it is to late",
178
+ "they're house is big", "she is happy today"]:
179
+ print(f"{phrase:<26} -> {proofread(m, phrase)}")