File size: 2,005 Bytes
c800ac3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
---
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