|
|
"""
|
|
|
Threshold Network for NOT Gate
|
|
|
|
|
|
A formally verified single-neuron threshold network computing logical negation.
|
|
|
Weights are integer-constrained and activation uses the Heaviside step function.
|
|
|
"""
|
|
|
|
|
|
import torch
|
|
|
from safetensors.torch import load_file
|
|
|
|
|
|
|
|
|
class ThresholdNOT:
|
|
|
"""
|
|
|
NOT gate implemented as a threshold neuron.
|
|
|
|
|
|
Circuit: output = (weight * input + bias >= 0)
|
|
|
With weight=-1, bias=0: NOT(0)=1, NOT(1)=0
|
|
|
"""
|
|
|
|
|
|
def __init__(self, weights_dict):
|
|
|
self.weight = weights_dict['weight']
|
|
|
self.bias = weights_dict['bias']
|
|
|
|
|
|
def __call__(self, x):
|
|
|
x = torch.as_tensor(x, dtype=torch.float32)
|
|
|
return (x * self.weight + self.bias >= 0).float()
|
|
|
|
|
|
@classmethod
|
|
|
def from_safetensors(cls, path="model.safetensors"):
|
|
|
return cls(load_file(path))
|
|
|
|
|
|
|
|
|
def forward(x, weights):
|
|
|
"""
|
|
|
Forward pass with Heaviside activation.
|
|
|
|
|
|
Args:
|
|
|
x: Input tensor (0 or 1)
|
|
|
weights: Dict with 'weight' and 'bias' tensors
|
|
|
|
|
|
Returns:
|
|
|
NOT(x)
|
|
|
"""
|
|
|
x = torch.as_tensor(x, dtype=torch.float32)
|
|
|
return (x * weights['weight'] + weights['bias'] >= 0).float()
|
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
weights = load_file("model.safetensors")
|
|
|
model = ThresholdNOT(weights)
|
|
|
|
|
|
print("NOT Gate Truth Table:")
|
|
|
print("-" * 20)
|
|
|
for inp in [0, 1]:
|
|
|
out = int(model(inp).item())
|
|
|
expected = 1 - inp
|
|
|
status = "OK" if out == expected else "FAIL"
|
|
|
print(f"NOT({inp}) = {out} [{status}]")
|
|
|
|