Skip to content

Hybrid API

Defined in: griffith_logic.layers.logic_linear.LogicLinear (class)

class LogicLinear(in_features: int, out_features: int, spec: LogicSpec | None = None)

An nn.Linear-compatible logic-gate layer.

Arguments

  • in_features — number of input features
  • out_features — number of output features
  • spec — the construction recipe (defaults to LogicSpec())

Defined in: griffith_logic.layers.logic_linear.LogicMLP (class)

class LogicMLP(
in_features: int,
out_features: int | None = None,
spec: LogicSpec | None = None,
)

A drop-in replacement for an entire Transformer FFN (Linear → activation → Linear).

A single LUT stack is more efficient than replacing the FFN with two LogicLinears, so this is offered as its own class. When out_features is omitted it matches in_features (a d_model→d_model FFN replacement).

Defined in: griffith_logic.hybrid.policy.LogicSpec (class)

class LogicSpec(
n_inputs: int = 2,
parameterization: str = 'softmax',
selection: str = 'soft',
depth: int = 2,
width: int | None = None,
neurons_per_output: int = 8,
encoder: str = 'sigmoid',
encoder_tau: float = 1.0,
encoder_bits: int = 8,
decoder: str = 'groupsum_centered',
decoder_tau: float | None = None,
connections: str = 'random',
grad_factor: float = 1.0,
)

Construction recipe for logic-gate layers.

Attributes

  • n_inputs — number of LUT inputs (2/4/6)
  • parameterization — LutLayer parameterization, plus ‘dwn’ (uses DWNLayer)
  • selection — ‘soft’ | ‘hard_st’ (the CAGE approach; ignored for dwn)
  • depth — number of LUT layers
  • width — width of the hidden layers (None → out_features × neurons_per_output)
  • neurons_per_output — number of redundant neurons per output before GroupSum
  • encoder — input boundary: ‘sigmoid’ | ‘binarize_ste’ | ‘identity’ | ‘thermometer’
  • encoder_tau — initial temperature of the sigmoid encoder
  • encoder_bits — bits per feature for the thermometer encoder
  • decoder — output boundary: ‘groupsum_centered’ | ‘groupsum’ | ‘layernorm’ | ‘identity’
  • decoder_tau — decoder temperature (None → √group size)
  • connections — ‘random’ | ‘unique’ (for dwn: learnable in the first layer, random afterwards)
  • grad_factor — gradient scale for the LUT layers (>1 for deep configurations; ignored for dwn)

Examples using this API

Defined in: griffith_logic.encoding.bridges.ToLogic (class)

class ToLogic(mode: str = 'sigmoid', tau_init: float = 1.0, bits: int = 8)

Real values → [0,1] conversion.

mode: ‘sigmoid’ — sigmoid(x/τ). τ is learnable (mitigates vanishing gradients from saturation) ‘binarize_ste’ — binarize at threshold 0, backward is a HardTanh STE ‘identity’ — no conversion (when the input is already in [0,1]) ‘thermometer’ — thermometer encoding (expands D → D×bits, STE). Thresholds are fitted automatically on the first training batch (uniform)

Notes

thermometer changes the output width. Get the width for the next stage with out_width().

Defined in: griffith_logic.encoding.bridges.FromLogic (class)

class FromLogic(
in_width: int,
out_features: int,
mode: str = 'groupsum_centered',
tau: float | None = None,
)

[0,1] logic outputs → real values (group aggregation).

Splits the in_width logic outputs into out_features groups and sums each group, then zero-centers and scales to recover a real-valued representation.

mode: ‘groupsum_centered’ — (Σ - G/2)/τ. Keeps the mean well behaved even with residual connections (recommended) ‘groupsum’ — Σ/τ (same as the classic GroupSum, non-negative) ‘layernorm’ — groupsum_centered + LayerNorm ‘identity’ — no conversion (requires in_width == out_features)

τ defaults to √G (G = group size). Since the standard deviation of a sum of binary outputs is √G/2, the output is normalized to O(1).

Defined in: griffith_logic.hybrid.replace.replace_modules (function)

def replace_modules(
model: nn.Module,
match: MatchSpec,
factory: Callable[[str, nn.Module], nn.Module],
inplace: bool = False,
) -> tuple[nn.Module, list[str]]

Replaces every submodule matching match with what factory produces.

Arguments

  • match — a type / tuple of types / predicate (name, module)->bool / name glob string
  • factory — (name, old module) -> new module
  • inplace — if False, deepcopy before replacing (preserving the original model)

Returns

(the model after replacement, list of replaced module names)

Notes

The insides of a matched module are not traversed any further (if both a parent and a child match, the parent wins).

Defined in: griffith_logic.hybrid.replace.convert_linear_to_logic (function)

def convert_linear_to_logic(
model: nn.Module,
spec: LogicSpec | None = None,
include: str | None = None,
exclude: str | None = None,
inplace: bool = False,
) -> tuple[nn.Module, list[str]]

Replaces nn.Linear with LogicLinear.

Arguments

  • spec — the logic-gate conversion recipe
  • include — only replace Linears matching this name glob (e.g. ‘.mlp.’)
  • exclude — skip Linears matching this name glob (e.g. ‘head’)

Defined in: griffith_logic.hybrid.replace.replace_mlp_with_lut (function)

def replace_mlp_with_lut(
model: nn.Module,
spec: LogicSpec | None = None,
mlp_class: type | None = None,
mlp_name_pattern: str = '*mlp*',
inplace: bool = False,
) -> tuple[nn.Module, list[str]]

Replaces whole FFN/MLP blocks with LogicMLP (the LL-ViT use case).

Attention, LayerNorm, and embeddings stay in PyTorch; only the MLP part becomes LUT-based logic gates.

Detection criteria (either one): - if mlp_class is given: instances of that class - modules whose trailing name component matches mlp_name_pattern and that contain two or more nn.Linear inside

The in/out dimensions are inferred automatically from the first and last inner nn.Linear.

Examples using this API

Defined in: griffith_logic.hybrid.replace.split_param_groups (function)

def split_param_groups(
model: nn.Module,
logic_lr: float | None = None,
ann_lr: float | None = None,
) -> list[dict]

Splits LUT parameters and ANN parameters into separate optimizer param groups.

The appropriate learning rates for logic-gate layers (around lr=0.01) and real-valued layers (around lr=1e-3) differ by an order of magnitude, so they are separated and can be set individually.

Returns

A list that can be passed straight to torch.optim.*(param_groups, …)

Examples using this API