Skip to content

A Mapping Table for PyTorch Users

This library is plain PyTorch. It subclasses nn.Module, loss.backward() works, and torch.optim can be used as-is. Migration is therefore fast.

At the same time, a few things share a name but not a meaning, and that is where accidents happen. The worst offender is model.eval(): in PyTorch it only changes how Dropout and BatchNorm behave, but here it changes the mathematics of the model itself (a real-valued mixture becomes a Boolean circuit).

This page is a translation table from PyTorch vocabulary to the vocabulary of this library.

The minimal mapping — the same network written two ways

Section titled “The minimal mapping — the same network written two ways”
# PyTorch (a real-valued MLP)
import torch.nn as nn
model = nn.Sequential(
nn.Flatten(),
nn.Linear(784, 256), nn.ReLU(),
nn.Linear(256, 256), nn.ReLU(),
nn.Linear(256, 10), # → into cross_entropy
)
# griffith-logic (a logic-gate network)
import torch.nn as nn
from griffith_logic import GroupSum, LutLayer
model = nn.Sequential(
nn.Flatten(),
LutLayer(784, 8000, n_inputs=2), # no activation function needed
LutLayer(8000, 8000, n_inputs=2), # the gates themselves carry the nonlinearity
GroupSum(k=10, tau=10.0), # → into cross_entropy
)

The two look almost identical, and neither loss.backward() nor optimizer.step() changes. What differs is what lives inside a single neuron. One output of nn.Linear is a weighted sum over every input, whereas one output of LutLayer is a single LUT (truth table) that sparsely picks up just N of the input lines, and what is learned is not a weight but which logic function it becomes.


PyTorchHereWhat differsReference
nn.Linear(i, o)LutLayer(i, o, n_inputs=2)Not a dense sum of products but a LUT that picks up only N lines. What is learned is the truth table. Wiring is fixed at initialization (wiring='learnable' makes it trainable too)The Mathematics of LutLayer
nn.ReLU / nn.GELUNot neededThe nonlinearity is built into the LUT. The concept of an activation function does not exist hereWhat is DLGN
nn.Conv2dLutConv2d(in_ch, out_ch, kernel_size, tree_depth=3)The kernel is not a sum of products but a tree of gates. tree_depth sets its depthConvolution and Spatial Processing API
nn.MaxPool2dOrPooling2dmax is arithmetic. On the logic side, aggregation is done with OR5. Exporting a CNN to HDL
nn.BatchNorm / nn.LayerNormLogicLayerNorm and othersNormalization by statistics does not map onto a circuit. Use the logic-based replacementsGeneral NN Blocks API
nn.Linear(h, C) + softmax at the outputGroupSum(k=C, tau)It simply splits the final gate outputs evenly into C groups, sums them, and divides by τ. It carries no weights, and on the circuit side it is a single adderCore Concepts
nn.MultiheadAttentionThe LogicAttention familyThere is an implementation with attention itself made logical (scores via XNOR-popcount, softmax via MUX)Attention Tour
nn.Embedding / input normalizationThermometerEncoder and othersReal-valued inputs are encoded into bit strings first. Inputs are either reals in [0,1][0,1] or 0/1 bits. With ThermometerEncoder(bits, input_bits=8) (the quantization width of the input) the threshold comparisons themselves become 8-input LUTs inside the IR; without it the encoder stays a preprocessing step outside the IRDWN (Thermometer Encoding)
nn.Linear(i, o) + sign (a perceptron layer)LTTLayer(i, o, n_inputs=6)Each gate is a linear threshold function 1[w⋅x+b>0]1[w\cdot x + b > 0] of N inputs. N+1 parameters per gate; it can express only threshold (linearly separable) Boolean functions. Trained with STE, exported as an N-input LUTAPI: core layers
nn.DropoutUsually not usedRegularization is normally tuned through capacity (gate count k) and the amount of trainingRunning Training

That is the entirety of what GroupSum does.

logitc=1τ∑i∈groupcyi\text{logit}_c = \frac{1}{\tau}\sum_{i \in \text{group}_c} y_i

