mini-transformer 0.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of mini-transformer might be problematic. Click here for more details.

@@ -0,0 +1,17 @@
1
+ from .layer import (
2
+ RMSNorm,
3
+ MLA,
4
+ GQA,
5
+ MLP,
6
+ Block,
7
+ Transformer
8
+ )
9
+
10
+ __all__ = [
11
+ 'RMSNorm',
12
+ 'MLA',
13
+ 'GQA',
14
+ 'MLP',
15
+ 'Block',
16
+ 'Transformer',
17
+ ]
@@ -0,0 +1,366 @@
1
+ import torch
2
+ import torch.nn as nn
3
+ from einops import rearrange, repeat
4
+
5
+
6
+ class RMSNorm(nn.Module):
7
+ """
8
+ https://arxiv.org/abs/1910.07467
9
+
10
+ """
11
+
12
+ def __init__(self,
13
+ dim: int = 512,
14
+ eps: float = 1e-6
15
+ ):
16
+ super().__init__()
17
+ self.dim = dim
18
+ self.eps = eps
19
+ self.weight = nn.Parameter(torch.ones(dim))
20
+
21
+ def forward(self, x: torch.Tensor):
22
+ return nn.functional.rms_norm(x, (self.dim, ), self.weight, self.eps)
23
+
24
+
25
+ def precompute_rope_emb(dim: int = 16, seq_len: int = 512 * 8, theta: float = 10000.0):
26
+ freqs = 1.0 / (theta ** (torch.arange(0, dim, 2, dtype = torch.float32) / dim))
27
+ t = torch.arange(seq_len)
28
+ freqs = torch.outer(t, freqs)
29
+ rope_emb = torch.polar(torch.ones_like(freqs), freqs)
30
+ return rope_emb
31
+
32
+
33
+ def apply_rope_emb(x: torch.Tensor, rope_emb: torch.Tensor):
34
+ dtype = x.dtype
35
+ x = torch.view_as_complex(x.float().view(*x.shape[:-1], -1, 2))
36
+ rope_emb = rope_emb.view(1, x.shape[1], 1, x.shape[-1])
37
+ y = torch.view_as_real(x * rope_emb).flatten(3)
38
+ return y.to(dtype)
39
+
40
+
41
+ class MLA(nn.Module):
42
+ """
43
+ https://arxiv.org/abs/2412.19437
44
+
45
+ """
46
+
47
+ def __init__(self,
48
+ dim: int = 512,
49
+ n_head: int = 8,
50
+ q_lora_rank: int = 0,
51
+ kv_lora_rank: int = 128,
52
+ qk_nope_head_dim: int = 32,
53
+ qk_rope_head_dim: int = 16,
54
+ v_head_dim: int = 32,
55
+ max_batch_size: int = 32,
56
+ max_seq_len: int = 512 * 8
57
+ ):
58
+ super().__init__()
59
+ self.dim = dim
60
+ self.n_head = n_head
61
+ self.q_lora_rank = q_lora_rank
62
+ self.kv_lora_rank = kv_lora_rank
63
+ self.qk_nope_head_dim = qk_nope_head_dim
64
+ self.qk_rope_head_dim = qk_rope_head_dim
65
+ self.qk_head_dim = qk_nope_head_dim + qk_rope_head_dim
66
+ self.v_head_dim = v_head_dim
67
+ self.max_batch_size = max_batch_size
68
+ self.max_seq_len = max_seq_len
69
+
70
+ if self.q_lora_rank == 0:
71
+ self.to_q = nn.Linear(self.dim, self.n_head * self.qk_head_dim, bias = False)
72
+ else:
73
+ self.to_q = nn.Sequential(
74
+ nn.Linear(self.dim, self.q_lora_rank, bias = False),
75
+ RMSNorm(self.q_lora_rank),
76
+ nn.Linear(self.q_lora_rank, self.n_head * self.qk_head_dim, bias = False)
77
+ )
78
+ self.to_kv_a = nn.Linear(self.dim, qk_rope_head_dim + kv_lora_rank, bias = False)
79
+ self.kv_norm = RMSNorm(self.kv_lora_rank)
80
+ self.to_kv_b = nn.Linear(self.kv_lora_rank, self.n_head * (self.qk_nope_head_dim + self.v_head_dim),
81
+ bias = False)
82
+ self.to_out = nn.Linear(self.n_head * self.v_head_dim, self.dim, bias = False)
83
+
84
+ self.register_buffer('k_cache',
85
+ torch.zeros(self.max_batch_size, self.max_seq_len, self.n_head, self.qk_head_dim),
86
+ persistent = False
87
+ )
88
+ self.register_buffer('v_cache',
89
+ torch.zeros(self.max_batch_size, self.max_seq_len, self.n_head, self.v_head_dim),
90
+ persistent = False
91
+ )
92
+
93
+ def forward(self,
94
+ x: torch.Tensor,
95
+ start_pos: int,
96
+ rope_emb: torch.Tensor,
97
+ mask: torch.Tensor = None,
98
+ use_cache: bool = False
99
+ ):
100
+ # x:[b, n, d]
101
+ b, n, _ = x.shape
102
+ end_pos = start_pos + n
103
+ # q
104
+ q = self.to_q(x)
105
+ q = rearrange(q, 'b n (h d) -> b n h d', h = self.n_head)
106
+ q_nope, q_rope = q.split((self.qk_nope_head_dim, self.qk_rope_head_dim), dim = -1)
107
+ q_rope = apply_rope_emb(q_rope, rope_emb)
108
+ # kv
109
+ kv = self.to_kv_a(x)
110
+ k_rope, kv = kv.split((self.qk_rope_head_dim, self.kv_lora_rank), dim = -1)
111
+ k_rope = apply_rope_emb(k_rope.unsqueeze(2), rope_emb)
112
+ # attn
113
+ q = torch.cat((q_nope, q_rope), dim = -1)
114
+ kv = self.to_kv_b(self.kv_norm(kv))
115
+ kv = rearrange(kv, 'b n (h d) -> b n h d', h = self.n_head)
116
+ k_nope, v = kv.split((self.qk_nope_head_dim, self.v_head_dim), dim = -1)
117
+ k = torch.cat((k_nope, k_rope.expand(-1, -1, self.n_head, -1)), dim = -1)
118
+ if use_cache:
119
+ self.k_cache[:b, start_pos:end_pos] = k
120
+ self.v_cache[:b, start_pos:end_pos] = v
121
+ k = self.k_cache[:b, :end_pos]
122
+ v = self.v_cache[:b, :end_pos]
123
+ q, k, v = map(lambda t: rearrange(t, 'b n h d -> b h n d'), (q, k, v))
124
+ attn = torch.matmul(q, k.transpose(-2, -1)) * (self.qk_head_dim ** -0.5)
125
+ # mask
126
+ if mask is not None:
127
+ attn += mask
128
+ attn = torch.softmax(attn, dim = -1)
129
+ # out
130
+ out = torch.matmul(attn, v)
131
+ out = rearrange(out, 'b h n d -> b n (h d)')
132
+ out = self.to_out(out)
133
+ return out
134
+
135
+
136
+ class GQA(nn.Module):
137
+ """
138
+ https://arxiv.org/abs/2305.13245
139
+
140
+ """
141
+
142
+ def __init__(self,
143
+ dim: int = 512,
144
+ n_head: int = 8,
145
+ n_kv_head: int = 2,
146
+ dropout: float = 0.0,
147
+ max_batch_size: int = 32,
148
+ max_seq_len: int = 512 * 8
149
+ ):
150
+ super().__init__()
151
+ self.dim = dim
152
+ self.n_head = n_head
153
+ self.head_dim = self.dim // self.n_head
154
+ self.n_kv_head = n_kv_head
155
+ self.dropout = dropout
156
+ self.max_batch_size = max_batch_size
157
+ self.max_seq_len = max_seq_len
158
+
159
+ self.to_q = nn.Linear(self.dim, self.n_head * self.head_dim, bias = False)
160
+ self.to_kv = nn.Linear(self.dim, 2 * self.n_kv_head * self.head_dim, bias = False)
161
+ self.to_out = nn.Linear(self.n_head * self.head_dim, self.dim, bias=False)
162
+ self.dropout = nn.Dropout(self.dropout)
163
+
164
+ self.register_buffer('k_cache',
165
+ torch.zeros(self.max_batch_size, self.max_seq_len, self.n_head, self.head_dim),
166
+ persistent=False
167
+ )
168
+ self.register_buffer('v_cache',
169
+ torch.zeros(self.max_batch_size, self.max_seq_len, self.n_head, self.head_dim),
170
+ persistent=False
171
+ )
172
+
173
+ def forward(self,
174
+ x: torch.Tensor,
175
+ start_pos: int,
176
+ rope_emb: torch.Tensor,
177
+ mask: torch.Tensor = None,
178
+ use_cache: bool = False
179
+ ):
180
+ # x:[b, n, d]
181
+ b, n, _ = x.shape
182
+ end_pos = start_pos + n
183
+ # q, k, v
184
+ q = self.to_q(x)
185
+ k, v = self.to_kv(x).chunk(2, dim = -1)
186
+ q = rearrange(q, 'b n (h d) -> b n h d', h = self.n_head)
187
+ k, v = map(lambda t: rearrange(t, 'b n (h d) -> b n h d', h = self.n_kv_head), (k, v))
188
+ q, k = map(lambda t: apply_rope_emb(t, rope_emb), (q, k))
189
+ if use_cache:
190
+ self.k_cache[:b, start_pos:end_pos] = k
191
+ self.v_cache[:b, start_pos:end_pos] = v
192
+ k = self.k_cache[:b, :end_pos]
193
+ v = self.v_cache[:b, :end_pos]
194
+ k, v = map(lambda t: repeat(t, 'b n h d -> b n (r h) d', r = self.n_head // self.n_kv_head), (k, v))
195
+ q, k, v = map(lambda t: rearrange(t, 'b n h d -> b h n d'), (q, k, v))
196
+ # attn
197
+ attn = torch.matmul(q, k.transpose(-2, -1)) * (self.head_dim ** -0.5)
198
+ # mask
199
+ if mask is not None:
200
+ attn += mask
201
+ attn = torch.softmax(attn, dim=-1)
202
+ attn = self.dropout(attn)
203
+ # out
204
+ out = torch.matmul(attn, v)
205
+ out = rearrange(out, 'b h n d -> b n (h d)')
206
+ out = self.to_out(out)
207
+ return out
208
+
209
+
210
+ class MLP(nn.Module):
211
+
212
+ def __init__(self,
213
+ dim: int = 512,
214
+ inter_dim: int = 1344
215
+ ):
216
+ super().__init__()
217
+ self.dim = dim
218
+ self.inter_dim = inter_dim
219
+
220
+ self.linear1 = nn.Linear(self.dim, self.inter_dim, bias = False)
221
+ self.linear2 = nn.Linear(self.inter_dim, self.dim, bias = False)
222
+ self.linear3 = nn.Linear(self.dim, self.inter_dim, bias = False)
223
+ self.silu = nn.SiLU()
224
+
225
+ def forward(self, x: torch.Tensor):
226
+ return self.linear2(self.silu(self.linear1(x)) * self.linear3(x))
227
+
228
+
229
+ class Block(nn.Module):
230
+
231
+ def __init__(self,
232
+ # MLA
233
+ dim: int = 512,
234
+ inter_dim: int = 1344,
235
+ n_head: int = 8,
236
+ q_lora_rank: int = 0,
237
+ kv_lora_rank: int = 128,
238
+ qk_nope_head_dim: int = 32,
239
+ qk_rope_head_dim: int = 16,
240
+ v_head_dim: int = 32,
241
+ # GQA
242
+ n_kv_head: int = 2,
243
+ dropout: float = 0.0,
244
+ # common
245
+ max_batch_size: int = 32,
246
+ max_seq_len: int = 512 * 8,
247
+ attn_name = 'mla',
248
+ mlp_name = 'mlp'
249
+ ):
250
+ super().__init__()
251
+
252
+ if attn_name == 'MLA' or attn_name == 'mla':
253
+ self.attn = MLA(dim = dim, n_head = n_head, q_lora_rank = q_lora_rank, kv_lora_rank = kv_lora_rank,
254
+ qk_nope_head_dim = qk_nope_head_dim, qk_rope_head_dim = qk_rope_head_dim,
255
+ v_head_dim = v_head_dim, max_batch_size = max_batch_size, max_seq_len = max_seq_len)
256
+ elif attn_name == 'GQA' or attn_name == 'gqa':
257
+ self.attn = GQA(dim = dim, n_head = n_head, n_kv_head = n_kv_head, dropout = dropout,
258
+ max_batch_size = max_batch_size, max_seq_len = max_seq_len)
259
+ else:
260
+ raise ValueError('attn_name must be MLA or GQA')
261
+
262
+ if mlp_name == 'mlp':
263
+ self.mlp = MLP(dim = dim, inter_dim = inter_dim)
264
+ else:
265
+ raise ValueError('mlp_name must be mlp')
266
+
267
+ self.attn_norm = RMSNorm(dim)
268
+ self.mlp_norm = RMSNorm(dim)
269
+
270
+ def forward(self,
271
+ x: torch.Tensor,
272
+ start_pos: int,
273
+ rope_emb: torch.Tensor,
274
+ mask: torch.Tensor = None,
275
+ use_cache: bool = False
276
+ ):
277
+ x = x + self.attn(self.attn_norm(x), start_pos, rope_emb, mask = mask, use_cache = use_cache)
278
+ x = x + self.mlp(self.mlp_norm(x))
279
+ return x
280
+
281
+
282
+ class Transformer(nn.Module):
283
+
284
+ def __init__(self,
285
+ # embedding
286
+ vocab_size: int = 6400,
287
+ # MLA
288
+ dim: int = 512,
289
+ inter_dim: int = 1344,
290
+ n_head: int = 8,
291
+ q_lora_rank: int = 0,
292
+ kv_lora_rank: int = 128,
293
+ qk_nope_head_dim: int = 32,
294
+ qk_rope_head_dim: int = 16,
295
+ v_head_dim: int = 32,
296
+ # GQA
297
+ n_kv_head: int = 2,
298
+ dropout: float = 0.0,
299
+ # Transformer
300
+ n_layer: int = 8,
301
+ # common
302
+ max_batch_size: int = 32,
303
+ max_seq_len: int = 512 * 8,
304
+ attn_name='mla',
305
+ mlp_name='mlp'
306
+ ):
307
+ super().__init__()
308
+
309
+ self.token_embedding = nn.Embedding(vocab_size, dim)
310
+
311
+ self.transformer = nn.ModuleList([
312
+ Block(dim=dim, inter_dim=inter_dim, n_head=n_head, q_lora_rank=q_lora_rank,
313
+ kv_lora_rank=kv_lora_rank, qk_nope_head_dim=qk_nope_head_dim, qk_rope_head_dim=qk_rope_head_dim,
314
+ v_head_dim=v_head_dim, n_kv_head=n_kv_head, dropout=dropout, max_batch_size=max_batch_size,
315
+ max_seq_len=max_seq_len, attn_name=attn_name, mlp_name=mlp_name)
316
+ for _ in range(n_layer)
317
+ ])
318
+
319
+ self.out_norm = RMSNorm(dim)
320
+ self.to_out = nn.Linear(dim, vocab_size, bias = False)
321
+
322
+ self.register_buffer('rope_emb',
323
+ precompute_rope_emb(dim = qk_rope_head_dim, seq_len = max_seq_len) if attn_name == 'mla'
324
+ else precompute_rope_emb(dim = dim // n_head, seq_len = max_seq_len),
325
+ persistent = False
326
+ )
327
+
328
+ def forward(self,
329
+ x: torch.Tensor,
330
+ start_pos: int,
331
+ mask: torch.Tensor = None,
332
+ use_cache: bool = False
333
+ ):
334
+ # x:[b, n]
335
+ b, n = x.shape
336
+ end_pos = start_pos + n
337
+ # embedding
338
+ x = self.token_embedding(x)
339
+ rope_emb = self.rope_emb[start_pos: end_pos]
340
+ # transformer
341
+ for layer in self.transformer:
342
+ x = layer(x, start_pos, rope_emb, mask = mask, use_cache = use_cache)
343
+ out = self.to_out(self.out_norm(x))
344
+ return out
345
+
346
+
347
+ if __name__ == '__main__':
348
+ data = torch.randint(0, 6400, (2, 512))
349
+
350
+ mask = torch.triu(torch.full((512, 512), float('-inf')), 1)
351
+
352
+ model = Transformer(attn_name = 'mla')
353
+ total_param = 0
354
+ for param in model.parameters():
355
+ if param.requires_grad:
356
+ total_param += param.numel()
357
+ print(total_param)
358
+ model(data, 0, mask = mask)
359
+
360
+ model = Transformer(attn_name='gqa')
361
+ total_param = 0
362
+ for param in model.parameters():
363
+ if param.requires_grad:
364
+ total_param += param.numel()
365
+ print(total_param)
366
+ model(data, 0, mask = mask)
@@ -0,0 +1,20 @@
1
+ Metadata-Version: 2.4
2
+ Name: mini_transformer
3
+ Version: 0.0.1
4
+ Summary: An advanced minimal transformer component framework
5
+ Project-URL: Repository, https://github.com/LemonAttn/mini_transformer
6
+ Author-email: ztw <1837669410@qq.com>
7
+ License: MIT
8
+ License-File: LICENSE
9
+ Keywords: GQA,MLA,artificial intelligence,attention mechanism,deep learning,rotary embedding,transformer
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: License :: OSI Approved :: MIT License
13
+ Classifier: Programming Language :: Python :: 3.10
14
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
15
+ Requires-Python: >=3.10
16
+ Requires-Dist: einops>=0.8.1
17
+ Requires-Dist: numpy>=2.2.4
18
+ Description-Content-Type: text/markdown
19
+
20
+ # mini_transformer
@@ -0,0 +1,6 @@
1
+ mini_transformer/__init__.py,sha256=A2hSk9xJNU4XqO73NTxZHc1WSLcbXF4Skhy1HqMOsU0,200
2
+ mini_transformer/layer.py,sha256=vkzKo96fuGPu91PxmWUmtaglX9RiRmSC1F-xr3ryRig,13830
3
+ mini_transformer-0.0.1.dist-info/METADATA,sha256=chxZn2-qnHCoYCXxY3Zj75uK8YSwiUW1rp2xDfidVD0,770
4
+ mini_transformer-0.0.1.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
5
+ mini_transformer-0.0.1.dist-info/licenses/LICENSE,sha256=1AcUpYDXxKYgu9JbDYm5AwWSHxGN7BTXZp0Ad4bRhUA,1081
6
+ mini_transformer-0.0.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.27.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 ztw
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.