Download model.py from phanerozoic/threshold-nand: direct link, hf CLI and curl.
- Browser
- Download file 1.84 kB
-
https://huggingface.co/phanerozoic/threshold-nand/resolve/main/model.py
- Command line
-
hf download hf://phanerozoic/threshold-nand/model.py
-
curl -L -o model.py https://huggingface.co/phanerozoic/threshold-nand/resolve/main/model.py
1.84 kB
| """ | |
| Threshold Network for NAND Gate | |
| A formally verified single-neuron threshold network computing negated conjunction. | |
| Weights are integer-constrained and activation uses the Heaviside step function. | |
| NAND is functionally complete - any Boolean function can be built from NAND gates. | |
| """ | |
| import torch | |
| from safetensors.torch import load_file | |
| class ThresholdNAND: | |
| """ | |
| NAND gate implemented as a threshold neuron. | |
| Circuit: output = (w1*x1 + w2*x2 + bias >= 0) | |
| With weights=[-1,-1], bias=1: fires unless both inputs are 1. | |
| """ | |
| def __init__(self, weights_dict): | |
| self.weight = weights_dict['weight'] | |
| self.bias = weights_dict['bias'] | |
| def __call__(self, x1, x2): | |
| inputs = torch.tensor([float(x1), float(x2)]) | |
| weighted_sum = (inputs * self.weight).sum() + self.bias | |
| return (weighted_sum >= 0).float() | |
| 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 of shape [..., 2] | |
| weights: Dict with 'weight' and 'bias' tensors | |
| Returns: | |
| NAND(x[0], x[1]) | |
| """ | |
| x = torch.as_tensor(x, dtype=torch.float32) | |
| weighted_sum = (x * weights['weight']).sum(dim=-1) + weights['bias'] | |
| return (weighted_sum >= 0).float() | |
| if __name__ == "__main__": | |
| weights = load_file("model.safetensors") | |
| model = ThresholdNAND(weights) | |
| print("NAND Gate Truth Table:") | |
| print("-" * 25) | |
| for x1 in [0, 1]: | |
| for x2 in [0, 1]: | |
| out = int(model(x1, x2).item()) | |
| expected = 1 - (x1 & x2) | |
| status = "OK" if out == expected else "FAIL" | |
| print(f"NAND({x1}, {x2}) = {out} [{status}]") | |