Mental model
Reinforcement learning fits a policy to sequential feedback: an agent observes a state, chooses an action, and receives a reward and next state from its environment. Value functions estimate delayed return so one transition can improve decisions beyond its immediate reward. A high training return does not establish safety or future performance; those depend on the reward definition, data coverage, constraints, and rollout conditions.
Theory
For a Markov decision process, the environment is described by states (s), available actions (a), a transition distribution (P(s' \mid s,a)), a reward (r), and a discount factor (\gamma). A policy (\pi(a \mid s)) chooses actions. A trajectory is the resulting sequence of states, actions, and rewards. The return from time (t) is the discounted sum of future rewards:
Here (R_) is the next reward in reward points, (\gamma \in [0,1]) is dimensionless, and (T) is the terminal step in a finite episode. (G_t) is measured in discounted reward points. The state value (V^\pi(s)) is the expected return from state (s) when following policy (\pi); the action value (Q^\pi(s,a)) is the expected return after taking (a) once and then following (\pi). The Bellman equation expresses each value as immediate reward plus discounted successor value. Its expectation is over the environment's transition and the policy's next action.
Learning algorithms differ in how they estimate that expectation. Monte Carlo methods use complete returns and avoid bootstrapping, but must wait for episode outcomes and can have high variance. Temporal-difference methods update from a sampled transition and a current value estimate. In Q-learning, the next-state target uses the best estimated action, even when an exploratory behavior policy collected the transition; that makes it off-policy. SARSA instead uses the next action actually chosen by the behavior policy, so its target is on-policy. This distinction matters when exploring actions have different risk.
Policy-gradient methods optimize a parameterized action distribution directly. Actor-critic methods pair a policy (actor) with a value estimator (critic). PPO collects data from a policy snapshot and uses a clipped probability-ratio objective for multiple minibatch updates. The clipping discourages some overly large updates on sampled actions, but it is not a hard trust-region guarantee, a proof of monotonic improvement, or a safety constraint. The PPO paper describes an empirical method; deployment safety still needs separate validation and controls.
Worked example
Suppose a controller is in a state where it can inspect equipment before dispatch. Inspection costs 0.2 reward points now, and a successful dispatch is expected to return 2.0 future points. With (\gamma=0.9), the one-step bootstrapped target for inspection is (-0.2 + 0.9(2.0)=1.6) points. If the current estimate for that state-action pair is 1.0 and the learning rate is (\alpha=0.25), the update moves it to (1.0+0.25(1.6-1.0)=1.15) points. If inspection instead ended the episode, the target would be just (-0.2); bootstrapping through a terminal state invents future value that cannot occur.
The sampled one-step update is:
Here (d_) is 1 only when the transition truly terminates the task, and 0 otherwise. Both (\alpha) and (\gamma) are dimensionless; the target and (Q) are in reward points. A time-limit truncation is not always a terminal task state: if the task would continue, record truncation separately and bootstrap according to the evaluation protocol rather than masking the successor value by accident.
Trade-offs
| Method | Data and update target | Useful property | Main operational cost |
|---|---|---|---|
| Monte Carlo policy evaluation | Complete episodes and observed return | No value bootstrap in the target | Delayed updates and return variance |
| SARSA | Sampled transition and the behavior policy's next action | Learns values for its exploratory behavior | Data efficiency depends on the active policy |
| Q-learning | Sampled transition and greedy successor value | Can learn a greedy target from exploratory behavior | Off-policy data can poorly cover target actions |
| PPO | Fresh rollouts and clipped policy-ratio objective | Reuses one rollout for several optimizer passes | Old data becomes stale as the policy changes |
Reusing experience improves sample efficiency only when the target remains supported by the collected data. A replay buffer from an old policy can overrepresent familiar states and miss states the updated policy visits. Model-based planning can reduce interaction cost, but transition-model errors compound over long imagined horizons. More updates, larger networks, or a larger discount factor do not guarantee a better deployed policy.
Failure modes and misconceptions
- Reward hacking: The policy maximizes a proxy while harming the real objective. A robot rewarded for distance may learn to move unsafely; a scheduler rewarded for average latency may starve rare customers. Audit reward components against user-level outcomes and impose hard limits for safety-critical constraints.
- Coverage gaps: An off-policy estimator may score actions absent from the logged behavior data. Report state-action support and uncertainty; do not present an extrapolated value as measured evidence.
- Termination mistakes: Treating a time limit as a true terminal state biases value targets downward; bootstrapping across a genuine terminal state biases them upward.
- Distribution shift: A policy can exploit quirks in a simulator or historical logs that disappear when sensors, demand, or users change. Evaluate on held-out scenarios and monitor the same slices after launch.
- Exploration in production: Random exploratory actions can be unacceptable in control or financial settings. Collect exploration in a bounded simulator or approved experiment, then enforce an action shield and fallback policy in production.
Decision scenario
A cooling-system policy increases simulated energy savings, but a stress test shows that it occasionally exceeds the site's maximum temperature. The team should keep the baseline controller active, treat the temperature ceiling as a hard constraint rather than a reward penalty, and test the new policy on held-out demand and sensor-failure scenarios. A limited canary can proceed only behind an independent safety monitor that returns control to the baseline on a limit violation; higher average reward alone is not sufficient evidence to expand traffic.
Learning outcomes
- Derive a discounted return and a one-step Bellman target, including terminal masking.
- Distinguish on-policy SARSA, off-policy Q-learning, and PPO rollout reuse.
- Identify reward hacking, unsupported actions, termination errors, and deployment shift.
- Design a guarded evaluation and rollout that enforces hard operational constraints.
Implementation pattern
This executable tabular example uses a tiny inspection-and-dispatch environment to demonstrate epsilon-greedy Q-learning. The transition function is deliberately simple; it is not a plant model or a safe controller. Terminal transitions suppress the bootstrap term, and each episode has a step cap so a policy that keeps waiting cannot run forever.
pythonimport randomfrom collections import defaultdictrng = random.Random(7)q = defaultdict(lambda: [0.0, 0.0]) # actions: 0 = skip/wait, 1 = inspect/dispatchalpha, gamma = 0.25, 0.9def step(state, action):if state == 0:return (1, -0.2, False) if action == 1 else (2, -5.0, True)if state == 1:return (2, 2.0, True) if action == 1 else (1, -0.1, False)raise ValueError("terminal state has no outgoing action")for episode in range(500):state = 0epsilon = max(0.05, 1.0 - episode / 400)for _ in range(50):if rng.random() < epsilon:action = rng.randrange(2)else:best = max(q[state])action = rng.choice([i for i, value in enumerate(q[state]) if value == best])next_state, reward, terminal = step(state, action)bootstrap = 0.0 if terminal else max(q[next_state])target = reward + gamma * bootstrapq[state][action] += alpha * (target - q[state][action])if terminal:breakstate = next_stateprint("start action values:", [round(value, 2) for value in q[0]])
Before using a learned policy, evaluate on deterministic held-out seeds, report reward and constraint violations separately, and test sensor dropout and action-boundary cases. Keep the fallback and monitor outside the learned policy so a model cannot disable its own safety check.