threshold-xor4 / model.py
phanerozoic's picture
Upload folder using huggingface_hub
07d60e8 verified
"""
Threshold Network for 4-input XOR Gate
Cascade of three standard XORs (OR + NAND + AND structure).
"""
import torch
from safetensors.torch import load_file
def xor2(x1, x2, w, prefix):
inp = torch.tensor([float(x1), float(x2)])
or_out = int((inp * w[f'{prefix}.layer1.or.weight']).sum() + w[f'{prefix}.layer1.or.bias'] >= 0)
nand_out = int((inp * w[f'{prefix}.layer1.nand.weight']).sum() + w[f'{prefix}.layer1.nand.bias'] >= 0)
h = torch.tensor([float(or_out), float(nand_out)])
return int((h * w[f'{prefix}.layer2.and.weight']).sum() + w[f'{prefix}.layer2.and.bias'] >= 0)
class ThresholdXOR4:
def __init__(self, weights_dict):
self.w = weights_dict
def __call__(self, a, b, c, d):
xor_ab = xor2(a, b, self.w, 'xor1')
xor_abc = xor2(xor_ab, c, self.w, 'xor2')
xor_abcd = xor2(xor_abc, d, self.w, 'xor3')
return float(xor_abcd)
@classmethod
def from_safetensors(cls, path="model.safetensors"):
return cls(load_file(path))
if __name__ == "__main__":
weights = load_file("model.safetensors")
model = ThresholdXOR4(weights)
print("4-input XOR Gate:")
correct = 0
for a in [0, 1]:
for b in [0, 1]:
for c in [0, 1]:
for d in [0, 1]:
out = int(model(a, b, c, d))
expected = a ^ b ^ c ^ d
if out == expected:
correct += 1
status = "OK" if out == expected else "FAIL"
print(f" XOR4({a},{b},{c},{d}) = {out} [{status}]")
print(f"Total: {correct}/16")