| """
|
| Threshold Network for 4-input XNOR Gate
|
|
|
| XNOR4(a,b,c,d) = 1 when even number of inputs are 1 (0, 2, or 4)
|
| Built as: XNOR(XNOR(a,b), XNOR(c,d))
|
| """
|
|
|
| import torch
|
| from safetensors.torch import load_file
|
|
|
|
|
| def xnor2(x, y, w, prefix):
|
| """2-input XNOR using NOR + AND -> OR structure."""
|
| inp = torch.tensor([float(x), float(y)])
|
| n1 = int((inp * w[f'{prefix}.layer1.n1.weight']).sum() + w[f'{prefix}.layer1.n1.bias'] >= 0)
|
| n2 = int((inp * w[f'{prefix}.layer1.n2.weight']).sum() + w[f'{prefix}.layer1.n2.bias'] >= 0)
|
| h = torch.tensor([float(n1), float(n2)])
|
| return int((h * w[f'{prefix}.layer2.weight']).sum() + w[f'{prefix}.layer2.bias'] >= 0)
|
|
|
|
|
| class ThresholdXNOR4:
|
| def __init__(self, weights_dict):
|
| self.w = weights_dict
|
|
|
| def __call__(self, a, b, c, d):
|
|
|
| xnor_ab = xnor2(a, b, self.w, 'xnor1')
|
| xnor_cd = xnor2(c, d, self.w, 'xnor2')
|
| result = xnor2(xnor_ab, xnor_cd, self.w, 'xnor3')
|
| return float(result)
|
|
|
| @classmethod
|
| def from_safetensors(cls, path="model.safetensors"):
|
| return cls(load_file(path))
|
|
|
|
|
| if __name__ == "__main__":
|
| weights = load_file("model.safetensors")
|
| model = ThresholdXNOR4(weights)
|
|
|
| print("4-input XNOR Gate Truth Table:")
|
| print("-" * 35)
|
| 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 = 1 - (a ^ b ^ c ^ d)
|
| status = "OK" if out == expected else "FAIL"
|
| if out == expected:
|
| correct += 1
|
| print(f"XNOR4({a},{b},{c},{d}) = {out} [{status}]")
|
| print(f"\nTotal: {correct}/16 correct")
|
|
|