π Reinforcement Learning (RL)
Descriptionβ
< What is it? >β
- Reinforcement Learning (RL) is a learning paradigm in which an agent learns to choose actions from feedback about their consequences. Its objective is to maximize expected cumulative reward, rather than only the reward from the next action. Applications include robot control, games, resource allocation, and language-model post-training.
- Example: a robot must reach the end of a corridor. It receives
β1for each move that does not reach the goal and+10for reaching it. Moving toward the goal may initially receive a negative reward, but it enables a larger reward later. The agent learns which actions produce the best overall outcome. - Learning signal: the environment supplies rewards and new observations. A training example does not usually specify the correct action for every situation. Googleβs Introduction to Machine Learning introduces this reward-driven learning process.
Definitionβ
< Core terminology >β
-
The components: the corridor example gives each term a concrete meaning.
Term Meaning Corridor example Agent The decision-making learner The robotβs controller Environment The system the agent interacts with The corridor and its movement rules State, Information sufficient to describe the current situation for predicting transitions and rewards Current position: 0,1,2, or3Observation, Information available to the agent; it may reveal only part of the state The position sensor reading Action, A choice available to the agent Move left or right Reward, Numerical feedback after an action β1for a non-goal move;+10on reaching position3Policy, A rule or probability distribution for choosing actions Choose right at positions 0,1, and2Episode One run from a starting condition to termination Start at 0and finish at the goalReturn, Accumulated future reward, optionally discounted Reward from the remaining journey Value function Expected return under a specified policy values a state; values an action in that state -
Markov Decision Process (MDP): a common mathematical formulation specifies states, actions, transition probabilities, rewards, and a discount factor. The Markov assumption means that the current state and action provide the information needed to predict the next-state and reward distributions. When observations omit relevant information, the policy may need history or memory. See Key Concepts in RL.
Key pointsβ
< The interaction and learning loop >β
-
Training cycle: the agent collects experience and uses it to improve its policy or value estimates. Updates may happen after each interaction or after collecting a batch.
The policy is the agentβs decision rule. The learning algorithm improves it directly or through learned action values; the dashed arrow represents updates during training.
-
Experience record: a transition commonly contains
(state, action, reward, next_state, terminated). For example,(2, "right", 10, 3, True)records reaching the goal. This is observed experience, not a supplied label saying that βrightβ is the correct action. -
Training versus inference: training changes the learned parameters or table entries. At inference, the deployed policy chooses an action from an observation; receiving a reward does not automatically update the model unless the application explicitly runs a learning procedure.
< Reward, return, and delayed credit >β
-
Discounted return: for an episode ending at time , a common objective uses:
The discount factor determines how strongly future rewards contribute. With , only the immediate reward counts. Values closer to
1give later rewards more weight; finite episodic tasks can also use . -
Worked example: the route
0 β 1 β 2 β 3produces rewardsβ1, β1, +10. With :Its undiscounted total reward is
8. The discounted return is smaller because the goal reward arrives after two earlier actions. -
Credit assignment: the final reward must influence the earlier choices that made it possible. A value-based method propagates estimated future returns backward through visited states; a policy-gradient method adjusts action probabilities using return or advantage estimates.
< Exploration and exploitation >β
- Exploration tries actions to discover their consequences. Exploitation chooses actions that currently appear best. Always exploiting early estimates can prevent the agent from finding a better strategy.
- Epsilon-greedy example: with , choose a random action on
20%of decisions and a highest-value action on the remaining80%. Random exploration can also select the currently best action. Exploration is often reduced as training progresses.
< How Q-learning updates an action value >β
-
Update rule: tabular Q-learning stores a number for each stateβaction pair and updates it toward an observed reward plus an estimated future value:
Here, is the next state, ranges over its available actions, and is the learning rate. For a terminal transition, the future-value term is zero. See the original Q-learning paper.
-
One numerical update: initially, suppose
Q(2, right) = 0. Moving right reaches the goal with reward10. With , the updated value is0 + 0.2 Γ (10 β 0) = 2. Repeated updates bring it toward10; earlier states then learn that moving right leads to a valuable future state. -
Neural-network version: a Deep Q Network (DQN) replaces the table with a neural network that estimates action values. A loss measures disagreement with a reward-based target, and backpropagation updates the network. Tabular Q-learning itself does not require a neural network.
< Reinforcement learning in LLM post-training >β
- Mapping to language generation: the prompt and generated prefix form the policyβs context; a token is an action, and an answer or tool-use trajectory can receive a reward. Training adjusts the model to increase expected reward on the task distribution.
- Reward sources: Reinforcement Learning from Human Feedback (RLHF) can use a reward model learned from human preferences. Reinforcement Learning with Verifiable Rewards (RLVR) uses checkable outcomes, such as whether generated code passes tests. A reward need not be a human rating on every generated answer.
- Optimization and parameter updates: Proximal Policy Optimization (PPO) and Group Relative Policy Optimization (GRPO) are policy-optimization methods. Low-Rank Adaptation (LoRA) determines which parameters are trained and can be combined with an RL objective. These names describe different parts of the training setup. The TRL GRPO documentation provides reward-function and training examples.
- Application boundary: an Agentic RAG workflow does not become reinforcement learning merely because it calls tools repeatedly. RL requires a reward-driven learning update. Editing instructions is prompt engineering; it does not update model parameters, as explained in Googleβs Machine Learning Crash Course.
Comparisonβ
< Reinforcement learning vs. supervised learning >β
-
Choosing the learning setup: the distinction concerns the objective and feedback, not whether the implementation uses a neural network.
Aspect Supervised learning Reinforcement learning Training feedback Desired output for an input Rewards associated with actions and outcomes Typical goal Predict labels or target values accurately Choose actions with high expected return Example Predict whether a logged userβitem pair was clicked Choose recommendations to improve a long-term session objective Consequences Standard training treats examples as a supplied dataset Actions can change future states and available experience Main challenge Generalization to unseen examples Generalization, exploration, and delayed credit assignment When useful A prediction task has suitable inputβtarget examples Decisions affect later outcomes and reward feedback is available -
Recommendation example: training a click predictor from click/not-click labels is supervised learning. Using predicted click probability to sort items does not by itself make the system RL. A contextual bandit can learn from immediate recommendation feedback; full sequential RL additionally models consequences for future decisions.
< Main families of reinforcement learning methods >β
-
What is learned: these categories overlap; an actorβcritic method also performs policy optimization.
Family What it learns or uses Examples Strength Limitation Value-based Action values used to select actions Tabular Q-learning, DQN Direct action comparison; experience can be reused Tables do not scale; standard DQN needs discrete actions Policy-gradient A parameterized action-selection policy REINFORCE Directly optimizes policy behavior Gradient estimates can have high variance Actorβcritic An actor chooses actions; a critic estimates value PPO with a value critic, Soft Actor-Critic (SAC) Value estimates help guide policy updates More interacting components to train and tune Model-based Known or learned environment dynamics for planning or training World-model methods Can use predicted experience to reduce real interactions Model errors can mislead planning or policy learning -
Two separate distinctions: model-free means no explicit environment-dynamics model is used for planning or learning; the agent can still contain a neural network. On-policy methods use experience from the policy being optimized, while off-policy methods can learn from experience collected by another behavior policy. Offline RL learns from a fixed dataset without collecting new interactions during training; it is not simply another name for off-policy RL.
Implementationβ
< Learn a corridor policy with tabular Q-learning >β
-
Input and task: the environment has positions
[0, 1, 2, 3], starts at0, and ends at3. Actions areleftandright; moving left at0stays at0. Reaching3gives+10; every other move givesβ1. No labeled correct route is supplied. -
Runnable Python: this example uses only the standard library.
q[state][action]is the learned table. Training uses exploration; inference selects the action with the highest learned value.import randomrng = random.Random(7)actions = ("left", "right")goal = 3q = [[0.0, 0.0] for _ in range(goal + 1)]alpha, gamma, epsilon = 0.2, 0.9, 0.2def step(state, action):next_state = max(0, min(goal, state + (-1 if action == 0 else 1)))terminated = next_state == goalreward = 10.0 if terminated else -1.0return next_state, reward, terminated# Training: learn from consequences, without correct-action labels.for episode in range(1000):state = 0for _ in range(30):if rng.random() < epsilon:action = rng.randrange(2) # Explore.else:action = max(range(2), key=lambda a: q[state][a])next_state, reward, terminated = step(state, action)future = 0.0 if terminated else max(q[next_state])target = reward + gamma * futureq[state][action] += alpha * (target - q[state][action])state = next_stateif terminated:break# The 30-step collection limit is not a terminal state of this task.print("state | Q(left) | Q(right) | chosen action")for state in range(goal):action = max(range(2), key=lambda a: q[state][a])print(f"{state} | {q[state][0]:.2f} | {q[state][1]:.2f} | {actions[action]}")# Inference: use the learned table without changing it.state, total_reward = 0, 0.0path = [state]for _ in range(30):action = max(range(2), key=lambda a: q[state][a])state, reward, terminated = step(state, action)path.append(state)total_reward += rewardif terminated:breakprint("Path:", " -> ".join(map(str, path)))print(f"Total reward: {total_reward:.1f}") -
Verified output: running the code produces:
state | Q(left) | Q(right) | chosen action0 | 4.58 | 6.20 | right1 | 4.58 | 8.00 | right2 | 6.20 | 10.00 | rightPath: 0 -> 1 -> 2 -> 3Total reward: 8.0 -
Reading the result: for inference input
state = 0, the learned values are approximately[4.58, 6.20], so the output action isright. These values estimate discounted return; they are not probabilities.Q(0, right) = 6.20matches the earlier discounted-return calculation, while the printed total reward is the undiscounted sum8.0. -
Evaluation scope: this deterministic toy verifies the learning mechanism. A realistic evaluation should freeze the policy and measure return, success rate, and task costs across separate evaluation episodes, varied scenarios, and multiple training seeds. One successful route does not establish generalization.
< Libraries for larger tasks >β
-
Environment and training tools: choose the library according to the task rather than treating an environment API as a learning algorithm.
Tool Role Typical use Gymnasium Defines environments and reset()/step()interfacesSimulated control tasks and custom environments Stable-Baselines3 Provides PyTorch implementations of RL algorithms Training and evaluating DQN, PPO, or SAC agents Hugging Face TRL Provides language-model training workflows Reward-based LLM post-training with GRPO
Troubleshootβ
< Common training problems >β
-
Diagnose behavior as well as reward: monitor actual task outcomes alongside the scalar objective.
Symptom Possible cause What to check The agent never reaches the goal Rare rewards or insufficient exploration Start with an easier task and inspect sampled trajectories Reward improves but behavior is undesirable The reward rewards a shortcut Inspect high-reward trajectories and revise the objective Training is unstable Large updates or poorly scaled inputs and rewards Check normalization, learning rate, and results across seeds Training looks good but evaluation fails Overfitting to training scenarios Use separate evaluation scenarios and compare with a simple baseline Values are wrong near episode boundaries Termination and collection cutoffs are confused Use zero future value at true termination; retain bootstrapping at an external time limit -
Termination versus truncation: Gymnasium returns both
terminatedandtruncated. Either can end data collection for an episode, but an external time limit does not necessarily remove the stateβs future value. See Handling Time Limits.
Q & Aβ
< Does reinforcement learning require a neural network? >β
- No: tabular Q-learning stores values in a table. Deep reinforcement learning uses neural networks to represent policies, value functions, or environment models when tables are impractical.
< Who defines the reward, and is it a training label? >β
- The task designer defines how reward is measured: it can come from game rules, simulator outcomes, user feedback, a learned reward model, or an automated verifier. It evaluates an outcome rather than normally identifying the correct action. Algorithms can construct training targets from it, such as Q-learningβs
reward + discounted future value.
Video Tutorialβ
- Reinforcement Learning (90s)
- What is AWS DeepRacer
- AWS DeepRacer LarsLoop by waypoints
Related ideasβ
- Q-Learning β value-based learning from stateβaction transitions.
- Deep Q Network (DQN) β neural-network action-value estimation.
- Policy Gradient β learning an action-selection policy directly.
- World Model β predicting consequences for planning and learning.
- Fine-Tuning β post-training objectives and parameter-update methods.
- Low-Rank Adaptation (LoRA) β parameter-efficient updates that can accompany RL training.
- Agentic RAG post-training β deciding when to improve prompts, retrieval, or model behavior.
Referenceβ
- Google: Introduction to Machine Learning β learning paradigms, including reinforcement learning.
- Google Machine Learning Crash Course: Fine-tuning and prompt engineering β parameter updates versus changes to instructions.
- Spinning Up: Key Concepts in RL β terminology, returns, and value functions.
- Spinning Up: Kinds of RL Algorithms β value-based, policy-based, and model-based methods.
- Watkins and Dayan: Q-learning (1992) β the tabular Q-learning update and convergence analysis.
- Stable-Baselines3: RL Tips and Tricks β evaluation and practical training guidance.
- Gymnasium: Handling Time Limits β termination, truncation, and bootstrapping.
- Hugging Face TRL: GRPO Trainer β language-model optimization with reward functions.