model.py thing
Browse files
model.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
class MicroLM(nn.Module):
|
| 6 |
+
"""Character-level recurrent LM with exactly 500 parameters."""
|
| 7 |
+
|
| 8 |
+
def __init__(self, V=27, d=4, h=8, pad=0):
|
| 9 |
+
super().__init__()
|
| 10 |
+
self.emb = nn.Embedding(V, d)
|
| 11 |
+
self.ih = nn.Linear(d, h)
|
| 12 |
+
self.hh = nn.Linear(h, h, bias=False)
|
| 13 |
+
self.proj = nn.Linear(h, d)
|
| 14 |
+
self.out_bias = nn.Parameter(torch.zeros(V))
|
| 15 |
+
# dead-weight padding to hit the exact parameter count (unused in forward)
|
| 16 |
+
self.pad = nn.Parameter(torch.zeros(pad)) if pad > 0 else None
|
| 17 |
+
self.h = h
|
| 18 |
+
|
| 19 |
+
def forward(self, x):
|
| 20 |
+
B, T = x.shape
|
| 21 |
+
e = self.emb(x)
|
| 22 |
+
hs = torch.zeros(B, self.h, device=x.device)
|
| 23 |
+
outs = []
|
| 24 |
+
for t in range(T):
|
| 25 |
+
hs = torch.tanh(self.ih(e[:, t]) + self.hh(hs))
|
| 26 |
+
outs.append(hs)
|
| 27 |
+
z = self.proj(torch.stack(outs, dim=1))
|
| 28 |
+
return z @ self.emb.weight.T + self.out_bias # tied output layer
|