Skip to content
puchkovsPublic

About

A CPU-friendly language model built from scratch with PyTorch, featuring custom BPE tokenization, decoder-only Transformer architecture, reproducible training, and evaluation.

Topics

Resources

Contributing

Security policy

Stars

1 star

Watchers

0 watching

Forks

Repository files navigation

LLM Core

A compact, independently implemented language model for studying tokenization, causal Transformers, reproducible CPU training and evaluation. Built with Python, PyTorch primitives and NumPy; no pretrained weights or complete GPT classes.

Status

v0.1.0 experimental release. Phases 0–8 are implemented and verified, including bounded natural-language experiments. Source publication and hosted CI are verified. Release artifacts contain software only; no corpus or trained weights. This is an experimental educational model, not a general-purpose assistant.

Features

  • Custom deterministic byte-level BPE, exact byte round trips, EOD and checked JSON.
  • UTF-8 preparation, train-only tokenizer fitting, deterministic splits, uint16 memory maps, source hashes and document-safe next-token windows.
  • Decoder-only Pre-LayerNorm Transformer, causal multi-head SDPA, 4x GELU MLP, learned positions and tied output embeddings.
  • CPU FP32 AdamW, clipping, constant/warmup/cosine schedules, structured metrics, atomic best/latest checkpoints and exact same-environment resume.
  • Greedy, temperature, top-k and top-p generation with local seeded sampling.
  • Target-weighted validation/test evaluation, sparse smoothed bigram baseline, local experiment records and bounded CPU benchmarks.

Architecture

flowchart TB
    A[UTF-8 documents] --> B[Deterministic splits]
    B --> C[Train-only byte BPE]
    C --> D[Checked token memmaps]
    D --> E[Document-safe batches]
    E --> F[Decoder-only Transformer]
    F --> G[Training and checkpoints]
    G --> H[Autoregressive generation]
    G --> I[Fixed-window evaluation]
    D --> J[Train-only bigram baseline]
    J --> I
Loading

See architecture and technical contracts.

Configurations

Model Vocabulary Context Width Layers Heads Batch Unique parameters
Micro 512 64 64 2 4 16 136,960
Tiny 512 128 128 4 4 8 875,264
Small 1024 256 256 6 8 2 5,066,752

Counts are verified against actual tensors. Small has architecture tests but was not trained. The model vocabulary must match the prepared tokenizer's actual size.

Installation

Supported target: Linux x86-64, Python 3.12, CPU FP32. Install uv separately, then from this repository:

uv sync --locked --python 3.12
uv run --locked llm-core --version
uv run --locked llm-core --help

Distribution/CLI: llm-core; Python import: llm_core. uv.lock uses an explicit PyTorch CPU index. Plain pip does not honor uv's index settings. A verified wheel installation procedure is implemented in examples/verify_wheel.py. Download wheel and sdist from GitHub Releases. The package is not published on PyPI.

Quick start

Run the complete synthetic CLI pipeline without external downloads:

uv run --locked python examples/cli_smoke.py --output runs/quickstart

This prepares original text, trains a tiny test configuration for four steps with an intervening checkpoint resume, generates text, evaluates and benchmarks. For an actual Micro smoke model:

uv run --locked python examples/smoke_train.py --output runs/demo
uv run --locked llm-core generate --checkpoint runs/demo/train/best.pt \
  --prompt "The quiet robot " --greedy --max-tokens 12

Use new output directories. Synthetic output demonstrates functionality only.

Dataset preparation

uv run --locked python examples/acquire_alice.py --output data/alice
uv run --locked llm-core prepare-data --input data/alice/alice.txt \
  --output data/prepared --vocab-size 512 --context-length 128

The acquisition script verifies a pinned file hash, retains the original/full license and extracts the literary text. See provenance and conditions. The pipeline does no additional normalization; default splits target 90/5/5 using whole documents where possible, otherwise Unicode character boundaries. Repeat --input for separate documents. No tokenizer fitting uses held-out text.

Tokenizer

uv run llm-core tokenizer train --input tests/fixtures/training.txt \
  --vocab-size 280 --output artifacts/tokenizer.json
uv run llm-core tokenizer encode --tokenizer artifacts/tokenizer.json \
  --text "Hello, café!" --output artifacts/ids.json
uv run llm-core tokenizer decode --tokenizer artifacts/tokenizer.json \
  --input artifacts/ids.json --output artifacts/decoded.txt

Requested vocabulary is a ceiling. Bytes 0–255 and explicit EOD 256 are reserved; literal special-token-looking text is ordinary text. Decoding can preserve arbitrary bytes; generated incomplete UTF-8 uses the configured error policy.

Training

