Phase VI · Days 71–73 · ~8 hours Prerequisites: 01-dl-foundations Learning Objectives: Understand RL fundamentals, policy gradient, PPO, why RL alone isn’t enough for robotics
| Previous | 10-vision-language-models | Next | 12-diffusion-flow |
|---|---|---|---|
Reinforcement learning is the mathematical framework for learning optimal behavior from interaction. An agent takes actions in an environment, receives rewards, and learns a policy that maximizes cumulative reward. While RL has produced spectacular results in games (AlphaGo, Atari), its application to real robotics faces fundamental challenges that motivate imitation learning and VLA approaches.
Why study RL if we’re heading toward imitation learning? 1. RL provides the theoretical foundation for sequential decision-making 2. Many VLA training pipelines use RL fine-tuning after imitation pretraining 3. Understanding RL failures in robotics clarifies why demonstrations are so valuable 4. PPO is the backbone of RLHF used in LLM alignment (connects to Phase III)
An MDP is defined by the tuple $(S, A, P, R, \gamma)$:
| Symbol | Meaning | Robotics Example |
|---|---|---|
| $S$ | State space | Joint angles, end-effector pose, camera image |
| $A$ | Action space | Joint torques, velocity commands, gripper open/close |
| $P(s'|s,a)$ | Transition dynamics | Physics of the robot + environment |
| $R(s,a,s')$ | Reward function | +1 for grasping object, -0.01 per timestep |
| $\gamma$ | Discount factor | Typically 0.99 — how much we value future rewards |
The agent’s goal: find a policy $\pi(a|s)$ that maximizes the expected cumulative discounted reward:
where $\tau = (s_0, a_0, s_1, a_1, \ldots)$ is a trajectory sampled under policy $\pi$.
State value function — expected return starting from state $s$, following policy $\pi$:
Action-value (Q) function — expected return starting from state $s$, taking action $a$, then following policy $\pi$:
Advantage function — how much better is action $a$ than average?
The advantage function is crucial for policy gradient methods — it tells us which actions are better than expected, not just which states are good.
The recursive structure of value functions:
Optimal Bellman equation (for $Q^*$):
| Aspect | Value-Based (DQN) | Policy-Based (PG) |
|---|---|---|
| What is learned | $Q(s,a)$ → derive policy | $\pi_\theta(a|s)$ directly |
| Action space | Discrete (enumerate all actions) | Continuous or discrete |
| Stochastic policies | Hard (ε-greedy hack) | Natural |
| Convergence | Can be unstable | Guaranteed local convergence |
| Sample efficiency | Better (off-policy possible) | Worse (on-policy) |
| Robotics fit | Poor (continuous actions) | Better |
For robotics: policy gradient methods dominate because: - Actions are continuous (joint torques, velocities) - We want stochastic policies (for exploration and multimodal behavior) - Direct policy optimization is more natural for control
The fundamental dilemma: - Exploit: use current best policy to maximize reward - Explore: try new actions to discover potentially better strategies
In robotics, exploration is dangerous and expensive: - Random exploration can damage the robot or environment - Each real-world interaction takes real time (no fast-forward) - The cost of a bad action in the real world is high
This is a key motivation for imitation learning: instead of exploring randomly, start from expert demonstrations.
Start with a parameterized policy $\pi_\theta(a|s)$ (e.g., a neural network outputting action distribution). We want to maximize:
The Policy Gradient Theorem (Williams, 1992):
where $G_t = \sum_{k=t}^{T} \gamma^{k-t} R_k$ is the return from timestep $t$.
Intuition: increase the probability of actions that led to high returns, decrease the probability of actions that led to low returns.
REINFORCE algorithm:
for each episode:
collect trajectory τ = (s₀, a₀, r₀, s₁, a₁, r₁, ...)
for each timestep t:
compute return Gₜ = Σ γᵏ rₜ₊ₖ
θ ← θ + α · ∇log π_θ(aₜ|sₜ) · Gₜ
Problem: high variance! The return $G_t$ varies wildly between episodes, making gradient estimates noisy.
Replace $G_t$ with the advantage $A_t = G_t - b(s_t)$ where $b(s_t)$ is a baseline (typically the value function $V(s_t)$):
Why this works: subtracting the baseline doesn’t change the expected gradient (unbiased) but dramatically reduces variance. The advantage tells us: “was this action better or worse than average from this state?”
GAE (Schulman et al., 2016) balances bias and variance with parameter $\lambda$:
where $\delta_t = r_t + \gamma V(s_{t+1}) - V(s_t)$ is the TD residual.
PPO (Schulman et al., 2017) is the workhorse of modern RL. Key insight: prevent destructively large policy updates.
The clipped surrogate objective:
where: - $r_t(\theta) = \frac{\pi_\theta(a_t|s_t)}{\pi_{\theta_{\text{old}}}(a_t|s_t)}$ is the probability ratio - $\epsilon$ is the clip parameter (typically 0.2) - $\hat{A}_t$ is the estimated advantage
How the clip works:
| Advantage | Ratio too high ($r > 1+\epsilon$) | Ratio too low ($r < 1-\epsilon$) |
|---|---|---|
| $A > 0$ (good action) | Clip: don’t increase probability too much | Allow: increase probability |
| $A < 0$ (bad action) | Allow: decrease probability | Clip: don’t decrease too much |
PPO algorithm:
for each iteration:
collect trajectories with current policy π_θ_old
compute advantages  using GAE
for each mini-batch epoch (typically 3-10):
compute ratio r_t(θ) = π_θ(a|s) / π_θ_old(a|s)
compute clipped objective L^CLIP
update θ via gradient ascent on L^CLIP
θ_old ← θ
| Hyperparameter | Typical Value | Effect |
|---|---|---|
| Clip $\epsilon$ | 0.2 | Constrains policy update size |
| GAE $\lambda$ | 0.95 | Bias-variance tradeoff for advantages |
| Learning rate | 3e-4 | Adam optimizer step size |
| Epochs per iteration | 3-10 | How many passes over collected data |
| Batch size | 2048+ | Transitions per update |
| Discount $\gamma$ | 0.99 | How far ahead to look |
Training RL in simulation is fast but transfer to real robots is hard:
| Simulation | Reality |
|---|---|
| Perfect physics | Friction, deformation, contact dynamics |
| Perfect sensing | Noisy cameras, encoder drift |
| Instant reset | Manual reset takes minutes |
| Unlimited episodes | Robot wear, safety concerns |
| Deterministic | Non-deterministic, non-stationary |
Approaches to bridge the gap: - Domain randomization: randomize physics parameters during sim training - System identification: measure real-world parameters, match in sim - Sim-to-real transfer: progressive adaptation from sim to real - Real-world fine-tuning: sim pretrain → real fine-tune (few-shot)
RL algorithms need enormous amounts of data:
| Algorithm | Samples for Basic Manipulation | Wall-Clock Time (Real Robot) |
|---|---|---|
| PPO | ~10M timesteps | ~3000 hours (125 days!) |
| SAC | ~1M timesteps | ~300 hours (12 days) |
| Model-based | ~100K timesteps | ~30 hours |
| BC (imitation) | ~100 demonstrations | ~1 hour of demos |
This is the fundamental argument for imitation learning: a human demonstrator compresses millions of timesteps of experience into a few hundred demonstrations.
Designing reward functions is surprisingly hard:
Example: “pick up the red block” - Sparse reward: +1 when block is grasped → agent never discovers it randomly - Dense reward: distance to block → agent hovers hand near block, never grasps - Shaped reward: distance + height + grasp → agent finds unintended shortcuts
Reward hacking: the agent optimizes the reward function, not the intended task. The reward function is a lossy compression of human intent.
Comparison with imitation learning: demonstrations ARE the reward signal. The expert implicitly encodes the task objective through their behavior.
Real robots can: - Damage themselves (joint limits, collisions) - Damage the environment (breaking objects, scratching surfaces) - Harm humans (contact forces, unexpected movements)
RL exploration involves taking random actions → unsafe by default.
Safe RL approaches: - Constrained MDPs with safety constraints - Action space limits and velocity bounds - Human oversight during training - Sim-only exploration + real-world deployment
In robotics, success/failure is often binary and delayed: - “Did the robot successfully assemble the furniture?” → one bit of feedback after thousands of actions - Which actions were responsible for success or failure? - Credit assignment problem: distributing the final reward across the trajectory
Hindsight Experience Replay (HER): reinterpret failed trajectories as successful for a different goal. “I didn’t reach the target, but I reached somewhere — that’s a valid demonstration for reaching that location.”
| Challenge | Severity | RL Solution | Better Alternative |
|---|---|---|---|
| Sample efficiency | Critical | Model-based RL | Imitation learning |
| Reward design | High | Inverse RL | Demonstrations |
| Safety | Critical | Constrained RL | Supervised learning from safe demos |
| Sim-to-real | High | Domain randomization | Real demonstrations |
| Sparse rewards | High | HER, curiosity | Dense supervision from demos |
The emerging paradigm: 1. Pretrain with imitation learning (demonstrations) 2. Fine-tune with RL (for optimization beyond human performance) 3. This is exactly the LLM pattern: pretrain on data, RLHF for alignment
Let’s implement the core RL algorithm from scratch:
import torch
import torch.nn as nn
import torch.optim as optim
import numpy as np
try:
import gymnasium as gym
except ImportError:
import gym
class PolicyNetwork(nn.Module):
"""Simple 2-layer policy for CartPole."""
def __init__(self, obs_dim=4, act_dim=2, hidden=128):
super().__init__()
self.net = nn.Sequential(
nn.Linear(obs_dim, hidden),
nn.ReLU(),
nn.Linear(hidden, act_dim),
)
def forward(self, x):
return torch.softmax(self.net(x), dim=-1)
def reinforce(env_name="CartPole-v1", episodes=500, gamma=0.99, lr=1e-3):
"""REINFORCE with baseline (mean return)."""
env = gym.make(env_name)
policy = PolicyNetwork()
optimizer = optim.Adam(policy.parameters(), lr=lr)
all_returns = []
for ep in range(episodes):
obs, _ = env.reset()
log_probs, rewards = [], []
done = False
while not done:
obs_t = torch.FloatTensor(obs)
probs = policy(obs_t)
dist = torch.distributions.Categorical(probs)
action = dist.sample()
log_probs.append(dist.log_prob(action))
obs, reward, terminated, truncated, _ = env.step(action.item())
rewards.append(reward)
done = terminated or truncated
# Compute discounted returns
returns = []
G = 0
for r in reversed(rewards):
G = r + gamma * G
returns.insert(0, G)
returns = torch.tensor(returns)
# Baseline: subtract mean return for variance reduction
returns = (returns - returns.mean()) / (returns.std() + 1e-8)
# Policy gradient loss
loss = -sum(lp * G for lp, G in zip(log_probs, returns))
optimizer.zero_grad()
loss.backward()
optimizer.step()
ep_return = sum(rewards)
all_returns.append(ep_return)
if (ep + 1) % 50 == 0:
mean_ret = np.mean(all_returns[-50:])
print(f"Episode {ep+1:4d} | Mean Return (last 50): {mean_ret:.1f}")
env.close()
return policy, all_returns
# Run it
policy, returns = reinforce(episodes=300)
# CartPole is "solved" at 195+ average return over 100 episodes
print(f"\nFinal 100-episode average: {np.mean(returns[-100:]):.1f}")
Key insight: The entire REINFORCE algorithm is just: 1. Sample a trajectory using the current policy 2. Compute returns (discounted sum of rewards) 3. Push gradients in the direction of actions that led to high returns
This is the foundation that PPO, TRPO, and ultimately RLHF all build upon.
| Algorithm | Type | On/Off Policy | Action Space | Sample Eff. | Stability | Robotics Use |
|---|---|---|---|---|---|---|
| REINFORCE | PG | On | Continuous | Very low | Low | Rare |
| PPO | PG | On | Continuous | Low | High | Common |
| TRPO | PG | On | Continuous | Low | High | Moderate |
| SAC | Actor-Critic | Off | Continuous | Medium | High | Common |
| TD3 | Actor-Critic | Off | Continuous | Medium | Medium | Common |
| DQN | Value | Off | Discrete only | Medium | Medium | Rare |
| DDPG | Actor-Critic | Off | Continuous | Medium | Low | Declining |
| DrQ-v2 | Actor-Critic | Off | Continuous | High | Medium | Growing |
For robotics, the winners are: PPO (on-policy, stable) and SAC (off-policy, sample-efficient).
RL provides the theoretical foundation for sequential decision-making, but pure RL is impractical for real robotics due to sample efficiency, safety, and reward design challenges.
Policy gradient methods (especially PPO) are preferred for robotics because they handle continuous action spaces naturally and are robust to hyperparameter choices.
PPO’s clipped objective prevents catastrophically large policy updates — the same principle of “controlled updates” appears in LLM fine-tuning (RLHF).
The sample efficiency gap between RL (~millions of steps) and imitation learning (~hundreds of demonstrations) is the primary motivation for IL in robotics.
The emerging paradigm: pretrain with demonstrations (imitation), fine-tune with RL. This mirrors the LLM paradigm of pretraining + RLHF.
| Paper | Year | Key Contribution |
|---|---|---|
| Sutton & Barto, “RL: An Introduction” | 2018 | Textbook — comprehensive RL foundations |
| Williams, “Simple Statistical Gradient-Following” | 1992 | REINFORCE algorithm |
| Schulman et al., “High-Dimensional Continuous Control Using GAE” | 2016 | Generalized Advantage Estimation |
| Schulman et al., “Proximal Policy Optimization” | 2017 | PPO — the standard RL algorithm |
| Haarnoja et al., “Soft Actor-Critic” | 2018 | SAC — off-policy alternative to PPO |
| Tobin et al., “Domain Randomization for Sim-to-Real” | 2017 | Bridging the simulation gap |
| Andrychowicz et al., “Hindsight Experience Replay” | 2017 | Learning from failed episodes |
RL tries to learn optimal behavior from rewards alone — but for robotics, this requires millions of interactions and careful reward engineering. Demonstrations provide a much richer compression of expert knowledge: a single demonstration implicitly encodes the reward function, the task structure, and safe behavior patterns.
The VLA approach takes this further: by pretraining on internet-scale language and vision data, the model starts with a compressed world model before seeing a single robot demonstration. RL then serves as a fine-tuning tool, not the primary learning mechanism.
Pattern: unsupervised pretraining (compress the world) → supervised fine-tuning (compress demonstrations) → RL fine-tuning (optimize beyond human performance). This is the recipe for both LLMs and VLAs.
In Study Note 12, we’ll explore diffusion models — a powerful generative framework that turns noise into structured predictions. Diffusion policies can model multimodal action distributions (multiple valid ways to do a task), which is crucial for robot learning. Think of diffusion as iterative decompression: starting from maximum entropy (noise) and progressively adding structure until a valid action emerges.