# Reinforcement learning explained: MDPs, Q-learning, policy gradients and PPO, step by step

Reinforcement learning teaches an agent by reward instead of by answer key. This guide builds it from the ground up: Markov decision processes, Bellman updates, Q-learning, policy gradients, actor-critic and PPO, with numbers you can check and code you can run.

Supervised learning needs an answer key: every input comes with the correct output. Many problems do not have one. Nobody can write down the correct move for every chess position, the correct steering angle for every road, or the single correct reply to every prompt. What we can often do is score the outcome. Reinforcement learning (RL) is the family of methods that learns from those scores.

An RL agent acts, sees what happens, receives a number called a reward, and slowly changes its behaviour so that the total reward goes up. The same loop trains game-playing agents, robot controllers and, today, the reasoning behaviour of large language models. This article builds the ideas in order: the Markov decision process, returns and the Bellman equation, Q-learning, policy gradients, actor-critic methods and PPO. Every formula comes with a worked number, and the code runs on current library versions.

## What happened

Reinforcement learning is old, but its tooling moved this autumn. Three releases matter for anyone learning it now.

### Gymnasium 1.4.0 ships with stricter environment checks (5 October 2026)

Gymnasium is the Farama Foundation's maintained successor to OpenAI Gym and the standard interface for RL environments. Version 1.4.0 added a `max_concurrency` option to `AsyncVectorEnv`, and `check_env` now verifies that `reset` and `step` return distinct observation and info objects at each step. That check exposed buffer reuse in the `Humanoid` and `HumanoidStandup` environments, which the release fixed. The code in this article uses Gymnasium 1.4.0.

### TRL removes its PPO trainer (TRL 1.13.0, 10 September 2026)

Hugging Face's TRL library, the most used open-source toolkit for post-training language models, removed `PPOTrainer`, `PPOConfig` and its value-head model code in version 1.13.0, according to the release notes. The TRL v1.0 announcement in March 2026 had already listed the stable trainers as SFT, DPO, reward modelling, RLOO and GRPO. The current release, TRL 1.18.2 (19 November 2026), keeps that line-up. PPO is still the algorithm to understand, because GRPO and RLOO are both built from its pieces.

### PyTorch 2.15.0 (28 October 2026)

PyTorch 2.15.0 was published on PyPI on 28 October 2026. The policy-gradient example below runs on it on a CPU in under a minute.

## The setting: Markov decision processes and returns

RL problems are described as a Markov decision process (MDP). An MDP has five parts:

