Detailed content
🔄 The reinforcement learning cycle
In supervised learning, someone shows the correct answer for each example. In reinforcement learning (reinforcement learning, RL), no one shows the answer: an agent acts in an environment, observes what happened, and receives a reward —a number that tells it whether that was good or bad. By repeating the cycle many times, it learns which actions lead to more reward over time.
Terms you’ll find in any RL text: state is the current situation the agent observes; action is what it chooses to do; policy is the rule that maps a state to an action (it’s what training adjusts); episode is a complete attempt, from start to finish; and return is the sum of an episode’s rewards, usually with a discount factor that gives less weight to what comes later. The classic reference for all this is the book "Reinforcement Learning: An Introduction," by Richard Sutton and Andrew Barto.
What it is
RL is learning a policy through trial and error, guided by rewards. The question it answers isn’t "what’s the right answer?" but "what sequence of decisions produces the best cumulative outcome?"
| Aspect | Supervised | Reinforcement |
|---|---|---|
| Signal | Correct answer for each example | Score (reward), sometimes only at the end |
| Data | Collected beforehand, fixed | Generated by the agent itself as it acts |
| Question | What is the output for this input? | Which sequence of actions yields more? |
| Typical risk | Poor labels | Reward exploited in an unexpected way |
Why learn
RL is no longer just about robotics and games: it’s part of training all today’s major assistants. If you understand the agent–environment–reward cycle, you can make sense of model announcements, talk with vendors about fine-tuning, and anticipate odd behaviors caused by poorly chosen rewards.
Key concepts
🧭 Explore, value, and policy
Every agent faces a dilemma: explore (try something new that might be better) or exploit (repeat what it already knows works). An agent that only exploits gets stuck on the first reasonable path; one that only explores never makes use of what it has learned. The simplest strategy, called ε-greedy, explores with a probability ε that decreases during training.
Algorithms fall into two broad families. Value-based methods estimate the value of each action in each state (the Q function) and choose the one with the highest value—Q-learning is the classic example, and DQN, from DeepMind (published in Nature in 2015), brought the idea to Atari games using neural networks. Policy-based methods directly adjust the probability of each action in the direction that increased the reward (policy gradient). The actor-critic methods combine the two: an "actor" chooses, and a "critic" evaluates. PPO (Schulman and colleagues, 2017) is a stable actor-critic method that became standard and, years later, was used in RLHF for language models.
What it is
This is RL’s technical core: balancing exploration and exploitation, and choosing whether to learn the value of actions, learn the policy directly, or combine both approaches.
| Category | Idea | Examples | Good for |
|---|---|---|---|
| Value | Learns Q(state, action) | Q-learning, DQN | Few discrete actions |
| Policy | Adjusts the probability of actions | REINFORCE | Continuous actions or many options |
| Actor-critic | Policy + value estimate | PPO, SAC | Stable training at scale |
| With a world model | Plans by simulating the future | AlphaGo (search + networks) | Known rules, such as in games |
Try this: watch an agent learn from scratch with Q-learning on your computer (Python 3, runs in seconds, no GPU required).
# pip install gymnasium numpy
import gymnasium as gym
import numpy as np
env = gym.make("FrozenLake-v1", is_slippery=False) # 4x4 grid: reach the gift without falling through the ice
Q = np.zeros((env.observation_space.n, env.action_space.n)) # state x action table
alpha, gamma = 0.1, 0.99 # learning rate and discount factor
epsilon, eps_min, eps_decay = 1.0, 0.05, 0.995
rng = np.random.default_rng(42)
env.action_space.seed(42)
for episode in range(2000):
state, _ = env.reset(seed=episode)
done = False
while not done:
if rng.random() < epsilon:
action = int(env.action_space.sample()) # explore
else:
action = int(np.argmax(Q[state])) # exploit
new_state, reward, term, trunc, _ = env.step(action)
target = reward + gamma * np.max(Q[new_state]) * (not term)
Q[state, action] += alpha * (target - Q[state, action]) # Bellman update
state, done = new_state, term or trunc
epsilon = max(eps_min, epsilon * eps_decay)
successes = 0
for i in range(100): # evaluation: exploit only
state, _ = env.reset(seed=10_000 + i)
done, r = False, 0.0
while not done:
state, r, term, trunc, _ = env.step(int(np.argmax(Q[state])))
done = term or trunc
successes += int(r)
print(f"success rate: {successes}/100")
print("learned policy (0=left 1=down 2=right 3=up):")
print(np.argmax(Q, axis=1).reshape(4, 4))
How to check: the expected output is success rate: 100/100 and a 4x4 grid with the direction chosen in each square. Now change range(2000) to range(50): the rate drops because the agent did not explore enough. Then change to is_slippery=True (the ice makes the agent slip): the rate drops sharply and the policy changes — that is the effect of a stochastic environment.
Why learn
The same concepts — value, policy, exploration, discounting — appear in language model training, recommendation systems, and agents. Watching an agent learn on a 4x4 grid gives you an intuition no diagram can: learning depends on how much it explores and when the reward arrives.
Key concepts
🏆 Reward and reward hacking
An RL agent is a relentless optimizer: it maximizes exactly the number you give it, not what you had in mind. When it finds a shortcut that increases the reward without fulfilling the goal, this is called reward hacking or specification gaming (exploiting flaws in the specification). A well-known example was published by OpenAI in 2016: in a boat racing game, the agent discovered that going in circles and collecting bonuses earned more points than finishing the race.
In language models, the same phenomenon appears in subtler ways: longer answers because the evaluator preferred long texts; agreeing with the user (flattery, or sycophancy) because people rate those who agree with them more highly; in coding tasks, changing or bypassing the tests instead of fixing the program. None of this is "malice" on the model's part: it is optimization finding the loophole left by the design.
What it is
Reward hacking is when the reward goes up and the real goal does not improve — or gets worse. This happens because the reward is always an approximation (proxy) of what you want.
✓ Well-designed reward
- ✓Verified by something that is hard to game (hidden tests, real-world results).
- ✓Tracked with independent metrics that the agent cannot see.
- ✓Includes a penalty for straying too far from the original behavior.
- ✓Frequently inspected through samples reviewed by people.
✗ Fragile reward
- ✗Counting keywords, length, or format.
- ✗Tests visible to and editable by the agent itself.
- ✗A single automated judge with no auditing.
- ✗Engagement metric as the end goal.
💡 Tip
Reward hacking is not exclusive to RL. Any team goal measured by a number (tickets closed, support time) has the same problem. The question that protects you: "What is the cheapest way to hit this target without doing the work?" — if the answer is easy, the goal needs a second metric.
Why learn
Strange assistant behaviors — flattery, verbosity, "fixed" tests — make sense when you read them as reward hacking. If you are going to fine-tune models or evaluate agents, designing the reward and the independent metric is the part of the project that requires the most human judgment.
Key concepts
👥 RLHF: learning from preferences
“Be useful, honest, and polite” doesn’t fit into a formula. The solution of RLHF (reinforcement learning from human feedback, RL from human feedback) was to turn human judgment into a reward. The method became known through the paper “Training language models to follow instructions with human feedback” (Ouyang et al., 2022), which introduced InstructGPT. It became the basis for training the assistants that came later.
There are three stages. First, supervised fine-tuning (SFT) with examples of good responses. Then, people compare pairs of responses and choose the better one; those comparisons are used to train a reward model, which learns to predict human preferences. Finally, the model is optimized with RL (originally PPO) to maximize that score, with a KL penalty —a measure of how far it has moved from the original model—that prevents it from “drifting” toward strange responses approved only by the reward model.
What it is
RLHF fine-tunes a language model with RL, using a model trained on human comparisons of responses as the reward, with a constraint that keeps it close to its original behavior.
Constitutional AI
Proposed by Anthropic in 2022 (Bai et al.): a set of written principles guides a model in critiquing and comparing responses, reducing reliance on human labels for safety.
DPO
“Direct Preference Optimization” (Rafailov et al., 2023) showed that you can optimize preferences with a simple classification loss, without explicit RL. It became popular because it is easy to use.
Common limitation
Preference isn’t truth. People prefer confident, long responses that agree with them—and the model learns that, too. That leads to the sycophancy covered in the previous topic.
Why learn
RLHF explains assistants’ “personalities”: their tone, refusals, and tendency to agree. If you plan to fine-tune an open model with your own data, understanding the three stages and the variants can help you choose the least expensive option that works—often DPO with a few hundred or thousand carefully selected pairs, instead of a full RL pipeline.
Key concepts
✅ RL with verifiable rewards
Human preference is expensive and subjective. But for many tasks, there’s a better judge: an automated verifier. A math problem has a final answer you can check; a program either passes the tests or it doesn’t; an SQL query either returns the expected result or it doesn’t. RL with verifiable rewards (in English, RL with verifiable rewards, RLVR) uses that result as the reward—with no learned reward model in between.
The method popularized in this wave is GRPO (Group Relative Policy Optimization), introduced in the DeepSeekMath paper (2024): for each problem, the model generates a group of responses, the verifier scores each one, and training reinforces the responses that score above the group average. This removes PPO’s “critic” and makes the process less expensive. The verifier is the critical piece: if it has loopholes, the model will find them—that’s the reward hacking from Topic 3, in an automated form.
What it is
RLVR trains a model through reinforcement learning using a program-checked result as the reward—such as a correct answer, passing tests, or a valid format. It generates several attempts per problem and reinforces the ones that perform best.
Try this: two real, verifiable rewards and one case of reward hacking caught by hidden tests (Python 3, no dependencies).
# recompensa_verificavel.py — rewards a program can verify (Python 3, no dependencies)
import re, subprocess, sys, tempfile
from fractions import Fraction
def para_numero(texto):
return Fraction(texto.replace(",", ".").strip().rstrip("."))
def recompensa_matematica(saida, gabarito):
"""1.0 if the last 'Resposta: X' matches the answer key; 0.0 if it is wrong or doesn't follow the format."""
achados = re.findall(r"Resposta:\s*(-?[\d.,/]+)", saida)
if not achados:
return 0.0
try:
return 1.0 if para_numero(achados[-1]) == para_numero(gabarito) else 0.0
except (ValueError, ZeroDivisionError):
return 0.0
def recompensa_codigo(codigo, testes, timeout=5):
"""Fraction of tests (asserts) that pass. In production, run in an isolated sandbox."""
script = codigo + "\n\nok = 0\n"
for t in testes:
script += f"try:\n {t}\n ok += 1\nexcept Exception:\n pass\n"
script += "print(ok)\n"
with tempfile.NamedTemporaryFile("w", suffix=".py", delete=False) as f:
f.write(script)
try:
r = subprocess.run([sys.executable, f.name], capture_output=True, text=True, timeout=timeout)
return int(r.stdout.strip().splitlines()[-1]) / len(testes)
except (subprocess.TimeoutExpired, ValueError, IndexError):
return 0.0
if __name__ == "__main__":
print("math correct:", recompensa_matematica("I added the parts. Resposta: 3/4", "0.75"))
print("math format :", recompensa_matematica("I think it's 0,75", "0.75"))
testes = ["assert soma([1, 2, 3]) == 6", "assert soma([]) == 0"]
honesto = "def soma(xs):\n return sum(xs)"
trapaca = "def soma(xs):\n return {3: 6, 0: 0}[len(xs)]" # memorized the tests
print("honest :", recompensa_codigo(honesto, testes))
print("cheating :", recompensa_codigo(trapaca, testes))
ocultos = testes + ["assert soma([5, 5]) == 10", "assert soma([-1, 1]) == 0"]
print("cheating w/ hidden tests:", round(recompensa_codigo(trapaca, ocultos), 2))
How to check: run python3 recompensa_verificavel.py. The expected output is 1.0, 0.0, 1.0, 1.0 e 0.5. Look at the fourth line: the "cheating" code memorized the visible tests and got a perfect score. Only the hidden tests (last line) reveal the problem—that's why RL verifiers keep tests the model never sees.
Why learn
Verifiable rewards are why models have improved so much at math and programming, areas where there is an answer key. For a company, the practical lesson is: if your task has a reliable verifier (tests, checkable business rules, a verifiable result), it's a candidate for automated evaluation—and, ultimately, reinforcement fine-tuning.
Key concepts
🧠 Why RL made models reason
In September 2024, OpenAI released o1, presented as a model trained with RL to “think before answering”: it produces a long internal chain of reasoning before the final answer. In January 2025, the paper on DeepSeek-R1 openly described a similar recipe and released the model weights. The most discussed point: in a version trained only with RL and verifiable rewards (R1-Zero), the model began writing longer reasoning and reviewing its own steps without anyone having shown it examples of this behavior.
The intuitive explanation: when the reward depends only on getting the final answer right, any behavior that increases the chance of success—breaking down the problem, testing a hypothesis, backtracking—is reinforced. This opened a new avenue for improvement, inference-time compute (test-time compute): spending more compute thinking while answering, instead of just training larger models. The debate remains open: 2025 papers discuss whether RL creates new capabilities or mainly makes the base model's existing capabilities more reliable. For business decisions, the practical consequence is the same—reasoning models cost more per response and are worth it for multistep tasks.
What it is
This is the shift of 2024–2025: applying RL with verifiable rewards to language models produced long, useful reasoning chains and turned “thinking time” into a quality and cost control.
2015 · DQN in Nature — a neural network learns to play dozens of Atari games from pixels and scores.
2016 · AlphaGo — beats Lee Sedol at Go by combining networks, search, and RL; in 2017, AlphaGo Zero learns solely by playing against itself.
2017 · PPO — a stable algorithm that becomes the standard and is later used in RLHF.
2022 · InstructGPT and ChatGPT — RLHF turns language models into assistants.
2024 · o1 — a reasoning model trained with RL; thinking time becomes a quality parameter.
2025 · DeepSeek-R1 — an open recipe using RL and verifiable rewards; reasoning models spread across labs.
2025–2026 · RL in agents — the environment becomes a code repository, a browser, or an entire computer; the reward comes from completed tasks and tests.
🔎 Terms
Reasoning model is a model trained to generate intermediate steps before the final answer. Reasoning budget is the limit on tokens or effort you allow for these steps — several providers expose this kind of control in their API. Base model is the model after pretraining, before any fine-tuning or RL.
💡 Tip
Treat reasoning effort like a cost dial. Measure quality on your evaluation set at low, medium, and high effort; many simple tasks (classifying, extracting, summarizing) don’t improve with more reasoning, and cost more as a result.
Why learn
Choosing between a fast model and a reasoning model is now one of the architecture decisions with the greatest impact on cost and quality. Understanding where reasoning comes from — RL with a verifier — helps you predict where it helps (tasks with multiple steps and an answer key) and where it’s wasteful.
Key concepts
🏢 RL at your company
Most companies will use RL — by using models that have already gone through it — rather than training with RL. Still, there are three situations where in-house RL comes into the picture: sequential decisions with a simulator (inventory, dynamic pricing, routing, industrial control); fine-tuning a language model for a task with a clear verifier; and training agents in a custom environment, with tasks that end in checkable success or failure.
The tools are mature: Gymnasium for defining environments, Stable-Baselines3 for classic algorithms such as PPO and DQN, and the Hugging Face library TRL for fine-tuning language models with SFT, DPO, and GRPO. Some providers of closed models also offer reinforcement fine-tuning as a service; availability, supported models, and prices change, so check before planning. The cost that’s almost always underestimated isn’t the GPU: it’s building the environment, the verifier, and the independent evaluation.
What it is
One decision rule: use RL only when there are sequential decisions or a reliable verifier, when simpler alternatives (prompting, RAG, SFT, DPO) have already been measured and aren’t enough, and when there’s a budget for the environment and evaluation.
✓ Signs RL makes sense
- ✓There’s a simulator or safe environment where the system can fail thousands of times.
- ✓Success can be checked by a program, without relying on opinion.
- ✓Prompting, RAG, and supervised fine-tuning have already been measured and have plateaued.
- ✓There’s a team to maintain the environment and audit behavior.
✗ Signs it’s not the right time
- ✗The only way to test is with real customers.
- ✗“A good response” depends on taste and changes every week.
- ✗There’s no in-house evaluation set yet.
- ✗The motivation is “a competitor announced they use RL.”
Goal: evaluate with an assistant whether a use case justifies RL before spending on it.
You are a skeptical ML architect who prefers the simplest solution that works. Use case: <describe the task, who uses it, and what decision the system makes> Available data: <what exists today: histories, logs, labeled examples> What’s already been tried and the measured result: <prompting, RAG, fine-tuning... or “nothing”> Respond in sections: 1. Formulate it as RL: what would the agent, environment, state, actions, and reward be? If any piece isn’t clearly defined, say so first. 2. Verifier: can the reward be checked by a program? How could someone game it? 3. Simpler alternatives, ordered by cost (prompting, RAG, SFT, DPO, RL), with what each would need to solve the case. 4. Environment: can it be simulated safely? What would it cost to build and maintain? 5. Independent evaluation: what metric does the agent NOT see that would reveal reward hacking? 6. Risks: safety, LGPD (Brazil’s data protection law, if there’s personal data), and the impact of an error in production. Verdict: DO NOT USE RL / TEST AN ALTERNATIVE FIRST / RL PILOT, with 3 next steps. Don’t invent cost or gain figures; mark them as “to be measured.”
How to check: A good analysis identifies at least one concrete way to game the reward (item 2) and one independent metric (item 5). If the verdict is “RL pilot” without items 1 and 2 being clear, the analysis is too optimistic — ask for a reassessment starting with the cheapest alternative.
Why learn
RL is at the center of AI news, creating pressure to “use RL.” A leader who knows the conditions under which it works protects the team’s budget, chooses the cheaper alternative when it’s enough, and recognizes the rare case where an environment with a verifier becomes a competitive advantage.
Key concepts
✅ Module summary
Next module:
3.6 — Safety and Red Teaming 🛡️