mkvn's picture
Paper, codec, routing traces and measurements
6ec9472 verified
Raw
History Blame Contribute Delete
1.66 kB
"""Optimised GPU primitives for the decode path.
* `fwht_kron` - Walsh-Hadamard transform as two dense GEMMs via the Kronecker
factorisation H_{ab} = H_a (x) H_b, which replaces O(log n) kernel launches
with two cuBLAS calls.
* `decode` - multi-stage codebook reconstruction using int32 index_select
and a preallocated accumulator, avoiding the int64 promotion and the
per-stage temporaries of the naive gather.
"""
import math
import torch
_HCACHE = {}
def hadamard_matrix(n, device, dtype):
key = (n, device, dtype)
if key not in _HCACHE:
H = torch.ones(1, 1, device=device, dtype=dtype)
while H.shape[0] < n:
H = torch.cat([torch.cat([H, H], 1), torch.cat([H, -H], 1)], 0)
_HCACHE[key] = H / math.sqrt(n)
return _HCACHE[key]
def _factor(n):
a = 1 << (int(math.log2(n)) // 2)
return a, n // a
def fwht_kron(x):
"""Normalised WHT over the last dimension (power of two)."""
n = x.shape[-1]
a, b = _factor(n)
Ha = hadamard_matrix(a, x.device, x.dtype) * math.sqrt(a)
Hb = hadamard_matrix(b, x.device, x.dtype) * math.sqrt(b)
y = x.reshape(-1, a, b)
y = Ha @ y @ Hb
return (y / math.sqrt(n)).reshape(x.shape)
def decode(idx32, codebooks, scale=None, out=None, row=2048):
"""idx32: [stages, N] int32 codebook indices; codebooks: [stages][256, D]."""
S, N = idx32.shape
D = codebooks[0].shape[1]
acc = torch.index_select(codebooks[0], 0, idx32[0])
for s in range(1, S):
acc.add_(torch.index_select(codebooks[s], 0, idx32[s]))
if scale is not None:
acc = acc.view(-1, row) * scale
return acc.reshape(-1)