Threshold Logic Circuits
Collection
Boolean gates, voting functions, modular arithmetic, and adders as threshold networks.
•
248 items
•
Updated
•
1
Detect signed addition overflow from sign bits of operands and result.
overflow(a_sign, b_sign, sum_sign) = 1 if overflow occurred
In 2's complement addition, overflow occurs when:
| a_sign | b_sign | sum_sign | overflow | meaning |
|---|---|---|---|---|
| 0 | 0 | 0 | 0 | pos + pos = pos (ok) |
| 0 | 0 | 1 | 1 | pos + pos = neg (OVERFLOW) |
| 0 | 1 | 0 | 0 | pos + neg = pos (ok) |
| 0 | 1 | 1 | 0 | pos + neg = neg (ok) |
| 1 | 0 | 0 | 0 | neg + pos = pos (ok) |
| 1 | 0 | 1 | 0 | neg + pos = neg (ok) |
| 1 | 1 | 0 | 1 | neg + neg = pos (OVERFLOW) |
| 1 | 1 | 1 | 0 | neg + neg = neg (ok) |
2-layer circuit detecting both overflow cases:
Layer 1:
Layer 2:
| Inputs | 3 |
| Outputs | 1 |
| Neurons | 3 |
| Layers | 2 |
| Parameters | 11 |
| Magnitude | 12 |
from safetensors.torch import load_file
import torch
w = load_file('model.safetensors')
def overflow_detect(a_sign, b_sign, sum_sign):
inp = torch.tensor([float(a_sign), float(b_sign), float(sum_sign)])
n1 = int((inp @ w['layer1.n1.weight'].T + w['layer1.n1.bias'] >= 0).item())
n2 = int((inp @ w['layer1.n2.weight'].T + w['layer1.n2.bias'] >= 0).item())
hidden = torch.tensor([float(n1), float(n2)])
return int((hidden @ w['layer2.weight'].T + w['layer2.bias'] >= 0).item())
# Example: 5 + 4 = 9, but in 4-bit signed: 0101 + 0100 = 1001 = -7
print(overflow_detect(0, 0, 1)) # 1 (overflow!)
# Example: -3 + 2 = -1 (no overflow)
print(overflow_detect(1, 0, 1)) # 0 (ok)
MIT