Threshold Logic Circuits
Collection
Boolean gates, voting functions, modular arithmetic, and adders as threshold networks.
β’
269 items
β’
Updated
β’
1
8-bit count trailing zeros (CTZ). Returns the number of trailing zero bits before the first set bit. Returns 8 if input is zero.
x7 x6 x5 x4 x3 x2 x1 x0
β β β β β β β β
βββββ΄ββββ΄ββββ΄ββββ΄ββββ΄ββββ΄ββββ
β
βΌ
βββββββββββββββββββββββ
β Priority Detect β Layer 1-3
β (find first 1) β
βββββββββββββββββββββββ
β
βΌ
βββββββββββββββββββββββ
β Position Encoder β Layer 4-5
β (binary encoding) β
βββββββββββββββββββββββ
β
βΌ
[c2, c1, c0]
(count 0-7)
Plus: all_zero detector for count=8
ctz8(x7, x6, x5, x4, x3, x2, x1, x0) -> (c3, c2, c1, c0)
where c = 4*c3 + 2*c2 + c1 + c0 = number of trailing zeros
If x0 is set, count = 0. If only x7 is set, count = 7. If no bits set, count = 8.
| Input (hex) | Binary | CTZ | c3 c2 c1 c0 |
|---|---|---|---|
| 0x01 | 00000001 | 0 | 0 0 0 0 |
| 0x02 | 00000010 | 1 | 0 0 0 1 |
| 0x04 | 00000100 | 2 | 0 0 1 0 |
| 0x08 | 00001000 | 3 | 0 0 1 1 |
| 0x10 | 00010000 | 4 | 0 1 0 0 |
| 0x20 | 00100000 | 5 | 0 1 0 1 |
| 0x40 | 01000000 | 6 | 0 1 1 0 |
| 0x80 | 10000000 | 7 | 0 1 1 1 |
| 0x00 | 00000000 | 8 | 1 0 0 0 |
| 0x06 | 00000110 | 1 | 0 0 0 1 |
| 0xF0 | 11110000 | 4 | 0 1 0 0 |
Step 1: Find first set bit from LSB
Detect positions where a bit is set and all lower bits are zero:
| Signal | Condition | Meaning |
|---|---|---|
| p0 | x0 | First 1 at position 0 |
| p1 | x1 AND NOT x0 | First 1 at position 1 |
| p2 | x2 AND NOT x1 AND NOT x0 | First 1 at position 2 |
| ... | ... | ... |
| p7 | x7 AND NOT(x6..x0) | First 1 at position 7 |
| pZ | NOT(x7..x0) | All zeros |
Step 2: Encode position to binary
| Layer | Components | Function |
|---|---|---|
| 1 | 8 position detectors | Find first 1 |
| 2 | Zero detector | All zeros? |
| 3 | 4 OR gates | Encode to binary |
| Inputs | 8 |
| Outputs | 4 |
| Neurons | 13 |
| Layers | 3 |
| Parameters | 85 |
| Magnitude | 52 |
from safetensors.torch import load_file
import torch
w = load_file('model.safetensors')
def ctz8(bits):
# bits = [x0, x1, x2, x3, x4, x5, x6, x7] (LSB first)
inp = torch.tensor([float(b) for b in bits])
c0 = int((inp @ w['c0.weight'].T + w['c0.bias'] >= 0).item())
c1 = int((inp @ w['c1.weight'].T + w['c1.bias'] >= 0).item())
c2 = int((inp @ w['c2.weight'].T + w['c2.bias'] >= 0).item())
c3 = int((inp @ w['c3.weight'].T + w['c3.bias'] >= 0).item())
return c3, c2, c1, c0
# Examples
print(ctz8([1,0,0,0,0,0,0,0])) # (0,0,0,0) = 0 trailing zeros
print(ctz8([0,0,0,0,1,0,0,0])) # (0,1,0,0) = 4 trailing zeros
print(ctz8([0,0,0,0,0,0,0,0])) # (1,0,0,0) = 8 trailing zeros (all zero)
threshold-clz8: Count leading zeros (mirror operation)threshold-ffs8: Find first set (similar, 1-indexed)threshold-priorityencoder8: Finds MSB position insteadthreshold-ctz8/
βββ model.safetensors
βββ model.py
βββ create_safetensors.py
βββ config.json
βββ README.md
MIT