---
title: Predictor lab
heading: Bimodal and gshare predictors, a 2-bit counter's accuracy and a return stack, in Python
eyebrow: S4 · Lesson 12 · Predictor lab
xp: 60
---

::: hook
Branch predictors are judged on traces, and the quickest way to understand them is to build them. This lab writes a bimodal predictor of 2-bit counters and a gshare predictor that adds global history, runs both on branches with different patterns, works out exactly how well a 2-bit counter does on a branch that's simply random, and simulates a return-address stack to see where it breaks. Each result connects to a formula from lessons 7 and 8.
:::

::: play
- The curve is the long-run accuracy of a 2-bit saturating counter on a branch taken independently with probability p, from the counter's stationary distribution.
- On a random branch it does slightly worse than always predicting the majority outcome (the dashed line), because a run of the minority outcome sometimes flips it.
- On patterned branches, which most are, history-based predictors do far better than either.
:::

```sim plot
view: graph
x: p = 0.5..0.99
y: a = 0.4..1
samples: 300
plot: (p*(p^2*(1 - p) + p^3) + (1 - p)*((1 - p)^3 + (1 - p)^2*p))/((1 - p)^3 + (1 - p)^2*p + (1 - p)*p^2 + p^3) | label: 2-bit counter
plot: p | dashed | label: always predict taken
```

::: predict
## A loop branch is taken nine times and then not taken once, over and over. What accuracy does a bimodal predictor of 2-bit counters reach, and what does gshare with 12 bits of history reach?

- [x] About 90% for bimodal; nearly 100% for gshare
- [ ] Nearly 100% for both
- [ ] About 50% for both
- [ ] About 80% for bimodal; about 90% for gshare

::: reveal
The counter sits at strongly taken and mispredicts only the loop exit, then is right again on the next taken: 9 of 10. Gshare's history register sees the last 12 outcomes, which tell exactly where in the loop the branch is, so each position gets its own counter, and after a short warm-up even the exit is predicted.
:::
:::

::: nameit
## The predictors

- **Bimodal:** index a table of $2^n$ 2-bit counters with the low n bits of the branch address; predict taken in states 2 and 3; count up on taken, down on not taken, saturating at 0 and 3.
- **gshare:** the same table, indexed by the address XOR an h-bit global history of recent outcomes (shifted in after each branch).
- **A 2-bit counter on a random branch:** its state is a Markov chain; with taken probability p and $q = 1 - p$, the stationary probabilities go as $1, p/q, (p/q)^2, (p/q)^3$, and the accuracy is $p\,P(\text{predict taken}) + q\,P(\text{predict not taken})$.
- **Return-address stack:** push on calls, pop on returns; with depth d, recursion deeper than d overwrites the oldest entries, so the returns from the deepest calls beyond d are mispredicted.
:::

::: check
kind: python

## Write `bimodal(trace, n)` and `gshare(trace, n, h)`: trace is a list of (pc, taken) pairs; counters start at 2 (weakly taken). Return each predictor's accuracy.

```python starter
def bimodal(trace, n):
    return 0.5

def gshare(trace, n, h):
    return 0.5
```

```python solution
def bimodal(trace, n):
    t, ok, m = [2] * (1 << n), 0, (1 << n) - 1
    for pc, tk in trace:
        i = pc & m
        ok += (t[i] >= 2) == tk
        t[i] = min(3, t[i] + 1) if tk else max(0, t[i] - 1)
    return ok / len(trace)

def gshare(trace, n, h):
    t, g, ok, m = [2] * (1 << n), 0, 0, (1 << n) - 1
    for pc, tk in trace:
        i = (pc ^ g) & m
        ok += (t[i] >= 2) == tk
        t[i] = min(3, t[i] + 1) if tk else max(0, t[i] - 1)
        g = ((g << 1) | int(tk)) & ((1 << h) - 1)
    return ok / len(trace)
```

```python tests
loop = [(0x40, k % 10 != 9) for k in range(10000)]
alt = [(0x80, k % 2 == 0) for k in range(10000)]
assert abs(bimodal(loop, 10) - 0.9) < 1e-9, "The predict: bimodal misses each loop exit."
assert gshare(loop, 12, 12) > 0.999, "Gshare learns where the exit comes."
assert bimodal(alt, 10) == 0.5 and gshare(alt, 10, 4) > 0.999, "Alternating: bimodal is a coin; one bit of history solves it."
```

