---
title: Verification lab
heading: Coverage by simulation, a scoreboard against a reference model, and LFSR stimulus, in Python
eyebrow: S3 · Lesson 29 · Verification lab
xp: 60
---

::: hook
A testbench is software, and the habits of lessons 25 and 26 are easiest to learn by writing one. This lab measures random coverage by simulation and checks it against the coupon-collector formulas, builds a scoreboard that compares a FIFO against a reference model and reports the first mismatch, and generates stimulus with a linear-feedback shift register whose period shows whether its taps are maximal. Each piece is small, and each catches a different kind of mistake.
:::

::: play
- The line is the expected coverage of a coverpoint with N equally likely bins after n random tests, $1 - (1 - 1/N)^n$; the dashed line marks n = $NH_N$, the expected number of tests to fill every bin.
- Coverage climbs quickly at first: half the bins take well under N tests. The last few bins take as long as all the others.
- The lab simulates this and compares.
:::

```sim plot
view: graph
x: n = 1..2000
y: c = 0..1
slider: N = 8..256 step 8 = 64
plot: 1 - (1 - 1/N)^n | label: expected coverage
readout: tests to fill (N H_N, approx.) = N*(ln(N) + 0.577) | digits: 4
```

::: predict
## A FIFO of depth 8 accepts a push when it's full, overwriting its oldest entry instead of refusing. A scoreboard compares its pops with a reference model's. When does the scoreboard first complain?

- [ ] At the push that overflows
- [x] At the first pop that returns a different value than the model, which may be many cycles after the overflow
- [ ] Never, if the testbench only pushes and pops random data
- [ ] At the end of the test, when the counts differ

::: reveal
A push doesn't produce output, so the overflow itself is invisible to a scoreboard that compares outputs. The corruption shows up when the overwritten entry would have been popped: the DUT returns newer data where the model returns the old value. That delay is why designers also add assertions (never push while full) that fire at the cause.
:::
:::

::: nameit
## The pieces

- **Coverage:** sample bins at random; the covered fraction should track $1 - (1 - 1/N)^n$, and filling all bins takes $NH_N$ tests on average.
- **Reference model and scoreboard:** run the same operations through a simple, obviously correct model (here a deque) and compare each output with the design's; report the first index where they differ.
- **LFSR stimulus:** a Fibonacci LFSR of n bits shifts right and feeds back the XOR of its tap bits; with maximal taps (such as 16, 14, 13, 11) it cycles through all $2^n - 1$ nonzero states.
:::

::: check
kind: python

## Write `coverage(n_bins, tests, trials, seed)`: in each trial draw `tests` bins uniformly with `random.Random(seed)` and record the fraction of bins hit; return the average over the trials. Write `fill(n_bins, trials, seed)`: the average number of draws needed to hit every bin.

```python starter
import random

def coverage(n_bins, tests, trials, seed):
    return 0.0

def fill(n_bins, trials, seed):
    return 0.0
```

```python solution
import random

def coverage(n_bins, tests, trials, seed):
    r = random.Random(seed)
    tot = 0.0
    for _ in range(trials):
        tot += len({r.randrange(n_bins) for _ in range(tests)}) / n_bins
    return tot / trials

def fill(n_bins, trials, seed):
    r = random.Random(seed)
    tot = 0
    for _ in range(trials):
        seen, k = set(), 0
        while len(seen) < n_bins:
            seen.add(r.randrange(n_bins))
            k += 1
        tot += k
    return tot / trials
```

```python tests
assert abs(coverage(64, 200, 300, 1) - (1 - (1 - 1 / 64) ** 200)) < 0.01, "200 tests on 64 bins: about 95.7%."
H = sum(1 / i for i in range(1, 65))
assert abs(fill(64, 400, 2) / (64 * H) - 1) < 0.03, "Filling 64 bins takes about 304 tests."
```

::: right
Right. Simulated coverage follows the formula, so the formula is a fair estimate of a random test plan's cost.
:::
:::

::: check
kind: python

## Write `scoreboard(ops, outs, depth)`: ops is a list of ('push', value) or ('pop', 0); outs is the design's output for each op (None for pushes and for pops of an empty FIFO). Model a FIFO of the given depth that refuses pushes when full, and return the index of the first op whose output differs from the model's, or None.

```python starter
def scoreboard(ops, outs, depth):
    return None
```

```python solution
from collections import deque

def scoreboard(ops, outs, depth):
    q = deque()
    for i, (op, val) in enumerate(ops):
        if op == 'push':
            if len(q) < depth:
                q.append(val)
            exp = None
        else:
            exp = q.popleft() if q else None
        if outs[i] != exp:
            return i
    return None
```

```python tests
import random
def dut(ops, depth, bug=False):
    mem, w, r, n, outs = [0] * depth, 0, 0, 0, []
    for op, val in ops:
        if op == 'push':
            if n < depth or bug:
                mem[w % depth] = val
                w += 1
                n += 1
            outs.append(None)
        elif n > 0:
            outs.append(mem[r % depth])
            r += 1
            n -= 1
        else:
            outs.append(None)
    return outs
rng = random.Random(5)
ops = [('push', rng.randrange(256)) if rng.random() < 0.6 else ('pop', 0) for _ in range(500)]
assert scoreboard(ops, dut(ops, 8), 8) is None, "A correct FIFO matches the model."
k = scoreboard(ops, dut(ops, 8, bug=True), 8)
assert k is not None and ops[k][0] == 'pop', "The overwriting FIFO is caught, at a pop."
```

::: right
Right. The scoreboard catches the bug only when bad data comes out; an assertion on push-while-full would catch it at the cause.
:::
:::

::: check
kind: python

## Write `lfsr_period(taps, n)`: start an n-bit Fibonacci LFSR at state 1; each step compute the XOR of bits (n − t) for each tap t (bit 0 the least significant), shift right by one and put that bit in at the top. Return the number of steps until the state returns to 1.

```python starter
def lfsr_period(taps, n):
    return 1
```

```python solution
def lfsr_period(taps, n):
    s, k = 1, 0
    while True:
        bit = 0
        for t in taps:
            bit ^= (s >> (n - t)) & 1
        s = (s >> 1) | (bit << (n - 1))
        k += 1
        if s == 1:
            return k
```

```python tests
assert lfsr_period([4, 3], 4) == 15, "Taps 4, 3: maximal, 15 states."
assert lfsr_period([4, 2], 4) == 6, "Taps 4, 2: not maximal."
assert lfsr_period([16, 14, 13, 11], 16) == 65535, "The standard 16-bit taps: 65 535 states."
```

::: right
Right. A wrong tap set gives short cycles, and a random-looking stimulus that repeats after a few states leaves most of the design untested.
:::
:::

::: explain
## Why does a testbench need both a scoreboard and assertions?

::: model
A scoreboard compares what the design outputs with what a reference model predicts, so it catches any bug that eventually produces a wrong output, whatever its cause. But it only notices when the wrong data comes out, which can be long after the mistake happened, and it says nothing about internal rules that don't immediately affect outputs. Assertions check those rules where they apply, such as never pushing into a full FIFO, and fire in the cycle the rule is broken, pointing straight at the cause. The scoreboard gives broad end-to-end checking; assertions give early, precise diagnosis.
:::
:::
