Foundations to Frontier
Tests

The reinforcement learning problem and the agent–environment loop

In reinforcement learning an agent learns to act by trial and error: it observes the state of an environment, chooses an action, and receives a reward and the next state. Its goal is to maximise the total reward over time. This page sets up the agent–environment loop in the Gymnasium style, defines policies, episodes and returns, and shows with an exhaustive search that an agent optimises exactly the reward it is given, which is not always the task its designer meant.

Level 0: Foundation

★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.

Learning by trying

A child learning to ride a bicycle is not given a list of correct movements. They try, wobble, fall, and slowly find what works. Reinforcement learning works the same way: a program tries actions, gets a score called a reward, and learns which actions lead to high scores. The tricky part is choosing the score: the program will do whatever earns the most points, even if that is not what you wanted.

Reinforcement learning lab
Corridor of 7 cells, start in cell 3, goal in cell 6 (+10), −0.1 per step, at most 50 steps; with probability 0.1 the chosen move is reversed. The plot is the first episode's position. Over 300 episodes the policy “always right” earns mean return 9.62, reaches the goal 100.0% of the time and takes 3.8 steps on average.
Why engineers care

Reinforcement learning taught programs to play Go and chess at world-champion level, and to control robots, data-centre cooling and chip layouts.

📝 Quick check (Level 0)
0/3 answered
  1. 1. In reinforcement learning, the program learns from…
  2. 2. The agent tries to make the total reward…
  3. 3. A badly chosen reward can make the agent…

Level 1: Beginner

★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.

By hand

  • Agent: the learner and decision maker. Environment: everything it interacts with.
  • State s_t: what the agent observes at time t. Action a_t: what it does. Reward r_(t+1): a number it receives after acting.
  • Loop: observe s_t → choose a_t → environment returns r_(t+1) and s_(t+1) → repeat.
  • Episode: one run from a start state until a terminal state (terminated) or a time limit (truncated).
  • Return: the sum of rewards over an episode, G = r_1 + r_2 + … + r_T.
  • Policy π: the agent’s rule for choosing actions; deterministic (a = π(s)) or stochastic (π(a|s)).
  • Reward hypothesis: every goal can be described as maximising the expected cumulative reward.
  • Reward shaping: extra rewards that guide learning; only potential-based shaping is guaranteed not to change the best policy.
📝 Quick check (Level 1)
0/3 answered
  1. 1. A policy maps…
  2. 2. An episode that hits the time limit is…
  3. 3. The return of an episode is…

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 25 minUndergraduate students and practising engineers.

Writing the loop

Exercise 1.

  • A 7-state corridor in the Gymnasium style (reset, step returning state, reward, terminated, truncated).
  • Start in the middle, goal at the right end worth +10, a cost of 0.1 per step, at most 50 steps.
  • Run the always-right, always-left and random policies.

Practice.

  • Use the Gymnasium API: reset() returns the first observation; step(a) returns observation, reward, terminated, truncated and info.
  • Separate terminated from truncated: a time limit is not a real end state, and learning algorithms treat them differently.
  • Start with the simplest reward that says what success is; add shaping only if learning fails, and prefer potential-based shaping.
  • Watch the agent, not only the reward curve: reward hacking shows up as strange behaviour.
  • Evaluate with many episodes and report the spread, because returns are noisy.
  • Tools: Gymnasium, PettingZoo for multiple agents, Stable-Baselines3 for algorithms.
import gymnasium as gym

env = gym.make("CartPole-v1")
obs, info = env.reset(seed=0)
done, G = False, 0.0
while not done:
    action = env.action_space.sample()      # a random policy
    obs, r, terminated, truncated, info = env.step(action)
    G += r; done = terminated or truncated
🐍 Exercise 1: an environment and the agent–environment loop
Write a corridor environment with reset and step, and a loop that runs a policy for one episode and returns its return, length and success.
📝 Quick check (Level 2)
0/3 answered
  1. 1. In Gymnasium, step() returns…
  2. 2. Shaping that cannot change the best policy is…
  3. 3. Reward hacking is best spotted by…

Level 3: Advanced

★★★★☆ Advanced⏱ 25 minGraduate level, with full derivations and proofs.

Theory

Formal setting. At each step the environment is in state s_t; the agent picks a_t ~ π(·|s_t); the environment draws r_(t+1) and s_(t+1) from its dynamics. The objective is J(π) = E_π[G], the expected return. Because the agent’s actions change which states it sees, the data are not independent and identically distributed, which separates reinforcement learning from supervised learning.

Exploration and credit assignment. The agent only sees rewards for actions it actually tried, so it must explore; and a reward may arrive many steps after the action that earned it, so it must assign credit backwards in time. Both problems return throughout this section.

