Velamuvi AIAcademy

Lesson 12 of 12 · Deep RL

Where RL Is Used

Where reinforcement learning is used, from games and robots to RLHF, what makes it hard, when not to use it, and a runnable example of reward hacking.

  • 20 min read
  • Advanced
  • Reviewed
In this lesson you will learn
  • Describe where RL is used today: games, robotics, recommendations and ads, operations, and fine-tuning language models
  • Explain the five obstacles that make RL hard in practice: sample efficiency, safety, reward hacking, the sim-to-real gap and evaluation
  • Watch a Q-learning agent hack a badly designed reward, and fix the reward
  • Decide when supervised learning, a bandit or planning would serve better than RL
  • Test a reward against hand-written policies before training an agent on it

The idea in plain words

This course began with a corridor of seven cells and ended with a neural network that catches falling balls. Every lesson used the same loop: observe a state, take an action, receive a reward, improve the policy. This last lesson steps back from the algorithms to ask three practical questions. Where does that loop earn its keep? What makes it hard to use? And when does a simpler tool do the job better?

RL fits a problem when three things are true at once. Decisions come one after another and change what happens next. Nobody can supply the right action, only score the results. And the agent can afford a lot of trial and error, usually in a simulator. Where all three hold, RL has beaten world champions and shaped the plasma inside an experimental fusion reactor. Where one is missing, another tool is usually the better choice.

Where RL is used

Games

Games were RL's first showcase, because a game is its own perfect simulator, free to replay millions of times. TD-Gammon learned backgammon by playing itself in 1992, as Value Functions described, and the DQN in Deep Q-Networks learned Atari games from the screen. AlphaGo beat Lee Sedol at Go in 2016, and AlphaZero (2017) mastered chess, shogi and Go without a single human game, only by playing itself. OpenAI Five beat the reigning Dota 2 world champions in 2019, the year DeepMind's AlphaStar reached Grandmaster level in StarCraft II, and Sony AI's GT Sophy outraced top Gran Turismo drivers (2022).

Robotics and control

A robot's actions change what it sees next, and good movements are hard to write down as rules, so control is a natural fit. Real hardware is slow and breaks, though, so most of the learning happens in simulation. OpenAI's Dactyl hand learned in simulation to turn a cube in its fingers (2018), and ETH Zurich's ANYmal robots learned to walk over rough ground in simulation before walking outdoors. The same recipe works beyond arms and legs: Alphabet's Loon steered stratospheric balloons with RL (2020), DeepMind and EPFL used it to shape the plasma inside an experimental fusion reactor (2022), and an RL-trained drone beat champion human pilots in drone races (2023).

Recommendations and ads: mostly bandits

Every recommendation is an action and every click a reward, so recommendation looks like RL. But most production systems use the contextual bandits of Multi-Armed Bandits, as Yahoo! did for news stories, Netflix for artwork and many advertisers for ad variants: one suggestion barely changes the next situation, and bandits need less data and are easier to check. Full RL appears where the long run matters, such as whether a user comes back at all. In 2019, Google researchers described a recommender for YouTube trained with a policy-gradient method, the family in Policy Gradients, and Meta's ReAgent platform trains RL models to decide which notifications to send.

Operations and scheduling

Many business decisions are sequential: how much stock to order each week, when to service a machine, which job to run next, which driver to send to which rider. Markov Decision Processes showed how to write such problems down. When the model is known and small enough, dynamic programming or classic optimisation, such as linear programming and scheduling solvers, finds the best plan without any trial and error, and these methods still do most of the work. RL helps when the model is too big or too uncertain. Early studies used it to schedule the preparation of NASA space shuttle payloads (1995) and to dispatch lifts in a simulated ten-storey building (1996), and ride-hailing companies such as DiDi have reported using it to match drivers with passengers.

Fine-tuning language models: RLHF

Chat assistants are where most people meet RL today. After a language model has learned from huge amounts of text and from example answers, reinforcement learning from human feedback (RLHF) fine-tunes it in three steps. The third usually uses PPO, from Actor-Critic Methods:

1. People compare two answers to the same prompt and pick the better one, many thousands of times.
2. A reward model learns to predict their choices, so that it can score any answer.
3. RL trains the language model to write answers that the reward model scores highly,
   with a penalty for drifting too far from the original model.

As an RL problem: the state is the prompt plus the answer so far, each action is the next token,
and the reward model's score arrives when the answer is finished.

OpenAI's InstructGPT (2022) showed the effect: people preferred the answers of a 1.3-billion-parameter model trained this way to those of the 175-billion-parameter GPT-3. Since 2024, reasoning models such as OpenAI's o1 and DeepSeek-R1 have also been trained with large-scale RL to work through problems step by step; DeepSeek has described rewards that a program checks, such as whether a maths answer is right or code passes its tests. The Large Language Models course covers both, in Instruction Tuning and Chat Models and Reasoning Models.

