MarxistLeninist commited on
Commit
961f534
·
verified ·
1 Parent(s): eae6787

Upload model.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. model.py +214 -0
model.py ADDED
@@ -0,0 +1,214 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Binary Looped Transformer-Mamba Hybrid LM (small demonstrator).
3
+
4
+ Design, in the spirit of Scott's AGILLM experiments but tiny enough to train
5
+ live on a laptop RTX 2060:
6
+
7
+ * Hybrid stack alternating two block types:
8
+ - SSMBlock: a Mamba-style *selective* state-space block written in pure
9
+ PyTorch (no mamba-ssm / CUDA kernels). Delta, B and C are
10
+ input-dependent ("selective"); A is a learned diagonal matrix.
11
+ The recurrence h_t = a_t * h_{t-1} + u_t is evaluated exactly with a
12
+ parallel associative (prefix) scan, O(log T) sequential steps.
13
+ - LoopedTransformerBlock: ONE transformer block whose weights are
14
+ shared and applied R times in a row (the "internal reasoning" loop).
15
+ Every linear layer inside it is a BinaryLinear.
16
+ * BinaryLinear: forward uses W_eff = alpha * sign(W) with per-row scale
17
+ alpha = mean(|W|); gradients reach the latent full-precision W through a
18
+ straight-through estimator (STE). So the looped transformer's matmuls are
19
+ genuinely 1-bit (plus a scale), while training keeps latent fp weights.
20
+ * Byte-level LM: vocab = 256 raw UTF-8 bytes, no tokenizer to train.
21
+
22
+ Everything else (embeddings, SSM projections, LM head) stays full precision.
23
+ """
24
+
25
+ import math
26
+ import torch
27
+ import torch.nn as nn
28
+ import torch.nn.functional as F
29
+
30
+
31
+ # --------------------------------------------------------------------------
32
+ # Binary linear (sign weights + STE)
33
+ # --------------------------------------------------------------------------
34
+ class BinaryLinear(nn.Module):
35
+ def __init__(self, in_features, out_features, bias=True):
36
+ super().__init__()
37
+ self.in_features = in_features
38
+ self.out_features = out_features
39
+ self.weight = nn.Parameter(torch.empty(out_features, in_features))
40
+ nn.init.kaiming_uniform_(self.weight, a=math.sqrt(5))
41
+ if bias:
42
+ self.bias = nn.Parameter(torch.zeros(out_features))
43
+ else:
44
+ self.bias = None
45
+
46
+ def forward(self, x):
47
+ w = self.weight
48
+ alpha = w.abs().mean(dim=1, keepdim=True) # per-row scale
49
+ w_bin = alpha * torch.sign(w) # 1-bit weights
50
+ w_eff = w + (w_bin - w).detach() # STE
51
+ return F.linear(x, w_eff, self.bias)
52
+
53
+
54
+ # --------------------------------------------------------------------------
55
+ # Selective SSM (Mamba-style) with exact parallel associative scan
56
+ # --------------------------------------------------------------------------
57
+ def associative_scan(a, u):
58
+ """h_t = a_t * h_{t-1} + u_t with h_{-1} = 0.
59
+ a, u: (B, T, D, N). Returns h: (B, T, D, N). Exact, via prefix doubling."""
60
+ A, U = a, u
61
+ T = a.size(1)
62
+ shift = 1
63
+ while shift < T:
64
+ A_new = A[:, shift:] * A[:, :-shift]
65
+ U_new = A[:, shift:] * U[:, :-shift] + U[:, shift:]
66
+ A = torch.cat([A[:, :shift], A_new], dim=1)
67
+ U = torch.cat([U[:, :shift], U_new], dim=1)
68
+ shift *= 2
69
+ return U
70
+
71
+
72
+ class SSMBlock(nn.Module):
73
+ """Simplified Mamba-1 block: gated selective SSM, pure PyTorch."""
74
+
75
+ def __init__(self, d_model, d_inner=384, d_state=8, d_conv=4, dt_rank=16):
76
+ super().__init__()
77
+ self.d_inner = d_inner
78
+ self.d_state = d_state
79
+ self.norm = nn.RMSNorm(d_model)
80
+ self.in_proj = nn.Linear(d_model, 2 * d_inner, bias=False)
81
+ self.conv1d = nn.Conv1d(d_inner, d_inner, d_conv, padding=d_conv - 1,
82
+ groups=d_inner, bias=True)
83
+ self.x_proj = nn.Linear(d_inner, dt_rank + 2 * d_state, bias=False)
84
+ self.dt_proj = nn.Linear(dt_rank, d_inner, bias=True)
85
+ # dt bias init: softplus(bias) spread over ~[0.001, 0.1]
86
+ dt = torch.exp(torch.rand(d_inner) * (math.log(0.1) - math.log(0.001))
87
+ + math.log(0.001))
88
+ inv_dt = dt + torch.log(-torch.expm1(-dt))
89
+ with torch.no_grad():
90
+ self.dt_proj.bias.copy_(inv_dt)
91
+ # A: diagonal, negative, S4D-style init A_n = n+1 stored in log space
92
+ A = torch.arange(1, d_state + 1, dtype=torch.float32)
93
+ self.A_log = nn.Parameter(torch.log(A).repeat(d_inner, 1))
94
+ self.D = nn.Parameter(torch.ones(d_inner))
95
+ self.out_proj = nn.Linear(d_inner, d_model, bias=False)
96
+
97
+ def forward(self, x):
98
+ residual = x
99
+ x = self.norm(x)
100
+ xz = self.in_proj(x) # (B, T, 2*d_inner)
101
+ x_, z = xz.chunk(2, dim=-1)
102
+ # depthwise causal conv over time
103
+ x_ = self.conv1d(x_.transpose(1, 2))[:, :, :x.size(1)].transpose(1, 2)
104
+ x_ = F.silu(x_)
105
+ # selective parameters (computed in fp32 for scan stability)
106
+ dtbc = self.x_proj(x_)
107
+ dt_r, Bv, Cv = torch.split(
108
+ dtbc, [self.dt_proj.in_features, self.d_state, self.d_state], dim=-1)
109
+ dt = F.softplus(self.dt_proj(dt_r.float())) # (B,T,d_inner)
110
+ A = -torch.exp(self.A_log.float()) # (d_inner, N)
111
+ a = torch.exp(dt.unsqueeze(-1) * A) # (B,T,d_inner,N)
112
+ u = (dt.unsqueeze(-1) * Bv.float().unsqueeze(2)) * x_.float().unsqueeze(-1)
113
+ h = associative_scan(a, u) # (B,T,d_inner,N)
114
+ y = (h * Cv.float().unsqueeze(2)).sum(-1) # (B,T,d_inner)
115
+ y = y + self.D.float() * x_.float()
116
+ y = (y * F.silu(z.float())).to(residual.dtype)
117
+ return residual + self.out_proj(y)
118
+
119
+
120
+ # --------------------------------------------------------------------------
121
+ # Looped (weight-shared) transformer block with binary linears
122
+ # --------------------------------------------------------------------------
123
+ class LoopedTransformerBlock(nn.Module):
124
+ """A single transformer block applied `loops` times with shared weights.
125
+ Each application is one 'internal reasoning' iteration. All of its linear
126
+ layers are BinaryLinear (1-bit forward weights, STE training)."""
127
+
128
+ def __init__(self, d_model, n_head=8, mlp_ratio=4, loops=3):
129
+ super().__init__()
130
+ assert d_model % n_head == 0
131
+ self.n_head = n_head
132
+ self.head_dim = d_model // n_head
133
+ self.loops = loops
134
+ self.norm1 = nn.RMSNorm(d_model)
135
+ self.qkv = BinaryLinear(d_model, 3 * d_model, bias=False)
136
+ self.attn_out = BinaryLinear(d_model, d_model, bias=False)
137
+ self.norm2 = nn.RMSNorm(d_model)
138
+ self.fc1 = BinaryLinear(d_model, mlp_ratio * d_model, bias=False)
139
+ self.fc2 = BinaryLinear(mlp_ratio * d_model, d_model, bias=False)
140
+
141
+ def _apply_once(self, x):
142
+ B, T, D = x.shape
143
+ h = self.norm1(x)
144
+ q, k, v = self.qkv(h).chunk(3, dim=-1)
145
+ q = q.view(B, T, self.n_head, self.head_dim).transpose(1, 2)
146
+ k = k.view(B, T, self.n_head, self.head_dim).transpose(1, 2)
147
+ v = v.view(B, T, self.n_head, self.head_dim).transpose(1, 2)
148
+ att = F.scaled_dot_product_attention(q, k, v, is_causal=True)
149
+ att = att.transpose(1, 2).reshape(B, T, D)
150
+ x = x + self.attn_out(att)
151
+ h = self.norm2(x)
152
+ x = x + self.fc2(F.gelu(self.fc1(h)))
153
+ return x
154
+
155
+ def forward(self, x):
156
+ for _ in range(self.loops):
157
+ x = self._apply_once(x)
158
+ return x
159
+
160
+
161
+ # --------------------------------------------------------------------------
162
+ # Full hybrid LM
163
+ # --------------------------------------------------------------------------
164
+ class BinaryLoopHybridLM(nn.Module):
165
+ def __init__(self, vocab_size=256, d_model=256, seq_len=256,
166
+ n_ssm=3, n_loop_blocks=3, loops=3, n_head=8,
167
+ d_inner=384, d_state=8):
168
+ super().__init__()
169
+ self.seq_len = seq_len
170
+ self.loops = loops
171
+ self.tok_emb = nn.Embedding(vocab_size, d_model)
172
+ self.pos_emb = nn.Embedding(seq_len, d_model)
173
+ blocks = []
174
+ for i in range(max(n_ssm, n_loop_blocks)):
175
+ if i < n_ssm:
176
+ blocks.append(SSMBlock(d_model, d_inner=d_inner,
177
+ d_state=d_state))
178
+ if i < n_loop_blocks:
179
+ blocks.append(LoopedTransformerBlock(
180
+ d_model, n_head=n_head, loops=loops))
181
+ self.blocks = nn.ModuleList(blocks)
182
+ self.norm_f = nn.RMSNorm(d_model)
183
+ self.lm_head = nn.Linear(d_model, vocab_size, bias=False)
184
+ self.lm_head.weight = self.tok_emb.weight # tied embeddings
185
+
186
+ def forward(self, idx):
187
+ B, T = idx.shape
188
+ pos = torch.arange(T, device=idx.device)
189
+ x = self.tok_emb(idx) + self.pos_emb(pos).unsqueeze(0)
190
+ for blk in self.blocks:
191
+ if isinstance(blk, SSMBlock):
192
+ x = torch.utils.checkpoint.checkpoint(
193
+ blk, x, use_reentrant=False)
194
+ else:
195
+ x = blk(x)
196
+ x = self.norm_f(x)
197
+ return self.lm_head(x)
198
+
199
+ @torch.no_grad()
200
+ def generate(self, prompt_ids, n_new, device):
201
+ self.eval()
202
+ ids = list(prompt_ids)
203
+ for _ in range(n_new):
204
+ ctx = torch.tensor([ids[-self.seq_len:]], dtype=torch.long,
205
+ device=device)
206
+ logits = self(ctx)[0, -1]
207
+ nxt = int(torch.argmax(logits).item())
208
+ ids.append(nxt)
209
+ self.train()
210
+ return ids
211
+
212
+
213
+ def count_params(model):
214
+ return sum(p.numel() for p in model.parameters())