""" Threshold Network for 4-input XOR Gate (Magnitude 21) Cascade of three magnitude-7 optimal XORs. """ import torch from safetensors.torch import load_file def xor2(x1, x2, w, prefix): inp = torch.tensor([float(x1), float(x2)]) 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 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 (mag21):") 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")