If the output dimension is not divisible by the number of classes, an assert fires. τ affects accuracy directly: for a 6-layer MNIST model with k=8000, a fixed τ=10 is about 1.0pt better than the rule of thumb τ=k/C\tau=\sqrt{k/C}.

PyTorchHereWhat differsReference
Hand-written training looprun_training(cfg) / uv run griffith train recipe.yamlConfigs are validated with pydantic (unknown keys fail before the run starts). The CLI is a thin wrapper over the API with identical internalsRunning Training
torch.optim.Adam(model.parameters(), lr=1e-3)The same, except lr is 0.01–0.3Logic-side weights prefer learning rates 1–2 orders of magnitude larger than real-valued weights. independent sometimes needs lr ≥ 0.3Choosing a Parameterization
Hand-written param groupssplit_param_groups(model, logic_lr=0.02, ann_lr=1e-3)In hybrid setups it automatically separates the logic-side and real-valued lr. With a single shared lr, the logic side does not move2. Building a Hybrid NN
Backprop onlywith_learning(module, LearningSpec(rule=...)) + HybridTrainerYou can mix bp / ap / dfa / eggroll per layer. with_learning only annotates attributes rather than wrapping, so it can be bolted onto an existing modelLearning Rules (BP/AP/DFA/ES)
Reporting a single accAlways report both soft and hardtest_acc_soft is the score of the continuous approximation; test_acc (hard) is the true score as a circuitReading Training Curves
model.eval()model.eval() — but it means something elseIt discretizes with argmax and becomes a Boolean circuit. See belowWhat is DLGN
PyTorchHereWhat differsReference
torch.onnx.export(model, ...)export_ir(model, input_width=..., name=...)The output is IR (JSON): a neutral representation holding only truth tables and wiring, belonging neither to torch nor to HDL. For conv models, export_ir(model, input_shape=(C, H, W), native_conv=True) keeps conv2d / or_pool2d nodes (weight sharing is preserved)Working with IR
Inference with ONNX Runtimesimulate(ir) (bit-exact, in numpy)The IR itself becomes the golden model and serves as the reference for cross-checkingWorking with IR
TorchScript / TensorRTgriffith export-hdl ir.json --lang verilogThe destination is not an execution engine but synthesizable Verilog / VHDLHDL Export and Equivalence Checking
state_dict is the source of truthIR is the source of truthThe meaning of a trained model is pinned down in the IR. HDL generation, the editor, and the simulator all look only at the IRArchitecture Overview
load_state_dictbuild_torch(ir)You can go back from IR to a PyTorch model (edit the IR and continue training)Working with IR
“Probably behaves the same”Machine-verified three-stage equivalenceIt verifies that the three paths PyTorch hard eval ⇔ ir/simulate ⇔ HDL simulation agree on every vectorHDL Export and Equivalence Checking

ONNX can still be used as an entry point for teacher models (resolve_teacher('onnx:<path>'), etc.). As discussed below, however, converting or distilling from a pretrained model is not a silver bullet.


In PyTorch, eval() only changes the behavior of Dropout and BatchNorm, and you get an approximation of the same function. Not so here.

model.train()
y_soft = model(x) # reals in [0,1]. a softmax mixture of all gates. gradients flow
model.eval()
y_hard = model(x) # bits 0/1: only the single gate picked by argmax is active
soft (train())hard (eval())
Inputreals in [0,1][0,1]0/1 bits via round()
LUT weightssoftmax(W) (spread over all 2N2^N entries)one_hot(argmax(W)) (a single entry)
Outputreal valuesbits
Meaninghow well the continuous relaxation fitstrue performance as a logic circuit

The accuracy difference between the two is called the discretization gap.

GapInterpretationAction
0–0.5ptHealthy. Gates have converged well onto specific entriesLeave it as is
1pt or moreIt helps the continuous approximation but falls apart as a circuitMore epochs / revisit the parameterization
soft is low tooIt simply is not learningSuspect lr, τ, or capacity (k, number of layers)

