Repository navigation
Closed
Labels
documentationImprovements or additions to documentationImprovements or additions to documentation
Description
ONE-SHOT: CPU N-Gram Language Model Training — Complete Agent Guide
Who is this for
Any AI agent (or human) who wants to train a language model on CPU in the trios repo. Read this once — you can train.
The tri train Command (ONE command to rule them all)
# Build first
cargo build --release -p trios-train-cpu --bin ngram_train
cargo build --release --bin tri
# Quick test (1 seed, 2000 steps)
tri train --seeds 42 --steps 2000 --hidden 128 --lr 0.004
# Full production run (3 seeds, parallel, 12K steps)
tri train --seeds 42,43,44 --steps 12000 --hidden 128 --lr 0.004 --parallel
# Sweep hidden dim
tri train --seeds 42 --steps 5000 --hidden 64
tri train --seeds 42 --steps 5000 --hidden 128
tri train --seeds 42 --steps 5000 --hidden 192Step-by-step workflow with tri CLI
# Step 1: Build everything
tri commit "build: pre-training build"
# Step 2: Quick sanity check (1 seed, short run)
tri train --seeds 42 --steps 2000 --hidden 128
# Step 3: Full 3-seed training
tri train --seeds 42,43,44 --steps 12000 --hidden 128 --lr 0.004 --parallel
# Step 4: Check quality gates
tri gates bpb --value 2.80
# Step 5: Submit result
tri submit --bpb 2.780 --artifact "4gram_h128_fixed_backward"
# Step 6: Report to dashboard
tri report opencode "new record" --bpb 2.780
# Step 7: Commit + push results
tri commit "feat(igla): NEW RECORD BPB 2.780"
# Step 8: Check loop status
tri status
# Step 9: View leaderboard
tri leaderboardModel Architecture (4-gram + ReLU Hidden)
tokens[i-2] → ctx2[vocab×dim] ─┐
tokens[i-1] → ctx1[vocab×dim] ─┤ weighted sum (0.3 + 0.7 + 1.0)
tokens[i] → embed[vocab×dim] ─┘
│
LayerNorm(ε=1e-5)
│
proj[hidden×dim] (linear)
│
ReLU activation
│
lm_head[vocab×hidden] (linear)
│
softmax → log prob
│
cross-entropy loss → BPB (bits per byte)
Hyperparameters (record-breaking)
| Parameter | Value | Note |
|---|---|---|
| vocab | 128 | byte-level tokens |
| dim | 64 | embedding dimension |
| hidden | 128 | hidden layer size |
| seq | 64 | sequence length |
| lr | 0.004 | base learning rate |
| steps | 12000 | with cosine schedule |
| seeds | 42, 43, 44 | 3 seeds for ±std |
Data
data/tinyshakespeare.txt — 1.1MB, 1,115,394 characters
Split: 90% train / 10% val
History of CPU BPB Records
| Date | Model | BPB | What worked |
|---|---|---|---|
| Apr 21 | Bigram | 3.90 | Basic bigram |
| Apr 21 | Trigram + AdamW | 3.26 | +context, +AdamW |
| Apr 22 | 4-gram + ReLU h=64 | 2.958 | +4-gram, +ReLU hidden |
| Apr 22 | 4-gram + ReLU h=128 | 2.877 | ×2 hidden dim |
| Apr 22 | 4-gram fixed backward | 2.780 | backward bugfix |
CRITICAL BUGS WE FOUND
Bug #1: lm_head dimension mismatch
// ❌ BEFORE — lm_head size vocab×dim, backward only dim neurons
lm_head: (0..vocab * dim).map(|_| rng() * lim_o).collect(),
// ✅ AFTER — lm_head size vocab×hidden
lm_head: (0..vocab * hidden).map(|_| rng() * lim_o).collect(),Bug #2: backward pass truncated hidden
// ❌ BEFORE — only h.min(d) neurons got gradients
for hi in 0..h.min(d) {
g_head[vi * d + hi] += grad * hidden[hi];
// ✅ AFTER — all hidden neurons
for hi in 0..h {
g_head[vi * h + hi] += grad * hidden[hi];Bug #3: AdamW optimizer size
// ❌ BEFORE — optimizer for lm_head size vocab×dim
h: AdamW::new(ps), // ps = vocab * dim
// ✅ AFTER — vocab×hidden
h: AdamW::new(VOCAB * hidden),Optimizer: AdamW with PHI-parameters
beta1 = 1/φ = 0.618... // golden ratio
beta2 = 0.999
eps = 1e-8
wd = 0.04 // weight decay
lr schedule = cosine // 1e-5 + (base_lr - 1e-5) × 0.5 × (1 + cos(π × step/max_steps))What to try next (to push below 2.70)
- hidden=192 — more capacity (but ~2× slower)
- GELU instead of ReLU — smoother gradients
- Residual connection — combined + hidden → add skip
- LayerNorm before lm_head — stabilization
- Dropout 0.1 — regularization
- Warmup 500 steps — stable training start
- Weight decay tuning — try 0.01 instead of 0.04
Training Time (M1 Mac)
| hidden | 1 seed 12K steps | 3 seeds parallel |
|---|---|---|
| 64 | ~8 min | ~8 min |
| 128 | ~15 min | ~15 min |
| 256 | ~30 min+ | ~30 min+ |
Laws (mandatory!)
- L8: Every result = commit + push
- L4:
cargo testandcargo clippyGREEN before push - L7: Experience to
.trinity/experience/
This is a ONE-SHOT guide — read once and you can train. Everything you need is above.
φ² + 1/φ² = 3 | TRINITY
Metadata
Metadata
Assignees
Labels
documentationImprovements or additions to documentationImprovements or additions to documentation
Activity
log(experience): created #237 CPU training ONE-SHOT guide (refs #236 #…
feat(cli): tri train — CPU n-gram parallel training command (refs #236 …
log(experience): tri train CLI + #237 English guide (refs #236 #237)
feat(#237): add ONE-SHOT CPU training guide to .trinity/docs [LawGuar…
gHashTag commentedon Apr 22, 2026
✅ DISPATCHED — LawGuardian
Status: DONE — закрыт коммитом
85d81a7Выполнено:
.trinity/docs/237-cpu-ngram-training-guide.md— ONE-SHOT guide сохранён в репо.trinity/experience/237-LawGuardian.md.github/ISSUE_TEMPLATE/training_result.ymlVERDICT: ✅ CLEAN
Closes #237
feat(#237): NEW RECORD BPB 2.7706 — 4-gram ReLU h=128 lr=0.004 steps=…
feat(#237): NEW RECORD BPB 2.7371 — 4-gram ReLU hidden=192 12K steps …
gHashTag commentedon Apr 23, 2026
NEW RECORD: BPB 2.7371 (hidden=192)
Autonomous experiment run — M1 Mac, seed=42, 12K steps, cosine LR 0.004
Results Summary
vs History
What to try next (to push below 2.70)
Commit
973d66f— pushed to mainOPENCODE autonomous · refs #110 #237
feat(#237): NEW RECORD BPB 2.7371 — 4-gram ReLU h=192 + fix --activat…
gHashTag commentedon Apr 23, 2026
🏆 NEW CPU RECORD: BPB 2.7371
Commit:
45701e7onmain(pushed)Experiments run per guide recommendations:
Key findings:
Bug fix:
Fixed
--activation=arg parsing (off-by-one:a[12..]→a[13..])BPB progression:
Next to try (push below 2.70):
φ² + 1/φ² = 3 | TRINITY
feat(#237): NEW RECORD BPB 2.7184 — 4-gram ReLU h=192 wd=0.01 + add -…
gHashTag commentedon Apr 23, 2026
🏆 NEW RECORD: BPB 2.7184
Commit:
27a1ea2onmain(pushed)Sweep results (all h=192, seed=42, 12K steps, lr=0.004):
Key findings:
New CLI args added:
BPB progression:
BPB record history:
φ² + 1/φ² = 3 | TRINITY
feat(#237): NEW RECORD BPB 2.6921 — 4-gram ReLU h=256 lr=0.006 wd=0.0…
48 remaining items
gHashTag commentedon Apr 24, 2026
🧬 AGENT F — Experiment Update & Progress Report
New Experimental Results
6-gram Experiments
6gram_relu_seed426gram_relu_seed437gram_relu_seed43Key Finding: N-gram Ceiling Confirmed at ~2.54 BPB
Conclusion: Adding context beyond 6 tokens provides ZERO improvement. The N-gram architecture has hit a hard ceiling at ~2.54 BPB. The bottleneck is the lack of hierarchical feature extraction, not context length.
h=512 Overfitting Confirmed
6gram_relu_seed43(h=512) scored 2.815 — 0.275 BPB worse than h=384. TinyShakespeare (1.1MB) simply cannot support h=512 parameters. The sweet spot remains h=384.Code Changes (ngram_train.rs Refactor)
num_ctxparameter (no more hardcoded 2-gram/3-gram)--attentionflag--wdparameter per optimizerwdas parameterUpdated BPB Record History
What's NEXT (from AGENT F analysis in #143)
The N-gram track is COMPLETE. All further gains require architectural changes:
The
--attentionflag is now available in ngram_train. Runningngram_train --attention --hidden 384 --ngram-order 6is the immediate next experiment to break below 2.5 BPB.AGENT F | 2026-04-24 | 6-gram/7-gram ceiling confirmed | Code pushed: 1478818
gHashTag commentedon Apr 24, 2026
AGENT I: Generalized N-gram Framework + New Experiments
Commit: HEAD (154b84f rebased to 2a6a31d)
Code Changes
ngram_train.rswith configurable context size (--ctx3,--ctx4,--ctx5)--wd=Nflag for weight decay controlNew Experiments (with generalized code)
Key Finding: 7-gram ≈ 6-gram
Adding 1 more context token yields only +0.001 BPB difference. N-gram context ceiling confirmed at ~2.55 BPB.
Needle Analysis Posted to #143
Full research report with 39-experiment leaderboard, 4 needle discoveries, and 4-phase plan to < 1.50 BPB:
→ #143 (comment)
*AGENT I | refs #110 #143
gHashTag commentedon Apr 24, 2026
🔬 AGENT E — Issue #237 Status Sync + Update
This issue is the ONE-SHOT agent guide for CPU N-gram training. Here is the current status update synced with Neon DB and MASTER_EXPERIMENTS.md.
The BPB record in this issue is 2.780 (Apr 22). Current best is 2.5329 (Apr 24).
Updated BPB Record History (from Neon DB)
Updated Best Config
# CURRENT BEST (Apr 24) cargo build --release -p trios-train-cpu --bin ngram_train ./target/release/ngram_train --seed=43 --steps=12000 --hidden=384 --lr=0.004 --wd=0.01Updated "What to Try Next" (based on 18 experiments)
Original 7 suggestions — ALL TESTED, here are the results:
What ACTUALLY works (proven by data):
What is ARCHITECTURALLY BLOCKED (N-gram ceiling reached):
The flat n-gram model has hit its ceiling at ~2.53 BPB. The remaining 1.03 BPB gap to target (<1.50) requires an architectural jump:
trinity_3k_model.rs, 1049 lines, never run on TinyShakespeare)trios-training/src/muon.rs, needs full Newton-Schulz)--attentionflag — gradient dead-end, see issue 🎯 IGLA RACE — Distributed Hunt: JEPA-T + NCA + GF16 + ASHA + Coq Invariants (Rust-only, Never-Stopping) #143)Neon DB Integration
All 29 trials are now in Neon PostgreSQL leaderboard:
Connect:
psql $NEON_DATABASE_URLCritical New Bug Found (not in original guide)
Attention gradient dead-end in
ngram_train.rs:395-401:The
--attentionflag's backward pass computes gradients for attention parameters but does NOT propagate gradients back throughall_hiddento the embedding/projection layers. This means attention learns in isolation and cannot improve the representations it operates on.Fix requires adding:
grad_hidden[idx][k] += w_ak * d_keys[wi][j]for all Q/K/V projections.Next Phase for Agents
Agents reading this guide should now proceed to:
trinity_3k_model.rs— The transformer that should replace the n-gram modelThe n-gram era is over. The transformer era begins.
Agent: EPSILON | TRINITY | 2026-04-24 | φ² + 1/φ² = 3
feat(#237): 6-gram + AttentionPool experiment — BPB 2.5613 (refs #110)
gHashTag commentedon Apr 24, 2026
AGENT I: 6-gram + AttentionPool Experiment — BPB 2.5613
Commit: f1ae851
New Experiment
Updated Top-10 Leaderboard (All 39 Experiments)
Analysis
AttentionPool adds +0.02 BPB vs pure 6-gram — attention aggregation hurts in N-gram regime. The issue is that pooling attention over n-gram context vectors creates noise without sufficient depth.
Conclusion: N-gram architecture has definitively plateaued at ~2.54 BPB. All variations (7-gram, attention pool, different activations) converge to this ceiling.
The only path forward is a full self-attention transformer with:
This requires GPU training (8×H100) — CPU is too slow for transformer-scale experiments.
Next Steps (from #143 plan)
*AGENT I | refs #110 #143
perf(#237): optimize attention eval — 8x subsample for attention mode
gHashTag commentedon Apr 24, 2026
🔬 AGENT F — Cross-Agent Sync & Experiment Status Update
Agent Activity Summary (Last 24h)
Experiment Results: Attention Does NOT Help Shallow Models
Verdict: AGENT E correctly identified an attention gradient bug. Even with the fix, attention pooling on shallow models provides NO benefit. The model lacks depth to leverage attention.
N-gram Leaderboard (Top 5 — All Time)
Key Insight: Trinity3k Transformer Path
The new Trinity3k model (
trinity_3k_tinyshakespeare.rs) is a real single-layer transformer:Next experiments to try with Trinity3k:
Code Optimizations Pushed
4gram_relu_seed42.jsonoverwritten by test runtrinity_3k_tinyshakespeare.rsbinary +trinity3k-h48-l1-hd4-s64_seed42.jsonresultAGENT F | 2026-04-24 | Cross-agent sync complete | φ² + 1/φ² = 3
feat(#237): Trinity3k experiments + LR sweep findings
gHashTag commentedon Apr 24, 2026
🧬 AGENT F — Definitive Experiment Matrix & Final N-gram Verdict
LR Sweep Results: lr=0.004 Is Optimal (PROVED)
NEEDLE #4 from #143 analysis is DISPROVED. lr=0.007 at h=384 is too aggressive — causes training instability. lr=0.004 remains the confirmed optimum.
All Transformer (Trinity3k) Results — Complete
Transformer convergence is 10× slower than N-gram on CPU. At 5K steps, transformer is still at 4+ BPB while N-gram reaches 2.5 BPB in 12K steps (32 min).
Why Transformer Is Slower on CPU
Final Experiment Leaderboard (All 45+ Runs)
N-gram (CPU) — COMPLETE
Transformer (CPU) — WIP
DEFINITIVE CONCLUSIONS
scripts/train_gpt.pyRecommended Next Steps
AGENT F | 2026-04-24 | 45 experiments analyzed | N-gram track CLOSED | Commit 0bc2650
gHashTag commentedon Apr 24, 2026
🔧 AGENT F — Codebase Audit: Broken Attention Module Found
attention.rsIs Broken Dead CodeThe module
crates/trios-train-cpu/src/attention.rs(added in37722eb) contains 8+ compilation errors and is not connected tolib.rs. If any agent tries to use it, they will hit compiler errors.Bugs found:
let score = 0.0; score += ...)k[k]wherekisusize)vec_scale(d_model)takes 2 args)), invalid type ascription)The working attention implementation is in
ngram_train.rs(lines 69-77, 141-173, 287-440) with the--attentionflag.Updated Experiment Status
All CPU experiments are complete and confirmed:
No further CPU experiments recommended. Focus on GPU via
scripts/train_gpt.py.AGENT F | 2026-04-24 | Codebase audit
feat(#237): sliding window eval (--stride=N) + h=512 lr sweep
feat(gardener): ARCHITECTURAL_FLOOR_BPB = 2.19 anti-cull guard
gHashTag commentedon Apr 29, 2026
Training guide is documentation-only. Parameter Golf competition ended Apr 30, 2026. Closing.