AI Systems First-Principles AI From Zero · Companion 01

AI From Zero: A Seven-Stage Engineering Roadmap

How to move from scalar derivatives and simple neural networks to tokenizers, self-attention, and working language models without skipping the mechanics.

Most engineers first encounter modern artificial intelligence through a high-level SDK call: pass a string into an endpoint, parse a completion, and wire the output into a product. That workflow builds prototypes quickly, yet it creates a fragile ceiling. When latency spikes, when a model hallucinates across non-English scripts, or when fine-tuning collapses after three epochs, API familiarity offers no diagnostic lens.

AI From Zero takes the opposite route. Inspired by Andrej Karpathy’s open Neural Networks: Zero to Hero progression and adapted for multilingual self-study, you reconstruct the entire modern language-modelling stack in seven progressively richer layers—writing enough code at each stage to see why every component exists and what breaks when you remove it.

Why Bottom-Up Intuition Compounds

Large language models look intimidating at scale because production clusters fuse distributed parallelism, mixed-precision kernels, and multi-terabyte data pipelines. Yet the mathematical core inside a billion-parameter Transformer is surprisingly small: differentiable tensor arithmetic, probability distributions over discrete tokens, causal self-attention, and gradient descent.

Once you have built a tiny working version of each primitive yourself, research papers stop reading like folklore. A new positional encoding scheme, a normalisation placement tweak, or a tokenizer vocabulary change immediately slots into a mental model you already own.

The Seven-Stage Curriculum Architecture

Each stage below isolates a single conceptual leap. Do not rush to stage six before you can debug stage two by hand.

Stage Core Primitive Built Mathematical Concept Unlocked Primary Failure Mode Observed
01. Scalar Autograd Value node & reverse-mode graph Chain rule on directed acyclic graphs Forgetting to zero gradients between steps
02. Neural Perceptrons Multi-layer perceptron (MLP) Non-linear activations & parameter updates Vanishing gradients from saturated tanh
03. Bigram & Character LMs Next-character probability table Negative log-likelihood & cross-entropy loss Overfitting small vocabularies without smoothing
04. Activation & Normalisation Batch / Layer Normalisation & residual paths Variance stability across deep layers Exploding activations before the first epoch finishes
05. Subword Tokenization Byte Pair Encoding (BPE) Information-theoretic text compression Token fertility penalties on Persian, Arabic & Turkish
06. Causal Self-Attention Multi-head Transformer decoder Query–Key–Value routing & causal masking Context leakage if future positions are unmasked
07. Alignment & Evaluation Deterministic evals & post-training Calibration, refusal boundaries & structured output Metric gaming when test prompts leak into training

The Minimal Training Loop Beneath Every Model

Whether you train a 200-parameter scalar network on a laptop or a frontier foundation model across thousands of accelerators, the core optimisation heartbeat stays structurally identical:

def train_step(model, batch_inputs, batch_targets, learning_rate: float) -> float:
    # 1. Forward pass: map discrete inputs to unnormalised logits
    logits = model.forward(batch_inputs)

    # 2. Objective: measure surprise via cross-entropy loss
    loss = cross_entropy_loss(logits, batch_targets)

    # 3. Backward pass: clear stale buffers, then accumulate gradients
    model.zero_grad()
    loss.backward()

    # 4. Update: nudge every parameter opposite to its loss gradient
    for param in model.parameters():
        param.data -= learning_rate * param.grad

    return float(loss.data)

Read those four phases carefully. Almost every practical debugging session in machine learning reduces to isolating which of those four lines misbehaved: bad input preprocessing before line 1, a numerically unstable loss on line 2, broken gradient flow on line 3, or an aggressive step size on line 4.

How to Study Each Stage Effectively

Passive video watching creates the illusion of competence. Real retention requires tightening the feedback loop between theory and broken code:

  1. Predict before running. Before launching a training run, calculate the theoretical initial loss at random initialisation. For a uniform character model over 27 symbols, initial negative log-likelihood must sit near ln(27) ≈ 3.296. If your run starts at 11.4, your logits are mis-scaled before step one even occurs.
  2. Plot activation distributions, not just scalar loss. A decreasing training loss can still hide dead neurons or saturated pre-activations that will stall learning later.
  3. Test multilingual edge cases early. Run your tokenizer on English, Persian, Arabic, and Turkish sentences side by side. Seeing a single Persian phrase expand into three times as many tokens as its English equivalent explains context-window economics better than any slide deck.
  4. Build a frozen evaluation set before iterating. Never judge model changes by glancing at two cherry-picked completions. Maintain a small, versioned suite of deterministic checks covering syntax, reasoning steps, and refusal discipline.

Where to Go Next

Begin with Inside Automatic Differentiation to build the scalar engine from stage one, then jump forward to Reliable AI Agent Systems to see how probabilistic language models are wrapped inside deterministic engineering guardrails for production workloads.

Continue Reading