{
  "id": "reinforcement-learning",
  "module": "deep-learning",
  "level": 2,
  "minutes": 40,
  "audiences": [
    "researcher"
  ],
  "software": [],
  "text": {
    "en": {
      "title": "Reinforcement Learning Basics: MDPs, Q-Learning, DQN, Policy Gradients, PPO and AlphaZero",
      "description": "A systematic introduction to the reinforcement learning problem and its core algorithms: Markov decision processes, returns and the Bellman equations; value iteration, temporal-difference learning and Q-learning; experience replay and target networks in DQN; policy gradients, actor-critic, GAE, TRPO and PPO's clipped objective; continuous control and offline RL; self-play and tree search in AlphaGo, AlphaZero and MuZero; and how RLHF and GRPO connect RL to LLM post-training. Based on the original papers and official documentation, with runnable Gymnasium experiments.",
      "updated": "2026-11-14",
      "takeaways": [
        "Reinforcement learning studies how an agent improves its behaviour by interacting with an environment and receiving reward signals. The problem is usually formalised as a Markov decision process (MDP) whose goal is to maximise the discounted return Gₜ = rₜ + γrₜ₊₁ + γ²rₜ₊₂ + …; value functions satisfy the Bellman equations, the starting point of almost every algorithm.",
        "Q-learning (Watkins and Dayan, 1992) needs no model of the environment and converges to the optimal action values with probability 1 as long as every action is repeatedly sampled in every state. In this lesson's FrozenLake example, after 20,000 episodes the greedy Q-learning policy succeeds 0.737 of the time, the same as the optimal policy found by value iteration with the model known.",
        "DQN (Mnih et al., 2013, 2015) approximates the Q-function with a convolutional network and stabilises training with experience replay and a target network. Using only pixels and the score as input, it reached a level comparable to a professional human games tester across 49 Atari games, with the same algorithm, network architecture and hyperparameters for every game.",
        "Policy-gradient methods optimise the policy directly. PPO (Schulman et al., 2017) clips the probability ratio between the new and old policies to [1 − ε, 1 + ε], so the same batch of data can safely be used for several epochs; in the paper's continuous-control experiments, ε = 0.2 gives an average normalised score of 0.82, against −0.39 with neither clipping nor a penalty. In this lesson's example PPO reaches the maximum score of 500 on CartPole with all 3 seeds, while REINFORCE with the same 100,000 steps reaches only 178–291.",
        "RL also underpins LLM post-training: InstructGPT (Ouyang et al., 2022) trains a reward model from human preferences and then fine-tunes with PPO, and outputs from the 1.3B-parameter model are preferred to those of the 175B-parameter GPT-3; GRPO, proposed in DeepSeekMath, drops the value network and estimates the baseline from the scores of a group of answers to the same question."
      ],
      "faq": [
        {
          "q": "How does reinforcement learning differ from supervised learning?",
          "a": "In supervised learning every example has a correct answer and the loss tells the model directly what to output. In reinforcement learning there is only a reward signal: it says how good an outcome was but not which action the agent should have taken, and the reward may arrive many steps later (the credit-assignment problem). The data are also generated by the agent's own behaviour, so the data distribution shifts as the policy changes, and the agent must balance exploring new actions against exploiting actions known to be good."
        },
        {
          "q": "What is the difference between on-policy and off-policy methods?",
          "a": "On-policy methods update the current policy only with data generated by that policy, as in REINFORCE, A2C and PPO; most old data are discarded after an update. Off-policy methods can learn from data generated by other policies, including older ones, as in Q-learning, DQN, DDPG, TD3 and SAC. They can therefore use experience replay and are usually more sample-efficient, but stable training is harder to guarantee."
        },
        {
          "q": "Why does PPO clip the probability ratio?",
          "a": "The policy-gradient surrogate objective is only reliable when the new and old policies are close. PPO uses min(ratio × advantage, clipped ratio × advantage) as its objective: with a positive advantage the objective stops increasing once the ratio exceeds 1 + ε, and with a negative advantage it stops decreasing once the ratio falls below 1 − ε, so there is no gradient pushing the policy further away. In this lesson's example with ε = 0.2, a ratio of 1.5 with advantage +1 is clipped to 1.2, and a ratio of 0.5 with advantage −1 is clipped to −0.8. This lets the same batch be used for 10 epochs without the policy moving too far in one step."
        },
        {
          "q": "How do AlphaGo, AlphaGo Zero, AlphaZero and MuZero differ?",
          "a": "AlphaGo (2016) first trained its policy network on human expert games, then improved it by self-play reinforcement learning, combined with Monte Carlo tree search, and beat the European Go champion 5–0. AlphaGo Zero (2017) used no human data at all, learning by self-play from the rules alone, and beat the earlier AlphaGo 100–0. AlphaZero (2017) generalised the same algorithm to chess and shogi, reaching superhuman play in all three games within 24 hours. MuZero (2019) does not even need the rules: it learns a model that predicts reward, policy and value and searches with it, setting a new state of the art on 57 Atari games."
        },
        {
          "q": "Do I need reinforcement learning to study LLMs?",
          "a": "To understand RLHF, DPO and how reasoning models are trained, the basic concepts of RL are necessary: policies, rewards, advantages, KL constraints and PPO's clipped objective all appear directly in these methods. Application developers can skip it for now; anyone working on post-training or alignment should learn this lesson first and then move on to the alignment and reasoning-model lessons."
        }
      ],
      "sources": [
        {
          "title": "Sutton, Barto (2018), Reinforcement Learning: An Introduction (2nd edition, free full text from the authors)",
          "url": "http://incompleteideas.net/book/the-book-2nd.html"
        },
        {
          "title": "Sutton (1988), Learning to Predict by the Methods of Temporal Differences, Machine Learning",
          "url": "https://link.springer.com/article/10.1007/BF00115009"
        },
        {
          "title": "Watkins, Dayan (1992), Q-learning, Machine Learning",
          "url": "https://link.springer.com/article/10.1007/BF00992698"
        },
        {
          "title": "Williams (1992), Simple Statistical Gradient-Following Algorithms for Connectionist Reinforcement Learning, Machine Learning",
          "url": "https://link.springer.com/article/10.1007/BF00992696"
        },
        {
          "title": "Mnih et al. (2013), Playing Atari with Deep Reinforcement Learning",
          "url": "https://arxiv.org/abs/1312.5602"
        },
        {
          "title": "Mnih et al. (2015), Human-level Control through Deep Reinforcement Learning, Nature",
          "url": "https://www.nature.com/articles/nature14236"
        },
        {
          "title": "van Hasselt, Guez, Silver (2015), Deep Reinforcement Learning with Double Q-learning",
          "url": "https://arxiv.org/abs/1509.06461"
        },
        {
          "title": "Schaul et al. (2015), Prioritized Experience Replay",
          "url": "https://arxiv.org/abs/1511.05952"
        },
        {
          "title": "Mnih et al. (2016), Asynchronous Methods for Deep Reinforcement Learning",
          "url": "https://arxiv.org/abs/1602.01783"
        },
        {
          "title": "Schulman et al. (2015), Trust Region Policy Optimization",
          "url": "https://arxiv.org/abs/1502.05477"
        },
        {
          "title": "Schulman et al. (2015), High-Dimensional Continuous Control Using Generalized Advantage Estimation",
          "url": "https://arxiv.org/abs/1506.02438"
        },
        {
          "title": "Schulman et al. (2017), Proximal Policy Optimization Algorithms",
          "url": "https://arxiv.org/abs/1707.06347"
        },
        {
          "title": "Lillicrap et al. (2015), Continuous Control with Deep Reinforcement Learning",
          "url": "https://arxiv.org/abs/1509.02971"
        },
        {
          "title": "Fujimoto, van Hoof, Meger (2018), Addressing Function Approximation Error in Actor-Critic Methods",
          "url": "https://arxiv.org/abs/1802.09477"
        },
        {
          "title": "Haarnoja et al. (2018), Soft Actor-Critic: Off-Policy Maximum Entropy Deep Reinforcement Learning with a Stochastic Actor",
          "url": "https://arxiv.org/abs/1801.01290"
        },
        {
          "title": "Kumar et al. (2020), Conservative Q-Learning for Offline Reinforcement Learning",
          "url": "https://arxiv.org/abs/2006.04779"
        },
        {
          "title": "Chen et al. (2021), Decision Transformer: Reinforcement Learning via Sequence Modeling",
          "url": "https://arxiv.org/abs/2106.01345"
        },
        {
          "title": "Silver et al. (2016), Mastering the Game of Go with Deep Neural Networks and Tree Search, Nature",
          "url": "https://www.nature.com/articles/nature16961"
        },
        {
          "title": "Silver et al. (2017), Mastering the Game of Go without Human Knowledge, Nature",
          "url": "https://www.nature.com/articles/nature24270"
        },
        {
          "title": "Silver et al. (2017), Mastering Chess and Shogi by Self-Play with a General Reinforcement Learning Algorithm",
          "url": "https://arxiv.org/abs/1712.01815"
        },
        {
          "title": "Schrittwieser et al. (2019), Mastering Atari, Go, Chess and Shogi by Planning with a Learned Model",
          "url": "https://arxiv.org/abs/1911.08265"
        },
        {
          "title": "Ouyang et al. (2022), Training Language Models to Follow Instructions with Human Feedback",
          "url": "https://arxiv.org/abs/2203.02155"
        },
        {
          "title": "Shao et al. (2024), DeepSeekMath: Pushing the Limits of Mathematical Reasoning in Open Language Models",
          "url": "https://arxiv.org/abs/2402.03300"
        },
        {
          "title": "OpenAI Spinning Up: Part 1: Key Concepts in RL",
          "url": "https://spinningup.openai.com/en/latest/spinningup/rl_intro.html"
        },
        {
          "title": "OpenAI Spinning Up: Part 3: Intro to Policy Optimization",
          "url": "https://spinningup.openai.com/en/latest/spinningup/rl_intro3.html"
        },
        {
          "title": "OpenAI Spinning Up: Proximal Policy Optimization",
          "url": "https://spinningup.openai.com/en/latest/algorithms/ppo.html"
        },
        {
          "title": "Gymnasium documentation: Frozen Lake",
          "url": "https://gymnasium.farama.org/environments/toy_text/frozen_lake/"
        },
        {
          "title": "Gymnasium documentation: Cart Pole",
          "url": "https://gymnasium.farama.org/environments/classic_control/cart_pole/"
        },
        {
          "title": "CleanRL documentation: Proximal Policy Gradient (PPO)",
          "url": "https://docs.cleanrl.dev/rl-algorithms/ppo/"
        },
        {
          "title": "Huang et al. (2022), The 37 Implementation Details of Proximal Policy Optimization, ICLR Blog Track",
          "url": "https://iclr-blog-track.github.io/2022/03/25/ppo-implementation-details/"
        },
        {
          "title": "PyTorch tutorial: Reinforcement Learning (DQN) Tutorial",
          "url": "https://docs.pytorch.org/tutorials/intermediate/reinforcement_q_learning.html"
        },
        {
          "title": "Hugging Face Deep Reinforcement Learning Course",
          "url": "https://huggingface.co/learn/deep-rl-course/unit0/introduction"
        },
        {
          "title": "Lilian Weng: Policy Gradient Algorithms",
          "url": "https://lilianweng.github.io/posts/2018-04-08-policy-gradient/"
        }
      ],
      "url": "https://aimap.page/en/learn/deep-learning/reinforcement-learning/",
      "markdown": "**Overview**: reinforcement learning (RL) studies how an agent gradually improves its behaviour through interaction with an environment, guided by reward signals. It differs from supervised learning in two ways: there are no correct answers, only after-the-fact judgements of how good an outcome was, and the data are produced by the agent's own decisions. This lesson first sets out the basic concepts of Markov decision processes, returns, value functions and the Bellman equations, then follows two lines of core algorithms: value-based methods (value iteration, temporal-difference learning, Q-learning, DQN) and policy-based methods (REINFORCE, actor-critic, TRPO, PPO). It then covers continuous control, offline RL, and self-play and tree search in the AlphaGo family, and finally explains how RL connects to LLM post-training (RLHF, GRPO). All experimental figures come from the runnable example at the end.\n\nThis lesson belongs to the [Reinforcement Learning Basics](/learn/unit/u33-rl-basics) unit. Its prerequisites are [Probability and Information Theory](/learn/probability-information) (expectations, conditional probability) and [Training Deep Networks](/learn/training-deep-nets) (optimisers and gradient clipping). It leads on to RLHF in [How LLMs Learn](/learn/how-llms-learn) and to [Reasoning Models](/learn/reasoning-models). Related algorithm cards: [Q-learning](/learn/algorithms/q-learning), [DQN](/learn/algorithms/dqn), [policy gradient](/learn/algorithms/policy-gradient), [actor-critic and A3C](/learn/algorithms/a3c), [TRPO](/learn/algorithms/trpo), [PPO](/learn/algorithms/ppo), [DDPG/TD3](/learn/algorithms/ddpg-td3), [SAC](/learn/algorithms/sac), [CQL](/learn/algorithms/cql), [Decision Transformer](/learn/algorithms/decision-transformer), [AlphaGo/AlphaZero](/learn/algorithms/mcts-alphazero), [MuZero](/learn/algorithms/muzero), [RLHF](/learn/algorithms/rlhf) and [GRPO](/learn/algorithms/grpo).\n\n## The problem: agents, environments and Markov decision processes\n\nAt each time step t the agent observes a state sₜ and chooses an action aₜ according to its policy π; the environment returns a reward rₜ and moves to the next state sₜ₊₁. This interaction is usually formalised as a Markov decision process (MDP) with five elements:\n\n| Element | Meaning | FrozenLake example |\n|---|---|---|\n| State set S | Situations the environment can be in | The 16 cells of a 4×4 frozen lake |\n| Action set A | Actions available to the agent | Up, down, left, right |\n| Transition probabilities P(s′ \\| s, a) | Probability of reaching each state after an action | Slippery ice: the agent moves in the intended direction with probability 1/3 and in each perpendicular direction with probability 1/3 |\n| Reward function R | Scalar feedback at each step | 1 for reaching the goal, 0 otherwise |\n| Discount factor γ | Weight of future rewards, 0 ≤ γ ≤ 1 | 0.99 |\n\n“Markov” means the next state depends only on the current state and action, not on earlier history. A policy π(a | s) gives the probability of each action in each state; a deterministic policy gives a single action.\n\n## Returns, value functions and the Bellman equations\n\nThe agent's goal is to maximise the **return**, the discounted sum of rewards from the current time onwards:\n\n> Gₜ = rₜ + γ·rₜ₊₁ + γ²·rₜ₊₂ + … = rₜ + γ·Gₜ₊₁\n\nWith γ < 1 distant rewards count for less, and the return of an infinitely long sequence stays bounded. In the example, with rewards (0, 0, 0, 1) and γ = 0.9, the returns at successive times are 0.729, 0.81, 0.9 and 1.0: the earlier the time, the further from the reward and the smaller the return.\n\nThe **state value** Vπ(s) is the expected return starting from state s and following policy π; the **action value** Qπ(s, a) is the expected return after first taking action a in s and then following π; their difference Aπ(s, a) = Qπ(s, a) − Vπ(s) is the **advantage**, how much better action a is than the average in that state. The recursive form of the return gives the **Bellman equation**:\n\n> Vπ(s) = Σₐ π(a | s) · Σₛ′ P(s′ | s, a) · [ R(s, a, s′) + γ·Vπ(s′) ]\n\nThe optimal value function satisfies the **Bellman optimality equation**, which replaces the average over the policy with a maximum:\n\n> Q*(s, a) = Σₛ′ P(s′ | s, a) · [ R(s, a, s′) + γ·maxₐ′ Q*(s′, a′) ]\n\nOnce Q* is known, choosing the action with the largest Q* in each state is an optimal policy. The algorithms below can all be seen as different ways of solving or approximating these two equations (Sutton and Barto, 2018, Chapters 3–4).\n\n## Known model: dynamic programming and value iteration\n\nIf the transition probabilities and reward function are known, the problem can be solved directly by dynamic programming. **Value iteration** repeatedly applies the Bellman optimality equation to every state until the values stop changing. The example runs value iteration on Gymnasium's slippery 4×4 FrozenLake: it converges after 438 sweeps (largest change below 10⁻⁸), with an optimal start-state value of 0.542; running the resulting policy for 10,000 episodes reaches the goal 0.737 of the time. Because the ice is slippery, even the optimal policy cannot guarantee success.\n\nIn real problems the environment model is usually unknown (game internals, robot dynamics) or there are too many states to enumerate. This calls for model-free methods that learn from interaction data, and for neural networks that approximate value functions or policies.\n\n## Model-free learning: temporal differences and Q-learning\n\nWithout the transition probabilities, values can be estimated from experienced samples. **Monte Carlo methods** wait until an episode ends and use the actual return Gₜ as the target; **temporal-difference (TD) learning** (Sutton, 1988) looks only one step ahead and uses rₜ + γ·V(sₜ₊₁) as the target, updating an estimate from an estimate (bootstrapping) without waiting for the episode to end. The two trade off bias against variance: the Monte Carlo target is unbiased but has high variance, while the TD target has lower variance but depends on how accurate the current estimate is.\n\n**Q-learning** (Watkins, 1989; Watkins and Dayan, 1992) applies the TD idea to the Bellman optimality equation. After each transition (s, a, r, s′) it makes one update:\n\n> Q(s, a) ← Q(s, a) + α · [ r + γ·maxₐ′ Q(s′, a′) − Q(s, a) ]\n\nThe bracketed term is the TD error and α is the learning rate. Watkins and Dayan proved that Q-learning converges to the optimal action values with probability 1 as long as every action is repeatedly sampled in every state and the action values are represented discretely in a table. To ensure exploration, an **ε-greedy** policy is common: with probability ε choose a random action, otherwise the action with the largest current Q-value, and decay ε during training. Because the update uses maxₐ′ Q(s′, a′) regardless of the exploratory action actually taken next, Q-learning is an **off-policy** method; using the Q-value of the next action actually taken gives the on-policy SARSA (Sutton and Barto, 2018, Chapter 6).\n\nThe example trains tabular Q-learning on the same FrozenLake for 20,000 episodes (α = 0.1, ε decaying exponentially from 1 to 0.05), without access to the transition probabilities. After training the largest Q-value at the start state is 0.504 (the exact value from value iteration is 0.542), and the greedy policy also succeeds 0.737 of the time; in 10 of the 11 non-terminal states it chooses the same action as value iteration.\n\n## Deep Q-networks (DQN)\n\nWhen the state space is large, as with game screens, a table per state is impossible and a neural network Q(s, a; θ) must approximate the action values. Naively combining Q-learning with a neural network is often unstable. The DQN of Mnih et al. (2013) reads raw pixels with a convolutional network that outputs a Q-value per action, and introduces two key techniques:\n\n1. **Experience replay**: transitions (s, a, r, s′) are stored in a replay buffer (the most recent 1 million frames in the paper) and training samples random minibatches from it, breaking the correlation between consecutive samples and letting each experience be used many times;\n2. **Target network**: the 2015 Nature version computes r + γ·maxₐ′ Q(s′, a′; θ⁻) with a target network whose parameters are copied periodically from the online network, so the target does not move with every update (described in van Hasselt et al., 2015).\n\nThe 2013 paper tested 7 Atari games, outperforming all previous approaches on 6 and a human expert on 3; ε was annealed linearly from 1 to 0.1 over the first million frames, and in most games the agent chose an action every 4 frames. The 2015 Nature paper extended the evaluation to 49 games using only pixels and the score as input, with the same algorithm, network architecture and hyperparameters for every game, reaching a level comparable to a professional human games tester.\n\nMany refinements followed. Double DQN (van Hasselt et al., 2015) showed that the max in Q-learning systematically overestimates action values and instead selects the action with the online network while evaluating it with the target network, reducing overestimation and improving scores. Prioritized experience replay (Schaul et al., 2015) samples transitions in proportion to their TD error and beats uniform-replay DQN on 41 of 49 games.\n\n## Policy gradients and actor-critic\n\nValue-based methods learn Q first and derive a policy from it, which makes continuous actions awkward. **Policy-gradient** methods parameterise the policy directly as πθ(a | s) and move the parameters along the gradient of the expected return J(θ). The log-derivative trick gives:\n\n> ∇J(θ) = E[ Σₜ ∇log πθ(aₜ | sₜ) · Gₜ ]\n\nIntuitively: raise the probability of actions that appear in high-return trajectories and lower it for low-return ones. This is the **REINFORCE** algorithm (Williams, 1992). Its weakness is high variance. Subtracting a **baseline** b(sₜ) that depends only on the state (usually a learned V(sₜ)) from Gₜ leaves the expected gradient unchanged but reduces its variance substantially; Gₜ − V(sₜ) is then an estimate of the advantage (Spinning Up, Part 3).\n\nMethods that learn a policy (the actor) and a value function (the critic) together are called **actor-critic** methods. Mnih et al. (2016) proposed A3C, in which several parallel actor-learners update shared parameters asynchronously; the paper reports that parallelism stabilises training, and its best variant surpassed the state of the art on Atari while training for half the time on a single multi-core CPU. **Generalized advantage estimation (GAE)** (Schulman et al., 2015) weights multi-step TD errors exponentially with a parameter λ, trading bias against variance continuously: λ = 0 is one-step TD and λ = 1 is the Monte Carlo return.\n\n## TRPO and PPO\n\nA central difficulty in policy gradients is the step size: an update that goes too far can make the policy collapse suddenly, and because the policy generates its own data, recovery is hard. **TRPO** (Schulman et al., 2015) starts from a procedure with guaranteed monotonic improvement and constrains the KL divergence between the old and new policies to a small region (the trust region) at each update. In experiments it improves steadily with little hyperparameter tuning, but each update approximately solves a constrained optimisation problem with the conjugate gradient method, which makes it complex to implement.\n\n**PPO** (Schulman et al., 2017) approximates the same goal with first-order methods. Writing the probability ratio of an action under the new and old policies as ratio = πθ(a | s) / πθ_old(a | s), PPO maximises the clipped surrogate objective:\n\n> L = E[ min( ratio · Â, clip(ratio, 1 − ε, 1 + ε) · Â ) ]\n\nwhere Â is an advantage estimate (usually from GAE) and ε is typically 0.2. Taking the minimum makes the objective a lower bound on the unclipped one: when an update would push the ratio outside [1 − ε, 1 + ε] in the direction that looks better, the objective stops increasing and there is no gradient pushing further. The example computes the clipped objective with ε = 0.2: with advantage +1, ratios 0.5, 0.8, 1.0, 1.2 and 1.5 give 0.5, 0.8, 1.0, 1.2 and 1.2; with advantage −1 they give −0.8, −0.8, −1.0, −1.2 and −1.5.\n\nThis constraint lets PPO run several epochs of minibatch updates on the same batch. The paper compares surrogate objectives on 7 MuJoCo continuous-control tasks (3 random seeds per setting, 21 runs in total): with neither clipping nor a penalty the average normalised score is −0.39; with ε = 0.1, 0.2 and 0.3 it is 0.76, 0.82 and 0.70; the best adaptive KL penalty scores 0.74 and the best fixed KL penalty 0.72, so clipping with ε = 0.2 scores highest.\n\nThe example compares REINFORCE (with a value baseline, one update per batch of 2,048 steps) and PPO (also 2,048 steps per batch, GAE λ = 0.95, 10 epochs per batch with minibatches of 64) on Gymnasium's CartPole-v1, with identical networks, 100,000 training steps and 3 random seeds each. CartPole gives 1 point for every step the pole stays up, and an episode lasts at most 500 steps. The results:\n\n| Algorithm | Mean return of last 20 episodes (seeds 0 / 1 / 2) | Step at which the 20-episode mean first reaches 475 |\n|---|---|---|\n| REINFORCE (with baseline) | 178.0 / 290.8 / 204.6 | Not reached within 100,000 steps |\n| PPO (ε = 0.2) | 500.0 / 500.0 / 500.0 | 46,296 / 45,191 / 35,285 |\n\nPPO is far more sample-efficient, mainly because each batch is safely reused for several epochs. Practical implementations involve many further details that affect results, such as advantage normalisation, gradient clipping, learning-rate annealing and value-function clipping; see the ICLR blog post “The 37 Implementation Details of PPO” and CleanRL's single-file implementation.\n\n## Continuous control and offline RL\n\nIn tasks such as robotics the actions are continuous, so a maximum over all actions is not available. **DDPG** (Lillicrap et al., 2015) combines DQN's experience replay and target networks with the deterministic policy gradient, and solves more than 20 simulated physics tasks with the same algorithm, network architecture and hyperparameters. **TD3** (Fujimoto et al., 2018) shows that value overestimation also occurs in actor-critic methods and mitigates it by taking the minimum of two critics and delaying policy updates. **SAC** (Haarnoja et al., 2018) belongs to the maximum-entropy RL framework: the policy maximises its own entropy as well as the return, which encourages exploration and improves stability.\n\n**Offline RL** trains only on a fixed historical dataset without further interaction, which suits settings where interaction is expensive or risky. The main difficulty is that the distribution shift between the dataset and the learned policy leads to overestimated values. **CQL** (Kumar et al., 2020) adds a regulariser to the Bellman error so that it learns a conservative Q-function whose estimate of the policy's value is a lower bound on the true value. **Decision Transformer** (Chen et al., 2021) takes a completely different approach and casts RL as conditional sequence modelling: conditioned on the desired return, past states and actions, a causal Transformer generates actions autoregressively, matching or exceeding state-of-the-art model-free offline RL baselines on Atari, OpenAI Gym and Key-to-Door tasks.\n\n## Planning and self-play: AlphaGo, AlphaZero and MuZero\n\nThe rules of board games are fully known, so learning can be combined with search. **AlphaGo** (Silver et al., 2016) uses a policy network to choose moves and a value network to evaluate positions; both are first trained by supervised learning on human expert games, then by self-play reinforcement learning, and combined with Monte Carlo tree search (MCTS). AlphaGo won 99.8% of its games against other Go programs and beat the European Go champion 5–0, the first time a computer program defeated a human professional on a full-sized board.\n\n**AlphaGo Zero** (Silver et al., 2017) uses no human data at all: a neural network learns to predict MCTS's own move choices and the winners of its games, a stronger network makes the search stronger and the self-play data better, and the cycle repeats. Starting from random play, AlphaGo Zero beat the champion-defeating AlphaGo 100–0. **AlphaZero** (Silver et al., 2017) generalises the same algorithm to chess and shogi with no domain knowledge beyond the rules, reaching superhuman play in all three games within 24 hours and convincingly defeating a world-champion program in each. **MuZero** (Schrittwieser et al., 2019) removes the need for the rules: it learns a model that predicts only the quantities most relevant to planning (reward, policy and value) and searches with that model, setting a new state of the art on 57 Atari games while matching AlphaZero's superhuman performance in Go, chess and shogi.\n\n## Connection to LLMs: RLHF and reasoning models\n\nIf a language model is treated as a policy and each generated token as an action, RL can optimise properties that are hard to express as supervised targets. **InstructGPT** (Ouyang et al., 2022) first fine-tunes on human demonstrations, then trains a reward model from human rankings of several answers, and finally optimises the policy with PPO, using a KL penalty to keep it from drifting too far from the supervised model. On its prompt distribution, outputs from the 1.3B-parameter InstructGPT were preferred to those of the 175B-parameter GPT-3. **GRPO**, proposed in DeepSeekMath (Shao et al., 2024), drops PPO's value network (the critic), samples a group of answers to the same question and uses the group's scores as the baseline for the advantage, substantially reducing training resources. The full RLHF pipeline is covered in [How LLMs Learn](/learn/how-llms-learn), and the use of GRPO in reasoning models such as DeepSeek-R1, together with RL from verifiable rewards, in [Reasoning Models](/learn/reasoning-models).\n\n## Runnable example\n\nThe code below was run with PyTorch 2.15 (CPU) and Gymnasium 1.4 with OMP_NUM_THREADS=3, and its output matches the figures above. The whole script takes about 3 minutes, mostly in the CartPole part. With a different thread count the order of floating-point accumulation changes, so training figures may differ slightly.\n\n```python\nimport numpy as np, torch, torch.nn as nn, gymnasium as gym, time\ntorch.manual_seed(0); np.random.seed(0); torch.set_num_threads(3)\n\n# 1) Discounted return\nr=[0,0,0,1]; g=0.9\nG=[sum(g**k*r[t+k] for k in range(len(r)-t)) for t in range(len(r))]\nprint('Discounted returns G_t:', [round(x,3) for x in G])\n\n# 2) FrozenLake 4x4 (slippery): value iteration\nenv=gym.make('FrozenLake-v1', is_slippery=True); P=env.unwrapped.P; nS,nA=16,4; gamma=0.99\nV=np.zeros(nS); it=0\nwhile True:\n    it+=1\n    Q=np.array([[sum(p*(rw+gamma*V[s2]*(not d)) for p,s2,rw,d in P[s][a]) for a in range(nA)] for s in range(nS)])\n    V2=Q.max(1)\n    if np.abs(V2-V).max()<1e-8: V=V2; break\n    V=V2\npi_vi=Q.argmax(1)\nprint(f'Value iteration converged in {it} sweeps, start-state value V(s0) = {V[0]:.3f}')\ndef evaluate(pi,n=10000,seed=1):\n    e=gym.make('FrozenLake-v1', is_slippery=True); w=0\n    for i in range(n):\n        s,_=e.reset(seed=seed+i); done=False\n        while not done:\n            s,rw,term,trunc,_=e.step(int(pi[s])); done=term or trunc\n        w+=rw\n    return w/n\nprint(f'Value-iteration policy success rate {evaluate(pi_vi):.3f}')\n\n# 3) Tabular Q-learning (epsilon-greedy, model-free)\nQt=np.zeros((nS,nA)); alpha=0.1; rng=np.random.default_rng(0); eps=1.0\ne=gym.make('FrozenLake-v1', is_slippery=True)\nfor ep in range(20000):\n    s,_=e.reset(seed=int(rng.integers(1e9))); done=False\n    while not done:\n        a=int(rng.integers(nA)) if rng.random()<eps else int(rng.choice(np.flatnonzero(Qt[s]==Qt[s].max())))\n        s2,rw,term,trunc,_=e.step(a); done=term or trunc\n        target=rw+(0 if term else gamma*Qt[s2].max())\n        Qt[s,a]+=alpha*(target-Qt[s,a]); s=s2\n    eps=max(0.05, eps*0.9997)\nprint(f'Q-learning after 20000 episodes: max Q(s0) {Qt[0].max():.3f}, greedy-policy success rate {evaluate(Qt.argmax(1)):.3f}, states matching the value-iteration policy {(Qt.argmax(1)==pi_vi)[[0,1,2,3,4,6,8,9,10,13,14]].sum()}/11')\n\n# 4) PPO clipped objective for positive and negative advantages\neps_c=0.2\nfor A in (1.0,-1.0):\n    vals=[]\n    for ratio in (0.5,0.8,1.0,1.2,1.5):\n        vals.append(round(min(ratio*A, float(np.clip(ratio,1-eps_c,1+eps_c))*A),2))\n    print(f'A={A:+.0f}: clipped objective at ratio=0.5/0.8/1.0/1.2/1.5', vals)\n\n# 5) CartPole: REINFORCE (with baseline) vs PPO, 100k steps each\ndef mlp(o): return nn.Sequential(nn.Linear(4,64),nn.Tanh(),nn.Linear(64,64),nn.Tanh(),nn.Linear(64,o))\ndef run(algo, steps=100_000, seed=0):\n    torch.manual_seed(seed); env=gym.make('CartPole-v1'); pi=mlp(2); vf=mlp(1)\n    opt=torch.optim.Adam(list(pi.parameters())+list(vf.parameters()), lr=3e-4 if algo=='ppo' else 1e-3)\n    obs,_=env.reset(seed=seed); t=0; ep_ret=0; rets=[]; first475=None\n    while t<steps:\n        O,A,R,D,LP=[],[],[],[],[]\n        for _ in range(2048):\n            o=torch.tensor(obs,dtype=torch.float32)\n            with torch.no_grad(): dist=torch.distributions.Categorical(logits=pi(o))\n            a=dist.sample(); obs,rw,term,trunc,_=env.step(int(a)); t+=1; ep_ret+=rw\n            O.append(o);A.append(a);R.append(rw);D.append(term);LP.append(dist.log_prob(a))\n            if term or trunc:\n                rets.append(ep_ret); ep_ret=0; obs,_=env.reset()\n                if first475 is None and len(rets)>=20 and np.mean(rets[-20:])>=475: first475=t\n                D[-1]=True if (term or trunc) else D[-1]\n        O=torch.stack(O);A=torch.stack(A);LP=torch.stack(LP);R=torch.tensor(R);Dn=torch.tensor(D,dtype=torch.float32)\n        with torch.no_grad():\n            V=vf(O).squeeze(-1); nv=vf(torch.tensor(obs,dtype=torch.float32)).squeeze()\n        # GAE(lambda=0.95); REINFORCE uses Monte Carlo returns (lambda=1)\n        lam=0.95 if algo=='ppo' else 1.0; adv=torch.zeros(len(R)); last=0\n        for i in reversed(range(len(R))):\n            nxt=nv if i==len(R)-1 else V[i+1]\n            delta=R[i]+0.99*nxt*(1-Dn[i])-V[i]; last=delta+0.99*lam*(1-Dn[i])*last; adv[i]=last\n        ret=adv+V\n        if algo=='ppo':\n            for _ in range(10):\n                for idx in torch.randperm(len(R)).split(64):\n                    a_=(adv[idx]-adv[idx].mean())/(adv[idx].std()+1e-8)\n                    nlp=torch.distributions.Categorical(logits=pi(O[idx])).log_prob(A[idx])\n                    ratio=(nlp-LP[idx]).exp()\n                    l=-torch.min(ratio*a_, ratio.clamp(0.8,1.2)*a_).mean()+0.5*((vf(O[idx]).squeeze(-1)-ret[idx])**2).mean()\n                    opt.zero_grad(); l.backward(); nn.utils.clip_grad_norm_(list(pi.parameters())+list(vf.parameters()),0.5); opt.step()\n        else:\n            a_=(adv-adv.mean())/(adv.std()+1e-8)\n            nlp=torch.distributions.Categorical(logits=pi(O)).log_prob(A)\n            l=-(nlp*a_).mean()+0.5*((vf(O).squeeze(-1)-ret)**2).mean()\n            opt.zero_grad(); l.backward(); opt.step()\n    return np.mean(rets[-20:]), first475\nfor algo in ('reinforce','ppo'):\n    res=[]\n    for seed in (0,1,2):\n        t0=time.time(); m,f=run(algo,seed=seed); res.append((round(m,1),f))\n    print(f'{algo}: mean return of last 20 episodes and first step reaching 475, 3 seeds', [(float(a),b) for a,b in res])\n```\n\nOutput:\n\n```text\nDiscounted returns G_t: [0.729, 0.81, 0.9, 1.0]\nValue iteration converged in 438 sweeps, start-state value V(s0) = 0.542\nValue-iteration policy success rate 0.737\nQ-learning after 20000 episodes: max Q(s0) 0.504, greedy-policy success rate 0.737, states matching the value-iteration policy 10/11\nA=+1: clipped objective at ratio=0.5/0.8/1.0/1.2/1.5 [0.5, 0.8, 1.0, 1.2, 1.2]\nA=-1: clipped objective at ratio=0.5/0.8/1.0/1.2/1.5 [-0.8, -0.8, -1.0, -1.2, -1.5]\nreinforce: mean return of last 20 episodes and first step reaching 475, 3 seeds [(178.0, None), (290.8, None), (204.6, None)]\nppo: mean return of last 20 episodes and first step reaching 475, 3 seeds [(500.0, 46296), (500.0, 45191), (500.0, 35285)]\n```\n\n## Exercises\n\n1. **Unit project**: on [Gymnasium](https://gymnasium.farama.org/)'s CartPole, implement in turn tabular Q-learning with a discretised state (binning the continuous state), DQN (following the [PyTorch DQN tutorial](https://docs.pytorch.org/tutorials/intermediate/reinforcement_q_learning.html)) and PPO, record the number of environment steps each needs to reach a mean return of 475, and compare sample efficiency.\n2. Make the example's FrozenLake non-slippery (`is_slippery=False`), rerun value iteration and Q-learning, and explain why the optimal success rate becomes 1; then set γ to 0.9 and 0.5 and observe how the start-state value and the policy change.\n3. In the example's PPO, set the clipping coefficient to 0.1, 0.3 and effectively no clipping (a very large ε), run 3 seeds for each, and compare with the trends in Table 1 of the PPO paper.\n4. Read [CleanRL's PPO implementation](https://docs.cleanrl.dev/rl-algorithms/ppo/) and, using [“The 37 Implementation Details of PPO”](https://iclr-blog-track.github.io/2022/03/25/ppo-implementation-details/), list the details missing from the example code; add two of them and compare the learning curves.\n\n## Suggested reading order\n\nStart with Chapters 3, 4 and 6 of Sutton and Barto's [Reinforcement Learning: An Introduction](http://incompleteideas.net/book/the-book-2nd.html) (MDPs, dynamic programming, temporal differences), then read [Part 1](https://spinningup.openai.com/en/latest/spinningup/rl_intro.html) and [Part 3](https://spinningup.openai.com/en/latest/spinningup/rl_intro3.html) of Spinning Up for the derivation of policy gradients. For deep RL, read the original papers in the order DQN (2013), Double DQN, A3C, TRPO, GAE, PPO, and practise with the [Hugging Face Deep RL Course](https://huggingface.co/learn/deep-rl-course/unit0/introduction). For a full course, choose [UC Berkeley CS285](https://rail.eecs.berkeley.edu/deeprlcourse/) or [David Silver's RL course](https://davidstarsilver.wordpress.com/teaching/); for a survey, read [Lilian Weng's Policy Gradient Algorithms](https://lilianweng.github.io/posts/2018-04-08-policy-gradient/). Then move on to RLHF in [How LLMs Learn](/learn/how-llms-learn) and to [Reasoning Models](/learn/reasoning-models)."
    },
    "zh-hans": {
      "title": "强化学习基础：马尔可夫决策过程、Q 学习、DQN、策略梯度、PPO 与 AlphaZero",
      "description": "系统介绍强化学习的问题设定与核心算法：马尔可夫决策过程、回报与贝尔曼方程，价值迭代、时序差分与 Q 学习，深度 Q 网络（DQN）的经验回放与目标网络，策略梯度、Actor-Critic、GAE、TRPO 与 PPO 的裁剪目标，连续控制与离线强化学习，AlphaGo、AlphaZero 与 MuZero 的自我对弈和树搜索，以及 RLHF、GRPO 与大模型后训练的关系。依据原始论文与官方文档，附 Gymnasium 上可运行的实验。",
      "updated": "2026-11-14",
      "takeaways": [
        "强化学习研究智能体如何通过与环境交互、根据奖励信号改进行为。问题通常形式化为马尔可夫决策过程（MDP），目标是最大化折扣回报 Gₜ = rₜ + γrₜ₊₁ + γ²rₜ₊₂ + …；价值函数满足贝尔曼方程，这是几乎所有算法的出发点。",
        "Q 学习（Watkins 与 Dayan，1992）不需要环境模型，只要所有状态下的所有动作都被反复采样，就以概率 1 收敛到最优动作价值。本课示例在 FrozenLake 上训练 20000 回合后，Q 学习的贪心策略成功率为 0.737，与已知模型时用价值迭代求出的最优策略相同。",
        "DQN（Mnih 等，2013、2015）用卷积网络近似 Q 函数，借助经验回放和目标网络稳定训练，只用像素和得分作为输入，在 49 款 Atari 游戏上达到与专业人类测试员相当的水平，且所有游戏使用同一套算法、网络结构和超参数。",
        "策略梯度方法直接优化策略。PPO（Schulman 等，2017）把新旧策略的概率比裁剪在 [1 − ε, 1 + ε] 内，使同一批数据可以安全地训练多轮；论文的连续控制实验中，ε = 0.2 的平均归一化得分为 0.82，不裁剪也不加惩罚时为 −0.39。本课示例中 PPO 在 CartPole 上 3 个种子均达到满分 500，而同样 10 万步的 REINFORCE 只有 178–291。",
        "强化学习也是大模型后训练的基础：InstructGPT（Ouyang 等，2022）用人类偏好训练奖励模型，再用 PPO 微调，13 亿参数的模型输出比 1750 亿参数的 GPT-3 更受人类偏好；DeepSeekMath 提出的 GRPO 去掉价值网络，用同一问题多个回答的组内得分估计基线。"
      ],
      "faq": [
        {
          "q": "强化学习与监督学习有什么不同？",
          "a": "监督学习的每个样本都有正确答案，损失直接告诉模型应该输出什么；强化学习只有奖励信号，它说明结果好坏，却不告诉智能体应该采取哪个动作，而且奖励可能在很多步之后才出现（信用分配问题）。此外，强化学习的数据由智能体自己的行为产生，策略改变后数据分布也随之改变，因此需要在探索新动作与利用已知好动作之间权衡。"
        },
        {
          "q": "on-policy 和 off-policy 有什么区别？",
          "a": "on-policy 方法只用当前策略产生的数据更新当前策略，例如 REINFORCE、A2C 和 PPO；策略更新后旧数据大多要丢弃。off-policy 方法可以用其他策略（包括旧策略）产生的数据学习，例如 Q 学习、DQN、DDPG、TD3 和 SAC，因此可以使用经验回放，样本效率通常更高，但训练稳定性更难保证。"
        },
        {
          "q": "为什么 PPO 要裁剪概率比？",
          "a": "策略梯度的替代目标只在新旧策略接近时才可靠。PPO 用 min(比值 × 优势, 裁剪后的比值 × 优势) 作为目标：优势为正时，比值超过 1 + ε 后目标不再增加；优势为负时，比值低于 1 − ε 后目标不再减小，从而没有继续把策略推远的梯度。本课示例中 ε = 0.2、优势为 +1 时，比值 1.5 的目标被截为 1.2；优势为 −1 时，比值 0.5 的目标被截为 −0.8。这样同一批数据可以训练 10 轮，而不会让策略一步走得太远。"
        },
        {
          "q": "AlphaGo、AlphaGo Zero、AlphaZero 和 MuZero 有什么区别？",
          "a": "AlphaGo（2016）先用人类棋谱监督训练策略网络，再通过自我对弈强化学习，并与蒙特卡洛树搜索结合，以 5:0 击败欧洲围棋冠军。AlphaGo Zero（2017）完全不用人类数据，只从规则开始自我对弈，以 100:0 战胜此前的 AlphaGo。AlphaZero（2017）把同一算法推广到国际象棋和将棋，24 小时内在三种棋类上都达到超人水平。MuZero（2019）连规则也不需要，学习一个预测奖励、策略和价值的模型并在其上做树搜索，在 57 款 Atari 游戏上取得新的最好成绩。"
        },
        {
          "q": "学大模型需要先学强化学习吗？",
          "a": "如果要理解 RLHF、DPO、推理模型的训练，强化学习的基本概念是必要的：策略、奖励、优势、KL 约束和 PPO 的裁剪目标都直接出现在这些方法中。只做应用开发可以暂时跳过；做后训练或对齐研究则应先掌握本课内容，再学习对齐与推理模型相关课程。"
        }
      ],
      "sources": [
        {
          "title": "Sutton、Barto（2018），Reinforcement Learning: An Introduction（第 2 版，作者公开全文）",
          "url": "http://incompleteideas.net/book/the-book-2nd.html"
        },
        {
          "title": "Sutton（1988），Learning to Predict by the Methods of Temporal Differences，Machine Learning",
          "url": "https://link.springer.com/article/10.1007/BF00115009"
        },
        {
          "title": "Watkins、Dayan（1992），Q-learning，Machine Learning",
          "url": "https://link.springer.com/article/10.1007/BF00992698"
        },
        {
          "title": "Williams（1992），Simple Statistical Gradient-Following Algorithms for Connectionist Reinforcement Learning，Machine Learning",
          "url": "https://link.springer.com/article/10.1007/BF00992696"
        },
        {
          "title": "Mnih 等（2013），Playing Atari with Deep Reinforcement Learning",
          "url": "https://arxiv.org/abs/1312.5602"
        },
        {
          "title": "Mnih 等（2015），Human-level Control through Deep Reinforcement Learning，Nature",
          "url": "https://www.nature.com/articles/nature14236"
        },
        {
          "title": "van Hasselt、Guez、Silver（2015），Deep Reinforcement Learning with Double Q-learning",
          "url": "https://arxiv.org/abs/1509.06461"
        },
        {
          "title": "Schaul 等（2015），Prioritized Experience Replay",
          "url": "https://arxiv.org/abs/1511.05952"
        },
        {
          "title": "Mnih 等（2016），Asynchronous Methods for Deep Reinforcement Learning",
          "url": "https://arxiv.org/abs/1602.01783"
        },
        {
          "title": "Schulman 等（2015），Trust Region Policy Optimization",
          "url": "https://arxiv.org/abs/1502.05477"
        },
        {
          "title": "Schulman 等（2015），High-Dimensional Continuous Control Using Generalized Advantage Estimation",
          "url": "https://arxiv.org/abs/1506.02438"
        },
        {
          "title": "Schulman 等（2017），Proximal Policy Optimization Algorithms",
          "url": "https://arxiv.org/abs/1707.06347"
        },
        {
          "title": "Lillicrap 等（2015），Continuous Control with Deep Reinforcement Learning",
          "url": "https://arxiv.org/abs/1509.02971"
        },
        {
          "title": "Fujimoto、van Hoof、Meger（2018），Addressing Function Approximation Error in Actor-Critic Methods",
          "url": "https://arxiv.org/abs/1802.09477"
        },
        {
          "title": "Haarnoja 等（2018），Soft Actor-Critic: Off-Policy Maximum Entropy Deep Reinforcement Learning with a Stochastic Actor",
          "url": "https://arxiv.org/abs/1801.01290"
        },
        {
          "title": "Kumar 等（2020），Conservative Q-Learning for Offline Reinforcement Learning",
          "url": "https://arxiv.org/abs/2006.04779"
        },
        {
          "title": "Chen 等（2021），Decision Transformer: Reinforcement Learning via Sequence Modeling",
          "url": "https://arxiv.org/abs/2106.01345"
        },
        {
          "title": "Silver 等（2016），Mastering the Game of Go with Deep Neural Networks and Tree Search，Nature",
          "url": "https://www.nature.com/articles/nature16961"
        },
        {
          "title": "Silver 等（2017），Mastering the Game of Go without Human Knowledge，Nature",
          "url": "https://www.nature.com/articles/nature24270"
        },
        {
          "title": "Silver 等（2017），Mastering Chess and Shogi by Self-Play with a General Reinforcement Learning Algorithm",
          "url": "https://arxiv.org/abs/1712.01815"
        },
        {
          "title": "Schrittwieser 等（2019），Mastering Atari, Go, Chess and Shogi by Planning with a Learned Model",
          "url": "https://arxiv.org/abs/1911.08265"
        },
        {
          "title": "Ouyang 等（2022），Training Language Models to Follow Instructions with Human Feedback",
          "url": "https://arxiv.org/abs/2203.02155"
        },
        {
          "title": "Shao 等（2024），DeepSeekMath: Pushing the Limits of Mathematical Reasoning in Open Language Models",
          "url": "https://arxiv.org/abs/2402.03300"
        },
        {
          "title": "OpenAI Spinning Up：Part 1: Key Concepts in RL",
          "url": "https://spinningup.openai.com/en/latest/spinningup/rl_intro.html"
        },
        {
          "title": "OpenAI Spinning Up：Part 3: Intro to Policy Optimization",
          "url": "https://spinningup.openai.com/en/latest/spinningup/rl_intro3.html"
        },
        {
          "title": "OpenAI Spinning Up：Proximal Policy Optimization",
          "url": "https://spinningup.openai.com/en/latest/algorithms/ppo.html"
        },
        {
          "title": "Gymnasium 文档：Frozen Lake",
          "url": "https://gymnasium.farama.org/environments/toy_text/frozen_lake/"
        },
        {
          "title": "Gymnasium 文档：Cart Pole",
          "url": "https://gymnasium.farama.org/environments/classic_control/cart_pole/"
        },
        {
          "title": "CleanRL 文档：Proximal Policy Gradient (PPO)",
          "url": "https://docs.cleanrl.dev/rl-algorithms/ppo/"
        },
        {
          "title": "Huang 等（2022），The 37 Implementation Details of Proximal Policy Optimization，ICLR Blog Track",
          "url": "https://iclr-blog-track.github.io/2022/03/25/ppo-implementation-details/"
        },
        {
          "title": "PyTorch 教程：Reinforcement Learning (DQN) Tutorial",
          "url": "https://docs.pytorch.org/tutorials/intermediate/reinforcement_q_learning.html"
        },
        {
          "title": "Hugging Face 深度强化学习课程",
          "url": "https://huggingface.co/learn/deep-rl-course/unit0/introduction"
        },
        {
          "title": "Lilian Weng：Policy Gradient Algorithms",
          "url": "https://lilianweng.github.io/posts/2018-04-08-policy-gradient/"
        }
      ],
      "url": "https://aimap.page/zh-hans/learn/deep-learning/reinforcement-learning/",
      "markdown": "**概要**：强化学习（RL）研究智能体如何在与环境的交互中，根据奖励信号逐步改进自己的行为。它与监督学习的区别在于：没有标准答案，只有事后的好坏评价；数据由智能体自己的决策产生。本课先给出马尔可夫决策过程、回报、价值函数与贝尔曼方程等基本概念，再沿两条主线介绍核心算法：基于价值的方法（价值迭代、时序差分、Q 学习、DQN）和基于策略的方法（REINFORCE、Actor-Critic、TRPO、PPO），然后介绍连续控制、离线强化学习、AlphaGo 系列的自我对弈与树搜索，最后说明强化学习与大模型后训练（RLHF、GRPO）的关系。文中实验数字均来自文末可运行示例。\n\n本课属于[强化学习基础](/learn/unit/u33-rl-basics)单元，前置为[概率与信息论](/learn/probability-information)（期望、条件概率）和[训练深层网络](/learn/training-deep-nets)（优化器与梯度裁剪）。后续可学习[大模型如何学会说话](/learn/how-llms-learn)中的 RLHF 和[推理模型](/learn/reasoning-models)。相关算法卡：[Q 学习](/learn/algorithms/q-learning)、[DQN](/learn/algorithms/dqn)、[策略梯度](/learn/algorithms/policy-gradient)、[Actor-Critic 与 A3C](/learn/algorithms/a3c)、[TRPO](/learn/algorithms/trpo)、[PPO](/learn/algorithms/ppo)、[DDPG/TD3](/learn/algorithms/ddpg-td3)、[SAC](/learn/algorithms/sac)、[CQL](/learn/algorithms/cql)、[Decision Transformer](/learn/algorithms/decision-transformer)、[AlphaGo/AlphaZero](/learn/algorithms/mcts-alphazero)、[MuZero](/learn/algorithms/muzero)、[RLHF](/learn/algorithms/rlhf)、[GRPO](/learn/algorithms/grpo)。\n\n## 问题设定：智能体、环境与马尔可夫决策过程\n\n在每个时间步 t，智能体观察到状态 sₜ，按策略 π 选择动作 aₜ；环境返回奖励 rₜ 并转移到下一个状态 sₜ₊₁。这一交互过程通常形式化为马尔可夫决策过程（MDP），由五个要素组成：\n\n| 要素 | 含义 | FrozenLake 示例 |\n|---|---|---|\n| 状态集合 S | 环境可能处于的情况 | 4×4 冰面上的 16 个格子 |\n| 动作集合 A | 智能体可选的动作 | 上、下、左、右 |\n| 转移概率 P(s′ \\| s, a) | 执行动作后到达各状态的概率 | 冰面打滑：按意图方向移动的概率为 1/3，其余两种垂直方向各 1/3 |\n| 奖励函数 R | 每一步得到的标量反馈 | 到达终点得 1，其余为 0 |\n| 折扣因子 γ | 未来奖励的权重，0 ≤ γ ≤ 1 | 0.99 |\n\n“马尔可夫”指下一状态只取决于当前状态和动作，与更早的历史无关。策略 π(a | s) 给出每个状态下选择各动作的概率；确定性策略则直接给出一个动作。\n\n## 回报、价值函数与贝尔曼方程\n\n智能体的目标是最大化**回报**，即从当前时刻起奖励的折扣和：\n\n> Gₜ = rₜ + γ·rₜ₊₁ + γ²·rₜ₊₂ + … = rₜ + γ·Gₜ₊₁\n\nγ < 1 使越远的奖励权重越小，也保证无限长序列的回报有界。示例中奖励序列为 (0, 0, 0, 1)、γ = 0.9 时，各时刻的回报依次为 0.729、0.81、0.9、1.0：越早的时刻离奖励越远，回报越小。\n\n**状态价值** Vπ(s) 是从状态 s 出发、按策略 π 行动的期望回报；**动作价值** Qπ(s, a) 是在 s 先执行动作 a、之后按 π 行动的期望回报；二者之差 Aπ(s, a) = Qπ(s, a) − Vπ(s) 称为**优势**，表示动作 a 比该状态下的平均水平好多少。由回报的递推关系可以得到**贝尔曼方程**：\n\n> Vπ(s) = Σₐ π(a | s) · Σₛ′ P(s′ | s, a) · [ R(s, a, s′) + γ·Vπ(s′) ]\n\n最优价值函数满足**贝尔曼最优方程**，把对策略的平均换成取最大：\n\n> Q*(s, a) = Σₛ′ P(s′ | s, a) · [ R(s, a, s′) + γ·maxₐ′ Q*(s′, a′) ]\n\n求出 Q* 后，每个状态选 Q* 最大的动作就是最优策略。下面的算法都可以看作求解或近似这两个方程的不同方式（Sutton 与 Barto，2018，第 3–4 章）。\n\n## 已知模型：动态规划与价值迭代\n\n如果转移概率和奖励函数已知，可以直接用动态规划求解。**价值迭代**反复用贝尔曼最优方程更新所有状态的价值，直到不再变化。示例在 Gymnasium 的 FrozenLake 4×4 打滑版本上运行价值迭代，438 轮后收敛（最大变化小于 10⁻⁸），起点状态的最优价值为 0.542；按所得策略实际运行 10,000 回合，成功到达终点的比例为 0.737。由于冰面打滑，即使是最优策略也无法保证成功。\n\n现实问题中，环境模型通常未知（例如游戏内部逻辑、机器人动力学），或者状态太多无法逐一枚举。这就需要从交互数据中学习的无模型方法，以及用神经网络近似价值函数或策略。\n\n## 无模型学习：时序差分与 Q 学习\n\n不知道转移概率时，可以用实际经历的样本估计价值。**蒙特卡洛方法**等一个回合结束后，用实际回报 Gₜ 作为目标；**时序差分（TD）学习**（Sutton，1988）只看一步，用 rₜ + γ·V(sₜ₊₁) 作为目标，即用当前估计更新估计（自举，bootstrapping），不必等回合结束。两者之间存在偏差与方差的权衡：蒙特卡洛目标无偏但方差大，TD 目标方差小但依赖当前估计的准确性。\n\n**Q 学习**（Watkins，1989；Watkins 与 Dayan，1992）是把 TD 思想用于贝尔曼最优方程的算法。每经历一次转移 (s, a, r, s′)，就做一次更新：\n\n> Q(s, a) ← Q(s, a) + α · [ r + γ·maxₐ′ Q(s′, a′) − Q(s, a) ]\n\n方括号内称为 TD 误差，α 为学习率。Watkins 与 Dayan 证明，只要所有状态下的所有动作都被反复采样，且动作价值用表格离散表示，Q 学习就以概率 1 收敛到最优动作价值。为了保证探索，常用 **ε-贪心**策略：以概率 ε 随机选动作，否则选当前 Q 值最大的动作，并让 ε 随训练逐渐减小。Q 学习更新时用的是 maxₐ′ Q(s′, a′)，与实际采取的探索动作无关，因此属于 **off-policy** 方法；若改用实际执行的下一个动作的 Q 值，就是 on-policy 的 SARSA（Sutton 与 Barto，2018，第 6 章）。\n\n示例用表格 Q 学习在同一个 FrozenLake 上训练 20,000 回合（α = 0.1，ε 从 1 指数衰减到 0.05），智能体不知道转移概率。训练后起点的最大 Q 值为 0.504（价值迭代的精确值为 0.542），贪心策略的成功率同样为 0.737；在 11 个非终止状态中，有 10 个选择了与价值迭代相同的动作。\n\n## 深度 Q 网络（DQN）\n\n状态空间很大时（例如游戏画面），无法为每个状态建表，需要用神经网络 Q(s, a; θ) 近似动作价值。直接把 Q 学习与神经网络结合往往不稳定。Mnih 等（2013）提出的 DQN 用卷积网络读取原始像素、输出各动作的 Q 值，并引入两项关键技术：\n\n1. **经验回放**：把转移 (s, a, r, s′) 存入回放缓冲区（论文中保存最近 100 万帧），训练时随机抽取小批量，打破连续样本之间的相关性，并让每条经验被多次使用；\n2. **目标网络**：2015 年的 Nature 版本用一个定期从在线网络复制参数的目标网络计算 r + γ·maxₐ′ Q(s′, a′; θ⁻)，避免目标随每次更新同步移动（van Hasselt 等，2015，对该设计有说明）。\n\n2013 年的论文在 7 款 Atari 游戏上测试，其中 6 款超过此前所有方法，3 款超过人类专家；ε 在前 100 万帧中从 1 线性降到 0.1，大多数游戏中智能体每 4 帧选择一次动作。2015 年的 Nature 论文把测试扩展到 49 款游戏，只用像素和得分作为输入，所有游戏使用同一套算法、网络结构和超参数，达到与专业人类游戏测试员相当的水平。\n\n后续改进很多。Double DQN（van Hasselt 等，2015）指出 Q 学习中的 max 操作会系统性地高估动作价值，改为用在线网络选动作、目标网络评估该动作，减轻了高估并提升了得分；优先经验回放（Schaul 等，2015）按 TD 误差大小优先抽取样本，在 49 款游戏中的 41 款上超过均匀回放的 DQN。\n\n## 策略梯度与 Actor-Critic\n\n基于价值的方法先学 Q 再导出策略，难以直接处理连续动作。**策略梯度**方法直接把策略参数化为 πθ(a | s)，沿期望回报 J(θ) 的梯度方向更新参数。利用对数导数技巧可以得到：\n\n> ∇J(θ) = E[ Σₜ ∇log πθ(aₜ | sₜ) · Gₜ ]\n\n直观地说：回报高的轨迹中出现的动作，提高其概率；回报低的，降低其概率。这就是 **REINFORCE** 算法（Williams，1992）。它的问题是方差很大。从 Gₜ 中减去一个只依赖状态的**基线** b(sₜ)（通常是学到的 V(sₜ)）不改变梯度的期望，却能显著降低方差；减去基线后的 Gₜ − V(sₜ) 正是优势的一个估计（Spinning Up，Part 3）。\n\n同时学习策略（actor）和价值函数（critic）的方法称为 **Actor-Critic**。Mnih 等（2016）提出 A3C，让多个并行的 actor-learner 异步更新共享参数，论文称并行有稳定训练的作用，其最佳变体在 Atari 上超过当时的最好结果，而训练时间只有一半，且只用一台多核 CPU。**广义优势估计（GAE）**（Schulman 等，2015）用参数 λ 对多步 TD 误差做指数加权，在偏差与方差之间连续调节：λ = 0 相当于单步 TD，λ = 1 相当于蒙特卡洛回报。\n\n## TRPO 与 PPO\n\n策略梯度的一大难点是步长：一次更新走得太远，策略可能突然崩溃，而且由于数据由策略本身产生，崩溃后很难恢复。**TRPO**（Schulman 等，2015）从可保证单调改进的理论出发，在每次更新时把新旧策略之间的 KL 散度限制在一个小范围内（信赖域），实验中几乎不需要调超参数就能稳定改进，但每次更新要用共轭梯度法近似求解带约束的优化问题，实现比较复杂。\n\n**PPO**（Schulman 等，2017）用一阶方法近似实现同样的目标。记新旧策略在同一动作上的概率比为 ratio = πθ(a | s) / πθ_old(a | s)，PPO 最大化裁剪后的替代目标：\n\n> L = E[ min( ratio · Â, clip(ratio, 1 − ε, 1 + ε) · Â ) ]\n\n其中 Â 为优势估计（通常用 GAE），ε 一般取 0.2。取最小值使目标成为未裁剪目标的下界：当更新会让比值超出 [1 − ε, 1 + ε] 并且看起来“更好”时，目标不再增加，也就没有继续推动的梯度。示例计算了 ε = 0.2 时的裁剪目标：优势为 +1 时，比值 0.5、0.8、1.0、1.2、1.5 对应 0.5、0.8、1.0、1.2、1.2；优势为 −1 时对应 −0.8、−0.8、−1.0、−1.2、−1.5。\n\n这一约束使 PPO 可以对同一批数据做多轮小批量梯度更新。论文在 7 个 MuJoCo 连续控制任务上比较了不同替代目标（每种设置 3 个随机种子、共 21 次运行）：不裁剪也不加惩罚的平均归一化得分为 −0.39，ε = 0.1、0.2、0.3 时分别为 0.76、0.82、0.70；自适应 KL 惩罚的最好结果为 0.74，固定 KL 惩罚为 0.72，ε = 0.2 的裁剪目标得分最高。\n\n示例在 Gymnasium 的 CartPole-v1 上比较 REINFORCE（带价值基线，每批 2048 步数据更新一次）与 PPO（同样每批 2048 步，GAE λ = 0.95，每批训练 10 轮、小批量 64），两者网络结构相同，各训练 10 万步、3 个随机种子。CartPole 每坚持一步得 1 分，回合最长 500 步。结果如下：\n\n| 算法 | 最后 20 回合平均回报（种子 0 / 1 / 2） | 最近 20 回合平均首次达到 475 的步数 |\n|---|---|---|\n| REINFORCE（带基线） | 178.0 / 290.8 / 204.6 | 10 万步内未达到 |\n| PPO（ε = 0.2） | 500.0 / 500.0 / 500.0 | 46,296 / 45,191 / 35,285 |\n\nPPO 的样本效率明显更高，主要原因是每批数据被安全地复用了多轮。实际实现中还有许多影响结果的细节，例如优势归一化、梯度裁剪、学习率退火和价值函数裁剪，见 ICLR 博客文章《The 37 Implementation Details of PPO》与 CleanRL 的单文件实现。\n\n## 连续控制与离线强化学习\n\n机器人等任务的动作是连续的，无法对所有动作取最大值。**DDPG**（Lillicrap 等，2015）把 DQN 的经验回放和目标网络与确定性策略梯度结合，用同一套算法、网络结构和超参数解决了 20 多个物理仿真任务。**TD3**（Fujimoto 等，2018）发现 Actor-Critic 中同样存在价值高估，采用两个 critic 取较小值、延迟策略更新等方法加以缓解。**SAC**（Haarnoja 等，2018）属于最大熵强化学习框架，策略在最大化回报的同时最大化自身的熵，以鼓励探索并提高稳定性。\n\n**离线强化学习**只用一个固定的历史数据集训练，不再与环境交互，适合交互代价高或有风险的场景。主要困难是数据集与学习到的策略之间的分布偏移会导致价值被高估。**CQL**（Kumar 等，2020）在贝尔曼误差之外加入正则项，学习一个保守的 Q 函数，使策略价值的估计成为真实价值的下界。**Decision Transformer**（Chen 等，2021）则完全换了思路，把强化学习表述为条件序列建模：以期望回报、过去的状态和动作为条件，用因果 Transformer 自回归地生成动作，在 Atari、OpenAI Gym 和 Key-to-Door 任务上达到或超过当时最好的无模型离线强化学习基线。\n\n## 规划与自我对弈：AlphaGo、AlphaZero 与 MuZero\n\n棋类游戏的规则完全已知，可以把学习与搜索结合。**AlphaGo**（Silver 等，2016）用策略网络选择落子、价值网络评估局面：两类网络先用人类专家棋谱做监督学习，再通过自我对弈做强化学习，并与蒙特卡洛树搜索（MCTS）结合。AlphaGo 对其他围棋程序的胜率达到 99.8%，并以 5:0 击败欧洲围棋冠军，这是计算机程序首次在全尺寸棋盘上击败职业棋手。\n\n**AlphaGo Zero**（Silver 等，2017）不再使用任何人类数据：神经网络学习预测 MCTS 自己的落子选择和对局胜负，更强的网络又带来更强的搜索和更高质量的自我对弈数据，如此循环。从随机下棋开始，AlphaGo Zero 以 100:0 战胜了此前击败世界冠军的 AlphaGo。**AlphaZero**（Silver 等，2017）把同一算法推广到国际象棋和将棋，除规则外不使用领域知识，24 小时内在三种棋类上都达到超人水平，并分别击败各自的世界冠军程序。**MuZero**（Schrittwieser 等，2019）进一步去掉了对规则的依赖：它学习一个只预测与规划直接相关的量（奖励、策略和价值）的模型，在学到的模型上做树搜索，在 57 款 Atari 游戏上取得新的最好成绩，同时在围棋、国际象棋和将棋上达到与 AlphaZero 相当的水平。\n\n## 与大模型的关系：RLHF 与推理模型\n\n把语言模型看作策略、生成的每个 token 看作动作，强化学习就可以用来优化难以写成监督目标的性质。**InstructGPT**（Ouyang 等，2022）先用人类示范做监督微调，再用人类对多个回答的排序训练奖励模型，最后用 PPO 优化策略，同时用 KL 惩罚防止模型偏离监督微调模型太远。在其提示分布上，13 亿参数的 InstructGPT 输出比 1750 亿参数的 GPT-3 更受人类偏好。DeepSeekMath（Shao 等，2024）提出的 **GRPO** 去掉了 PPO 中的价值网络（critic），对同一问题采样一组回答，以组内得分作为基线估计优势，显著降低了训练资源。RLHF 的完整流程见[大模型如何学会说话](/learn/how-llms-learn)，GRPO 在 DeepSeek-R1 等推理模型中的应用以及基于可验证奖励的强化学习见[推理模型](/learn/reasoning-models)。\n\n## 可运行示例\n\n以下代码在 PyTorch 2.15（CPU）、Gymnasium 1.4 上以 OMP_NUM_THREADS=3 实测，输出与上文数字一致，全部运行约需 3 分钟（CartPole 部分占大部分时间）。线程数不同时浮点累加顺序会变化，训练类数字可能略有差异。\n\n```python\nimport numpy as np, torch, torch.nn as nn, gymnasium as gym, time\ntorch.manual_seed(0); np.random.seed(0); torch.set_num_threads(3)\n\n# 1) 折扣回报\nr=[0,0,0,1]; g=0.9\nG=[sum(g**k*r[t+k] for k in range(len(r)-t)) for t in range(len(r))]\nprint('折扣回报 G_t:', [round(x,3) for x in G])\n\n# 2) FrozenLake 4x4（滑动）：价值迭代\nenv=gym.make('FrozenLake-v1', is_slippery=True); P=env.unwrapped.P; nS,nA=16,4; gamma=0.99\nV=np.zeros(nS); it=0\nwhile True:\n    it+=1\n    Q=np.array([[sum(p*(rw+gamma*V[s2]*(not d)) for p,s2,rw,d in P[s][a]) for a in range(nA)] for s in range(nS)])\n    V2=Q.max(1)\n    if np.abs(V2-V).max()<1e-8: V=V2; break\n    V=V2\npi_vi=Q.argmax(1)\nprint(f'价值迭代 {it} 轮收敛，起点价值 V(s0) = {V[0]:.3f}')\ndef evaluate(pi,n=10000,seed=1):\n    e=gym.make('FrozenLake-v1', is_slippery=True); w=0\n    for i in range(n):\n        s,_=e.reset(seed=seed+i); done=False\n        while not done:\n            s,rw,term,trunc,_=e.step(int(pi[s])); done=term or trunc\n        w+=rw\n    return w/n\nprint(f'价值迭代策略成功率 {evaluate(pi_vi):.3f}')\n\n# 3) 表格 Q-learning（ε-贪心，无模型）\nQt=np.zeros((nS,nA)); alpha=0.1; rng=np.random.default_rng(0); eps=1.0\ne=gym.make('FrozenLake-v1', is_slippery=True)\nfor ep in range(20000):\n    s,_=e.reset(seed=int(rng.integers(1e9))); done=False\n    while not done:\n        a=int(rng.integers(nA)) if rng.random()<eps else int(rng.choice(np.flatnonzero(Qt[s]==Qt[s].max())))\n        s2,rw,term,trunc,_=e.step(a); done=term or trunc\n        target=rw+(0 if term else gamma*Qt[s2].max())\n        Qt[s,a]+=alpha*(target-Qt[s,a]); s=s2\n    eps=max(0.05, eps*0.9997)\nprint(f'Q-learning 20000 回合后 Q(s0) 最大值 {Qt[0].max():.3f}，贪心策略成功率 {evaluate(Qt.argmax(1)):.3f}，与价值迭代策略相同的状态数 {(Qt.argmax(1)==pi_vi)[[0,1,2,3,4,6,8,9,10,13,14]].sum()}/11')\n\n# 4) PPO 裁剪目标：优势为正/负时概率比的有效范围\neps_c=0.2\nfor A in (1.0,-1.0):\n    vals=[]\n    for ratio in (0.5,0.8,1.0,1.2,1.5):\n        vals.append(round(min(ratio*A, float(np.clip(ratio,1-eps_c,1+eps_c))*A),2))\n    print(f'A={A:+.0f} 时 ratio=0.5/0.8/1.0/1.2/1.5 的裁剪目标', vals)\n\n# 5) CartPole：REINFORCE（带基线） vs PPO，同样 10 万步\ndef mlp(o): return nn.Sequential(nn.Linear(4,64),nn.Tanh(),nn.Linear(64,64),nn.Tanh(),nn.Linear(64,o))\ndef run(algo, steps=100_000, seed=0):\n    torch.manual_seed(seed); env=gym.make('CartPole-v1'); pi=mlp(2); vf=mlp(1)\n    opt=torch.optim.Adam(list(pi.parameters())+list(vf.parameters()), lr=3e-4 if algo=='ppo' else 1e-3)\n    obs,_=env.reset(seed=seed); t=0; ep_ret=0; rets=[]; first475=None\n    while t<steps:\n        O,A,R,D,LP=[],[],[],[],[]\n        for _ in range(2048):\n            o=torch.tensor(obs,dtype=torch.float32)\n            with torch.no_grad(): dist=torch.distributions.Categorical(logits=pi(o))\n            a=dist.sample(); obs,rw,term,trunc,_=env.step(int(a)); t+=1; ep_ret+=rw\n            O.append(o);A.append(a);R.append(rw);D.append(term);LP.append(dist.log_prob(a))\n            if term or trunc:\n                rets.append(ep_ret); ep_ret=0; obs,_=env.reset()\n                if first475 is None and len(rets)>=20 and np.mean(rets[-20:])>=475: first475=t\n                D[-1]=True if (term or trunc) else D[-1]\n        O=torch.stack(O);A=torch.stack(A);LP=torch.stack(LP);R=torch.tensor(R);Dn=torch.tensor(D,dtype=torch.float32)\n        with torch.no_grad():\n            V=vf(O).squeeze(-1); nv=vf(torch.tensor(obs,dtype=torch.float32)).squeeze()\n        # GAE(λ=0.95)；REINFORCE 用 λ=1 的蒙特卡洛回报\n        lam=0.95 if algo=='ppo' else 1.0; adv=torch.zeros(len(R)); last=0\n        for i in reversed(range(len(R))):\n            nxt=nv if i==len(R)-1 else V[i+1]\n            delta=R[i]+0.99*nxt*(1-Dn[i])-V[i]; last=delta+0.99*lam*(1-Dn[i])*last; adv[i]=last\n        ret=adv+V\n        if algo=='ppo':\n            for _ in range(10):\n                for idx in torch.randperm(len(R)).split(64):\n                    a_=(adv[idx]-adv[idx].mean())/(adv[idx].std()+1e-8)\n                    nlp=torch.distributions.Categorical(logits=pi(O[idx])).log_prob(A[idx])\n                    ratio=(nlp-LP[idx]).exp()\n                    l=-torch.min(ratio*a_, ratio.clamp(0.8,1.2)*a_).mean()+0.5*((vf(O[idx]).squeeze(-1)-ret[idx])**2).mean()\n                    opt.zero_grad(); l.backward(); nn.utils.clip_grad_norm_(list(pi.parameters())+list(vf.parameters()),0.5); opt.step()\n        else:\n            a_=(adv-adv.mean())/(adv.std()+1e-8)\n            nlp=torch.distributions.Categorical(logits=pi(O)).log_prob(A)\n            l=-(nlp*a_).mean()+0.5*((vf(O).squeeze(-1)-ret)**2).mean()\n            opt.zero_grad(); l.backward(); opt.step()\n    return np.mean(rets[-20:]), first475\nfor algo in ('reinforce','ppo'):\n    res=[]\n    for seed in (0,1,2):\n        t0=time.time(); m,f=run(algo,seed=seed); res.append((round(m,1),f))\n    print(f'{algo}: 3 个种子最后 20 回合平均回报与首次达到 475 的步数', [(float(a),b) for a,b in res])\n```\n\n输出：\n\n```text\n折扣回报 G_t: [0.729, 0.81, 0.9, 1.0]\n价值迭代 438 轮收敛，起点价值 V(s0) = 0.542\n价值迭代策略成功率 0.737\nQ-learning 20000 回合后 Q(s0) 最大值 0.504，贪心策略成功率 0.737，与价值迭代策略相同的状态数 10/11\nA=+1 时 ratio=0.5/0.8/1.0/1.2/1.5 的裁剪目标 [0.5, 0.8, 1.0, 1.2, 1.2]\nA=-1 时 ratio=0.5/0.8/1.0/1.2/1.5 的裁剪目标 [-0.8, -0.8, -1.0, -1.2, -1.5]\nreinforce: 3 个种子最后 20 回合平均回报与首次达到 475 的步数 [(178.0, None), (290.8, None), (204.6, None)]\nppo: 3 个种子最后 20 回合平均回报与首次达到 475 的步数 [(500.0, 46296), (500.0, 45191), (500.0, 35285)]\n```\n\n## 动手练习\n\n1. **单元项目**：在 [Gymnasium](https://gymnasium.farama.org/) 的 CartPole 上依次实现表格离散化 Q 学习（把连续状态分箱）、DQN（参考 [PyTorch DQN 教程](https://docs.pytorch.org/tutorials/intermediate/reinforcement_q_learning.html)）和 PPO，记录达到平均回报 475 所需的环境步数，比较样本效率。\n2. 把示例中的 FrozenLake 改为不打滑（`is_slippery=False`），重新运行价值迭代和 Q 学习，解释最优成功率为什么变为 1；再把 γ 改为 0.9 和 0.5，观察起点价值与策略的变化。\n3. 在示例的 PPO 中分别把裁剪系数改为 0.1、0.3 和不裁剪（ε 取很大的值），每种设置跑 3 个种子，与 PPO 论文表 1 的趋势对照。\n4. 阅读 [CleanRL 的 PPO 实现](https://docs.cleanrl.dev/rl-algorithms/ppo/)，对照[《The 37 Implementation Details of PPO》](https://iclr-blog-track.github.io/2022/03/25/ppo-implementation-details/)逐项找出示例代码缺少的实现细节，补上其中两项并比较学习曲线。\n\n## 推荐学习顺序\n\n先读 Sutton 与 Barto《[Reinforcement Learning: An Introduction](http://incompleteideas.net/book/the-book-2nd.html)》第 3、4、6 章（MDP、动态规划、时序差分），再读 [Spinning Up 的 Part 1](https://spinningup.openai.com/en/latest/spinningup/rl_intro.html) 和 [Part 3](https://spinningup.openai.com/en/latest/spinningup/rl_intro3.html) 建立策略梯度的推导。深度强化学习部分按 DQN（2013）、Double DQN、A3C、TRPO、GAE、PPO 的顺序读原论文，配合 [Hugging Face 深度强化学习课程](https://huggingface.co/learn/deep-rl-course/unit0/introduction)动手。系统课程可选 [UC Berkeley CS285](https://rail.eecs.berkeley.edu/deeprlcourse/) 或 [David Silver 的强化学习课程](https://davidstarsilver.wordpress.com/teaching/)；综述可读 [Lilian Weng 的 Policy Gradient Algorithms](https://lilianweng.github.io/posts/2018-04-08-policy-gradient/)。之后进入[大模型如何学会说话](/learn/how-llms-learn)中的 RLHF 和[推理模型](/learn/reasoning-models)。"
    }
  }
}