--- license: mit tags: - pytorch - safetensors - threshold-logic - neuromorphic --- # threshold-overflowdetect Detect signed addition overflow from sign bits of operands and result. ## Function overflow(a_sign, b_sign, sum_sign) = 1 if overflow occurred In 2's complement addition, overflow occurs when: - Two positive numbers produce a negative result - Two negative numbers produce a positive result ## Truth Table | 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) | ## Architecture 2-layer circuit detecting both overflow cases: **Layer 1:** - N1: detects positive overflow (0,0,1) - weights [-1,-1,+1], bias -1 - N2: detects negative overflow (1,1,0) - weights [+1,+1,-1], bias -2 **Layer 2:** - OR gate: weights [1,1], bias -1 ## Parameters | | | |---|---| | Inputs | 3 | | Outputs | 1 | | Neurons | 3 | | Layers | 2 | | Parameters | 11 | | Magnitude | 12 | ## Usage ```python 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) ``` ## License MIT