threshold-xor3 / model.py
phanerozoic's picture
Upload folder using huggingface_hub
d6c45a8 verified
"""
Threshold Network for 3-input XOR Gate
Cascade of two standard XORs (OR + NAND + AND structure).
"""
import torch
from safetensors.torch import load_file
class ThresholdXOR3:
def __init__(self, weights_dict):
self.w = weights_dict
def __call__(self, a, b, c):
inp1 = torch.tensor([float(a), float(b)])
or1 = int((inp1 * self.w['xor1.layer1.or.weight']).sum() + self.w['xor1.layer1.or.bias'] >= 0)
nand1 = int((inp1 * self.w['xor1.layer1.nand.weight']).sum() + self.w['xor1.layer1.nand.bias'] >= 0)
h1 = torch.tensor([float(or1), float(nand1)])
xor_ab = int((h1 * self.w['xor1.layer2.and.weight']).sum() + self.w['xor1.layer2.and.bias'] >= 0)
inp2 = torch.tensor([float(xor_ab), float(c)])
or2 = int((inp2 * self.w['xor2.layer1.or.weight']).sum() + self.w['xor2.layer1.or.bias'] >= 0)
nand2 = int((inp2 * self.w['xor2.layer1.nand.weight']).sum() + self.w['xor2.layer1.nand.bias'] >= 0)
h2 = torch.tensor([float(or2), float(nand2)])
out = int((h2 * self.w['xor2.layer2.and.weight']).sum() + self.w['xor2.layer2.and.bias'] >= 0)
return float(out)
@classmethod
def from_safetensors(cls, path="model.safetensors"):
return cls(load_file(path))
if __name__ == "__main__":
weights = load_file("model.safetensors")
model = ThresholdXOR3(weights)
print("3-input XOR Gate:")
correct = 0
for a in [0, 1]:
for b in [0, 1]:
for c in [0, 1]:
out = int(model(a, b, c))
expected = a ^ b ^ c
if out == expected:
correct += 1
status = "OK" if out == expected else "FAIL"
print(f" XOR3({a},{b},{c}) = {out} [{status}]")
print(f"Total: {correct}/8")