Engineering Category: Balanced Ternary & b158 Quantization
Best Use in Production: High-speed ternary dot-product accumulation without integer multiplier bottlenecks; ideal for b158 neural weights and low-bit attention inner loops.
When to Select This Capsule: Sole canonical implementation for its 64-vector functional equivalence class. Low-latency L1-resident kernel (3475467/200000 cyc/op); well-suited for high-frequency pipeline stages.
Snap-Circuit Wiring Role: 2-to-1 Binary Combiner / Join Stage `(i64,i64)->i64` — ideal for merging two upstream DAG branches, dot products, or pairwise rank fusion.
.text: 198 B (44 x86_64 insns)1035 B)/// Dot product of eight ternary lanes packed into one machine word, without
/// multiplying.
///
/// Each byte is a trit: 0x01 (+1), 0x00 (0) or 0xFF (-1). Both the +1 and the
/// -1 lanes have a set low bit, so the negative lanes are cleared out before a
/// lane is read as +1 -- missing that is the classic packed-ternary bug.
///
/// `+1 * +1` and `-1 * -1` are +1, a mismatched sign is -1, a zero lane is 0,
/// so the whole product is two AND masks per outcome and two popcounts. No
/// multiply, no widening, no table, identical on every architecture: the
/// portable twin of a NEON int8 dot.
pub fn ternary_dot_packed(a: i64, b: i64) -> i64 {
const LANE_ONE: i64 = 0x0101_0101_0101_0101;
let a_neg = (a >> 7) & LANE_ONE;
let b_neg = (b >> 7) & LANE_ONE;
let a_one = a & LANE_ONE & !a_neg;
let b_one = b & LANE_ONE & !b_neg;
let positive = (a_one & b_one) | (a_neg & b_neg);
let negative = (a_one & b_neg) | (a_neg & b_one);
i64::from(positive.count_ones()) - i64::from(negative.count_ones())
}
rustc -C opt-level=3 x86_64 Disassembly (198 B .text / 44 insns)ternary_dot_packed:
mov rax, rsi
shr rax, 7
movabs rcx, 72340172838076673
and rcx, rdi
movq xmm0, rdi
not rdi
shr rdi, 7
mov rdx, rax
not rdx
and rdx, rsi
and rcx, rdi
movq xmm1, rdx
and rdx, rcx
and rcx, rax
movq xmm2, rax
punpcklqdq xmm2, xmm1
pand xmm2, xmmword ptr [rip + .LCPI7_0]
pshufd xmm0, xmm0, 68
psrlq xmm0, 7
pand xmm0, xmm2
movq xmm1, rdx
movq xmm2, rcx
punpcklqdq xmm1, xmm2
por xmm1, xmm0
movdqa xmm0, xmm1
psrlw xmm0, 1
pand xmm0, xmmword ptr [rip + .LCPI7_1]
psubb xmm1, xmm0
movdqa xmm0, xmmword ptr [rip + .LCPI7_2]
movdqa xmm2, xmm1
pand xmm2, xmm0
psrlw xmm1, 2
pand xmm1, xmm0
paddb xmm1, xmm2
movdqa xmm0, xmm1
psrlw xmm0, 4
paddb xmm0, xmm1
pand xmm0, xmmword ptr [rip + .LCPI7_3]
pxor xmm1, xmm1
psadbw xmm1, xmm0
pshufd xmm0, xmm1, 238
psubq xmm1, xmm0
movq rax, xmm1
ret
| Global Rank | Capsule & Domain | Hardware _rdtsc | Latency | Throughput | ELF .text | Ternary Vote | Author Aye |
|---|---|---|---|---|---|---|---|
| #1542 | ternary_dot_packed (THIS CAPSULE) domain: ternary | id: ab34bfb18eb3a622467788b62bbd699b | 3475467/200000 cyc/op | 2172623/400000 ns/op | 400000000/2172623 ops/us | 198 B .text (44 insns) | + (1) | aye::Peter+Omni(0+1)::aarch64 @ 432Hz |