Skip to content

Test Layers (L1–L5)

A differentiable logic-gate NN is the kind of software that keeps working even when it is broken. Get one term of the gradient wrong and the loss still goes down; reverse the bit order of a truth table and the accuracy still looks fine. Export that, and you find out only once it is Verilog.

Against that structural fragility, this project splits its tests into five layers by the strength of the claim each one makes. The lower layers are faster and stricter; the upper ones slower and more holistic.


graph TD
L1["L1 mathematical properties<br/>tests/l1_math/<br/>'does the formula match the definition?'"]
L2["L2 gradients<br/>tests/l2_grad/<br/>'is the derivative correct?'"]
L3["L3 paper reproduction<br/>tests/l3_paper/<br/>'do we get the paper's numbers?'"]
L4["L4 convergence<br/>tests/l4_learning/<br/>'can it still solve the task after discretization?'"]
L5["L5 hybrid<br/>tests/l5_hybrid/<br/>'do gradients flow when wired to real-valued layers?'"]
HDL["HDL equivalence<br/>tests/hdl/<br/>'is it the same once it is a circuit?'"]
L1 --> L2 --> L4 --> L5 --> HDL
L2 -.->|"when verifying a paper's claim"| L3
classDef fast fill:#0f766e,stroke:#0f766e,color:#fff
classDef slow fill:#b45309,stroke:#b45309,color:#fff
class L1,L2,L4,L5 fast
class L3,HDL slow

Green = the fast suite (runs every time by default); orange = runs only when the marker is given explicitly.

LayerLocationWhat it assertsPassing criterionRuns by default
L1tests/l1_math/Mathematical properties (partition of unity, truth tables, Boolean agreement at binary vertices, the discretization spec)Exact float64 agreement with a naive loop✓
L2tests/l2_grad/Correctness of gradientsgradcheck + comparison against the reference implementation✓
L3tests/l3_paper/Reproduction of a paperThresholds calibrated from measurements-m paper
L4tests/l4_learning/That training convergeshard eval accuracy = 100%✓
L5tests/l5_hybrid/Hybrid integration (gradient flow, the replacement API)Gradients reach the real-valued layers✓
HDLtests/hdl/That the generated circuit behaves identicallyBit-exact agreement on every pattern-m hdl

New model-level and integration tests go into tests/integration/. The flat layout directly under tests/ is a historical leftover — do not move it.


When in doubt, consult this table. The answer is “everything that applies, from the top down”.

What you changedRequired layersWhat to actually write
A custom autograd FunctionL2 + L1A reference implementation in core/reference.py → float64 gradcheck → comparison against the reference → property tests
A formula or basis (butterfly etc.)L1Exact comparison with a naive loop, sweeping all 2n2^n cases
A new layer or componentL1 + L2 + L4→ see “The four steps for adding a new component” below
A learning rule (BP / AP / DFA / ES)L2 + L4Analytic comparison against a pure numpy reference + convergence on a small task
Hybrid work (wiring to real-valued layers, the replacement API)L5Confirm gradients flow all the way to the real-valued layers
The IR schema or serializationEquivalencesimulate output matches torch hard eval
HDL generation (Verilog / VHDL)HDLThree-way equivalence (→ see “Three-way equivalence” below)
A claim from a paper, or a reproduction experimentL3The @paper marker. Fix the threshold only after measuring it
Adding or moving a public APIBackward compatibilityA shim at the old path, plus a line in the backward compatibility tests
CLI or editorIntegrationAn API-level round-trip test in tests/integration/

3. Three-way equivalence — the lifeline of HDL

Section titled “3. Three-way equivalence — the lifeline of HDL”

This is the one invariant around the IR that is absolute.

graph LR
T["PyTorch hard eval<br/>the discrete output of model.eval()"]
S["ir.simulate<br/>bit-exact numpy"]
H["HDL simulation<br/>iverilog / ghdl"]
T ---|"① extraction is correct"| S
S ---|"② generation is correct"| H
T -.-|"③ guaranteed by transitivity"| H

PyTorch hard eval ⇔ ir.simulate ⇔ HDL simulation must agree bit for bit on every input pattern.

  • If ① breaks, the discretization (export_ir) or the truth-table bit convention is wrong
  • If ② breaks, suspect the bit order (MSB / LSB in concatenation) of Verilog / VHDL generation
  • simulate is called the golden model because it contains no floating-point approximation whatsoever — it is integer bit arithmetic in numpy. It is the standard for “how this should behave as a circuit”

Whenever you touch code around the IR, make sure no link in that chain is broken. For details, see HDL export and equivalence checking.


4. The four steps for adding a new component

Section titled “4. The four steps for adding a new component”

When adding a new layer, autograd Function or model, write the tests first. The order matters.

graph LR
R["① reference impl<br/>core/reference.py<br/>written naively"]
G["② L2 gradients<br/>gradcheck + reference comparison"]
P["③ L1 properties<br/>naive comparison, binary vertices"]
C["④ L4 convergence<br/>hard acc=100% on XOR/parity"]
R --> G --> P --> C

