File size: 1,660 Bytes
6ec9472
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
"""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)