::: right
Right. History turns a pattern in time into a choice of counter, which is why every modern predictor indexes by it.
:::
:::

::: check
kind: python

## Write `two_bit_accuracy(p)`: the long-run accuracy of one 2-bit saturating counter on a branch taken independently with probability p (0 < p < 1), from the stationary distribution.

```python starter
def two_bit_accuracy(p):
    return p
```

```python solution
def two_bit_accuracy(p):
    q = 1 - p
    r = p / q
    w = [1, r, r * r, r ** 3]
    s = sum(w)
    pt = (w[2] + w[3]) / s
    return p * pt + q * (1 - pt)
```

```python tests
assert abs(two_bit_accuracy(0.7) - 0.6380) < 1e-4, "A 70% branch: 63.8%, below always-taken's 70%."
assert abs(two_bit_accuracy(0.5) - 0.5) < 1e-12, "A fair coin: 50%."
assert two_bit_accuracy(0.95) > 0.94, "Strongly biased branches are predicted nearly as well as their bias."
```

::: right
Right. Counters help with biased branches and patterns; on truly random branches nothing beats the bias.
:::
:::

::: check
kind: python

## Write `ras_misses(seq, depth)`: seq is a list of ('call', addr) and ('ret', addr) events; a return-address stack of the given depth pushes on calls (dropping its oldest entry when full) and pops on returns. Count returns whose predicted address is wrong or missing.

```python starter
def ras_misses(seq, depth):
    return 0
```

```python solution
def ras_misses(seq, depth):
    st, miss = [], 0
    for op, addr in seq:
        if op == 'call':
            st.append(addr)
            if len(st) > depth:
                st.pop(0)
        else:
            if st and st[-1] == addr:
                st.pop()
            else:
                miss += 1
                if st:
                    st.pop()
    return miss
```

```python tests
rec = lambda d: [('call', i) for i in range(d)] + [('ret', i) for i in reversed(range(d))]
assert ras_misses(rec(10), 16) == 0, "Recursion within the stack: perfect."
assert ras_misses(rec(20), 16) == 4, "Twenty deep on a 16-entry stack: the 4 deepest-beyond returns miss."
```

::: right
Right. Overflow costs exactly the calls beyond the stack's depth, which is why recursion-heavy code sees return mispredictions.
:::
:::

::: check
kind: python

## Write `alias_prob(branches, n)`: the probability that a given branch shares its entry in a table of $2^n$ entries with at least one of the other branches, placed uniformly; and `alias_sim(branches, n, trials, seed)`: estimate it by simulation.

```python starter
def alias_prob(branches, n):
    return 0.0

def alias_sim(branches, n, trials, seed):
    return 0.0
```

```python solution
import random

def alias_prob(branches, n):
    return 1 - (1 - 2 ** -n) ** (branches - 1)

def alias_sim(branches, n, trials, seed):
    r = random.Random(seed)
    hits = 0
    for _ in range(trials):
        mine = r.randrange(1 << n)
        hits += any(r.randrange(1 << n) == mine for _ in range(branches - 1))
    return hits / trials
```

```python tests
p = alias_prob(2000, 12)
assert abs(p - 0.3863) < 1e-4, "2000 branches, 4096 entries: 39%."
assert abs(alias_sim(2000, 12, 3000, 1) - p) < 0.03, "Simulation agrees."
```

::: right
Right. Aliasing grows quickly with the number of branches, which is why gshare spreads them by history and TAGE adds tags.
:::
:::

::: explain
## Why does a 2-bit counter predict a random 70%-taken branch worse than simply always predicting taken?

::: model
Always predicting taken is right exactly 70% of the time. The counter usually sits in a taken state, but every so often two not-taken outcomes arrive together and push it into a not-taken state. While it's there it predicts not taken, which for this branch is right only 30% of the time, until two taken outcomes push it back. Those excursions follow random runs that carry no information about the future, so each costs accuracy, and the long-run result is about 64%. Hysteresis helps when outcomes come in patterns or long runs; on independent outcomes, any reaction to recent history only adds mistakes.
:::
:::