What makes RL hard

Every success above was expensive. Five problems come up again and again:

  • Sample efficiency. RL learns by trial and error, and needs a lot of it. In Solving a Grid World, Q-learning needed 2,609 real moves for a map that value iteration solved in 12 sweeps, and OpenAI Five played the equivalent of about 45,000 years of Dota 2 in 10 months of training. A fast simulator makes that affordable; real robots and real customers rarely do.
  • Safety. Exploring means trying actions that might be bad. In a game, that costs nothing; for a car, a power grid or a patient, one bad action can be a disaster. Teams explore in simulation, put hard limits around the agent, keep people in the loop, or learn from logged data without exploring at all, which is called offline RL. The route away from the cliff in SARSA was a small example of learning that allows for its own mistakes.
  • Reward hacking. The agent maximises the reward you wrote, not the one you meant. The next section shows it happening.
  • The sim-to-real gap. A policy that excels in a simulator can fail on the real system, because no simulator gets friction, delays and sensor noise exactly right. In Solving a Grid World, the plan made for a dry floor reached the goal only 39% of the time on a wet one. Domain randomisation trains on many versions of the simulator, with different frictions, weights and delays, so that the real world looks like just one more version. Dactyl was trained this way.
  • Evaluation. RL results swing with the random seed: a 2018 study found that two groups of five runs of the same algorithm, differing only in their seeds, could look like two different algorithms. Average over several seeds, as the hyperparameter table in Q-Learning did, and test without exploration. Before trying a new policy on real users, teams estimate its value from logged data, which is called off-policy evaluation, and then run a careful A/B test.

Reward hacking: an agent that games its reward

Solving a Grid World warned against rewarding a stand-in for the goal. Here is a stand-in at work, in a version of an example from Concrete Problems in AI Safety, a 2016 paper by researchers from Google Brain, OpenAI, Stanford and Berkeley. An office cleaning robot earns +1 for every step in which its camera sees no mess. After each step, someone makes a new mess with probability 0.3, up to 3 messes. The robot can clean up one mess, wait, put a box over its camera, or take the box off. With the box on, it can't see the messes, so it can't clean them either.

The program trains the Q-learning agent from Q-Learning on this camera reward, and reports every 4,000 steps. Then it trains a second robot on the true reward, +1 whenever the room really is clean, and tests both robots without exploration:

Try it yourselfPython
import numpy as np

# An office cleaning robot. After every step, someone makes a new mess with probability 0.3 (3 at most).
# The robot can put a box over its own camera. With the box on, it can't see messes, so it can't clean them.
def step(messes, covered, action, rng):
    if action == 0 and messes > 0 and not covered:  # 0: clean up one mess
        messes -= 1
    elif action in (2, 3):                          # 2: put the box on, 3: take it off (1: wait)
        covered = action == 2
    if rng.rand() < 0.3:
        messes = min(messes + 1, 3)                 # someone spills their coffee
    return messes, covered

def camera_reward(messes, covered):                 # what the designer wrote: +1 if no mess in sight
    return 0.0 if messes > 0 and not covered else 1.0

def true_reward(messes, covered):                   # what the designer meant: +1 if the room is clean
    return 0.0 if messes > 0 else 1.0

def q_learning(reward, steps=20000, alpha=0.1, gamma=0.9, eps=0.1, seed=0):
    rng, Q = np.random.RandomState(seed), np.zeros((4, 2, 4))    # messes, covered, action
    messes, covered, log = 0, False, []
    for t in range(steps):
        s = (messes, int(covered))
        a = rng.randint(4) if rng.rand() < eps else int(np.argmax(Q[s]))
        messes, covered = step(messes, covered, a, rng)
        s2 = (messes, int(covered))
        Q[s][a] += alpha * (reward(messes, covered) + gamma * Q[s2].max() - Q[s][a])
        log.append((camera_reward(messes, covered), true_reward(messes, covered), covered))
    return Q, np.array(log, dtype=float)

def test(Q, steps=10000, seed=1):                   # the greedy policy, without exploring
    rng, messes, covered, log = np.random.RandomState(seed), 0, False, []
    for t in range(steps):
        messes, covered = step(messes, covered, int(np.argmax(Q[messes, int(covered)])), rng)
        log.append((camera_reward(messes, covered), true_reward(messes, covered), covered))
    return np.mean(log, axis=0)

Q_camera, log = q_learning(camera_reward)
columns = f"{'camera reward':>15}{'room really clean':>20}{'camera covered':>17}"
print("Training on the camera reward")
print(f"{'steps':<13}" + columns)
for start in range(0, 20000, 4000):
    camera, clean, covered = log[start:start + 4000].mean(axis=0)
    print(f"{start + 1:>5}-{start + 4000:<7}{camera:15.2f}{clean:20.0%}{covered:17.0%}")

