cogforge-engine 0.2.0__tar.gz → 1.0.0__tar.gz

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.
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,333 @@
1
+ Metadata-Version: 2.4
2
+ Name: cogforge-engine
3
+ Version: 1.0.0
4
+ Summary: A custom autograd engine and Transformer block built from scratch.
5
+ Project-URL: Homepage, https://github.com/avikmjd2/cogforge
6
+ Author-email: Avik Majumder <avikmjd2@gmail.com>
7
+ License-File: LICENSE
8
+ Requires-Python: >=3.8
9
+ Requires-Dist: numexpr>=2.8.0
10
+ Requires-Dist: numpy>=1.20.0
11
+ Provides-Extra: cuda
12
+ Requires-Dist: cupy>=12.0.0; extra == 'cuda'
13
+ Description-Content-Type: text/markdown
14
+
15
+ # cogforge
16
+
17
+ > A from-scratch deep learning library built on nothing but NumPy — a reverse-mode autograd engine extended all the way to a working GPT.
18
+
19
+ `cogforge` is a small, readable, educational deep learning framework. At its core is a `Tensor` that records every operation into a computation graph and backpropagates through it (micrograd-style), but unlike a toy autograd it scales up to real architectures: MLPs, RNNs, batch/layer normalization, multi-head attention, and a decoder-only transformer (`GPTV1`) you can actually train and sample from.
20
+
21
+ There is no C++, no CUDA, no PyTorch — just NumPy and explicit, hand-derived gradients. The goal is to *understand* every gradient that flows, not to be fast.
22
+
23
+ ---
24
+
25
+ ## Table of contents
26
+
27
+ - [Installation](#installation)
28
+ - [Quick start](#quick-start)
29
+ - [Core concept: the `Tensor`](#core-concept-the-tensor)
30
+ - [API reference](#api-reference)
31
+ - [Tensor — autograd engine](#tensor--autograd-engine)
32
+ - [Losses](#losses)
33
+ - [Layers](#layers)
34
+ - [Containers](#containers)
35
+ - [Recurrent](#recurrent)
36
+ - [Sequence-to-sequence](#sequence-to-sequence)
37
+ - [Optimizers](#optimizers)
38
+ - [Models](#models)
39
+ - [Worked example: train a char-level GPT](#worked-example-train-a-char-level-gpt)
40
+ - [Gotchas](#gotchas)
41
+ - [Roadmap](#roadmap)
42
+ - [License](#license)
43
+
44
+ ---
45
+
46
+ ## Installation
47
+
48
+ ```bash
49
+ pip install cogforge-engine
50
+ ```
51
+
52
+ Requires Python 3.8+ and NumPy. That's the only dependency.
53
+
54
+ The package is organized into two modules:
55
+
56
+ | Module | Contains |
57
+ | --- | --- |
58
+ | `cogforge.app` | The autograd engine (`Tensor`) and every building block — layers, optimizers, losses, normalization, attention. |
59
+ | `cogforge.models` | Ready-to-use models. Currently `GPTV1`. |
60
+
61
+ ```python
62
+ from cogforge.app import Tensor, Linear, Adam, MultiHeadAttention # building blocks
63
+ from cogforge.models import GPTV1 # models
64
+ ```
65
+
66
+ ---
67
+
68
+ ## Quick start
69
+
70
+ ```python
71
+ import numpy as np
72
+ from cogforge.app import Tensor
73
+
74
+ # Build a graph
75
+ a = Tensor(np.array([2.0, 3.0]))
76
+ b = Tensor(np.array([4.0, 5.0]))
77
+ c = (a * b).sigmoid().softmax()
78
+
79
+ # Backpropagate (note the spelling: backwards, with an 's')
80
+ c.backwards()
81
+
82
+ print(a.grad) # gradient of the output w.r.t. a
83
+ ```
84
+
85
+ Every `Tensor` carries a `.data` (the NumPy array), a `.grad` (same shape, accumulates gradients), and a hidden `_backwards` closure that knows how to push gradient to its parents. Calling `.backwards()` on any node runs a topological sort and walks the graph in reverse.
86
+
87
+ ---
88
+
89
+ ## Core concept: the `Tensor`
90
+
91
+ ```python
92
+ Tensor(array, children=(), requires_grad=True, typed="compressed")
93
+ ```
94
+
95
+ | Argument | Meaning |
96
+ | --- | --- |
97
+ | `array` | Any array-like; stored as a NumPy array in `.data`. |
98
+ | `children` | Parent tensors in the graph (set internally by ops; you rarely pass this). |
99
+ | `requires_grad` | Reserved flag (currently informational). |
100
+ | `typed` | `"compressed"` → `float32` (default), anything else → `float64`. |
101
+
102
+ Gradients **accumulate** into `.grad`. Always zero them between optimization steps (the optimizers do this for you via `zero_grad()`).
103
+
104
+ ---
105
+
106
+ ## API reference
107
+
108
+ ### Tensor — autograd engine
109
+
110
+ **Differentiable operations** (each builds graph and defines its own backward):
111
+
112
+ | Operation | Notes |
113
+ | --- | --- |
114
+ | `a + b`, `a - b`, `a * b` | Elementwise, with broadcasting support. |
115
+ | `a @ b` | Batched matmul; gradients are correctly un-broadcast. |
116
+ | `a[key]` | Indexing/slicing. |
117
+ | `.relu()` | |
118
+ | `.sigmoid()` | |
119
+ | `.tanh()` | |
120
+ | `.softmax(axis=-1)` | Numerically stable (max-subtraction). |
121
+ | `.view(shape)` | Reshape (handles non-contiguous data). |
122
+ | `.flatten()` | Flattens everything after the batch dim → `(B, -1)`. |
123
+ | `.flatten_consective(num)` | Groups `num` consecutive timesteps. Expects a 3-D `(B, T, C)` tensor; `T` must be divisible by `num`. |
124
+ | `.transpose(axes)` | Permute axes (pass the full permutation tuple). |
125
+ | `.masked_fill(mask, value)` | Sets entries where `mask` is `True` to `value` (used for causal attention). |
126
+
127
+ **Backward pass**
128
+
129
+ | Method | Notes |
130
+ | --- | --- |
131
+ | `.backwards()` | **Primary.** Iterative topological sort — safe for deep/long graphs. |
132
+ | `.backwards_recursive()` | Legacy recursive version; can hit Python's recursion limit on long sequences. Prefer `.backwards()`. |
133
+
134
+ **Static helper**
135
+
136
+ - `Tensor.unbroadcast(grad, shape)` — reduces a broadcasted gradient back to the original parameter shape. Used internally.
137
+
138
+ ---
139
+
140
+ ### Losses
141
+
142
+ All losses are **classmethods** on `Tensor` and return a scalar loss tensor you call `.backwards()` on. Mind the distinction between losses that take **probabilities** and losses that take **raw logits** — this is the most common mistake.
143
+
144
+ | Loss | Input expectation | Use when |
145
+ | --- | --- | --- |
146
+ | `Tensor.cross_entropy_loss(predictions, targets)` | `predictions` are **probabilities** (call `.softmax()` first), `targets` one-hot. | You already have a softmax in your graph. |
147
+ | `Tensor.softmax_cross_entropy(scores, targets)` | `scores` are **raw logits**, `targets` one-hot. Softmax is fused inside (stable). Works for 2-D `(B,V)` and 3-D `(B,T,V)`. | Standard classification / LM. **Recommended.** |
148
+ | `Tensor.sparse_softmax_cross_entropy(scores, target_ids)` | `scores` raw logits `(B,T,V)`, `target_ids` integers `(B,T)`. | Language modeling — skips building one-hot targets. |
149
+ | `Tensor.cross_entropy_loss_masked(predictions, targets, mask)` | Probabilities + per-row `mask` (1 = real, 0 = pad). | Padded batches. |
150
+ | `Tensor.softmax_cross_entropy_masked(scores, targets, mask)` | Logits + per-row mask. | Padded batches, fused softmax. |
151
+
152
+ > ℹ️ `softmax_cross_entropy` and `sparse_softmax_cross_entropy` apply softmax internally. Do **not** pass already-softmaxed values into them. `cross_entropy_loss` is the opposite — it expects probabilities.
153
+
154
+ ---
155
+
156
+ ### Layers
157
+
158
+ #### `Linear(nin, nout)`
159
+ Affine transform `x @ W + b`. He-initialized weights. `.parameters()` → `[W, b]`.
160
+
161
+ #### `Embedding(vocab_size, embedding_dim)`
162
+ Lookup table. Call with an integer index array; backward scatters gradients correctly (uses `np.add.at`, so repeated indices accumulate). `.parameters()` → `[weights]`.
163
+
164
+ #### `LayerNorm(dim, eps=1e-5)`
165
+ Normalizes over the last dimension. Learnable `gamma`/`beta`. `.parameters()` → `[gamma, beta]`.
166
+
167
+ #### `BatchNorm1D(dim, eps=1e-5, momentum=0.1)`
168
+ Normalizes over the batch (and time, for 3-D input). Tracks `running_mean`/`running_var` for inference. Toggle `.training = True/False`. Learnable `gamma`/`beta`.
169
+
170
+ #### `Attention(dk)`
171
+ Scaled dot-product attention. Call `attention(Q, K, V, mask=None)`. `dk` is the key dimension (sets the `1/√dk` scale).
172
+
173
+ #### `MultiHeadAttention(dinp, dmodel, dout, n)`
174
+ `n` heads, `dmodel` split into `n` chunks of size `dmodel // n` (must divide evenly). Projects input `dinp → dmodel`, attends, projects `dmodel → dout`. Call `mha(query, key, value, mask=None)`. `.parameters()` returns all four projection layers' params.
175
+
176
+ #### `FeedForward(dmodel, dff=None)`
177
+ Position-wise MLP: `Linear → ReLU → Linear`. `dff` defaults to `4 * dmodel`. `.parameters()` included.
178
+
179
+ #### `Transformer(dmodel, n, dff=None)`
180
+ A **pre-norm** decoder block: `x + Attn(LN(x))` then `x + FF(LN(x))`. `n` = number of attention heads. Call `block(x, mask=None)`. `.parameters()` included.
181
+
182
+ #### `PositionalEncoding(max_len, dmodel)`
183
+ Fixed sinusoidal positions, added to the input. Call `pe(x)`. No parameters.
184
+
185
+ ---
186
+
187
+ ### Containers
188
+
189
+ #### `Sequential(layers)`
190
+ Runs layers in order. `.train()` / `.test()` flip the `training` flag on any layer that has one (e.g. `BatchNorm1D`).
191
+
192
+ > ⚠️ `Sequential.parameters()` only collects layers exposing `W`, `b`, `gamma`, or `beta` attributes (i.e. `Linear`, `LayerNorm`, `BatchNorm1D`). Composite layers like `MultiHeadAttention`, `FeedForward`, and `Transformer` hold sub-modules, so their parameters are **not** picked up here — gather those via each module's own `.parameters()`.
193
+
194
+ #### `MLP(layer_sizes)`
195
+ Convenience feed-forward net: `Linear → ReLU` between layers, plain `Linear` output. Built from a list of sizes, e.g. `MLP([784, 128, 64, 10])`.
196
+
197
+ - `.save(filename="best_model.npz")` / `.load(filename="best_model.npz")` — persist/restore weights.
198
+ - *Note:* `MLP` does not expose a `parameters()` method; collect them via `[p for layer in mlp.layers for p in layer.parameters()]` if you want to optimize it.
199
+
200
+ ---
201
+
202
+ ### Recurrent
203
+
204
+ #### `RNNCell(input_dim, hidden_dim)`
205
+ One tanh recurrence step: `h_next = tanh(i2h(x) + h2h(h_prev))`. `.parameters()` included.
206
+
207
+ #### `RNN(input_dim, hidden_dim)`
208
+ Unrolls a cell over a **list** of timestep tensors (each `(B, input_dim)`) and returns the list of hidden states (each `(B, hidden_dim)`). Optional `prev_hidden`.
209
+
210
+ #### `StackedRNN(input_dim, hidden_dim, num_layers)`
211
+ Multiple `RNN` layers stacked. Returns `(top_layer_states, per_layer_final_states)` — the second value is convenient for seq2seq.
212
+
213
+ ---
214
+
215
+ ### Sequence-to-sequence
216
+
217
+ #### `Bridge(enc_hidden, dec_hidden, enc_layers, dec_layers, mode="project")`
218
+ Maps encoder final hidden states to decoder initial hidden states, handling mismatched layer counts and hidden sizes.
219
+
220
+ | `mode` | Behavior |
221
+ | --- | --- |
222
+ | `"project"` | One learned `Linear(enc_hidden → dec_hidden)` per decoder layer. General, recommended. |
223
+ | `"tie"` | No parameters; requires `enc_hidden == dec_hidden`. Selects/repeats raw states. |
224
+
225
+ ---
226
+
227
+ ### Optimizers
228
+
229
+ Both take an iterable of parameter tensors and share the same interface: `step()`, `zero_grad()`, `clip_grads(max_norm=5.0)`.
230
+
231
+ #### `SGD(parameters, learning_rate=0.01)`
232
+ Plain stochastic gradient descent.
233
+
234
+ #### `Adam(parameters, lr=1e-3, beta1=0.9, beta2=0.999, eps=1e-8)`
235
+ Adam with bias correction. Recommended for transformers.
236
+
237
+ ```python
238
+ opt = Adam(model.parameters(), lr=3e-4)
239
+ opt.zero_grad()
240
+ loss.backwards()
241
+ opt.clip_grads(1.0) # optional gradient clipping
242
+ opt.step()
243
+ ```
244
+
245
+ ---
246
+
247
+ ### Models
248
+
249
+ #### `GPTV1(vocab, d_model, n_heads, n_layers, max_len, d_ff=None)`
250
+ A decoder-only transformer (token embedding + sinusoidal positions + stacked pre-norm `Transformer` blocks + final `LayerNorm` + output head). Causal masking is applied internally.
251
+
252
+ | Method | Description |
253
+ | --- | --- |
254
+ | `model(idx)` | `idx`: integer array `(B, T)`. Returns logits `(B, T, vocab)`. |
255
+ | `model.parameters()` | All trainable tensors. |
256
+ | `model.generate(idx, n_new, temperature=1.0, top_k=None)` | Autoregressive sampling. Crops to `max_len`, supports temperature and top-k. Returns `(B, T + n_new)`. |
257
+
258
+ ---
259
+
260
+ ## Worked example: train a char-level GPT
261
+
262
+ ```python
263
+ import numpy as np
264
+ from cogforge.app import Tensor, Adam
265
+ from cogforge.models import GPTV1
266
+
267
+ # --- data -------------------------------------------------------------
268
+ text = open("input.txt").read()
269
+ chars = sorted(set(text))
270
+ stoi = {c: i for i, c in enumerate(chars)}
271
+ itos = {i: c for i, c in enumerate(chars)}
272
+ data = np.array([stoi[c] for c in text])
273
+ vocab = len(chars)
274
+
275
+ # --- model ------------------------------------------------------------
276
+ block = 64
277
+ model = GPTV1(vocab=vocab, d_model=128, n_heads=4,
278
+ n_layers=4, max_len=block)
279
+ opt = Adam(model.parameters(), lr=3e-4)
280
+
281
+ def get_batch(bs=32):
282
+ ix = np.random.randint(0, len(data) - block - 1, size=bs)
283
+ x = np.stack([data[i:i + block] for i in ix])
284
+ y = np.stack([data[i + 1:i + block + 1] for i in ix])
285
+ return x, y
286
+
287
+ # --- train ------------------------------------------------------------
288
+ for step in range(2000):
289
+ x, y = get_batch()
290
+ logits = model(x) # (B, T, vocab)
291
+ loss = Tensor.sparse_softmax_cross_entropy(logits, y)
292
+
293
+ opt.zero_grad()
294
+ loss.backwards()
295
+ opt.clip_grads(1.0)
296
+ opt.step()
297
+
298
+ if step % 100 == 0:
299
+ print(f"step {step:4d} | loss {loss.data:.4f}")
300
+
301
+ # --- sample -----------------------------------------------------------
302
+ ctx = np.array([[stoi["\n"]]])
303
+ out = model.generate(ctx, n_new=300, temperature=0.8, top_k=20)
304
+ print("".join(itos[i] for i in out[0]))
305
+ ```
306
+
307
+ ---
308
+
309
+ ## Gotchas
310
+
311
+ - **It's `backwards()`, not `backward()`.** The backward pass method has a trailing `s`.
312
+ - **Logits vs. probabilities.** `softmax_cross_entropy` / `sparse_softmax_cross_entropy` fuse the softmax internally — feed them **raw logits**. `cross_entropy_loss` expects **probabilities**. Mixing these up silently trains the wrong thing.
313
+ - **Gradients accumulate.** Call `optimizer.zero_grad()` every step (or `p.grad[...] = 0`), or gradients pile up across iterations.
314
+ - **`Sequential.parameters()` is shallow** — see the note under [Containers](#containers). For attention/feed-forward/transformer stacks, gather parameters through each module's own `.parameters()` (as `GPTV1.parameters()` does).
315
+ - **RNNs operate on lists**, not a single `(B, T, C)` tensor — pass a list of per-timestep tensors.
316
+
317
+ ---
318
+
319
+ ## Roadmap
320
+
321
+ Planned / under consideration:
322
+
323
+ - RoPE (rotary position embeddings) with length interpolation
324
+ - SwiGLU feed-forward and RMSNorm
325
+ - Weight tying between embedding and output head
326
+ - KV cache for faster generation
327
+ - Linear-attention block (as a study in the recall-vs-cost tradeoff)
328
+
329
+ ---
330
+
331
+ ## License
332
+
333
+ MIT License. See [LICENSE](LICENSE) for details.