| import torch |
| from safetensors.torch import save_file |
|
|
| weights = {} |
|
|
| |
| |
| |
| |
| |
| |
|
|
| |
| for i in range(4): |
| weights[f'inv{i}.weight'] = torch.tensor([[-1.0]], dtype=torch.float32) |
| weights[f'inv{i}.bias'] = torch.tensor([0.0], dtype=torch.float32) |
|
|
| |
| def add_xor(name): |
| weights[f'{name}.or.weight'] = torch.tensor([[1.0, 1.0]], dtype=torch.float32) |
| weights[f'{name}.or.bias'] = torch.tensor([-1.0], dtype=torch.float32) |
| weights[f'{name}.nand.weight'] = torch.tensor([[-1.0, -1.0]], dtype=torch.float32) |
| weights[f'{name}.nand.bias'] = torch.tensor([1.0], dtype=torch.float32) |
| weights[f'{name}.and.weight'] = torch.tensor([[1.0, 1.0]], dtype=torch.float32) |
| weights[f'{name}.and.bias'] = torch.tensor([-2.0], dtype=torch.float32) |
|
|
| def add_ha(name): |
| add_xor(f'{name}.sum') |
| weights[f'{name}.carry.weight'] = torch.tensor([[1.0, 1.0]], dtype=torch.float32) |
| weights[f'{name}.carry.bias'] = torch.tensor([-2.0], dtype=torch.float32) |
|
|
| |
| |
| |
| |
| |
|
|
| |
| |
| |
| |
| |
|
|
| |
| |
| |
| |
| |
| |
| |
|
|
| |
| |
| |
| |
| |
| |
|
|
| |
| |
| |
| |
| |
| |
| |
|
|
| |
| |
| |
|
|
| |
| |
| |
| |
| |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| |
|
|
| for i in range(4): |
| add_ha(f'inc{i}') |
|
|
| |
| |
| |
| weights['ov_nora.weight'] = torch.tensor([[-1.0, -1.0, -1.0]], dtype=torch.float32) |
| weights['ov_nora.bias'] = torch.tensor([0.0], dtype=torch.float32) |
|
|
| weights['overflow.weight'] = torch.tensor([[1.0, 1.0]], dtype=torch.float32) |
| weights['overflow.bias'] = torch.tensor([-2.0], dtype=torch.float32) |
|
|
| save_file(weights, 'model.safetensors') |
|
|
| def twos_comp(a): |
| inv = (~a) & 0xF |
| neg = (inv + 1) & 0xF |
| overflow = 1 if a == 8 else 0 |
| return neg, overflow |
|
|
| print("Verifying 4-bit Two's Complement...") |
| errors = 0 |
| for a in range(16): |
| result, ov = twos_comp(a) |
| if a == 0: |
| expected = 0 |
| else: |
| expected = (16 - a) & 0xF |
| exp_ov = 1 if a == 8 else 0 |
|
|
| if result != expected or ov != exp_ov: |
| errors += 1 |
| if errors <= 5: |
| print(f"ERROR: -({a}) = {result}, expected {expected}") |
|
|
| if errors == 0: |
| print("All 16 test cases passed!") |
| else: |
| print(f"FAILED: {errors} errors") |
|
|
| print("\nSigned interpretation:") |
| for a in range(16): |
| signed_a = a if a < 8 else a - 16 |
| neg, ov = twos_comp(a) |
| signed_neg = neg if neg < 8 else neg - 16 |
| ov_str = " (OVERFLOW)" if ov else "" |
| print(f" -({signed_a:+d}) = {signed_neg:+d}{ov_str}") |
|
|
| mag = sum(t.abs().sum().item() for t in weights.values()) |
| print(f"\nMagnitude: {mag:.0f}") |
| print(f"Parameters: {sum(t.numel() for t in weights.values())}") |
|
|