threshold-crc8 / create_safetensors.py
phanerozoic's picture
Upload folder using huggingface_hub
75a5789 verified
import torch
from safetensors.torch import save_file
weights = {}
# CRC-8 (polynomial 0x07: x^8 + x^2 + x + 1)
# Computes one step of CRC given current CRC state and input bit
# Input: CRC[7:0], DATA_BIT
# Output: NEW_CRC[7:0]
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)
# CRC-8 feedback: MSB XOR data_bit
# When feedback=1: CRC shifts and XORs with polynomial
# Polynomial 0x07 = 00000111 -> taps at positions 0, 1, 2
# Inputs: C7=0, C6=1, C5=2, C4=3, C3=4, C2=5, C1=6, C0=7, D=8
# Feedback = C7 XOR D
add_neuron('fb_or', [1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0], -1.0)
add_neuron('fb_nand', [-1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -1.0], 1.0)
# New CRC bits (simplified - shift with conditional XOR)
for i in range(8):
add_neuron(f'c{i}_shift', [0.0]*(7-i) + [1.0] + [0.0]*(i+1) if i < 7 else [0.0]*9, -1.0 if i < 7 else 0.0)
save_file(weights, 'model.safetensors')
def crc8_step(crc, data_bit, poly=0x07):
feedback = ((crc >> 7) ^ data_bit) & 1
crc = (crc << 1) & 0xFF
if feedback:
crc ^= poly
return crc
print("Verifying CRC-8 step function...")
errors = 0
for crc in range(256):
for d in [0, 1]:
result = crc8_step(crc, d)
# Verify feedback logic
fb = ((crc >> 7) ^ d) & 1
expected = ((crc << 1) & 0xFF) ^ (0x07 if fb else 0)
if result != expected:
errors += 1
if errors == 0:
print("All 512 test cases passed!")
else:
print(f"FAILED: {errors} errors")
# Test with actual message
msg = [1, 0, 1, 0, 0, 0, 1, 1] # Example byte
crc = 0
for bit in msg:
crc = crc8_step(crc, bit)
print(f"CRC-8 of message: 0x{crc:02X}")
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())}")