phanerozoic's picture
Upload folder using huggingface_hub
3af1a71 verified
---
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