Monte Carlo Control
Imagine teaching a robot to navigate a warehouse maze. It learns using only trial-and-error, with no map. It also has no model of how its wheels respond to commands. Every episode it wanders until it reaches the loading dock, or gets stuck. Only at the end does it learn whether the whole trip was good or bad. There is no simulator to query "what happens if I turn left instead?" The robot must actually live through entire episodes to learn anything. Monte Carlo Control answers a key question. How do you turn raw episodic experience like this into a genuinely optimal decision-making policy? This must happen with no model of the environment's dynamics at all. This matters because most real control problems are exactly this hard. Game-playing agents, recommendation systems, and physical robots often cannot query a transition model. They can only act and observe outcomes. Monte Carlo Control extends Monte Carlo Prediction, which merely evaluates a fixed policy. It becomes a full control loop that improves the policy over time. This uses the same Generalized Policy Iteration template that underlies almost all of reinforcement learning. The big picture is elegant: alternate between estimating how good the current policy's actions are (evaluation), and greedily tightening the policy toward those better actions (improvement). Repeating this cycle, under mild exploration conditions, provably converges to an optimal policy. This happens without ever writing down a transition probability or reward function. The catch, and the heart of what this article teaches, is that naive greedy improvement destroys exploration. So Monte Carlo Control must solve an exploration problem before it can solve a control problem. This article builds the algorithm from first principles. It covers why action-values are used instead of state-values, and why exploring starts or soft policies are non-negotiable. It gives the exact pseudocode for on-policy MC control with an ε-soft policy. It also explains the convergence argument via the policy improvement theorem. Finally, it covers concrete pitfalls, like biased first-visit vs every-visit counting, or forgetting to explore, that break real implementations.
- Monte Carlo Control estimates action-values q(s,a), not state-values, so a greedy policy can be extracted without a model.
- It follows Generalized Policy Iteration: alternate Monte Carlo policy evaluation with greedy (or ε-greedy) policy improvement.
- Exploring Starts or ε-soft policies are required — without them, greedy improvement stops visiting many (state, action) pairs forever.
- The Policy Improvement Theorem guarantees each improvement step yields a policy at least as good as before.
- On-policy ε-greedy MC control converges to the best policy achievable within the ε-soft policy class, not the true optimum, unless ε → 0.
- This algorithm is the direct ancestor of SARSA: On-Policy TD Control and motivates the On-Policy vs Off-Policy Learning distinction.
Monte Carlo Control finds optimal behavior purely from sampled episodes by alternately estimating action-values and greedily improving the policy toward them, provided every state-action pair keeps getting visited.
The idea
Monte Carlo Control is the application of Generalized Policy Iteration (GPI) using Monte Carlo estimation as the evaluation mechanism, with no access to a transition model . Recall that GPI is the interplay of two processes: policy evaluation (compute or for the current policy ) and policy improvement (make greedy, or partially greedy, with respect to those value estimates). In dynamic-programming methods this interplay uses the Bellman equations directly; in Monte Carlo methods, since there is no model, evaluation must instead be done by averaging observed returns from sampled episodes. A crucial design decision separates MC control from DP-style policy iteration: MC control estimates action-value functions rather than state-value functions . This is not a stylistic choice — it is forced. Greedy policy improvement under requires
which needs the model to look one step ahead. Without a model, this lookahead is unavailable. But if we instead estimate directly, greedy improvement is simply
no model required. This is the single idea that makes model-free control possible. The second essential idea is the exploration problem. A deterministic greedy policy, by definition, never selects the non-greedy actions again once it locks onto a choice at a state. If some pair is never selected, its Monte Carlo estimate never receives new samples and may remain permanently wrong — possibly making a genuinely excellent action look bad forever, with no way to correct the mistake. Two standard remedies exist. Exploring Starts (ES) assumes every episode begins at a uniformly random state-action pair, guaranteeing infinite visits to every pair over infinitely many episodes (a strong, often unrealistic assumption in real environments where you cannot "teleport" the start). ε-soft policies instead relax the target policy class itself: every action at every state retains probability at least , so no action is ever completely abandoned. This yields on-policy Monte Carlo control with ε-greedy policies, the workhorse version of the algorithm and the version emphasized here.
How it works
The algorithm maintains, for every state–action pair, a running estimate of the action-value , obtained by averaging the returns following visits to across many sampled episodes. After each full episode, the policy is updated to be ε-greedy with respect to the current . This single loop — generate episode, evaluate, improve — is repeated until (and hence the policy) stabilizes. Two bookkeeping choices matter and must be fixed explicitly:
- First-visit vs every-visit: first-visit MC averages only the return following the first occurrence of within an episode; every-visit averages the return following every occurrence. First-visit gives i.i.d.-style samples per episode and has the cleanest convergence proof (by the law of large numbers, since the samples across different episodes are independent). Every-visit is also consistent (converges to the same ) but the within-episode samples are correlated, which affects finite-sample variance and standard convergence arguments slightly differently.
- Incremental averaging: rather than storing every return, maintain a visit count and update incrementally,
which is mathematically identical to a running sample mean but uses memory per pair instead of . ```pseudocode Algorithm: On-Policy Monte Carlo Control (first-visit, epsilon-greedy) Input: epsilon in (0,1], discount factor gamma, number of episodes M Initialize: Q(s,a) arbitrarily for all s in S, a in A(s) # e.g. all zeros N(s,a) <- 0 for all s, a # visit counts pi(a|s) <- an arbitrary epsilon-soft policy # e.g. uniform random for episode = 1 to M:
# 1. GENERATE an episode by following current policy pi S_0, A_0, R_1, S_1, A_1, R_2, ..., S_{T-1}, A_{T-1}, R_T <- rollout using pi until terminal state S_T
# 2. EVALUATE: compute first-visit returns and update Q G <- 0 visited <- empty set for t = T-1 down to 0: G <- gamma G + R_{t+1} if (S_t, A_t) not in visited: # first-visit check visited.add((S_t, A_t)) N(S_t, A_t) <- N(S_t, A_t) + 1 Q(S_t, A_t) <- Q(S_t, A_t) + (1 / N(S_t, A_t)) (G - Q(S_t, A_t))
# 3. IMPROVE: make pi epsilon-greedy with respect to updated Q for each state s visited in this episode: A_star <- argmax_a Q(s, a) # ties broken arbitrarily/randomly for each a in A(s): if a == A_star: pi(a|s) <- 1 - epsilon + epsilon / |A(s)| else: pi(a|s) <- epsilon / |A(s)| return Q, pi ``` The loop is structured exactly as GPI: step 2 pulls toward (evaluation), and step 3 pulls toward greediness with respect to (improvement), and the two processes chase each other episode by episode until convergence.
Complexity & correctness
Per-episode time complexity. Let be the episode length (number of time steps until termination). Generating the episode costs environment interactions. Computing returns backward and updating costs arithmetic operations (each step does work: one increment, one running-average update, one set-membership check, which is amortized with a hash set). The improvement step recomputes the greedy action at each visited state, costing per state, so at most for the episode. Total per-episode cost: . Over episodes, total time is where is average episode length.
Space complexity. The algorithm stores and for every reachable pair, giving space — independent of the number of episodes, because of incremental averaging. This is a major practical advantage over storing raw return lists, which would cost in the worst case.
Correctness argument. The proof of convergence rests on two pillars. Pillar 1 — Monte Carlo evaluation is consistent. For a fixed policy , by the strong law of large numbers, the sample average of returns following first visits to converges almost surely to as the number of visits , provided returns have finite variance (true whenever rewards are bounded and , or episodes are guaranteed to terminate when ). Pillar 2 — the Policy Improvement Theorem. If is greedy (or ε-greedy in the appropriate sense) with respect to , then for all implies for all . For ε-soft policies the correct statement uses the ε-soft improvement theorem: if is the ε-greedy policy with respect to and was already ε-soft, then
which follows because the ε-greedy distribution places all its "extra" non-uniform mass on , and a weighted average that shifts mass toward the max value can only increase (a short averaging argument: writing 's distribution as -uniform plus on the argmax, and comparing against any other ε-soft expressed the same way, term-by-term the argmax action dominates). Chaining these two pillars: each full cycle of evaluation-then-improvement produces a policy whose value function is weakly better everywhere, and value functions are bounded above (rewards and hence returns are bounded, or discounted to be summable), so the sequence of value functions converges. At the fixed point, the policy is already ε-greedy with respect to its own , satisfying the ε-soft Bellman optimality condition restricted to the ε-soft policy class.
Honest tradeoffs.
- With Exploring Starts, the fixed point is the true optimal policy , because greedy improvement combined with guaranteed infinite exploration of every pair satisfies the classical GPI convergence theorem exactly.
- With ε-greedy (no exploring starts), the algorithm provably converges only to the optimal policy within the ε-soft policy class — a policy that must keep exploring with probability at least ε forever, so it cannot be arbitrarily close to a deterministic optimal policy unless ε is annealed toward zero.
- High variance: Monte Carlo returns accumulate all randomness over an entire episode, so estimates can be noisy, especially with long episodes or high-variance rewards. This is the central weakness that motivates SARSA: On-Policy TD Control, which bootstraps from one-step estimates instead of waiting for full returns, trading some bias for large variance reduction.
- Episodic requirement: pure Monte Carlo control needs episodes to terminate (or requires special handling for non-terminating tasks), unlike temporal-difference methods that update online, step by step.
Worked example
Consider a tiny 1-row gridworld with three non-terminal states in a line, and a terminal state to the right of . From every state the agent can choose action Right (move toward ) or Left (move toward the wall, bouncing back to the same state at cost). Reward is per step until reaching , where the episode ends; . The optimal policy is obviously "always go Right," but the agent starts knowing nothing, with for all , and , uniform-random initial policy. Trace one early episode starting at under the (initially uniform-random) policy:
| t | State | Action | Reward | Next State |
|---|---|---|---|---|
| 0 | A | Left | -1 | A (bounced) |
| 1 | A | Right | -1 | B |
| 2 | B | Left | -1 | B (bounced) |
| 3 | B | Right | -1 | C |
| 4 | C | Right | -1 | T (terminal) |
Episode length . Returns computed backward (, so ):
| t | ||
|---|---|---|
| 4 | (C, Right) | -1 |
| 3 | (B, Right) | -2 |
| 2 | (B, Left) | -3 |
| 1 | (A, Right) | -4 |
| 0 | (A, Left) | -5 |
First-visit check: each pair above is distinct within this episode (no repeats), so all five updates apply. After this episode, with for each pair, becomes exactly these returns:
| (s,a) | Q before | G observed | Q after (N=1) |
|---|---|---|---|
| (A, Left) | 0 | -5 | -5.0 |
| (A, Right) | 0 | -4 | -4.0 |
| (B, Left) | 0 | -3 | -3.0 |
| (B, Right) | 0 | -2 | -2.0 |
| (C, Right) | 0 | -1 | -1.0 |
Policy improvement at each visited state now makes Right the greedy action wherever both actions were tried (at : , at : ), so and jump to , while Left drops to . Note that was never visited, so remains at its initial value — larger than the newly learned ! If the policy at were made purely greedy right now, it would wrongly prefer the untried Left action, since . This is precisely why ε-softness matters: the ε-greedy policy still assigns Left at a small probability (), so it will eventually be sampled, its true (poor) value discovered, and the estimate corrected — whereas a fully greedy policy with no exploration could lock onto the wrong action at permanently. Across many further episodes, every action at every state keeps getting sampled with probability , all converge to the true under the current , and the ε-greedy policy converges toward always choosing Right (up to the residual ε exploration floor).
Common pitfalls & traps
| Pitfall | Why it happens | Consequence |
|---|---|---|
| Using instead of | Copying DP-style policy iteration directly | Greedy improvement becomes impossible without a model — cannot look ahead one step |
| No exploration mechanism (pure greedy from the start) | Forgetting GPI requires visiting all pairs infinitely often | Some pairs are never sampled; their estimate is permanently wrong, as shown for above |
| Confusing first-visit and every-visit counting | Updating on every occurrence while intending first-visit semantics | Overweights states revisited within loops; biases toward longer trajectories |
| Treating ε-greedy MC control as converging to the true optimum | Not distinguishing "optimal within ε-soft class" from | Reported policy is provably suboptimal by an gap unless ε is annealed |
| Applying MC control to non-terminating () continuing tasks | Forgetting the "episodic" requirement of returns | Returns never finish accumulating; algorithm never produces an update |
| Ignoring high variance of in long episodes | Assuming MC estimates are as stable as TD estimates | Slow, noisy convergence; many episodes needed to shrink variance |
Pioneers & history
Monte Carlo methods for control emerged directly from the reinforcement learning framework formalized by Richard Sutton and Andrew Barto, who unified earlier scattered ideas — trial-and-error learning, dynamic programming, and temporal-difference methods — into the modern GPI-based treatment of prediction and control. The Monte Carlo approach itself borrows its statistical machinery (sampling to estimate expectations) from the Monte Carlo method invented for physics computations, but its application to control via action-values is a distinctly reinforcement-learning-era contribution built on the policy iteration ideas from dynamic programming (Bellman) and the exploration-versus-exploitation framing from bandit theory.
Origins · 1 minAndrew G. Barto and how this was discovered
Where this matters
Monte Carlo Control's core idea — estimate action-values from sampled outcomes, then greedily (or ε-greedily) tighten the policy — underlies much of practical reinforcement learning even where the specific first-visit averaging is replaced by more sophisticated machinery. Classic applications include backgammon and other turn-based games where full episodes are cheap to simulate and the outcome (win/lose/score) is a natural terminal return. Monte Carlo Tree Search, used in AlphaGo and its successors, borrows the same "sample full rollouts, average returns, improve action selection" philosophy, generalized into a search tree rather than a flat table. In industrial and robotics settings, Monte Carlo-style episodic evaluation is used whenever a simulator can generate complete episodes but a differentiable or explicit transition model is unavailable — for instance, evaluating a trading strategy over historical episodes, or a dialogue policy over full conversations, where the "return" is only meaningful at the end of an interaction. The exploration mechanisms introduced here (ε-soft policies, and the exploring-starts idea of injecting randomized starting conditions) recur throughout deep RL, from ε-greedy DQN agents to the initial-state randomization used in robotics sim-to-real training. Most importantly, this algorithm is the conceptual stepping stone to SARSA: On-Policy TD Control and On-Policy vs Off-Policy Learning: nearly every idea here — action-values, GPI, ε-soft exploration, the improvement theorem — reappears verbatim once returns are replaced by bootstrapped one-step targets.
Ask the tutor: How does replacing full-episode Monte Carlo returns with one-step bootstrapped targets turn this algorithm into SARSA?
Why must episodes terminate for Monte Carlo control to work?
Monte Carlo returns are defined by summing rewards up to the terminal step . If the task never terminates and , this sum can be unbounded or simply never finish accumulating, so no update ever becomes available — the algorithm has to wait for the whole episode before it can learn anything. Continuing tasks are instead handled by discounting (, giving convergent infinite sums) or by switching to temporal-difference methods, which bootstrap from partial returns and update after every single step rather than waiting for termination.
What is the difference between Exploring Starts and ε-soft policies as exploration fixes?
Exploring Starts assumes every episode can begin at a uniformly random (state, action) pair, guaranteeing infinite visitation to every pair and allowing convergence to the true optimal policy . It is theoretically clean but often physically unrealistic — you usually cannot force a real robot or a real customer interaction to "start" in an arbitrary configuration. ε-soft policies instead bake a minimum exploration probability into the policy itself at every state, requiring no special control over the environment's start distribution, but the tradeoff is that the algorithm only converges to the best policy within the ε-soft class, not the true unconstrained optimum, unless ε is annealed toward zero over time.
Is first-visit or every-visit Monte Carlo control preferred in practice?
First-visit is more commonly analyzed because its convergence proof is the cleanest: returns sampled from the first visit to across different episodes are independent, so the standard law of large numbers applies directly. Every-visit is also consistent — it converges to the same — but returns from multiple visits within one episode are correlated (they can share overlapping future rewards), which complicates the convergence argument and can change finite-sample variance. In practice, many implementations use every-visit for simplicity when states rarely repeat within an episode, since the difference becomes negligible.
How does Monte Carlo Control relate to Generalized Policy Iteration?
Monte Carlo Control is a specific instantiation of Generalized Policy Iteration where the evaluation half of the loop is performed by averaging sampled episodic returns instead of solving Bellman equations with a model. The improvement half is unchanged in spirit: make the policy greedy (or ε-greedy) with respect to the latest value estimates. GPI is the abstract template — any reinforcement learning algorithm with an evaluate-then-improve structure, including SARSA: On-Policy TD Control and Q-learning, is an instance of it; Monte Carlo Control is simply the version that plugs in Monte Carlo estimation as its evaluation engine.
Why is Monte Carlo Control considered high-variance compared to temporal-difference control?
Each Monte Carlo return accumulates the randomness of every reward and every state transition from time all the way to the end of the episode. In long episodes, or in environments with high-variance rewards or stochastic transitions, this compounding makes individual return samples noisy, so many episodes are needed before the running average stabilizes. Temporal-difference methods instead bootstrap: they update using a one-step estimate that itself relies on the current (possibly imperfect) values, trading some bias for a large reduction in variance, since only one step of randomness enters each update rather than an entire episode's worth.
Can Monte Carlo Control be used off-policy instead of on-policy?
Yes — this is the natural next extension. On-policy MC control (described here) uses the same ε-soft policy both to generate episodes and to be improved. Off-policy variants instead generate episodes from a separate, more exploratory behavior policy while learning about a different, typically greedy, target policy, using importance sampling to correct for the mismatch between the two distributions. This decoupling is exactly the theme developed under On-Policy vs Off-Policy Learning, and it removes the need to keep the learned policy itself exploratory, at the cost of the added variance and complexity of importance-sampling corrections.
What happens if two actions tie for the maximum Q-value during improvement?
Ties should be broken randomly (uniformly among the tied maximizers) rather than always favoring, say, the first action in some fixed ordering. Deterministic tie-breaking by index or insertion order introduces a hidden, unintended bias: certain actions get systematically favored whenever values happen to be equal (which is common early in training when many Q-values are still at their identical initial value). Random tie-breaking preserves the symmetry the algorithm assumes and avoids artificially starving some actions of exploration purely due to an implementation detail unrelated to their true value.