|
|
"""
|
|
|
Threshold Network for 3-input XNOR Gate
|
|
|
|
|
|
XNOR3(a,b,c) = 1 when even number of inputs are 1 (0 or 2)
|
|
|
Built as: XOR(XNOR(a,b), c)
|
|
|
"""
|
|
|
|
|
|
import torch
|
|
|
from safetensors.torch import load_file
|
|
|
|
|
|
|
|
|
class ThresholdXNOR3:
|
|
|
def __init__(self, weights_dict):
|
|
|
self.w = weights_dict
|
|
|
|
|
|
def __call__(self, a, b, c):
|
|
|
|
|
|
inp1 = torch.tensor([float(a), float(b)])
|
|
|
n1 = int((inp1 * self.w['xnor1.layer1.n1.weight']).sum() + self.w['xnor1.layer1.n1.bias'] >= 0)
|
|
|
n2 = int((inp1 * self.w['xnor1.layer1.n2.weight']).sum() + self.w['xnor1.layer1.n2.bias'] >= 0)
|
|
|
|
|
|
h1 = torch.tensor([float(n1), float(n2)])
|
|
|
xnor_ab = int((h1 * self.w['xnor1.layer2.weight']).sum() + self.w['xnor1.layer2.bias'] >= 0)
|
|
|
|
|
|
|
|
|
inp2 = torch.tensor([float(xnor_ab), float(c)])
|
|
|
n3 = int((inp2 * self.w['xor2.layer1.n1.weight']).sum() + self.w['xor2.layer1.n1.bias'] >= 0)
|
|
|
n4 = int((inp2 * self.w['xor2.layer1.n2.weight']).sum() + self.w['xor2.layer1.n2.bias'] >= 0)
|
|
|
|
|
|
h2 = torch.tensor([float(n3), float(n4)])
|
|
|
out = int((h2 * self.w['xor2.layer2.weight']).sum() + self.w['xor2.layer2.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 = ThresholdXNOR3(weights)
|
|
|
|
|
|
print("3-input XNOR Gate Truth Table:")
|
|
|
print("-" * 30)
|
|
|
correct = 0
|
|
|
for a in [0, 1]:
|
|
|
for b in [0, 1]:
|
|
|
for c in [0, 1]:
|
|
|
out = int(model(a, b, c))
|
|
|
|
|
|
expected = 1 - (a ^ b ^ c)
|
|
|
status = "OK" if out == expected else "FAIL"
|
|
|
if out == expected:
|
|
|
correct += 1
|
|
|
print(f"XNOR3({a}, {b}, {c}) = {out} [{status}]")
|
|
|
print(f"\nTotal: {correct}/8 correct")
|
|
|
|