Core Layers
LutLayer
Section titled “LutLayer”Defined in: griffith_logic.layers.lut.LutLayer (class)
class LutLayer( in_dim: int, out_dim: int, n_inputs: int = 2, device: str = 'cpu', grad_factor: float = 1.0, connections: str = 'random', parameterization: str = 'softmax', selection: str = 'soft', gumbel_noise: bool = False, gumbel_tau: float = 1.0, residual_init: bool = False, wiring: str = 'fixed', lm_tau: float = 0.001, wh_degree_cap: int | None = None, estimator: str = 'sigmoid', ri_mu: float = 1.2, ri_sigma: float = 0.25, gate_mask: Sequence[int] | None = None, init_mode: str | None = None, init_scale: float = 5.0, generator: torch.Generator | None = None,)N-input LUT (Look-Up Table) layer.
Generalized LUT equation: y = Σ_{k=0}^{2^N-1} f(W)[k] × Π_{j=0}^{N-1} (x_j if bit(k,j)=1 else 1-x_j)
Parameterizations: - ‘softmax’: f = softmax (entries compete, sum to 1) — the DLGN approach - ‘independent’: f = ρ (entries independent, sum ≠ 1) — the BinaryBrain approach. Mathematically identical to the IWP of arXiv:2510.03250 (Eq. 11) (a generalized LUT whose entry probabilities are ω_k = ρ(Ω_k)) - ‘iwp’: a single literal product with one parameter per input (a single minterm). This is NOT the IWP of arXiv:2510.03250 (it can express only 4 of the 16 two-input gates). The paper’s IWP corresponds to ‘independent’ - ‘raw’: weights held directly in [0,1] — the BinaryBrain approach - ‘warp’: Walsh-Hadamard basis (unconstrained reals, Gumbel smoothing) — the WARP approach
At N=2 this is equivalent to difflogic’s softmax-weighted 16 gates. At N=4 and N=6 it has the same expressive power as BinaryBrain’s LUT4/LUT6. For N=4 and 6, the warp parameterization is recommended for stable training (Gerlach et al., 2025).
Examples using this API
- Intro 3. Replace the MLP with a DLGN —
examples/26_mlp_to_dlgn.py - 1. Train on MNIST —
examples/06_mnist.py - 2. Build a Hybrid NN —
examples/02_hybrid_llvit.py - 3. Export to HDL —
examples/04_export_hdl.py - 4. Deploy —
examples/29_deploy_mnist.py - 5. Export a CNN to HDL —
examples/05_cnn_export_hdl.py - 6. Switching Learning Rules (DFA / AP) —
examples/03_learning_rules.py - 7. End-to-End Walkthrough: From Training to FPGA
- Appendix: A Minimal Look Inside, with XOR —
examples/01_xor.py - Gating Is a Boolean Operation (LSTM/GRU) — Logicizing the RNN —
examples/09_logic_lstm.py - Activity Recognition (UCI-HAR, Phone Accelerometer) —
examples/27_har.py
LTTLayer
Section titled “LTTLayer”Defined in: griffith_logic.layers.ltt.LTTLayer (class)
class LTTLayer( in_dim: int, out_dim: int, n_inputs: int = 6, connections: str | torch.Tensor = 'random', ste: str = 'clip', ste_scale: float = 1.0, clamp: bool = True, lm_tau: float = _DEFAULT_LM_TAU, device: str = 'cpu',)Linear threshold gate layer: binary input → n-input threshold function × out_dim → binary output.
Arguments
in_dim— number of input bitsout_dim— number of gates = number of output bitsn_inputs— number of inputs n per gate (default 6, as in prior internal experiments)connections— ‘random’ (balanced random) / ‘unique’ / ‘learnable’ (LearnableMapping) / an int Tensor of shape (n_inputs, out_dim)ste— surrogate gradient: ‘clip’ (default) / ‘identity’ / ‘sigmoid’ste_scale— temperature s of the surrogate gradient (default 1.0)clamp— clamp w and b to [−1, 1] on every forward during training (default True)lm_tau— backward softmax temperature of the LearnableMapping when connections=‘learnable’device— target device
FixedLutLayer
Section titled “FixedLutLayer”Defined in: griffith_logic.layers.fixed_lut.FixedLutLayer (class)
class FixedLutLayer( in_dim: int, out_dim: int, n_inputs: int, indices, truth_tables, train_info: dict | None = None, device: str = 'cpu',)A frozen LUT layer holding finalized truth tables (any number of inputs, no trainable parameters).
Arguments
in_dim— input bit widthout_dim— output bit width (the number of LUTs)n_inputs— number of LUT inputs n (1 or more; not limited to 2 / 4 / 6)indices— connection table of shape (n_inputs, out_dim) (int)truth_tables— truth tables of length out_dim (integers or hex strings; bit k = pattern k)train_info— train_info used when converting back to IR (e.g. kind=‘thermometer’)device— device for the buffers
Permute
Section titled “Permute”Defined in: griffith_logic.layers.permute.Permute (class)
class Permute(in_shape, perm)Treats x as (…, *in_shape), reorders the axes in the order given by perm, and flattens back to (…, width).
Arguments
in_shape— shape of the input (product of elements = input width)perm— axis permutation (a permutation of 0 .. len(in_shape)−1). Output axis i = input axis perm[i]
GroupSum
Section titled “GroupSum”Defined in: griffith_logic.group_sum.GroupSum (class)
class GroupSum(k: int, tau: float = 1.0, assign: str = 'contig', bias=None)Layer that groups the output neurons into k classes and sums each group. It turns the final LUT outputs into classification logits.
Class assignment assign (the GroupSum of prior internal experiments):
contig — neuron i → class i // m (contiguous blocks; the difflogic / previous default)
stride — neuron i → class i mod k (every k-th neuron; avoids the “contiguous-assignment trap”
in which the locality of the previous layer in a conv head biases the classes)
In the IR the group_sum node itself stays contig, and stride is expressed by inserting
an (m, k) → (k, m) transpose (permute / identity lut_layer) in front of it
(export/extract.py; the same shape as the SpatialGroupSum extraction).
Decision bias bias (the two-class decision rule s1 > s0 + t from prior internal experiments):
a per-class constant is added to the class sums before dividing by τ (logits = (Σ + bias) / τ).
The NID rule s1 > s0 + t is bias = [t, 0] (or [0, −t]). In the IR it is carried as
group_sum.params.bias (integers; omitted = all 0) and added by simulate. HDL generation does not support it yet
(validate(target=‘hdl’) rejects bias ≠ 0; this is left to a terminating block on the FPGA side or a follow-up task).
Examples using this API
- Intro 3. Replace the MLP with a DLGN —
examples/26_mlp_to_dlgn.py - 1. Train on MNIST —
examples/06_mnist.py - 3. Export to HDL —
examples/04_export_hdl.py - 4. Deploy —
examples/29_deploy_mnist.py - 5. Export a CNN to HDL —
examples/05_cnn_export_hdl.py - 6. Switching Learning Rules (DFA / AP) —
examples/03_learning_rules.py - 7. End-to-End Walkthrough: From Training to FPGA
- Appendix: A Minimal Look Inside, with XOR —
examples/01_xor.py - Gating Is a Boolean Operation (LSTM/GRU) — Logicizing the RNN —
examples/09_logic_lstm.py - Activity Recognition (UCI-HAR, Phone Accelerometer) —
examples/27_har.py
get_random_connections
Section titled “get_random_connections”Defined in: griffith_logic.core.connections.get_random_connections (function)
def get_random_connections( in_dim: int, out_dim: int, n_inputs: int, device: str = 'cpu', generator: torch.Generator | None = None,) -> torch.TensorRandomly assigns N inputs to each output neuron. It does not guarantee that every input is used at least once.
Note (a measured property confirmed in prior internal experiments): this implementation
remaps randperm(n_inputs·out_dim) % in_dim through randperm(in_dim), so
the usage count of each input takes only the two values floor / ceil(n_inputs·out_dim / in_dim)
(= it is balanced). Therefore when n_inputs·out_dim >= in_dim
the coverage is always 100%, and the distribution is the same as get_permutation_connections
(with in=9216 / out=8000 / n=2 the coverage is 9216/9216; 2432 inputs are used once and 6784 twice).
When you need unconstrained random wiring that “draws each slot independently and uniformly”,
use get_uniform_random_connections (coverage about 82% under the same conditions).
Arguments
in_dim— number of input dimensionsout_dim— number of output neuronsn_inputs— number of inputs per gatedevice— device of the output tensorgenerator— random number generator (None uses the global RNG = bitwise identical to the previous behavior)
Returns
indices: (n_inputs, out_dim) int64 tensor
get_unique_connections
Section titled “get_unique_connections”Defined in: griffith_logic.core.connections.get_unique_connections (function)
def get_unique_connections( in_dim: int, out_dim: int, n_inputs: int, device: str = 'cpu',) -> torch.TensorConnections that guarantee every input is used at least once. Generalizes difflogic’s offset pairing algorithm to N inputs.
For N=2 the algorithm is identical to difflogic’s:
- offset=0: (0,1), (2,3), (4,5), …
- offset=1: (1,2), (3,4), (5,6), …
- offset=2: (0,2), (1,3), (2,4), …
- continue until out_dim unique pairs have been collected
For N>2: apply offset pairing independently to each input slot.
Returns
indices: (n_inputs, out_dim) int64 tensor
get_rot_connections
Section titled “get_rot_connections”Defined in: griffith_logic.core.connections.get_rot_connections (function)
def get_rot_connections( in_dim: int, out_dim: int, s_a: int, s_b: int, device: str = 'cpu', step: int = 1,) -> torch.TensorRegular wiring by the rot rule (2 inputs only).
Same definition as rot_layer in the wiring.py of prior internal experiments:
idx_a[g] = (g · step + s_a) mod in_dimidx_b[g] = (g · step + s_b) mod in_dim (g = 0 .. out_dim-1)Wiring in which the “shift s” has a geometric meaning in the flattening order of the input (e.g. in the CIFAR thermometer order ((c*32+row)*32+col)*3+t used in prior internal experiments, s=3 is one pixel to the right and s=96 is one row down). It uses no randomness, so it is fully deterministic.
The step step (default 1 = bitwise identical to the previous rot) is the rot2 of prior internal
experiments ((g·r + s) mod W_in; in a conv head where the previous layer is wider than the output,
adjacent gates are spaced r apart so that no output of the previous layer goes dead). In the computed
overlay only the step constant changes from V to r·V, so the shape of the IR, HDL and overlay does not change.
Arguments
in_dim— number of input dimensionsout_dim— number of output neuronss_a— shift of the first input (negative values and values beyond in_dim are allowed; wrapped by modulo)s_b— shift of the second inputdevice— device of the output tensorstep— step r (the base position of gate g is g·r; default 1)
Returns
indices: (2, out_dim) int64 tensor
get_permutation_connections
Section titled “get_permutation_connections”Defined in: griffith_logic.core.connections.get_permutation_connections (function)
def get_permutation_connections( in_dim: int, out_dim: int, generator: torch.Generator | None = None, device: str = 'cpu',) -> torch.TensorPermutation (balanced surjective) wiring (2 inputs only).
Wiring with the same meaning as perm_index / perm_layer in the wiring.py of prior internal
experiments: the 2·out_dim input slots are filled by the in_dim sources an equal number of times each.
The usage count (= fan-out) of each source takes only the two values floor(2·out_dim / in_dim) and
ceil(2·out_dim / in_dim), so “structurally unreferenced sources” cannot occur in principle
(when 2·out_dim >= in_dim).
Implementation: with q, r = divmod(2·out_dim, in_dim), build a pool from arange(in_dim) tiled q times plus “r randomly chosen sources”, shuffle it, and use the first half as idx_a and the second half as idx_b. → Each source is used exactly q or q+1 times, with no bias in which sources get the +1.
The original implementation draws idx_a / idx_b independently as balanced surjections and decides the remainder by truncating the tiling. That (a) assumes in_dim <= out_dim (its docstring states that w_in > w_out does not occur in that experiment, that only pixels 0..w_out-1 would be used in that case, and that a redesign is needed), and the first layer of a later experiment (9216 -> 8000) does not satisfy that condition. (b) Because it truncates, the remainder is always biased toward the leading sources (the top-left of the image). This implementation avoids both by balancing all 2·out_dim slots together and choosing the remainder at random. With in_dim == out_dim (r = 0) each source is used exactly twice, as in the original implementation.
idx_a[g] == idx_b[g] (a gate reading the same input twice) is not excluded, as in the original implementation (it is kept as something the reducer counts under the “same input” rule).
Note: when 2·out_dim < in_dim, the pigeonhole principle means not all sources can be used (q=0, r=2·out_dim, so “2·out_dim randomly chosen sources, once each”).
Arguments
in_dim— number of input dimensionsout_dim— number of output neuronsgenerator— random number generator (None uses the global RNG)device— device of the output tensor
Returns
indices: (2, out_dim) int64 tensor
get_stretched_rot_connections
Section titled “get_stretched_rot_connections”Defined in: griffith_logic.core.connections.get_stretched_rot_connections (function)
def get_stretched_rot_connections( in_dim: int, out_dim: int, s_a: int, s_b: int, device: str = 'cpu',) -> torch.TensorStretched rot wiring (2 inputs only; the SR arm of prior internal experiments).
In rot the base position is g (steps of 1), so with out_dim < in_dim it reads only the first out_dim + max(s_a, s_b) inputs. This wiring stretches only the base position to steps of in_dim / out_dim, and keeps the way pairs are formed (the shifts s_a / s_b) as in rot:
base[g] = round(g · in_dim / out_dim)idx_a[g] = (base[g] + s_a) mod in_dimidx_b[g] = (base[g] + s_b) mod in_dim (g = 0 .. out_dim-1)Rounding is done half-up (half-integers round up) with integer arithmetic:
base[g] = (2·g·in_dim + out_dim) // (2·out_dim) ( = floor(g·in/out + 1/2) )Python’s built-in round rounds half to even, so it differs on half-integers (e.g. for in=4, out=8,
g=1 is 1 under this definition while round(0.5) is 0). No floating point is used, so it is
fully deterministic regardless of device or environment.
Properties:
- With
in_dim == out_dim, base[g] = g and it is bitwise identical toget_rot_connections. - The difference within a pair is constant, as in rot:
(idx_b - idx_a) ≡ (s_b - s_a) (mod in_dim). In an encoding whose flattening order is geometric (the CIFAR thermometer order of prior internal experiments), locality such as “one pixel right and one row down” with s_b - s_a = 93 is preserved. - The coverage for the first layer of prior internal experiments (in_dim=9216, out_dim=8000, s_a=3, s_b=96) is 9216/9216 = 100.0% (measured; asserted by a test in tests/l1_math/test_connections_generators.py). Under the same conditions rot reads only 8093/9216 = 87.81%. 2432 inputs are used once and 6784 twice, and no input is left unreferenced.
- 100% coverage is not guaranteed in general. The base position jumps in steps of in_dim / out_dim,
so when the ratio is an integer, holes remain depending on s_b - s_a modulo that ratio
(e.g. in=16, out=8 gives only even bases; with s_a=3, s_b=5 only odd inputs are read, 50%,
while s_a=3, s_b=6 gives 100%). Under experimental conditions where in_dim / out_dim is not an integer
(9216/8000 = 1.152) the increments of the base position mix 1 and 2, and the holes are filled.
Check the coverage with
connection_statsbefore use.
Arguments
in_dim— number of input dimensionsout_dim— number of output neuronss_a— shift of the first input (negative values and values beyond in_dim are allowed; wrapped by modulo)s_b— shift of the second inputdevice— device of the output tensor
Returns
indices: (2, out_dim) int64 tensor
get_uniform_random_connections
Section titled “get_uniform_random_connections”Defined in: griffith_logic.core.connections.get_uniform_random_connections (function)
def get_uniform_random_connections( in_dim: int, out_dim: int, n_inputs: int, device: str = 'cpu', generator: torch.Generator | None = None,) -> torch.TensorUnconstrained uniform random wiring (each slot sampled independently and uniformly; the RAND arm of prior internal experiments).
idx[j, g] ~ Uniform{0, ..., in_dim-1} (i.i.d.)Unlike get_random_connections / get_permutation_connections, it does not balance the usage counts,
so unreferenced inputs occur stochastically.
The expected unreferenced fraction is (1 - 1/in_dim)^(n_inputs·out_dim), which for
in_dim=9216 / out_dim=8000 / n_inputs=2 is exp(-16000/9216) ≈ 0.176
(coverage about 82.4%; 0.8244 measured on one sample).
Arguments
in_dim— number of input dimensionsout_dim— number of output neuronsn_inputs— number of inputs per gatedevice— device of the output tensorgenerator— random number generator (None uses the global RNG)
Returns
indices: (n_inputs, out_dim) int64 tensor
connection_stats
Section titled “connection_stats”Defined in: griffith_logic.core.connections.connection_stats (function)
def connection_stats(connections: torch.Tensor, in_dim: int) -> dictSummarizes the coverage and usage-count distribution of a wiring table (wiring verification from prior internal experiments).
A pure function (no randomness and no device dependence). Used to record at startup that each arm’s wiring matches its specification.
Arguments
connections— connection table of shape (n_inputs, out_dim) (int)in_dim— number of input dimensions
Returns
{ ‘coverage’: number of distinct inputs read / in_dim (0.0 to 1.0), ‘usage_hist’: {‘0’,‘1’,‘2’,‘3+’} → number of inputs read exactly that many times (the four always sum to in_dim), ‘same_input’: number of gates that read the same input two or more times (a == b for n_inputs=2), ‘n_gates’: number of gates (= out_dim), }
Raises
ValueError: the shape is not 2-dimensional / an index is outside [0, in_dim)
sort_model_wiring
Section titled “sort_model_wiring”Defined in: griffith_logic.core.sort_wiring.sort_model_wiring (function)
def sort_model_wiring( model: nn.Sequential, inplace: bool = True, optimizer: torch.optim.Optimizer | None = None,) -> nn.SequentialRenumbers the output neurons of every LutLayer in ascending order of their first input index.
This is a model-equivalent permutation (the forward output and the backward gradients are unchanged up to the renumbering). It orders the gates by the address they read, which improves the memory locality of the gather. When training with the fused CUDA kernels the effect on speed is small (0.5–0.7% measured).
Call it before constructing the optimizer. If you call it afterwards (including in the middle of
training), pass optimizer=: the moments of Adam and similar optimizers (state with the same shape
as the weights) are then permuted in the same way. Otherwise the moments stay attached to different
neurons while training continues (this function cannot detect the optimizer, so this is the
caller’s responsibility).
Arguments
model— an nn.Sequential (non-LutLayer elements such as Flatten are allowed). Only a run of consecutive LutLayers (all with wiring=‘fixed’) followed by an optional trailing GroupSum is supported.inplace— if True (default), modifymodelin place and return it. If False, modify and return a deepcopy, leaving the original model untouched (useful for before/after comparisons, or when the caller wants to keep the original as a fallback).optimizer— the optimizer holding the model’s parameters (when calling after constructing it). Its per-parameter state is permuted in the same way as the weights. Cannot be combined with inplace=False (the copied parameters are not the ones the optimizer holds).
Returns
The permuted model (the same object as the argument when inplace=True).
Raises
UnsupportedWiringError: - model is not an nn.Sequential - the LutLayers are not consecutive within the Sequential - any LutLayer has wiring=‘learnable’ - the output dimension of the last LutLayer is not divisible by the number of GroupSum classes (an inconsistency between LutLayer and GroupSum themselves; normally impossible) ValueError: optimizer was given together with inplace=False
UnsupportedWiringError
Section titled “UnsupportedWiringError”Defined in: griffith_logic.core.sort_wiring.UnsupportedWiringError (class)
class UnsupportedWiringError()Raised when sort_model_wiring does not support the model structure or wiring mode.
get_rot_n_connections
Section titled “get_rot_n_connections”Defined in: griffith_logic.core.connections.get_rot_n_connections (function)
def get_rot_n_connections( in_dim: int, out_dim: int, shifts, device: str = 'cpu', step: int = 1,) -> torch.Tensorn-input rot: idx[m, g] = (g · step + shifts[m]) mod in_dim (m = 0 .. n−1).
A generalization of get_rot_connections to shifts=[s_a, s_b]. The step is the rot2 of prior internal
experiments ((g·r + s) mod W_in). The butterfly gather stage of prior internal experiments
(bf6_gather: (n·i + m) mod D) corresponds to shifts = 0..n−1, step = n
(if n·out_dim ≥ in_dim, it constructively covers every input).
Arguments
in_dim— number of input dimensionsout_dim— number of output neuronsshifts— per-slot shifts (length n_inputs)device— device of the output tensorstep— step (default 1)
Returns
indices: (len(shifts), out_dim) int64 tensor
get_butterfly_connections
Section titled “get_butterfly_connections”Defined in: griffith_logic.core.connections.get_butterfly_connections (function)
def get_butterfly_connections( in_dim: int, out_dim: int, n_inputs: int, stride: int, device: str = 'cpu',) -> torch.TensorOne stage of a cyclic radix-n butterfly (bf6_stage of the BF6 / BF4 arms in prior internal
experiments).
idx[m, g] = (g + m · stride) mod in_dim (m = 0 .. n_inputs−1)A Cooley-Tukey radix-n stage, wrapped around by mod when the width is not a power of n.
Using stride = n^(s−1) at layer s (1-based), after k stages each output node j reaches the contiguous range
{ j + t (mod W) : 0 ≤ t < n^k } (every base-n representation).
If n^k ≥ W it reaches every node, and together with the full coverage of the gather stage
(get_rot_n_connections with shifts 0..n−1, step n) every output reaches every input.
With in_dim == out_dim each input is read exactly n times (balanced fan-out).
Combinations where stride · m collides mod in_dim (e.g. in_dim=12, n=6, stride=6)
read the same input in several slots. Collapse them with dedupe_connections if needed
(the original builder always collapsed them).
Returns
indices: (n_inputs, out_dim) int64 tensor
get_local1d_connections
Section titled “get_local1d_connections”Defined in: griffith_logic.core.connections.get_local1d_connections (function)
def get_local1d_connections( in_dim: int, out_dim: int, n_inputs: int, stride: int, device: str = 'cpu',) -> torch.Tensor1D local window (an n-input version of candidate B arm_local1d from prior internal experiments).
c_g = prop_map(out_dim, in_dim)idx[m, g] = (c_g + m · stride) mod in_dim (m = 0 .. n_inputs−1)With n_inputs=2, a = c_g and b = (c_g + stride) mod in_dim, the same as in prior internal experiments. With in_dim == out_dim it matches rot (s_a=0, s_b=stride, …).
Returns
indices: (n_inputs, out_dim) int64 tensor
get_local2d_connections
Section titled “get_local2d_connections”Defined in: griffith_logic.core.connections.get_local2d_connections (function)
def get_local2d_connections( in_dim: int, out_dim: int, offsets, grid=None, bits_per_cell: int = 1, device: str = 'cpu',) -> torch.Tensor2D local window (candidate C / L2D6 / L2D4 from prior internal experiments).
Treats the in_dim input bits as “cells of an (H, W) grid × bits_per_cell bits” (feature-major bit = cell · z + t; for an image with z thermometer bits, z = bits_per_cell). The center cell of gate g is c_g = prop_map(out_dim, n_cells) (n_cells = in_dim / z), and (y, x) = divmod(c_g, W). For each offset k = (dx, dy) it takes the neighboring cell on a torus, and the part where the grid is larger than the number of cells (the tail of a square grid) is wrapped by mod n_cells:
cell_k(g) = (((y + dy) mod H) · W + ((x + dx) mod W)) mod n_cellsidx[k · z + t, g] = cell_k(g) · z + t (t = 0 .. z−1)grid=None is a square grid with G = ceil(√n_cells) (the default for hidden layers; with in_dim == out_dim, c_g = g and it matches the hidden-layer formula of prior internal experiments). For layer 0 of an image pass grid=(H, W): L2D6 layer 0 = grid (28, 28), z=3, offsets [(1,0),(0,1)] (the right and lower neighbor, 2 pixels × 3 bits); L2D4 layer 0 = z=4, offsets [(0,0)] (the 4 bits of the pixel itself).
Arguments
in_dim— number of input dimensions (a multiple of bits_per_cell)out_dim— number of output neuronsoffsets— sequence of (dx, dy), as produced byring_offsets/local2d_offset_schedulegrid— (H, W). A square grid if Nonebits_per_cell— number of bits z per celldevice— device of the output tensor
Returns
indices: (len(offsets) · bits_per_cell, out_dim) int64 tensor
butterfly_strides
Section titled “butterfly_strides”Defined in: griffith_logic.core.connections.butterfly_strides (function)
def butterfly_strides(n_stages: int, radix: int, order: str = 'asc') -> list[int]Stride sequence of the butterfly stages [radix^0, radix^1, …, radix^(n_stages−1)]
(the strides of bf6_plan in prior internal experiments).
order=‘desc’ is the reverse, coarse-to-fine order (the “desc” stage assignment of prior internal experiments: long-distance jumps in early layers compound through union propagation in later stages).
local1d_strides
Section titled “local1d_strides”Defined in: griffith_logic.core.connections.local1d_strides (function)
def local1d_strides(depth: int, width: int, frac: float = 0.13) -> list[int]Geometric-series strides of local1d_stride from prior internal experiments (layers 0 .. depth−1).
S_max = max(1, floor(frac · width))s_l = clip(round(S_max^(l / (depth−1))), 1, S_max)frac=0.13 is the default from prior internal experiments (13% of the width, a window equivalent to at width 2000).
ring_offsets
Section titled “ring_offsets”Defined in: griffith_logic.core.connections.ring_offsets (function)
def ring_offsets(n: int) -> list[tuple[int, int]]The first n entries of the sequence that lists the four ring directions of radius s, [(s,0), (0,s), (s,s), (s,−s)],
for s = 1, 2, … (the ring_seq of prior internal experiments). Each element is (dx, dy).
The first 6 match C2D_OFFSETS [(1,0),(0,1),(1,1),(1,−1),(2,0),(0,2)] from prior internal experiments.
local2d_offset_schedule
Section titled “local2d_offset_schedule”Defined in: griffith_logic.core.connections.local2d_offset_schedule (function)
def local2d_offset_schedule( n_layers: int, n_inputs: int, assign: str = 'contig',) -> list[list[tuple[int, int]]]Offset tables of n_inputs entries for each of the n_layers hidden layers
(the contig / stride assignments of l2d6_offsets in prior internal experiments).
contig: layer l (0-based) takes [n·l, n·(l+1)) of the ring sequence. With n_inputs=4, layer l is one full ring of radius l+1 (the L2D4 design). stride: layer l takes n entries of the ring sequence starting at l with a stride of n_layers (each layer mixes several scales).
dedupe_connections
Section titled “dedupe_connections”Defined in: griffith_logic.core.connections.dedupe_connections (function)
def dedupe_connections(indices: torch.Tensor, in_dim: int) -> torch.TensorDeterministically collapses duplicates in gates that read the same input in several slots (by shifting +1).
Unifies _fix_degenerate (2 inputs: if a == b then b ← (b+1) mod in_dim) and
dedupe_ins (n inputs: scanning the slots in order, an index already seen is advanced by +1 until
it reaches an unused index) from prior internal experiments. Gates without duplicates are left unchanged.
Arguments
indices— connection table of shape (n_inputs, out_dim) (int)in_dim— number of input dimensions
Returns
(n_inputs, out_dim) int64 tensor (a new tensor; the input is not modified)
Raises
ValueError: the shape is not 2-dimensional / n_inputs > in_dim so duplicates cannot all be collapsed
prop_map
Section titled “prop_map”Defined in: griffith_logic.core.connections.prop_map (function)
def prop_map(out_dim: int, in_dim: int) -> torch.TensorProportional map from gate index → input coordinate, c_g = round(g · (in_dim − 1) / (out_dim − 1)).
The same formula as prop_map in prior internal experiments (rounding is round-half-to-even =
numpy / torch round; it computes in float64 in the same order, so it is bitwise identical to the numpy version).
It is the identity map when in_dim == out_dim and 0 when out_dim == 1. It is used to determine the
“center of the gate” for the local-window wirings (local1d / local2d). The formula differs from the base position
floor(g·in/out + 1/2) of get_stretched_rot_connections (that one rounds half-integers up and steps both ends by in/out).
Returns
(out_dim,) int64 tensor