① Write the reference implementation (ground truth)

Section titled “① Write the reference implementation (ground truth)”

In griffith_logic/core/reference.py, write the equations from the paper down directly as naive torch operations. No butterfly decomposition, no custom Function, no CUDA kernel. Efficiency is irrelevant; clarity comes first.

For components that do not use autograd (trainers and the like), write a pure numpy reference inside the test instead.

In tests/l2_grad/, run torch.autograd.gradcheck in float64 and compare against the gradient obtained by differentiating the reference implementation from ① with autograd. Always include at least one case at a boundary point (x = 0.0 / 1.0).

STE-style components with a discontinuous forward (argmax, thresholds) cannot use gradcheck in principle. In that case, switch to a contract test.

What is checked
Forward contractExact comparison of the hard output
Backward contractAgreement with the autograd gradient of the soft reference

In tests/l1_math/, verify the properties the component must satisfy (partition of unity, Boolean agreement at binary vertices, linearity, temperature scaling) by exhaustive sweep or hypothesis. Use the shared hypothesis strategies (tests/strategies.py).

This is the only layer that guarantees the reference implementation is correct. If the reference is broken, partition of unity or the binary-vertex property fails, and that is how you find out.

Confirm that small tasks such as XOR / parity reach accuracy = 100% in hard (post-discretization) mode.

model.eval()
with torch.no_grad():
acc = (model(x).argmax(-1) == y).float().mean().item()
assert acc == 1.0, f'XORが学習できない: hard acc={acc}'

Do not judge on soft accuracy. A model that only gets the answers right under the continuous relaxation can break the instant it is discretized, and soft accuracy hides that. If convergence is stochastic, pin the seed to make it deterministic (do not paper over it with a loose threshold). Keep the runtime within a few seconds per component.

A component is not considered finished until all four steps are green.


Never hard-code a tolerance as a numeric literal in a test file. Import the constants from tests/conftest.py.

ConstantValueUsed for
TOL_F64_EQ1e-12Forward agreement in float64
TOL_F64_GRAD1e-10Gradient agreement in float64 (against the reference implementation)
TOL_F32_EQ1e-6Agreement in float32
GRADCHECK_KWatol=1e-6, rtol=1e-3Standard settings for torch.autograd.gradcheck

Hard-coding them means nobody can tell which test is how lax, and the whole suite loosens without anyone noticing. Thresholds can only be monitored once they live in one place.


6. Never loosen a threshold (absolute rule)

Section titled “6. Never loosen a threshold (absolute rule)”

Only when a threshold genuinely has to be reset for mathematical reasons (conditioning, cancellation in a sum, and so on) do you go through this measurement-based calibration procedure.

  1. Run 10 times with different seeds and record the worst value of the metric in question
  2. Take a value with at least 10× headroom over that worst case as the new threshold (worst error 3e-12 → threshold 1e-10)
  3. Record the calibration (worst value, chosen threshold, mathematical justification)
  4. If the threshold is looser than the shared constant in conftest.py, state the reason in a docstring inside the test (do not silently replace the shared constant)

The same holds for @paper thresholds: never guess, always measure before fixing them, and keep the calibration history in the docstring.

The same principle applies to coverage (→ the ratchet policy in Get started). Verification strictness only ever moves upwards.


ターミナルウィンドウ
make test # fast suite. The bar is: always green (under 2 minutes)
make test-all # includes slow (hdl / cuda / paper stay excluded)
make lint # ruff
make type # mypy (strictness is being introduced gradually, core and encoding first)
make cov # coverage measurement
make hdl # HDL equivalence (needs iverilog / ghdl)

You can also run a single layer.

ターミナルウィンドウ
uv run pytest tests/l2_grad/ -q # L2 only
uv run pytest -m paper # paper reproduction (Modal recommended)
uv run pytest -m hdl # Verilog equivalence (needs iverilog)
uv run pytest -m hdl_vhdl # VHDL equivalence (needs ghdl)

The default addopts in pyproject.toml exclude slow / paper / hdl / hdl_vhdl, so plain uv run pytest gives you the fast suite without any arguments.

MarkerMeaningCI
slowTakes a long time to runexcluded
cudaRequires a CUDA GPU (auto-skipped where unavailable)excluded (run on Modal)
paperPaper reproduction (minutes; run nightly / on Modal)excluded
hdlRequires an HDL simulator (iverilog)excluded
hdl_vhdlRequires GHDLexcluded
learningRuns a training loop to assert convergence / accuracyexcluded (does run in a local make test)

learning is kept out of CI because the runtime of a training loop does not fit the CI budget. It does run in a local make test, so always check it on your machine after changing a component.

ターミナルウィンドウ
uv run modal run scripts/modal_app.py::pytest_cuda # @cuda tests
uv run modal run scripts/modal_app.py::pytest_cuda --marker paper # paper reproduction

For submission and monitoring details, see Cloud GPU.