threshold-parity6 / model.py
phanerozoic's picture
Upload folder using huggingface_hub
a1b9bf4 verified
import torch
from safetensors.torch import load_file
def load_model(path='model.safetensors'):
return load_file(path)
def xor2(a, b, prefix, w):
or_out = int(a * w[f'{prefix}.or.weight'][0] + b * w[f'{prefix}.or.weight'][1] + w[f'{prefix}.or.bias'] >= 0)
nand_out = int(a * w[f'{prefix}.nand.weight'][0] + b * w[f'{prefix}.nand.weight'][1] + w[f'{prefix}.nand.bias'] >= 0)
return int(or_out * w[f'{prefix}.and.weight'][0] + nand_out * w[f'{prefix}.and.weight'][1] + w[f'{prefix}.and.bias'] >= 0)
def parity6(x0, x1, x2, x3, x4, x5, weights):
"""6-bit parity: returns 1 if odd number of inputs are high."""
xor01 = xor2(x0, x1, 'xor_01', weights)
xor23 = xor2(x2, x3, 'xor_23', weights)
xor45 = xor2(x4, x5, 'xor_45', weights)
xor0123 = xor2(xor01, xor23, 'xor_0123', weights)
return xor2(xor0123, xor45, 'xor_final', weights)
if __name__ == '__main__':
w = load_model()
print('parity6 truth table by Hamming weight:')
print('HW | Example | Parity')
print('---+--------------+--------')
for hw in range(7):
bits = [1 if j < hw else 0 for j in range(6)]
result = parity6(*bits, w)
expected = hw % 2
status = 'OK' if result == expected else 'FAIL'
bits_str = ''.join(str(b) for b in bits)
print(f' {hw} | {bits_str} | {result} {status}')