|
| 1 | +"""Single-head attention (12 kernel launches) -- verified against NumPy. |
| 2 | +
|
| 3 | +Run: PYTHONPATH="build/bindings:python" python3 examples/attention_test.py |
| 4 | +""" |
| 5 | + |
| 6 | +import numpy as np |
| 7 | +import tiny_ton as tt |
| 8 | + |
| 9 | + |
| 10 | +# --- linear / matvec kernel (same kernel, different grid) ------------------- |
| 11 | + |
| 12 | +@tt.jit |
| 13 | +def linear_kernel(W_ptr, x_ptr, y_ptr, in_features): |
| 14 | + pid = tt.program_id(0) |
| 15 | + tid = tt.arange(0, 64) |
| 16 | + mask = tid < in_features |
| 17 | + w = tt.load(W_ptr + pid * in_features + tid, mask=mask) |
| 18 | + x = tt.load(x_ptr + tid, mask=mask) |
| 19 | + dot = tt.reduce_sum(w * x) |
| 20 | + tt.store(y_ptr + pid, dot) |
| 21 | + |
| 22 | + |
| 23 | +matvec_kernel = linear_kernel |
| 24 | + |
| 25 | + |
| 26 | +# --- softmax kernels (reused from softmax_test) ----------------------------- |
| 27 | + |
| 28 | +@tt.jit |
| 29 | +def kern_reduce_max(src, dst, N): |
| 30 | + pid = tt.program_id(0) |
| 31 | + off = pid * 64 + tt.arange(0, 64) |
| 32 | + mask = off < N |
| 33 | + x = tt.load(src + off, mask=mask) |
| 34 | + mx = tt.reduce_max(x) |
| 35 | + tt.store(dst + pid, mx) |
| 36 | + |
| 37 | + |
| 38 | +@tt.jit |
| 39 | +def kern_sub_scalar(src, scalar_ptr, dst, N): |
| 40 | + pid = tt.program_id(0) |
| 41 | + off = pid * 64 + tt.arange(0, 64) |
| 42 | + mask = off < N |
| 43 | + x = tt.load(src + off, mask=mask) |
| 44 | + s = tt.load(scalar_ptr) |
| 45 | + tt.store(dst + off, x - s, mask=mask) |
| 46 | + |
| 47 | + |
| 48 | +@tt.jit |
| 49 | +def kern_exp(src, dst, N): |
| 50 | + pid = tt.program_id(0) |
| 51 | + off = pid * 64 + tt.arange(0, 64) |
| 52 | + mask = off < N |
| 53 | + x = tt.load(src + off, mask=mask) |
| 54 | + tt.store(dst + off, tt.exp(x), mask=mask) |
| 55 | + |
| 56 | + |
| 57 | +@tt.jit |
| 58 | +def kern_reduce_sum(src, dst, N): |
| 59 | + pid = tt.program_id(0) |
| 60 | + off = pid * 64 + tt.arange(0, 64) |
| 61 | + mask = off < N |
| 62 | + x = tt.load(src + off, mask=mask) |
| 63 | + total = tt.reduce_sum(x) |
| 64 | + tt.store(dst + pid, total) |
| 65 | + |
| 66 | + |
| 67 | +@tt.jit |
| 68 | +def kern_div_scalar(src, scalar_ptr, dst, N): |
| 69 | + pid = tt.program_id(0) |
| 70 | + off = pid * 64 + tt.arange(0, 64) |
| 71 | + mask = off < N |
| 72 | + x = tt.load(src + off, mask=mask) |
| 73 | + s = tt.load(scalar_ptr) |
| 74 | + tt.store(dst + off, x / s, mask=mask) |
| 75 | + |
| 76 | + |
| 77 | +def softmax(x, out, N): |
| 78 | + """Host-side softmax: 5 kernel launches.""" |
| 79 | + grid = (max(1, (N + 63) // 64),) |
| 80 | + tmp_max = np.zeros(1, dtype=x.dtype) |
| 81 | + tmp_exp = np.zeros(N, dtype=x.dtype) |
| 82 | + tmp_sum = np.zeros(1, dtype=x.dtype) |
| 83 | + |
| 84 | + kern_reduce_max[(1,)](x, tmp_max, N) |
| 85 | + kern_sub_scalar[grid](x, tmp_max, tmp_exp, N) |
| 86 | + kern_exp[grid](tmp_exp, tmp_exp, N) |
| 87 | + kern_reduce_sum[(1,)](tmp_exp, tmp_sum, N) |
| 88 | + kern_div_scalar[grid](tmp_exp, tmp_sum, out, N) |
| 89 | + |
| 90 | + |
| 91 | +# --- attention orchestrator (12 launches) ----------------------------------- |
| 92 | + |
| 93 | +def attention(x, Wq, Wk, Wv, Wo, K_cache, V_cache, n_embd): |
| 94 | + """Single-head scaled dot-product attention with Q/K/V/O projections.""" |
| 95 | + q = np.zeros(n_embd, dtype=np.float32) |
| 96 | + k = np.zeros(n_embd, dtype=np.float32) |
| 97 | + v = np.zeros(n_embd, dtype=np.float32) |
| 98 | + |
| 99 | + linear_kernel[(n_embd,)](Wq, x, q, n_embd) |
| 100 | + linear_kernel[(n_embd,)](Wk, x, k, n_embd) |
| 101 | + linear_kernel[(n_embd,)](Wv, x, v, n_embd) |
| 102 | + |
| 103 | + K_cache.append(k.copy()) |
| 104 | + V_cache.append(v.copy()) |
| 105 | + K = np.ascontiguousarray(np.vstack(K_cache)) |
| 106 | + V = np.vstack(V_cache) |
| 107 | + seq_len = len(K_cache) |
| 108 | + |
| 109 | + scores = np.zeros(seq_len, dtype=np.float32) |
| 110 | + matvec_kernel[(seq_len,)](K.flatten(), q, scores, n_embd) |
| 111 | + |
| 112 | + sqrt_d = np.array([np.sqrt(float(n_embd))], dtype=np.float32) |
| 113 | + scores_scaled = np.zeros(seq_len, dtype=np.float32) |
| 114 | + kern_div_scalar[(1,)](scores, sqrt_d, scores_scaled, seq_len) |
| 115 | + |
| 116 | + weights = np.zeros(seq_len, dtype=np.float32) |
| 117 | + softmax(scores_scaled, weights, seq_len) |
| 118 | + |
| 119 | + V_T = np.ascontiguousarray(V.T) |
| 120 | + attn_out = np.zeros(n_embd, dtype=np.float32) |
| 121 | + matvec_kernel[(n_embd,)](V_T.flatten(), weights, attn_out, seq_len) |
| 122 | + |
| 123 | + output = np.zeros(n_embd, dtype=np.float32) |
| 124 | + linear_kernel[(n_embd,)](Wo, attn_out, output, n_embd) |
| 125 | + return output |
| 126 | + |
| 127 | + |
| 128 | +# --- NumPy reference -------------------------------------------------------- |
| 129 | + |
| 130 | +def attention_numpy(x, Wq, Wk, Wv, Wo, K_cache, V_cache, n_embd): |
| 131 | + """NumPy reference for single-head attention.""" |
| 132 | + q = Wq @ x |
| 133 | + k = Wk @ x |
| 134 | + v = Wv @ x |
| 135 | + |
| 136 | + K_cache.append(k.copy()) |
| 137 | + V_cache.append(v.copy()) |
| 138 | + K = np.vstack(K_cache) |
| 139 | + V = np.vstack(V_cache) |
| 140 | + |
| 141 | + scores = K @ q / np.sqrt(float(n_embd)) |
| 142 | + shifted = scores - np.max(scores) |
| 143 | + w = np.exp(shifted) / np.sum(np.exp(shifted)) |
| 144 | + attn_out = V.T @ w |
| 145 | + return Wo @ attn_out |
| 146 | + |
| 147 | + |
| 148 | +# --- test ------------------------------------------------------------------- |
| 149 | + |
| 150 | +def main(): |
| 151 | + np.random.seed(42) |
| 152 | + n_embd = 16 |
| 153 | + n_tokens = 4 |
| 154 | + |
| 155 | + Wq = np.random.randn(n_embd, n_embd).astype(np.float32) * 0.1 |
| 156 | + Wk = np.random.randn(n_embd, n_embd).astype(np.float32) * 0.1 |
| 157 | + Wv = np.random.randn(n_embd, n_embd).astype(np.float32) * 0.1 |
| 158 | + Wo = np.random.randn(n_embd, n_embd).astype(np.float32) * 0.1 |
| 159 | + |
| 160 | + tokens = [np.random.randn(n_embd).astype(np.float32) for _ in range(n_tokens)] |
| 161 | + |
| 162 | + K_gpu, V_gpu = [], [] |
| 163 | + K_ref, V_ref = [], [] |
| 164 | + |
| 165 | + all_ok = True |
| 166 | + for t in range(n_tokens): |
| 167 | + x = tokens[t] |
| 168 | + gpu_out = attention(x.copy(), |
| 169 | + Wq.flatten().copy(), Wk.flatten().copy(), |
| 170 | + Wv.flatten().copy(), Wo.flatten().copy(), |
| 171 | + K_gpu, V_gpu, n_embd) |
| 172 | + ref_out = attention_numpy(x.copy(), Wq, Wk, Wv, Wo, |
| 173 | + K_ref, V_ref, n_embd) |
| 174 | + |
| 175 | + ok = np.allclose(gpu_out, ref_out, atol=1e-3) |
| 176 | + print(f"attention pos={t} (seq_len={t+1}): {'PASS' if ok else 'FAIL'}") |
| 177 | + if not ok: |
| 178 | + for i in range(n_embd): |
| 179 | + print(f" [{i}] got={gpu_out[i]:.6f} expected={ref_out[i]:.6f}") |
| 180 | + all_ok = False |
| 181 | + |
| 182 | + assert all_ok, "attention test failed" |
| 183 | + print("All attention tests passed.") |
| 184 | + |
| 185 | + |
| 186 | +if __name__ == "__main__": |
| 187 | + main() |
0 commit comments