Text Generation
PyTorch
English
poetry
custom-architecture
from-scratch
rope
swiglu

PoemFormer: a 95M-parameter transformer for English poetry with line, stanza and rhyme structure, trained from scratch on one T4

PoemFormer

PoemFormer is a ~95M-parameter decoder-only transformer trained from scratch to write English poetry. It has the usual causal language model backbone, plus extra inputs for line, stanza and rhyme structure.

Heads-up: this is an experimental hobby project. The output quality is modest: poem-shaped text, but often not very coherent. No benchmark numbers or curated samples are provided.

Note: this is a custom PyTorch model. It does not load with transformers / AutoModel, and the hosted Inference widget is disabled. To run it, use the generate.py script in this repo (see Usage).

Architecture

Parameters ~95M (input and output embeddings are tied)
Layers / heads / d_model 10 / 12 / 768
FFN SwiGLU, d_ff = 2048
Context length 256 tokens
Tokenizer SentencePiece BPE, 16,000 vocab; \n is kept as its own token
Position RoPE (base 10,000)

What it adds to a plain GPT:

  1. Hierarchical embedding. Each token embedding has a learned line embedding (up to 64 lines) and a learned stanza embedding (up to 16 stanzas) added to it. Line and stanza numbers come from counting newlines. A blank line (\n\n) starts a new stanza.
  2. Rhyme memory bank. Each block has a half-width cross-attention layer. It looks at the embeddings of the last 8 tokens that ended a line, so a line ending can attend to earlier line endings no matter how far back they are.
  3. Metrical attention bias. A learned (heads × 24 × 24) bias is added to the attention logits, indexed by each token's position within its line. This gives the heads a way to learn meter-like patterns from data.

Files

File Purpose
generate.py Command-line sampling script (start here)
poemformer.py Model definition
tokenizer.py Tokenizer wrapper that also outputs line, stanza and line-position ids
train.py Training script (made for a single Kaggle T4 or P100)
checkpoints/model_config.json Architecture config used to rebuild the model
checkpoints/weights_best.pt Model state_dict, the checkpoint with the lowest validation loss (fp32)
poem_tok.model / poem_tok.vocab SentencePiece tokenizer

Usage

pip install torch sentencepiece huggingface_hub
huggingface-cli download rororova/poemformer --local-dir poemformer
cd poemformer

python generate.py --ckpt-dir checkpoints --prompt "The autumn wind"
python generate.py --ckpt-dir checkpoints --prompt "Roses are red" --temperature 1.1 --top-p 0.95
python generate.py --ckpt-dir checkpoints --prompt "" --max-new-tokens 300   # unconditional
python generate.py --ckpt-dir checkpoints --prompt "Moonlight" --num-samples 3

Pass --ckpt-dir checkpoints every time. Without it, the script looks in /kaggle/working/checkpoints. It finds the tokenizer in the parent folder on its own.

From Python:

from pathlib import Path
import torch
from generate import load_model, generate

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model, tok = load_model(Path("checkpoints"), device)
print(generate(model, tok, "The autumn wind", max_new_tokens=200,
               temperature=0.9, top_p=0.92, device=device))

Default sampling settings are temperature 0.9 and top-p 0.92.

Training

  • Data: poems taken from the sources below, in this order, until 200,000 texts were collected, with rough duplicate removal. The Gutenberg corpus is stored one line per row, so its lines were grouped into 32-line chunks. The training script also lists several song-lyrics datasets after these, but they are only used if the poetry sources don't reach the 200k cap.
  • Objective: next-token prediction (cross-entropy), with each poem truncated to 256 tokens.
  • Optimizer: AdamW (β = 0.9, 0.95; weight decay 0.1), peak learning rate 3e-4, 300 warmup steps, then cosine decay down to 10% of the peak.
  • Batch: 8 × 4 gradient-accumulation steps, for an effective batch of 32. 4 epochs, fp16 mixed precision, gradient clipping at 1.0.
  • Hardware: one NVIDIA T4 (Kaggle).

Limitations

  • This is a small model trained from scratch on a single GPU. Expect poem-like text with uneven coherence, not polished verse. Rhyme and meter are learned only loosely.
  • It handles English only. Most of the data is older public-domain poetry, so the style often sounds archaic.
  • The context is 256 tokens, so long poems lose track of their opening.
  • During generation, the rhyme memory only fills from lines the model writes itself. Lines in the prompt are not added to it.
  • The outputs have not been filtered and may repeat biases or content found in the source texts.

License

MIT

Downloads last month

-

Downloads are not tracked for this model. How to track
Inference Providers NEW
This model isn't deployed by any Inference Provider. 🙋 Ask for provider support

Datasets used to train rororova/poemformer

Collection including rororova/poemformer