Learn machine learning from scratch

Start at chapter 1 and build up: what a model is, how it measures its own mistakes, and how it learns. Everything is worked out in plain Python, with the maths shown rather than assumed. Two shorter tracks hold reference notes on the maths and on modern architectures.

Track Progress: 0 Completed
0%
The Math Behind MLLEVEL 4 · FRONTIERChapter 8

Continuous Flow Matching ODEs & Post-Training RL Mathematics

Rectified flow velocity fields, Bellman optimality, DPO closed-form substitution, and DeepSeek-R1 GRPO advantage.

Reference notes. Condensed summaries of each topic, not step-by-step lessons. The Core Course is the one to work through.

7 min Prerequisites: Differential Equations & Probability
Inspect Architecture: DeepSeek-V3 and R1 reasoning MoE

1. The idea

Modern frontier AI models synthesize media via straight-line Ordinary Differential Equations (Rectified Flow Matching) and learn complex reasoning behaviors through group-normalized relative advantage reinforcement learning (DeepSeek-R1 GRPO). These mathematical breakthroughs replace complex diffusion SDEs with deterministic velocity vectors and eliminate the need for separate Value critic networks.

Chart of the DPO loss for one preference pair, minus log sigma(z), against z, which is beta times the chosen answer's log-ratio minus the rejected answer's log-ratio, where a log-ratio is log of pi_theta over pi_ref. The loss is large for negative z, passes ln 2, about 0.693, at z = 0, and falls towards 0 for positive z.Chart of the DPO loss for one preference pair, minus log sigma(z), against z, which is beta times the chosen answer's log-ratio minus the rejected answer's log-ratio, where a log-ratio is log of pi_theta over pi_ref. The loss is large for negative z, passes ln 2, about 0.693, at z = 0, and falls towards 0 for positive z.
DPO pushes the chosen answer's log-ratio above the rejected one's, directly on the policy, with no reward model to train.

2. The math

Rectified Flow Matching Straight-Line Trajectory
xt=(1−t)x0+tx1  ⟹  Target Velocity vt(xt)=dxtdt=x1−x0x_t = (1-t) x_0 + t x_1 \implies \text{Target Velocity } v_t(x_t) = \frac{d x_t}{dt} = x_1 - x_0
Straight probability path connecting pure Gaussian noise x_0 to clean data point x_1.
Flow Matching Least-Squares Objective
LRFM(θ)=Et∼U(0,1),x0∼p0,x1∼p1[∥vθ(xt,t)−(x1−x0)∥22]\mathcal{L}_{\text{RFM}}(\theta) = \mathbb{E}_{t \sim \mathcal{U}(0,1), x_0 \sim p_0, x_1 \sim p_1} \left[ \|v_\theta(x_t, t) - (x_1 - x_0)\|_2^2 \right]
Neural network v_θ directly learns the constant velocity vector field along the ODE trajectory.
Direct Preference Optimization (DPO) Closed-Form Objective
LDPO(θ)=−E(x,yw,yl)[log⁡σ(βlog⁡πθ(yw∣x)πref(yw∣x)−βlog⁡πθ(yl∣x)πref(yl∣x))]\mathcal{L}_{\text{DPO}}(\theta) = -\mathbb{E}_{(x, y_w, y_l)} \left[ \log \sigma \left( \beta \log \frac{\pi_\theta(y_w|x)}{\pi_{\text{ref}}(y_w|x)} - \beta \log \frac{\pi_\theta(y_l|x)}{\pi_{\text{ref}}(y_l|x)} \right) \right]
Directly solves the constrained RL problem without training a separate reward model or critic.
DeepSeek-R1 Group Relative Policy Optimization (GRPO) Advantage
Ai=ri−mean({r1,…,rG})std({r1,…,rG})+ϵJGRPO(θ)=1G∑i=1Gmin⁡(πθ(oi∣q)πold(oi∣q)Ai,clip(πθ(oi∣q)πold(oi∣q), 1−ε, 1+ε)Ai)A_i = \frac{r_i - \text{mean}(\{r_1, \dots, r_G\})}{\text{std}(\{r_1, \dots, r_G\}) + \epsilon} \qquad \mathcal{J}_{\text{GRPO}}(\theta) = \frac{1}{G}\sum_{i=1}^G \min\left( \frac{\pi_\theta(o_i|q)}{\pi_{\text{old}}(o_i|q)} A_i, \text{clip}\left( \frac{\pi_\theta(o_i|q)}{\pi_{\text{old}}(o_i|q)},\ 1-\varepsilon,\ 1+\varepsilon \right) A_i \right)
Computes relative baseline advantages across group of G sampled rollouts, completely eliminating the Critic model.

• In RLHF, the objective with KL penalty is max_pi E_{x, y ~ pi}[r(x, y)] - beta * D_KL(pi(y|x) || pi_ref(y|x)).

• The closed-form analytical solution to this constrained optimization is pi*(y|x) = (1 / Z(x)) * pi_ref(y|x) * exp((1 / beta) * r(x, y)).

• Rearranging yields the exact implicit reward: r(x, y) = beta * log(pi*(y|x) / pi_ref(y|x)) + beta * log Z(x).

• Substitute this implicit reward into the Bradley-Terry preference probability P(y_w > y_l | x) = sigma(r(x, y_w) - r(x, y_l)).

• The partition function terms beta * log Z(x) cancel out exactly, yielding the DPO loss without any reward model. Q.E.D.

3. How it works

1
Deterministic Flow Generation
Euler ODE integration dx/dt = v_theta(x, t) generates high-resolution samples in as few as 4-8 steps.
2
Group-Normalized Baseline
GRPO samples G responses for question q and normalizes rewards to create zero-mean advantages.
3
Emergent Long Chain-of-Thought
Pure rule-based correctness rewards (math/code tests) combined with GRPO drive models to self-reflect and verify.

4. The code (python)

math_flow_rl.py
import numpy as np

# GRPO Group-Normalized Advantage Calculation from Scratch (DeepSeek-R1)
def compute_grpo_advantages(rewards: np.ndarray, eps: float = 1e-8):
    mean_r = np.mean(rewards, axis=-1, keepdims=True)
    std_r = np.std(rewards, axis=-1, keepdims=True)
    advantages = (rewards - mean_r) / (std_r + eps)
    return advantages

if __name__ == "__main__":
    sample_rewards = np.array([
        [1.0, 0.0, 1.0, 0.0],  # Prompt 1: 2 correct, 2 incorrect
        [0.8, 0.9, 0.2, 0.8]   # Prompt 2: partial credits
    ])
    adv = compute_grpo_advantages(sample_rewards)
    print("Computed GRPO Relative Advantages:")
    print(np.round(adv, 3))
    assert np.allclose(np.mean(adv, axis=-1), 0.0), "Group mean must be zero!"
    print("✓ Zero-mean baseline normalization verified.")

5. Check yourself

Answer all 1 questions correctly to complete the chapter · 0 / 1 done
Q1/1 How does DeepSeek-R1's GRPO eliminate the need for a separate Value (Critic) network during RL fine-tuning?

Finished this chapter?

Weekly newsletter

The Epoch Zero newsletter

What changed in ML architectures this week: new models worth knowing, benchmark moves, and one architecture explained in plain words. Free, once a week, unsubscribe anytime.