"""cocotb tests for systolic_array.sv: every tile is compared bit for bit with a NumPy integer matmul. 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 EXTREMES = np.array([-128, -127, -1, 0, 1, 126, 127]) def pack(values: np.ndarray, width: int) -> int: """Pack signed integers into one unsigned bus value, element 0 in the low bits.""" word = 0 for i, v in enumerate(values): word |= (int(v) & ((1 << width) - 1)) << (width * i) return word def unpack_c(word: int, n: int) -> np.ndarray: c = np.zeros((n, n), dtype=np.int64) for idx in range(n * n): v = (word >> (32 * idx)) & 0xFFFFFFFF c[idx // n, idx % n] = v - (1 << 32) if v & 0x80000000 else v return c def random_int8(rng: np.random.Generator, shape: tuple[int, ...]) -> np.ndarray: """Uniform INT8 values with about 30 % taken from the extreme set.""" x = rng.integers(-128, 128, size=shape) pick = rng.random(shape) < 0.3 x[pick] = rng.choice(EXTREMES, size=int(pick.sum())) return x def schedule_tiles(tiles: list[tuple[np.ndarray, np.ndarray]], n: int, rng: np.random.Generator | None) -> list[dict | None]: """One entry per clock cycle: a beat (dict) or None for an idle cycle. Optional random idle cycles inside a tile. Between tiles, idle cycles are added so that two in_last beats are at least 2N-1 cycles apart. """ cycles: list[dict | None] = [] last_at = -10**9 for a, b in tiles: k = a.shape[1] for kk in range(k): if rng is not None and kk > 0 and rng.random() < 0.2: cycles.extend([None] * int(rng.integers(1, 4))) if kk == k - 1: while len(cycles) - last_at < 2 * n - 1: cycles.append(None) cycles.append({"a": a[:, kk], "b": b[kk, :], "first": kk == 0, "last": kk == k - 1}) if kk == k - 1: last_at = len(cycles) - 1 return cycles async def run_schedule(dut, cycles: list[dict | None], n: int) -> list[np.ndarray]: """Drive the beats, return every C tile seen when out_valid is high.""" results: list[np.ndarray] = [] for beat in cycles + [None] * (2 * n + 2): await FallingEdge(dut.clk) if beat is None: dut.in_valid.value = 0 dut.in_first.value = 0 dut.in_last.value = 0 else: dut.in_valid.value = 1 dut.in_first.value = int(beat["first"]) dut.in_last.value = int(beat["last"]) dut.a_col.value = pack(beat["a"], 8) dut.b_row.value = pack(beat["b"], 8) await RisingEdge(dut.clk) await ReadOnly() if int(dut.out_valid.value) == 1: results.append(unpack_c(dut.c_out.value.to_unsigned(), n)) return results async def reset(dut) -> int: Clock(dut.clk, 10, unit="ns").start() n = len(dut.a_col) // 8 dut.rst.value = 1 dut.in_valid.value = 0 dut.in_first.value = 0 dut.in_last.value = 0 dut.a_col.value = 0 dut.b_row.value = 0 for _ in range(3): await RisingEdge(dut.clk) await FallingEdge(dut.clk) dut.rst.value = 0 return n async def check_tiles(dut, tiles, n, rng) -> None: got = await run_schedule(dut, schedule_tiles(tiles, n, rng), n) assert len(got) == len(tiles), f"expected {len(tiles)} tiles, saw {len(got)}" for t, ((a, b), c) in enumerate(zip(tiles, got)): expect = L.int_matmul(a, b) assert np.array_equal(c, expect), f"tile {t}: got\n{c}\nexpected\n{expect}" @cocotb.test() async def random_tiles_with_gaps(dut) -> None: """60 random tiles, K from 1 to 40, random idle cycles inside and between tiles.""" n = await reset(dut) rng = np.random.default_rng(11) tiles = [] for _ in range(60): k = int(rng.integers(1, 41)) tiles.append((random_int8(rng, (n, k)), random_int8(rng, (k, n)))) await check_tiles(dut, tiles, n, rng) dut._log.info("60 random tiles match NumPy") @cocotb.test() async def back_to_back_minimum_spacing(dut) -> None: """Tiles with K = 2N-1 and no idle cycles: the tightest legal spacing.""" n = await reset(dut) rng = np.random.default_rng(12) k = 2 * n - 1 tiles = [(random_int8(rng, (n, k)), random_int8(rng, (k, n))) for _ in range(20)] await check_tiles(dut, tiles, n, None) @cocotb.test() async def largest_magnitudes(dut) -> None: """All -128 times -128 and -128 times 127 for K = 64: the largest sums of the classifier size.""" n = await reset(dut) k = 64 tiles = [ (np.full((n, k), -128), np.full((k, n), -128)), (np.full((n, k), -128), np.full((k, n), 127)), (np.full((n, k), 127), np.full((k, n), 127)), ] await check_tiles(dut, tiles, n, None) @cocotb.test() async def classifier_layer(dut) -> None: """The INT8 digit classifier from int8_layer.py, run as N x N output tiles.""" n = await reset(dut) r = L.build() qx = r["qx"][:8] # 8 test images, 64 INT8 inputs each wt = r["layer"].qw.T # 64 x 10 m, k = qx.shape p = wt.shape[1] mp, pp = -(-m // n) * n, -(-p // n) * n a_pad = np.zeros((mp, k), dtype=np.int64) b_pad = np.zeros((k, pp), dtype=np.int64) a_pad[:m], b_pad[:, :p] = qx, wt tiles = [(a_pad[i:i + n], b_pad[:, j:j + n]) for i in range(0, mp, n) for j in range(0, pp, n)] got = await run_schedule(dut, schedule_tiles(tiles, n, None), n) c = np.zeros((mp, pp), dtype=np.int64) for idx, (i, j) in enumerate((i, j) for i in range(0, mp, n) for j in range(0, pp, n)): c[i:i + n, j:j + n] = got[idx] assert np.array_equal(c[:m, :p], r["acc"][:8]) dut._log.info(f"classifier accumulators match for {m} images x {p} classes ({len(tiles)} tiles)")