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.

Key takeaways
  • 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.
The core insight

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 p(s′,r∣s,a)p(s', r \mid s, a). Recall that GPI is the interplay of two processes: policy evaluation (compute vπv_\pi or qπq_\pi for the current policy π\pi) and policy improvement (make π\pi 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 qπ(s,a)q_\pi(s,a) rather than state-value functions vπ(s)v_\pi(s). This is not a stylistic choice — it is forced. Greedy policy improvement under vπv_\pi requires

π′(s)=arg⁡max⁡a∑s′,rp(s′,r∣s,a)[r+γvπ(s′)],\pi'(s) = \arg\max_a \sum_{s',r} p(s',r\mid s,a)\big[r + \gamma v_\pi(s')\big],

which needs the model p(s′,r∣s,a)p(s',r\mid s,a) to look one step ahead. Without a model, this lookahead is unavailable. But if we instead estimate qπ(s,a)q_\pi(s,a) directly, greedy improvement is simply

π′(s)=arg⁡max⁡aqπ(s,a),\pi'(s) = \arg\max_a q_\pi(s,a),

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 (s,a)(s,a) pair is never selected, its Monte Carlo estimate q(s,a)q(s,a) 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 ε/∣A(s)∣\varepsilon/|\mathcal{A}(s)|, 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 Q(s,a)≈qπ(s,a)Q(s,a) \approx q_\pi(s,a), obtained by averaging the returns following visits to (s,a)(s,a) across many sampled episodes. After each full episode, the policy is updated to be ε-greedy with respect to the current QQ. This single loop — generate episode, evaluate, improve — is repeated until QQ (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 (s,a)(s,a) 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 qπq_\pi) 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 N(s,a)N(s,a) and update incrementally,
Q(s,a)←Q(s,a)+1N(s,a)(G−Q(s,a)),Q(s,a) \leftarrow Q(s,a) + \frac{1}{N(s,a)}\Big(G - Q(s,a)\Big),

which is mathematically identical to a running sample mean but uses O(1)O(1) memory per pair instead of O(N)O(N). ```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 QQ toward qπq_\pi (evaluation), and step 3 pulls π\pi toward greediness with respect to QQ (improvement), and the two processes chase each other episode by episode until convergence.

Figure
Generalized Policy Iteration loop specialized to Monte Carlo Control
π (policy) ε-soft, acts to generate episodes Q(s,a) averaged returns from episodes generate episode evaluate: Q ← average(G) improve: π ← ε-greedy(Q) Each full lap = one episode processed. π and Q chase each other; fixed point reached only when π is already greedy (ε=0 limit) w.r.t. its own Q.

Complexity & correctness

Per-episode time complexity. Let TT be the episode length (number of time steps until termination). Generating the episode costs O(T)O(T) environment interactions. Computing returns backward and updating QQ costs O(T)O(T) arithmetic operations (each step does O(1)O(1) work: one increment, one running-average update, one set-membership check, which is O(1)O(1) amortized with a hash set). The improvement step recomputes the greedy action at each visited state, costing O(∣A∣)O(|\mathcal{A}|) per state, so at most O(T⋅∣A∣)O(T \cdot |\mathcal{A}|) for the episode. Total per-episode cost: O(T⋅∣A∣)O(T \cdot |\mathcal{A}|). Over MM episodes, total time is O(M⋅Tˉ⋅∣A∣)O(M \cdot \bar{T} \cdot |\mathcal{A}|) where Tˉ\bar T is average episode length.

Space complexity. The algorithm stores Q(s,a)Q(s,a) and N(s,a)N(s,a) for every reachable (s,a)(s,a) pair, giving O(∣S∣⋅∣A∣)O(|\mathcal{S}| \cdot |\mathcal{A}|) 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 O(∣S∣∣A∣M)O(|\mathcal{S}||\mathcal{A}|M) 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 π\pi, by the strong law of large numbers, the sample average of returns following first visits to (s,a)(s,a) converges almost surely to Eπ[Gt∣St=s,At=a]=qπ(s,a)\mathbb{E}_\pi[G_t \mid S_t=s, A_t=a] = q_\pi(s,a) as the number of visits →∞\to \infty, provided returns have finite variance (true whenever rewards are bounded and γ<1\gamma < 1, or episodes are guaranteed to terminate when γ=1\gamma = 1). Pillar 2 — the Policy Improvement Theorem. If π′\pi' is greedy (or ε-greedy in the appropriate sense) with respect to qπq_\pi, then qπ(s,π′(s))≥vπ(s)q_\pi(s, \pi'(s)) \geq v_\pi(s) for all ss implies vπ′(s)≥vπ(s)v_{\pi'}(s) \geq v_\pi(s) for all ss. For ε-soft policies the correct statement uses the ε-soft improvement theorem: if π′\pi' is the ε-greedy policy with respect to qπq_\pi and π\pi was already ε-soft, then

qπ(s,π′(s))=∑aπ′(a∣s)qπ(s,a)≥vπ(s),q_\pi(s, \pi'(s)) = \sum_a \pi'(a|s) q_\pi(s,a) \geq v_\pi(s),

which follows because the ε-greedy distribution places all its "extra" non-uniform mass on arg⁡max⁡aqπ(s,a)\arg\max_a q_\pi(s,a), and a weighted average that shifts mass toward the max value can only increase (a short averaging argument: writing π′\pi''s distribution as ε\varepsilon-uniform plus (1−ε)(1-\varepsilon) on the argmax, and comparing against any other ε-soft π\pi 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 qπq_\pi, 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 π∗\pi_*, 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 GtG_t 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 γ=1\gamma=1 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 A,B,CA, B, C in a line, and a terminal state TT to the right of CC. From every state the agent can choose action Right (move toward TT) or Left (move toward the wall, bouncing back to the same state at cost). Reward is −1-1 per step until reaching TT, where the episode ends; γ=1\gamma = 1. The optimal policy is obviously "always go Right," but the agent starts knowing nothing, with Q(s,a)=0Q(s,a) = 0 for all s,as,a, and ε=0.2\varepsilon = 0.2, uniform-random initial policy. Trace one early episode starting at AA under the (initially uniform-random) policy:

tStateActionRewardNext State
0ALeft-1A (bounced)
1ARight-1B
2BLeft-1B (bounced)
3BRight-1C
4CRight-1T (terminal)

Episode length T=5T=5. Returns computed backward (γ=1\gamma=1, so Gt=∑k>tRkG_t = \sum_{k>t} R_k):

t(St,At)(S_t,A_t)GtG_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 (St,At)(S_t,A_t) pair above is distinct within this episode (no repeats), so all five updates apply. After this episode, with N=1N=1 for each pair, QQ becomes exactly these returns:

(s,a)Q beforeG observedQ 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 AA: −4>−5-4 > -5, at BB: −2>−3-2 > -3), so π(Right∣A)\pi(\text{Right}\mid A) and π(Right∣B)\pi(\text{Right}\mid B) jump to 1−ε+ε/2=0.91-\varepsilon+\varepsilon/2 = 0.9, while Left drops to 0.10.1. Note that (C,Left)(C,\text{Left}) was never visited, so Q(C,Left)Q(C,\text{Left}) remains at its initial value 00 — larger than the newly learned Q(C,Right)=−1Q(C,\text{Right}) = -1! If the policy at CC were made purely greedy right now, it would wrongly prefer the untried Left action, since 0>−10 > -1. This is precisely why ε-softness matters: the ε-greedy policy still assigns Left at CC a small probability (ε/2=0.1\varepsilon/2=0.1), 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 CC permanently. Across many further episodes, every action at every state keeps getting sampled with probability ≥ε/∣A∣\geq \varepsilon/|\mathcal{A}|, all Q(s,a)Q(s,a) converge to the true qπ(s,a)q_\pi(s,a) under the current π\pi, and the ε-greedy policy converges toward always choosing Right (up to the residual ε exploration floor).

Common pitfalls & traps

PitfallWhy it happensConsequence
Using v(s)v(s) instead of q(s,a)q(s,a)Copying DP-style policy iteration directlyGreedy 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 oftenSome (s,a)(s,a) pairs are never sampled; their QQ estimate is permanently wrong, as shown for (C,Left)(C,\text{Left}) above
Confusing first-visit and every-visit countingUpdating N(s,a)N(s,a) on every occurrence while intending first-visit semanticsOverweights states revisited within loops; biases toward longer trajectories
Treating ε-greedy MC control as converging to the true optimumNot distinguishing "optimal within ε-soft class" from π∗\pi_*Reported policy is provably suboptimal by an O(ε)O(\varepsilon) gap unless ε is annealed
Applying MC control to non-terminating (γ=1\gamma=1) continuing tasksForgetting the "episodic" requirement of returnsReturns never finish accumulating; algorithm never produces an update
Ignoring high variance of GtG_t in long episodesAssuming MC estimates are as stable as TD estimatesSlow, 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
AG
Andrew G. Barto
born 1948 · Co-formalized reinforcement learning as a field alongside Richard Sutton, at the University of Massachusetts Amherst, integrating Monte Carlo, dynamic programming, and temporal-difference ideas into a single coherent theory of prediction and control

History
1944
— von Neumann and Ulam develop the Monte Carlo method for statistical sampling problems at Los Alamos.
1957
— Richard Bellman formalizes dynamic programming and the principle of optimality, giving the theoretical backbone for policy iteration.
1988
— Sutton introduces temporal-difference learning, setting up the prediction methods that MC control is compared against.
1998
— Sutton and Barto publish the first edition of Reinforcement Learning: An Introduction, formalizing on-policy Monte Carlo control with exploring starts and ε-soft policies as a unified GPI instance.
2018
— the second edition refines and modernizes the treatment of Monte Carlo control alongside deep reinforcement learning connections.

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 Gt=Rt+1+γRt+2+⋯+γT−t−1RTG_t = R_{t+1} + \gamma R_{t+2} + \dots + \gamma^{T-t-1} R_T are defined by summing rewards up to the terminal step TT. If the task never terminates and γ=1\gamma = 1, 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 (γ<1\gamma < 1, 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 π∗\pi_*. 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 (s,a)(s,a) across different episodes are independent, so the standard law of large numbers applies directly. Every-visit is also consistent — it converges to the same qπ(s,a)q_\pi(s,a) — 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 GtG_t accumulates the randomness of every reward and every state transition from time tt 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 Q(s,a)Q(s,a) stabilizes. Temporal-difference methods instead bootstrap: they update Q(s,a)Q(s,a) using a one-step estimate that itself relies on the current (possibly imperfect) QQ 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.

Before this

Where this leads