--- license: mit tags: - pytorch - safetensors - threshold-logic - neuromorphic - arithmetic --- # threshold-ripplecarry4bit Adds two 4-bit numbers with carry-in. Four cascaded full adders in the classic ripple-carry architecture. ## Circuit ``` a0 b0 cin a1 b1 a2 b2 a3 b3 │ │ │ │ │ │ │ │ │ └──┼──┘ └──┼──┘ └──┼──┘ └──┼──┘ ▼ ▼ ▼ ▼ ┌───────┐ ┌───────┐ ┌───────┐ ┌───────┐ │ FA0 │───c0───│ FA1 │──c1──│ FA2 │──c2──│ FA3 │───cout └───────┘ └───────┘ └───────┘ └───────┘ │ │ │ │ ▼ ▼ ▼ ▼ s0 s1 s2 s3 Input: (a3 a2 a1 a0) + (b3 b2 b1 b0) + cin Output: (cout s3 s2 s1 s0) ``` The carry ripples through each full adder sequentially, hence "ripple-carry." ## Full Adder Structure (each FA) ``` a b │ │ └───┬───┘ ▼ ┌─────────┐ │ HA1 │ Half adder 1 └─────────┘ │ │ s1 c1 │ \ │ cin \ └──┬──┘ \ ▼ \ ┌─────────┐ \ │ HA2 │ │ └─────────┘ │ │ │ │ sum c2 │ │ │ └──┬───┘ ▼ ┌──────┐ │ OR │ └──────┘ │ ▼ cout ``` ## Example ``` 1111 (15) + 0001 ( 1) ────── 10000 (16) ``` 15 + 1 = 16, which overflows 4 bits. The result is s=[0,0,0,0] with cout=1. ## Architecture | Component | Per FA | Total (4 FAs) | |-----------|--------|---------------| | Neurons | 9 | 36 | | Parameters | 27 | 108 | | Layers | 4 | 16 | ## Inputs/Outputs | Name | Bits | Description | |------|------|-------------| | a | a3..a0 | First 4-bit number (LSB = a0) | | b | b3..b0 | Second 4-bit number (LSB = b0) | | cin | 1 | Carry in | | s | s3..s0 | 4-bit sum (LSB = s0) | | cout | 1 | Carry out | ## Critical Path The worst-case delay is when a carry must propagate through all 4 full adders: ``` cin → FA0.cout → FA1.cout → FA2.cout → FA3.cout ``` This is 4 × 4 = 16 layers deep. Carry-lookahead would reduce this but requires more complex circuitry. ## Usage ```python from safetensors.torch import load_file w = load_file('model.safetensors') def ripple_carry_4bit(a, b, cin): """a, b: 4-bit lists [a0,a1,a2,a3] (LSB first)""" # See model.py for full implementation pass # Example: 7 + 5 = 12 a = [1, 1, 1, 0] # 7 in LSB-first b = [1, 0, 1, 0] # 5 in LSB-first sums, cout = ripple_carry_4bit(a, b, 0) # sums = [0, 0, 1, 1], cout = 0 → 12 ``` ## Scaling | Bits | Full Adders | Neurons | Parameters | Max Depth | |------|-------------|---------|------------|-----------| | 2 | 2 | 18 | 54 | 8 | | 4 | 4 | 36 | 108 | 16 | | 8 | 8 | 72 | 216 | 32 | | n | n | 9n | 27n | 4n | ## Files ``` threshold-ripplecarry4bit/ ├── model.safetensors ├── model.py ├── config.json └── README.md ``` ## License MIT