Skip to main content
Interactive Curriculum & TrackerPhase 0 – Phase 841 Modules · 410 Topics

Your Complete Journey Into AI & LLM Development

Start with Python and mathematics, master machine learning and neural networks, understand Transformers, and eventually build and train your own language models from scratch.

9 Structured Learning Phases

Prerequisite-ordered progression

~78 Weeks of Planned Study

Est. at ~15–20 hrs/wk focused study

14 Hands-on Projects

Across the complete curriculum

Beginner to Advanced

Zero prerequisites to LLM research

Free Learning Resources

Open university lectures & guides

Study Pace Estimate: The ~78-week duration is an estimate assuming roughly 15–20 hours of focused study and coding per week. All phases are unlocked so experienced programmers or mathematicians can move faster or jump directly to later phases.

Overall Learning Progress

Curriculum Mastery Ledger

0%

Topics Mastered

Topic Checklist Completion0 / 410 topics

Phases

0/9

Completed

Modules

0/41

100% checked

Milestones

0/14

Core projects

Recommended Next TopicP0 · Module 0.1

Python Fundamentals: Variables and data types

Saved automatically in your browser (localStorage)
Connected 9-Phase Architecture

Interactive Phase Navigation

All 9 phases are unlocked. Select any phase to jump directly to its modules, or switch between full curriculum overview and single-phase focus mode.

PHASE 0 · P04 WeeksBeginnerNot Started

Phase 0 — Programming Foundations

Purpose: Develop the Python and numerical programming skills required to understand and implement machine-learning algorithms.

Phase Progress0%
0 / 37 topics0 / 4 modules

Recommended Prerequisites

Phases are never locked—jump directly here if you already know these foundations:

  • Basic computer literacy and high-school algebra; no prior AI or programming experience required.

Phase 0 Learning Objectives

  • Write clean, modular, type-annotated Python programs independently.
  • Understand how Python manages memory, references, mutability, and iteration under the hood.
  • Manipulate multi-dimensional vectors, matrices, and tensors using NumPy broadcasting and vectorization.
  • Use professional data science and engineering workflows including Pandas, Matplotlib, Git, virtual environments, and pytest.

Detailed Modules & Topic Checklists (4)

0/13 topics0%
What You'll Learn

You will master the building blocks of Python—from primitive types, control structures, and collections to classes, generators, decorators, file I/O, static type hints, and automated unit testing.

Why It Matters for AI & LLMs

Python is the universal host language of modern AI research and production engineering. Clean abstractions, type hints, and unit tests prevent silent tensor-shape bugs when building neural network pipelines.

Module Learning Objectives
  • Write clean Python programs independently.
  • Select the appropriate collection type (list, tuple, set, dict) based on lookup and mutability needs.
  • Design reusable classes and functions with explicit type annotations and unit tests.
Key Concepts
Primitive types & control flowHash maps (dict) & setsComprehensions & generatorsObject-oriented classesType hints & pytest
Topics to Master (0/13)
  • Variables bind names to objects in memory. Core scalar types include integers (`int`), IEEE-754 floating-point numbers (`float`), booleans (`bool`), and Unicode strings (`str`).

    learning_rate: float = 3e-4 batch_size: int = 32
    Dynamic typingint vs float precisionBoolean truthinessString formatting

    Outcome: Declare, inspect, and convert scalar data types without implicit type-coercion bugs.

  • Conditional branches (`if`, `elif`, `else`) and loops (`for`, `while`, `break`, `continue`) direct execution order—such as iterating over training epochs and stopping early when validation loss plateaus.

    Conditional branchingfor/while loopsenumerate() & zip()Early termination

    Outcome: Structure multi-step iterative algorithms such as training loops and convergence checks.

  • Functions encapsulate reusable logic with explicit inputs, default parameters, keyword arguments, and return values, keeping data preprocessing and mathematical formulas modular.

    Positional vs keyword argsDefault parametersPure functionsVariable scope (LEGB)

    Outcome: Decompose complex mathematical procedures into small, testable pure functions.

  • Lists store ordered mutable sequences; tuples represent fixed immutable records (like tensor shapes `(batch, seq_len, d_model)`); sets track unique tokens; dictionaries map keys to values in O(1) average time (like token-to-ID vocabularies).

    vocab: dict[str, int] = {'<pad>': 0, '<bos>': 1, 'ai': 2} tensor_shape: tuple[int, int, int] = (4, 128, 768)
    List indexing & slicingImmutable tuples for shapesO(1) set membershipDictionary hash tables

    Outcome: Build token vocabularies and dataset indexes using optimal built-in data structures.

  • Comprehensions provide a concise, readable syntax for transforming and filtering sequences or inverting token-to-ID lookup tables in a single expression.

    id_to_token = {idx: tok for tok, idx in vocab.items()}
    List comprehensionFiltering predicatesDictionary inversionSet comprehension

    Outcome: Transform datasets and invert vocabulary mappings cleanly without verbose boilerplate loops.

  • Classes bundle state (attributes like layer weights and biases) with behavior (methods like `forward()` and `parameters()`). Every PyTorch `nn.Module` you write later is a Python class.

    __init__ constructorInstance attributes (self)Dunder methods (__call__, __repr__)Inheritance

    Outcome: Model stateful components such as neural network layers, optimizers, and tokenizers as classes.

  • Generators use `yield` to produce items lazily one batch at a time rather than loading terabytes of training text into RAM all at once.

    Lazy evaluationyield keywordGenerator expressionsStreaming data batches

    Outcome: Write memory-efficient data loaders that stream batches from large files.

  • Decorators wrap functions to add cross-cutting behavior—such as timing execution, caching results, or disabling gradient tracking with `@torch.no_grad()`.

    Higher-order functionsClosures@functools.wrapsExecution timing wrappers

    Outcome: Create and apply decorators for profiling, logging, and state management.

  • Structured `try/except/finally` blocks and custom `ValueError` assertions catch mismatched matrix dimensions or corrupted dataset rows immediately with informative diagnostics.

    Exception hierarchyRaising ValueError on shape mismatchContext managers (with)Fail-fast validation

    Outcome: Guard mathematical functions with explicit shape and domain validations.

  • Organizing code across separate `.py` modules and packages (`__init__.py`) separates model definitions, data pipelines, training loops, and evaluation suites.

    Absolute vs relative importsPackage structure__name__ == '__main__'Namespace hygiene

    Outcome: Structure multi-file Python projects cleanly instead of working in a single script.

  • Context managers (`with open(...)`) and `pathlib.Path` safely read and write UTF-8 text corpora, JSON configurations, and binary model checkpoints.

    pathlib.PathContext managersUTF-8 encodingJSON & binary serialization

    Outcome: Read training corpora and persist configuration files safely across operating systems.

  • Static type annotations (`def matmul(a: list[list[float]], b: list[list[float]]) -> list[list[float]]:`) document contracts and catch bugs before a long training run starts.

    Function signaturesGeneric collectionsOptional & Union typesStatic type checking

    Outcome: Annotate functions and classes so inputs, outputs, and collection types are self-documenting.

  • Unit tests (`pytest`), assertions, and interactive debuggers (`pdb` / IDE breakpoints) verify that custom mathematical implementations match analytical reference values.

    pytest assertionsEdge-case testingFloating-point approximate equalityStack trace inspection

    Outcome: Write automated unit tests that verify mathematical correctness and edge cases.

Practice Exercises
  • 1.Write a type-annotated `Matrix` class in pure Python supporting shape inspection, transpose, and element-wise addition.
  • 2.Build a lazy generator `batch_iterable(items, batch_size)` that yields fixed-size chunks from a large text file.
  • 3.Write a `pytest` suite verifying your `Matrix` class against hand-calculated 2×3 and 3×2 examples.
Recommended Module Courses & Resources
2 Matched Resources
Module Completion Milestone: Write clean Python programs independently with classes, generators, type hints, and unit tests.
0/7 topics0%
0/8 topics0%
0/9 topics0%

Phase 0 Practical Assignments

Complete these focused coding exercises while progressing through the modules above:

  1. 1Implement matrix multiplication without NumPy.
  2. 2Implement matrix multiplication using NumPy.
  3. 3Build vector operations.
  4. 4Write a simple numerical derivative calculator.
  5. 5Read and clean a CSV dataset.
  6. 6Plot mathematical functions and derivatives.
  7. 7Build a small reusable matrix operations library.

Hands-On Project Milestones

1 Primary Curriculum Milestone
Milestone #1 of 14BeginnerNot Started

Matrix Operations Engine

Build a complete pure-Python linear algebra engine implementing vector addition, scalar multiplication, dot products, 2D matrix multiplication, transposes, and automated verification against NumPy.

Implementation Task Progress0 / 12 steps (0%)
2D matrix multiplication & transposesVector addition, scaling & dot productsShape validation & dimension error handlingAutomated verification against NumPy
Expected Outcome: A self-contained, unit-tested Python matrix operations library verified against NumPy.
Open Project Guide
Supplementary Phase BuildOptional Practice

Reusable Vector & Matrix Operations Toolkit

A tested Python + NumPy package implementing dot products, matrix multiplication, finite-difference derivatives, and diagnostic plotting (prepares directly for Milestone 1 in Phase 1).

Phase 0 Completion Criteria & Self-Assessment

User should be able to explain array shapes, matrix multiplication, and numerical computing without blindly relying on libraries.

Readiness Check: 0 / 5

Self-assessment readiness checks help you verify conceptual mastery before moving on (tracked separately from topic completion percentage):

  • Can you explain array shapes, broadcasting rules, and matrix multiplication inner dimensions without guessing?

    Verify you can predict the output shape of (B, T, D) @ (B, D, V) + (V,) on paper.

  • Have you completed all 7 Phase 0 practical assignments?

    Including both pure-Python and NumPy matrix multiplication, CSV cleaning, and derivative plotting.

  • Can you implement vector dot products and 2D matrix multiplication independently in pure Python?

    Without looking up loop indices or relying on external libraries.

  • Have you written automated unit tests comparing your pure-Python matrix routines against NumPy?

    Using pytest and floating-point tolerance assertions.

  • Can you explain why pure-Python nested loops are orders of magnitude slower than vectorized NumPy operations?

    Referencing interpreter dispatch, object boxing, and contiguous C memory buffers.

PHASE 1 · P18 WeeksBeginner → IntermediateNot Started

Phase 1 — Mathematics for AI

Purpose: Understand the mathematics behind machine learning, optimization, and neural networks.

Phase Progress0%
0 / 59 topics0 / 4 modules

Recommended Prerequisites

Phases are never locked—jump directly here if you already know these foundations:

Phase 1 Learning Objectives

  • Represent data features, neural layer weights, and linear transformations using vectors, matrices, and tensors.
  • Derive partial derivatives, gradients, and chain-rule expressions for multivariable loss functions.
  • Model uncertainty and next-token prediction using probability distributions, maximum likelihood, entropy, and cross-entropy.
  • Implement gradient-based optimization algorithms (SGD, Momentum, RMSProp, Adam) and verify gradients numerically.

Detailed Modules & Topic Checklists (4)

0/17 topics0%
What You'll Learn

You will learn how vectors and matrices act as geometric transformations, how dot products and cosine similarity measure directional alignment in high-dimensional embedding spaces, and how matrices decompose via eigenvalues and Singular Value Decomposition (SVD).

Why It Matters for AI & LLMs

Every forward pass in a neural network or Transformer attention head is a sequence of linear combinations, dot products, and matrix multiplications interleaved with simple non-linearities.

Core Mathematical & Algorithmic IntuitionHow an Artificial Neuron Uses a Weighted Sum
z = w₁·x₁ + w₂·x₂ + b = wᵀx + b
x = [x₁, x₂]ᵀInput feature vector representing measurable properties of a data sample.
w = [w₁, w₂]ᵀLearnable weight vector controlling how strongly each input feature influences the output.
w₁·x₁ + w₂·x₂ (or wᵀx)The dot product (weighted sum) measuring alignment between the input vector x and weight vector w.
bScalar bias term that shifts the activation threshold unabhängig of the origin.
zPre-activation scalar score before passing through a non-linear activation function.

