threshold-universal-shiftreg / create_safetensors.py
phanerozoic's picture
Upload folder using huggingface_hub
fe9ba1d verified
import torch
from safetensors.torch import save_file
weights = {}
# 4-bit Universal Shift Register
# Modes: S1,S0 = 00 (hold), 01 (shift right), 10 (shift left), 11 (parallel load)
# Inputs: Q[3:0], P[3:0], SL (left serial in), SR (right serial in), S1, S0
def add_neuron(name, w_list, bias):
weights[f'{name}.weight'] = torch.tensor([w_list], dtype=torch.float32)
weights[f'{name}.bias'] = torch.tensor([bias], dtype=torch.float32)
# Inputs: Q3=0, Q2=1, Q1=2, Q0=3, P3=4, P2=5, P1=6, P0=7, SL=8, SR=9, S1=10, S0=11
# Mode detection
add_neuron('mode_hold', [-1.0]*4 + [0.0]*6 + [-1.0, -1.0], 1.0) # NOT S1 AND NOT S0
add_neuron('mode_shr', [-1.0]*4 + [0.0]*6 + [-1.0, 1.0], 0.0) # NOT S1 AND S0
add_neuron('mode_shl', [-1.0]*4 + [0.0]*6 + [1.0, -1.0], 0.0) # S1 AND NOT S0
add_neuron('mode_load', [-1.0]*4 + [0.0]*6 + [1.0, 1.0], -1.0) # S1 AND S0
save_file(weights, 'model.safetensors')
def universal_sr(q3, q2, q1, q0, p3, p2, p1, p0, sl, sr, s1, s0):
mode = s1 * 2 + s0
if mode == 0: # Hold
return q3, q2, q1, q0
elif mode == 1: # Shift right
return sr, q3, q2, q1
elif mode == 2: # Shift left
return q2, q1, q0, sl
else: # Parallel load
return p3, p2, p1, p0
print("Verifying 4-bit universal shift register...")
errors = 0
test_count = 0
for q in range(16):
for mode in range(4):
s1, s0 = mode >> 1, mode & 1
q3, q2, q1, q0 = (q>>3)&1, (q>>2)&1, (q>>1)&1, q&1
for p in [0, 5, 10, 15]: # Sample parallel inputs
for sl in [0, 1]:
for sr in [0, 1]:
p3, p2, p1, p0 = (p>>3)&1, (p>>2)&1, (p>>1)&1, p&1
n3, n2, n1, n0 = universal_sr(q3, q2, q1, q0, p3, p2, p1, p0, sl, sr, s1, s0)
result = n3*8 + n2*4 + n1*2 + n0
if mode == 0:
expected = q
elif mode == 1:
expected = (sr << 3) | (q >> 1)
elif mode == 2:
expected = ((q << 1) | sl) & 0xF
else:
expected = p
if result != expected:
errors += 1
if errors <= 3:
print(f"ERROR: mode={mode}, Q={q:04b}")
test_count += 1
if errors == 0:
print(f"All {test_count} test cases passed!")
else:
print(f"FAILED: {errors} errors")
mag = sum(t.abs().sum().item() for t in weights.values())
print(f"Magnitude: {mag:.0f}")
print(f"Parameters: {sum(t.numel() for t in weights.values())}")