File size: 5,398 Bytes
e8a992b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
"""Unit tests verifying Q6_K, Q8_0, SwitchGLU MoE, and KDA CUDA kernels against gguf/PyTorch."""
from __future__ import annotations

import sys
import time
from pathlib import Path

import gguf
import numpy as np
import torch

ROOT = Path(r"C:\Users\jhjwi\.gemini\antigravity\scratch\webbrain-lingloop-8b-wsp")
sys.path.insert(0, str(ROOT))

from lingloop_cuda.cuda_gguf_kernels import (
    Q6_K_BYTES,
    Q8_0_BYTES,
    dequantize_q6_k_cuda,
    dequantize_q8_0_cuda,
    kda_step_cuda,
    naive_recurrent_kda_torch,
    q6_k_gemv_cuda,
    q6_k_switch_gate_up_swiglu_cuda,
    q6_k_switch_gemv_cuda,
)


def make_random_q6_k(rng: np.random.Generator, shape: tuple[int, ...]) -> np.ndarray:
    total = 1
    for d in shape:
        total *= int(d)
    assert total % 256 == 0
    nb = total // 256
    blks = rng.integers(0, 256, size=(nb, 210), dtype=np.uint8)
    # Valid scales int8 in [-16, 16] and valid small FP16 d in ~[0.01, 0.05]
    blks[:, 192:208] = rng.integers(-16, 17, size=(nb, 16), dtype=np.int8).view(np.uint8)
    d_vals = rng.uniform(0.0005, 0.002, size=(nb, 1)).astype(np.float16)
    blks[:, 208:210] = d_vals.view(np.uint8)
    return blks.reshape(*shape[:-1], (shape[-1] // 256) * 210)


def main() -> None:
    torch.manual_seed(0)
    rng = np.random.default_rng(0)

    # 1. Test Q6_K dequant against gguf.quants.dequantize
    rows, cols = 64, 512
    q6_np = make_random_q6_k(rng, (rows, cols))
    w_gguf_ref = gguf.quants.dequantize(q6_np, gguf.GGMLQuantizationType.Q6_K).astype(np.float16).astype(np.float32)
    w_q6_gpu = torch.from_numpy(q6_np.copy()).cuda()
    w_cuda = dequantize_q6_k_cuda(w_q6_gpu, (rows, cols), out_dtype=torch.float16).cpu().float().numpy()
    diff_q6 = float(np.abs(w_cuda - w_gguf_ref).max())
    print(f"[test] q6_k_dequant (vs fp16-cast ref): max_abs_diff={diff_q6:.6e}", flush=True)
    assert diff_q6 <= 1e-2

    # 2. Test Q8_0 dequant against gguf.quants.dequantize
    w8_f32 = rng.normal(0.0, 0.25, size=(32, 256)).astype(np.float32)
    q8_np = gguf.quants.quantize(w8_f32, gguf.GGMLQuantizationType.Q8_0)
    w8_ref = gguf.quants.dequantize(q8_np, gguf.GGMLQuantizationType.Q8_0).astype(np.float16).astype(np.float32)
    w8_cuda = dequantize_q8_0_cuda(torch.from_numpy(q8_np.copy()).cuda(), (32, 256), out_dtype=torch.float16).cpu().float().numpy()
    diff_q8 = float(np.abs(w8_cuda - w8_ref).max())
    print(f"[test] q8_0_dequant (vs fp16-cast ref): max_abs_diff={diff_q8:.6e}", flush=True)
    assert diff_q8 <= 2e-3

    # 3. Test Q6_K GEMV (M=1 and M=3)
    w_fp16_ref = dequantize_q6_k_cuda(w_q6_gpu, (rows, cols), out_dtype=torch.float16)
    for M in (1, 3):
        x = torch.randn((M, cols), device="cuda", dtype=torch.float16) * 0.05
        y_ref = x @ w_fp16_ref.T
        y_cu = q6_k_gemv_cuda(x, w_q6_gpu, cols, rows)
        err = float((y_ref - y_cu).abs().max().item())
        print(f"[test] q6_k_gemv M={M}: max_abs_diff={err:.6e}", flush=True)
        assert err < 2e-2

    # 4. Test SwitchGLU Q6_K (gate+up+swiglu + down GEMV)
    E, H, I = 16, 512, 256
    qg = torch.from_numpy(make_random_q6_k(rng, (E, I, H)).copy()).cuda()
    qu = torch.from_numpy(make_random_q6_k(rng, (E, I, H)).copy()).cuda()
    qd = torch.from_numpy(make_random_q6_k(rng, (E, H, I)).copy()).cuda()

    wg_d = dequantize_q6_k_cuda(qg, (E, I, H))
    wu_d = dequantize_q6_k_cuda(qu, (E, I, H))
    wd_d = dequantize_q6_k_cuda(qd, (E, H, I))

    M_tok, top_k = 2, 4
    x_moe = torch.randn((M_tok, H), device="cuda", dtype=torch.float16) * 0.05
    inds = torch.randint(0, E, (M_tok, top_k), device="cuda", dtype=torch.int32)
    act_cu = q6_k_switch_gate_up_swiglu_cuda(x_moe, inds, qg, qu, H, I, k_rep=top_k)
    out_cu = q6_k_switch_gemv_cuda(act_cu, inds, qd, I, H, k_rep=1, x_per_pair=True)

    out_ref = torch.empty_like(out_cu)
    for m in range(M_tok):
        for k in range(top_k):
            e = int(inds[m, k].item())
            gv = x_moe[m : m + 1] @ wg_d[e].T
            uv = x_moe[m : m + 1] @ wu_d[e].T
            av = (torch.nn.functional.silu(gv.float()) * uv.float()).to(torch.float16)
            out_ref[m, k] = (av @ wd_d[e].T)[0]
    err_moe = float((out_cu - out_ref).abs().max().item())
    print(f"[test] q6_k_switch_moe: max_abs_diff={err_moe:.6e}", flush=True)
    assert err_moe < 0.1

    # 5. Test KDA recurrent kernel against naive_recurrent_kda_torch
    B, T, nH, D = 1, 5, 16, 128
    q_t = torch.nn.functional.normalize(torch.randn((B, T, nH, D), device="cuda"), p=2, dim=-1) * (D ** -0.5)
    k_t = torch.nn.functional.normalize(torch.randn((B, T, nH, D), device="cuda"), p=2, dim=-1)
    v_t = torch.randn((B, T, nH, D), device="cuda") * 0.3
    g_t = -5.0 * torch.sigmoid(torch.randn((B, T, nH, D), device="cuda"))
    beta_t = torch.sigmoid(torch.randn((B, T, nH), device="cuda"))
    st0 = torch.randn((B, nH, D, D), device="cuda") * 0.05

    y_ref, st_ref = naive_recurrent_kda_torch(q_t, k_t, v_t, g_t, beta_t, initial_state=st0)
    st_cu = st0.clone()
    y_cu = kda_step_cuda(q_t, k_t, v_t, g_t, beta_t, st_cu)
    err_y = float((y_ref - y_cu).abs().max().item())
    err_s = float((st_ref - st_cu).abs().max().item())
    print(f"[test] kda_step_f32: y_diff={err_y:.6e} state_diff={err_s:.6e}", flush=True)
    assert err_y < 1e-5 and err_s < 1e-5
    print("[test] ALL LINGLOOP GGUF CUDA KERNEL TESTS PASSED!", flush=True)


if __name__ == "__main__":
    main()