|
|
"""
|
|
|
Threshold Network for MOD-4 Circuit
|
|
|
|
|
|
A formally verified threshold network computing Hamming weight mod 4.
|
|
|
Uses the algebraic weight pattern [1, 1, 1, -3, 1, 1, 1, -3].
|
|
|
"""
|
|
|
|
|
|
import torch
|
|
|
from safetensors.torch import load_file
|
|
|
|
|
|
|
|
|
class ThresholdMod4:
|
|
|
"""
|
|
|
MOD-4 circuit using threshold logic.
|
|
|
|
|
|
Weight pattern: (1, 1, 1, 1-m) repeating for m=4
|
|
|
Computes cumulative sum that cycles mod 4.
|
|
|
"""
|
|
|
|
|
|
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
|
|
|
|
|
|
def get_residue(self, bits):
|
|
|
"""Returns Hamming weight mod 4."""
|
|
|
return sum(bits) % 4
|
|
|
|
|
|
@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
|
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
weights = load_file("model.safetensors")
|
|
|
model = ThresholdMod4(weights)
|
|
|
|
|
|
print("MOD-4 Circuit Tests:")
|
|
|
print("-" * 40)
|
|
|
for hw in range(9):
|
|
|
bits = [1]*hw + [0]*(8-hw)
|
|
|
out = model(bits).item()
|
|
|
expected_residue = hw % 4
|
|
|
print(f"HW={hw}: weighted_sum={out:.0f}, HW mod 4 = {expected_residue}")
|
|
|
|