"""cocotb tests for requant.sv: every output is compared with int8_layer.requantize, bit for bit. These coroutines run inside the simulator. Start them with test_cocotb_ai.py (pytest). """ from __future__ import annotations import numpy as np import cocotb from cocotb.clock import Clock from cocotb.triggers import FallingEdge, ReadOnly, RisingEdge import int8_layer as L LATENCY = 3 async def reset(dut) -> None: Clock(dut.clk, 10, unit="ns").start() dut.rst.value = 1 dut.in_valid.value = 0 for name in ("acc", "bias", "m0", "shift", "zp", "relu"): getattr(dut, name).value = 0 for _ in range(3): await RisingEdge(dut.clk) await FallingEdge(dut.clk) dut.rst.value = 0 async def stream(dut, items: list[tuple[int, int, int, int, int, int] | None]) -> list[int]: """Drive one item (or an idle cycle) per clock; return q for every out_valid cycle.""" out: list[int] = [] for item in items + [None] * (LATENCY + 2): await FallingEdge(dut.clk) if item is None: dut.in_valid.value = 0 else: acc, bias, m0, shift, zp, relu = item dut.in_valid.value = 1 dut.acc.value = acc dut.bias.value = bias dut.m0.value = m0 dut.shift.value = shift dut.zp.value = zp dut.relu.value = relu await RisingEdge(dut.clk) await ReadOnly() if int(dut.out_valid.value) == 1: out.append(dut.q.value.to_signed()) return out @cocotb.test() async def random_and_edge_values(dut) -> None: """4000 random inputs plus corner cases, with random idle cycles.""" await reset(dut) rng = np.random.default_rng(21) items: list[tuple[int, int, int, int, int, int]] = [] edge_acc = [-2**31, 2**31 - 1, 0, -1, 1] for acc in edge_acc: for bias in (-2**31, 2**31 - 1, 0): for m0, shift in ((1 << 30, 0), ((1 << 31) - 1, 0), ((1 << 31) - 1, 31), (1 << 30, 31)): for zp in (-128, 0, 127): for relu in (0, 1): items.append((acc, bias, m0, shift, zp, relu)) for _ in range(4000): m0, shift = L.quantize_multiplier(float(10.0 ** rng.uniform(-9, -0.01))) items.append((int(rng.integers(-2**31, 2**31)), int(rng.integers(-2**24, 2**24)), m0, shift, int(rng.integers(-128, 128)), int(rng.integers(0, 2)))) sched: list = [] for it in items: if rng.random() < 0.1: sched.append(None) sched.append(it) got = await stream(dut, sched) expect = [L.requantize(*it[:5], relu=bool(it[5])) for it in items] assert len(got) == len(expect) bad = [i for i, (g, e) in enumerate(zip(got, expect)) if g != e] assert not bad, f"{len(bad)} mismatches, first at {bad[0]}: {items[bad[0]]} -> {got[bad[0]]}, expected {expect[bad[0]]}" dut._log.info(f"{len(items)} requantised values match the Python model") @cocotb.test() async def classifier_logits(dut) -> None: """Accumulators of the digit classifier with per-channel m0 and shift give the INT8 logits.""" await reset(dut) r = L.build() lay = r["layer"] acc = r["acc"][:40] items = [(int(acc[i, n]), int(lay.bias_eff[n]), int(lay.m0[n]), int(lay.shift[n]), lay.zy, 0) for i in range(acc.shape[0]) for n in range(acc.shape[1])] got = np.array(await stream(dut, items)).reshape(acc.shape) assert np.array_equal(got, r["qy"][:40]) dut._log.info(f"INT8 logits match for {acc.shape[0]} images x {acc.shape[1]} classes")