SYSTARS Development Workflow
This guide explains how to develop, test, and verify RTL components in the SYSTARS project using Amaranth HDL and cocotb.
Overview
Section titled “Overview”SYSTARS uses a modern Python-based RTL development flow:
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐│ Amaranth HDL │────>│ Verilog Gen │────>│ Cocotb Tests ││ (Python) │ │ (gen/*.v) │ │ (Verilator) │└─────────────────┘ └─────────────────┘ └─────────────────┘ │ │ ▼ ▼┌─────────────────┐ ┌─────────────────┐│ Unit Tests │ │ Waveforms ││ (pytest) │ │ (*.vcd) │└─────────────────┘ └─────────────────┘| Layer | Tool | Purpose |
|---|---|---|
| RTL Description | Amaranth HDL | Python-based hardware description |
| Unit Tests | pytest + Amaranth simulator | Fast Python-level verification |
| RTL Generation | amaranth.back.verilog |
Convert to synthesizable Verilog |
| RTL Simulation | cocotb + Verilator | Cycle-accurate Verilog simulation |
| Waveform Debug | GTKWave | Visual signal inspection |
Getting Started
Section titled “Getting Started”Prerequisites
Section titled “Prerequisites”- Python 3.10+ with virtual environment
- OSS-CAD-SUITE (provides Verilator, Yosys, GTKWave)
- just command runner
Initial Setup
Section titled “Initial Setup”# Clone the repositorygit clone https://github.com/stillwater-sc/systars.gitcd systars
# Run automated setup (creates venv, installs deps, downloads tools if needed)./bin/setup-dev-env.sh
# Or if OSS-CAD-SUITE is already installed:just setup
# Activate the virtual environmentsource .venv/bin/activate
# Verify tools are availablejust check-toolsProject Structure
Section titled “Project Structure”systars/├── src/systars/ # Amaranth RTL source code│ ├── config.py # Central configuration│ ├── core/ # PE, PEArray, SystolicArray components│ └── memory/ # Scratchpad, Combiner├── tests/unit/ # Python unit tests (pytest)├── verif/cocotb/tests/ # RTL simulation tests (cocotb)│ ├── pe/│ ├── pe_array/│ ├── systolic_array/│ ├── scratchpad/│ └── combiner/├── gen/ # Generated Verilog (gitignored)├── scripts/ # RTL generation scripts├── docs/ # Documentation pages (Markdown)└── docs-site/ # Starlight site built from docs/Development Workflow
Section titled “Development Workflow”1. Write Amaranth RTL
Section titled “1. Write Amaranth RTL”Create or modify components in src/systars/. Amaranth uses Python to describe hardware:
from amaranth import Module, Signal, signed, unsignedfrom amaranth.lib.wiring import Component, In, Out
from ..config import SystolicConfig
class MyComponent(Component): """ A new hardware component.
Ports: input_data: Input data signal output_data: Processed output valid: Data valid flag """
def __init__(self, config: SystolicConfig): self.config = config
# Define the component's interface super().__init__({ "input_data": In(signed(config.input_bits)), "output_data": Out(signed(config.acc_bits)), "valid": Out(1), })
def elaborate(self, _platform): m = Module()
# Combinational logic m.d.comb += self.output_data.eq(self.input_data << 2)
# Sequential logic (registered) m.d.sync += self.valid.eq(1)
return mKey Amaranth Patterns:
| Pattern | Code | Description |
|---|---|---|
| Combinational | m.d.comb += sig.eq(value) |
Wire assignment |
| Sequential | m.d.sync += sig.eq(value) |
Registered (clocked) |
| Conditional | with m.If(cond): |
Mux/conditional logic |
| Submodule | m.submodules.name = Module() |
Instantiate child |
| Memory | Memory(shape=..., depth=...) |
RAM/ROM |
2. Write Unit Tests
Section titled “2. Write Unit Tests”Create pytest tests in tests/unit/ to verify Python-level behavior:
import pytestfrom amaranth.sim import Simulator
from systars.config import SystolicConfigfrom systars.core.example import MyComponent
class TestMyComponent: @pytest.fixture def config(self): return SystolicConfig()
@pytest.fixture def dut(self, config): return MyComponent(config)
def test_instantiation(self, dut): """Test that the component can be instantiated.""" assert dut is not None
def test_output_scaling(self, dut): """Test that output is input << 2."""
async def testbench(ctx): # Amaranth 0.5 async testbench API ctx.set(dut.input_data, 5) await ctx.tick() # Advance one clock result = ctx.get(dut.output_data) assert result == 20, f"Expected 20, got {result}"
sim = Simulator(dut) sim.add_clock(1e-6) sim.add_testbench(testbench) sim.run()Run unit tests:
just test-unit # Run all unit testsjust test-file tests/unit/test_example.py # Run specific filejust test-k "test_output" # Run tests matching pattern3. Generate Verilog
Section titled “3. Generate Verilog”Once unit tests pass, generate synthesizable Verilog:
just gen # Generate every target into gen/just gen-pe # Generate PE Verilogjust gen-pe-array # Generate PEArray Verilogjust gen-systolic-array # Generate SystolicArray VerilogThe targets (python3 -m systars.targets list) are in src/systars/targets.py, the one
list that just gen, just synth and CI read. To generate and synthesize a new module, add
a Target there.
Or manually:
from amaranth.back import verilogfrom systars.config import SystolicConfigfrom systars.core.example import MyComponent
config = SystolicConfig()component = MyComponent(config)rtl = verilog.convert(component, name="MyComponent")
with open("gen/mycomponent.v", "w") as f: f.write(rtl)4. Write Cocotb Tests
Section titled “4. Write Cocotb Tests”Create RTL simulation tests in verif/cocotb/tests/<component>/:
Directory structure:
verif/cocotb/tests/mycomponent/├── Makefile├── __init__.py└── test_mycomponent.pyMakefile (recipe lines must start with a tab):
# Makefile for MyComponent cocotb tests
SIM ?= verilatorTOPLEVEL_LANG ?= verilog
PROJECT_ROOT := $(shell cd ../../../.. && pwd)GEN_DIR := $(PROJECT_ROOT)/gen
VERILOG_SOURCES = $(GEN_DIR)/mycomponent.vTOPLEVEL = MyComponentCOCOTB_TEST_MODULES = test_mycomponent
# Disable pytest assertion rewriting conflictsexport COCOTB_REWRITE_ASSERTION_FILES :=
# Verilator lint waivers for Amaranth-generated codeifeq ($(SIM),verilator)EXTRA_ARGS += --timingEXTRA_ARGS += -Wno-WIDTHEXPANDEXTRA_ARGS += -Wno-WIDTHTRUNCEXTRA_ARGS += -Wno-UNUSEDSIGNALEXTRA_ARGS += -Wno-DECLFILENAMEEXTRA_ARGS += -Wno-PROCASSINITendif
include $(shell cocotb-config --makefiles)/Makefile.sim
.PHONY: gen-rtlgen-rtl: @echo "Generating MyComponent Verilog..." @cd $(PROJECT_ROOT) && python3 -c "\from systars.config import SystolicConfig; \from systars.core.example import MyComponent; \from amaranth.back import verilog; \config = SystolicConfig(); \comp = MyComponent(config); \import os; os.makedirs('gen', exist_ok=True); \open('gen/mycomponent.v', 'w').write(verilog.convert(comp, name='MyComponent')); \print('Generated gen/mycomponent.v')"
.PHONY: test-alltest-all: gen-rtl $(MAKE) simTest file:
import cocotbfrom cocotb.clock import Clockfrom cocotb.triggers import RisingEdge
async def reset_dut(dut): """Reset the DUT.""" dut.rst.value = 1 await RisingEdge(dut.clk) await RisingEdge(dut.clk) dut.rst.value = 0 await RisingEdge(dut.clk)
@cocotb.test()async def test_reset(dut): """Test initial state after reset.""" clock = Clock(dut.clk, 10, unit="ns") cocotb.start_soon(clock.start())
await reset_dut(dut)
# Verify initial state assert dut.valid.value == 0, "valid should be 0 after reset" dut._log.info("Reset test passed")
@cocotb.test()async def test_scaling(dut): """Test output = input << 2.""" clock = Clock(dut.clk, 10, unit="ns") cocotb.start_soon(clock.start())
await reset_dut(dut)
# Apply input dut.input_data.value = 5 await RisingEdge(dut.clk) await RisingEdge(dut.clk)
# Check output result = dut.output_data.value.to_signed() assert result == 20, f"Expected 20, got {result}"
dut._log.info(f"Scaling test passed: 5 << 2 = {result}")5. Run Cocotb Tests
Section titled “5. Run Cocotb Tests”just test-cocotb # Run all cocotb testsjust test-cocotb-component pe # Run specific componentjust test-cocotb-component scratchpad # Run memory testsjust test-cocotb-component systolic_top # Matmul and Conv2d on the whole tilesystolic_top simulates the whole tile, so its tests import systars: tb/isa.py runs an
ISA instruction in Amaranth and the test pushes its commands onto the Verilated tile. Its
Makefile puts src/ on PYTHONPATH for that.
Investigating Failures
Section titled “Investigating Failures”Unit Test Failures
Section titled “Unit Test Failures”# Run with verbose outputpytest tests/unit/test_example.py -v -s
# Run with debugger on failurepytest tests/unit/test_example.py --pdb
# Run specific testpytest tests/unit/test_example.py::TestMyComponent::test_scaling -vCocotb Test Failures
Section titled “Cocotb Test Failures”- Check the log output - cocotb prints detailed timing information
- Generate waveforms - Add to your test:
@cocotb.test()async def test_with_waves(dut): # Waveforms are automatically generated as dump.vcd ...- View waveforms:
just waves # Opens GTKWave with the most recent .vcd file# Or manually:gtkwave verif/cocotb/tests/mycomponent/sim_build/dump.vcd- Add debug logging:
dut._log.info(f"Signal value: {dut.some_signal.value}")dut._log.info(f"As signed: {dut.some_signal.value.to_signed()}")dut._log.info(f"As hex: {hex(dut.some_signal.value.to_unsigned())}")Common Issues
Section titled “Common Issues”| Issue | Cause | Solution |
|---|---|---|
AttributeError: 'NoneType' |
Signal doesn’t exist | Check signal name matches Verilog |
to_signed() returns large positive |
Value is unsigned | Use two’s complement: (1 << bits) - value |
| Test hangs | Missing clock or await |
Ensure cocotb.start_soon(clock.start()) |
UnusedElaboratable warning |
Fixture creates unused DUT | Filtered in pyproject.toml |
Running the Full Test Suite
Section titled “Running the Full Test Suite”# Quick check (no RTL tools needed)just check
# Full CI pipelinejust ci
# Individual stepsjust lint # Lint Python and RTLjust test-unit # Python unit testsjust test-cocotb # RTL simulation testsjust synth-check # Yosys synthesis checkCI runs the same recipes (.github/workflows/). just ci covers the lint, unit-test, cocotb and
synth-check jobs; CI also runs just synth <target> for each Yosys target, the pre-commit hooks
and the docs build, so run those too before pushing a change that touches them (just synth ice40, pre-commit run --all-files, just docs):
| Workflow | Job | Runs |
|---|---|---|
lint.yml |
Python Lint | just lint-python, just format-check, just typecheck |
lint.yml |
RTL Lint | just gen, just lint-rtl (every target; the waivers live in the justfile) |
test.yml |
Unit Tests (3.10, 3.12) | just test-unit |
test.yml |
Unit Tests (3.11) | just test-cov xml (the same tests, with coverage for Codecov) |
test.yml |
RTL Tests, one job per suite | just test-cocotb-component <suite> |
lint.yml |
Pre-commit Hooks | pre-commit/action, the same hooks as pre-commit run --all-files (not in just ci) |
docs.yml |
Build Documentation | npm run build in docs-site/, what just docs runs (not in just ci) |
synthesis.yml |
Yosys Synthesis Check | just gen, just synth-check, just synth <target> (just ci runs only synth-check) |
No workflow generates RTL itself: every file comes from systars.targets, through just gen
or a cocotb Makefile’s gen-rtl. A new cocotb suite goes in both just test-cocotb and the
rtl-tests matrix in test.yml.
Synthesis
Section titled “Synthesis”just synth <target> maps every generated module onto a device’s cells with Yosys and
prints the cell counts. CI runs it for each target, and just synth-report writes the
Markdown report that CI uploads.
| Target | Yosys command | Device cells |
|---|---|---|
generic |
synth |
Yosys’s internal gates |
ice40 |
synth_ice40 -noflatten |
Lattice iCE40: SB_LUT4, SB_CARRY, SB_DFF*, SB_RAM40_4K |
ecp5 |
synth_ecp5 -noflatten |
Lattice ECP5: LUT4, CCU2C, TRELLIS_FF, DP16KD, MULT18X18D |
polarfire |
synth_microchip -family polarfire -noflatten -noiopad |
Microchip PolarFire: CFG1-CFG4, ARI1, SLE, MACC_PA, RAM1K20 |
This is a check, not an FPGA build. It shows that the RTL maps onto real cells and gives a
resource estimate, with no place and route, timing or bitstream. iCE40 and ECP5 have open
place and route (nextpnr); PolarFire’s is Libero. The vendor flows run hierarchically
(-noflatten), so the counts are per module and Yosys can’t delete logic that no top-level
port observes.
PolarFire flip-flops have no power-up value, so the polarfire flow first drops the initial
values Amaranth writes:
- Registers (
attrmap -remove init). Every register also has a synchronous reset, so this is safe as long as the design is reset before use. - Memories (
delete t:$meminit_v2). The targets’ memories (scratchpad, Combiner) start at zero only in simulation. On hardware a word nobody has written reads back unspecified, and so do the bytes a masked write leaves out. Today’s targets map their memories to block RAM without this step, butSystolicTopwould need it, as kpugen’s tiles do.
What that means:
- The design never reads a scratchpad or Combiner word it hasn’t written: the
Streamer reads the L2 rows a LOAD (or a
CLEAR) wrote, and Matmul writes a Combiner row withCOMPUTEon its first k-slice and accumulates only after that, or onto the values a Combiner LOAD wrote first (a bias, or the C being accumulated onto).test_no_read_before_write(tests/unit/test_gemm_systolic.py) runs OS, WS and IS GEMMs, withCOMPUTE_ACCUMULATEand partial rows, from random scratchpad and Combiner contents, and checks that C is still exact. - The host must write what it reads. A
COMPUTE_ACCUMULATEonto a Combiner row that neither aCOMPUTEnor a Combiner LOAD wrote, a Combiner LOAD with the add flag (LocalAddrbit 30) onto such a row, aCOMPUTEon a scratchpad slot that no LOAD filled, or a STORE of unwritten rows returns unspecified data on hardware where the simulation returns zero. - Preloads.
tests/unit/test_targets.pychecks that no target has non-zero memory contents, so the step drops nothing a target relies on.
The numbers for a 16x16 array are in the PolarFire deployment plan.
Documentation
Section titled “Documentation”The site at https://stillwater-sc.github.io/systars/ is built with Astro Starlight, the same setup as stillwater-sc/universal and stillwater-sc/mtl5. It needs Node.js 22.23.4 or later.
just docs # Build the site into docs-site/dist (npm ci, npm run build)just docs-serve # Serve it locally with live reloadWhile just docs-serve runs, an edit, a new page or a removed page in docs/ (or
CHANGELOG.md) re-runs the sync and the browser reloads; no restart is needed.
- Write pages in
docs/as plain Markdown, starting with an H1 (it becomes the page title).docs-site/sync-content.mjsgeneratesdocs-site/src/content/docs/fromdocs/andCHANGELOG.md. That directory is git-ignored, so never edit it. - A page in a subdirectory of
docs/(design/,architecture/,plan/,sessions/) appears in that sidebar group automatically. A page at the top ofdocs/needs an entry inROOT_PAGESinsync-content.mjs, or the sync fails. - Link pages with relative paths (
[ISA](isa-instructions.md#corner-turns)), so the links work on GitHub too; the sync rewrites them for the site. Images and other files underdocs/are served from/systars/assets/. A link to another file in the repository becomes a GitHub link. - A link that resolves to nothing fails the sync, and a broken internal link or
anchor fails the build (
starlight-links-validator). - Starlight-native pages (MDX with Starlight components, such as the landing page)
live in
docs/site/and are copied as they are. - CI (
.github/workflows/docs.yml) builds the site on every pull request that touches the docs, and deploys it frommain.
Best Practices
Section titled “Best Practices”Amaranth RTL
Section titled “Amaranth RTL”- Use
Componentbase class for clean interfaces - Document ports in docstrings
- Keep
elaborate()focused - extract complex logic to methods - Use
SystolicConfigfor all parameterization - Prefer
signed()for arithmetic signals
Unit Tests
Section titled “Unit Tests”- Test instantiation first - catches import/syntax errors
- Test port existence - verify interface matches spec
- Test edge cases - zero, max, negative values
- Use fixtures for common setup
Cocotb Tests
Section titled “Cocotb Tests”- Always reset the DUT before testing
- Use
unit="ns"(not deprecatedunits) - Use
to_signed()(not deprecatedsigned_integer) - Add meaningful log messages for debugging
- Test timing - verify latencies match design
Adding a New Component
Section titled “Adding a New Component”- Create Amaranth module in
src/systars/<category>/ - Add to
__init__.pyexports - Create unit tests in
tests/unit/test_<component>.py - Create cocotb test directory
verif/cocotb/tests/<component>/ - Add Makefile and test file
- Add to
justfilecomponent list intest-cocotb - Add generation script if needed
Tool Reference
Section titled “Tool Reference”| Command | Description |
|---|---|
just |
Show all available commands |
just setup |
Initial project setup |
just test |
Run all tests (unit + cocotb) |
just test-unit |
Run Python unit tests |
just test-cocotb |
Run all cocotb RTL tests |
just test-cocotb-component <name> |
Run single component tests |
just gen |
Generate all Verilog |
just synth <target> |
Map every module onto generic, iCE40, ECP5 or PolarFire cells |
just synth-report |
Write the resource utilization report |
just lint |
Run all linters |
just format |
Format Python code |
just waves |
Open waveform viewer |
just docs |
Build the documentation site |
just docs-serve |
Serve the documentation site locally |
just check-tools |
Verify tool installation |
just check-ruff-version |
Verify ruff version consistency |
Troubleshooting
Section titled “Troubleshooting”“No module named ‘systars’”
Section titled ““No module named ‘systars’””pip install -e ".[dev]"Verilator not found
Section titled “Verilator not found”# Check OSS-CAD-SUITE is in PATHexport PATH="/opt/oss-cad-suite/bin:$PATH"# Or set environment variableexport OSS_CAD_SUITE=/path/to/oss-cad-suiteCocotb pytest traceback
Section titled “Cocotb pytest traceback”The COCOTB_REWRITE_ASSERTION_FILES env var should be set to empty in the Makefile. This is already configured in all test Makefiles.
Ruff formatting conflicts
Section titled “Ruff formatting conflicts”just check-ruff-version # Verify versions matchjust update-ruff # Update all configs to latest