Key Takeaway: A single neuron is simply a dot product plus a bias; a full layer of M neurons computes Z = XW + b across an entire batch of inputs simultaneously using matrix multiplication.

Module Learning Objectives
  • Compute dot products, matrix-vector products, and matrix-matrix products by hand and in code.
  • Explain how neurons compute weighted sums of inputs plus a bias term.
  • Measure vector magnitude and directional similarity using L2 norms, Euclidean distance, and cosine similarity.
  • Understand matrix rank, orthogonality, projections, eigenvectors, and low-rank approximations via SVD.
Key Concepts
Weighted sums & hyperplanesDot products & cosine similarityLinear transformations & rankOrthogonal projectionsEigenvalues & SVD
Topics to Master (0/17)
  • A scalar is a single number (0D); a vector is an ordered 1D array of numbers; a matrix is a 2D grid of rows and columns; a tensor generalizes arrays to 3 or more axes (such as `[batch, seq_len, d_model]`).

    Rank / order of a tensorColumn vs row vectorsDimension indexingBatch tensors

    Outcome: Identify the rank and dimensional semantics of scalars, vectors, matrices, and higher-order tensors.

  • A vector space $\mathbb{R}^n$ is a collection of $n$-dimensional vectors closed under vector addition and scalar multiplication, serving as the coordinate system where feature representations and embeddings live.

    Closure under addition & scalingBasis vectorsSpan and dimensionalityFeature spaces

    Outcome: Interpret data samples and word embeddings as points and directions in an $n$-dimensional vector space.

  • Adding two vectors of the same dimension sums their corresponding components ($u + v = [u_1+v_1, \dots, u_n+v_n]^T$), geometrically translating one vector along the other—used directly in residual connections (`x + sublayer(x)`).

    Component-wise sumTip-to-tail geometric ruleResidual stream addition

    Outcome: Compute vector sums algebraically and interpret them geometrically.

  • Multiplying a vector by a scalar $c$ stretches or shrinks its magnitude by $|c|$ (and reverses its direction if $c < 0$) without changing the line it lies on.

    Magnitude scalingDirection reversalLearning rate scaling of gradient vectors

    Outcome: Scale vectors and understand how scalar factors affect magnitude and direction.

  • A linear combination $c_1 v_1 + c_2 v_2 + \dots + c_k v_k$ blends multiple vectors using scalar weights. In self-attention, every output token is a weighted linear combination of Value vectors.

    Weighted sums of vectorsLinear independenceSpan of a set of vectorsAttention value mixing

    Outcome: Express matrix-vector products and attention outputs as linear combinations of columns or rows.

  • The dot product $u \cdot v = \sum_{i=1}^n u_i v_i = \|u\| \|v\| \cos(\theta)$ combines algebraic multiplication with geometric angle: it is positive when vectors point in similar directions, zero when orthogonal, and negative when opposed.

    z = w1 * x1 + w2 * x2 + b # Dot product w·x plus bias b
    Algebraic definitionGeometric cosine relationshipPre-activation neuron scoreQuery-Key attention score

    Outcome: Calculate dot products and interpret them as unnormalized similarity scores.

  • For $A \in \mathbb{R}^{m \times k}$ and $B \in \mathbb{R}^{k \times n}$, entry $(i, j)$ of $C = AB$ is the dot product of row $i$ of $A$ with column $j$ of $B$, transforming a batch of $m$ input vectors of dimension $k$ into dimension $n$.

    Row-by-column dot productsColumn-space viewNon-commutativity (AB != BA)Linear layer forward pass X @ W

    Outcome: Perform matrix multiplication by hand and explain why inner dimensions must match.

  • The transpose $A^T$ swaps rows and columns ($(A^T)_{ij} = A_{ji}$) and satisfies $(AB)^T = B^T A^T$—used constantly when computing attention scores $QK^T$ and weight gradients during backpropagation.

    Row-column swapProduct transpose rule (AB)ᵀ = BᵀAᵀSymmetric matrices (A = Aᵀ)

    Outcome: Apply matrix transposes to align dimensions in forward and backward passes.

  • A square matrix $A$ is invertible if there exists $A^{-1}$ such that $AA^{-1} = I$. In practice, explicit inversion is numerically unstable and avoided in favor of solving linear systems $Ax = b$ or gradient optimization.

    Identity matrix ISingular (non-invertible) matricesSolving Ax = b vs computing A⁻¹

    Outcome: Explain when a matrix inverse exists and why numerical solvers avoid explicit matrix inversion.

  • The rank of a matrix is the number of linearly independent rows or columns—the true dimensionality of the subspace onto which the matrix maps inputs. Low-Rank Adaptation (LoRA) exploits low-rank weight updates.

    Full rank vs rank-deficientColumn space dimensionLow-rank decomposition (B @ A where r << d)

    Outcome: Determine matrix rank and explain how low-rank factorizations compress parameter updates.

  • Every matrix represents a linear transformation that maps vectors from one space to another while preserving grid lines parallel and evenly spaced (rotations, reflections, shears, projections).

    Matrices as functionsWhere basis vectors landComposition of transformations via matrix product

    Outcome: Visualize neural network weight matrices as geometric transformations of space.

  • Two vectors are orthogonal if $u \cdot v = 0$. Orthogonal projection finds the closest point in a subspace to a target vector, forming the geometric foundation of least-squares linear regression.

    u · v = 0Orthonormal bases (QᵀQ = I)Projection formulaLeast-squares error vector

    Outcome: Project vectors onto subspaces and explain why the residual error is orthogonal to the subspace.

  • Norms measure vector magnitude: the $L_1$ norm ($\sum |x_i|$) promotes sparsity, the $L_2$ Euclidean norm ($\sqrt{\sum x_i^2}$) measures straight-line length and powers weight decay and gradient clipping, and $L_\infty$ tracks the maximum absolute entry.

    L1 norm (Manhattan)L2 norm (Euclidean)Frobenius matrix normGradient norm clipping

    Outcome: Compute L1 and L2 norms and apply them to regularization and vector normalization.

  • The Euclidean distance $\|u - v\|_2 = \sqrt{\sum (u_i - v_i)^2}$ measures straight-line separation between two points in feature space, used in k-nearest neighbors and k-means clustering.

    ||u - v||₂Sensitivity to vector scaleSquared Euclidean distance in MSE

    Outcome: Compute pairwise Euclidean distances between feature vectors in vectorized form.

  • Cosine similarity $\frac{u \cdot v}{\|u\|_2 \|v\|_2} \in [-1, 1]$ normalizes the dot product by vector lengths, measuring pure directional alignment between semantic embeddings regardless of magnitude.

    Unit vector normalizationAngle invariance to scalingEmbedding retrieval similarity

    Outcome: Implement vectorized cosine similarity to compare high-dimensional embeddings.

  • An eigenvector $v$ of square matrix $A$ only gets scaled (not rotated) when multiplied by $A$: $Av = \lambda v$. Eigenvalues $\lambda$ reveal variance directions in PCA and curvature in Hessian matrices.

    Av = λvCharacteristic equationSpectral theorem for symmetric matricesPrincipal directions

    Outcome: Explain what eigenvectors and eigenvalues represent geometrically and algebraically.

  • Any $m \times n$ matrix factors as $A = U \Sigma V^T$ into orthogonal rotation $V^T$, diagonal scaling $\Sigma$ (singular values), and orthogonal rotation $U$—enabling dimensionality reduction and low-rank matrix approximation.

    A = UΣVᵀSingular valuesEckart-Young low-rank approximationConnection to PCA and LoRA

    Outcome: Decompose matrices with SVD and construct rank-$k$ approximations.

Practice Exercises
  • 1.Compute $z = w_1 x_1 + w_2 x_2 + b$ by hand and in Python for a 3-sample batch, then generalize to $Z = XW + b$.
  • 2.Implement a cosine similarity search function that ranks 5 candidate embedding vectors against a query vector.
  • 3.Use SVD (`np.linalg.svd`) to compress a 2D grayscale image matrix using only its top $k=15$ singular values.
Recommended Module Courses & Resources
3 Matched Resources
Module Completion Milestone: Perform vector and matrix operations fluently, explain weighted sums in neurons, and implement Project Milestone 1 (Matrix Operations Engine).
0/12 topics0%
0/18 topics0%
0/12 topics0%

Phase 1 Practical Assignments

Complete these focused coding exercises while progressing through the modules above:

  1. 1Implement vector and matrix operations.
  2. 2Calculate cosine similarity.
  3. 3Write numerical derivatives.
  4. 4Implement gradient descent.
  5. 5Implement linear regression mathematically.
  6. 6Implement logistic regression and manually calculate gradients.
  7. 7Compare analytical and numerical gradients.

Hands-On Project Milestones

1 Primary Curriculum Milestone
Milestone #2 of 14Beginner → IntermediateNot Started

Linear Regression From Scratch

Train a regression model without using a predefined machine-learning estimator—deriving analytical MSE gradients manually, implementing gradient descent, plotting loss convergence, and evaluating on held-out data.

Implementation Task Progress0 / 12 steps (0%)
Vectorized MSE loss & analytical gradientsGradient descent & learning rate schedulesLoss curve visualization & convergenceHeld-out evaluation & library comparison
Expected Outcome: A complete linear regression training pipeline with derived gradients and diagnostic plots.
Open Project Guide

Phase 1 Completion Criteria & Self-Assessment

Explain derivatives, gradients, matrix operations, probability distributions, and how parameters are updated during training.

Readiness Check: 0 / 5

Self-assessment readiness checks help you verify conceptual mastery before moving on (tracked separately from topic completion percentage):

  • Can you explain the geometric meaning of dot products, gradients, and cross-entropy loss?

    Including why neurons use z = w·x + b and why language models minimize negative log-likelihood.

  • Have you completed all 7 Phase 1 mathematical assignments?

    Covering cosine similarity, numerical derivatives, gradient descent, and manual logistic gradients.

  • Can you write the gradient descent update w_new = w_old - lr * grad and stable softmax from memory?

    Including the max-logit shift that prevents floating-point overflow.

  • Have you verified your analytical gradients against centered finite-difference numerical gradients?

    Achieving relative error below 1e-6.

  • Can you explain Milestone #1 (Matrix Operations Engine) and how its O(N³) complexity scales?

    Understanding both algorithmic correctness and memory layout.

PHASE 2 · P28 WeeksIntermediateNot Started

Phase 2 — Machine Learning From Scratch

Purpose: Understand how algorithms learn patterns and generalize to unseen data.

Phase Progress0%
0 / 44 topics0 / 4 modules

Recommended Prerequisites

Phases are never locked—jump directly here if you already know these foundations:

Phase 2 Learning Objectives

  • Distinguish supervised, unsupervised, and self-supervised learning paradigms.
  • Implement linear and logistic regression from scratch using NumPy and gradient-based training.
  • Implement classical ML algorithms (KNN, Decision Trees, Naive Bayes, K-Means, PCA) in NumPy before comparing with scikit-learn.
  • Design leak-free train/validation/test splits and evaluate models with precision, recall, F1, ROC-AUC, and RMSE.

Detailed Modules & Topic Checklists (4)

0/16 topics0%
What You'll Learn

You will learn the foundational principles of statistical learning: how models generalize beyond their training set, why separate validation and test splits are mandatory, how bias and variance trade off, and how regularization penalizes excessive model complexity.

Why It Matters for AI & LLMs

Every failure mode of classical ML—overfitting, distribution shift, hyperparameter over-tuning, and train-test contamination—reappears at massive scale when pretraining and evaluating Large Language Models.

