|
|
---
|
|
|
license: mit
|
|
|
tags:
|
|
|
- pytorch
|
|
|
- safetensors
|
|
|
- threshold-logic
|
|
|
- neuromorphic
|
|
|
- modular-arithmetic
|
|
|
---
|
|
|
|
|
|
# threshold-mod3
|
|
|
|
|
|
Computes Hamming weight mod 3 for 8-bit inputs. Multi-layer network using thermometer encoding.
|
|
|
|
|
|
## Circuit
|
|
|
|
|
|
```
|
|
|
xβ xβ xβ xβ xβ xβ
xβ xβ
|
|
|
β β β β β β β β
|
|
|
ββββ΄βββ΄βββ΄βββΌβββ΄βββ΄βββ΄βββ
|
|
|
βΌ
|
|
|
βββββββββββββββ
|
|
|
β Thermometer β Layer 1: 9 neurons
|
|
|
β Encoding β Fires when HW β₯ k
|
|
|
βββββββββββββββ
|
|
|
β
|
|
|
βΌ
|
|
|
βββββββββββββββ
|
|
|
β MOD-3 β Layer 2: 2 neurons
|
|
|
β Detection β Weight pattern (1,1,-2)
|
|
|
βββββββββββββββ
|
|
|
β
|
|
|
βΌ
|
|
|
βββββββββββββββ
|
|
|
β Classify β Output: 3 classes
|
|
|
βββββββββββββββ
|
|
|
β
|
|
|
βΌ
|
|
|
{0, 1, 2}
|
|
|
```
|
|
|
|
|
|
## Algebraic Insight
|
|
|
|
|
|
The weight pattern `(1, 1, -2)` causes cumulative sums to cycle mod 3:
|
|
|
|
|
|
```
|
|
|
HW=0: sum=0 β 0 mod 3
|
|
|
HW=1: sum=1 β 1 mod 3
|
|
|
HW=2: sum=2 β 2 mod 3
|
|
|
HW=3: sum=0 β 0 mod 3 (reset: 1+1-2=0)
|
|
|
HW=4: sum=1 β 1 mod 3
|
|
|
...
|
|
|
```
|
|
|
|
|
|
The key: `1 + 1 + (1-3) = 0`. Every 3 increments, the sum resets.
|
|
|
|
|
|
This generalizes to MOD-m: use `(1, 1, ..., 1, 1-m)` with m-1 ones.
|
|
|
|
|
|
## Architecture
|
|
|
|
|
|
| Layer | Neurons | Function |
|
|
|
|-------|---------|----------|
|
|
|
| Input | 8 | Binary bits |
|
|
|
| Hidden 1 | 9 | Thermometer: fires when HW β₯ k |
|
|
|
| Hidden 2 | 2 | MOD-3 detection |
|
|
|
| Output | 3 | One-hot classification |
|
|
|
|
|
|
**Total: 14 neurons, 110 parameters**
|
|
|
|
|
|
## Output Distribution
|
|
|
|
|
|
| Class | HW values | Count/256 |
|
|
|
|-------|-----------|-----------|
|
|
|
| 0 | 0, 3, 6 | 85 |
|
|
|
| 1 | 1, 4, 7 | 86 |
|
|
|
| 2 | 2, 5, 8 | 85 |
|
|
|
|
|
|
## Usage
|
|
|
|
|
|
```python
|
|
|
from safetensors.torch import load_file
|
|
|
import torch
|
|
|
|
|
|
w = load_file('model.safetensors')
|
|
|
|
|
|
def forward(x):
|
|
|
x = x.float()
|
|
|
x = (x @ w['layer1.weight'].T + w['layer1.bias'] >= 0).float()
|
|
|
x = (x @ w['layer2.weight'].T + w['layer2.bias'] >= 0).float()
|
|
|
out = x @ w['output.weight'].T + w['output.bias']
|
|
|
return out.argmax(dim=-1)
|
|
|
|
|
|
inp = torch.tensor([[1,0,1,1,0,0,1,0]]) # HW=4
|
|
|
print(forward(inp).item()) # 1 (4 mod 3 = 1)
|
|
|
```
|
|
|
|
|
|
## Files
|
|
|
|
|
|
```
|
|
|
threshold-mod3/
|
|
|
βββ model.safetensors
|
|
|
βββ model.py
|
|
|
βββ config.json
|
|
|
βββ README.md
|
|
|
```
|
|
|
|
|
|
## License
|
|
|
|
|
|
MIT
|
|
|
|