Why potential-based shaping is safe. With F(s, s’) = γΦ(s’) − Φ(s), the shaping collected along any trajectory telescopes: with γ = 1 it equals Φ(s_T) − Φ(s_0). Every policy gains the same amount once it reaches the goal, and loops gain nothing, so the ranking of policies is unchanged (Ng, Harada and Russell 1999). A bonus that rewards progress but does not charge for going back does not telescope, so a loop can collect it forever.

📝 Quick check (Level 3)
0/3 answered
  1. 1. Reinforcement learning data are not i.i.d. because…
  2. 2. Credit assignment is about…
  3. 3. Potential-based shaping along a trajectory sums to…

Level 4: Expert

★★★★★ Expert⏱ 30 minResearchers: original papers and open problems.

If an agent finds the best policy for a reward, does that policy do the intended task? Compare a sparse goal reward, a respawning coin, a naive progress bonus and potential-based shaping on the same corridor.

History.

  • R. S. Sutton and A. G. Barto (1998, 2018) set out the agent–environment framework of modern reinforcement learning; its roots go back to animal learning (E. L. Thorndike’s law of effect, 1911) and optimal control (R. Bellman, 1957).
  • A. Y. Ng, D. Harada and S. Russell (1999) proved that potential-based shaping preserves optimal policies.
  • D. Amodei and colleagues (2016) listed reward hacking among the concrete problems of AI safety; OpenAI’s CoastRunners boat, which circled to collect points instead of finishing the race, is a well-known example.
  • G. Brockman and colleagues (2016) released OpenAI Gym, continued as Gymnasium (M. Towers and colleagues, 2024).

Exercise 2.

  • The 7-state corridor of Exercise 1 with slip probability 0.1 (the action is reversed one time in ten).
  • The task: reach the right end. Four rewards for the same task: sparse (+10 at the goal, −0.1 per step); coin (plus +1 whenever the agent enters state 1, the coin respawning); progress (plus 0.5 for every step to the right); potential (plus 0.5 s’ − 0.5 s).
  • All 64 deterministic policies on states 0–5 are evaluated on 300 episodes each with the same random numbers; for each reward the policy with the highest estimated return is chosen.

Seed 0:

reward best policy (states 0–5) its estimated return reaches the goal steps
sparse RRRRRR 9.63 100% 3.6
coin RLLLLL 18.08 0% 50
progress RLRRRL 12.76 88.7% 21.3
potential RRRRRR 11.13 100% 3.6
  • The coin reward was hacked completely: the best policy shuttles between states 0 and 1, collecting the coin every second step, and never reaches the goal.
  • The progress bonus was hacked partly: the policy steps back from state 5 to 4 to earn the bonus again, and reaches the goal only when a slip pushes it there, taking six times as long.
  • Potential-based shaping kept the sparse optimum, adding exactly 1.5 (Φ(6) − Φ(3)) to its return.
  • Seeds 1 and 2 gave the same picture: the coin policy RLLLLL never reached the goal (designed return 18.15 and 18.14); the progress policy reached it 84.3% and 89.7% of the time in about 22 steps; sparse and potential chose the same policy in both.
🐍 Exercise 2 (research): if an agent finds the best policy for a reward, does that policy do the intended task? Compare a sparse goal reward, a respawning coin, a naive progress bonus and potential-based shaping on the same corridor.
Evaluate every deterministic policy on a slippery corridor under four reward designs for the same task, pick the best policy for each, and check whether it actually completes the task.

Reinforcement learning in practice

  • Reward design is engineering: many real projects spend more time on rewards, resets and safety limits than on the learning algorithm.
  • Simulators (MuJoCo, Isaac Sim) let agents fail safely millions of times before touching a real robot.
  • Learning from preferences: when a good reward is hard to write, humans can compare behaviours instead, as in reinforcement learning from human feedback.
  • The rest of this section builds the tools: Markov decision processes, value functions, Bellman equations, and algorithms that learn without trying every policy.

References

  1. R. S. Sutton and A. G. Barto (2018). Reinforcement Learning: An Introduction, 2nd edition. MIT Press.
  2. A. Y. Ng, D. Harada and S. Russell (1999). “Policy invariance under reward transformations: theory and application to reward shaping.” ICML.
  3. D. Amodei, C. Olah, J. Steinhardt, P. Christiano, J. Schulman and D. Mané (2016). “Concrete problems in AI safety.” arXiv:1606.06565.
  4. G. Brockman et al. (2016). “OpenAI Gym.” arXiv:1606.01540.
  5. M. Towers et al. (2024). “Gymnasium: a standard interface for reinforcement learning environments.” arXiv:2407.17032.