Module Learning Objectives
  • Distinguish supervised, unsupervised, and self-supervised learning (the paradigm behind LLM pretraining).
  • Diagnose high bias (underfitting) versus high variance (overfitting) from training and validation learning curves.
  • Prevent data leakage when scaling features or selecting hyperparameters.
Key Concepts
Supervised vs self-supervised learningTrain / validation / test splitsParameters vs hyperparametersBias-variance tradeoffL1/L2 regularization & data leakage
Topics to Master (0/16)
  • Rather than hand-coding explicit decision rules, machine learning optimizes parameterized mathematical functions so they extract statistical regularities directly from data.

    Data-driven parameter estimationTask, performance measure, experienceML vs rule-based software

    Outcome: Articulate when a problem calls for machine learning versus deterministic programming.

  • Learning a mapping $f_\theta: X \to Y$ from labeled input-output pairs $(x_i, y_i)$—predicting continuous targets (regression) or discrete categories (classification).

    Labeled datasetsRegression vs classificationEmpirical risk minimization

    Outcome: Formulate regression and classification tasks with explicit input features and target labels.

  • Discovering latent structure, clusters, or low-dimensional manifolds in unlabeled data $X$ without human annotations (clustering, dimensionality reduction, density estimation).

    Unlabeled dataClusteringLatent representations

    Outcome: Identify structure discovery tasks where ground-truth labels do not exist.

  • Generating supervisory labels automatically from the structure of raw data itself—such as predicting the next token from preceding tokens in raw text corpora, enabling LLM pretraining on trillions of words without human labeling.

    Pretext tasks from raw dataNext-token prediction as self-supervisionScaling without manual labels

    Outcome: Explain why self-supervised learning unlocked modern foundation models and LLMs.

  • Features ($X \in \mathbb{R}^{N \times d}$) are the measurable input attributes of each example; labels ($y$) are the target outcomes the model is trained to predict.

    Design matrix XTarget vector yNumerical vs categorical features

    Outcome: Construct clean feature matrices $X$ and target vectors $y$ from raw domain records.

  • The training set fits parameters $\theta$; the validation set tunes hyperparameters and selects architectures; the held-out test set is evaluated once at the end to measure unbiased generalization.

    Three-way dataset partitioningStratified splittingTemporal splitting for time series

    Outcome: Partition datasets into train, validation, and test splits appropriately for the domain.

  • Parameters (weights $W$ and biases $b$) are internal variables updated automatically by optimization algorithms during training.

    Weights & biasesParameter countLearned state

    Outcome: Calculate the exact number of trainable parameters in linear and neural models.

  • Hyperparameters (learning rate $\eta$, regularization strength $\lambda$, polynomial degree, number of layers) are configuration choices set prior to training and tuned on the validation split.

    Learning rateRegularization strengthGrid & random search on validation set

    Outcome: Distinguish trainable parameters from hyperparameters and tune them systematically.

  • Overfitting occurs when a model memorizes noise and idiosyncrasies in the training set, achieving low training loss but high validation/test loss.

    Memorization vs learningDiverging train and validation loss curvesExcessive capacity

    Outcome: Detect overfitting early by comparing training and validation loss curves.

  • Underfitting occurs when a model is too simple or insufficiently trained to capture the underlying signal, resulting in high error on both training and validation data.

    Insufficient model capacityHigh training lossFeature poverty

    Outcome: Diagnose underfitting and remedy it by increasing model capacity or improving features.

  • Expected generalization error decomposes into Bias² (systematic error from overly restrictive assumptions), Variance (sensitivity to fluctuations in the training sample), and irreducible noise.

    Error = Bias² + Variance + NoiseModel complexity spectrumSweet spot of generalization

    Outcome: Explain the bias-variance decomposition and how model complexity shifts the balance.

  • Generalization is a model's ability to perform accurately on new, unseen examples drawn from the same underlying distribution.

    In-distribution generalizationOut-of-distribution (OOD) shiftInductive bias

    Outcome: Measure and reason about a model's generalization gap.

  • Data leakage happens when information from the validation or test set inadvertently enters training—such as computing normalization mean/std across the whole dataset before splitting, or target leakage in features.

    Fit scaler on train onlyTarget leakageDuplicate examples across splits (contamination)

    Outcome: Audit ML pipelines to guarantee zero information leakage from validation/test splits.

  • Standardizing features to zero mean and unit variance ($z = (x - \mu_{\text{train}})/\sigma_{\text{train}}$) or min-max scaling transforms elongated loss contours into circular ones so gradient descent converges rapidly.

    Z-score standardizationMin-max normalizationEffect on gradient descent conditioning

    Outcome: Implement leak-free feature standardization fitting statistics strictly on the training split.

  • Adding a complexity penalty to the loss—$L_2$ Ridge ($\lambda \|w\|_2^2$, equivalent to weight decay) or $L_1$ Lasso ($\lambda \|w\|_1$, inducing sparse zero weights)—constrains parameter magnitude to reduce variance.

    L2 Ridge (weight decay)L1 Lasso (sparsity)Early stopping

    Outcome: Derive and implement L1 and L2 regularization penalties in loss and gradient calculations.

  • $K$-fold cross-validation partitions training data into $K$ folds, training $K$ times while rotating the validation fold to obtain a low-variance estimate of generalization performance.

    K-fold rotationStratified K-foldHyperparameter selection stability

    Outcome: Implement $K$-fold cross-validation from scratch in NumPy.

Practice Exercises
  • 1.Fit polynomial regression models of degrees 1, 3, and 15 on noisy synthetic data and plot training vs. validation error to visualize underfitting, optimal fit, and overfitting.
  • 2.Demonstrate how fitting a `StandardScaler` before train/test splitting leaks test statistics, and implement the leak-free pipeline.
Recommended Module Courses & Resources
5 Matched Resources
Module Completion Milestone: Design leak-free train/validation/test pipelines, diagnose bias vs. variance, and apply L2 regularization.
0/8 topics0%
0/8 topics0%
0/12 topics0%

Phase 2 Practical Assignments

Complete these focused coding exercises while progressing through the modules above:

  1. 1Implement multivariable linear regression with MSE loss and L2 regularization in NumPy.
  2. 2Implement binary logistic regression with BCE loss and gradient descent in NumPy.
  3. 3Implement K-Nearest Neighbors, K-Means, and PCA in NumPy.
  4. 4Build a complete Spam Classification pipeline comparing Multinomial Naive Bayes and Logistic Regression.
  5. 5Produce a full evaluation report with confusion matrices, Precision, Recall, F1, and ROC-AUC.

Hands-On Project Milestones

1 Primary Curriculum Milestone
Milestone #3 of 14IntermediateNot Started

Spam Classifier

Build an end-to-end email/SMS spam classification system implementing text preprocessing, Bag-of-Words/TF-IDF feature extraction, and a Naive Bayes or Logistic Regression classifier from scratch.

Implementation Task Progress0 / 11 steps (0%)
Text preprocessing, tokenization & TF-IDFLog-space Naive Bayes & Logistic RegressionPrecision, Recall, and F1 evaluationError analysis & scikit-learn baseline comparison
Expected Outcome: A working text classification system with precision, recall, F1, and misclassification analysis.
Open Project Guide
Supplementary Phase BuildOptional Practice

Logistic Regression Classifier & Decision Boundary Visualizer

Standalone binary and multiclass (softmax) logistic classifier with 2D contour plotting of linear and polynomial decision boundaries.

Phase 2 Completion Criteria & Self-Assessment

Train, evaluate, and compare classical machine-learning models, including at least one manually implemented classifier.

Readiness Check: 0 / 5

Self-assessment readiness checks help you verify conceptual mastery before moving on (tracked separately from topic completion percentage):

  • Can you explain the bias-variance tradeoff, data leakage, and why self-supervised learning powers LLMs?

    Contrasting supervised labeled tasks with next-token self-supervision.

  • Have you implemented linear regression, logistic regression, and Naive Bayes in NumPy?

    Without relying on scikit-learn's .fit() for the core algorithms.

  • Can you derive and code the vectorized gradients for MSE and Binary Cross-Entropy?

    Showing why both reduce to forms of (1/N) Xᵀ(prediction - target).

  • Have you evaluated your Spam Classifier using Precision, Recall, F1, and ROC-AUC rather than raw accuracy alone?

    Including a comparison against a majority-class dummy baseline.

  • Can you explain why linear classifiers fail on non-linearly separable patterns (like XOR) without manual feature engineering?

    Motivating the transition to multi-layer neural networks in Phase 3.

PHASE 3 · P38 WeeksIntermediate → AdvancedNot Started

Phase 3 — Deep Learning & Neural Networks

Purpose: Implement neural networks and understand their internal training mechanisms.

Phase Progress0%
0 / 46 topics0 / 4 modules

Recommended Prerequisites

Phases are never locked—jump directly here if you already know these foundations:

Phase 3 Learning Objectives

  • Explain and implement forward propagation, activation functions, and backpropagation across multi-layer networks.
  • Build a micrograd-style reverse-mode automatic differentiation engine in pure Python.
  • Master PyTorch tensors, autograd, nn.Module layers, DataLoaders, checkpointing, and mixed-precision training loops.
  • Understand the inductive biases of CNNs, RNNs, LSTMs, Autoencoders, and Reinforcement Learning.

Detailed Modules & Topic Checklists (4)

0/19 topics0%
What You'll Learn

You will learn how stacking linear matrix transformations with non-linear activation functions enables neural networks to approximate arbitrary functions, and how initialization, normalization, and residual connections keep gradients healthy across deep layers.

Why It Matters for AI & LLMs

Without non-linear activations, a 100-layer network collapses into a single linear matrix multiplication. Without proper initialization, normalization, and residual connections, deep networks fail to train due to vanishing or exploding gradients.

Module Learning Objectives
  • Implement forward and backward passes for linear layers and modern activations (ReLU, GELU, SiLU, Softmax).
  • Explain why Xavier/He weight initialization and Layer/Batch Normalization stabilize activation variance.
  • Trace how residual connections ($y = x + F(x)$) create an unimpeded gradient highway during backpropagation.
Key Concepts
Affine layers + non-linearitiesReLU, GELU & SiLU activationsForward & backward propagationXavier / He initializationNormalization & residual highways
Topics to Master (0/19)
  • A computational unit that computes a weighted sum of inputs plus a bias ($z = w^T x + b$) and applies a non-linear activation function $a = \phi(z)$.

    Pre-activation zPost-activation aGeometrical half-space

    Outcome: Implement a single artificial neuron forward and backward step.

  • Rosenblatt's classical binary threshold classifier; its inability to solve non-linearly separable tasks like XOR proved the necessity of multi-layer networks with smooth differentiable activations.

    Step threshold functionLinear separability limit (XOR)Historical motivation for MLPs

    Outcome: Demonstrate why a single perceptron cannot separate XOR and how a 2-layer network solves it.

  • For a layer mapping $d_{\text{in}} \to d_{\text{out}}$, the weight matrix $W \in \mathbb{R}^{d_{\text{in}} \times d_{\text{out}}}$ rotates/scales inputs and the bias vector $b \in \mathbb{R}^{d_{\text{out}}}$ shifts activation thresholds.

    Parameter tensor shapesBroadcast addition of biasTotal parameter calculation

    Outcome: Calculate exact weight and bias shapes for any multi-layer architecture.

  • Multi-Layer Perceptrons (MLPs) compose sequential layers $h^{(l)} = \phi(h^{(l-1)} W^{(l)} + b^{(l)})$ without feedback loops, forming both standalone classifiers and the FFN sublayer inside every Transformer block.

    Hidden layer representationsUniversal Approximation TheoremDepth vs width

    Outcome: Assemble multi-layer feedforward networks from modular layer objects.

  • Dense linear projections (`nn.Linear`) where every output unit connects to every input unit, executing batched matrix multiplication $Y = XW + b$ accompanied by backward gradients $dX = dY \cdot W^T$ and $dW = X^T \cdot dY$.

    dX = dY @ W.T dW = X.T @ dY db = dY.sum(axis=0)
    Forward Y = XW + bInput gradient dX = dY @ WᵀWeight gradient dW = Xᵀ @ dY

    Outcome: Code a `Linear` layer class with explicit `forward()` and `backward()` methods.

  • Element-wise non-linear functions that break linearity between matrix multiplications so stacked layers learn hierarchical features.

    Why linearity collapses (W₁W₂ = W₃)Saturation & vanishing gradientsSmooth vs piecewise linear

    Outcome: Prove algebraically that stacking linear layers without activations equals a single linear layer.

  • $\sigma(x) = \frac{1}{1 + e^{-x}} \in (0, 1)$ has derivative $\sigma(x)(1 - \sigma(x)) \le 0.25$, which saturates near 0 and 1 and causes vanishing gradients in deep hidden layers, though it remains ideal for binary gates.

    Range (0, 1)Maximum derivative 0.25Tail saturation

    Outcome: Explain why sigmoid causes vanishing gradients when stacked across many layers.

  • $\tanh(x) = \frac{e^x - e^{-x}}{e^x + e^{-x}} \in (-1, 1)$ is zero-centered with derivative $1 - \tanh^2(x) \le 1$, improving over sigmoid for hidden states in RNNs/LSTMs.

    Zero-centered outputsDerivative 1 - tanh²(x)Tail saturation

    Outcome: Compare tanh and sigmoid activation dynamics and derivatives.

  • Rectified Linear Unit $\text{ReLU}(x) = \max(0, x)$ has derivative $1$ for $x > 0$ and $0$ for $x < 0$, eliminating positive-side saturation at the risk of 'dead ReLUs' when units stay negative.

    max(0, x)Non-saturating positive gradientDying ReLU phenomenon

    Outcome: Implement ReLU forward and backward passes using boolean masks.

  • Gaussian Error Linear Unit $\text{GELU}(x) = x \Phi(x)$ smoothly weights inputs by their Gaussian cumulative probability, serving as the standard activation in GPT-2, BERT, and Vision Transformers.

    Smooth probabilistic gatingNon-zero gradient for slightly negative xTanh approximation

    Outcome: Implement GELU and compare its smooth curvature near zero against ReLU.

  • Sigmoid Linear Unit (Swish) $\text{SiLU}(x) = x \cdot \sigma(x)$ pairs with gating in SwiGLU feed-forward networks used across modern LLaMA, Mistral, and DeepSeek LLMs.

    x * sigmoid(x)Smooth self-gated activationFoundation of SwiGLU

    Outcome: Implement SiLU and its analytical derivative in NumPy and PyTorch.

  • Converts a vector of arbitrary real logits $z \in \mathbb{R}^V$ into a normalized probability distribution $p_i = \frac{e^{z_i}}{\sum_j e^{z_j}}$ summing to 1.

    Simplex normalizationTemperature scaling z / TShift invariance

    Outcome: Compute softmax probabilities over vocabulary logits.

  • Combining Softmax and Negative Log-Likelihood into a single fused operation yields the clean upstream logit gradient $\frac{\partial L}{\partial z_i} = p_i - y_i$.

    Fused log-softmax + NLLAnalytical gradient p - one_hot(y)

    Outcome: Implement fused Softmax + Cross-Entropy forward and backward passes.

  • Sequentially passing input tensors through each layer while caching intermediate activations needed later during the backward pass.

    Activation cachingInference mode (no caching needed) vs training mode

    Outcome: Trace activation shapes and cached intermediates through a multi-layer forward pass.

  • Propagating upstream loss sensitivities $\frac{\partial L}{\partial a^{(l)}}$ backward from the output layer to the first layer using cached forward activations and local Jacobians.

    Reverse-mode chain ruleReusing cached activationsLinear memory & compute cost

    Outcome: Implement manual backpropagation across a 3-layer MLP without autograd.

  • Initializing weights all to zero causes symmetry (every neuron learns the same thing); too large causes exploding activations; Xavier ($1/\sqrt{d_{\text{in}}}$) and He ($\sqrt{2/d_{\text{in}}}$) preserve activation and gradient variance across depth.

    Symmetry breakingXavier / Glorot initializationKaiming / He initialization for ReLU

    Outcome: Initialize layer weights with Kaiming/Xavier scaling and verify constant activation variance across 20 layers.

  • Randomly zeroes a fraction $p$ of activations during training and scales remaining activations by $\frac{1}{1-p}$ (inverted dropout) to prevent co-adaptation, while acting as an identity pass during inference.

    Inverted dropout scaling 1/(1-p)Train vs eval mode behaviorRegularization effect

    Outcome: Implement inverted Dropout with distinct training and evaluation behavior.

  • BatchNorm normalizes across the batch dimension for CNNs; LayerNorm and RMSNorm normalize across the feature dimension independently for each token, making them standard in Transformers.

    BatchNorm vs LayerNorm vs RMSNormLearnable scale γ and shift βStabilizing deep training

    Outcome: Implement LayerNorm from scratch and explain why Transformers use LayerNorm/RMSNorm instead of BatchNorm.

  • Skip connections $y = x + F(x)$ have gradient $\frac{\partial y}{\partial x} = I + \frac{\partial F}{\partial x}$, ensuring gradients flow unimpeded through the identity term $I$ even in 100-layer networks.

    Identity skip pathwayGradient highwayResidual stream view of Transformers

    Outcome: Explain mathematically why residual connections prevent vanishing gradients in deep architectures.

Practice Exercises
  • 1.Implement a modular NumPy neural network with `Linear`, `ReLU`, `GELU`, `LayerNorm`, and `SoftmaxCrossEntropy` layers.
  • 2.Plot activation histograms across a 10-layer MLP under naive `N(0, 1)` initialization vs. He `N(0, sqrt(2/d_in))` initialization.
Recommended Module Courses & Resources
4 Matched Resources
Module Completion Milestone: Implement forward and backward propagation across a multi-layer neural network in pure NumPy (Milestone #5).
0/8 topics0%
0/13 topics0%
0/6 topics0%

Phase 3 Practical Assignments

Complete these focused coding exercises while progressing through the modules above:

  1. 1Build a micrograd-style reverse-mode automatic differentiation engine in pure Python and verify against PyTorch.
  2. 2Implement a multi-layer neural network with Linear, ReLU/GELU, LayerNorm, and SoftmaxCrossEntropy in pure NumPy.
  3. 3Train an MNIST handwritten digit classifier using both your NumPy network and a PyTorch CNN/MLP.
  4. 4Implement checkpoint saving, validation tracking, and learning-rate warmup in PyTorch.

Hands-On Project Milestones

3 Primary Curriculum Milestones
Milestone #4 of 14IntermediateNot Started

Automatic Differentiation Engine

Build a dynamic reverse-mode autodiff engine in pure Python that constructs computational DAGs, performs topological sorting, and backpropagates exact gradients through multi-layer perceptrons.

Implementation Task Progress0 / 15 steps (0%)
Dynamic computational graph constructionReverse-mode chain rule & topological sortGradient accumulation (+=) handlingParity testing against torch.autograd
Expected Outcome: A working micrograd-style autodiff engine capable of training a multi-layer neural network from scratch.
Open Project Guide
Milestone #5 of 14Intermediate → AdvancedNot Started

Neural Network From Scratch

Implement a vectorized multi-layer neural network in pure NumPy with forward activation caching, explicit backward pass Jacobians, He initialization, Dropout, LayerNorm, and Adam optimization.

Implementation Task Progress0 / 14 steps (0%)
Vectorized Linear, ReLU, GELU, and Softmax layersExplicit matrix backpropagation (dX, dW, db)He/Xavier initialization & LayerNormFinite-difference gradient verification
Expected Outcome: A modular NumPy deep learning library that trains multi-layer networks without PyTorch or TensorFlow.
Open Project Guide
Milestone #6 of 14IntermediateNot Started

Image Classifier

Build, train, and evaluate an MNIST handwritten digit and image classification pipeline in PyTorch comparing MLP and CNN architectures with checkpointing and confusion matrix diagnostics.

Implementation Task Progress0 / 12 steps (0%)
PyTorch nn.Module, Dataset & DataLoaderMLP vs 2D Convolutional Neural NetworksTraining/validation loops & checkpointingPer-class error & misclassified sample analysis
Expected Outcome: A reproducible PyTorch vision classifier achieving >98.5% test accuracy on MNIST with diagnostic visualization.
Open Project Guide
Supplementary Phase BuildOptional Practice

PyTorch Neural Network & Activation Telemetry Lab

Diagnostic experiment comparing activation distributions and gradient norms across 15 layers with and without Residual Connections and LayerNorm.

Phase 3 Completion Criteria & Self-Assessment

Explain and implement forward propagation, backward propagation, loss calculation, and parameter updates.

Readiness Check: 0 / 5

Self-assessment readiness checks help you verify conceptual mastery before moving on (tracked separately from topic completion percentage):

  • Can you explain how forward activation caching, reverse-mode autodiff, and residual connections work?

    Including why y = x + F(x) prevents vanishing gradients.

  • Have you built both the pure-Python Autograd Engine (Milestone #4) and the NumPy Neural Network (Milestone #5)?

    Verifying every backward gradient against numerical finite differences or PyTorch.

  • Can you write the forward and backward equations for a Linear layer (dX = dY @ Wᵀ, dW = Xᵀ @ dY) from memory?

    Checking that all matrix dimensions align.

  • Have you trained and evaluated your PyTorch Image Classifier (Milestone #6) with proper train/eval mode switching?

    Using model.eval() and torch.no_grad() during validation.

  • Can you explain why standard fixed-size MLPs and CNNs struggle with variable-length text sequences?

    Setting up the transition to tokenization and sequence modeling in Phase 4.

PHASE 4 · P46 WeeksIntermediate → AdvancedNot Started

Phase 4 — NLP & Language Modeling

Purpose: Understand how language is converted into numerical representations and modeled statistically.

Phase Progress0%
0 / 39 topics0 / 5 modules

Recommended Prerequisites

Phases are never locked—jump directly here if you already know these foundations:

Phase 4 Learning Objectives

  • Process Unicode/UTF-8 text and understand why modern LLMs operate on subword tokens rather than raw characters or whole words.
  • Implement a complete Byte Pair Encoding (BPE) tokenizer from scratch with `encode()` and `decode()` methods.
  • Explain how dense word/token embeddings capture semantic similarity in continuous vector spaces.
  • Train autoregressive language models using next-token cross-entropy loss, evaluate them with perplexity, and understand why recurrent models bottleneck on long contexts.

Detailed Modules & Topic Checklists (5)

0/7 topics0%
What You'll Learn

You will learn how computers represent human writing systems as Unicode code points and variable-length UTF-8 byte sequences, how Unicode normalization prevents duplicate token representations, and how raw text corpora are cleaned and indexed into vocabularies.

Why It Matters for AI & LLMs

Modern byte-level BPE tokenizers (used in GPT-2/3/4 and LLaMA-3) operate directly over UTF-8 byte streams so they can represent any character, emoji, or code symbol on Earth without ever producing an `<unk>` unknown token.

Module Learning Objectives
  • Inspect Unicode code points (`ord`, `chr`) and variable-length UTF-8 byte encodings (`.encode('utf-8')`).
  • Apply Unicode normalization (NFC / NFKC) and clean noisy text corpora without destroying code or math syntax.
  • Build deterministic token-to-ID (`stoi`) and ID-to-token (`itos`) lookup tables.
Key Concepts
Unicode code points vs UTF-8 bytesNFC / NFKC normalizationCorpus cleaning & segmentationstoi / itos vocabulary mappingUnknown (<unk>) token handling
Topics to Master (0/7)
  • The Unicode standard assigns a unique integer code point (`U+0000` to `U+10FFFF`) to over 150,000 characters across human scripts, mathematical symbols, and emojis.

    Code points (ord() / chr())Multilingual scriptsCombining characters

    Outcome: Inspect Unicode code points of multilingual strings in Python.

  • A variable-width encoding that represents every Unicode code point as 1 to 4 bytes (`0`–`255`), preserving 1-byte ASCII compatibility while enabling byte-level tokenization with a base vocabulary of just 256 byte values.

    raw_bytes = list('Hello 🌍!'.encode('utf-8')) # integers in 0..255
    1-to-4 byte variable widthBase vocabulary of 256 byteslist(text.encode('utf-8'))

    Outcome: Convert strings to raw UTF-8 byte lists and decode byte sequences back to strings.

  • Visually identical characters (like `é` as a single code point vs. `e` + combining acute accent) have different byte sequences unless canonicalized via Unicode normalization (`unicodedata.normalize('NFC', text)`).

    NFC vs NFKC canonicalizationWhitespace standardizationWhen NOT to lowercase (code & proper nouns)

    Outcome: Normalize Unicode strings consistently before tokenization.

  • Splitting documents into sentences or semantic paragraphs while handling abbreviations (`Dr.`, `e.g.`, `3.14`) and code blocks accurately.

    Boundary disambiguationDocument & paragraph chunking

    Outcome: Segment raw documents into clean sentence and paragraph units.

  • Removing broken HTML markup, control characters, and boilerplate navigation text while carefully preserving indentation and punctuation needed for code and prose.

    Stripping markup artifactsPreserving structural whitespaceFiltering corrupted records

    Outcome: Build reproducible text-cleaning pipelines for raw web or book corpora.

  • Collecting unique tokens from a training corpus, sorting or ranking them by frequency, and assigning contiguous integer IDs `0 .. V-1` via bidirectional `stoi` and `itos` maps.

    Frequency thresholdingBijective stoi and itos dictionariesVocabulary size V

    Outcome: Construct deterministic vocabulary lookup tables from a training corpus.

  • Word-level vocabularies map out-of-vocabulary (OOV) words to a shared `<unk>` token, destroying information—a flaw solved by character-level or byte-level subword tokenization.

    Out-of-vocabulary (OOV) problem<unk> information lossWhy byte-level BPE eliminates <unk>

    Outcome: Handle OOV tokens in word-level models and explain how byte-level subwords eliminate them.

Practice Exercises
  • 1.Inspect the UTF-8 byte lengths of English, Devanagari, CJK, mathematical symbols, and emojis, verifying why `len(text)` differs from `len(text.encode('utf-8'))`.
Recommended Module Courses & Resources
3 Matched Resources
Module Completion Milestone: Process multilingual UTF-8 text and construct deterministic vocabulary lookup tables.
0/8 topics0%
0/10 topics0%
0/8 topics0%
0/6 topics0%

Phase 4 Practical Assignments

Complete these focused coding exercises while progressing through the modules above:

  1. 1Build an N-gram text generator with additive smoothing and compute its validation perplexity.
  2. 2Implement a complete Byte Pair Encoding (BPE) tokenizer from scratch with train(), encode(), and decode().
  3. 3Build and train a Character-Level Neural Language Model in PyTorch.
  4. 4Train an RNN or LSTM text generator and compare its validation perplexity against your N-gram and MLP models.

Hands-On Project Milestones

2 Primary Curriculum Milestones
Milestone #7 of 14IntermediateNot Started

Character Language Model

Build and train an autoregressive character-level neural language model in PyTorch using token embeddings, context-window slicing, cross-entropy loss, perplexity tracking, and temperature-controlled multinomial sampling.

Implementation Task Progress0 / 12 steps (0%)
Shifted (x, y) autoregressive batch constructionnn.Embedding lookup tables & hidden projectionsCross-entropy loss & Perplexity evaluationAutoregressive sampling with temperature
Expected Outcome: A neural language model that learns spelling, word structure, and stylistic patterns directly from raw text.
Open Project Guide
Milestone #8 of 14Intermediate → AdvancedNot Started

BPE Tokenizer

Implement a byte-level Byte Pair Encoding (BPE) tokenizer from scratch in Python capable of training merge tables on any UTF-8 corpus, registering special tokens, and performing lossless encode/decode round-trips.

Implementation Task Progress0 / 14 steps (0%)
UTF-8 byte stream manipulationIterative pair-frequency counting & mergingPriority-ordered merge application in encode()Special token (<|bos|>, <|eos|>) handling
Expected Outcome: A reusable, GPT-compatible BPE tokenizer ready to tokenize datasets for your Mini GPT in Phase 5 and Pretrained LLM in Phase 6.
Open Project Guide
Supplementary Phase BuildOptional Practice

N-Gram Statistical Text Generator

Bigram and trigram Markov language model with Laplace smoothing and perplexity benchmarking.

Supplementary Phase BuildOptional Practice

RNN / LSTM Sequential Text Generator

Multi-layer recurrent neural language model demonstrating teacher forcing and hidden-state carry-over.

Phase 4 Completion Criteria & Self-Assessment

Understand the full process of converting text into tokens, learning token probabilities, and generating sequences.

Readiness Check: 0 / 5

Self-assessment readiness checks help you verify conceptual mastery before moving on (tracked separately from topic completion percentage):

  • Can you explain how UTF-8 byte-level BPE eliminates unknown (<unk>) tokens?

    Starting from 256 base byte values and iteratively merging frequent pairs.

  • Have you implemented both Milestone #7 (Character Language Model) and Milestone #8 (BPE Tokenizer)?

    Including lossless decode(encode(text)) == text verification.

  • Can you explain how an input sequence is shifted by one position to create autoregressive (input, target) pairs?

    For example, Input: 'The sky is' -> Target: 'blue' across all prefix positions simultaneously.

  • Have you verified that your untrained language model starts at loss ≈ ln(V) and improves perplexity on a validation split?

    Confirming your loss calculation and logit shapes are bug-free.

  • Can you explain the two main limitations of RNNs/LSTMs that led to the invention of the Transformer?

    Sequential O(T) unrolling preventing GPU parallelization, and the fixed-size hidden state bottleneck.

PHASE 5 · P510 WeeksAdvancedNot Started

Phase 5 — Transformers From Scratch

Purpose: Understand and implement the architecture underlying GPT-style language models.

Phase Progress0%
0 / 47 topics0 / 5 modules

Recommended Prerequisites

Phases are never locked—jump directly here if you already know these foundations:

Phase 5 Learning Objectives

  • Derive and implement Scaled Dot-Product Attention with causal masking and explain every tensor dimension.
  • Build Multi-Head Attention, Rotary Position Embeddings (RoPE), RMSNorm/LayerNorm, and SwiGLU/GELU Feed-Forward blocks.
  • Compare Encoder-only (BERT), Decoder-only (GPT/LLaMA), and Encoder-Decoder (T5) Transformer architectures.
  • Assemble a complete GPT-style decoder-only Transformer from scratch in PyTorch and implement KV-cached autoregressive decoding with Temperature, Top-k, and Top-p sampling.

Detailed Modules & Topic Checklists (5)

0/9 topics0%
What You'll Learn

You will understand how self-attention allows every token in a sequence to directly route information from any preceding token in O(1) sequential path length, and you will implement the exact Scaled Dot-Product Attention equation with causal masking.

Why It Matters for AI & LLMs

Scaled dot-product self-attention is the central routing mechanism of every Transformer language model. Understanding its tensor shapes and $1/\sqrt{d_k}$ variance scaling is essential for LLM engineering.

Core Mathematical & Algorithmic IntuitionScaled Dot-Product Attention & Tensor Dimensions
Attention(Q, K, V) = softmax( (Q Kᵀ) / √d_k + M ) V
Q ∈ ℝ^(B × H × T × d_k)Query tensor: what each token position t is looking for in prior context.
K ∈ ℝ^(B × H × T × d_k)Key tensor: the searchable descriptor advertised by each token position.
Q Kᵀ ∈ ℝ^(B × H × T × T)Pairwise compatibility score matrix between every query position i and key position j.
√d_kScaling factor that keeps dot products at unit variance so softmax does not saturate into one-hot gradients.
M ∈ {0, -∞}^(T × T)Causal mask setting future positions (j > i) to -∞ so softmax assigns exactly 0 weight to future tokens.
V ∈ ℝ^(B × H × T × d_v)Value tensor: the payload vectors aggregated according to the normalized attention probabilities.

Key Takeaway: Multiplying attention weights (B, H, T, T) by Values (B, H, T, d_v) produces an output of shape (B, H, T, d_v) where each token is a context-sensitive weighted average of preceding tokens.

Module Learning Objectives
  • Explain why attention was introduced to eliminate the recurrent bottleneck.
  • Explain the distinct roles and tensor dimensions of Queries ($Q$), Keys ($K$), and Values ($V$).
  • Implement `Attention(Q, K, V) = softmax(QKᵀ / sqrt(d_k))V` with causal upper-triangular `-inf` masking.
Key Concepts
Direct token-to-token routingQuery (Q), Key (K), Value (V) projections1 / sqrt(d_k) variance preservationCausal lower-triangular maskT × T attention weight matrices
Topics to Master (0/9)
  • Originally introduced to let seq2seq translation models look back at all source tokens without compressing a whole sentence into a single vector, before Vaswani et al. (2017) showed that self-attention alone ('Attention Is All You Need') eliminates recurrence entirely.

    Eliminating fixed-vector compressionO(1) path length between any two tokensFull GPU parallelization across T

    Outcome: Contrast O(T) sequential recurrent paths with O(1) direct attention paths.

  • Projected from token representations via $Q = X W_Q$, a Query vector $q_t \in \mathbb{R}^{d_k}$ represents the question or lookup criteria issued by token position $t$.

    Linear projection W_QLookup request representation

    Outcome: Compute Query projections $Q = X W_Q$ and verify their tensor shape.

  • Projected via $K = X W_K$, a Key vector $k_j \in \mathbb{R}^{d_k}$ represents the label or address advertised by token position $j$ to match against incoming Queries.

    Linear projection W_KMatching dimension d_k with Queries

    Outcome: Compute Key projections $K = X W_K$ and align axes for $Q K^T$.

  • Projected via $V = X W_V$, a Value vector $v_j \in \mathbb{R}^{d_v}$ contains the actual semantic content contributed by token $j$ once its Key matches a Query.

    Linear projection W_VInformation payload routed to output

    Outcome: Distinguish between routing address matching ($Q K^T$) and content aggregation ($\text{weights} \cdot V$).

  • The raw matrix product $S = Q K^T$ of shape `(B, H, T, T)` where entry $S_{i,j} = q_i \cdot k_j$ measures raw affinity between query token $i$ and key token $j$.

    Batched transpose K.transpose(-2, -1)O(T²) pairwise score matrix

    Outcome: Compute batched raw attention score matrices in PyTorch.

  • When $q$ and $k$ have zero mean and unit variance, their dot product has variance $d_k$. Dividing by $\sqrt{d_k}$ restores unit variance so softmax inputs do not grow large and push gradients to zero.

    Attention(Q,K,V) = softmax(QKᵀ / sqrt(d_k))V
    Variance of sum of d_k products1 / math.sqrt(d_k) scalingPreventing softmax saturation

    Outcome: Implement scaled dot-product attention and prove why $1/\sqrt{d_k}$ prevents vanishing softmax gradients.

  • Applied row-wise along the last dimension (`dim=-1`) of the scaled score matrix so that for each query token $i$, the attention weights over all attended keys $j$ are non-negative and sum to $1.0$.

    Row-wise normalization (dim=-1)Convex combination of Values

    Outcome: Verify that every row of the post-softmax attention matrix sums to 1.0.

  • In autoregressive language modeling, token $i$ must never peek at future tokens $j > i$. Using `torch.tril` and `masked_fill(mask == 0, float('-inf'))` before softmax forces future weights to $\exp(-\infty) = 0$.

    Lower-triangular mask torch.trilSetting upper triangle to -inf BEFORE softmaxPreventing future token leakage

    Outcome: Implement causal masking with `register_buffer` and verify that changing future tokens never alters past outputs.

  • Visualizing the $T \times T$ attention matrix reveals interpretable routing patterns—such as induction heads, previous-token heads, and delimiter-attending heads.

    T × T heatmapsPrevious-token & induction headsQuadratic O(T²) memory footprint

    Outcome: Plot and interpret $T \times T$ causal attention weight heatmaps.

Practice Exercises
  • 1.Complete Primary Project Milestone #9: Implement a standalone `SelfAttentionEngine` in PyTorch, plot causal attention heatmaps, and write a causality unit test verifying zero future leakage.
Recommended Module Courses & Resources
4 Matched Resources
Module Completion Milestone: Implement Scaled Dot-Product Causal Self-Attention from scratch and verify all tensor shapes (Milestone #9).
0/13 topics0%
0/6 topics0%
0/11 topics0%
0/8 topics0%

Phase 5 Practical Assignments

Complete these focused coding exercises while progressing through the modules above:

  1. 1Implement Scaled Dot-Product Attention and verify causal masking prevents future token leakage.
  2. 2Implement Multi-Head Attention and Rotary Position Embeddings (RoPE).
  3. 3Implement a Pre-LN Transformer Block with RMSNorm/LayerNorm and GELU/SwiGLU FFN.
  4. 4Assemble and train a complete Mini GPT model from random initialization in PyTorch.
  5. 5Add Top-k, Top-p, Temperature, and KV Caching to your Mini GPT text generator.

Hands-On Project Milestones

2 Primary Curriculum Milestones
Milestone #9 of 14AdvancedNot Started

Self-Attention Engine

Implement single-head and multi-head causal scaled dot-product attention from scratch in PyTorch with RoPE positional rotations, attention matrix visualization, and causality unit tests.

Implementation Task Progress0 / 13 steps (0%)
Scaled dot-product attention QKᵀ / √d_kCausal lower-triangular maskingMulti-head tensor splitting & mergingRotary Position Embeddings (RoPE)
Expected Outcome: A standalone, unit-tested attention module with visual attention-head heatmap diagnostics.
Open Project Guide
Milestone #10 of 14AdvancedNot Started

Mini GPT Architecture

Build a complete decoder-only Transformer (Mini GPT) from scratch in PyTorch—including embeddings, stacked Pre-LN Transformer blocks, weight tying, scaled initialization, and KV-cached Top-k/Top-p generation.

Implementation Task Progress0 / 15 steps (0%)
End-to-end decoder-only Transformer assemblyRMSNorm / LayerNorm & SwiGLU / GELU FFN blocksWeight tying & residual depth initializationKV-cached autoregressive sampling (Top-k / Top-p)
Expected Outcome: A complete, trainable GPT model written entirely in clean PyTorch tensor operations.
Open Project Guide
Supplementary Phase BuildOptional Practice

Multi-Head Attention & KV-Cache Benchmark Lab

Empirical latency and memory profiler comparing naive recomputation vs. KV-cached autoregressive generation across sequence lengths 64 to 2048.

Phase 5 Completion Criteria & Self-Assessment

Build a functional decoder-only Transformer that can be trained from random initialization.

Readiness Check: 0 / 5

Self-assessment readiness checks help you verify conceptual mastery before moving on (tracked separately from topic completion percentage):

  • Can you write Attention(Q,K,V) = softmax(QKᵀ / sqrt(d_k))V and state the shape of every tensor?

    Including why dividing by sqrt(d_k) keeps softmax from saturating.

  • Have you built both Milestone #9 (Self-Attention Engine) and Milestone #10 (Mini GPT Architecture)?

    Using your own PyTorch tensor code without importing pretrained Transformer classes.

  • Can you explain how the causal mask, Pre-Norm residual stream, and weight tying work in your code?

    Tracing a batch from token IDs (B, T) to output logits (B, T, V).

  • Have you verified that KV-cached decoding produces the exact same logits as full-sequence recomputation while running significantly faster?

    Testing prefill + token-by-token decode parity.

  • Can you explain why attention memory and compute scale quadratically O(T²) with sequence length T?

    Understanding the hardware implications before scaling pretraining in Phase 6.

PHASE 6 · P610 WeeksAdvancedNot Started

Phase 6 — Train Your Own LLM

Purpose: Train your own GPT-style language model from random weights using your own training pipeline.

Phase Progress0%
0 / 48 topics0 / 5 modules

Recommended Prerequisites

Phases are never locked—jump directly here if you already know these foundations:

Phase 6 Learning Objectives

  • Engineer a clean, deduplicated, packed, and memory-mapped pretraining dataset pipeline with clear provenance and licensing.
  • Implement a production-grade LLM pretraining loop with gradient accumulation, AdamW decoupled weight decay, linear warmup + cosine decay, mixed precision, and fault-tolerant checkpointing.
  • Train small language models at hardware-appropriate educational scales (e.g., 100K–1M, 5M–20M, or 30M–100M parameters) and understand how loss scales with compute and data.
  • Evaluate pretrained models rigorously on validation perplexity, memorization vs. generalization, contamination checks, and package `MyLLM v1` with a reproducible model card and inference CLI.

Detailed Modules & Topic Checklists (5)

0/13 topics0%
What You'll Learn

You will learn how raw text collections are transformed into high-signal binary token shards (`uint16` memory-mapped arrays): verifying open licenses, cleaning extraction artifacts, deduplicating documents, filtering personal information, and packing tokenized sequences with `<|eos|>` separators.

Why It Matters for AI & LLMs

Data quality dictates model quality: a clean, deduplicated 1-billion-token educational corpus consistently outperforms a noisy, repetitive 5-billion-token scrape and trains 5× faster.

Module Learning Objectives
  • Curate and clean a pretraining text dataset with verified licensing and provenance.
  • Apply exact and near-duplicate filtering, language identification, and PII scrubbing.
  • Tokenize and pack documents into contiguous `np.memmap` binary shards (`train.bin`, `val.bin`) for zero-RAM-overhead streaming.
Key Concepts
Data provenance & permissive licensingMinHash / exact deduplicationPII & quality filteringSequence packing with <|eos|>Memory-mapped (np.memmap) binary shards
Topics to Master (0/13)
  • Sourcing domain-appropriate text corpora—such as TinyStories, FineWeb-Edu subsets, open-access textbooks, or permissive code repositories—matched to your target model size and compute budget.

    Signal-to-noise ratioDomain mixture weightingMatching token budget to parameter count

    Outcome: Select and download an appropriate open pretraining corpus for your hardware budget.

  • Inspecting dataset licenses (CC-BY, CC0, MIT, Apache-2.0 vs. non-commercial or restrictive terms) so you know what rights apply to models trained on the corpus.

    Permissive open licensesAttribution requirementsRespecting opt-out & terms

    Outcome: Document the license of every data source in your training manifest.

  • Recording the exact origin URL, snapshot date, hash checksum, and preprocessing script version for every shard entering your training set.

    SHA-256 checksumsData lineage trackingReproducible download scripts

    Outcome: Maintain a verifiable provenance manifest for your pretraining data.

  • Extracting clean prose and code from raw HTML, Markdown, or PDF sources while stripping navigation menus, ads, and broken markup.

    Boilerplate removalPreserving code blocks & math formulas

    Outcome: Extract clean text passages from structured document formats.

  • Applying heuristic quality filters (symbol-to-word ratios, stop-word presence, line-length distributions) to discard gibberish, machine-generated spam, and corrupted encodings.

    Heuristic quality filters (Gopher / FineWeb rules)Encoding repair

    Outcome: Implement document-level quality filters that discard low-quality text.

  • Removing exact duplicate documents/paragraphs (via SHA-256 hashes) and near-duplicates (via MinHash LSH) prevents the model from memorizing repeated boilerplate and reduces train-test leakage.

    Exact hash deduplicationMinHash LSH near-deduplicationPreventing verbatim memorization

    Outcome: Deduplicate a text corpus and measure the percentage of redundant tokens removed.

  • Filtering documents by target language probability using fast classifiers so a small model does not waste capacity across dozens of unintended scripts.

    Fast n-gram language classifiersConfidence thresholds

    Outcome: Filter a corpus to your intended target language(s).

  • Redacting email addresses, phone numbers, IP addresses, and secret API keys using regex patterns before tokenization.

    Regex redaction of emails/phones/keysPrivacy-preserving replacement tokens

    Outcome: Implement a PII and credential scrubbing pass in your data pipeline.

  • Splitting at the document level (never slicing inside a single document!) after deduplication so validation perplexity measures true generalization to unseen documents.

    Document-level splittingZero cross-split document overlap

    Outcome: Create leak-free document-level train, validation, and test shards.

  • Encoding millions of documents in parallel across CPU worker processes into compact `uint16` (for $V < 65536$) or `uint32` integer arrays.

    Multiprocessing tokenizationuint16 binary storage (2 bytes/token)

    Outcome: Tokenize a multi-megabyte or gigabyte corpus into binary integer files.

  • Concatenating tokenized documents separated by `<|eos|>` into a single continuous stream and slicing fixed-length `block_size` windows eliminates wasted `<|pad|>` compute during pretraining.

    Concatenate-and-chunk packing<|eos|> document boundary token100% non-padded token utilization

    Outcome: Pack variable-length documents into dense, pad-free training sequences.

  • Using `np.memmap('train.bin', dtype=np.uint16, mode='r')` maps binary token files directly from disk into virtual address space, letting you train on datasets larger than system RAM.

    data = np.memmap('train.bin', dtype=np.uint16, mode='r') ix = torch.randint(len(data) - block_size, (batch_size,))
    OS virtual memory paging (np.memmap)Instant startup & constant RAM usage

    Outcome: Stream random batches from a disk-backed `np.memmap` binary shard.

  • Recording the tokenizer hash, shard checksums, total token counts, and filtering statistics in a `dataset_card.json` alongside the binary shards.

    Shard metadata manifestTokenizer-dataset compatibility checks

    Outcome: Version your tokenized shards with metadata verification.

Practice Exercises
  • 1.Build a complete data preparation script that cleans, deduplicates, splits, tokenizes, and writes `train.bin`, `val.bin`, and `meta.json` using `np.memmap`.
Recommended Module Courses & Resources
3 Matched Resources
Module Completion Milestone: Produce clean, deduplicated, memory-mapped `train.bin` and `val.bin` pretraining shards.
0/13 topics0%
0/3 topics0%
0/12 topics0%
0/7 topics0%

Phase 6 Practical Assignments

Complete these focused coding exercises while progressing through the modules above:

  1. 1Curate, clean, deduplicate, and tokenize an open text corpus into memory-mapped train.bin and val.bin shards.
  2. 2Implement the complete pretraining pipeline with gradient accumulation, AdamW decoupled weight decay, warmup-cosine LR, and checkpointing.
  3. 3Train Model A (100K–1M params) and, if hardware permits, Model B (5M–20M params) from random initialization.
  4. 4Generate a full evaluation report comparing validation perplexity against baselines and checking n-gram memorization.
  5. 5Package MyLLM v1 with its custom tokenizer, config.json, checkpoints, Model Card, and CLI inference script.

Hands-On Project Milestones

1 Primary Curriculum Milestone
Milestone #11 of 14Advanced · CapstoneNot Started

Pretrained Mini LLM

MyLLM v1 — Train your own decoder-only GPT language model from randomly initialized weights using your custom BPE tokenizer, memory-mapped dataset pipeline, AdamW + cosine schedule pretraining loop, and evaluation suite.

Implementation Task Progress0 / 19 steps (0%)
Dataset cleaning, deduplication & binary packingMixed-precision pretraining with gradient accumulationWarmup-cosine LR scheduling & checkpoint recoveryPerplexity evaluation, ablation & Model Card packaging

Required Project Deliverables:

  • Custom tokenizer
  • GPT-style architecture
  • Training pipeline
  • Model checkpoints
  • Evaluation report
  • Inference script
  • Reproducible documentation
Expected Outcome: A self-trained, reproducibly packaged language model (MyLLM v1) with full training telemetry and CLI inference.
Open Project Guide

Phase 6 Completion Criteria & Self-Assessment

Successfully train and evaluate a small model from randomly initialized weights and explain the complete training pipeline.

Readiness Check: 0 / 5

Self-assessment readiness checks help you verify conceptual mastery before moving on (tracked separately from topic completion percentage):

  • Can you explain every stage of the pretraining pipeline from raw text deduplication to AdamW parameter updates?

    Including why 1D norms/biases are excluded from weight decay and why warmup is needed.

  • Have you prepared leak-free, memory-mapped train.bin and val.bin shards using your custom tokenizer?

    Splitting at the document level after deduplication.

  • Have you trained MyLLM v1 (Milestone #11) from random weights at a scale suited to your hardware?

    Verifying initial loss ≈ ln(V) and smooth validation perplexity improvement.

  • Have you produced all 7 MyLLM v1 deliverables, including the evaluation report and standalone inference script?

    Testing that your packaged checkpoint reloads and generates text deterministically.

  • Can you explain why a base pretrained model simply continues documents rather than acting as a helpful question-answering assistant?

    Motivating Post-Training, Instruction Tuning (SFT), and Alignment in Phase 7.

PHASE 7 · P78 WeeksAdvancedNot Started

Phase 7 — Post-training & Alignment

Purpose: Understand how pretrained language models become useful instruction-following assistants.

Phase Progress0%
0 / 35 topics0 / 5 modules

Recommended Prerequisites

Phases are never locked—jump directly here if you already know these foundations:

Phase 7 Learning Objectives

  • Distinguish clearly between base pretraining, Supervised Fine-Tuning (SFT), preference optimization (DPO/RLHF), and inference-time prompting.
  • Format multi-turn chat datasets with special control tokens and assistant-only loss masking.
  • Implement Low-Rank Adaptation (LoRA) from scratch and fine-tune open-weight or custom models using LoRA/QLoRA.
  • Explain Direct Preference Optimization (DPO), RLHF with PPO, and Group Relative Policy Optimization (GRPO) for verifiable reasoning.

Detailed Modules & Topic Checklists (5)

0/7 topics0%
What You'll Learn

You will learn why a base pretrained model responds to a question by generating more questions (document continuation), and how Supervised Fine-Tuning (SFT) on curated `(instruction, response)` pairs formatted with chat templates teaches the model to act as a conversational assistant.

Why It Matters for AI & LLMs

Pretraining gives a model broad knowledge and linguistic fluency; SFT teaches it the interaction format of answering user requests directly and stopping at `<|im_end|>`.

Module Learning Objectives
  • Contrast base document completion with instruction-following behavior.
  • Format multi-turn dialogues using structured chat templates (`<|im_start|>user ... <|im_end|>`).
  • Implement assistant-only loss masking (`labels = -100` on user prompt tokens) during SFT.
Key Concepts
Knowledge acquisition (pretraining) vs format alignment (SFT)ChatML & special turn delimitersAssistant-only loss masking (ignore_index=-100)Teacher forcing on target responsesQuality over quantity (LIMA principle)
Topics to Master (0/7)
  • Pretraining optimizes next-token prediction over billions/trillions of raw web tokens using massive compute to acquire world knowledge; fine-tuning adapts those weights on thousands of curated examples at a smaller learning rate.

    Compute scale asymmetryDistribution shift from raw web to assistant turnsLower learning rate in SFT

    Outcome: Articulate what capabilities come from pretraining versus post-training.

  • Collections of `(system, user_instruction, assistant_response)` records covering question answering, coding, summarization, and multi-turn dialogue.

    Single-turn vs multi-turn conversationsTask diversityVerifying license & provenance

    Outcome: Inspect and curate JSONL instruction-tuning datasets.

  • Deterministic serialization formats (such as ChatML `<|im_start|>role\ncontent<|im_end|>`) that convert structured message arrays into a single token stream with unambiguous turn boundaries.

    Role delimiters (system, user, assistant)EOS / end-of-turn stopping tokenAvoiding prompt injection across roles

    Outcome: Apply and customize chat templates that map message lists to token IDs.

  • Constructing input `input_ids` and target `labels` where user prompt tokens are masked with `-100` (`ignore_index`) so cross-entropy loss is computed strictly on the assistant's response tokens.

    # Mask prompt tokens so loss only trains on assistant response labels = [-100] * len(prompt_ids) + response_ids + [eos_id]
    Prompt masking with -100Computing loss only on assistant completionsPreventing the model from memorizing user prompts

    Outcome: Build an SFT collator that masks user prompt tokens with `-100`.

  • Standard autoregressive cross-entropy training over formatted instruction-response trajectories for 1–3 epochs with a small learning rate (e.g., `2e-5`).

    1–3 epoch scheduleLow learning rate to preserve pretrained weightsPacking vs padding SFT examples

    Outcome: Run a complete Supervised Fine-Tuning loop and compare completions before vs. after SFT.

  • During SFT, the model is conditioned on the ground-truth prefix at every token position of the assistant's target answer, enabling parallel loss calculation in a single forward pass.

    Parallel target token conditioningExposure bias at inference time

    Outcome: Explain how teacher forcing enables fast parallel SFT training.

  • A few thousand carefully written, accurate, and well-formatted demonstrations consistently outperform 100,000 noisy or contradictory examples during SFT.

    LIMA (Less Is More for Alignment)Formatting consistencyFiltering incorrect or verbose completions

    Outcome: Audit and filter an instruction dataset for accuracy, formatting consistency, and diversity.

Practice Exercises
  • 1.Write an SFT data collator that formats multi-turn conversations into ChatML tokens, masks `system` and `user` turns with `-100`, and verifies via a unit test that loss is zero if assistant tokens are predicted perfectly.
Recommended Module Courses & Resources
4 Matched Resources
Module Completion Milestone: Implement an SFT pipeline with chat templates and prompt-masked cross-entropy loss.
0/6 topics0%
0/7 topics0%
0/9 topics0%
0/6 topics0%

Phase 7 Practical Assignments

Complete these focused coding exercises while progressing through the modules above:

  1. 1Format an instruction dataset with ChatML templates and assistant-only loss masking (-100 on prompt tokens).
  2. 2Implement LoRA from scratch in PyTorch and fine-tune an open-weight model (or your Phase 6 model) into an instruction-following assistant.
  3. 3Evaluate the model before and after Supervised Fine-Tuning (SFT) on a structured prompt benchmark.
  4. 4Implement Direct Preference Optimization (DPO) loss and run preference alignment on a small pairwise dataset.

Hands-On Project Milestones

1 Primary Curriculum Milestone
Milestone #12 of 14AdvancedNot Started

Instruction-Tuned Assistant

Transform a base pretrained language model into a multi-turn instruction-following assistant using custom ChatML formatting, assistant-masked Supervised Fine-Tuning (SFT), Low-Rank Adaptation (LoRA), and Direct Preference Optimization (DPO).

Implementation Task Progress0 / 12 steps (0%)
ChatML template serialization & prompt loss maskingCustom LoRA adapter implementation & mergingSupervised Fine-Tuning (SFT) & DPO alignmentBefore-and-after SFT/DPO qualitative & rubric evaluation
Expected Outcome: An instruction-tuned, preference-aligned assistant model with quantitative before/after evaluation comparisons.
Open Project Guide
Supplementary Phase BuildOptional Practice

LoRA Rank & Target-Module Ablation Study

Empirical comparison of LoRA ranks (r=4, 16, 64) and attention-only vs. all-linear target modules on memory usage and validation loss.

Supplementary Phase BuildOptional Practice

Verifiable Reasoning Mini-Lab (GRPO)

Small-scale reinforcement learning experiment using programmatic verifiable rewards on structured math word problems.

Phase 7 Completion Criteria & Self-Assessment

Understand the distinction between pretraining, instruction tuning, preference optimization, and inference-time prompting.

Readiness Check: 0 / 5

Self-assessment readiness checks help you verify conceptual mastery before moving on (tracked separately from topic completion percentage):

  • Can you clearly distinguish pretraining, SFT, preference optimization (DPO/RLHF), and inference-time prompting?

    Explaining the objective function, data format, and compute scale of each stage.

  • Have you completed Milestone #12 (Instruction-Tuned Assistant) and evaluated the model before and after SFT?

    Demonstrating clear improvements in instruction following and turn stopping.

  • Can you implement a LoRA linear layer (W_0 x + (α/r) BAx) and the DPO loss function in PyTorch?

    Including why B is initialized to zero and why prompt tokens are masked with -100 in SFT.

  • Have you tested your fine-tuned model for reward hacking (verbosity/sycophancy) and catastrophic forgetting?

    Comparing output lengths and base knowledge retention.

  • Can you explain why SFT and RLHF cannot reliably inject massive amounts of brand-new factual knowledge that was absent in pretraining?

    Understanding the capabilities boundary of post-training.

PHASE 8 · P816 WeeksAdvanced → ResearchNot Started

Phase 8 — Advanced LLM Systems & Research

Purpose: Understand large-scale training systems, model optimization, inference infrastructure, and experimental research.

Phase Progress0%
0 / 55 topics0 / 5 modules

Recommended Prerequisites

Phases are never locked—jump directly here if you already know these foundations:

Phase 8 Learning Objectives

  • Understand GPU memory hierarchies (HBM vs. SRAM), arithmetic intensity, kernel fusion, FlashAttention, and Triton kernels.
  • Understand distributed training strategies across multiple GPUs/nodes: DDP, FSDP / ZeRO, Tensor Parallelism, and Pipeline Parallelism.
  • Analyze frontier architectures including Grouped-Query Attention (GQA), Mixture of Experts (MoE), long-context RoPE scaling, Multimodal VLM/Audio models, and Diffusion.
  • Build a high-throughput LLM Inference Server (Milestone #13) and execute a rigorous Research Reproduction study (Milestone #14).

Detailed Modules & Topic Checklists (5)

0/12 topics0%
What You'll Learn

You will understand how modern GPUs execute tensor operations: why memory bandwidth between HBM (VRAM) and on-chip SRAM—not raw FLOPs—is the bottleneck of naive attention and normalization layers, and how kernel fusion, `torch.compile`, Triton, and FlashAttention eliminate redundant HBM round-trips.

Why It Matters for AI & LLMs

A naive PyTorch Transformer utilizes less than 20% of a GPU's peak FLOPs because it repeatedly reads and writes large intermediate tensors to slow HBM memory. Systems-aware engineers achieve 3×–5× speedups on the exact same hardware.

Module Learning Objectives
  • Explain the GPU memory hierarchy (Registers, Shared Memory / SRAM, L2 Cache, HBM) and the Roofline Model (compute-bound vs. memory-bandwidth-bound).
  • Explain how FlashAttention tiles $Q, K, V$ blocks in SRAM using online softmax to compute exact attention in $O(T)$ HBM memory instead of $O(T^2)$.
  • Use `torch.profiler`, `torch.compile`, activation checkpointing, and Triton to optimize Transformer workloads.
Key Concepts
SMs, Tensor Cores & HBM vs SRAM bandwidthRoofline model & arithmetic intensity (FLOPs / Byte)Kernel fusion & torch.compileFlashAttention online softmax tilingActivation (gradient) checkpointing
Topics to Master (0/12)
  • GPUs consist of dozens of Streaming Multiprocessors (SMs) containing specialized Tensor Cores for matrix multiply-accumulate ($D = A B + C$) alongside high-bandwidth off-chip HBM memory.

    Streaming Multiprocessors (SMs)Tensor Cores vs CUDA coresSIMT warp execution (32 threads)

    Outcome: Relate matrix dimensions (multiples of 64/128) to Tensor Core hardware utilization.

  • The parallel programming model organizing threads into warps, thread blocks (scheduled onto a single SM), and grids, indexing tensors via `blockIdx.x * blockDim.x + threadIdx.x`.

    Grid -> Block -> Thread hierarchyAsynchronous kernel launchesMemory coalescing

    Outcome: Explain how a parallel GPU kernel maps thread blocks across tensor dimensions.

  • Off-chip HBM is large (16–80+ GB) but relatively slow (~1–3 TB/s), whereas on-chip SRAM / Shared Memory is tiny (~20–50 MB across SMs) but ~10× faster (~19+ TB/s).

    HBM capacity vs SRAM bandwidthArithmetic intensity (FLOPs per byte transferred)Memory-bound elementwise ops vs compute-bound matmuls

    Outcome: Classify Transformer operations as compute-bound or memory-bandwidth-bound using the Roofline model.

  • Every un-fused PyTorch operation (`x * 0.5`, `torch.tanh`, `+`) launches a separate GPU kernel that reads inputs from HBM, computes in registers, and writes outputs back to HBM.

    Kernel launch overheadHBM read/write round-trips

    Outcome: Identify redundant HBM memory round-trips in eager PyTorch code.

  • Combining sequences of element-wise and reduction operations (like `RMSNorm` or `GeLU`) into a single GPU kernel so intermediate values stay in ultra-fast registers/SRAM (`torch.compile`).

    Operator fusionSingle HBM read + single HBM writetorch.compile Inductor backend

    Outcome: Apply `torch.compile` and benchmark the speedup on RMSNorm and SwiGLU layers.

  • Performing matrix multiplications in 16-bit precision on Tensor Cores while accumulating products and maintaining master weights in FP32.

    Tensor Core throughput multiplierFP32 master weight accumulation

    Outcome: Calculate the memory and throughput gains of mixed-precision training.

  • IEEE 16-bit float (1 sign, 5 exponent, 10 mantissa bits): high precision but narrow dynamic range (max value `65,504`), requiring dynamic loss scaling (`GradScaler`) to prevent small gradients from underflowing to zero.

    5 exponent bits (narrow range)Dynamic loss scaling (GradScaler)Overflow above 65,504

    Outcome: Configure FP16 mixed precision with `GradScaler` and detect overflow step skips.

  • Brain Float 16 (1 sign, 8 exponent, 7 mantissa bits): matches FP32's exact 8-bit exponent dynamic range, eliminating `GradScaler` and overflow headaches during LLM pretraining.

    8 exponent bits (same range as FP32)Drop-in stability for LLM pretraining

    Outcome: Explain why BF16 is preferred over FP16 for Large Language Model training.

  • Activation checkpointing discards intermediate sublayer activations during the forward pass and recomputes them on the fly during the backward pass—trading ~25–33% extra compute to reduce activation VRAM by 4×–8×.

    Compute-for-memory tradeofftorch.utils.checkpointEnabling longer context lengths & larger batches

    Outcome: Enable activation checkpointing in your Transformer and measure peak VRAM reduction.

  • Tiles $Q, K, V$ into SRAM blocks and uses the online softmax rescaling trick to compute exact attention without ever materializing the $O(T^2)$ attention matrix in HBM (`F.scaled_dot_product_attention`).

    SRAM block tilingOnline softmax running max & sumO(T) memory instead of O(T²)Exact (non-approximate) output

    Outcome: Explain the online softmax tiling algorithm behind FlashAttention and use `F.scaled_dot_product_attention`.

  • A Python-based GPU kernel language that operates on tile blocks (`tl.load`, `tl.store`, `tl.dot`) rather than individual scalar threads, making custom fused kernels (fused softmax, RMSNorm, cross-entropy) accessible without raw C++ CUDA.

    Block-level programming modeltl.program_id & pointer arithmeticWriting fused softmax / RMSNorm

    Outcome: Read and write a basic block-tiled vector addition or fused row-wise softmax kernel in Triton.

  • Using `torch.profiler` and Chrome trace timelines (`trace.json`) to inspect GPU kernel occupancy, CPU launch gaps, and memory allocation lifecycles.

    torch.profiler.profileIdentifying CPU-bound gaps between GPU kernelsModel FLOPs Utilization (MFU)

    Outcome: Profile a Transformer training step and compute its Model FLOPs Utilization (MFU).

Practice Exercises
  • 1.Implement the online single-pass softmax algorithm in Python/NumPy and verify it produces identical probabilities to standard two-pass softmax while updating running max and sum in a single loop.
  • 2.Benchmark your Phase 5 `MiniGPT` attention module against `F.scaled_dot_product_attention` (FlashAttention) across sequence lengths 256, 1024, and 2048.
Recommended Module Courses & Resources
5 Matched Resources
Module Completion Milestone: Explain GPU memory hierarchies and FlashAttention online softmax tiling, and profile Transformer MFU.
0/10 topics0%
0/12 topics0%
0/11 topics0%
0/10 topics0%

Phase 8 Practical Assignments

Complete these focused coding exercises while progressing through the modules above:

  1. 1Optimize a small attention module using FlashAttention / torch.compile and profile its HBM bandwidth and MFU.
  2. 2Implement INT8 and group-wise INT4 weight quantization from scratch and measure perplexity vs. memory savings.
  3. 3Build and benchmark a streaming LLM Inference Server reporting TTFT, TPOT, and throughput.
  4. 4Execute and document a controlled multi-seed Research Reproduction study on a Transformer architecture or optimization paper.

Hands-On Project Milestones

2 Primary Curriculum Milestones
Milestone #13 of 14AdvancedNot Started

LLM Inference Server

Build a high-throughput, quantized LLM inference engine and streaming HTTP server supporting INT8/INT4 weight quantization, KV-cache management, speculative decoding, and real-time latency/throughput telemetry.

Implementation Task Progress0 / 15 steps (0%)
INT8 / INT4 weight quantizationKV-cache prefix reuse & memory managementSpeculative decoding & streaming HTTP/SSE APITTFT, TPOT & concurrency load benchmarking
Expected Outcome: A production-style inference serving engine with full latency-throughput benchmark reports.
Open Project Guide
Milestone #14 of 14Advanced → ResearchNot Started

Research Reproduction

Select a foundational LLM architecture or optimization paper (e.g., RoPE vs. ALiBi, GQA vs. MHA, SwiGLU vs. GELU, or Muon/AdamW), reproduce its core experiment at a manageable scale across multiple seeds, and publish a rigorous technical report.

Implementation Task Progress0 / 15 steps (0%)
Paper deconstruction & hypothesis formulationFLOP-matched & parameter-matched experimental designMulti-seed statistical evaluation & ablation tablesReproducible research code & technical writing
Expected Outcome: A complete, reproducible research repository and technical paper validating an empirical LLM hypothesis.
Open Project Guide
Supplementary Phase BuildOptional Practice

Online Softmax & Attention Kernel Benchmark

Implementation and profiling of tiled online softmax vs. naive materialized softmax across increasing context lengths.

Phase 8 Completion Criteria & Self-Assessment

Design, implement, measure, and explain an advanced language-model system or research experiment.

Readiness Check: 0 / 5

Self-assessment readiness checks help you verify conceptual mastery before moving on (tracked separately from topic completion percentage):

  • Can you explain the GPU memory hierarchy (HBM vs. SRAM), why decoding is memory-bandwidth-bound, and how FlashAttention and GQA work?

    Connecting hardware physics directly to Transformer architecture design.

  • Can you explain how FSDP (ZeRO-1/2/3), Tensor Parallelism, and Pipeline Parallelism partition training across multiple GPUs?

    Including the collective operations (AllGather, ReduceScatter, AllReduce) used by each.

  • Have you built and benchmarked Milestone #13 (LLM Inference Server) with weight quantization and KV caching?

    Measuring Time-To-First-Token (TTFT) and Time-Per-Output-Token (TPOT).

  • Have you completed Milestone #14 (Research Reproduction) with a controlled baseline and multi-seed evaluation?

    Holding token budget, data order, and parameter count constant.

  • Can you critically read a new LLM research paper, identify its core mathematical change, and design an ablation to test its claims?

    Completing the journey from AI beginner to independent AI & LLM engineer.

14 Canonical Hands-on Projects

Complete Curriculum Project Milestones (1–14)

Every core project across Phases 1 through 8 builds directly toward implementing, training, aligning, and serving your own language model from scratch.

Completed: 0 / 14 milestones
#01Phase 0

Matrix Operations Engine

Build a complete pure-Python linear algebra engine implementing vector addition, scalar multiplication, dot products, 2D matrix multiplication, transposes, and automated verification against NumPy.

Beginner
#02Phase 1

Linear Regression From Scratch

Train a regression model without using a predefined machine-learning estimator—deriving analytical MSE gradients manually, implementing gradient descent, plotting loss convergence, and evaluating on held-out data.

Beginner → Intermediate
#03Phase 2

Spam Classifier

Build an end-to-end email/SMS spam classification system implementing text preprocessing, Bag-of-Words/TF-IDF feature extraction, and a Naive Bayes or Logistic Regression classifier from scratch.

Intermediate
#04Phase 3

Automatic Differentiation Engine

Build a dynamic reverse-mode autodiff engine in pure Python that constructs computational DAGs, performs topological sorting, and backpropagates exact gradients through multi-layer perceptrons.

Intermediate
#05Phase 3

Neural Network From Scratch

Implement a vectorized multi-layer neural network in pure NumPy with forward activation caching, explicit backward pass Jacobians, He initialization, Dropout, LayerNorm, and Adam optimization.

Intermediate → Advanced
#06Phase 3

Image Classifier

Build, train, and evaluate an MNIST handwritten digit and image classification pipeline in PyTorch comparing MLP and CNN architectures with checkpointing and confusion matrix diagnostics.

Intermediate
#07Phase 4

Character Language Model

Build and train an autoregressive character-level neural language model in PyTorch using token embeddings, context-window slicing, cross-entropy loss, perplexity tracking, and temperature-controlled multinomial sampling.

Intermediate
#08Phase 4

BPE Tokenizer

Implement a byte-level Byte Pair Encoding (BPE) tokenizer from scratch in Python capable of training merge tables on any UTF-8 corpus, registering special tokens, and performing lossless encode/decode round-trips.

Intermediate → Advanced
#09Phase 5

Self-Attention Engine

Implement single-head and multi-head causal scaled dot-product attention from scratch in PyTorch with RoPE positional rotations, attention matrix visualization, and causality unit tests.

Advanced
#10Phase 5

Mini GPT Architecture

Build a complete decoder-only Transformer (Mini GPT) from scratch in PyTorch—including embeddings, stacked Pre-LN Transformer blocks, weight tying, scaled initialization, and KV-cached Top-k/Top-p generation.

Advanced
#11Phase 6

Pretrained Mini LLM

MyLLM v1 — Train your own decoder-only GPT language model from randomly initialized weights using your custom BPE tokenizer, memory-mapped dataset pipeline, AdamW + cosine schedule pretraining loop, and evaluation suite.

Advanced · Capstone
#12Phase 7

Instruction-Tuned Assistant

Transform a base pretrained language model into a multi-turn instruction-following assistant using custom ChatML formatting, assistant-masked Supervised Fine-Tuning (SFT), Low-Rank Adaptation (LoRA), and Direct Preference Optimization (DPO).

Advanced
#13Phase 8

LLM Inference Server

Build a high-throughput, quantized LLM inference engine and streaming HTTP server supporting INT8/INT4 weight quantization, KV-cache management, speculative decoding, and real-time latency/throughput telemetry.

Advanced
#14Phase 8

Research Reproduction

Select a foundational LLM architecture or optimization paper (e.g., RoPE vs. ALiBi, GQA vs. MHA, SwiGLU vs. GELU, or Muon/AdamW), reproduce its core experiment at a manageable scale across multiple seeds, and publish a rigorous technical report.

Advanced → Research