"""cocotb tests for muladd_pipe.sv with a NumPy reference model. Structure: a driver task feeds samples (with random idle cycles), a monitor task collects every result, and a scoreboard compares them in order with the reference model. The monitor also measures the latency of each sample. """ from __future__ import annotations from collections import deque import numpy as np import cocotb from cocotb.clock import Clock from cocotb.triggers import ClockCycles, ReadOnly, RisingEdge from models import muladd_ref LATENCY = 3 class Scoreboard: """In-order scoreboard: expected values go in, DUT results are checked.""" def __init__(self) -> None: self.expected: deque[tuple[int, int]] = deque() # (value, cycle sent) self.checked = 0 self.errors: list[str] = [] def add_expected(self, value: int, cycle: int) -> None: self.expected.append((value, cycle)) def check(self, got: int, cycle: int) -> None: if not self.expected: self.errors.append(f"cycle {cycle}: unexpected output {got}") return want, sent = self.expected.popleft() if got != want: self.errors.append(f"cycle {cycle}: got {got}, expected {want}") if cycle - sent != LATENCY: self.errors.append(f"cycle {cycle}: latency {cycle - sent}, expected {LATENCY}") self.checked += 1 async def monitor(dut, sb: Scoreboard) -> None: """Sample the outputs after every rising edge.""" cycle = 0 while True: await RisingEdge(dut.clk) cycle += 1 await ReadOnly() if dut.out_valid.value == 1: sb.check(dut.y.value.to_signed(), cycle) async def drive(dut, sb: Scoreboard, a: np.ndarray, b: np.ndarray, c: np.ndarray, idle_prob: float, rng: np.random.Generator) -> None: """Present one sample per cycle, with random idle cycles in between. Inputs are written just after a rising edge, so they are stable for the whole cycle and the DUT samples them on the next edge.""" expected = muladd_ref(a, b, c) cycle = 0 i = 0 while i < len(a): await RisingEdge(dut.clk) cycle += 1 if rng.random() < idle_prob: dut.in_valid.value = 0 continue dut.in_valid.value = 1 dut.a.value = int(a[i]) dut.b.value = int(b[i]) dut.c.value = int(c[i]) sb.add_expected(int(expected[i]), cycle) # presented in this cycle i += 1 await RisingEdge(dut.clk) dut.in_valid.value = 0 async def run(dut, a: np.ndarray, b: np.ndarray, c: np.ndarray, idle_prob: float, seed: int) -> Scoreboard: cocotb.start_soon(Clock(dut.clk, 10, unit="ns").start()) dut.rst.value = 1 dut.in_valid.value = 0 await ClockCycles(dut.clk, 3) dut.rst.value = 0 sb = Scoreboard() cocotb.start_soon(monitor(dut, sb)) await drive(dut, sb, a, b, c, idle_prob, np.random.default_rng(seed)) await ClockCycles(dut.clk, LATENCY + 2) # let the pipeline drain assert not sb.errors, "\n".join(sb.errors[:10]) assert not sb.expected, f"{len(sb.expected)} results never came out" assert sb.checked == len(a) return sb @cocotb.test() async def corner_cases(dut) -> None: """Extreme values back to back, no idle cycles.""" lo, hi = -(2**15), 2**15 - 1 clo, chi = -(2**31), 2**31 - 1 a = np.array([0, 1, -1, lo, lo, hi, hi, lo, 0], dtype=np.int64) b = np.array([0, -1, -1, lo, hi, hi, lo, lo, hi], dtype=np.int64) c = np.array([0, 0, 0, chi, clo, chi, clo, clo, -1], dtype=np.int64) await run(dut, a, b, c, idle_prob=0.0, seed=1) @cocotb.test(timeout_time=200, timeout_unit="us") @cocotb.parametrize(idle_prob=[0.0, 0.3]) async def random_samples(dut, idle_prob: float) -> None: """5000 random samples, run once without and once with idle cycles.""" rng = np.random.default_rng(cocotb.RANDOM_SEED) n = 5000 a = rng.integers(-(2**15), 2**15, n) b = rng.integers(-(2**15), 2**15, n) c = rng.integers(-(2**31), 2**31, n) sb = await run(dut, a, b, c, idle_prob, seed=cocotb.RANDOM_SEED + 1) dut._log.info(f"idle_prob={idle_prob}: {sb.checked} results checked")