File size: 1,187 Bytes
6dfdbee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""

Threshold Network for MOD-6 Circuit



A formally verified threshold network computing Hamming weight mod 6.

Uses the algebraic weight pattern [1, 1, 1, 1, 1, -5, 1, 1].

"""

import torch
from safetensors.torch import load_file


class ThresholdMod6:
    """

    MOD-6 circuit using threshold logic.



    Weight pattern: (1, 1, 1, 1, 1, 1-m) for m=6 at position 6

    """

    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

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


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

    print("MOD-6 Circuit Tests:")
    print("-" * 40)
    for hw in range(9):
        bits = [1]*hw + [0]*(8-hw)
        out = model(bits).item()
        expected = hw % 6
        print(f"HW={hw}: weighted_sum={out:.0f}, HW mod 6 = {expected}")