phanerozoic's picture
Rename from tiny-BiImplies-verified
e1404bc verified
"""
Threshold Network for Biconditional Gate
A formally verified two-layer threshold network computing logical equivalence (iff).
Biconditional is not linearly separable, requiring at least 2 layers.
Architecture: Layer1 computes NOR and AND, Layer2 computes OR of results.
"""
import torch
from safetensors.torch import load_file
class ThresholdBiImplies:
"""
Biconditional gate implemented as a 2-layer threshold network.
Layer 1: NOR (neuron 1) and AND (neuron 2) in parallel
Layer 2: OR of layer 1 outputs
BiImplies(x,y) = OR(NOR(x,y), AND(x,y)) = (x iff y)
"""
def __init__(self, weights_dict):
self.l1_n1_weight = weights_dict['layer1.neuron1.weight']
self.l1_n1_bias = weights_dict['layer1.neuron1.bias']
self.l1_n2_weight = weights_dict['layer1.neuron2.weight']
self.l1_n2_bias = weights_dict['layer1.neuron2.bias']
self.l2_weight = weights_dict['layer2.weight']
self.l2_bias = weights_dict['layer2.bias']
def __call__(self, x1, x2):
inputs = torch.tensor([float(x1), float(x2)])
nor_out = ((inputs * self.l1_n1_weight).sum() + self.l1_n1_bias >= 0).float()
and_out = ((inputs * self.l1_n2_weight).sum() + self.l1_n2_bias >= 0).float()
layer1_out = torch.tensor([nor_out, and_out])
output = ((layer1_out * self.l2_weight).sum() + self.l2_bias >= 0).float()
return output
@classmethod
def from_safetensors(cls, path="model.safetensors"):
return cls(load_file(path))
def forward(x1, x2, weights):
"""
Forward pass with Heaviside activation.
Args:
x1, x2: Input values (0 or 1)
weights: Dict with layer weights and biases
Returns:
BiImplies(x1, x2) = (x1 iff x2)
"""
inputs = torch.tensor([float(x1), float(x2)])
nor_out = ((inputs * weights['layer1.neuron1.weight']).sum() + weights['layer1.neuron1.bias'] >= 0).float()
and_out = ((inputs * weights['layer1.neuron2.weight']).sum() + weights['layer1.neuron2.bias'] >= 0).float()
layer1_out = torch.tensor([nor_out, and_out])
output = ((layer1_out * weights['layer2.weight']).sum() + weights['layer2.bias'] >= 0).float()
return output
if __name__ == "__main__":
weights = load_file("model.safetensors")
model = ThresholdBiImplies(weights)
print("Biconditional Gate Truth Table:")
print("-" * 30)
for x1 in [0, 1]:
for x2 in [0, 1]:
out = int(model(x1, x2).item())
expected = 1 if x1 == x2 else 0
status = "OK" if out == expected else "FAIL"
print(f"BiImplies({x1}, {x2}) = {out} [{status}]")