First-Visit vs Every-Visit Monte Carlo
Imagine an agent playing thousands of hands of blackjack. You want to know the true value of standing on a soft 18. You have episode logs, but a single hand might visit that exact state twice. It could happen once early, once late. You must decide how to count that hand when averaging returns. This small bookkeeping choice has real consequences. Should you average returns from only the first occurrence of a state? Or from every occurrence? The answer affects statistical bias and variance. It is one of the first design decisions anyone implementing Monte Carlo Prediction must make. Monte Carlo (MC) methods estimate the value function of a policy. They do this by averaging the actual returns observed after visiting a state. This differs from bootstrapping off other estimates, as in Temporal-Difference Learning. This makes MC conceptually simple and unbiased in a precise sense. But it also means the estimator's exact definition matters more than it might in a bootstrapped method. This includes what counts as "a visit" and how visits are aggregated. First-visit MC and every-visit MC are the two canonical answers to that question. Both converge to the true value function under standard conditions. But they get there by different statistical routes. This article isolates that single design choice and analyzes it carefully. It covers what each estimator computes and why both are consistent. It also covers how their bias and variance differ in finite samples. Finally, it explains what this implies for implementation. The ideas here are foundational for everything that follows in model-free reinforcement learning. Once you understand how MC estimates a value function from sampled returns, you are one step from Monte Carlo Control. There, the same averaging machinery is combined with policy improvement. This finds optimal behavior without ever knowing the environment's transition dynamics. The treatment is deliberately narrow and precise. There is no bootstrapping, no function approximation. Just the pure statistics of averaging returns over episodes, done two different ways.
- First-visit MC averages the return only from the first time a state appears in each episode.
- Every-visit MC averages the return from every time a state appears, including repeats within one episode.
- Both estimators converge to the true value function as the number of episodes grows.
- First-visit returns across episodes are i.i.d., giving a clean unbiased estimator with tractable variance.
- Every-visit returns within an episode are correlated, making the estimator biased in finite samples but often lower-variance in practice.
- The choice mostly matters when states can recur within a single episode; for episodes with no repeated states the two coincide exactly.
First-visit and every-visit Monte Carlo differ only in how they handle repeated visits to a state within one episode — first-visit keeps returns statistically independent and unbiased, while every-visit uses more data at the cost of within-episode correlation and finite-sample bias.
The idea
Monte Carlo prediction estimates the state-value function by generating episodes under policy and averaging the observed returns that follow visits to . A visit to state is any time step at which occurs within an episode. Because an agent following can, in general, pass through the same state more than once in a single episode (this is common in gridworlds with loops, in continuing tasks cut into episodes, or in any MDP without a strict layering structure), an episode can contribute more than one return sample for the same state.
First-visit MC resolves this by looking, for each episode, only at the first time step at which occurs, and using the return computed from that time step onward. Later occurrences of in the same episode are ignored for the purposes of updating . The estimator is
where the sum ranges over episodes in which was visited at least once, is the return from the first visit in episode , and is the number of such episodes.
Every-visit MC instead uses every occurrence of within every episode, treating each occurrence as a separate return sample:
where counts total visits across all episodes (an episode with visits to contributes terms), and each is the return computed from that particular visit onward. Both estimators are built from the same raw material — sampled trajectories under — and both converge almost surely to as the number of episodes tends to infinity, by the Law of Large Numbers applied appropriately. The distinction is entirely about how much of the correlated information within a single episode gets folded into the running average, and this affects bias and variance in finite samples, which is the substance of the rest of this article.
How it works
Both algorithms share a common skeleton: generate an episode, walk it backward accumulating the discounted return, and update a running average of returns keyed by state. The only difference is a single conditional check — "have I already processed this state in this episode?" ``` Initialize: V(s) ← arbitrary value for all states s Returns(s) ← empty list, for all states s # or running sum + count Repeat forever (for each episode): Generate an episode following policy π: S_0, A_0, R_1, S_1, A_1, R_2, ..., S_{T-1}, A_{T-1}, R_T G ← 0 visited_in_episode ← empty set() # only used by first-visit for t = T-1 down to 0: G ← γ * G + R_{t+1} if FIRST_VISIT: if S_t not in visited_in_episode: visited_in_episode.add(S_t) append G to Returns(S_t) V(S_t) ← average(Returns(S_t)) else: # EVERY_VISIT append G to Returns(S_t) V(S_t) ← average(Returns(S_t)) ``` Walking the episode backward is what makes the return computation efficient: , so each step costs rather than re-summing the whole remaining trajectory, turning a naive computation of all returns into . The first-visit/every-visit distinction is implemented by the `visited_in_episode` set, checked once per state per episode. This is the entire algorithmic difference — everything else (episode generation, backward return accumulation, incremental averaging) is identical. In practice, `average(Returns(s))` is not recomputed from scratch each time; it is maintained incrementally,
where is incremented each time a (first- or every-) visit return is folded in, avoiding storage of the full list of returns.
Complexity & correctness
Time complexity. Generating an episode of length costs environment interactions. Processing it backward to compute all returns and update the visited states costs as well, since each of the time steps does work (one multiply-add for , one set lookup/insert for first-visit, one incremental average update). Over episodes, the total cost is where is the mean episode length — identical for both variants, since the only difference is a constant-time set membership check per step.
Space complexity. Maintaining and a visit counter for every state requires space (using the incremental-mean update, not storing full return lists). The `visited_in_episode` set used by first-visit needs at most additional space per episode, discarded after each episode. Neither variant needs to store past episodes.
Correctness — every-visit is trivially unbiased in the limit, first-visit is unbiased exactly. First-visit MC. Fix a state . Consider only the episodes in which is visited at least once, and let be the return from the first visit in the -th such episode. Because each episode is generated independently by re-running the policy in the environment from the start, and because the first-visit return in episode is a (deterministic, given the trajectory) function of only that episode's randomness, the sequence is i.i.d. across episodes, each distributed as the true conditional return distribution given (using the Markov property: the distribution of the return following a visit to depends only on , not on how the episode reached ). Hence
so is an average of i.i.d. unbiased samples: it is itself unbiased for every fixed , and by the Strong Law of Large Numbers,
Its variance is exactly , the textbook rate for an i.i.d. average. Every-visit MC. Now every occurrence of within an episode contributes a term, and these terms are not independent: if is visited at and again later at in the same episode, the return from is a sub-trajectory of the return from (they share the same future dynamics after , and are correlated through the shared random seed of that one episode continuing from each time). So within one episode, multiple visits to give correlated, not i.i.d., samples of the return distribution. This means that for a finite number of episodes, can be a biased estimator of — repeated visits from unusually long or short episodes get overweighted relative to a pure i.i.d. average. Despite this, every-visit MC is still consistent: as the number of episodes , the fraction of total visits contributed by any single episode shrinks, the law of large numbers still applies across episodes (only within an episode is there correlation, and each episode itself is drawn i.i.d.), and
This convergence result appears in the original analyses of MC prediction and is the standard justification cited for using either variant interchangeably in the large-sample regime.
Bias-variance intuition. First-visit trades away data (ignoring later same-episode visits) in exchange for a clean i.i.d. sample and zero finite-sample bias. Every-visit uses strictly more of the available data per episode, which typically reduces variance for a fixed number of episodes (more samples averaged), but at the cost of a finite-sample bias induced by intra-episode correlation. As both the bias (for every-visit) and the variance gap shrink, and the two estimators become statistically indistinguishable. In episodic tasks where states rarely or never repeat within an episode (e.g., strictly acyclic state spaces, or games where you naturally never return to an exact past state), first-visit and every-visit produce identical numbers, since for every state.
Worked example
Consider three toy episodes generated under some fixed policy in a small MDP with discount (episodic, undiscounted for simplicity), where state is the state of interest and it can recur within an episode.
| Episode | Trajectory (states, then rewards) | Visits to X | Returns from each visit |
|---|---|---|---|
| 1 | X → Y → X → Z (terminal); rewards +1, +2, +3 | t=0, t=2 | ; |
| 2 | Y → X → Z (terminal); rewards +0, +4 | t=1 | |
| 3 | X → X → Z (terminal); rewards +5, −1 | t=0, t=1 | ; |
First-visit MC for X: use only the first occurrence in each episode.
Three episodes, three samples, one per episode — exactly the i.i.d. structure the correctness argument relies on.
Every-visit MC for X: use every occurrence.
Five samples from three episodes — episode 1 and episode 3 each contribute two correlated terms (the second visit's return is nested inside the first visit's return in episode 1, and directly adjacent in episode 3). Notice the two estimates disagree substantially (4.67 vs. 3.2) with only three episodes — this is the finite-sample bias/variance difference made concrete. As more episodes accumulate, assuming the policy and environment are fixed, both numbers will drift toward the same true value ; the gap you see here is exactly the sampling artifact the theory predicts, not an error in either method.
| Quantity | First-visit | Every-visit |
|---|---|---|
| Samples used | 3 (one per episode) | 5 (all occurrences) |
| Independence | Exact (across episodes) | Violated within episodes 1, 3 |
| Finite-sample bias | None | Present (shrinks with more episodes) |
| Estimate here | 4.67 | 3.20 |
Common pitfalls & traps
| Pitfall | Why it happens | Fix |
|---|---|---|
| Forgetting to reset `visited_in_episode` each episode | Reusing a global visited-set across episodes silently turns first-visit MC into "first-visit ever," corrupting all subsequent estimates | Re-initialize the set at the top of every episode's loop |
| Computing returns forward with re-summation | Naively recomputing from scratch at each costs | Always accumulate backward: |
| Treating every-visit returns as i.i.d. when computing confidence intervals | Standard error formulas assume independent samples; every-visit samples from the same episode are correlated | Use first-visit for statistically valid variance/CI estimates, or use episode-level bootstrapping for every-visit |
| Mixing first-visit and every-visit updates for the same state within one run | Produces an estimator that is neither, with no known convergence guarantee | Pick one scheme and apply it consistently across the entire run |
| Assuming the two methods always give different answers | In acyclic or short episodes without repeats, first-visit and every-visit are numerically identical | Check whether repeated visits are even possible before worrying about the distinction |
Pioneers & history
Monte Carlo methods for sequential decision-making trace back to the broader Monte Carlo simulation tradition in physics and statistics, later adapted into the reinforcement-learning framework that formalized first-visit and every-visit as two distinct, analyzable estimators for policy evaluation.
Origins · 1 minRichard S. Sutton and how this was discovered
Where this matters
Monte Carlo prediction, in either its first-visit or every-visit form, is the conceptual seed for a large swath of practical model-free reinforcement learning. It underlies Monte Carlo Control, where the same return-averaging machinery is combined with an -greedy or exploring-starts policy improvement step to learn optimal behavior directly from experience, without ever building a model of the environment's transition probabilities. This matters in domains like game-playing agents, robotic control from raw episodic rollouts, and any setting where a full transition model is infeasible to specify but complete episodes can be simulated or observed. The bias-variance tradeoff between first-visit and every-visit also foreshadows a recurring theme in RL: the tension between using data efficiently (every-visit, more samples per episode) versus using it in a statistically clean way (first-visit, valid independence for variance estimates). This same tension reappears, in different guises, in eligibility traces, in the design of Temporal-Difference Learning methods that blend MC and bootstrapping, and in modern policy-gradient estimators that must decide how to weight correlated trajectory samples. Every-visit MC's approach — using all the data, tolerating correlation — is philosophically close to how eligibility traces later generalize MC and TD into a single spectrum (TD(λ)), making the first-visit/every-visit distinction a genuine conceptual stepping stone rather than a historical footnote. Production RL libraries that implement tabular MC baselines (used for benchmarking and for small, well-understood MDPs before scaling to deep function approximation) typically expose both variants, precisely because the choice affects convergence behavior and variance in small-sample regimes common in early-stage experimentation.
Ask the tutor: Can you show how first-visit vs every-visit MC estimators behave differently when I add a policy-improvement step on top, moving from prediction to control?
Do first-visit and every-visit MC converge to different value functions?
No. Under standard conditions (the policy is fixed, every state is visited infinitely often with positive probability, and returns have finite variance), both estimators converge almost surely to the same true value function as the number of episodes goes to infinity. They differ only in their finite-sample behavior: first-visit is unbiased at every finite sample size with a clean i.i.d. variance formula, while every-visit is biased at finite sample sizes due to intra-episode correlation but becomes unbiased in the limit. In the long run, if you ran either algorithm forever, you would get the same numbers.
Which variant should I use in practice?
For small tabular problems and educational implementations, first-visit is usually preferred because its statistical properties (unbiasedness, straightforward variance/confidence-interval estimation) are cleaner and easier to reason about. Every-visit can be preferable when episodes are long and states recur often, since it extracts more return samples per episode and often has lower variance for a fixed computational budget, even though those samples are correlated. In most textbook treatments of Monte Carlo control, first-visit is the default presented, but both are valid and both appear in practical codebases.
Does the discount factor γ affect the first-visit vs every-visit comparison?
The discount factor changes the value of each individual return , but it does not change which estimator is unbiased or which samples are correlated — that distinction comes purely from how visits are counted, not from how returns are weighted by γ. That said, a very small γ effectively "forgets" the far future, which can reduce the correlation between the two returns from repeated visits within one episode (since their tails matter less), softening the every-visit bias somewhat, but it does not eliminate it in general.
Can I mix first-visit and every-visit within the same algorithm run?
You should not. Doing so produces an estimator whose statistical behavior is not covered by the standard convergence proofs for either method, since you would be averaging a heterogeneous mix of independent and correlated samples with no clean characterization of the resulting bias or variance. If you need different behavior for different states (for example, some states never recur and the distinction is moot), it is fine, but you should not switch schemes for the same state across different episodes or runs.
How does this distinction generalize to action-value estimation, Q(s,a)?
Exactly the same way. Replace "visit to state s" with "visit to state-action pair (s,a)" — the first-visit variant averages the return from the first time-step at which in each episode, and every-visit averages the return from every such time-step. This is directly relevant to Monte Carlo Control, where action-value estimates (rather than state values) are what gets averaged, since control requires comparing actions within a state to improve the policy.
Is every-visit MC ever strictly better in a formal sense?
"Better" depends on the criterion. In terms of mean squared error for a fixed, small number of episodes, every-visit can sometimes have lower total error than first-visit because it uses more data, even though part of that error is bias rather than variance — the bias-variance tradeoff can favor either side depending on the specific MDP and episode-length distribution. Neither estimator dominates the other uniformly across all environments; the choice is a bias-variance-computation tradeoff, not a strict improvement in one direction.
What happens if a state is never visited during sampling?
Both estimators simply leave at its initial value for any state that never appears in any generated episode, since no return samples are ever collected for it. This is a well-known limitation of pure Monte Carlo prediction — it can only estimate values for states the behavior actually reaches, motivating the "maintaining exploration" requirement (e.g., exploring starts or an -soft policy) that becomes essential once you move from prediction to Monte Carlo Control.