Nice — balanced ternary is a great fit for “matmul‑free” IMPLs because w ∈ {−1,0,1} turns multiplies into adds/subtracts or no‑ops. Below I’ll (1) state the simple algebraic facts you need, (2) show how to think about W·X when W is ternary and X is fp32/fp16, (3) give several GPU-friendly implementation patterns (with pros/cons), and (4) list practical tips (packing, accumulation precision, quantization/scaling, when you’ll actually win). If you want, I can follow up with a CUDA kernel skeleton tuned for a specific GPU/shape.
- Core algebra — why ternary is simple
- A ternary weight w ∈ {−1,0,1} gives the trivial identity:
y_i = Σ_j w_ij * x_j ⇒ y_i = Σ_{j: w_ij=+1} x_j − Σ_{j: w_ij=−1} x_j.
So each multiply reduces to either "add x", "subtract x", or "skip".
- Representational view: W = P − N where P,N are binary masks (P_{ij}=1 iff w_ij=+1; N_{ij}=1 iff w_ij=−1). Then W X = P X − N X.
- You can also store a scale α (per-layer or per-channel): real weight ≈ α ⋅ t where t∈{−1,0,1}. That recovers more accuracy: WX ≈ (α ⊙ T) X = α ⊙ (T X) (scale after accumulation).
- Balanced ternary digits (if you care about positional representation) have unique representation and carry rules; for ML you mostly use the scalar ±1/0 semantics.
- Matrix multiplication shapes and arithmetic choices
Let W ∈ {−1,0,1}^{M×K}, X ∈ R^{K×N} (fp16/fp32), Y = W·X ∈ R^{M×N}.
Two algebraic decompositions you will use:
- Row (inner‑product) view: for each output row i, y_i = Σ_j w_ij * x_j.
- Outer‑product view: Y = Σ_{k=0..K-1} w_{:,k} ⊗ X[k,:]. For each k you add or subtract the whole row X[k,:] to selected rows of Y.
Implementation choices follow from these decompositions.
- GPU-friendly implementation patterns (high level + tradeoffs)
A. Outer‑product (rank‑1 updates) — usually the most natural for ternary
- Algorithm: for k in 0..K−1: load row Xk = X[k,:]; for each output row i, if w_{i,k}=+1 then Y[i,:]+=Xk else if −1 then Y[i,:]−=Xk.
- Pros:
- Activations Xk are read once and reused to update many output rows → good activation reuse.
- Very natural to store W as two bitmasks (pos/neg) per column k: lists of rows to add/subtract.
- Perfect fit for blocked kernels: load Xk tile into shared memory once per inner loop.
- Cons:
- Requires many scattered writes to Y (but these can be handled by making each threadblock own a Y tile).
- If W is dense and M is small, you may not amortize the cost of broadcast updates.
B. Inner‑product (per‑row dot product)
- Algorithm: each thread (or thread-row) computes y_i by iterating over k in chunks; use pos/neg masks to either add or subtract x[k] to an accumulator.
- Pros:
- Conceptually identical to usual GEMM, easier to map to existing GEMM tiling.
- Coalesced writes: each thread writes contiguous output.
- Cons:
- You repeatedly read X elements (unless you tile well) — less activation reuse than outer‑product.
- Branching/bit testing per element unless you decode masks into sign vectors.
C. Two practical decompositions to implement cheaply
- Two binary matmuls: compute A = P·X and B = N·X, then Y = A − B. Implement P·X as sum of selected rows (same strategies above). This is easy conceptually.
- Decode into sign vectors and do vectorized FMAs: for a small chunk (say 16–32 entries) decode into float sign values s_j∈{+1,0,−1} and do acc += s · X_chunk using vector FMA. This uses multiplies but is extremely SIMD friendly and often fast on GPU.
- Data layout and packing
- Best practical store: two bit‑masks (pos, neg) of size ceil(K/word_bits) per output row (or per column depending on kernel). Bits are cheap and coalescent if you tile right.
- 2‑bit per weight scheme is another option: store 2 bits per weight packed into bytes or 32/64‑bit words; decode with a small LUT to sign/zero. But two separate bitmaps (pos, neg) is the simplest and fastest in decode.
- If weights are sparse, store index lists (CSR‑like): for each column k store the list of rows i with pos and neg. That’s ideal if density << 1.
- Avoiding multiplies (if you truly want matmul‑free)
- Replace multiply by 1 with add, by −1 with subtract. Implement subtraction without multiplication by bitwise sign flip:
- For fp32: neg_x = reinterpret_u32_as_f32(reinterpret_f32_as_u32(x) ^ 0x80000000u).
- For fp16: flip the high bit (0x8000).
- Then accumulator += neg_x (a single add).
- This reduces the kernel to loads, bit ops (cheap), and adds — but note: hardware multiply units are often as fast as adds, so removing multiplies doesn’t always give raw ALU speedup; the real win is weightmemory reduction and activation reuse.
- Accumulation precision & numerical stability
- Use FP32 accumulation (even if X is fp16). With large K, sums of many terms require fp32 to avoid catastrophic rounding; mixed FP16 inputs + FP32 accumulator is recommended for inference.
- Order of adds matters for rounding — consistent tiling/order is good for deterministic output. Pairwise or tree reductions produce better precision.
- Scale factors α multiply a final FP32 accumulator and are low overhead.
- Typical CUDA kernel outline — outer‑product style (pseudo)
Below is a simplified outer‑product style kernel sketch (conceptual):
// shapes: W: M x K ternary stored as pos_bitmap[M][ceil(K/32)], neg_bitmap[...].
// X: K x N (fp16 or fp32). Y: M x N (fp32 accumulators).
for blockM in 0..M step Mblock:
for blockN in 0..N step Nblock:
Y_tile = zeros(Mblock, Nblock) // in regs/shared
for k in 0..K:
load Xk_block = X[k, blockN:blockN+Nblock] into shared or regs
// Each thread handles some subset of rows of Y_tile:
for r in threads_assigned_rows:
pos_word = pos_bitmap[blockM + r][k/32]
neg_word = neg_bitmap[blockM + r][k/32]
// iterate bits (unroll) or branch on words:
for b in 0..min(31,K-1-(k/32*32)):
if ((pos_word >> b) & 1):
for c in thread_assigned_cols: Y_tile[r][c] += Xk_block[b][c]
else if ((neg_word >> b) & 1):
for c in thread_assigned_cols: Y_tile[r][c] -= Xk_block[b][c]
// apply per-row scale alpha (if any) and write Y_tile to global memory
Notes:
- You will vectorize the inner-most loops (half2/float4) and unroll bit loops.
- Shared memory stores Xk_block so multiple rows read it from fast memory.
- Choose Mblock, Nblock to fit registers & shared memory.
- Decode & vectorized alternative (fast, uses FMA)
- For each chunk of K say chunk_size=16:
- Load packed 2‑bit codes for 16 weights → decode into float array s[16] ∈ {+1,0,−1} using a small LUT or bit ops.
- Load X_chunk[16, Nblock]
- acc += s * X_chunk (vectorized FMAs). This is a clean, SIMD‑friendly inner loop that maps well to GPU ALUs.
- Performance expectations and when you win
- Memory saving: 2 bits per weight vs 32 bits is ≈16× weight memory reduction (or 8× vs fp16). If weights dominate your GEMM traffic, ternary can drastically reduce bandwidth and memory footprint.
- Compute: you replace multiply+add with add (and sign flip). On GPUs multiply and add throughput is often similar, so raw ALU speed may be similar; the main speed wins come from:
- Reduced weight memory traffic (less global memory bandwidth).
- If weights are sparse (lots of zeros), you skip many updates.
- Better cache/shared memory reuse due to smaller weight representation.
- If your layer is compute‑bound with activations large and weights fit in L2 or on‑chip cache, ternary may not help much.
- If you can restructure to outer‑product with big reuse of X rows, you can sometimes beat GEMM because convolution of 1×1 or FC layers becomes memory dominated by weights.
- Quantization & training (quick)
- Typical approach: quantize full‑precision W to ternary by thresholding and compute α (per-layer or per‑filter):
- t_ij = sign(w_ij) if |w_ij| > Δ else 0.
- α_i = mean(|w_ij| over j where t_ij ≠ 0) (per-output scaling)
- W ≈ α ⊙ T
- Use straight‑through estimator (STE) during training; many papers (Ternary Weight Network, Trained Ternary Quantization / TTQ) use per‑channel thresholds and per‑channel α to retain accuracy.
- If you use two scalars (α_pos, α_neg) one for + and one for −, you can gain accuracy at negligible runtime cost.
- Practical engineering tips / checklist
- Use two bitmaps (pos/neg) unless extreme packing matters. They’re simple and decode fast.
- Accumulate in FP32. Convert inputs (fp16) to fp32 when summing if numeric range is large.
- Tile so that X rows are reused from shared memory (outer‑product) or so that threads read contiguous memory (inner‑product).
- Use sign‑flip by XOR for fast negation without multiply.
- If using decode+FMA, tune chunk_size so LUT/decode cost amortized and vector ops fill ALUs.
- If weights are sparse, use index lists per column for even faster outer‑product updates.
- Measure the expected roofline: if weight memory traffic is your bottleneck, ternary will help; if activation loads or FMA throughput is critical and weight cache fits, the speedup may be modest.
- Watch numerical cancellation: compute pos and neg sums separately if that reduces catastrophic cancellation, then subtract.
- Example micro‑benchmark math (to reason if you’ll win)
- Suppose M×K weights, N outputs. Standard GEMM loads one weight per MAC: 4 bytes (fp32). Ternary loads ~0.25 bytes (2 bits). So memory traffic for weights reduces by ~16×. If your runtime is bandwidth‑bound on weight fetch, you can get large speedups (up to ~16× in the ideal limit). But you add some decode overhead and more memory transfers for any index lists or alpha scalars.
Wrap up / next steps
- If you want, tell me:
- typical shapes M,K,N,
- input type (fp16 or fp32),
- expected ternary density (fraction of non‑zeros),
- target GPU (Ampere, Ada, etc.),
and I’ll draft a tuned CUDA microkernel skeleton (outer‑product and decode+FMA versions) with register/shared memory layout and expected FLOP/BW model so we can see break‑even points.
Would you like a CUDA-style kernel skeleton for outer‑product (add/sub) and for decode+FMA so you can compare?