| import torch |
| from safetensors.torch import save_file |
|
|
| |
| |
| |
| |
| |
| |
| |
|
|
| weights = {} |
|
|
| |
|
|
| |
| weights['g3.weight'] = torch.tensor([[2.0, 0.0, 0.0, 0.0]], dtype=torch.float32) |
| weights['g3.bias'] = torch.tensor([-1.0], dtype=torch.float32) |
|
|
| |
| weights['g2_or.weight'] = torch.tensor([[1.0, 1.0, 0.0, 0.0]], dtype=torch.float32) |
| weights['g2_or.bias'] = torch.tensor([-1.0], dtype=torch.float32) |
| weights['g2_nand.weight'] = torch.tensor([[-1.0, -1.0, 0.0, 0.0]], dtype=torch.float32) |
| weights['g2_nand.bias'] = torch.tensor([1.0], dtype=torch.float32) |
| weights['g2.weight'] = torch.tensor([[1.0, 1.0]], dtype=torch.float32) |
| weights['g2.bias'] = torch.tensor([-2.0], dtype=torch.float32) |
|
|
| |
| weights['g1_or.weight'] = torch.tensor([[0.0, 1.0, 1.0, 0.0]], dtype=torch.float32) |
| weights['g1_or.bias'] = torch.tensor([-1.0], dtype=torch.float32) |
| weights['g1_nand.weight'] = torch.tensor([[0.0, -1.0, -1.0, 0.0]], dtype=torch.float32) |
| weights['g1_nand.bias'] = torch.tensor([1.0], dtype=torch.float32) |
| weights['g1.weight'] = torch.tensor([[1.0, 1.0]], dtype=torch.float32) |
| weights['g1.bias'] = torch.tensor([-2.0], dtype=torch.float32) |
|
|
| |
| weights['g0_or.weight'] = torch.tensor([[0.0, 0.0, 1.0, 1.0]], dtype=torch.float32) |
| weights['g0_or.bias'] = torch.tensor([-1.0], dtype=torch.float32) |
| weights['g0_nand.weight'] = torch.tensor([[0.0, 0.0, -1.0, -1.0]], dtype=torch.float32) |
| weights['g0_nand.bias'] = torch.tensor([1.0], dtype=torch.float32) |
| weights['g0.weight'] = torch.tensor([[1.0, 1.0]], dtype=torch.float32) |
| weights['g0.bias'] = torch.tensor([-2.0], dtype=torch.float32) |
|
|
| save_file(weights, 'model.safetensors') |
|
|
| def binary2gray(b3, b2, b1, b0): |
| inp = [b3, b2, b1, b0] |
|
|
| |
| g3 = int(2*b3 - 1 >= 0) |
|
|
| |
| g2_or = int(b3 + b2 - 1 >= 0) |
| g2_nand = int(-b3 - b2 + 1 >= 0) |
| g2 = int(g2_or + g2_nand - 2 >= 0) |
|
|
| |
| g1_or = int(b2 + b1 - 1 >= 0) |
| g1_nand = int(-b2 - b1 + 1 >= 0) |
| g1 = int(g1_or + g1_nand - 2 >= 0) |
|
|
| |
| g0_or = int(b1 + b0 - 1 >= 0) |
| g0_nand = int(-b1 - b0 + 1 >= 0) |
| g0 = int(g0_or + g0_nand - 2 >= 0) |
|
|
| return g3, g2, g1, g0 |
|
|
| print("Verifying binary2gray...") |
| errors = 0 |
| for i in range(16): |
| b3, b2, b1, b0 = (i >> 3) & 1, (i >> 2) & 1, (i >> 1) & 1, i & 1 |
| g3, g2, g1, g0 = binary2gray(b3, b2, b1, b0) |
| result = g3 * 8 + g2 * 4 + g1 * 2 + g0 |
|
|
| expected = i ^ (i >> 1) |
|
|
| if result != expected: |
| errors += 1 |
| print(f"ERROR: binary {b3}{b2}{b1}{b0} -> gray {g3}{g2}{g1}{g0} (={result}), expected {expected}") |
|
|
| if errors == 0: |
| print("All 16 test cases passed!") |
|
|
| mag = sum(t.abs().sum().item() for t in weights.values()) |
| print(f"Magnitude: {mag:.0f}") |
|
|