There are also options that drive the gap structurally to zero: selection='hard_st' (the CAGE approach, where the forward pass uses argmax and only the backward pass approximates with softmax gradients), the warp parameterization (measured at −0.06pp), and DWN (train/eval logit difference of 0.0).


Here is the honest list. Starting without knowing these guarantees you get stuck.

Training only progresses in soft, but the score that means something is the hard one. test_acc is hard, test_acc_soft is soft. It is easy to read them backwards until you are used to it.

There is no pretrained ecosystem like timm / torchvision / HuggingFace. Nor does “just convert a strong real-valued model” hold up: distillation, transfer initialization, and layerwise binary distillation were all measured, and none of the three beat training from scratch (transfer initialization degraded badly). The strength of a native DLGN is that it can learn free Boolean logic, and transferring arithmetic structure constrains that freedom (→ Taxonomy and Lineage of DLGN).

The practical answers are training from scratch, or keeping the parts that should stay real-valued via hybridization (e.g. replacing only a Transformer’s MLP with LUTs).

3. Floating-point-centric techniques lose their meaning

Section titled “3. Floating-point-centric techniques lose their meaning”

The final artifact is a Boolean circuit with no multiplication. Therefore:

  • Tuning precision (FP16/BF16/quantization) is meaningless on the inference side — the output is nothing but 0/1 bits
  • The magnitude of a weight carries no meaning by itself. All that matters is which entry is the largest
  • The main battleground of regularization is managing the discretization gap, not weight norms
  • Correctness is measured by bit-level agreement, not numerical error (three-stage equivalence)

Your sense that Adam sits around 1e-3 does not apply. 0.01 is the default, and with independent or deep serial configurations you go up to 0.1–0.3. The first suspect for “the loss will not move off its initial value” is always the learning rate.

5. “Layer width” means something different

Section titled “5. “Layer width” means something different”

The out in LutLayer(in, out) is the number of gates, and it maps directly to circuit area. For MNIST you work in the range of 2,000 (smoke test) to 64,000 (paper reproduction). Numbers 1–2 orders of magnitude larger than an nn.Linear hidden dimension are normal here, which is visually surprising.

Training is real-valued computation in PyTorch, so a GPU helps during training. “No GPU needed” refers to the circuit after baking (CUDA is not required; CPU / MPS work too).

7. There are three axes beyond architecture

Section titled “7. There are three axes beyond architecture”

In PyTorch, “which layer to use” is nearly the whole design, but here you also get three orthogonal axes: parameterization / selection / learning rule. What to pick is summarized in What Should I Use? (Selection Guide).

Swapping nn.Linear(784, 256) for LutLayer(784, 256) does not give you an equivalent. A single gate sees only N inputs, so you need many more gates and more layers to get the same expressive power. This is why the hybridization API (LogicSpec(n_inputs=2, depth=2, neurons_per_output=8)) exposes depth and neurons_per_output as knobs.


flowchart TD
A["Existing PyTorch model"] --> Q{"Make all of it logic?"}
Q -->|"Only part<br/>(try it first)"| H["replace_mlp_with_lut<br/>Replace just the MLP with LUTs"]
Q -->|"All of it<br/>(you want a circuit)"| S["Rebuild from scratch<br/>LutLayer + GroupSum"]
H --> T["split_param_groups to<br/>separate logic/real lr"]
S --> T2["griffith train / run_training"]
T --> E["Check with hard eval"]
T2 --> E
E --> IR["export_ir → validate → simulate"]
IR --> HDL["Verilog / VHDL + equivalence checking"]
style H fill:#38bdf826,stroke:#38bdf8
style S fill:#eab30826,stroke:#eab308
style E fill:#10b98126,stroke:#10b981
style HDL fill:#10b98126,stroke:#10b981
  1. Get one run working with the Quickstart
  2. Decide architecture, N, parameterization, and learning rule in What Should I Use?
  3. Match the usual ranges for lr, τ, and k in Running Training
  4. Learn to read soft vs. hard in Reading Training Curves
  5. Turn it into a circuit with Working with IR → HDL Export