- Python 100%
| Filename | Latest commit message | Latest commit date |
|---|---|---|
best.pt is epoch 13 (val 1.9632, ppl 7.12); epoch 50 drifted up to 1.9801, so sampling should use best.pt. Adds generation examples, the artifact counts from the per-epoch samples, and the 15-vs-50-epoch finding. Full run record lives in the vault at Documentation/Results.md. |
||
| tests | ||
| .gitignore | ||
| data.py | ||
| model.py | ||
| preprocess.py | ||
| README.md | ||
| requirements.txt | ||
| sample.py | ||
| train.py | ||
vintage-model-nostalgia
Rebuilding the first model I ever trained — char-rnn's 2-layer LSTM-128 on Joyce's complete corpus, on a 2011 MacBook Pro — in modern PyTorch.
Old architecture, modern framework. Char-rnn's defaults copied verbatim. No Torch7, no Lua, no container archaeology.
Goal
Train a char-level LSTM on the corpus on Clod's RTX 3060, sampling text with the remembered texture: portmanteau word-shapes, odd punctuation, real phrases occasionally surfacing.
Done means: a trained model and readable Joycean samples. That's it — and
it is: checkpoints/best.pt (epoch 13), with samples in
checkpoints/samples/.
Corpus
input.txt — Joyce's complete corpus, 3,647,130 chars. Not tracked by git
(copyrighted). Measured composition:
| Work | Chars | Share |
|---|---|---|
| Ulysses | 1,515,027 | 41.5% |
| Finnegans Wake | 1,298,700 | 35.6% |
| A Portrait of the Artist | 463,760 | 12.7% |
| Dubliners | 369,642 | 10.1% |
Expect sampled text to read as mostly Ulysses-ish prose with Wake-ish bursts — 64% of the corpus is realist prose. That blend is what the original run produced.
The 127-char vocabulary includes transcription artifacts (<p>, _, page numbers,
846 form feeds). char-rnn keeps every character, so the model learns to emit them
sporadically. Authentic, not a bug — don't "clean" the corpus.
char-rnn defaults (verified against upstream train.lua / model/LSTM.lua)
| Setting | Value |
|---|---|
| model | lstm |
| rnn_size | 128 |
| num_layers | 2 |
| seq_length | 50 |
| batch_size | 50 |
| dropout | 0 |
| optimizer | optim.rmsprop, learningRate = 2e-3, alpha = 0.95 |
| learning_rate_decay | 0.97, after epoch 10 |
| max_epochs | 50 |
| grad_clip | 5 |
| train_frac / val_frac | 0.95 / 0.05 |
| seed | 123 |
| input | one-hot (OneHot -> Linear, no embedding) |
Numerical identity with the 2011 run is not achievable (different RNG, init, RMSprop epsilon, GPU reductions). Reproducing the regime is the goal.
Usage
.venv is a ready CPU-only environment (torch 2.14+cpu, numpy, pytest).
# once: preprocess the corpus
.venv/bin/python preprocess.py --input_txt input.txt # -> data/corpus.npz, data/vocab.json
# watch it train (about 1.7 min/epoch, ~1.5 h for 50 epochs on Clod's CPU)
.venv/bin/python -u train.py --device cpu
# sample from the best checkpoint
.venv/bin/python sample.py --checkpoint checkpoints/best.pt --temperature 0.8
-u matters: without it Python buffers stdout and a redirected log looks dead
until the first epoch ends.
While training, every epoch prints:
- progress every 100 batches (
epoch 1 batch 300/1385 loss 2.7398 0:21 elapsed, 1:17 left) - the epoch's train/val loss and perplexity
- a 200-character sample, also saved to
checkpoints/samples/epoch_NNN.txt
So watching the tail of the samples directory is the low-effort way to see the
text cohere over the run. Useful flags: --sample_every N (0 disables
sampling), --prime, --sample_length, --temperature, --progress_every N
(0 disables), --max_epochs, --resume checkpoints/latest.pt.
Tests (including end-to-end train and sample):
.venv/bin/python -m pytest -q
Layout
preprocess.py— modern-Python port of torch-rnn'sscripts/preprocess.pydata.py—.npzloading, sequential (never shuffled) batch iteratormodel.py— hand-rolled char-rnn LSTM: one-hot →i2h/h2h→ 4 gates, gate order i, f, o, g, decoderLinear+ log-softmaxtrain.py— RMSprop, lr schedule, elementwise grad clamp, checkpointingsample.py— temperature sampling from a checkpointtests/— preprocessing parity, batching order, LSTM semantics, the lr schedule and defaults, an end-to-end train→sample run
Fidelity notes
- Gate order is char-rnn's
i, f, o, g, notnn.LSTM'si, f, g, o. A hand-rolled cell keeps the mapping tomodel/LSTM.lualegible;nn.LSTMwould silently be a different parameterisation. - Gradients are clamped elementwise to
[-5, 5](grad_params:clampin char-rnn), not rescaled by global norm. - RMSprop epsilon placement differs by framework: Torch7 uses
sqrt(m + eps), PyTorchsqrt(m) + eps. At1e-8this is negligible, but it is one of the reasons loss curves cannot match. - The lr decays once per epoch after epoch 10: epochs 1–10 at
2e-3, epoch 11 at2e-3 * 0.97, and so on. - Only whole batches are yielded. A short final batch would either crash on a hidden-state size mismatch or require zero-padding (fake data), so the trailing remainder (at most 2,499 chars/epoch, < 0.1%) is dropped.
- Sampling uses
softmax(log_probs / T), the numerically stable form ofsample.lua's divide → exp → renormalise. Same distribution, no NaN when a low temperature underflowsexp().
Preprocessing
A modern-Python port of torch-rnn's py2 scripts/preprocess.py. That script only
depended on h5py/six because Torch7 read training data from HDF5; the actual
work was small. It does: vocabulary from every character in first-appearance
order, integer ids, contiguous unshuffled splits, compact dtype.
No character filtering at all — no UNK, no frequency threshold. Every character in the corpus becomes part of the vocabulary, exactly as upstream.
Deliberate deviations from upstream (documented in the module docstring):
| Deviation | Why |
|---|---|
| 0-based vocab ids | PyTorch is 0-indexed; Torch was not. Ordering is preserved, so it's a relabelling |
| 0.95/0.05 split | char-rnn's default; torch-rnn used 0.1/0.1 |
| Zero-size test split allowed | Upstream raised IndexError on it |
| No h5py / six / py2 | .npz + JSON instead |
--encoding latin-1 is available for older transcripts; encoding mismatches fail
loudly rather than silently mangling bytes.
Notes
- Corpus is copyrighted (Joyce, 1882–1941; Finnegans Wake pub. 1939). Personal use only — do not commit the corpus or long generated excerpts, and keep the Forgejo remote private.
- A 128-wide 2-layer char-LSTM is launch-latency-bound, not FLOP-bound. The GPU will sit largely idle. That's expected, not a bug.
- Measured on Clod, real-corpus-sized batches (1,385/epoch), defaults: CPU ~90 ms/batch → ~2.1 min/epoch → ~1.7 h for 50 epochs; RTX 3060 ~120 ms/batch → ~2.8 min/epoch → ~2.3 h for 50 epochs.
- The GPU is slower here, and that is expected rather than a misconfiguration:
the hand-rolled cell issues ~100 tiny kernel launches per batch, so the 3060
pays launch latency the 12-core Xeon does not.
--device cpuis the faster choice for this literal formulation. A fusednn.LSTMpath (weights re-permuted from i,f,o,g to i,f,g,o) would change that, but it is not the same code path and has not been built. - CPU and GPU runs agree to ~4 decimal places on a 3-epoch smoke test (train 1.8652 vs 1.8625), which is a useful reproducibility sanity check.
Status
Trained. 50 epochs on Clod's CPU, ~85 min, char-rnn defaults verbatim.
Best val loss 1.9632 (ppl 7.12) at epoch 13; by epoch 50 it has drifted up
to 1.9801 (ppl 7.24), so best.pt is the checkpoint to sample from. Samples
read as mostly Ulysses-ish prose with Wake-ish bursts, and the transcription
artifacts surface sporadically (7 form feeds and 4 numerals across 11,150
sampled chars, no <p> tags). Per-epoch samples are in
checkpoints/samples/, one file per epoch.
The 50-epoch default overshoots: val bottoms around epoch 13, so a 15-epoch
run is the efficient version of this experiment. See
Documentation/Results.md in the vault for the run record.