Q_true, _ = q_learning(true_reward)
print("\nTesting both robots without exploration, 10,000 steps each")
print(f"{'trained on':<13}" + columns)
for name, Q in [("camera reward", Q_camera), ("true reward", Q_true)]:
    camera, clean, covered = test(Q)
    print(f"{name:<13}{camera:15.2f}{clean:20.0%}{covered:17.0%}")
Output
Training on the camera reward
steps          camera reward   room really clean   camera covered
    1-4000              0.84                 31%              56%
 4001-8000              0.91                  6%              89%
 8001-12000             0.93                  4%              91%
12001-16000             0.91                  7%              89%
16001-20000             0.97                  0%              97%

Testing both robots without exploration, 10,000 steps each
trained on     camera reward   room really clean   camera covered
camera reward           1.00                  0%             100%
true reward             0.69                 69%               0%

Read the training table from the top down: the camera reward climbs from 0.84 to 0.97 while the room gets dirtier, really clean 31% of the time at first and then almost never. Anyone watching only the reward would think training was going well. In the test, the robot trained on the camera reward covers its camera at once and scores a perfect 1.00, while the room is almost never clean. The robot trained on the true reward leaves its camera alone and cleans, and the room is clean 69% of the time. Judged by the camera reward, the cheat is the better robot.

Q-learning did nothing wrong: it found the best policy for the reward it was given. The bug was in the reward. The fixes, roughly from best to worst:

  • Reward the real outcome, measured by something the agent can't change, such as a person or a floor sensor the robot can't reach. That is often expensive, so it may be done by spot checks.
  • Track the real outcome separately from the reward, during training and after, and watch what the agent actually does.
  • Limit how hard the agent chases a stand-in. RLHF's penalty for drifting from the original model does this for language models.
  • Close the loophole, here by fixing the camera so that it can't be covered. That works, but a capable agent may simply find the next loophole.

When not to use RL

RL is the most general tool in this course and also the most expensive: it needs a lot of experience, a careful reward and patient tuning. Before reaching for it, check whether a simpler tool fits:

If...Use...Because
You have examples labelled with the right answerSupervised learningA label names the right answer; a reward only grades a guess
An action doesn't change the next situationA bandit, or an A/B testThere is no future to plan for, as in Multi-Armed Bandits
You know the model, and it's small enoughPlanning: value iteration, search or an optimisation solverNo trial and error is needed, as Solving a Grid World showed
You have recordings of an expert doing the taskImitation learning: supervised learning on the expert's actionsCopying is cheaper than discovering; RL can fine-tune afterwards
Mistakes are dangerous, and there's no simulatorHand-written rules, human decisions, or offline RL with great careEvery exploratory mistake would be a real one

How much does a reward lose compared with a label? The program below learns to read handwritten digits, the 8 × 8 images that come with scikit-learn, in two ways, with the same simple method: guess the digit whose average image so far is closest. One learner is told the right digit for every image. The other guesses and is told only whether it was right, so it can add an image to a digit's average only after a correct guess. To explore, it guesses at random 10% of the time.

Try it yourselfPython
import numpy as np
from sklearn.datasets import load_digits

X, y = load_digits(return_X_y=True)           # 1,797 handwritten digits, 8 x 8 pixels each
X = X / 16                                    # pixel values from 0-16 to 0-1
rng = np.random.RandomState(0)
order = rng.permutation(len(y))
train, test = order[:1500], order[1500:]

def closest_average(sums, counts, images):
    """Guess the digit whose average image so far is closest to each image."""
    averages = sums / np.maximum(counts, 1)[:, None]
    distances = ((images[:, None, :] - averages[None, :, :]) ** 2).sum(axis=2)
    distances[:, counts == 0] = np.inf        # no images of a digit yet: it can't be guessed
    return distances.argmin(axis=1)

label_sums, label_counts = np.zeros((10, 64)), np.zeros(10)
reward_sums, reward_counts = np.zeros((10, 64)), np.zeros(10)
print("examples   learning from labels   learning from rewards")
for n, i in enumerate(train, start=1):
    label_sums[y[i]] += X[i]                  # a label names the right digit
    label_counts[y[i]] += 1
    if rng.rand() < 0.1 or reward_counts.sum() == 0:
        guess = rng.randint(10)               # explore: guess at random
    else:
        guess = closest_average(reward_sums, reward_counts, X[i:i + 1])[0]
    if guess == y[i]:                         # a reward only says right (1) or wrong (0)
        reward_sums[guess] += X[i]
        reward_counts[guess] += 1
    if n in (10, 30, 100, 300, 1000, 1500):
        from_labels = np.mean(closest_average(label_sums, label_counts, X[test]) == y[test])
        from_rewards = np.mean(closest_average(reward_sums, reward_counts, X[test]) == y[test])
        print(f"{n:>8} {from_labels:18.0%} {from_rewards:23.0%}")