| Symbol | Name | FrozenLake 4x4 example |
|---|---|---|
| S | states | 16 tiles, numbered 0 to 15 |
| A | actions | 4 moves: left, down, right, up |
| P(s' given s, a) | transition probabilities | on slippery ice, the intended move happens with probability 1/3 and each perpendicular move with 1/3 |
| R | reward | +1 for reaching the goal tile, 0 otherwise |
| γ | discount factor | 0.99 in our code |

"Markov" means the next state depends only on the current state and action, not on the full history. A policy π(a given s) is the agent's rule for choosing actions. The goal is to find the policy that maximises the expected return.

The return from time t is the discounted sum of future rewards:

G_t = r_{t+1} + γ r_{t+2} + γ² r_{t+3} + ...

**Worked example.** Suppose an episode gives rewards 0, 0, 1 and γ = 0.9. Then G_0 = 0 + 0.9 × 0 + 0.9² × 1 = 0.81. The goal reward counts for less because it arrives two steps later. An everyday analogy: a euro today is worth a little more to you than a euro next year. The discount factor encodes that impatience, and it also keeps the sum finite for long tasks.

Two functions summarise how good things are under a policy π:

- The state value V^π(s) is the expected return starting from s and following π.
- The action value Q^π(s, a) is the expected return after taking action a in state s and then following π.

## The Bellman equation and Q-learning

The key insight of RL is that values are recursive. The value of where you are equals the immediate reward plus the discounted value of where you land. For the optimal action values this gives the Bellman optimality equation:

Q*(s, a) = E[ r + γ max_{a'} Q*(s', a') ]

If the transition probabilities are known, you can solve this by repeated sweeps over all states. That is value iteration, and it is dynamic programming rather than learning. RL becomes interesting when P is unknown and the agent only sees samples.

Q-learning, introduced by Chris Watkins in 1989, replaces the expectation with one observed transition (s, a, r, s'). It nudges the current estimate toward a sampled target:

Q(s, a) ← Q(s, a) + α [ r + γ max_{a'} Q(s', a') − Q(s, a) ]

The term in brackets is the temporal-difference (TD) error: the surprise between what you predicted and what one step of experience suggests.

**Worked example.** Let Q(s, a) = 0.5, the step reward r = 0, γ = 0.99, the best next value max Q(s', a') = 0.8, and the learning rate α = 0.1.

1. Target = 0 + 0.99 × 0.8 = 0.792.
2. TD error = 0.792 − 0.5 = 0.292.
3. New Q(s, a) = 0.5 + 0.1 × 0.292 = 0.5292.

The estimate moves a tenth of the way toward the target. Repeat this millions of times over many transitions and the table converges to Q*, provided every state-action pair keeps being visited and α shrinks appropriately (Sutton and Barto give the conditions).

Q-learning is off-policy: it learns about the greedy policy while behaving with a different, exploratory one. The usual exploratory rule is ε-greedy: take a random action with probability ε, otherwise take the best known action. You can watch this process on a grid in the [Q-learning gridworld simulation](/ai-simulations/q-learning-gridworld).

### Code: value iteration versus Q-learning on FrozenLake

The script below solves slippery FrozenLake twice. First with value iteration, which reads the true model from `env.unwrapped.P`. Then with Q-learning, which only sees experience. It then measures the real success rate of each greedy policy over 5,000 episodes.

```python
import numpy as np
import gymnasium as gym   # 1.4.0

env = gym.make("FrozenLake-v1", map_name="4x4", is_slippery=True)
nS, nA = env.observation_space.n, env.action_space.n
gamma = 0.99

# 1) Value iteration on the known model
P = env.unwrapped.P
V = np.zeros(nS)
for it in range(10_000):
    Q = np.array([[sum(p * (r + gamma * V[s2] * (not d)) for p, s2, r, d in P[s][a])
                   for a in range(nA)] for s in range(nS)])
    V_new = Q.max(axis=1)
    if np.max(np.abs(V_new - V)) < 1e-10:
        break
    V = V_new
pi_star = Q.argmax(axis=1)

# 2) Tabular Q-learning from experience only
rng = np.random.default_rng(0)
Qt = np.zeros((nS, nA))
alpha, eps = 0.1, 1.0
for ep in range(20_000):
    s, _ = env.reset(seed=int(rng.integers(1e9)))
    done = False
    while not done:
        a = int(rng.integers(nA)) if rng.random() < eps else int(np.argmax(Qt[s]))
        s2, r, term, trunc, _ = env.step(a)
        target = r + gamma * np.max(Qt[s2]) * (not term)
        Qt[s, a] += alpha * (target - Qt[s, a])
        s, done = s2, term or trunc
    eps = max(0.05, eps * 0.9997)

def evaluate(policy, n=5000, seed=123):
    wins = 0
    for i in range(n):
        s, _ = env.reset(seed=seed + i)
        done = False
        while not done:
            a = env.action_space.sample() if policy is None else int(policy[s])
            s, r, term, trunc, _ = env.step(a)
            done = term or trunc
        wins += r
    return wins / n

print("V*(start) =", round(V[0], 4), " Q-learning max Q(start) =", round(Qt[0].max(), 4))
print(evaluate(Qt.argmax(1)), evaluate(pi_star), evaluate(None))
```

Our run printed V*(start) = 0.542 after 570 sweeps and a Q-learning estimate of 0.5153 for the start state. The measured success rates were 73.8% for the Q-learning policy, 73.2% for the value-iteration policy and 1.8% for random actions. The two learned policies are within sampling noise of each other.

```chart
{"type": "bar", "title": "FrozenLake 4x4 (slippery): success rate over 5,000 episodes", "x": ["Random actions", "Q-learning (20,000 episodes)", "Value iteration (true model)"], "series": [{"name": "success rate", "data": [1.8, 73.8, 73.2]}], "unit": "%", "ylabel": "episodes reaching the goal", "note": "Computed by the FrozenLake script in this article (Gymnasium 1.4.0, seed 123 for evaluation)"}
```

Notice a subtle point. V*(start) is 0.542, yet the success rate is about 73%. They measure different things. V* is a discounted return, so a goal reached after 30 slippery steps counts as 0.99^29 ≈ 0.75 rather than 1. The success rate is undiscounted. Mixing these up is a common reporting mistake.

Tables stop working once the state is an image or a sentence. Deep Q-Networks (DQN) replace the table with a neural network and add a replay buffer and a slowly updated target network to keep the TD targets stable. That recipe, published by DeepMind in 2015, is what learned Atari games from pixels.

## Policy gradients: learning the policy directly

Value methods learn Q and act greedily. Policy-gradient methods skip that step and adjust a parameterised policy π_θ directly. The objective is the expected return J(θ) = E_π[G]. The policy-gradient theorem gives its gradient in a form you can estimate from samples:

∇J(θ) = E[ Σ_t ∇ log π_θ(a_t given s_t) · A_t ]

Here A_t is a weight that says how much better the action was than expected. In the simplest algorithm, REINFORCE (Williams, 1992), A_t is the return G_t, often minus a baseline to reduce variance. The intuition is plain: make actions that led to high returns more likely and actions that led to low returns less likely. It is like a coach replaying a match and saying "more of that pass, less of that tackle".

### Code: REINFORCE on CartPole with PyTorch

CartPole-v1 gives +1 per step while a pole stays balanced, up to 500 steps. A two-layer network outputs two logits, one per push direction.

```python
import numpy as np, torch, torch.nn as nn
import gymnasium as gym

torch.manual_seed(0)
env = gym.make("CartPole-v1")
policy = nn.Sequential(nn.Linear(4, 64), nn.Tanh(), nn.Linear(64, 2))
opt = torch.optim.Adam(policy.parameters(), lr=1e-2)
gamma = 0.99

def run_episode(seed):
    obs, _ = env.reset(seed=seed)
    logps, rewards, done = [], [], False
    while not done:
        dist = torch.distributions.Categorical(
            logits=policy(torch.as_tensor(obs, dtype=torch.float32)))
        a = dist.sample()
        logps.append(dist.log_prob(a))
        obs, r, term, trunc, _ = env.step(a.item())
        rewards.append(r)
        done = term or trunc
    return torch.stack(logps), rewards

lengths = []
for ep in range(500):
    logps, rewards = run_episode(seed=ep)
    G, returns = 0.0, []
    for r in reversed(rewards):                     # return-to-go
        G = r + gamma * G
        returns.append(G)
    returns = torch.tensor(returns[::-1])
    adv = (returns - returns.mean()) / (returns.std() + 1e-8)
    loss = -(logps * adv).sum()                     # gradient ascent on J
    opt.zero_grad(); loss.backward(); opt.step()
    lengths.append(len(rewards))
```

The mean episode length per block of 50 episodes rose from 60.5 to 500 within 250 episodes, then wobbled between 478 and 500.

```chart
{"type": "line", "title": "REINFORCE on CartPole-v1: mean episode length per 50 episodes", "x": ["1-50", "51-100", "101-150", "151-200", "201-250", "251-300", "301-350", "351-400", "401-450", "451-500"], "series": [{"name": "mean length (max 500)", "data": [60.5, 181.8, 451.1, 485.6, 500.0, 500.0, 498.5, 496.5, 478.3, 491.5]}], "xlabel": "episodes", "ylabel": "steps balanced", "note": "Computed by the REINFORCE script in this article (PyTorch 2.15.0, Gymnasium 1.4.0, torch seed 0)"}
```

The late dips show the main weakness of plain policy gradients. One unlucky batch can push the policy too far, and nothing pulls it back.

## Actor-critic and PPO

Actor-critic methods add a learned value function, the critic V_φ(s), to reduce the noise in A_t. Instead of using the raw return, they use the advantage: how much better the outcome was than the critic expected. The one-step version is A_t = r_t + γ V(s_{t+1}) − V(s_t), which is exactly the TD error from Q-learning, now used as a weight for the actor. Generalised Advantage Estimation (GAE) blends several step lengths with a parameter λ.

Proximal Policy Optimization (PPO), from Schulman and colleagues in 2017, adds one more safeguard. It reuses each batch of experience for several epochs but stops the policy from moving too far from the one that collected the data. Define the probability ratio ρ = π_θ(a given s) / π_old(a given s). The clipped objective is:

L = E[ min( ρ A, clip(ρ, 1 − ε, 1 + ε) A ) ]

with ε = 0.2 in the paper's main experiments. The minimum means the update never gets credit for moving the ratio outside the band [0.8, 1.2] in the helpful direction.

| Ratio ρ | Advantage A | ρ A | clipped ρ × A | Objective (min) | What happens |
|---|---|---|---|---|---|
| 1.1 | +2 | 2.2 | 2.2 | 2.2 | inside the band, normal gradient |
| 1.5 | +2 | 3.0 | 1.2 × 2 = 2.4 | 2.4 | capped, no extra push upward |
| 0.7 | +2 | 1.4 | 0.8 × 2 = 1.6 | 1.4 | unclipped term kept, gradient pushes ρ back up |
| 0.7 | −1 | −0.7 | 0.8 × −1 = −0.8 | −0.8 | capped, no extra push downward |
| 1.5 | −1 | −1.5 | 1.2 × −1 = −1.2 | −1.5 | unclipped term kept, gradient pulls ρ back down |

The table is worth reading slowly. Clipping only removes the incentive to move further in the direction that already looks good. It never blocks a correction. You can move the ratio and advantage yourself in the [PPO clipped objective simulation](/ai-simulations/ppo-clipped-objective-ratio).

| Family | Learns | Example algorithms | Strength | Weakness |
|---|---|---|---|---|
| Dynamic programming | V or Q from a known model | value iteration, policy iteration | exact, no sampling | needs P, small state spaces |
| Value-based | Q from experience | Q-learning, DQN | sample-efficient, off-policy | discrete actions, unstable with function approximation |
| Policy gradient | π directly | REINFORCE | simple, any action space | high variance |
| Actor-critic | π and V together | A2C, PPO | lower variance, stable updates | more moving parts, critic can be wrong |
| Critic-free group methods | π, baseline from a group of samples | GRPO, RLOO | no value network, cheap for LLMs | needs several samples per prompt |

## Use cases and examples

**A student validating an RL setup.** Before training anything large, run tabular Q-learning and value iteration on FrozenLake, as above. If the learned policy does not reach the 73% that value iteration reaches on the same map, the bug is in your loop (often a missing `not term` mask on the target), not in your network.

**A robotics team training a locomotion policy in simulation.** They use MuJoCo environments through Gymnasium's vector API with dozens of parallel copies, and PPO with GAE. The new `max_concurrency` option in `AsyncVectorEnv` lets them run more environments than CPU cores without oversubscribing the machine. The policy is then fine-tuned with domain randomisation before moving to hardware.

**A language-model team aligning a chat model with RLHF.** The "environment" is a prompt, the action is a whole generated reply, and the reward comes from a reward model trained on human comparisons. The InstructGPT paper (Ouyang et al., 2022) used PPO with a per-token KL penalty toward the supervised model and reported that outputs from a 1.3B-parameter model were preferred to those of the 175B GPT-3. See our [RLHF overview](/tools/rlhf) for the full pipeline.

**A reasoning-model team training on maths with verifiable rewards.** Each prompt gets a group of sampled answers, a checker gives 1 or 0, and GRPO uses the group mean as the baseline instead of a critic. TRL's `GRPOTrainer` defaults to `beta=0.0`, so it does not even load a reference model unless you ask for a KL term. Our article on [GRPO loss variants](/articles/grpo-loss-normalisation-dapo-dr-grpo) works through the normalisation choices, and the [GRPO simulation](/ai-simulations/grpo-reinforcement-learning) shows group advantages live.

**A recommendation team testing a bandit.** When each decision is independent (one ad slot, one reward), the MDP collapses to a contextual bandit with γ irrelevant. Starting there, rather than with full PPO, saves months.

## What it means in practice

RL is the right tool when you can score outcomes but cannot label correct actions, and when actions change what data you see next. It is the wrong tool when you have labels: supervised learning on the same data is cheaper and more stable, as covered in our [supervised learning guide](/articles/supervised-learning-losses-generalisation-evaluation).

For language models the shape of RL has changed. The state is the prompt plus tokens so far, the action is the next token, and the reward usually arrives only at the end. Learned critics are expensive at that scale, which is why critic-free methods such as GRPO and RLOO now dominate open tooling and why TRL could drop its PPO trainer. The ideas did not disappear: the probability ratio, the clipping band, the advantage and the KL penalty all come straight from PPO.

## What to do now

1. **Run the FrozenLake script first.** It checks your understanding of the Bellman target and the terminal mask in a setting where the right answer is known.
2. **Separate discounted value from success rate.** Report both, and say which one a chart shows.
3. **Always seed and evaluate on fresh episodes.** RL curves are noisy; compare methods over several seeds, not one run.
4. **Use a baseline in every policy-gradient method.** Even a mean-return baseline, as in our REINFORCE code, cuts variance sharply.
5. **Start PPO from known defaults.** Use ε = 0.2, a few epochs per batch and GAE, then tune one setting at a time.
6. **Log the approximate KL and the clip fraction.** If the fraction of clipped ratios climbs, your learning rate is too high.
7. **Pin your library versions.** Use Gymnasium 1.4.0 and TRL 1.18.2 or later, and expect `from trl import PPOTrainer` to fail in current TRL.
8. **Move to critic-free methods for LLMs.** For language-model post-training, start with `GRPOTrainer` or `RLOOTrainer` and a reward you can verify.

## Risks and open questions

**Reward hacking is the default, not the exception.** An agent optimises the reward you wrote, not the goal you meant. A coding agent rewarded by tests will exploit weak tests.

**Sample efficiency is still poor.** Our CartPole agent needed about 200 episodes for a task a person learns in a minute, and real robots cannot afford millions of falls.

**Instability hides behind good averages.** The late dip to 478 in our chart is small here but can be catastrophic in large runs, where one bad update can collapse a policy.

**Credit assignment over long horizons is hard.** When a single reward arrives after thousands of tokens, deciding which tokens earned it remains an open research problem.

**Watch next:** how critic-free methods handle process rewards for long reasoning chains, how Gymnasium's stricter `check_env` affects third-party environments, and whether TRL's experimental trainers bring back a PPO-style learned critic for agentic tasks. For more context, see our [reinforcement learning reference](/tools/reinforcement-learning).

## Frequently asked questions

### What is the difference between reinforcement learning and supervised learning?

Supervised learning is told the correct output for each input and minimises the error against it. Reinforcement learning only receives a score for what it did, often delayed, and must discover good actions by trying them. RL also changes its own data, because the actions it takes decide which states it sees next.

### Why does Q-learning use the maximum over next actions?

The maximum makes the target describe the best policy rather than the one currently being followed. That is why Q-learning is off-policy: it can explore randomly and still learn the value of acting greedily. The same maximum also causes overestimation when values are noisy, which Double DQN corrects.

### What does the discount factor γ actually do?

It weights future rewards less than immediate ones, so a reward k steps away counts γ^k as much. A γ near 1 makes the agent far-sighted but slows learning and increases variance. It also keeps the return finite in tasks that never end.

### Why did PPO become the standard for RLHF?

PPO allows several passes over each expensive batch of samples while the clipping keeps each update small. That combination was stable enough for the large-model runs of 2020 to 2023, including InstructGPT. Newer methods such as GRPO keep PPO's ratio and clipping but drop the value network to save memory.

### Can I still run PPO with TRL?

Not with the current stable release: TRL 1.13.0 removed `PPOTrainer` and `PPOConfig`. You can pin an older TRL version, use another library, or use `GRPOTrainer` or `RLOOTrainer`, which keep PPO's clipped ratio without a learned critic. For classic control tasks, a short PyTorch implementation like the one above is enough to learn from.

## Summary

Reinforcement learning learns from rewards instead of labels. An MDP describes the problem, the return defines the goal, and the Bellman equation turns long-term value into a one-step recursive target. Q-learning follows that target from experience and, on slippery FrozenLake, matched the 73% success of exact value iteration. Policy gradients adjust the policy directly and taught a CartPole agent to balance for the full 500 steps, but they are noisy. Actor-critic methods and PPO add a critic and a clipping band to keep updates safe. Today's LLM post-training uses the same parts, usually in critic-free form through GRPO and RLOO in TRL 1.18. For more, see the [PPO reference page](/tools/ppo).

## Sources

- [MIT Press / Sutton and Barto: Reinforcement Learning: An Introduction, 2nd edition](http://incompleteideas.net/book/the-book-2nd.html)
- [arXiv: Proximal Policy Optimization Algorithms (Schulman et al., 2017)](https://arxiv.org/abs/1707.06347)
- [arXiv: Training language models to follow instructions with human feedback (Ouyang et al., 2022)](https://arxiv.org/abs/2203.02155)
- [Gymnasium: FrozenLake environment documentation](https://gymnasium.farama.org/environments/toy_text/frozen_lake/)
- [GitHub: Gymnasium v1.4.0 release notes](https://github.com/Farama-Foundation/Gymnasium/releases/tag/v1.4.0)
- [GitHub: TRL releases (v1.13.0, PPO removed)](https://github.com/huggingface/trl/releases)
- [Hugging Face: TRL v1.0, post-training library built to move with the field](https://huggingface.co/blog/trl-v1)
- [PyPI: trl 1.18.2](https://pypi.org/project/trl/1.18.2/)
- [PyPI: torch 2.15.0](https://pypi.org/project/torch/2.15.0/)
