Skip to content
AloneMathPublic

About

Memory planner and ablation harness for decoder-only LLM pre-training. It measures its own memory model and tells you when it's wrong.

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Latest commit

 

History

1 Commit

Folders and files

Repository files navigation

Newton

A compute-efficient pre-training stack for decoder-only language models. It measures itself, and it tells you when it is wrong.

from newtonllm import Trainer, TrainConfig

trainer = Trainer(TrainConfig())
result = trainer.train()

newtonllm decides the memory plan, picks the optimizer, runs the loop, and reports what actually happened. Where it disagrees with reality, reality wins and the README gets corrected.

Status: v0.1, single device. Correct, measured, and honest about the gaps. It does not yet do multi-GPU. See Limitations.


Why another training stack

PyTorch is not hard to use. What is hard is everything it leaves to you:

You want PyTorch gives you What it costs
Train a 7B model model(x) works 112 GB of parameter state before any activations
Fit a batch DataLoader padding waste, tokenizer on the critical path
Go faster torch.compile you still pick the parallelism yourself
Know if it fits nothing you find out at step 200

Newton does not replace the tensor layer, the kernels, or autograd. That is a multi-year fight against cuBLAS and it is not where the wins are. Newton owns the layer above: the memory plan, the defaults, and the measurement harness.

The failure that shaped this project

The arithmetic planner — 16 bytes per parameter, a fixed activation coefficient, a 512 MiB overhead constant — was 18% low on the machine it was written on. It predicted 7,065 MiB for a 60M-parameter run. The run peaked at 8,150 MiB, exceeded the card's 8 GiB of physical VRAM, and the driver silently paged to system RAM. Result: 1,679 tokens/s instead of 3,600, with no error message.

That is the worst possible failure mode for a training tool. Worse than OOM, because OOM tells you the truth.

So the planner now measures itself before training. Two short forward/backward passes at micro-batch 1 and 4 give two points on a line:

peak(micro_batch) = fixed + per_sample x micro_batch

fixed absorbs parameters, gradients, CUDA context and allocator slack. per_sample absorbs the real activation cost of this architecture on this device. Adam state is added analytically because it is allocated lazily, and a separate 512 MiB term covers the driver, CUDA context and desktop VRAM that max_memory_allocated cannot see.

arithmetic plan calibrated plan
micro-batch 16 8
planned memory 7,065 MiB 6,684 MiB + 512 MiB reserved
actual peak 8,150 MiB — spilled to shared memory 4,839 MiB
throughput 1,679 tok/s 3,623 tok/s
throughput drift 0.52x 1.22x

Reproduce with --no-calibrate versus the default.


Install

pip install -e ".[dev]"

Requires Python 3.10+ and PyTorch 2.4+. On Windows the PyPI torch wheel is CPU-only; for CUDA use:

pip install torch --index-url https://download.pytorch.org/whl/cu128

Quick start

Check what the interpreter can do before trusting any number it prints:

newton doctor

See the plan for a model without allocating anything:

newton plan --preset tiny

Train, and run the ablation suite:

newton train --preset tiny --steps 500
newton bench --preset small --steps 120 --seq-len 512 --batch-tokens 8192

newton doctor exists because a training stack that silently falls back to CPU wastes hours. It prints the interpreter path, torch build, CUDA availability and device — everything needed to tell "no GPU" apart from "wrong interpreter".

Measured results

75.7M parameters, seq_len=512, bf16, RTX 3070 Laptop (8 GiB), 120 steps. Same data, same seed, same step count; one variable changes at a time.

variant final loss peak memory tokens to 0.4723 vs baseline
baseline 0.4723 4.44 GiB 983,040 1.00x
chunked CE 0.4710 4.44 GiB 976,330 1.01x
+ selective recompute 0.4714 1.69 GiB 979,945 1.00x
+ Muon 0.4519 1.41 GiB 894,007 1.10x
planner picks (auto) 0.4511 4.16 GiB 890,154 1.10x