uv run llm-core train --config configs/micro.json --dataset data/prepared \
  --output runs/micro --steps 448 --stop-after 128

This starts a fixed 448-step horizon and stops after step 128. Defaults include AdamW LR .0003, weight decay .01 and gradient clipping 1. CPU threads, validation and checkpoint intervals are configurable through --training-config.

Resume

uv run llm-core train --config configs/micro.json --dataset data/prepared \
  --output runs/micro --steps 448 --resume runs/micro/latest.pt

Keep the total horizon and algorithmic settings unchanged. Restore the entire run including best.pt. Exact continuation requires the same supported Python/PyTorch/ NumPy/thread deterministic environment and matching data identities. See training.

Generation

uv run llm-core generate --checkpoint runs/micro/best.pt --prompt "Alice was " \
  --max-tokens 32 --temperature 0.8 --top-k 20 --top-p 0.9 --seed 123 --json

Use --greedy separately for argmax decoding. Model mode and global sampling RNG are preserved. Context slides within the learned maximum; no KV cache is used. Empty prompts start with EOD as context; generated EOD stops decoding. See inference.

Evaluation

uv run llm-core evaluate --checkpoint runs/micro/best.pt --dataset data/prepared \
  --split validation --json
uv run llm-core evaluate --baseline-only --dataset data/prepared --split test \
  --context-length 64 --smoothing 1 --json

Freeze settings/checkpoint choices on validation before final test scoring. Metrics weight actual target counts, including short tails and EOD. Fixed windows reset context at each window; this is not full sliding-context scoring. See evaluation.

Benchmarks

uv run llm-core benchmark --config configs/micro.json --threads 2 \
  --warmup 2 --iterations 5 --generation-tokens 32 --json
uv run llm-core model-info --config configs/tiny.json

Timings exclude setup/tokenization except the explicit initialization measurement. Checkpoint sizes and process RSS are measured; FP32 weight bytes are theoretical. RSS includes Python/torch/setup and may retain an inherited process floor.

Actual experiments

Natural-language corpus: Lewis Carroll's Alice's Adventures in Wonderland, 150,404 prepared bytes, one document, train-only 512-token BPE. Both models trained 448 steps / 458,752 target tokens, seed 42, two CPU threads. Validation selected checkpoints; final test scored 3,495 target tokens for every model.

Model Validation loss Test loss Test perplexity
Bigram, alpha=1 4.4181 4.4725 87.57
Micro 4.4265 4.4260 83.59
Tiny 4.0157 4.0234 55.89

Micro slightly loses to bigram on validation and slightly improves on test. Tiny has lower measured losses but still generates incoherent, repetitive text. Different contexts/capacities remain confounders; one short book and one seed do not establish general language ability. Remote Debian/EPYC measurements are not laptop estimates.

Measured natural-language learning curves

See experiments for synthetic versus natural results, throughput/RSS, all 24 unedited generation examples, raw data and reproduction.

Repository structure

Path Contents
src/llm_core tokenizer, data, model, training, checkpoints, inference, evaluation, benchmarks
configs strict model/training JSON and recorded experiment budgets
tests original synthetic algorithm, regression and CLI integration tests
examples reproducible bounded workflows, acquisition and plotting scripts
docs architecture/contracts, provenance, actual experiment results and curves
.github/workflows CPU-only local-equivalent CI configuration
runs, artifacts ignored runtime data/checkpoints/build output; outside source Git

Testing and development

make check
uv run --locked pytest --cov=llm_core --cov-report=term-missing
uv run --locked python examples/verify_wheel.py

The last command builds wheel/sdist, installs the wheel into a fresh CPU environment and executes the full public CLI workflow. Tests/CI require no external corpus, GPU or paid API. See contributing and security boundaries.

Limitations

Small models, learned context limits, byte-BPE inefficiency, no KV cache, CPU FP32 only, single-process training and simple O(merges*tokens) tokenizer algorithms. Current generations include malformed words, repeated fragments and replacement characters for incomplete UTF-8. No instruction tuning, safety evaluation, broad benchmark or production-service readiness is claimed. Only load trusted checkpoints; weights-only loading is not a complete security sandbox.

Roadmap and release

Roadmap distinguishes implemented work, completed experiments, local and hosted verification. Review release notes and model card. Releases require history, license, package and CI checks.

License

MIT for LLM Core software; see LICENSE. Literary source rights and Project Gutenberg distribution/trademark terms are separate and retained with source artifacts. Required corpus provenance is in docs/dataset.md. No endorsement by corpus providers or dependency authors is implied.

About

A CPU-friendly language model built from scratch with PyTorch, featuring custom BPE tokenization, decoder-only Transformer architecture, reproducible training, and evaluation.

Topics

Resources

Contributing

Security policy

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages