GiTech · Learn AI Progress 0/0
Public-good project · Free starter handbook

Learn AI from Stanford's open courses: from zero to training models and building agents by hand

For graduate students and PhDs with a solid engineering background but no AI training. We lay out one route built on Stanford's public courses: what to brush up on, which course to take, which lectures you can skip, and what you should build yourself at every stage. Every video is free on YouTube.

Compiled by GiTech Design · links last checked 2026-10-29 · no ads, no sign-up

5
stages, from refreshers to agents
25
hand-picked open courses
≈6
months at 8–10 h a week
0
cost: everything is free

Use the YouTube / Bilibili switch at the top right. Bilibili is China's main video site, where these courses are reposted with Chinese subtitles; outside China, stay on YouTube.

This handbook

When you finish, you can do two things on your own

The goal isn't to “know about AI” but to build with it. The whole route is worked backwards from these two end points.

01

Train models by hand

From gradient descent written in plain numpy, to a convolutional network trained in PyTorch, to a tokenizer and Transformer written from scratch and a small language model trained on top. You know what every line computes, and where to look when training goes wrong.

02

Build a harness and an agent by hand

Without a framework, write an agent that is just “model + tools + loop”, then wrap it in permissions, context management, logging and evaluation. That outer layer is the harness. Coding assistants such as Claude Code are, at heart, very good harnesses.

This is for you if

  • you hold (or are working on) an engineering master's or PhD: you know linear algebra, probability and calculus, and have written some code
  • you want AI inside your own research or engineering: sensor data, images, simulation, documents…
  • you can set aside 8–10 hours a week and will do the assignments, not just watch

What this handbook is not

  • a “learn AI in three days” crash course, or a tutorial for some AI product
  • a job-hunting guide: interview prep and coding drills are out of scope
  • a substitute for the courses: we only plan the route and point to the material; the learning happens in the assignments

Where to start

One-minute self-check: find your starting stage

Seven honest answers. Every “no” marks a gap. When you've answered all seven, you'll see which stage to start from and what to patch first.

I can write Python functions and classes and do vectorised matrix maths in numpy without constantly looking up syntax.
I'm comfortable on the command line and can commit, revert and branch with git.
I can explain the geometric meaning of matrix multiplication, eigenvalues and the SVD.
I'm at home with conditional probability, Bayes' rule, expectation and variance, and maximum-likelihood estimation.
I can take the gradient of a multivariate function and use the chain rule on nested functions.
I know what overfitting is and can explain what the training, validation and test sets are each for.
I have implemented backpropagation for a neural network by hand, without a framework.

The route

Five stages, about six months

Estimated at 8–10 hours a week. Stages 1, 2 and 3 build on each other, so take them in order; the API-based agent work in stage 4 can start early and run in parallel.

  1. 0FoundationsPython, command line, linear algebra, probability: patch what's missing0–3 weeks (depends on gaps)
  2. 1Machine learningCS229: supervised learning, generalisation, error analysis4–6 weeks
  3. 2Deep learning & CNNsCS231n: backpropagation, convolutional networks, training tricks6–8 weeks
  4. 3Transformers & LLMsKarpathy + CS336: train a language model from scratch8–10 weeks
  5. 4Agents & harnessesLLM Agents + CS329Z: tools, loops, evaluation4–6 weeks

When you have the time, or your research calls for it, see the electives: physics-informed ML, reinforcement learning, graph neural networks, generative models, few-shot and transfer learning…

Stage 0 · optional

Foundations: patch only what's missing

Most engineering PhDs only need Python/numpy and tooling. Use the self-check above to find your gaps rather than watching foundation courses end to end.

0–3 weeks (depends on gaps)Python / NumPyshell · gitlinear algebraprobability

The five courses here are for filling holes: take only the lectures that match your gaps. Keep the maths intuitive for now; the rigorous derivations are easier to pick up when stage 1 actually needs them.

CS50POptionalNot Stanford · Harvard≈15 h of video

CS50's Introduction to Programming with Python

Harvard · David J. Malan · 2022

Harvard's introduction to Python: clear lectures and well-designed problem sets, one of the most often recommended courses for learning Python from zero. Skip it if you already write Python.

How to watch: the first six lectures (functions, conditionals, loops, exceptions, libraries, file I/O) are enough; object-oriented programming as needed.

Then: work through CS231n's Python/NumPy tutorial, the coding style every later assignment assumes.

Bilibili repost: “哈佛大学《CS50P 2022:Python编程入门|CS50's Introduction to Programming with Python》中英” · GPT中英字幕课程资源 · 11 parts · Chinese–English subtitles (machine-translated)

MITOptionalNot Stanford · MIT≈11 h of video

The Missing Semester of Your CS Education

MIT · Anish Athalye, Jon Gjengset, Jose Javier Gonzalez Ortiz · IAP 2020 · 2026

MIT's course on the tools nobody teaches but everyone uses daily: the shell, git, editors, debugging. A dozen hours here saves time every day for months.

Must watch: shell and scripting, version control (git), debugging and profiling.

Skippable: Vim, metaprogramming, security and cryptography; return when you need them.

Bilibili repost: “[自制双语字幕] 计算机教育缺失的一课(2020)” · 刘黑黑a · 11 parts · Chinese–English subtitles

YouTube: Missing Semester IAP 2020 · Missing Semester · 11 videos

3B1BOptionalNot Stanford · 3Blue1Brown≈3 h of video

Essence of Linear Algebra

3Blue1Brown · Grant Sanderson

Animated geometric intuition for linear algebra: a matrix is a transformation, a determinant is how area scales, an eigenvector is a direction that doesn't turn. Engineers often can compute but not “see”; this series fixes that.

How to watch: a dozen or so episodes of 10–15 minutes each; one weekend.

Focus on: linear transformations, matrix multiplication as composition, determinants, eigenvectors and eigenvalues, change of basis.

Bilibili repost: “【官方双语/合集】线性代数的本质 - 系列合集” · 3Blue1Brown · 16 parts · Chinese–English subtitles

YouTube: Essence of linear algebra · 3Blue1Brown · 16 videos

18.06OptionalNot Stanford · MIT≈26 h of video

Linear Algebra

MIT · Gilbert Strang · OCW

Gilbert Strang's classic linear-algebra course. Don't watch it end to end; use it as the reference you open when a derivation stalls.

As needed: projections and least squares, orthogonalisation, eigendecomposition, the singular value decomposition, positive-definite matrices.

Tip: these are exactly the tools behind linear regression and PCA in CS229.

Bilibili repost: “麻省理工公开课 线性代数 MIT 18.06 Linear Algebra 中英双语字幕” · 仲春Mon · 35 parts · Chinese–English subtitles

YouTube: MIT 18.06 Linear Algebra, Spring 2005 · MIT OpenCourseWare · 36 videos

CS109Optional≈30 h of video

Probability for Computer Scientists

Stanford · Chris Piech · Spring 2022

Stanford's probability course for computer scientists. Many examples come from machine learning, so it is closer to what you'll need than a typical maths-department course.

As needed: conditional probability and Bayes, random variables and common distributions, expectation and variance, maximum likelihood (MLE) and MAP.

Skippable: the early counting and combinatorics lectures, which most engineers already know.

Bilibili repost: “斯坦福大学《计算机科学的概率论|CS109 Introduction to Probability for Computer Scientists 22》” · GPT中英字幕课程资源 · 29 parts · Chinese–English subtitles (machine-translated)

YouTube: Stanford CS109 Probability for Computer Scientists (2022) · Stanford Online · 29 videos

Stage 0 · Hands-on milestone

Set up your environment and make your first git commit

No models yet, just preparation: every assignment and note from the next six months will live in the repository you create now.

You've cleared this stage when you can:

Stage 1

Machine learning: the model–loss–optimisation–generalisation framework

Turn an engineering problem into a supervised-learning problem, pick the right loss and evaluation, and diagnose why a model overfits.

4–6 weekslinear / logistic regressionregularisationcross-validationerror analysis

CS229 is the backbone of this stage. For engineers the derivations are not the hard part; the hard part is the way of thinking: how to split data, what generalisation means, and how to tell whether you need more data or a different model. If you want intuition first, start with Andrew Ng's 2022 Machine Learning Specialization and come back to CS229 for the derivations.

CS229Core≈26 h of video

Machine Learning

Stanford · Andrew Ng · Autumn 2018

Andrew Ng's Stanford machine-learning course: complete derivations and outstanding lecture notes. It teaches the framework that every later stage builds on.

Must watch: linear regression and gradient descent, logistic regression, generalised linear models, bias–variance and regularisation, model selection and cross-validation, intro to neural networks, and debugging ML models / error analysis (the most useful lecture for engineering work).

Skim: Gaussian discriminant analysis and naive Bayes, SVMs and kernels, learning theory. Skip for now: EM, factor analysis, ICA and reinforcement learning at the end; come back when you need them.

Alongside: read the CS229 main notes as you go; if the maths is rusty, start with the linear-algebra and probability review notes.

Bilibili repost: “【斯坦福大学】CS229 机器学习 · 2018年(完结·中英字幕·机翻)” · 鬼谷良师 · 28 parts · Chinese–English subtitles (machine-translated)

YouTube: Stanford CS229: Machine Learning led by Andrew Ng | Autumn 2018 · Stanford Online · 21 videos

MLSAlternative≈30 h of video

Machine Learning Specialization

Stanford Online · DeepLearning.AI · Andrew Ng · 2022

Andrew Ng's 2022 Machine Learning Specialization: lighter on maths than CS229, with plenty of runnable Jupyter labs. Good if you want intuition before derivations.

How to watch: of its three courses, the first two (regression and classification; neural networks and decision trees) matter most. CS229's derivations get much easier afterwards.

Note: course 2 uses TensorFlow; the rest of this route uses PyTorch, so don't invest in the framework. The official YouTube playlist covers only the first three weeks of course 1; the full specialization can be audited for free on Coursera.

Bilibili repost: “(强推|双字)最新吴恩达机器学习Deeplearning.ai课程” · 啥都会一点的研究生 · 151 parts · Chinese–English subtitles

YouTube: Machine Learning Specialization by Andrew Ng · DeepLearningAI · 41 videos

Stage 1 · Hands-on milestone

Gradient descent by hand, no framework

This snippet uses numpy only: it generates data, applies a hand-derived gradient, iterates, and finally checks the answer against the closed-form least-squares solution. If the two agree, your gradient is right.

import numpy as np

rng = np.random.default_rng(0)
X = rng.normal(size=(200, 3))                  # 200 samples, 3 features
y = X @ np.array([2.0, -1.0, 0.5]) + 0.3 + 0.1 * rng.normal(size=200)

w, b, lr = np.zeros(3), 0.0, 0.1
for step in range(500):
    err = X @ w + b - y                        # prediction error
    loss = (err ** 2).mean()                   # mean squared error
    w -= lr * 2 * X.T @ err / len(y)           # dL/dw, derived by hand
    b -= lr * 2 * err.mean()                   # dL/db
    if step % 100 == 0:
        print(f"step {step:3d}  loss {loss:.4f}")

# sanity check against the closed-form least-squares answer
A = np.c_[X, np.ones(len(y))]
print("gradient descent:", np.round(np.r_[w, b], 3))
print("least squares   :", np.round(np.linalg.lstsq(A, y, rcond=None)[0], 3))

Run: python s1_gd.py (needs numpy). In our test the two printed lines match exactly.

Then turn it into logistic regression (sigmoid plus cross-entropy loss), train it on a tabular dataset from your own field, and evaluate it with a proper train / validation / test split.

You've cleared this stage when you can:

Stage 2

Deep learning and CNNs: train your first serious model

Write backpropagation by hand; design, train and debug a convolutional network in PyTorch; and know the full path from baseline to usable model on a new dataset.

6–8 weeksbackpropagationCNNsBatchNorm / DropoutPyTorch

CS231n is widely considered one of the best introductions to deep learning. Its assignments start with networks written in numpy and move step by step to PyTorch, which is exactly the “train models by hand” goal. How many lectures you watch is flexible; assignments 1 and 2 are not.

CS231nCore≈20 h of video

Deep Learning for Computer Vision

Stanford · Fei-Fei Li, Justin Johnson, Serena Yeung et al. · Spring 2017 · 2025

Fei-Fei Li's group's course on deep learning for computer vision, the classic way into deep learning. Starting from image classification, it covers backpropagation, convolutional networks and the craft of training neural nets.

Must watch: image classification and linear classifiers, loss functions and optimisation, backpropagation, neural networks, CNNs, training neural networks (both parts), CNN architectures (AlexNet, VGG, ResNet).

Pick by interest: recurrent networks, detection and segmentation, visualisation, generative models.

Assignments: 1 and 2 are mandatory and are the real content of this stage; 3 is optional.

Bilibili repost: “【双语字幕】斯坦福CS231n《深度视觉识别》课程(2017) by Fei-Fei Li, Justin Johnson, Serena Yeung” · 爱可可-爱生活 · 16 parts · Chinese–English subtitles

YouTube: Stanford CS231N Deep Learning for Computer Vision I 2025 · Stanford Online · 18 videos

3B1BOptionalNot Stanford · 3Blue1Brown≈3 h of video

Neural Networks

3Blue1Brown · Grant Sanderson

Four animated episodes on neural networks, gradient descent and backpropagation, plus newer chapters on GPT and attention. Watch them around CS231n's backprop lecture to build intuition.

How to watch: the first four (what a neural network is, gradient descent, backprop intuition, backprop calculus) in one evening; save the Transformer chapters for stage 3.

Bilibili repost: “【官方双语】深度学习之神经网络的结构 Part 1 ver 2.0” · 3Blue1Brown · 1 parts · Chinese–English subtitles

YouTube: Neural networks · 3Blue1Brown · 10 videos

CS230Optional≈13 h of video

Deep Learning

Stanford · Andrew Ng, Kian Katanforoosh · Autumn 2018 · 2025

Andrew Ng's other deep-learning course. Its lectures focus on applying deep learning to real projects: project strategy, error analysis, the full project cycle and case studies.

How to watch: after CS231n, pick the lectures on project strategy, error analysis and full-cycle projects. The technical material repeats CS231n.

Bilibili repost: “【双语字幕+资料下载】斯坦福CS230 | 深度学习-吴恩达主讲(2018·完整版)” · ShowMeAI · 10 parts · Chinese–English subtitles (machine-translated)

YouTube: Stanford CS230: Deep Learning | Autumn 2018 · Stanford Online · 10 videos

EECS 498AlternativeNot Stanford · Michigan≈26 h of video

Deep Learning for Computer Vision

Michigan · Justin Johnson · Fall 2019

Justin Johnson, one of CS231n's original instructors, teaches an expanded version at Michigan: deeper and more recent, with all assignments in PyTorch on Colab.

When to choose it: if your research is image-centric and you want computer vision in more depth, take it instead of CS231n, or add its lectures on attention, detection and generative models afterwards.

Bilibili repost: “【双语字幕+资料下载】CS231n进阶课 | 深度学习与计算机视觉(2019·全22讲)” · ShowMeAI · 22 parts · Chinese–English subtitles

Stage 2 · Hands-on milestone

A training loop you will reuse forever

Every training loop looks like this: split the data, define the model, forward pass, loss, backward pass, update, evaluate on the validation set, keep the best checkpoint. Get it running on synthetic data first, then swap in your own data and model.

import torch
from torch import nn
from torch.utils.data import DataLoader, TensorDataset, random_split

torch.manual_seed(0)
X = torch.rand(2000, 2) * 4 - 2                # swap in your own measurements here
y = torch.sin(2 * X[:, :1]) + X[:, 1:] ** 2 + 0.05 * torch.randn(2000, 1)
train_ds, val_ds = random_split(TensorDataset(X, y), [1600, 400])
train_dl = DataLoader(train_ds, batch_size=64, shuffle=True)
val_dl = DataLoader(val_ds, batch_size=400)

model = nn.Sequential(nn.Linear(2, 64), nn.ReLU(), nn.Linear(64, 64), nn.ReLU(), nn.Linear(64, 1))
opt = torch.optim.AdamW(model.parameters(), lr=3e-3)
loss_fn = nn.MSELoss()

yv = torch.cat([yb for _, yb in val_dl])
print(f"baseline (always predict the mean): {((yv - yv.mean()) ** 2).mean():.4f}")
best = float("inf")
for epoch in range(30):
    model.train()
    for xb, yb in train_dl:
        loss = loss_fn(model(xb), yb)
        opt.zero_grad()
        loss.backward()                        # autograd does the calculus
        opt.step()
    model.eval()
    with torch.no_grad():
        val = sum(loss_fn(model(xb), yb).item() * len(xb) for xb, yb in val_dl) / len(val_ds)
    if val < best:                             # keep the best checkpoint, not the last
        best = val
        torch.save(model.state_dict(), "best.pt")
    if epoch % 5 == 0:
        print(f"epoch {epoch:2d}  val_mse {val:.4f}")
print(f"best val_mse {best:.4f}")

Run: python s2_loop.py (needs PyTorch; CPU is fine, a dozen seconds or so). In our test the validation error falls from a baseline of 1.84 to 0.0036.

Note that the code computes an “always predict the mean” baseline first. If your model can't beat the baseline, no amount of tuning matters.

You've cleared this stage when you can:

Stage 3

Transformers and LLMs: train a small language model from scratch

Write a tokenizer, attention and a Transformer from scratch and train a small language model; understand what pre-training, fine-tuning and alignment each do; read LLM papers with ease.

8–10 weeksattentionBPE tokenizationpre-trainingfine-tuning & alignment

This stage is hands-on first: build GPT line by line with Karpathy, then implement it again on your own in CS336 assignment 1. CS224n fills in the concepts; CS25 shows the frontier.

Zero to HeroCoreNot Stanford · Karpathy≈18 h of video

Neural Networks: Zero to Hero

Karpathy · Andrej Karpathy · 2022–2024

A series by Andrej Karpathy, OpenAI founding member and original CS231n instructor: from micrograd (your own autograd) all the way to GPT and a GPT-2 reproduction, typing every line. The most direct material there is for “train models by hand”.

Must watch: micrograd, the makemore series, Let's build GPT, the GPT tokenizer. The GPT-2 (124M) reproduction needs a GPU and is optional.

Method: type along; don't just watch. The micrograd episode can be watched early, during stage 2.

Bilibili repost: “【精译⚡从零开始构建 GPT 系列】Andrej Karpathy” · 常青藤中英字幕课程 · 10 parts · Chinese–English subtitles

YouTube: Neural Networks: Zero to Hero · Andrej Karpathy · 10 videos

CS336Core≈22 h of video

Language Modeling from Scratch

Stanford · Percy Liang, Tatsunori Hashimoto · Spring 2025

Stanford's course from 2025 on building language models from scratch: tokenization, architecture, GPUs and kernels, parallel training, scaling laws, data and alignment. Its assignment 1 is this handbook's final exam for training models by hand.

Must watch: the opening lectures on tokenization and resource accounting, architectures and hyperparameters, scaling laws, data, and alignment.

Pick by interest: GPUs, kernels, parallelism and inference, especially if you lean towards systems.

Assignments: assignment 1 is mandatory (tokenizer, Transformer, AdamW and training loop all from scratch); 2–5 by interest.

Bilibili repost: “斯坦福大学《从零开始的语言模型|CS336 Language Modeling from Scratch Spring 2025》中英字幕(ds-R1)” · GPT中英字幕课程资源 · 16 parts · Chinese–English subtitles (machine-translated)

YouTube: Stanford CS336 Language Modeling from Scratch I 2025 · Stanford Online · 17 videos

CS224nOptional≈26 h of video

Natural Language Processing with Deep Learning

Stanford · Christopher Manning · Winter 2021 · Spring 2024

Stanford's classic NLP course. On this route it fills in concepts: word vectors, where attention came from, and what pre-training and post-training each do.

Pick: word vectors, from recurrent networks to attention, Transformers, pre-training, post-training (instruction tuning and RLHF), evaluation.

Skippable: dependency parsing and other classic NLP material.

Bilibili repost: “【斯坦福CS224N】(2021|中英) 深度自然语言处理Natural Language Processing with Deep Learning” · 偷得半日来学习 · 18 parts · Chinese–English subtitles

YouTube: Stanford CS224N: NLP with Deep Learning | Winter 2021 · Stanford Online · 23 videos

CS25Optional≈55 h of video

Transformers United

Stanford · guest researchers · V1–V6

Stanford's Transformers seminar. Each session features a researcher presenting their own work on LLMs, multimodality, robotics, science and more.

How to watch: every session stands alone; pick by title, in any order. Good for a change of pace when stage 3 gets heavy.

Bilibili repost: “【中英字幕】2022最新 | 斯坦福CS25:Transformers United专题讲座” · 矩池云 · 10 parts · Chinese–English subtitles

YouTube: Stanford CS25 - Transformers United · Stanford Online · 50 videos

Stage 3 · Hands-on milestone

Write causal self-attention by hand, then check it against PyTorch

The heart of a Transformer is about a dozen lines. This snippet writes causal self-attention by hand (each token sees only the tokens before it) and compares the result with PyTorch's built-in implementation.

import torch
import torch.nn.functional as F

torch.manual_seed(0)
B, T, C = 2, 8, 32                             # batch, sequence length, embedding size
x = torch.randn(B, T, C)
Wq, Wk, Wv = (torch.nn.Linear(C, C, bias=False) for _ in range(3))
q, k, v = Wq(x), Wk(x), Wv(x)

scores = q @ k.transpose(-2, -1) / C ** 0.5    # (B, T, T): how much each token attends to each other
causal = torch.tril(torch.ones(T, T, dtype=torch.bool))
scores = scores.masked_fill(~causal, float("-inf"))   # a token may not look at the future
out = F.softmax(scores, dim=-1) @ v            # (B, T, C): weighted mix of values

ref = F.scaled_dot_product_attention(q, k, v, is_causal=True)
print("matches PyTorch's built-in attention:", torch.allclose(out, ref, atol=1e-5))

Run: python s3_attn.py. True means the two agree.

Next, follow Karpathy's “Let's build GPT” to write a character-level GPT, then complete CS336 assignment 1 on your own: BPE tokenizer, Transformer language model, AdamW and training loop, all written from scratch and trained on TinyStories.

You've cleared this stage when you can:

Stage 4

Agents and harnesses: write an agent that gets work done

Without a framework, write an agent that calls tools and completes multi-step tasks; then add permissions, context management, logging and evaluation to make a minimal harness.

4–6 weekstool callingagent looppermissions & sandboxingevaluation

An agent's skeleton is simple: the model decides which tool to call, your program runs it, the result goes back to the model, and the loop repeats until the task is done. The hard parts live in the harness around it: how much power to grant, what to do when the context fills up, and how to know it actually got things right.

CS294/194-196CoreNot Stanford · UC Berkeley≈20 h of video

Large Language Model Agents

UC Berkeley · Dawn Song, Xinyun Chen · Fall 2024 · Spring 2025

Berkeley's open course on LLM agents, with leading industry and academic teams on reasoning, planning, tool use, agent frameworks, evaluation and safety. Stanford has two agents courses: CS329Z is engineering-focused but its recordings are not public, and CS329A is research-level. For video lectures that build the big picture, start here.

Start with: the lectures on LLM reasoning and on the history and overview of agents, to get the big picture.

Then: frameworks, coding agents, evaluation and safety, chosen by the kind of agent you want to build. The advanced edition (spring 2025) goes deeper; watch it after you've written your own agent.

No stable Bilibili repost found yet: use search, or switch to YouTube.

YouTube: LLM Agents MOOC, Fall 2024 · Berkeley RDI · 14 videos

CS329ZCore

Engineering AI Agents

Stanford · Diyi Yang, Michael Ryan, John Yang · Fall 2026

Stanford's Fall 2026 “Engineering AI Agents” treats agents as engineered systems, from simple LLM pipelines to compound AI systems to autonomous agents: RAG, tool use and MCP, design patterns and context management, memory, multi-agent systems, prompt and weight optimization, data, evaluation and safety. You first build the core components from scratch, then see how frameworks such as DSPy abstract them. Recordings are for enrolled students only; the slides, reading lists and assignments are public.

How: work through the schedule lecture by lecture, slides plus the required readings, as the backbone of stage 4; where you want video, use the Berkeley recordings. The course runs from September to December 2026, so the later slides appear as the quarter goes on. It expects CS224N- or CS336-level background, which stage 3 gives you.

Best part: HW1, “Build an Agentic Harness”: with no agent framework, just a chat-completion call and your own code, build a company's internal assistant with tools, a terminal, memory and a human in the loop. The deterministic tests make no model calls, so you can get the logic right for free; the live evaluation needs an OpenRouter API key.

READCoreNot Stanford · Anthropic · OpenAI · DeepSeek · MCP

Agent engineering reading list

Anthropic · OpenAI · DeepSeek · MCP · engineering docs

To build agents, the most useful reading is engineering write-ups from the teams that ship them, not videos. These explain the tool-calling protocol, and when a simple workflow is enough and when you really need an agent.

Read in order: ① Anthropic's “Building effective agents”, on common agent patterns and their trade-offs; ② the tool-calling docs of whichever API you use; ③ the Model Context Protocol (MCP) introduction, the common standard for plugging in tools.

CS329AOptional

Self-Improving AI Agents

Stanford · Aakanksha Chowdhery, Azalia Mirhoseini · Autumn 2025

Stanford CS329A, Self-Improving AI Agents: test-time compute, verification, reinforcement learning, memory, search and deep research, coding agents. In August 2026 Stanford Online released nine condensed lecture recordings; we also built a free interactive study companion from the course site and papers (in English, with Chinese support): all 20 sessions, with hands-on labs and quizzes.

When: after you've written your own minimal agent. Watch the nine recordings for the big picture, then use the companion to read the papers chapter by chapter and test yourself. It's the advanced path after stage 4.

No stable Bilibili repost found yet: use search, or switch to YouTube.

YouTube: CS329A Self-Improving AI Agents · Stanford Online · 9 videos

Stage 4 · Hands-on milestone

A minimal agent in about sixty lines, with the beginnings of a harness

Python standard library only, and it works with any OpenAI-compatible endpoint: OpenAI, Anthropic, Gemini, Mistral, DeepSeek, or a local Ollama. It already has three harness essentials: a tool sandbox (it can only touch the workspace/ folder), human confirmation before any write, and a printed trace of every step.

import json, os, pathlib, urllib.request

BASE = os.environ.get("LLM_BASE_URL", "https://api.deepseek.com")   # any OpenAI-compatible endpoint
MODEL = os.environ.get("LLM_MODEL", "deepseek-chat")
KEY = os.environ.get("LLM_API_KEY", "")
ROOT = pathlib.Path("workspace").resolve()     # the agent may only touch this folder
ROOT.mkdir(exist_ok=True)

def inside(path):                              # permission check #1: stay in the sandbox
    p = (ROOT / path).resolve()
    if not p.is_relative_to(ROOT):
        raise PermissionError(f"{path} is outside the workspace")
    return p

def list_files(path="."):
    return "\n".join(sorted(f.name for f in inside(path).iterdir()))

def read_file(path):
    return inside(path).read_text(encoding="utf-8")[:4000]   # cap what flows back into context

def write_file(path, content):
    if input(f"Allow writing {path}? [y/N] ").strip().lower() != "y":   # permission check #2: ask a human
        return "the user refused this write"
    inside(path).write_text(content, encoding="utf-8")
    return f"wrote {len(content)} characters to {path}"

TOOLS = {f.__name__: f for f in (list_files, read_file, write_file)}
SCHEMAS = [
    {"type": "function", "function": {"name": "list_files", "description": "List files in a workspace folder",
        "parameters": {"type": "object", "properties": {"path": {"type": "string"}}}}},
    {"type": "function", "function": {"name": "read_file", "description": "Read a UTF-8 text file from the workspace",
        "parameters": {"type": "object", "properties": {"path": {"type": "string"}}, "required": ["path"]}}},
    {"type": "function", "function": {"name": "write_file", "description": "Create or overwrite a text file in the workspace",
        "parameters": {"type": "object", "properties": {"path": {"type": "string"}, "content": {"type": "string"}},
                       "required": ["path", "content"]}}},
]

def chat(messages):
    body = json.dumps({"model": MODEL, "messages": messages, "tools": SCHEMAS}).encode()
    req = urllib.request.Request(BASE.rstrip("/") + "/chat/completions", data=body,
                                 headers={"Content-Type": "application/json", "Authorization": f"Bearer {KEY}"})
    with urllib.request.urlopen(req, timeout=120) as r:
        return json.load(r)["choices"][0]["message"]

def run(task, max_steps=10):
    messages = [{"role": "system", "content": "You work inside a sandboxed workspace. Use the tools; never guess file contents."},
                {"role": "user", "content": task}]
    for step in range(max_steps):              # the loop is the agent
        msg = chat(messages)
        messages.append(msg)
        if not msg.get("tool_calls"):
            return msg.get("content")
        for call in msg["tool_calls"]:
            name, args = call["function"]["name"], json.loads(call["function"]["arguments"] or "{}")
            try:
                result = TOOLS[name](**args)
            except Exception as e:             # errors go back to the model, not up the stack
                result = f"error: {e}"
            print(f"[{step}] {name}({args}) -> {str(result)[:60]!r}")   # the trace: your first eval tool
            messages.append({"role": "tool", "tool_call_id": call["id"], "content": str(result)})
    return "stopped: step limit reached"

if __name__ == "__main__":
    print(run("Summarise every .txt file in the workspace into summary.md"))

Run: set LLM_BASE_URL, LLM_MODEL and LLM_API_KEY (a local Ollama needs no key), then python s4_agent.py. We tested three paths against a mock endpoint: normal completion, an out-of-sandbox read being blocked, and a write being refused.

Then grow it into a real harness, one step at a time: ① compress the history when the context gets long; ② add retries and timeouts; ③ count tokens per task; ④ build an evaluation set of 20 small tasks with automatic scoring, and rerun it after every model or prompt change; ⑤ let the agent run code, but inside a sandbox with a timeout and no network.

For a larger exercise, do CS329Z's HW1: it is a complete harness-engineering assignment (see the CS329Z card above).

You've cleared this stage when you can:

Electives

Electives: choose by research direction

Take these after the main route, or whenever your research needs them. For each course, pick only the lectures that touch your problem.

PIMLOptionalNot Stanford · University of Washington

Physics-Informed Machine Learning

University of Washington · Steve Brunton

Steve Brunton's (University of Washington) lectures on physics-informed machine learning, data-driven modelling of dynamical systems, PINNs and neural operators. For PhDs in structures, fluids, hydraulics or control, this is the elective closest to their own research.

How to watch: after stage 2. Start with the overview, then pick the topics that match your equations and your systems.

Bilibili repost: “【Steve Brunton】物理信息机器学习(PIML)全套教程:AI for Science 必修课 | 稀疏动力学/几何深度学习/神经微分方程” · 赛博门外憨 · 24 parts

YouTube: Physics Informed Machine Learning · Steve Brunton · 24 videos

CS234Optional≈20 h of video

Reinforcement Learning

Stanford · Emma Brunskill · Spring 2024

Stanford's reinforcement-learning course: MDPs, Q-learning, policy gradients, PPO, offline RL, and the RLHF and DPO used to align LLMs.

Good for: scheduling, control and decision problems, or really understanding RL-based post-training of LLMs.

Bilibili repost: “【强化学习 CS234 2024】斯坦福大学—中英字幕” · 常青藤中英字幕课程 · 16 parts · Chinese–English subtitles

YouTube: Stanford CS234: Reinforcement Learning | Spring 2024 · Stanford Online · 16 videos

CS224WOptional≈20 h of video

Machine Learning with Graphs

Stanford · Jure Leskovec · 2021

Stanford's machine learning with graphs: node embeddings, graph neural networks (GCN, GraphSAGE, GAT), knowledge graphs, graph generative models.

Good for: data that is naturally a network: pipe networks, power grids, transport networks, structural member connectivity, molecules.

Bilibili repost: “【双语字幕】斯坦福CS224W《图机器学习》课程(2021) by Jure Leskovec” · 爱可可-爱生活 · 60 parts · Chinese–English subtitles

YouTube: Stanford CS224W: Machine Learning with Graphs · Stanford Online · 60 videos

CS236Optional≈23 h of video

Deep Generative Models

Stanford · Stefano Ermon · 2023

Stanford's deep generative models: autoregressive models, VAEs, normalising flows, GANs, energy-based and diffusion models, with rigorous derivations.

Good for: understanding diffusion models properly, or using generative models as simulation surrogates, for data augmentation or inverse problems.

Bilibili repost: “[中英字幕] 斯坦福大学 CS236:深度生成模型 I 2023 I Stefano Ermon” · AInsight · 18 parts · Chinese–English subtitles

YouTube: Stanford CS236: Deep Generative Models I 2023 · Stanford Online · 18 videos

CS330Optional≈23 h of video

Deep Multi-Task and Meta Learning

Stanford · Chelsea Finn · Autumn 2022

Stanford's multi-task and meta-learning course: transfer learning, multi-task learning, meta-learning, few-shot learning, domain adaptation.

Good for: engineering settings with little data and many operating conditions, e.g. moving from one plant to another, or from lab data to field data.

Bilibili repost: “斯坦福大学《深度多任务与元学习|Stanford CS330 Deep Multi-Task and Meta Learning 2022》中英(豆包翻译)” · GPT中英字幕课程资源 · 17 parts · Chinese–English subtitles (machine-translated)

YouTube: Stanford CS330: Deep Multi-Task and Meta Learning | Autumn 2022 · Stanford Online · 17 videos

CS221Optional≈25 h of video

Artificial Intelligence: Principles and Techniques

Stanford · Percy Liang et al. · Autumn 2019 · 2025

Stanford's introduction to AI: search, MDPs, games, constraint satisfaction, Bayesian networks, logic. Broad coverage that rounds out your picture of AI beyond deep learning.

Good for: planning, scheduling and probabilistic-reasoning problems, or anyone who wants the full map of AI.

Bilibili repost: “【斯坦福大学】CS221 人工智能原理与技术 · 2019秋(完结·中英字幕·人工校对中)” · 鬼谷良师 · 19 parts · Chinese–English subtitles (machine-translated)

YouTube: Stanford CS221: Artificial Intelligence | Autumn 2025 · Stanford Online · 20 videos

EE364AOptional≈25 h of video

Convex Optimization I

Stanford · Stephen Boyd · 2023

Stephen Boyd's Convex Optimization, the standard course in the field. Training a model is an optimisation problem; this course gives you firm ground to understand it.

Good for: readers in optimisation, control or signal processing, or anyone who wants to understand regularisation, duality and constrained optimisation in depth.

Bilibili repost: “【斯坦福大学】EE364A 凸优化 · 2014年冬(完结·中英字幕·机翻)” · 鬼谷良师 · 13 parts · Chinese–English subtitles (machine-translated)

YouTube: Stanford EE364A Convex Optimization I Stephen Boyd I 2023 · Stanford Online · 18 videos

Environment and compute

Get it running

Stages 0–2 run on an ordinary laptop; stage 3 needs a GPU, which free notebooks or hourly rentals cover; stage 4 needs only a model API.

Python environment

Install Miniconda or uv and give each course its own environment so dependencies don't fight.

Install PyTorch with the selector on pytorch.org; without an NVIDIA GPU, choose the CPU build. VS Code with the Python and Jupyter extensions is a good editor.

GPU compute

CS231n assignments can be done on a CPU, just more slowly.

For CS336 assignment 1 and the GPT-2 reproduction, use the free GPU tiers of Google Colab or Kaggle Notebooks (quotas change; check their current terms), or rent a cloud GPU by the hour.

Shut hourly instances down when you're done.

Models and datasets

Models and datasets, TinyStories included, come from Hugging Face.

In mainland China, set HF_ENDPOINT=https://hf-mirror.com or use ModelScope instead.

Local models

With Ollama you can run open models such as Qwen, Llama or Mistral on your own machine. The stage-4 agent can talk to the local endpoint: free, and nothing leaves your computer.

Which models run on which hardware: see our hands-on report “Putting AI on your own computer” (in Chinese).

Model APIs for stage 4

All of these speak the OpenAI-compatible format: change the two environment variables LLM_BASE_URL and LLM_MODEL and not a line of code. Model names change often; check each provider's docs.

ProviderLLM_BASE_URLDocs
OpenAIhttps://api.openai.com/v1Function calling
Anthropic (OpenAI-compatible)https://api.anthropic.com/v1/OpenAI SDK compatibility
Google Gemini (OpenAI-compatible)https://generativelanguage.googleapis.com/v1beta/openai/OpenAI compatibility
Mistralhttps://api.mistral.ai/v1docs.mistral.ai
DeepSeekhttps://api.deepseek.comapi-docs.deepseek.com
Local Ollamahttp://localhost:11434/v1ollama.com

How to study

Eight study habits for PhDs

You already know how to do research. Bring those habits with you and AI comes much faster.

  1. Assignments matter more than videosIn these Stanford courses the assignments are the course. Watch at 1.5× and skip freely, but never copy solutions. When stuck, reread the notes first, then the forums and other people's discussions.
  2. Notes first, video secondSpend 15 minutes scanning each lecture's notes or slides, then watch with questions in mind. Fast-forward what you understand, replay what you don't.
  3. Always build a baselinePredict the mean, fit a linear model, or use your field's traditional method: a new model that can't beat the baseline doesn't count. In engineering this matters more than any tuning trick.
  4. Train models like you run experimentsFix random seeds, log every configuration and result, change one variable at a time. “It seems better” is not a conclusion; it has to reproduce.
  5. Use data from your own fieldAt every stage, run a small project on data from your own research. Knowing where the data comes from, where the errors come from and which metrics matter for engineering is the biggest advantage someone switching fields can have.
  6. Use AI to learn AI, but don't let it do your homeworkAsking an LLM to explain a derivation, quiz you or review your code is great; but write the assignment code yourself, or stage 3 will stop you cold.
  7. Read one paper closely each weekStart from the course reading lists and follow citations with arXiv and Semantic Scholar. The bar for a close read: you can reproduce one figure from the paper.
  8. Keep your notes in publicPut each stage's notes and code on GitHub or a blog. Writing forces real understanding, and it becomes your best portfolio.

My progress

Where am I?

Tick “Done” at the bottom of each course card and each stage's milestone items. Progress is stored in this browser on this device and never uploaded. All four language editions share the same progress.

Glossary

Terms in Chinese, English, Japanese and French

Courses and notes are in English. Knowing these words makes the videos much easier to follow.

中文English日本語Français
机器学习machine learning機械学習apprentissage automatique
深度学习deep learning深層学習(ディープラーニング)apprentissage profond
监督学习supervised learning教師あり学習apprentissage supervisé
损失函数loss function損失関数fonction de perte
梯度下降gradient descent勾配降下法descente de gradient
反向传播backpropagation誤差逆伝播法rétropropagation du gradient
过拟合overfitting過学習surapprentissage
正则化regularization正則化régularisation
训练集 / 验证集 / 测试集training / validation / test set訓練/検証/テストデータjeux d’entraînement, de validation et de test
基线baselineベースラインréférence (baseline)
超参数hyperparameterハイパーパラメータhyperparamètre
卷积神经网络convolutional neural network (CNN)畳み込みニューラルネットワークréseau de neurones convolutif
批归一化batch normalizationバッチ正規化normalisation par lots
注意力机制attention注意機構(アテンション)mécanisme d’attention
词元tokenトークンjeton (token)
分词器tokenizerトークナイザーtokeniseur
嵌入(向量)embedding埋め込みplongement (embedding)
预训练pre-training事前学習pré-entraînement
微调fine-tuningファインチューニングaffinage (fine-tuning)
推理(模型运行)inference推論inférence
上下文窗口context windowコンテキストウィンドウfenêtre de contexte
智能体agentエージェントagent
工具调用tool calling (function calling)ツール呼び出しappel d’outils
评测evaluation (evals)評価évaluation
检索增强生成retrieval-augmented generation (RAG)検索拡張生成(RAG)génération augmentée par récupération (RAG)
强化学习reinforcement learning強化学習apprentissage par renforcement

FAQ

Frequently asked questions

Should I relearn the maths properly first?

No. The linear algebra, probability and calculus of an engineering degree are mostly enough. Use the self-check to find specific gaps and patch only those; most of the time you'll learn as you go, and CS229 introduces each new tool when it first needs it.

My English listening isn't great. What can I do?

YouTube's subtitle settings offer auto-translation into many languages. The notes and assignments are in English; translation tools help, but learn the original English terms (see the glossary). Chinese readers can switch to Bilibili, where most reposts carry Chinese–English subtitles (many machine-translated).

Can I do this without a GPU?

Stages 0–2, yes; CS231n's assignments run on a CPU. Stage 3's CS336 assignment and the GPT-2 reproduction need a GPU: free Colab or Kaggle notebooks, or an hourly rental. You can also shrink the model and data, get it working on a CPU, then move to a GPU.

Do I have to follow the order?

Stages 1, 2 and 3 depend on each other; take them in order. The API-based agent work in stage 4 needs no training knowledge, so you can start it in parallel from stage 1; building something early helps keep you motivated.

A link is dead. What now?

Every course card also has a search link and the official course site; the YouTube links point to the official channels where possible. Please tell us about dead links (email in the footer) and we'll update them.

Why mostly Stanford?

These Stanford courses form a complete curriculum, publish all notes and assignments, and stay current (CS336, for instance, is from 2025). A few non-Stanford resources (Karpathy, Berkeley's agents course, 3Blue1Brown, MIT and Harvard courses) appear only where they fit better, and every card says where it comes from.

Will this get me a machine-learning job?

The goal is for you to use AI independently in your own research and engineering. Changing careers takes interview prep, project experience and more systematic training, which this handbook doesn't cover, but the assignments and projects on this route are a very solid start.

How is this different from AI-tool tutorials?

Tool tutorials teach you to use products someone else built. This handbook teaches the principles and how to build them yourself: train your own models, write your own agents. Once you understand the principles, you'll see much more clearly what any tool can and can't do.