|
|
"""
|
|
|
Threshold Network for Majority Gate
|
|
|
|
|
|
A formally verified single-neuron threshold network computing 8-bit majority.
|
|
|
Outputs 1 when 5 or more of the 8 inputs are true (strict majority).
|
|
|
"""
|
|
|
|
|
|
import torch
|
|
|
from safetensors.torch import load_file
|
|
|
|
|
|
|
|
|
class ThresholdMajority:
|
|
|
"""
|
|
|
Majority gate implemented as a threshold neuron.
|
|
|
|
|
|
Circuit: output = (sum of inputs + bias >= 0)
|
|
|
With all weights=1, bias=-5: fires when hamming weight >= 5.
|
|
|
"""
|
|
|
|
|
|
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(x0, x1, x2, x3, x4, x5, x6, x7, weights):
|
|
|
"""
|
|
|
Forward pass with Heaviside activation.
|
|
|
|
|
|
Args:
|
|
|
x0-x7: Individual input bits
|
|
|
weights: Dict with 'weight' and 'bias' tensors
|
|
|
|
|
|
Returns:
|
|
|
1 if majority (5+ of 8) are true, else 0
|
|
|
"""
|
|
|
x = torch.tensor([float(x0), float(x1), float(x2), float(x3),
|
|
|
float(x4), float(x5), float(x6), float(x7)])
|
|
|
weighted_sum = (x * weights['weight']).sum() + weights['bias']
|
|
|
return (weighted_sum >= 0).float()
|
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
weights = load_file("model.safetensors")
|
|
|
model = ThresholdMajority(weights)
|
|
|
|
|
|
print("Majority 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,1,0,0,0,0],
|
|
|
[1,1,1,1,1,0,0,0],
|
|
|
[1,1,1,1,1,1,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 >= 5 else 0
|
|
|
status = "OK" if out == expected else "FAIL"
|
|
|
print(f"HW={hw}: Majority({bits}) = {out} [{status}]")
|
|
|
|