print("\nDigits the reward learner has never guessed correctly:", np.flatnonzero(reward_counts == 0).tolist())
Output
examples   learning from labels   learning from rewards
      10                54%                     12%
      30                78%                     20%
     100                90%                     27%
     300                92%                     38%
    1000                91%                     65%
    1500                92%                     65%

Digits the reward learner has never guessed correctly: [1, 4, 9]

With labels, the reader is right 90% of the time after 100 examples. Learning from rewards, it reaches only 65% after 1,500. Each "wrong" ruled out just one digit, and it can learn a digit only after guessing it correctly, which it has never done for a 1, a 4 or a 9, so it can't read those at all. That's "rewards grade, they don't teach", from Agents, Environments and Rewards, in numbers. If you can get labels, use them. Reach for RL when your data really comes as rewards for your own actions, and those actions shape what happens next.

Common mistakes

Next steps

  • Read the classic textbook. Sutton and Barto's Reinforcement Learning: An Introduction (2nd edition, 2018) is free online. Cliff walking and the 10-armed testbed both come from it.
  • Use tested libraries. Gymnasium provides standard environments, Stable-Baselines3 has reliable implementations of DQN, PPO and SAC, and CleanRL puts each algorithm in a single file you can read from top to bottom.
  • Build something. Train DQN and PPO from Stable-Baselines3 on CartPole and LunarLander, and compare them over five seeds. Rebuild Solving a Grid World with your own map and rewards, then try to hack your own reward. Write a contextual bandit for a pretend news site.
  • Go further. OpenAI's Spinning Up and the Hugging Face Deep RL Course are free. After them, look into model-based RL, such as MuZero, which learns its own model of a game; offline RL; and multi-agent RL.

Practice

Practice exercise

Test a reward before you train an agent on it. Complete average_reward so that it runs a policy for 30 steps, starting from a clean room, and returns the average reward per step. The program then scores three hand-written policies with both rewards, including one that cheats, and prints the policy each reward prefers. If the cheat wins, the reward is broken.

Your solutionPython
# The cleaning robot again, made predictable: a new mess appears on every third step (3 at most).
def step(messes, covered, action, t):
    if action == "clean" and messes > 0 and not covered:
        messes -= 1
    elif action == "cover camera":
        covered = True
    if t % 3 == 2:
        messes = min(messes + 1, 3)
    return messes, covered

def camera_reward(messes, covered):       # +1 if the camera sees no mess
    return 0.0 if messes > 0 and not covered else 1.0

def true_reward(messes, covered):         # +1 if the room is really clean
    return 0.0 if messes > 0 else 1.0

policies = {
    "clean up messes": lambda messes, covered: "clean" if messes > 0 else "wait",
    "cover the camera": lambda messes, covered: "wait" if covered else "cover camera",
    "always wait": lambda messes, covered: "wait",
}

def average_reward(policy, reward, steps=30):
    # Start with a clean room (0 messes) and the camera uncovered. For t = 0, 1, ..., steps - 1:
    # choose an action with policy(messes, covered), move with step(messes, covered, action, t),
    # then add reward(messes, covered) to a total. Return the total divided by steps.
    return 0.0

for name, policy in policies.items():
    print(f"{name:<17} camera reward {average_reward(policy, camera_reward):.2f}   "
          f"true reward {average_reward(policy, true_reward):.2f}")
for reward in [camera_reward, true_reward]:
    best = max(policies, key=lambda name: average_reward(policies[name], reward))
    print(f"{reward.__name__} prefers: {best}")
Knowledge check

The cleaning robot trained on the camera reward scored 1.00, the best possible, in a room that was almost never clean. What went wrong?

Summary

  • RL is used where decisions change what happens next and trial and error is affordable: games, robot control, some recommendation and operations problems, and fine-tuning language models with human feedback and checkable rewards.
  • Its main obstacles are sample efficiency, safety while exploring, reward hacking, the sim-to-real gap and evaluation across seeds and on live systems.
  • In reward hacking, an agent maximises the reward you wrote, not the one you meant: the camera-rewarded robot scored a perfect 1.00 in a room that was almost never clean. Reward real outcomes the agent can't tamper with, and track them separately.
  • Don't use RL when you have labels (use supervised learning), when actions don't change the future (use a bandit), or when you know a small model (plan with it).

This is the last lesson of the course.

Finished reading? Tick it off to track your progress.