--- license: mit tags: - pytorch - safetensors - threshold-logic - neuromorphic - comparison --- # threshold-comparator8bit 8-bit magnitude comparator. Compares two 8-bit unsigned values. ## Function compare8(A, B) -> (GT, LT, EQ) - GT = 1 if A > B - LT = 1 if A < B - EQ = 1 if A = B Exactly one output is always active. ## Architecture ``` A[7:0] B[7:0] │ │ └───────┬───────┘ │ ┌──────┴──────┐ │ │ ▼ ▼ ┌───┐ ┌───┐ │GT │ │LT │ Layer 1 │A-B│ │B-A│ │>=1│ │>=1│ └───┘ └───┘ │ │ └──────┬──────┘ │ ▼ ┌─────┐ │ EQ │ Layer 2 │ NOR │ └─────┘ ``` Uses positional weighting: treats inputs as binary numbers. **GT neuron:** weights A bits positively (128,64,32,16,8,4,2,1), B bits negatively. Fires when weighted sum A - B >= 1. **LT neuron:** opposite weights. Fires when B - A >= 1. **EQ neuron:** NOR of GT and LT. Fires when both are zero. ## Parameters | | | |---|---| | Inputs | 16 | | Outputs | 3 | | Neurons | 3 | | Layers | 2 | | Parameters | 37 | | Magnitude | 1024 | ## Truth Table (examples) | A | B | GT | LT | EQ | |-----|-----|----|----|---| | 0 | 0 | 0 | 0 | 1 | | 100 | 50 | 1 | 0 | 0 | | 50 | 100 | 0 | 1 | 0 | | 255 | 255 | 0 | 0 | 1 | ## Usage ```python from safetensors.torch import load_file import torch w = load_file('model.safetensors') def compare(a, b): a_bits = [(a >> (7-i)) & 1 for i in range(8)] b_bits = [(b >> (7-i)) & 1 for i in range(8)] inp = torch.tensor([float(x) for x in a_bits + b_bits]) gt = int((inp @ w['gt.weight'].T + w['gt.bias'] >= 0).item()) lt = int((inp @ w['lt.weight'].T + w['lt.bias'] >= 0).item()) eq = int((torch.tensor([float(gt), float(lt)]) @ w['eq.weight'].T + w['eq.bias'] >= 0).item()) return gt, lt, eq # compare(200, 100) = (1, 0, 0) # 200 > 100 ``` ## License MIT