|
|
"""
|
|
|
Threshold Network for MOD-8 Circuit
|
|
|
|
|
|
A formally verified threshold network computing Hamming weight mod 8.
|
|
|
Uses the algebraic weight pattern [1, 1, 1, 1, 1, 1, 1, -7].
|
|
|
"""
|
|
|
|
|
|
import torch
|
|
|
from safetensors.torch import load_file
|
|
|
|
|
|
|
|
|
class ThresholdMod8:
|
|
|
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 = ThresholdMod8(weights)
|
|
|
|
|
|
print("MOD-8 Circuit Tests:")
|
|
|
for hw in range(9):
|
|
|
bits = [1]*hw + [0]*(8-hw)
|
|
|
out = model(bits).item()
|
|
|
print(f"HW={hw}: weighted_sum={out:.0f}, HW mod 8 = {hw % 8}")
|
|
|
|