File size: 1,434 Bytes
9c4af73
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""

Threshold Network for 2-out-of-8 Gate



A formally verified single-neuron threshold network.

Outputs 1 when at least 2 of the 8 inputs are true.

"""

import torch
from safetensors.torch import load_file


class Threshold2OutOf8:
    """

    2-out-of-8 threshold gate.



    Circuit: output = (sum of inputs - 2 >= 0)

    Fires when hamming weight >= 2.

    """

    def __init__(self, weights_dict):
        self.weight = weights_dict['weight']
        self.bias = weights_dict['bias']

    def __call__(self, bits):
        inputs = torch.tensor([float(b) for b in bits])
        weighted_sum = (inputs * self.weight).sum() + self.bias
        return (weighted_sum >= 0).float()

    @classmethod
    def from_safetensors(cls, path="model.safetensors"):
        return cls(load_file(path))


def forward(x, weights):
    x = torch.as_tensor(x, dtype=torch.float32)
    weighted_sum = (x * weights['weight']).sum(dim=-1) + weights['bias']
    return (weighted_sum >= 0).float()


if __name__ == "__main__":
    weights = load_file("model.safetensors")
    model = Threshold2OutOf8(weights)

    print("2-out-of-8 Gate Tests:")
    print("-" * 35)
    for hw in range(9):
        bits = [1]*hw + [0]*(8-hw)
        out = int(model(bits).item())
        expected = 1 if hw >= 2 else 0
        status = "OK" if out == expected else "FAIL"
        print(f"HW={hw}: {out}  [{status}]")