File size: 1,676 Bytes
07d60e8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
"""

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")