File size: 7,380 Bytes
ac5c307
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
# Kat β€” tiny from-scratch chatbot on DailyDialog

Goal: a small decoder-only transformer, trained from random init on
`li2017dailydialog/daily_dialog`, that holds a short, grammatical,
generic conversation. Nothing more.

Hardware: CPU only (12 cores, 30 GB RAM). Everything below is sized for that.

## Architecture decision

Decoder-only LM (GPT-style), not seq2seq. One model, one loss, one
inference path; the dialogue is just a formatted text stream:

    <|user|> hello , how are you ? <|bot|> i am fine , thanks . <|eos|>

Train on next-token prediction over whole dialogues; at chat time, feed the
context ending in `<|bot|>` and sample until `<|eos|>`.

## Target model size

| knob | value | why |
|---|---|---|
| vocab | 8,000 BPE | DailyDialog is ~1.5 MB of text; bigger vocab wastes params |
| n_layer | 4 | |
| n_head | 4 | |
| n_embd | 256 | |
| block_size | 128 tokens | ~4-6 turns of context, plenty |
| params | ~5-8 M | trains on CPU in ~1-3 h |

Dropout 0.1 β€” the dataset is tiny (~76k utterances), overfitting is the
main risk.

## File layout

    data.py        download, clean, format, save train/val token arrays
    tokenizer.py   train the BPE tokenizer -> tokenizer.json
    model.py       the transformer (embeddings, blocks, attention, MLP, head)
    train.py       training loop, val loss, checkpointing
    chat.py        interactive REPL, sampling
    config.py      one dataclass holding all hyperparameters
    requirements.txt

Keep `model.py` hand-written β€” that is the point of the project. Use
libraries only for data loading and tokenization.

## Phases

### 1. Environment
`python3 -m venv .venv`, then `torch` (CPU wheel), `datasets`, `tokenizers`,
`numpy`. Pin versions in `requirements.txt`. Set `torch.set_num_threads(12)`.

### 2. Data pipeline (`data.py`)
- `load_dataset("li2017dailydialog/daily_dialog")` -> splits train/validation/test.
- Each row has `dialog` (list of utterances), plus `act`/`emotion` labels β€” ignore the labels.
- Clean: DailyDialog has spacing artifacts (` ' `, ` ’ `, stray double spaces,
  inconsistent punctuation spacing). Normalize whitespace, lowercase, collapse quotes.
- Format each dialogue by alternating `<|user|>` / `<|bot|>` and ending `<|eos|>`.
- Write `train.txt` / `val.txt`; the provided validation split is the val set (do not re-split train).
- Sanity check: print 3 formatted dialogues and total token count (expect ~1.5-2 M tokens).

### 3. Tokenizer (`tokenizer.py`)
- Byte-level BPE via `tokenizers`, vocab 8000, trained on `train.txt` only.
- Special tokens: `<|pad|> <|user|> <|bot|> <|eos|>` added as non-splittable.
- Encode both splits into flat `uint16` numpy arrays saved as `.bin` β€”
  training then just slices random windows, no per-step tokenization.

### 4. Model (`model.py`)
Build in this order, testing each piece in isolation:
1. token embedding + learned positional embedding
2. causal self-attention (`torch.nn.functional.scaled_dot_product_attention` with `is_causal=True`)
3. MLP block (4x expansion, GELU)
4. pre-norm residual block, stack N of them
5. final LayerNorm + linear head, weights tied to the token embedding
6. `forward(idx, targets=None)` returning logits and cross-entropy loss

Checkpoint: a randomly initialized model should give loss β‰ˆ ln(8000) β‰ˆ 8.99.
If it does not, the wiring is wrong β€” fix before training.

### 5. Training (`train.py`)
- AdamW, lr 3e-4, cosine decay with ~100 warmup steps, weight decay 0.1, grad clip 1.0.
- Batch 32, block 128. Evaluate val loss every 250 steps on a fixed set of batches.
- Train to ~3000-5000 steps, or until val loss stops improving (it will start
  rising β€” save the best checkpoint, not the last).