Note what is not in that table: a throughput column. Every run reported a drift between 0.71x and 1.22x, which on a laptop GPU means thermal throttling. The harness detects this and warns, and rather than publish a number it cannot defend, the column is omitted. Loss and memory are measured; speed is not.

What the table does say:

  • Activation recompute buys 2.6x memory at identical loss. 4.44 GiB down to 1.69 GiB, loss 0.4723 versus 0.4714. That is the trade that lets a small GPU hold a bigger model.
  • Muon reaches the same loss in 10% fewer tokens, and then keeps going to a lower final loss. Reproduced at 9.5M parameters twice (1.21x and 1.23x) and at 60M (1.10x).
  • The memory knobs do not change learning. Three variants, same loss to within 0.001. That is the correctness check for chunked cross entropy and activation checkpointing.

What the planner decides

Given a model shape, a sequence length and a memory budget it searches, fastest first:

  1. keep all activations,
  2. recompute the wide MLP sublayer only (selective),
  3. recompute each block (full),
  4. chunk the cross-entropy logits.

For each combination it takes the largest micro-batch that fits and divides the requested batch evenly, so tokens_per_step matches what you asked for instead of silently overshooting.


Limitations

Read this before using it for anything real.

  • Single device only. No FSDP, no tensor/pipeline/expert parallelism. The plan reports dp when several GPUs are visible, but the loop is single-device. This is the largest gap and the top roadmap item.
  • Verified only at 0.25M–75M parameters. MFU in that range is 2–9% on the development GPU, dominated by kernel-launch overhead. Nothing here has been validated at 1B+, where the interesting behaviour lives.
  • The synthetic corpus saturates. It is a deterministic pseudo-language for reproducible ablations, not a benchmark. Past a few hundred thousand tokens every variant hits the same loss floor. Use --data path/to/corpus.txt for real text, and --target-loss to compare above the floor.
  • The calibration is conservative. At micro-batch 8 it over-predicts peak memory by ~38%, because activation memory is sublinear in batch while the fit is linear. Safe direction, wasted headroom.
  • No FP8, no 8-bit optimizer states, no μP, no scaling-law fitting, no data deduplication or quality filtering.

Roadmap

  1. FSDP — shard parameters, gradients and optimizer state across devices. The pure logic (sharding, state-dict remapping, checkpoint merging) is unit-testable without hardware; the communication layer needs two GPUs.
  2. μP — tune hyperparameters on a small model, transfer to a large one. This is the cheapest way to spend less compute on tuning.
  3. Scaling-law fitting — predict the large run from small runs, so ablations cost 1% of the final training budget.
  4. Real data pipeline — deduplication, quality filtering, decontamination. Usually a larger lever than any architectural change.
  5. FP8 training.

Deliberately not on the roadmap: replacing PyTorch's tensor layer, autograd or kernel ecosystem. That fight is lost before it starts.

Development

pytest -q          # 74 tests, CPU only, under a minute
newtonllm/
  config.py     typed configuration, parameter/FLOP counts, LR schedule
  model.py      decoder-only Transformer, chunked cross entropy, checkpointing
  data.py       byte tokeniser, synthetic corpus, packed token streams
  planner.py    memory model and configuration search        <- the core
  calibrate.py  measure the memory model instead of guessing  <- the fix
  optimizer.py  AdamW, Muon, composite optimizer
  trainer.py    the training loop
  metrics.py    MFU, throughput, drift, memory accounting
  bench.py      ablation runner and comparison report
  cli.py        newton doctor / plan / train / bench

Design principles, in priority order:

  1. Measure, do not claim. Every efficiency decision has an ablation variant, and every published number has a command that reproduces it.
  2. Defaults should be the good ones. You get the efficient configuration by not thinking about it.
  3. Never lie about what is implemented. This README is the contract. When measurement contradicted it, the README changed — the 3% recompute cost and the "free" chunked cross entropy claims were both wrong and both corrected.

License

MIT. See LICENSE.

About

Memory planner and ablation harness for decoder-only LLM pre-training. It measures its own memory model and tells you when it's wrong.

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages