File size: 1,997 Bytes
b510417
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
"""

Threshold Network for Minority Gate



A formally verified single-neuron threshold network computing 8-bit minority.

Outputs 1 when 3 or fewer of the 8 inputs are true (strict minority).

"""

import torch
from safetensors.torch import load_file


class ThresholdMinority:
    """

    Minority gate implemented as a threshold neuron.



    Circuit: output = (sum of weighted inputs + bias >= 0)

    With all weights=-1, bias=3: fires when hamming weight <= 3.

    """

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

    Forward pass with Heaviside activation.



    Args:

        x: Input tensor of shape [..., 8]

        weights: Dict with 'weight' and 'bias' tensors



    Returns:

        1 if minority (3 or fewer of 8) are true, else 0

    """
    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 = ThresholdMinority(weights)

    print("Minority Gate Tests:")
    print("-" * 40)

    test_cases = [
        [0,0,0,0,0,0,0,0],
        [1,0,0,0,0,0,0,0],
        [1,1,1,0,0,0,0,0],
        [1,1,1,1,0,0,0,0],
        [1,1,1,1,1,0,0,0],
        [1,1,1,1,1,1,1,1],
    ]

    for bits in test_cases:
        hw = sum(bits)
        out = int(model(bits).item())
        expected = 1 if hw <= 3 else 0
        status = "OK" if out == expected else "FAIL"
        print(f"HW={hw}: Minority({bits}) = {out}  [{status}]")