File size: 1,906 Bytes
2b5226a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
52
53
54
55
56
"""

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):
        # Tree structure: XNOR(XNOR(a,b), XNOR(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))
                    # XNOR4 = even parity = NOT XOR4
                    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")