AbstractPhil commited on
Commit
7693e8a
Β·
verified Β·
1 Parent(s): e794337

Create eigh_cuda_kernel.py

Browse files
Files changed (1) hide show
  1. eigh_cuda_kernel.py +397 -0
eigh_cuda_kernel.py ADDED
@@ -0,0 +1,397 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ fl_eigh_cuda.py β€” CUDA FL Hybrid Eigh via CuPy RawKernel.
3
+
4
+ Compiles at runtime using NVRTC (part of CUDA toolkit, already installed).
5
+ No ninja, no C++ compiler, no build system. Just pip install cupy-cuda12x.
6
+
7
+ PyTorch <-> CuPy via DLPack (zero-copy).
8
+
9
+ Usage:
10
+ from fl_eigh_cuda import fl_eigh_cuda
11
+ evals, evecs = fl_eigh_cuda(A) # A is [B, 6, 6] PyTorch CUDA tensor
12
+ """
13
+
14
+ import math, time, gc, sys
15
+ import torch
16
+ from torch import Tensor
17
+ from typing import Tuple
18
+
19
+ torch.backends.cuda.matmul.allow_tf32 = False
20
+ torch.backends.cudnn.allow_tf32 = False
21
+ torch.set_float32_matmul_precision('highest')
22
+
23
+
24
+ _KERNEL_SRC = r"""
25
+ extern "C" __global__
26
+ void fl_eigh_kernel(
27
+ const float* __restrict__ A_in,
28
+ float* __restrict__ evals_out,
29
+ float* __restrict__ evecs_out,
30
+ int B
31
+ ) {
32
+ int tid = blockIdx.x * blockDim.x + threadIdx.x;
33
+ if (tid >= B) return;
34
+
35
+ const int NN = 6;
36
+ const int N2 = 36;
37
+
38
+ // Load A and pre-scale
39
+ double a[36];
40
+ double frob_sq = 0.0;
41
+ for (int i = 0; i < N2; i++) {
42
+ a[i] = (double)A_in[tid * N2 + i];
43
+ frob_sq += a[i] * a[i];
44
+ }
45
+ double scale = sqrt(frob_sq / 6.0);
46
+ if (scale < 1e-12) scale = 1e-12;
47
+ double inv_s = 1.0 / scale;
48
+ for (int i = 0; i < N2; i++) a[i] *= inv_s;
49
+
50
+ // Phase 1: FL coefficients (fp64)
51
+ double c[7];
52
+ for (int i = 0; i < 7; i++) c[i] = 0.0;
53
+ c[6] = 1.0;
54
+
55
+ double m[36];
56
+ for (int i = 0; i < N2; i++) m[i] = 0.0;
57
+
58
+ for (int k = 1; k <= NN; k++) {
59
+ double mn[36];
60
+ for (int i = 0; i < NN; i++) {
61
+ for (int j = 0; j < NN; j++) {
62
+ double acc = 0.0;
63
+ for (int l = 0; l < NN; l++)
64
+ acc += a[i*NN+l] * m[l*NN+j];
65
+ if (i == j) acc += c[NN-k+1];
66
+ mn[i*NN+j] = acc;
67
+ }
68
+ }
69
+ double tr = 0.0;
70
+ for (int i = 0; i < NN; i++)
71
+ for (int l = 0; l < NN; l++)
72
+ tr += a[i*NN+l] * mn[l*NN+i];
73
+ c[NN-k] = -tr / (double)k;
74
+ for (int i = 0; i < N2; i++) m[i] = mn[i];
75
+ }
76
+
77
+ // Phase 2: Laguerre + deflation + polish (fp64)
78
+ double diag[6];
79
+ for (int i = 0; i < NN; i++) diag[i] = a[i*NN+i];
80
+ for (int pass = 0; pass < NN-1; pass++)
81
+ for (int j = 0; j < NN-1; j++)
82
+ if (diag[j] > diag[j+1]) {
83
+ double tmp = diag[j]; diag[j] = diag[j+1]; diag[j+1] = tmp;
84
+ }
85
+ for (int i = 0; i < NN; i++)
86
+ diag[i] += -1e-4 + 2e-4 * (double)i / 5.0;
87
+
88
+ double cl[7];
89
+ for (int i = 0; i < 7; i++) cl[i] = c[i];
90
+
91
+ double roots[6];
92
+
93
+ for (int ri = 0; ri < NN; ri++) {
94
+ int deg = NN - ri;
95
+ double z = diag[ri];
96
+ for (int lag = 0; lag < 5; lag++) {
97
+ double pv = cl[deg], dp = 0.0, d2 = 0.0;
98
+ for (int j = deg - 1; j >= 0; j--) {
99
+ d2 = d2 * z + dp;
100
+ dp = dp * z + pv;
101
+ pv = pv * z + cl[j];
102
+ }
103
+ if (fabs(pv) > 1e-30) {
104
+ double G = dp / pv;
105
+ double H = G * G - 2.0 * d2 / pv;
106
+ double disc = ((double)(deg-1)) * ((double)deg * H - G * G);
107
+ if (disc < 0.0) disc = 0.0;
108
+ double sq = sqrt(disc);
109
+ double gp = G + sq, gm = G - sq;
110
+ double den = (fabs(gp) >= fabs(gm)) ? gp : gm;
111
+ if (fabs(den) > 1e-20)
112
+ z -= (double)deg / den;
113
+ }
114
+ }
115
+ roots[ri] = z;
116
+ if (deg > 1) {
117
+ double b = cl[deg];
118
+ for (int j = deg - 1; j > 0; j--) {
119
+ double bn = cl[j] + z * b;
120
+ cl[j] = b;
121
+ b = bn;
122
+ }
123
+ cl[0] = b;
124
+ }
125
+ }
126
+
127
+ // Newton polish
128
+ for (int pol = 0; pol < 3; pol++)
129
+ for (int ri = 0; ri < NN; ri++) {
130
+ double pv = c[NN], dp = 0.0;
131
+ for (int j = NN - 1; j >= 0; j--) {
132
+ dp = dp * roots[ri] + pv;
133
+ pv = pv * roots[ri] + c[j];
134
+ }
135
+ if (fabs(dp) > 1e-30)
136
+ roots[ri] -= pv / dp;
137
+ }
138
+
139
+ // Phase 3: Eigenvectors via interleaved FL+Horner (fp64)
140
+ float evecs[36];
141
+
142
+ for (int ei = 0; ei < NN; ei++) {
143
+ double lam = roots[ei];
144
+ double m_loc[36], r_loc[36];
145
+ for (int i = 0; i < N2; i++) m_loc[i] = 0.0;
146
+
147
+ for (int k = 1; k <= NN; k++) {
148
+ double mn_loc[36];
149
+ for (int i = 0; i < NN; i++)
150
+ for (int j = 0; j < NN; j++) {
151
+ double acc = 0.0;
152
+ for (int l = 0; l < NN; l++)
153
+ acc += a[i*NN+l] * m_loc[l*NN+j];
154
+ if (i == j) acc += c[NN-k+1];
155
+ mn_loc[i*NN+j] = acc;
156
+ }
157
+ if (k == 1)
158
+ for (int i = 0; i < N2; i++) r_loc[i] = mn_loc[i];
159
+ else
160
+ for (int i = 0; i < N2; i++) r_loc[i] = r_loc[i] * lam + mn_loc[i];
161
+ for (int i = 0; i < N2; i++) m_loc[i] = mn_loc[i];
162
+ }
163
+
164
+ int best_j = 0;
165
+ double best_norm = -1.0;
166
+ for (int j = 0; j < NN; j++) {
167
+ double col_sq = 0.0;
168
+ for (int i = 0; i < NN; i++)
169
+ col_sq += r_loc[i*NN+j] * r_loc[i*NN+j];
170
+ if (col_sq > best_norm) { best_norm = col_sq; best_j = j; }
171
+ }
172
+ double vnorm = 0.0;
173
+ double vec[6];
174
+ for (int i = 0; i < NN; i++) {
175
+ vec[i] = r_loc[i*NN + best_j];
176
+ vnorm += vec[i] * vec[i];
177
+ }
178
+ vnorm = sqrt(vnorm) + 1e-30;
179
+ for (int i = 0; i < NN; i++)
180
+ evecs[i*NN + ei] = (float)(vec[i] / vnorm);
181
+ }
182
+
183
+ // Phase 4: Newton-Schulz (fp32, 2 iters)
184
+ for (int ns = 0; ns < 2; ns++) {
185
+ float y[36], t_m[36], vn[36];
186
+ for (int i = 0; i < NN; i++)
187
+ for (int j = 0; j < NN; j++) {
188
+ float acc = 0.0f;
189
+ for (int l = 0; l < NN; l++)
190
+ acc += evecs[l*NN+i] * evecs[l*NN+j];
191
+ y[i*NN+j] = acc;
192
+ }
193
+ for (int i = 0; i < NN; i++)
194
+ for (int j = 0; j < NN; j++)
195
+ t_m[i*NN+j] = ((i==j) ? 3.0f : 0.0f) - y[i*NN+j];
196
+ for (int i = 0; i < NN; i++)
197
+ for (int j = 0; j < NN; j++) {
198
+ float acc = 0.0f;
199
+ for (int l = 0; l < NN; l++)
200
+ acc += evecs[i*NN+l] * t_m[l*NN+j];
201
+ vn[i*NN+j] = 0.5f * acc;
202
+ }
203
+ for (int i = 0; i < N2; i++) evecs[i] = vn[i];
204
+ }
205
+
206
+ // Phase 5: Rayleigh quotient (fp32)
207
+ float af[36];
208
+ for (int i = 0; i < N2; i++) af[i] = (float)a[i];
209
+
210
+ float evals_local[6];
211
+ for (int ei = 0; ei < NN; ei++) {
212
+ float lam_f = 0.0f;
213
+ for (int l = 0; l < NN; l++) {
214
+ float av = 0.0f;
215
+ for (int mm = 0; mm < NN; mm++)
216
+ av += af[l*NN+mm] * evecs[mm*NN+ei];
217
+ lam_f += evecs[l*NN+ei] * av;
218
+ }
219
+ evals_local[ei] = lam_f * (float)scale;
220
+ }
221
+
222
+ // Sort ascending + permute
223
+ int perm[6];
224
+ for (int i = 0; i < NN; i++) perm[i] = i;
225
+ for (int pass = 0; pass < NN-1; pass++)
226
+ for (int j = 0; j < NN-1; j++)
227
+ if (evals_local[j] > evals_local[j+1]) {
228
+ float tmp = evals_local[j]; evals_local[j] = evals_local[j+1]; evals_local[j+1] = tmp;
229
+ int ptmp = perm[j]; perm[j] = perm[j+1]; perm[j+1] = ptmp;
230
+ }
231
+
232
+ for (int i = 0; i < NN; i++)
233
+ evals_out[tid * NN + i] = evals_local[i];
234
+ for (int j_out = 0; j_out < NN; j_out++) {
235
+ int j_src = perm[j_out];
236
+ for (int i = 0; i < NN; i++)
237
+ evecs_out[tid * N2 + i*NN + j_out] = evecs[i*NN + j_src];
238
+ }
239
+ }
240
+ """
241
+
242
+ # ═══════════════════════════════════════════════════════════════════════
243
+ # CuPy compilation + PyTorch wrapper
244
+ # ═══════════════════════════════════════════════════════════════════════
245
+
246
+ _kernel = None
247
+
248
+ def _get_kernel():
249
+ global _kernel
250
+ if _kernel is not None:
251
+ return _kernel
252
+ import cupy
253
+ print(" Compiling via NVRTC...", end=" ", flush=True)
254
+ _kernel = cupy.RawKernel(_KERNEL_SRC, 'fl_eigh_kernel')
255
+ # Force compilation now (not on first launch)
256
+ _kernel.compile()
257
+ print("done.")
258
+ return _kernel
259
+
260
+
261
+ def fl_eigh_cuda(A: Tensor) -> Tuple[Tensor, Tensor]:
262
+ """CUDA FL Hybrid Eigendecomposition for [B, 6, 6] symmetric matrices.
263
+
264
+ Uses CuPy RawKernel (NVRTC). Zero-copy PyTorch interop via data_ptr.
265
+ """
266
+ assert A.is_cuda and A.shape[-2:] == (6, 6), f"Need CUDA [B,6,6], got {A.shape}"
267
+ B = A.shape[0]
268
+ kernel = _get_kernel()
269
+
270
+ A_contig = A.contiguous().float()
271
+ evals = torch.empty(B, 6, device=A.device, dtype=torch.float32)
272
+ evecs = torch.empty(B, 6, 6, device=A.device, dtype=torch.float32)
273
+
274
+ import cupy
275
+ # Raw pointers β€” zero copy, no DLPack needed
276
+ a_ptr = cupy.cuda.MemoryPointer(
277
+ cupy.cuda.UnownedMemory(A_contig.data_ptr(), A_contig.nelement() * 4, None), 0)
278
+ ev_ptr = cupy.cuda.MemoryPointer(
279
+ cupy.cuda.UnownedMemory(evals.data_ptr(), evals.nelement() * 4, None), 0)
280
+ vc_ptr = cupy.cuda.MemoryPointer(
281
+ cupy.cuda.UnownedMemory(evecs.data_ptr(), evecs.nelement() * 4, None), 0)
282
+
283
+ threads = 128
284
+ blocks = (B + threads - 1) // threads
285
+
286
+ # Launch on PyTorch's current CUDA stream
287
+ stream = cupy.cuda.ExternalStream(torch.cuda.current_stream().cuda_stream)
288
+ with stream:
289
+ kernel((blocks,), (threads,),
290
+ (a_ptr, ev_ptr, vc_ptr, B))
291
+
292
+ return evals, evecs
293
+
294
+
295
+ # ═══════════════════════════════════════════════════════════════════════
296
+ # Math purity test
297
+ # ═══════════════════════════════════════════════════════════════════════
298
+
299
+ def math_test(A, vals, vecs):
300
+ B,n,_=A.shape; dev=A.device
301
+ Ad=A.double(); vd=vals.double(); Vd=vecs.double()
302
+ AV=torch.bmm(Ad,Vd); VL=Vd*vd.unsqueeze(-2)
303
+ An=Ad.reshape(B,-1).norm(dim=-1,keepdim=True).clamp(min=1e-30)
304
+ res=(AV-VL).norm(dim=-2)/An
305
+ VtV=torch.bmm(Vd.mT,Vd); I=torch.eye(n,device=dev,dtype=torch.float64).unsqueeze(0)
306
+ orth=(VtV-I).reshape(B,-1).norm(dim=-1)
307
+ recon=torch.bmm(Vd*vd.unsqueeze(-2),Vd.mT)
308
+ recon_err=(Ad-recon).reshape(B,-1).norm(dim=-1)/An.squeeze(-1)
309
+ tr_err=(Ad.diagonal(dim1=-2,dim2=-1).sum(-1)-vd.sum(-1)).abs()
310
+ det_A=torch.linalg.det(Ad); det_err=(det_A-vd.prod(-1)).abs()/det_A.abs().clamp(min=1e-30)
311
+ return dict(res_max=res.max().item(), res_mean=res.mean().item(),
312
+ orth_max=orth.max().item(), orth_mean=orth.mean().item(),
313
+ recon_max=recon_err.max().item(), recon_mean=recon_err.mean().item(),
314
+ tr_max=tr_err.max().item(), det_max=det_err.max().item())
315
+
316
+
317
+ # ═══════════════════════════════════════════════════════════════════════
318
+ # Benchmark
319
+ # ═══════════════════════════════════════════════════════════════════════
320
+
321
+ def sync(): torch.cuda.synchronize()
322
+ def gt(fn,w=20,r=200):
323
+ for _ in range(w): fn()
324
+ sync(); t=time.perf_counter()
325
+ for _ in range(r): fn()
326
+ sync(); return (time.perf_counter()-t)/r
327
+ def fmt(s):
328
+ if s<1e-3: return f"{s*1e6:.1f}us"
329
+ if s<1: return f"{s*1e3:.2f}ms"
330
+ return f"{s:.3f}s"
331
+
332
+
333
+ def main():
334
+ if not torch.cuda.is_available(): sys.exit(1)
335
+ dev=torch.device('cuda')
336
+ p=torch.cuda.get_device_properties(0)
337
+ print("="*72)
338
+ print(" FL Eigh CUDA Kernel (CuPy/NVRTC)")
339
+ print("="*72)
340
+ print(f" {p.name}")
341
+ print(f" PyTorch {torch.__version__}")
342
+
343
+ N=6; B=4096
344
+ A=(lambda R:(R+R.mT)/2)(torch.randn(B,N,N,device=dev))
345
+ rv,rV=torch.linalg.eigh(A)
346
+
347
+ _get_kernel()
348
+
349
+ # Accuracy
350
+ print(f"\n ACCURACY (n={N} B={B})")
351
+ cv,cV=fl_eigh_cuda(A)
352
+ ve=(cv-rv).abs().max().item()
353
+ dots=torch.bmm(rV.double().mT,cV.double()).abs().max(dim=-1).values.min().item()
354
+ print(f" CUDA FL: val={ve:.1e} align={dots:.6f}")
355
+
356
+ # Math purity
357
+ mc=math_test(A,rv,rV); mf=math_test(A,cv,cV)
358
+ wins=0
359
+ print(f"\n MATH PURITY: CUDA FL vs cuSOLVER")
360
+ print(f" {'Property':<28} {'cuSOLVER':>10} {'CUDA FL':>10} {'Win':>6}")
361
+ for key in ['res_max','res_mean','orth_max','orth_mean','recon_max','recon_mean','tr_max','det_max']:
362
+ vc=mc[key]; vf=mf[key]; w='FL' if vf<vc else 'cuS'
363
+ if vf<vc: wins+=1
364
+ print(f" {key:<28} {vc:>10.1e} {vf:>10.1e} {w:>6}")
365
+ print(f"\n CUDA FL wins {wins}/8")
366
+
367
+ # Throughput
368
+ print(f"\n THROUGHPUT (n={N} B={B})")
369
+ tr=gt(lambda:torch.linalg.eigh(A))
370
+ tc=gt(lambda:fl_eigh_cuda(A))
371
+ print(f" cuSOLVER: {fmt(tr)}")
372
+ print(f" CUDA FL: {fmt(tc)} ({tr/tc:.2f}x)")
373
+
374
+ # Batch scaling
375
+ print(f"\n BATCH SCALING (n={N})")
376
+ print(f" {'B':>6} {'cuSOLVER':>10} {'CUDA FL':>10} {'ratio':>7}")
377
+ for Bx in [256,512,1024,2048,4096,8192,16384,32768]:
378
+ try:
379
+ Ax=(lambda R:(R+R.mT)/2)(torch.randn(Bx,N,N,device=dev))
380
+ t1=gt(lambda:torch.linalg.eigh(Ax),10,100)
381
+ t2=gt(lambda:fl_eigh_cuda(Ax),10,100)
382
+ print(f" {Bx:>6} {fmt(t1):>10} {fmt(t2):>10} {t1/t2:>6.2f}x")
383
+ del Ax
384
+ except RuntimeError:
385
+ print(f" {Bx:>6} OOM"); torch.cuda.empty_cache()
386
+
387
+ # Memory
388
+ print(f"\n MEMORY (n={N} B={B})")
389
+ for lbl,fn in [("cuSOLVER",lambda:torch.linalg.eigh(A)),("CUDA FL",lambda:fl_eigh_cuda(A))]:
390
+ torch.cuda.empty_cache(); gc.collect(); torch.cuda.reset_peak_memory_stats()
391
+ base=torch.cuda.memory_allocated(); fn(); sync()
392
+ print(f" {lbl:<12} {(torch.cuda.max_memory_allocated()-base)/1024**2:.1f}MB")
393
+
394
+ print("="*72)
395
+
396
+
397
+ if __name__=='__main__': main()