General NN Blocks
Concat
Section titled “Concat”Defined in: griffith_logic.blocks.structural.Concat (class)
class Concat()An explicit block for dim=-1 concatenation (maps to the IR concat node).
forward(xs): takes a sequence of tensors and concatenates them along the last dimension. The bit order is identical to the IR concat convention (the first element leads the output bit string).
Defined in: griffith_logic.blocks.structural.Add (class)
class Add(mode: str)Multi-input soft logical merge (maps to the IR add node).
mode: ‘or’ — 1-(1-a)(1-b) (exactly matches bitwise OR on {0,1} inputs) ‘xor’ — a+b-2ab (exactly matches bitwise XOR on {0,1} inputs) ‘sum’ — a+b (integer sum. Terminal use in the logic domain only; cannot be exported to HDL)
Residual
Section titled “Residual”Defined in: griffith_logic.blocks.structural.Residual (class)
class Residual(inner: nn.Module, merge: str = 'concat')Residual connection: forward(x) = merge(x, inner(x)).
merge: ‘concat’ — cat([x, inner(x)], -1). The width grows (per the IR concat bit-order convention, the identity branch is slot 0 = the head) ‘or’/‘xor’ — soft logical merge. Width unchanged (inner’s output width must equal its input width)
LogicLayerNorm
Section titled “LogicLayerNorm”Defined in: griffith_logic.blocks.norm.LogicLayerNorm (class)
class LogicLayerNorm(width: int)LayerNorm for the [0,1] logic domain.
Internally it maps to 2x-1 → nn.LayerNorm → sigmoid back into [0,1] (like FromLogic(‘layernorm’), it uses nn.LayerNorm as the normalization core). Because LayerNorm works across features, every output bit depends on every input, so it cannot be folded into a truth table (it becomes a blackbox node in blocks_to_ir).
LogicBatchNorm
Section titled “LogicBatchNorm”Defined in: griffith_logic.blocks.norm.LogicBatchNorm (class)
class LogicBatchNorm( width: int, momentum: float = 0.1, bn_gamma: float = 0.3, bn_beta: float = 0.5,)BatchNorm for the [0,1] logic domain, extracted from the BN part of DifferentiableLutBlock.
The output of BatchNorm1d (initialized with gamma=0.3, beta=0.5, per the BinaryBrain convention) is brought back into [0,1] by an STE clamp (forward = clamp, backward = identity). At eval time it is deterministic: a per-feature affine from the running statistics, plus the clamp.
Because it acts per feature, it can be folded into the truth table of the preceding LutLayer when the next block is a Binarize (a clamp does not change a comparison against the 0.5 threshold). See blocks_to_ir. A 3D input (B, S, D) is flattened to (B×S, D) for processing.
LogicDropout
Section titled “LogicDropout”Defined in: griffith_logic.blocks.dropout.LogicDropout (class)
class LogicDropout(p: float = 0.1, mode: str = 'neutral')Dropout for the [0,1] logic domain. Perturbs output units with probability p during training only.
mode: ‘neutral’ — pin to 0.5 (the least informative, neutral value for a LUT) ‘flip’ — invert to 1-x (a logical NOT perturbation) ‘zero’ — pin to 0 (the logic-domain version of standard dropout)
At eval time it is the identity. It is also skipped by IR extraction (blocks_to_ir) and leaves no trace. Gradients pass through unmasked positions unchanged (at masked positions they are 0 for neutral/zero, and multiplied by -1 for flip).
LogicPositionalEncoding
Section titled “LogicPositionalEncoding”Defined in: griffith_logic.blocks.positional.LogicPositionalEncoding (class)
class LogicPositionalEncoding(seq_len: int, width: int, code: str = 'binary')A block that concatenates a constant positional-encoding bit string onto the input.
forward(x: (B, in_width)) → (B, in_width + seq_lenwidth). It appends the flattened position table (position-major: bit(p, j) → index pwidth+j) at the end. In blocks_to_ir it expands into a constant node (bits=bits_flat) plus a concat node (slot 0 = input, slot 1 = constant) (per the IR concat bit-order convention, slot 0 leads the output bit string).
position_codes
Section titled “position_codes”Defined in: griffith_logic.blocks.positional.position_codes (function)
def position_codes(seq_len: int, width: int, code: str) -> torch.TensorGenerates a position → bit string table.
code: ‘binary’ — the binary representation of position p (bit j = (p >> j) & 1). Requires seq_len ≦ 2^width ‘gray’ — Gray code (adjacent positions differ by 1 bit). Same requirement ‘thermometer’ — bit j = 1 if p > j (a monotone embedding). Requires width ≧ seq_len-1 (popcount == p)
Returns
A (seq_len, width) {0,1} float32 tensor
LogicAttention
Section titled “LogicAttention”Defined in: griffith_logic.blocks.attention.LogicAttention (class)
class LogicAttention( d_model: int, n_heads: int = 1, mode: str = 'soft', similarity: str = 'xnor', qk_sizes: list | None = None, v_sizes: list | None = None, share_qk: bool = True, tau: float = 1.0, causal: bool = False, n_inputs: int = 2, parameterization: str = 'softmax', connections: str = 'random', grad_factor: float = 1.0, selection: str = 'soft',)An attention block based on XNOR similarity.
Architecture (the same equations as boolean_attention.py): q/k/v (each a [0,1] bit string of shape (B, S, d_model)) ↓ q_proj / k_proj / v_proj (LutStack) (B, S, d_qk), (B, S, d_qk), (B, S, d_v) ↓ XNOR similarity: score = Σ_d [q·k + (1-q)(1-k)] (per head) scores (B, H, S_q, S_k) ↓ soft: softmax(score/τ) / hard: one-hot of the argmax (STE) value aggregation (B, S_q, d_v)
mode: ‘soft’ — softmax-weighted average (for training, differentiable) ‘hard’ — one-hot selection by argmax. The forward is exactly one-hot, and the backward along the attention-weight path is an STE that passes the softmax gradient (∂out/∂v in the value aggregation uses the forward value = the one-hot. The forward contract and the backward contract are verified by STE contract tests)
Arguments
d_model— input bit width (shared by q/k/v)n_heads— number of heads (the projection dimensions d_qk, d_v are split evenly)mode— ‘soft’ | ‘hard’ (can be overridden per call via forward’s hard argument)similarity— only ‘xnor’ is supportedqk_sizes— LutStack size list for the q/k projections (default [d_model])v_sizes— LutStack size list for the v projection (default [d_model])share_qk— share the q and k projections (the equivalent of share_key_query in boolean_attention)tau— attention softmax temperaturecausal— True applies an autoregressive mask (position i sees only j<=i). For decoder-only LMs (LogicGPT). Assumes S_q==S_k. The default False gives the usual fully connected self/cross-attention
LogicTransformerBlock
Section titled “LogicTransformerBlock”Defined in: griffith_logic.blocks.transformer.LogicTransformerBlock (class)
class LogicTransformerBlock( d_model: int, n_heads: int = 1, mlp_ratio: int = 2, norm: str = 'layernorm', merge: str = 'xor', attn_mode: str = 'soft', causal: bool = False, n_inputs: int = 2, parameterization: str = 'softmax', connections: str = 'random', selection: str = 'soft',)Logic-gate version of a Transformer block. forward(x: (B, S, D)) → (B, S, D).
Structure (residuals are soft logical merges, so the width is unchanged): h = norm1(merge(x, attn(x, x, x))) — self-attention + residual y = norm2(merge(h, mlp(h))) — LogicMLP + residual
mlp reuses LogicMLP (layers/logic_linear.py): encoder=‘identity’ (the input is already in [0,1]), hidden width d_model×mlp_ratio, and decoder=‘groupsum’ with τ=mlp_ratio to return to [0,1] as a group average
Arguments
d_model— bit width per positionn_heads— number of attention headsmlp_ratio— multiplier for the MLP hidden widthnorm— ‘layernorm’ | ‘batchnorm’ | ‘none’merge— residual merge: ‘or’ | ‘xor’ (soft logic; the same equation as the IR add node)attn_mode— LogicAttention’s mode (‘soft’ is the training-oriented default)
blocks_to_ir
Section titled “blocks_to_ir”Defined in: griffith_logic.blocks.to_ir.blocks_to_ir (function)
def blocks_to_ir( model: nn.Module, input_width: int, name: str = 'blocks_model', metadata: dict | None = None,) -> IRGraphConverts a model assembled from blocks into an IR graph.
Arguments
model— an nn.Sequential (or a single Module). See the support table in the module docstring for what is coveredinput_width— input bit widthname— metadata.name
Returns
An IRGraph (a DAG when Residual and friends are involved; turn it into an IRGraphModule with build_torch)