File size: 1,450 Bytes
6a0af35
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
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 parity7(x0, x1, x2, x3, x4, x5, x6, weights):
    """7-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)
    xor456 = xor2(xor45, x6, 'xor_456', weights)
    return xor2(xor0123, xor456, 'xor_final', weights)

if __name__ == '__main__':
    w = load_model()
    print('parity7 truth table by Hamming weight:')
    print('HW | Example       | Parity')
    print('---+---------------+--------')
    for hw in range(8):
        bits = [1 if j < hw else 0 for j in range(7)]
        result = parity7(*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}')