- Log train/val loss to a CSV so the overfit point is visible.
- Expect val loss to land around 3.0-4.0. That is normal for this scale.

Overfitting on 20 batches first, to loss < 0.1, is the fastest proof the loop
is correct. Do that before any long run.

### 6. Chat (`chat.py`)
- Maintain a rolling history, truncated from the left to fit `block_size`.
- Append `<|bot|>`, sample with temperature ~0.8 and top-k 40, stop at `<|eos|>`
  or a max of 60 new tokens.
- Greedy decoding will loop ("i don't know . i don't know .") β€” sampling is required.

### 7. Evaluation
- Val perplexity as the tracked number.
- A fixed list of ~15 probe prompts ("hi", "how are you?", "what do you do?")
  run after each training config, so changes are comparable by eye.

## Success criteria

Grammatical, on-topic-ish short replies to common greetings and small talk.
No factual accuracy, no memory beyond the context window, no coherence over
long exchanges. Those are out of scope by design.

## Known traps

- Loss masking: training on the full stream (including `<|user|>` turns) is
  fine and simpler. Only mask user tokens if replies degrade.
- Padding: with flat-array windowing there is no padding at all in training.
  `<|pad|>` only matters if batching at chat time β€” it likely never will.
- `uint16` requires vocab < 65536. Fine at 8000; revisit if vocab grows.
- DailyDialog is small enough to memorize. If replies are verbatim dataset
  lines, the model is overfit β€” stop earlier or add dropout.

---

## Build log (actual)

Deviations from the plan above, recorded as they were hit:

- **venv**: `python3 -m venv` fails on this machine (no `ensurepip`). Used `uv` instead.
- **install**: torch must be installed from the PyTorch CPU index in a *separate*
  step; that index carries an old `requests` that conflicts with `datasets`.
- **dataset**: `datasets>=4` refuses to run loading scripts, and the dataset's
  `main` branch contains only a script. Pinned `revision="refs/convert/parquet"`.
- **cleaning**: the real artifacts were 12,084 spaced unicode apostrophes
  (`it ’ s`) and ~100k spaces before punctuation. Residual lone apostrophes
  (540) are genuine quotation marks and are left alone.
- **tokenizer**: `Tokenizer.decode()` strips special tokens by default. The
  round-trip check needs `skip_special_tokens=False`; chat.py wants the default.
- **model**: 5,240,320 params. Init loss 9.05 vs ln(8000)=8.99. Overfit a single
  batch to 0.009 in 200 steps. ~450 ms/step at batch 32, so ~35 min for 4000 steps.
- **training**: 4000 steps in 37.5 min (~560 ms/step). Best val **3.3460** at
  step 4000, perplexity 28.4 β€” inside the planned 3.0-4.0 band. Val loss dipped
  at steps 2750 and 3250 before recovering, so best-checkpoint saving mattered;
  train/val gap at the end was only 3.23 vs 3.35, i.e. not yet badly overfit.
  There is likely a little headroom left in more steps or a wider model.
- **generation bug (found in phase 7)**: stopping only at `<|eos|>` let the model
  write the *user's* next turn too, and `decode()` strips the `<|user|>` tag, so
  replies silently ran on as multi-turn transcripts. `generate()` now takes
  `stop_tokens` and halts at any turn boundary. Worth knowing: this looks like a
  model quality problem but is purely a decoding bug.

## Result

Single-turn replies are short, grammatical and usually topical; some are
non-sequiturs. Multi-turn holds loosely. That is the intended ceiling for a
5.2M-param model on 1.4M tokens β€” the goal was basic sentences, not accuracy.

Headroom, in rough order of value per CPU-hour: more steps (val was still
falling), then n_embd 384 / n_layer 6, then loss-masking the user turns.