DeepSeek V3 in 190 Lines of Pure JAX – Architecture, Training on a MacBook Air, and Results

TL;DR – What the repo shows

DeepSeek V3’s three key innovations – Multi‑head Latent Attention, bias‑based MoE balancing, and Multi‑Token Prediction – are reproduced in a 190‑line pure‑JAX implementation that trains on a MacBook Air M5 in 2.6 hours and matches the paper’s expert‑load balancing claim without any auxiliary loss.


Architecture in 190 Lines

The repository implements the DeepSeek‑V3 model exactly as described in the DeepSeek‑V3 Technical Report (arXiv:2412.19437) but strips away all external libraries. The entire model lives in deepseek_v3.py and consists of:

Paper idea Function in code Effect
Multi‑head Latent Attention (MLA) mla, init_cache Stores a tiny latent vector (480 → 144 numbers per token per layer) instead of full key/value matrices, reducing cache memory.
Decoupled RoPE rope, apply_rope, mla Uses a single rotary key shared across heads, kept outside the compressed latent.
DeepSeekMoE route, moe One always‑on expert plus 16 routed experts, selecting the top‑4 per token.
Aux‑loss‑free balancing update_bias, route Adds a per‑expert bias that nudges routing toward idle experts; routing probabilities change, not the expert weights.
Sequence‑wise balance loss seq_balance_loss Implements the paper’s small complementary loss (α = 1e‑4).
Multi‑Token Prediction (MTP) forward, loss_fn Predicts the token after next as an auxiliary target (λ = 0.3).
Training & generation utilities make_train_step, generate bf16 compute on f32 master weights; pre‑fill and decode using the MLA cache.

All parameters are plain Python dictionaries of JAX arrays; there is no Flax, Equinox, or PyTorch layer abstraction. The code can be read top‑to‑bottom, making the algorithmic flow explicit.


Training Run on a MacBook Air M5

The author performed a single end‑to‑end run with the default configuration on an Apple Silicon MacBook Air (M5, 24 GB RAM). Key numbers:

Metric Value
Model size 36.2 M parameters total; 13.6 M active per token (due to MLA compression)
Dataset 207 public‑domain detective novels (21.7 M tokens), validation on held‑out crime fiction
Steps 12 000 (≈98 M tokens, 4.5 epochs)
Training time ~2.6 h
Throughput ~10.7 k tokens / s (median)
Validation loss 5.02 at step 250 → 3.51 at step 12 000
Expert load (with bias) 5.7 %–6.9 % per expert (ideal 6.25 %)
Expert load (without bias) 0.09 %–18.6 % per expert

When the bias‑based balancing is disabled, validation loss at step 2000 is virtually unchanged (3.921 vs 3.923), confirming the paper’s claim that the bias evens out expert usage without hurting performance.

Sample generation (prompt “The fog came in off the”):

The fog came in off the bay, and the great trees were spreading and the stars were shining.

The model is clearly a demonstration rather than a production‑grade LLM; the write‑up discusses what worked, what didn’t, and missing components such as FP8 training, DualPipe, and large‑scale context extensions.


Reproducing the Experiment

The repository provides a step‑by‑step guide for exact replication on Apple Silicon. The essential steps are:

  1. Install – Clone the repo, create a Python 3.12 virtual environment with uv, and install pinned dependencies (including jax-metal==0.1.1 paired with jax==0.4.34).
  2. Validate the setup – Run the test suite (pytest tests.py) and the optional metal smoke test (smoke_metal.py).
  3. Prepare the data – prepare_data.py downloads the 207 books (~120 MB) and builds an 8 192‑token BPE tokenizer, producing train.bin, val.bin, and tokenizer.json. The published run’s SHA‑256 hashes are listed in the README; minor Gutenberg revisions may change the hashes but not token counts.
  4. Train – train.py runs the default 12 k‑step job (~2.6 h). Ablation runs with --no-bias or --steps 2000 reproduce the bias‑on/off experiments.
  5. Generate – sample.py produces text from the checkpoint (ckpt.pkl). The checkpoint is a Python pickle; load only from trusted sources.
  6. Plot – plots.py and charts.py recreate the paper’s figures from the logged metrics.jsonl files.

For non‑Apple hardware, the repo includes a CPU‑only mode (JAX_PLATFORMS=cpu) with a reduced configuration (--config small: 4 layers, 8 experts, top‑2, 128‑token context) that runs on 8–16 GB RAM machines.


Community Extensions and Gotchas

  • ROCm support – A top‑commenter reported a successful end‑to‑end run on an AMD RX 7600 XT using JAX’s ROCm plugin. Required environment tweaks:
    export HSA_OVERRIDE_GFX_VERSION=11.0.0
    export XLA_FLAGS=--xla_gpu_enable_triton_gemm=false
    export JAX_THREEFRY_PARTITIONABLE=false
    
    The contributor contributed a PR with a comparison script and plots.
  • Learning curve – Several commenters praised the “first‑principles” approach as a way to revisit JAX and understand LLM internals without heavyweight frameworks.
  • Requests – Users asked for C++ ports, larger model variants, and CPU‑only feasibility on newer Intel CPUs; the author has not provided those yet.

What Is Simplified Compared to the Full DeepSeek‑V3 Model?

Simplification Reason / Impact
Dense MoE compute All experts run on every token; unselected experts are zeroed. Simpler code but slower than sparse dispatch.
Explicit MLA decompression No weight absorption; easier to read but incurs extra inference cost.
Missing features FP8 training, DualPipe, node‑limited routing, YaRN context extension, and any post‑training fine‑tuning are omitted.
Scale reduction 36.2 M parameters vs the paper’s 671 B; 6 layers vs 61; 256‑token context vs 128 k tokens.

These reductions keep the implementation tractable while still demonstrating the core algorithmic ideas.


Licensing and Data

  • Code – MIT license (see LICENSE).
  • Training data – Entirely public‑domain detective fiction (Standard Ebooks CC0 editions of Dashiell Hammett works and ~200 Project Gutenberg titles). US public‑domain status is guaranteed; other jurisdictions may differ.

Takeaways

  • A faithful, minimal JAX implementation of DeepSeek‑V3 can be written in under 200 lines, proving that the model’s core ideas are algorithmically simple.
  • The bias‑based load‑balancing mechanism works as advertised: it equalizes expert utilization without degrading validation loss, eliminating the need for an auxiliary loss term.
  • Training such a model on modest hardware (a MacBook Air) is feasible, offering a low‑bar entry point for researchers and hobbyists to experiment with modern LLM techniques.

Sources

Related