--- license: mit tags: - pytorch - safetensors - threshold-logic - neuromorphic - arithmetic --- # threshold-halfsubtractor Subtracts two 1-bit inputs, producing difference and borrow. The subtraction counterpart to the half adder. ## Circuit ``` a b a b │ │ │ │ ├───┬───┤ └─┬─┘ │ │ │ │ ▼ │ ▼ ▼ ┌──────┐│┌──────┐ ┌───────┐ │ OR │││ NAND │ │ ¬a ∧ b│ │w:1,1 │││w:-1,-1│ │w:-1,1 │ │b: -1 │││b: +1 │ │b: -1 │ └──────┘│└──────┘ └───────┘ │ │ │ │ └───┼───┘ │ ▼ │ ┌──────┐ │ │ AND │ │ │w: 1,1│ │ │b: -2 │ │ └──────┘ │ │ │ ▼ ▼ diff borrow ``` The diff output uses XOR (2 layers). The borrow output detects when we subtract 1 from 0. ## Truth Table | a | b | diff | borrow | |---|---|------|--------| | 0 | 0 | 0 | 0 | | 0 | 1 | 1 | 1 | | 1 | 0 | 1 | 0 | | 1 | 1 | 0 | 0 | Binary: a - b = diff - (borrow × 2) ## Mechanism **Diff (XOR):** Same as the half adder's sum. The difference bit is 1 when exactly one input is 1. **Borrow:** Uses weights [-1, +1] with bias -1. This fires only when a=0 and b=1: - a=0, b=0: -0 + 0 - 1 = -1 < 0 → no borrow - a=0, b=1: -0 + 1 - 1 = 0 ≥ 0 → borrow - a=1, b=0: -1 + 0 - 1 = -2 < 0 → no borrow - a=1, b=1: -1 + 1 - 1 = -1 < 0 → no borrow The borrow is NOT(a) AND b - we borrow when subtracting 1 from 0. ## Components | Output | Function | Neurons | Layers | |--------|----------|---------|--------| | diff | XOR(a, b) | 3 | 2 | | borrow | ¬a ∧ b | 1 | 1 | **Total: 4 neurons, 12 parameters** ## Contrast with Half Adder | Circuit | Output 2 | Function | Weights | |---------|----------|----------|---------| | HalfAdder | carry | a ∧ b | [1, 1], b=-2 | | HalfSubtractor | borrow | ¬a ∧ b | [-1, 1], b=-1 | The only difference: borrow has an inhibitory weight on a. ## Usage ```python from safetensors.torch import load_file import torch w = load_file('model.safetensors') def half_subtractor(a, b): inp = torch.tensor([float(a), float(b)]) # XOR for diff l1 = (inp @ w['xor.layer1.weight'].T + w['xor.layer1.bias'] >= 0).float() diff = int((l1 @ w['xor.layer2.weight'].T + w['xor.layer2.bias'] >= 0).item()) # Borrow borrow = int((inp @ w['borrow.weight'].T + w['borrow.bias'] >= 0).item()) return diff, borrow ``` ## Files ``` threshold-halfsubtractor/ ├── model.safetensors ├── model.py ├── config.json └── README.md ``` ## License MIT