threshold-isone4 / create_safetensors.py
CharlesCNorton
Check if 4-bit input equals 1, magnitude 5
6c0bc0c
Raw
History Blame Contribute Delete
985 Bytes
import torch
from safetensors.torch import save_file
# Input order: a3, a2, a1, a0 (MSB to LSB)
# Output 1 if input == 0001 (decimal 1)
weights = {
'neuron.weight': torch.tensor([[-1.0, -1.0, -1.0, 1.0]], dtype=torch.float32),
'neuron.bias': torch.tensor([-1.0], dtype=torch.float32)
}
save_file(weights, 'model.safetensors')
def isone4(a3, a2, a1, a0):
inp = torch.tensor([float(a3), float(a2), float(a1), float(a0)])
return int((inp @ weights['neuron.weight'].T + weights['neuron.bias'] >= 0).item())
print("Verifying isone4...")
errors = 0
for i in range(16):
a3, a2, a1, a0 = (i >> 3) & 1, (i >> 2) & 1, (i >> 1) & 1, i & 1
result = isone4(a3, a2, a1, a0)
expected = 1 if i == 1 else 0
if result != expected:
errors += 1
print(f"ERROR: {a3}{a2}{a1}{a0} (={i}) -> {result}, expected {expected}")
if errors == 0:
print("All 16 test cases passed!")
print(f"Magnitude: {sum(t.abs().sum().item() for t in weights.values()):.0f}")