DongyunZou commited on
Commit
64e9f97
·
verified ·
1 Parent(s): 56c2c8d

Thread-safe first calls, prepared launches on other streams, first calls in graph capture, fp64 32-bit limits

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +1 -0
  2. README.md +43 -6
  3. build/torch-cuda/__pycache__/__init__.cpython-312.pyc +0 -0
  4. build/torch-cuda/__pycache__/_build.cpython-312.pyc +0 -0
  5. build/torch-cuda/_build.py +87 -0
  6. build/torch-cuda/_c2r_f32/__pycache__/__init__.cpython-312.pyc +0 -0
  7. build/torch-cuda/_c2r_f32/__pycache__/anyfft.cpython-312.pyc +0 -0
  8. build/torch-cuda/_c2r_f32/__pycache__/fftgen.cpython-312.pyc +0 -0
  9. build/torch-cuda/_c2r_f32/__pycache__/inplace.cpython-312.pyc +0 -0
  10. build/torch-cuda/_c2r_f32/__pycache__/kernel.cpython-312.pyc +0 -0
  11. build/torch-cuda/_c2r_f32/__pycache__/tables.cpython-312.pyc +0 -0
  12. build/torch-cuda/_c2r_f32/__pycache__/twopass.cpython-312.pyc +0 -0
  13. build/torch-cuda/_c2r_f32/anyfft.py +10 -6
  14. build/torch-cuda/_c2r_f32/kernel.py +19 -9
  15. build/torch-cuda/_c2r_f64/__pycache__/__init__.cpython-312.pyc +0 -0
  16. build/torch-cuda/_c2r_f64/__pycache__/bigprime.cpython-312.pyc +0 -0
  17. build/torch-cuda/_c2r_f64/__pycache__/fftgen.cpython-312.pyc +0 -0
  18. build/torch-cuda/_c2r_f64/__pycache__/kernel.cpython-312.pyc +3 -0
  19. build/torch-cuda/_c2r_f64/__pycache__/softfp.cpython-312.pyc +0 -0
  20. build/torch-cuda/_c2r_f64/__pycache__/twiddles.cpython-312.pyc +0 -0
  21. build/torch-cuda/_c2r_f64/bigprime.py +15 -1
  22. build/torch-cuda/_c2r_f64/kernel.py +84 -10
  23. build/torch-cuda/_r2c_f32/__pycache__/__init__.cpython-312.pyc +0 -0
  24. build/torch-cuda/_r2c_f32/__pycache__/fft3k.cpython-312.pyc +0 -0
  25. build/torch-cuda/_r2c_f32/__pycache__/fft_core.cpython-312.pyc +0 -0
  26. build/torch-cuda/_r2c_f32/__pycache__/fft_gen.cpython-312.pyc +0 -0
  27. build/torch-cuda/_r2c_f32/__pycache__/fft_generic.cpython-312.pyc +0 -0
  28. build/torch-cuda/_r2c_f32/__pycache__/fft_plane2.cpython-312.pyc +0 -0
  29. build/torch-cuda/_r2c_f32/__pycache__/fft_xy.cpython-312.pyc +0 -0
  30. build/torch-cuda/_r2c_f32/__pycache__/fft_ys1w.cpython-312.pyc +0 -0
  31. build/torch-cuda/_r2c_f32/__pycache__/fft_ysplit.cpython-312.pyc +0 -0
  32. build/torch-cuda/_r2c_f32/__pycache__/kernel.cpython-312.pyc +0 -0
  33. build/torch-cuda/_r2c_f32/__pycache__/plan.cpython-312.pyc +0 -0
  34. build/torch-cuda/_r2c_f32/__pycache__/ptx.cpython-312.pyc +0 -0
  35. build/torch-cuda/_r2c_f32/__pycache__/stockham.cpython-312.pyc +0 -0
  36. build/torch-cuda/_r2c_f32/fft_gen.py +12 -12
  37. build/torch-cuda/_r2c_f32/kernel.py +39 -19
  38. build/torch-cuda/_r2c_f32/plan.py +4 -2
  39. build/torch-cuda/_r2c_f64/__pycache__/__init__.cpython-312.pyc +0 -0
  40. build/torch-cuda/_r2c_f64/__pycache__/bigprime.cpython-312.pyc +0 -0
  41. build/torch-cuda/_r2c_f64/__pycache__/dsl_ops.cpython-312.pyc +0 -0
  42. build/torch-cuda/_r2c_f64/__pycache__/fft_codelets.cpython-312.pyc +0 -0
  43. build/torch-cuda/_r2c_f64/__pycache__/fft_direct.cpython-312.pyc +0 -0
  44. build/torch-cuda/_r2c_f64/__pycache__/fft_passes.cpython-312.pyc +0 -0
  45. build/torch-cuda/_r2c_f64/__pycache__/fft_plan.cpython-312.pyc +0 -0
  46. build/torch-cuda/_r2c_f64/__pycache__/fft_stages.cpython-312.pyc +0 -0
  47. build/torch-cuda/_r2c_f64/__pycache__/fftgen.cpython-312.pyc +0 -0
  48. build/torch-cuda/_r2c_f64/__pycache__/kernel.cpython-312.pyc +0 -0
  49. build/torch-cuda/_r2c_f64/__pycache__/planner.cpython-312.pyc +0 -0
  50. build/torch-cuda/_r2c_f64/__pycache__/tuned.cpython-312.pyc +0 -0
.gitattributes CHANGED
@@ -1,3 +1,4 @@
1
  *.so filter=lfs diff=lfs merge=lfs -text
2
  *.pyd filter=lfs diff=lfs merge=lfs -text
3
  *.dylib filter=lfs diff=lfs merge=lfs -text
 
 
1
  *.so filter=lfs diff=lfs merge=lfs -text
2
  *.pyd filter=lfs diff=lfs merge=lfs -text
3
  *.dylib filter=lfs diff=lfs merge=lfs -text
4
+ build/torch-cuda/_c2r_f64/__pycache__/kernel.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
README.md CHANGED
@@ -62,17 +62,23 @@ spectrum = launch() # ...then transform its current contents
62
  `launch()`, which transforms the buffer's current contents into one output
63
  tensor that it reuses on every call. Calls of one `launch` must be ordered
64
  (one stream). Keep `launch` alive as long as a CUDA graph captured from it.
65
- fp64 r2c has no two-phase form; its `launch()` calls `r2c(x)`.
 
 
 
66
  - Calls on different CUDA streams may run concurrently, including calls of the
67
- same shape.
 
 
 
68
  - A call costs about 13 to 17 us of host time (TVM-FFI launches on the current
69
  stream). Timed per call as the requests' benchmark does (flashinfer-bench:
70
  synchronize, event, call, event), every kernel is faster than `torch.fft` on
71
  every grid tried, the smallest included (see Performance).
72
  - The first call for a new shape compiles its kernels (CuTe DSL JIT), typically
73
  in 1 to 15 s, up to about 4 minutes for a very long z axis over a tiny y-x
74
- plane (such as 4096x8x16). Make that first call outside CUDA graph capture;
75
- later calls can be captured.
76
  - `c2r` expects a Hermitian-consistent half-spectrum, such as the output of
77
  `r2c` or Fourier-space data that keeps its symmetry. On other input the result
78
  depends on the order of the 1D passes, as with cuFFT; these kernels then
@@ -85,7 +91,9 @@ spectrum = launch() # ...then transform its current contents
85
  above 13 (fp64, such as 289) still take slow generic kernels. fp64 r2c raises
86
  `NotImplementedError` when a y or z axis needs a direct DFT longer than 6336
87
  points; fp64 c2r raises it for nz from 1280 to 4096, ny from 3072 to 4096 or
88
- nx / 2 from 3072 to 4096.
 
 
89
 
90
  ## Accuracy
91
 
@@ -236,6 +244,34 @@ two-stream checks):
236
 
237
  The eight grids keep their plans and their outputs are bitwise unchanged.
238
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
239
  ## Source and licensing
240
 
241
  Written by Claude Opus 5.5 in four 12-hour runs of KDA (kernel design agents),
@@ -244,7 +280,8 @@ built from the requests in [NVlabs/kda#7](https://github.com/NVlabs/kda/pull/7),
244
  and accepted by the KDA judge. Published from commit `e539498` of
245
  `humanfia/kda-kernels-internal`, directory `rtx5090/fft3d/` (now
246
  `sm120/fft3d/`), which also holds its tests and the fixes made after the
247
- judge's checks; updated from commit `b0811f8` (see [Changes](#changes)).
 
248
  MIT-licensed.
249
 
250
  ## Available functions
 
62
  `launch()`, which transforms the buffer's current contents into one output
63
  tensor that it reuses on every call. Calls of one `launch` must be ordered
64
  (one stream). Keep `launch` alive as long as a CUDA graph captured from it.
65
+ fp64 r2c has no two-phase form; its `launch()` calls `r2c(x)`. A `launch()`
66
+ on another stream than the one `prepare_*` ran on waits for `prepare_*`'s
67
+ work and keeps its output and workspaces reserved for that stream's work,
68
+ even if the launch object is dropped before the work ran.
69
  - Calls on different CUDA streams may run concurrently, including calls of the
70
+ same shape. Calls may also come from several threads: CuTe DSL is not
71
+ thread-safe while it compiles or makes the first call of a compiled function,
72
+ so a new shape's plan is built, and makes its first call, under a lock that
73
+ all kda kernels share (later calls take no lock).
74
  - A call costs about 13 to 17 us of host time (TVM-FFI launches on the current
75
  stream). Timed per call as the requests' benchmark does (flashinfer-bench:
76
  synchronize, event, call, event), every kernel is faster than `torch.fft` on
77
  every grid tried, the smallest included (see Performance).
78
  - The first call for a new shape compiles its kernels (CuTe DSL JIT), typically
79
  in 1 to 15 s, up to about 4 minutes for a very long z axis over a tiny y-x
80
+ plane (such as 4096x8x16). That first call may itself be inside CUDA graph
81
+ capture.
82
  - `c2r` expects a Hermitian-consistent half-spectrum, such as the output of
83
  `r2c` or Fourier-space data that keeps its symmetry. On other input the result
84
  depends on the order of the 1D passes, as with cuFFT; these kernels then
 
91
  above 13 (fp64, such as 289) still take slow generic kernels. fp64 r2c raises
92
  `NotImplementedError` when a y or z axis needs a direct DFT longer than 6336
93
  points; fp64 c2r raises it for nz from 1280 to 4096, ny from 3072 to 4096 or
94
+ nx / 2 from 3072 to 4096. The fp64 kernels address with 32-bit offsets: fp64
95
+ r2c raises `ValueError` past 2^30 complex outputs and fp64 c2r on 2^31 or more
96
+ half-spectrum elements.
97
 
98
  ## Accuracy
99
 
 
244
 
245
  The eight grids keep their plans and their outputs are bitwise unchanged.
246
 
247
+ Updated on 2026-10-27 with the fixes of a second audit on RTX 5090s and B300s
248
+ (threads, streams, CUDA graph capture, 32-bit limits; no wrong result was found
249
+ within 256 per axis):
250
+
251
+ - Threads making first calls at once failed: CuTe DSL is not thread-safe while
252
+ it compiles or makes the first call of a TVM-FFI function. Concurrent plan
253
+ builds raised MLIR errors or ended the process, and two first calls of one
254
+ shape at once left a spin lock held, so that the next first call of any
255
+ kernel in the process hung for good. Plans are now built, and make their first
256
+ call, under one process-wide lock; later calls take none.
257
+ - The first call of a shape inside CUDA graph capture raised; its tables are
258
+ now copied on a stream of the package's own, outside the graph.
259
+ - A `launch()` right after `prepare_*` on another stream could run before work
260
+ still queued on `prepare_*`'s stream, which then overwrote its output, and a
261
+ launch object dropped before its kernels ran handed its buffers to new tensors
262
+ on `prepare_*`'s stream. Such a launch now waits for `prepare_*`'s stream and
263
+ keeps its buffers until its work is done; same-stream launches are unchanged.
264
+ - fp32 r2c transforms a contiguous input that is not 16-byte aligned from an
265
+ aligned copy instead of raising.
266
+ - fp64 r2c past 2^30 complex outputs (an illegal memory access) and fp64 c2r
267
+ on 2^31 or more half-spectrum elements (a wrong result) now raise
268
+ `ValueError`, beyond 256 per axis.
269
+ - fp64 axes of 1529 points and more whose big-prime tile does not fit in
270
+ shared memory failed to compile (such as 8x6329x16); they keep the direct
271
+ DFT.
272
+
273
+ The eight grids keep their plans; their outputs and speeds are unchanged.
274
+
275
  ## Source and licensing
276
 
277
  Written by Claude Opus 5.5 in four 12-hour runs of KDA (kernel design agents),
 
280
  and accepted by the KDA judge. Published from commit `e539498` of
281
  `humanfia/kda-kernels-internal`, directory `rtx5090/fft3d/` (now
282
  `sm120/fft3d/`), which also holds its tests and the fixes made after the
283
+ judge's checks; updated from commits `b0811f8` and `2238a9e` (see
284
+ [Changes](#changes)).
285
  MIT-licensed.
286
 
287
  ## Available functions
build/torch-cuda/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (4.67 kB). View file
 
build/torch-cuda/__pycache__/_build.cpython-312.pyc ADDED
Binary file (6.01 kB). View file
 
build/torch-cuda/_build.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Plan building for the fp32 kernel packages: under the CuTe lock all kda kernels share, and outside CUDA
2
+ graph capture."""
3
+
4
+ import contextlib
5
+ import threading
6
+
7
+ import cuda.bindings.driver as cuda
8
+ import cutlass
9
+ import torch
10
+
11
+ # CuTe DSL is not thread-safe while it compiles (also across packages) or, for --enable-tvm-ffi
12
+ # functions, while a function is first called: every kda kernel package shares this lock.
13
+ # (Concurrent compiles fail with MLIR errors or end the process; two first calls of one function at once
14
+ # leave a process-wide spin lock held, so the next first call of any CuTe function spins forever.)
15
+ # The fp32 packages build their plans, and make each plan's first call, under it; later calls take no lock.
16
+ _CUTE_LOCK = cutlass.__dict__.setdefault("_kda_compile_lock", threading.RLock())
17
+ _SIDE = {} # device -> the private side stream plans are built on during a capture
18
+
19
+
20
+ def _private_stream(device):
21
+ """A stream of this module's own (cuStreamCreate, non-blocking), one per device. torch.cuda.Stream() hands out
22
+ one of a pool of 32 streams per device, which can be the very stream being captured (or another thread's)."""
23
+ side = _SIDE.get(device)
24
+ if side is None:
25
+ with torch.cuda.device(device):
26
+ err, h = cuda.cuStreamCreate(cuda.CUstream_flags.CU_STREAM_NON_BLOCKING.value)
27
+ if err != cuda.CUresult.CUDA_SUCCESS:
28
+ raise RuntimeError(f"cuStreamCreate failed: {err}")
29
+ side = _SIDE.setdefault(device, torch.cuda.ExternalStream(int(h), device=device))
30
+ return side
31
+
32
+
33
+ @contextlib.contextmanager
34
+ def building(device):
35
+ """Hold _CUTE_LOCK while a plan is built. If the current stream is being captured into a CUDA graph (the
36
+ first call of a shape inside capture), the plan's tables are copied to the GPU now, on a side stream
37
+ with this thread in relaxed capture mode: they are filled before the first replay and stay valid
38
+ for eager calls (torch refuses pageable copies on a capturing stream)."""
39
+ with _CUTE_LOCK:
40
+ if not torch.cuda.is_current_stream_capturing():
41
+ yield
42
+ return
43
+ err, mode = cuda.cuThreadExchangeStreamCaptureMode(cuda.CUstreamCaptureMode.CU_STREAM_CAPTURE_MODE_RELAXED)
44
+ if err != cuda.CUresult.CUDA_SUCCESS:
45
+ raise RuntimeError(f"fft3d: cuThreadExchangeStreamCaptureMode failed: {err}")
46
+ try:
47
+ side = _private_stream(torch.device(device))
48
+ with torch.cuda.stream(side):
49
+ yield
50
+ side.synchronize()
51
+ finally:
52
+ cuda.cuThreadExchangeStreamCaptureMode(mode)
53
+
54
+
55
+ def first_call(plan, fn, *args):
56
+ """fn(*args), the first call of `plan`'s compiled functions, under _CUTE_LOCK; then marks the plan ready."""
57
+ with _CUTE_LOCK:
58
+ fn(*args)
59
+ plan.ready = True
60
+
61
+
62
+ def stream_guard(device):
63
+ """For a launch object made by prepare(), made with no GPU work queued since prepare allocated its buffers:
64
+ guard(*buffers) at
65
+ each launch. The buffers come from the memory pool of the stream prepare ran on, so on another stream it
66
+ first waits until the work queued there before prepare has finished with that memory, then marks the
67
+ launch object's own buffers (output, workspaces) as used by its stream, so that dropping the launch
68
+ object before its kernels ran cannot hand their memory to a new allocation on prepare's stream while the
69
+ kernels still use it. (A capture cannot wait for outside work; torch.cuda.graph synchronizes before
70
+ capturing.) One integer compare on prepare's stream."""
71
+ index = device.index
72
+ home = torch._C._cuda_getCurrentRawStream(index)
73
+ ready = None
74
+ if not torch.cuda.is_current_stream_capturing():
75
+ ready = torch.cuda.Event()
76
+ ready.record(torch.cuda.current_stream(index))
77
+
78
+ def guard(*buffers):
79
+ if torch._C._cuda_getCurrentRawStream(index) != home:
80
+ stream = torch.cuda.current_stream(index)
81
+ if ready is not None and not torch.cuda.is_current_stream_capturing():
82
+ stream.wait_event(ready)
83
+ for b in buffers:
84
+ if b is not None:
85
+ b.record_stream(stream)
86
+
87
+ return guard
build/torch-cuda/_c2r_f32/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (473 Bytes). View file
 
build/torch-cuda/_c2r_f32/__pycache__/anyfft.cpython-312.pyc ADDED
Binary file (61.4 kB). View file
 
build/torch-cuda/_c2r_f32/__pycache__/fftgen.cpython-312.pyc ADDED
Binary file (12.3 kB). View file
 
build/torch-cuda/_c2r_f32/__pycache__/inplace.cpython-312.pyc ADDED
Binary file (39.4 kB). View file
 
build/torch-cuda/_c2r_f32/__pycache__/kernel.cpython-312.pyc ADDED
Binary file (19.8 kB). View file
 
build/torch-cuda/_c2r_f32/__pycache__/tables.cpython-312.pyc ADDED
Binary file (2.5 kB). View file
 
build/torch-cuda/_c2r_f32/__pycache__/twopass.cpython-312.pyc ADDED
Binary file (68.3 kB). View file
 
build/torch-cuda/_c2r_f32/anyfft.py CHANGED
@@ -25,7 +25,7 @@ import math
25
 
26
  import cutlass
27
  import torch
28
- from cutlass import Float32, Int32, cute
29
 
30
  from .fftgen import cmul, dft, ld_c, st_c
31
 
@@ -374,7 +374,6 @@ def _col_nl(N, cap=None):
374
  if cap is not None:
375
  while NL > 8 and NL // 2 >= cap:
376
  NL //= 2
377
- plan = line_plan(N)
378
  nbuf = 1
379
  while NL >= 4 and N * NL * 8 * nbuf + 2 * (N + 256) * 8 > _SMEM_LIMIT - 2048:
380
  NL //= 2
@@ -394,6 +393,7 @@ def _threads(NL, N, plan):
394
  w = max(work) if work else 64
395
  return max(64, min(256, _cdiv(w, 32) * 32))
396
 
 
397
  class ZPassG:
398
  """z line FFTs over the C = ny * nf input columns; kx < M into u, kx = M into nyq."""
399
 
@@ -540,10 +540,8 @@ class YPassG:
540
  eng.emit(tid, A, stw, 0, store, None)
541
 
542
  def kernel(self):
543
- nz, ny, M, NL, T = self.nz, self.ny, self.M, self.NL, self.T
544
  NU, NB = self.NU, self.NB
545
- eng = self.eng
546
- n_el = ny * NL
547
  TWF = self.table.numel()
548
  SF = ny * NL * 2
549
 
@@ -887,7 +885,13 @@ class AnyPlan:
887
 
888
  @cute.jit
889
  def launch3(
890
- x: cute.Tensor, u: cute.Tensor, nq: cute.Tensor, tz: cute.Tensor, ty: cute.Tensor, tx: cute.Tensor, stream
 
 
 
 
 
 
891
  ):
892
  zk(x, u, nq, tz).launch(grid=(zp.grid, 1, 1), block=(zp.T, 1, 1), stream=stream)
893
  yk(u, nq, ty).launch(grid=(yp.grid, 1, 1), block=(yp.T, 1, 1), stream=stream, use_pdl=True)
 
25
 
26
  import cutlass
27
  import torch
28
+ from cutlass import Float32, cute
29
 
30
  from .fftgen import cmul, dft, ld_c, st_c
31
 
 
374
  if cap is not None:
375
  while NL > 8 and NL // 2 >= cap:
376
  NL //= 2
 
377
  nbuf = 1
378
  while NL >= 4 and N * NL * 8 * nbuf + 2 * (N + 256) * 8 > _SMEM_LIMIT - 2048:
379
  NL //= 2
 
393
  w = max(work) if work else 64
394
  return max(64, min(256, _cdiv(w, 32) * 32))
395
 
396
+
397
  class ZPassG:
398
  """z line FFTs over the C = ny * nf input columns; kx < M into u, kx = M into nyq."""
399
 
 
540
  eng.emit(tid, A, stw, 0, store, None)
541
 
542
  def kernel(self):
543
+ nz, ny, NL, T = self.nz, self.ny, self.NL, self.T
544
  NU, NB = self.NU, self.NB
 
 
545
  TWF = self.table.numel()
546
  SF = ny * NL * 2
547
 
 
885
 
886
  @cute.jit
887
  def launch3(
888
+ x: cute.Tensor,
889
+ u: cute.Tensor,
890
+ nq: cute.Tensor,
891
+ tz: cute.Tensor,
892
+ ty: cute.Tensor,
893
+ tx: cute.Tensor,
894
+ stream,
895
  ):
896
  zk(x, u, nq, tz).launch(grid=(zp.grid, 1, 1), block=(zp.T, 1, 1), stream=stream)
897
  yk(u, nq, ty).launch(grid=(yp.grid, 1, 1), block=(yp.T, 1, 1), stream=stream, use_pdl=True)
build/torch-cuda/_c2r_f32/kernel.py CHANGED
@@ -42,18 +42,16 @@ Routing (one plan per (shape, device), compiled on first use and cached):
42
 
43
  from __future__ import annotations
44
 
45
- import threading
46
-
47
  import torch
48
  from cutlass import Float32, cute
49
 
 
50
  from .anyfft import AnyPlan, any_config
51
  from .fftgen import factor2
52
  from .inplace import XPassIP, YPassIP, YXFusedIP, ZPassIP
53
  from .twopass import TwoPassPlan, two_pass_config
54
 
55
  _SMEM_LIMIT = 99 * 1024
56
- _LOCK = threading.Lock()
57
  _PLANS: dict = {}
58
 
59
 
@@ -233,7 +231,7 @@ def _get_plan(nz, ny, nx, device):
233
  plan = _PLANS.get(key)
234
  if plan is not None:
235
  return plan
236
- with _LOCK:
237
  plan = _PLANS.get(key)
238
  if plan is None:
239
  cfg = _fast_config(nz, ny, nx)
@@ -252,10 +250,18 @@ def _get_plan(nz, ny, nx, device):
252
  from .generic import GenericPlan # only shapes no other path can plan need it
253
 
254
  plan = GenericPlan(nz, ny, nx, device)
 
255
  _PLANS[key] = plan
256
  return plan
257
 
258
 
 
 
 
 
 
 
 
259
  def _check(input):
260
  if input.dim() != 4 or input.shape[-1] != 2:
261
  raise ValueError("input must be [nz, ny, nf, 2]")
@@ -276,24 +282,28 @@ def _prepare(input):
276
  extra = ()
277
  if hasattr(plan, "nyq_numel"):
278
  extra = (torch.empty(plan.nyq_numel, dtype=torch.float32, device=input.device),)
 
279
  if input.is_contiguous() and input.data_ptr() % 16 == 0:
280
  x_flat = input.view(-1)
281
 
282
  def launch():
283
- plan(x_flat, out_flat, *extra)
 
284
  return out
285
  elif input.is_contiguous():
286
  # kernels assume a 16-byte aligned input; stage misaligned views
287
  stage = torch.empty(input.numel(), dtype=torch.float32, device=input.device)
288
 
289
  def launch():
 
290
  stage.copy_(input.view(-1))
291
- plan(stage, out_flat, *extra)
292
  return out
293
  else:
294
 
295
  def launch():
296
- plan(input.contiguous().view(-1), out_flat, *extra)
 
297
  return out
298
 
299
  return launch
@@ -331,7 +341,7 @@ def run(input):
331
  plan = _get_plan(nz, ny, nx, dev)
332
  out = torch.empty((nz, ny, nx), dtype=torch.float32, device=dev)
333
  if hasattr(plan, "nyq_numel"):
334
- plan(input.view(-1), out.view(-1), torch.empty(plan.nyq_numel, dtype=torch.float32, device=dev))
335
  else:
336
- plan(input.view(-1), out.view(-1))
337
  return out
 
42
 
43
  from __future__ import annotations
44
 
 
 
45
  import torch
46
  from cutlass import Float32, cute
47
 
48
+ from .._build import building, first_call, stream_guard
49
  from .anyfft import AnyPlan, any_config
50
  from .fftgen import factor2
51
  from .inplace import XPassIP, YPassIP, YXFusedIP, ZPassIP
52
  from .twopass import TwoPassPlan, two_pass_config
53
 
54
  _SMEM_LIMIT = 99 * 1024
 
55
  _PLANS: dict = {}
56
 
57
 
 
231
  plan = _PLANS.get(key)
232
  if plan is not None:
233
  return plan
234
+ with building(device):
235
  plan = _PLANS.get(key)
236
  if plan is None:
237
  cfg = _fast_config(nz, ny, nx)
 
250
  from .generic import GenericPlan # only shapes no other path can plan need it
251
 
252
  plan = GenericPlan(nz, ny, nx, device)
253
+ plan.ready = False # made its first call (under the build lock: see _build.first_call)
254
  _PLANS[key] = plan
255
  return plan
256
 
257
 
258
+ def _launch(plan, *args):
259
+ if plan.ready:
260
+ plan(*args)
261
+ else:
262
+ first_call(plan, plan, *args)
263
+
264
+
265
  def _check(input):
266
  if input.dim() != 4 or input.shape[-1] != 2:
267
  raise ValueError("input must be [nz, ny, nf, 2]")
 
282
  extra = ()
283
  if hasattr(plan, "nyq_numel"):
284
  extra = (torch.empty(plan.nyq_numel, dtype=torch.float32, device=input.device),)
285
+ guard = stream_guard(input.device)
286
  if input.is_contiguous() and input.data_ptr() % 16 == 0:
287
  x_flat = input.view(-1)
288
 
289
  def launch():
290
+ guard(out, *extra)
291
+ _launch(plan, x_flat, out_flat, *extra)
292
  return out
293
  elif input.is_contiguous():
294
  # kernels assume a 16-byte aligned input; stage misaligned views
295
  stage = torch.empty(input.numel(), dtype=torch.float32, device=input.device)
296
 
297
  def launch():
298
+ guard(out, stage, *extra)
299
  stage.copy_(input.view(-1))
300
+ _launch(plan, stage, out_flat, *extra)
301
  return out
302
  else:
303
 
304
  def launch():
305
+ guard(out, *extra)
306
+ _launch(plan, input.contiguous().view(-1), out_flat, *extra)
307
  return out
308
 
309
  return launch
 
341
  plan = _get_plan(nz, ny, nx, dev)
342
  out = torch.empty((nz, ny, nx), dtype=torch.float32, device=dev)
343
  if hasattr(plan, "nyq_numel"):
344
+ _launch(plan, input.view(-1), out.view(-1), torch.empty(plan.nyq_numel, dtype=torch.float32, device=dev))
345
  else:
346
+ _launch(plan, input.view(-1), out.view(-1))
347
  return out
build/torch-cuda/_c2r_f64/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (479 Bytes). View file
 
build/torch-cuda/_c2r_f64/__pycache__/bigprime.cpython-312.pyc ADDED
Binary file (50.9 kB). View file
 
build/torch-cuda/_c2r_f64/__pycache__/fftgen.cpython-312.pyc ADDED
Binary file (23.6 kB). View file
 
build/torch-cuda/_c2r_f64/__pycache__/kernel.cpython-312.pyc ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:553f5dd4062e171bda3a28bdb6fc21430ea89e184c5eb624bce7e125251d8da3
3
+ size 177493
build/torch-cuda/_c2r_f64/__pycache__/softfp.cpython-312.pyc ADDED
Binary file (12.8 kB). View file
 
build/torch-cuda/_c2r_f64/__pycache__/twiddles.cpython-312.pyc ADDED
Binary file (5.79 kB). View file
 
build/torch-cuda/_c2r_f64/bigprime.py CHANGED
@@ -84,8 +84,22 @@ def split(n):
84
  return P, m
85
 
86
 
 
 
 
 
87
  def supported(n):
88
- return split(n) is not None
 
 
 
 
 
 
 
 
 
 
89
 
90
 
91
  _PI = Decimal("3.14159265358979323846264338327950288419716939937510582097494459230781640628620899")
 
84
  return P, m
85
 
86
 
87
+ # the most shared memory one CTA can have on the RTX 5090
88
+ SMEM_MAX = 99 * 1024
89
+
90
+
91
  def supported(n):
92
+ """n has a big-prime split whose one-sequence tile fits in a CTA's shared memory (PassCfg._smem,
93
+ S = 1, for the direct sums and for the model's convolution); longer axes keep the direct DFT."""
94
+ sp = split(n)
95
+ if sp is None:
96
+ return False
97
+ P, m = sp
98
+ meth, L, _ = p_stage_method(P)
99
+ need = (2 * n + P) * 16 + 64
100
+ if meth != "direct":
101
+ need = max(need, (2 * max(n, m * L) + 2 * m) * 16 + 64)
102
+ return need <= SMEM_MAX
103
 
104
 
105
  _PI = Decimal("3.14159265358979323846264338327950288419716939937510582097494459230781640628620899")
build/torch-cuda/_c2r_f64/kernel.py CHANGED
@@ -35,6 +35,7 @@ NaN may carry another payload), so where an addition runs changes no result.
35
  # ruff: noqa: SIM102
36
 
37
  import math
 
38
 
39
  import cuda.bindings.driver as cuda
40
  import cutlass
@@ -2726,7 +2727,8 @@ def _make_passC_loop(yzd, ny, M, S, NT, soft, twnc_off, PDL, U, POL):
2726
 
2727
 
2728
  def _has_plan(n):
2729
- return bool(_radix_lists(n))
 
2730
 
2731
 
2732
  def make_kernels_direct(nz, ny, M):
@@ -2837,7 +2839,39 @@ def make_tables_2d(nz, ny, M, yzd):
2837
  return torch.cat([make_tables(nz, ny, M), yzd.nc_table(), yzd.twiddle_table()])
2838
 
2839
 
 
 
 
 
 
2840
  _PLANS = {}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2841
 
2842
 
2843
  def _fake(n):
@@ -2875,7 +2909,10 @@ class _Plan:
2875
  tables = make_tables_2d(nz, ny, M, YZ2D(ny, yz["A"], yz["rc"], yz.get("N1", 1)))
2876
  else:
2877
  tables = torch.cat([make_tables(nz, ny, M)] + [cfg.table() for cfg in big.values()])
2878
- self.tables = tables.to(device).contiguous()
 
 
 
2879
  nx_, no_ = nz * ny * nf * 2, nz * ny * M * 2
2880
  args = [_fake(nx_), _fake(no_), _fake(self.tables.numel())]
2881
  if self.direct:
@@ -2884,36 +2921,48 @@ class _Plan:
2884
  # few microseconds of host time (the shapes and the 16-byte alignment are checked at the call)
2885
  stream = cute.runtime.make_fake_stream(use_tvm_ffi_env_stream=True)
2886
  self.fn = cute.compile(launch, *args, stream, options="--enable-tvm-ffi")
 
 
 
 
 
 
 
 
 
2887
 
2888
  def bind(self, xin, out):
2889
- xf, of, fn, tw = xin.view(-1), out.view(-1), self.fn, self.tables
2890
  if self.direct:
2891
  ws = torch.empty_like(of)
2892
 
2893
  def go():
2894
- fn(xf, of, tw, ws)
2895
 
2896
  go.ws = ws
2897
  return go
2898
 
2899
  def go():
2900
- fn(xf, of, tw)
2901
 
2902
  return go
2903
 
2904
  def run_into(self, xin, out):
 
2905
  if self.direct:
2906
- self.fn(xin.view(-1), out.view(-1), self.tables, torch.empty_like(out).view(-1))
2907
  else:
2908
- self.fn(xin.view(-1), out.view(-1), self.tables)
2909
 
2910
 
2911
  def _get_plan(nz, ny, nf, device):
2912
  key = (nz, ny, nf, device)
2913
  p = _PLANS.get(key)
2914
  if p is None:
2915
- p = _Plan(nz, ny, nf, device)
2916
- _PLANS[key] = p
 
 
2917
  return p
2918
 
2919
 
@@ -2924,12 +2973,17 @@ def _check(x):
2924
  raise TypeError(f"this c2r takes float64, not {x.dtype}")
2925
  if x.dim() != 4 or x.shape[-1] != 2 or min(x.shape[:2]) < 1 or x.shape[2] < 2:
2926
  raise ValueError(f"c2r takes a [nz, ny, nf, 2] half-spectrum with nf >= 2, not {tuple(x.shape)}")
 
 
 
2927
 
2928
 
2929
  def run(input):
2930
  """Inverse real 3D FFT of input (float64 [nz, ny, nf, 2]) into a new float64 [nz, ny, 2*(nf-1)]."""
 
2931
  x = input.contiguous()
2932
- _check(x)
 
2933
  nz, ny, nf, _ = x.shape
2934
  plan = _get_plan(nz, ny, nf, x.device)
2935
  if x.data_ptr() % 16:
@@ -2946,12 +3000,32 @@ def prepare(input):
2946
  raise ValueError("prepare binds the input buffer itself, so it must be contiguous")
2947
  if input.data_ptr() % 16:
2948
  raise ValueError("prepare binds the input buffer itself, so it must be 16-byte aligned")
 
 
2949
  nz, ny, nf, _ = input.shape
2950
  plan = _get_plan(nz, ny, nf, input.device)
2951
  out = torch.empty((nz, ny, 2 * (nf - 1)), dtype=torch.float64, device=input.device)
2952
  go = plan.bind(input, out)
 
 
 
 
 
 
 
 
 
 
 
 
2953
 
2954
  def launch():
 
 
 
 
 
 
2955
  go()
2956
  return out
2957
 
 
35
  # ruff: noqa: SIM102
36
 
37
  import math
38
+ import threading
39
 
40
  import cuda.bindings.driver as cuda
41
  import cutlass
 
2727
 
2728
 
2729
  def _has_plan(n):
2730
+ # an axis of length 1 has no stages to plan; a grid with one takes the direct passes
2731
+ return n > 1 and bool(_radix_lists(n))
2732
 
2733
 
2734
  def make_kernels_direct(nz, ny, M):
 
2839
  return torch.cat([make_tables(nz, ny, M), yzd.nc_table(), yzd.twiddle_table()])
2840
 
2841
 
2842
+ # CuTe DSL is not thread-safe while it compiles (also across packages) or, for --enable-tvm-ffi
2843
+ # functions, while a function is first called: every kda kernel package shares this lock.
2844
+ _CUTE_LOCK = cutlass.__dict__.setdefault("_kda_compile_lock", threading.RLock())
2845
+
2846
+ _raw_stream = torch._C._cuda_getCurrentRawStream # device index -> current stream handle
2847
  _PLANS = {}
2848
+ _SIDE = {} # device -> stream that uploads tables while a CUDA graph is being captured
2849
+
2850
+
2851
+ def _outside_capture(fn, device):
2852
+ """fn() while the current stream is capturing a CUDA graph (the first call of a shape), without
2853
+ adding its copies to the graph, which torch refuses from pageable memory: it runs on a private
2854
+ side stream with this thread in relaxed capture mode and has completed before this returns, so
2855
+ the plan's tables serve the graph and later eager calls alike."""
2856
+ err, prev = cuda.cuThreadExchangeStreamCaptureMode(cuda.CUstreamCaptureMode.CU_STREAM_CAPTURE_MODE_RELAXED)
2857
+ if err != cuda.CUresult.CUDA_SUCCESS:
2858
+ raise RuntimeError(f"cuThreadExchangeStreamCaptureMode failed: {err}")
2859
+ try:
2860
+ side = _SIDE.get(device)
2861
+ if side is None:
2862
+ # a stream of its own: torch.cuda.Stream() hands out one of a pool of 32 per device, which can be
2863
+ # the very stream being captured
2864
+ with torch.cuda.device(device):
2865
+ err, h = cuda.cuStreamCreate(cuda.CUstream_flags.CU_STREAM_NON_BLOCKING.value)
2866
+ if err != cuda.CUresult.CUDA_SUCCESS:
2867
+ raise RuntimeError(f"cuStreamCreate failed: {err}")
2868
+ side = _SIDE.setdefault(device, torch.cuda.ExternalStream(int(h), device=device))
2869
+ with torch.cuda.stream(side):
2870
+ res = fn()
2871
+ side.synchronize()
2872
+ finally:
2873
+ cuda.cuThreadExchangeStreamCaptureMode(prev)
2874
+ return res
2875
 
2876
 
2877
  def _fake(n):
 
2909
  tables = make_tables_2d(nz, ny, M, YZ2D(ny, yz["A"], yz["rc"], yz.get("N1", 1)))
2910
  else:
2911
  tables = torch.cat([make_tables(nz, ny, M)] + [cfg.table() for cfg in big.values()])
2912
+ if torch.cuda.is_current_stream_capturing():
2913
+ self.tables = _outside_capture(lambda: tables.to(device).contiguous(), device)
2914
+ else:
2915
+ self.tables = tables.to(device).contiguous()
2916
  nx_, no_ = nz * ny * nf * 2, nz * ny * M * 2
2917
  args = [_fake(nx_), _fake(no_), _fake(self.tables.numel())]
2918
  if self.direct:
 
2921
  # few microseconds of host time (the shapes and the 16-byte alignment are checked at the call)
2922
  stream = cute.runtime.make_fake_stream(use_tvm_ffi_env_stream=True)
2923
  self.fn = cute.compile(launch, *args, stream, options="--enable-tvm-ffi")
2924
+ self.loaded = False # self.fn has been called once (under _CUTE_LOCK)
2925
+
2926
+ def _call(self, *args):
2927
+ if not self.loaded:
2928
+ with _CUTE_LOCK:
2929
+ self.fn(*args)
2930
+ self.loaded = True
2931
+ return
2932
+ self.fn(*args)
2933
 
2934
  def bind(self, xin, out):
2935
+ xf, of, tw = xin.view(-1), out.view(-1), self.tables
2936
  if self.direct:
2937
  ws = torch.empty_like(of)
2938
 
2939
  def go():
2940
+ (self.fn if self.loaded else self._call)(xf, of, tw, ws)
2941
 
2942
  go.ws = ws
2943
  return go
2944
 
2945
  def go():
2946
+ (self.fn if self.loaded else self._call)(xf, of, tw)
2947
 
2948
  return go
2949
 
2950
  def run_into(self, xin, out):
2951
+ fn = self.fn if self.loaded else self._call
2952
  if self.direct:
2953
+ fn(xin.view(-1), out.view(-1), self.tables, torch.empty_like(out).view(-1))
2954
  else:
2955
+ fn(xin.view(-1), out.view(-1), self.tables)
2956
 
2957
 
2958
  def _get_plan(nz, ny, nf, device):
2959
  key = (nz, ny, nf, device)
2960
  p = _PLANS.get(key)
2961
  if p is None:
2962
+ with _CUTE_LOCK:
2963
+ p = _PLANS.get(key)
2964
+ if p is None:
2965
+ p = _PLANS[key] = _Plan(nz, ny, nf, device)
2966
  return p
2967
 
2968
 
 
2973
  raise TypeError(f"this c2r takes float64, not {x.dtype}")
2974
  if x.dim() != 4 or x.shape[-1] != 2 or min(x.shape[:2]) < 1 or x.shape[2] < 2:
2975
  raise ValueError(f"c2r takes a [nz, ny, nf, 2] half-spectrum with nf >= 2, not {tuple(x.shape)}")
2976
+ if x.shape[0] * x.shape[1] * x.shape[2] >= 2**31:
2977
+ # the kernels index complex elements with 32-bit offsets
2978
+ raise ValueError("the half-spectrum has 2^31 or more complex elements, which the kernels cannot address")
2979
 
2980
 
2981
  def run(input):
2982
  """Inverse real 3D FFT of input (float64 [nz, ny, nf, 2]) into a new float64 [nz, ny, 2*(nf-1)]."""
2983
+ _check(input)
2984
  x = input.contiguous()
2985
+ if x.is_neg(): # a negated view (torch's neg bit): the kernels read the stored values
2986
+ x = x.resolve_neg()
2987
  nz, ny, nf, _ = x.shape
2988
  plan = _get_plan(nz, ny, nf, x.device)
2989
  if x.data_ptr() % 16:
 
3000
  raise ValueError("prepare binds the input buffer itself, so it must be contiguous")
3001
  if input.data_ptr() % 16:
3002
  raise ValueError("prepare binds the input buffer itself, so it must be 16-byte aligned")
3003
+ if input.is_neg():
3004
+ raise ValueError("prepare binds the input buffer itself, so it cannot be a negated view (resolve_neg() it)")
3005
  nz, ny, nf, _ = input.shape
3006
  plan = _get_plan(nz, ny, nf, input.device)
3007
  out = torch.empty((nz, ny, 2 * (nf - 1)), dtype=torch.float64, device=input.device)
3008
  go = plan.bind(input, out)
3009
+ # out (and the direct passes' workspace) come from this stream's memory pool: a launch on another
3010
+ # stream waits until this stream's work queued before prepare has finished with that memory, and
3011
+ # marks the buffers as used by its stream, so that dropping the launch early cannot hand them back
3012
+ # to this stream while its kernels run. (A capture cannot wait for outside work; torch.cuda.graph
3013
+ # synchronizes before capturing.)
3014
+ dev = input.get_device()
3015
+ home = _raw_stream(dev)
3016
+ ready = None
3017
+ if not torch.cuda.is_current_stream_capturing():
3018
+ ready = torch.cuda.Event()
3019
+ ready.record()
3020
+ buffers = (out, go.ws) if hasattr(go, "ws") else (out,)
3021
 
3022
  def launch():
3023
+ if _raw_stream(dev) != home:
3024
+ stream = torch.cuda.current_stream(dev)
3025
+ if ready is not None and not torch.cuda.is_current_stream_capturing():
3026
+ stream.wait_event(ready)
3027
+ for t in buffers:
3028
+ t.record_stream(stream)
3029
  go()
3030
  return out
3031
 
build/torch-cuda/_r2c_f32/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (470 Bytes). View file
 
build/torch-cuda/_r2c_f32/__pycache__/fft3k.cpython-312.pyc ADDED
Binary file (36.4 kB). View file
 
build/torch-cuda/_r2c_f32/__pycache__/fft_core.cpython-312.pyc ADDED
Binary file (13.6 kB). View file
 
build/torch-cuda/_r2c_f32/__pycache__/fft_gen.cpython-312.pyc ADDED
Binary file (48.9 kB). View file
 
build/torch-cuda/_r2c_f32/__pycache__/fft_generic.cpython-312.pyc ADDED
Binary file (7.3 kB). View file
 
build/torch-cuda/_r2c_f32/__pycache__/fft_plane2.cpython-312.pyc ADDED
Binary file (11.6 kB). View file
 
build/torch-cuda/_r2c_f32/__pycache__/fft_xy.cpython-312.pyc ADDED
Binary file (13.5 kB). View file
 
build/torch-cuda/_r2c_f32/__pycache__/fft_ys1w.cpython-312.pyc ADDED
Binary file (18.7 kB). View file
 
build/torch-cuda/_r2c_f32/__pycache__/fft_ysplit.cpython-312.pyc ADDED
Binary file (20.5 kB). View file
 
build/torch-cuda/_r2c_f32/__pycache__/kernel.cpython-312.pyc ADDED
Binary file (26.4 kB). View file
 
build/torch-cuda/_r2c_f32/__pycache__/plan.cpython-312.pyc ADDED
Binary file (15.7 kB). View file
 
build/torch-cuda/_r2c_f32/__pycache__/ptx.cpython-312.pyc ADDED
Binary file (11.8 kB). View file
 
build/torch-cuda/_r2c_f32/__pycache__/stockham.cpython-312.pyc ADDED
Binary file (15.9 kB). View file
 
build/torch-cuda/_r2c_f32/fft_gen.py CHANGED
@@ -22,14 +22,14 @@ import math
22
  import cutlass
23
  import torch
24
  from cutlass import Float32, Int32, Int64, cute
 
 
25
 
26
  from .fft_core import as_f32
27
  from .plan import SMEM_LIMIT, Layout, choose_layout, lanes_groups, line_plan_cost, line_plans
28
  from .ptx import _asm, _iv, ldg2, ldg4, lds2, lds4, stg2, stg2_if, stg4, stg4_if, sts2, sts2_if, sts4, sts4_if
29
  from .stockham import TwSmem, access_offsets, and_pv, b2i, bfly, emit_fft, fsel, lay_off
30
 
31
- from cutlass.cutlass_dsl import T as _T, dsl_user_op
32
-
33
 
34
  @dsl_user_op
35
  def lds1(addr, *, loc=None, ip=None):
@@ -485,7 +485,7 @@ def make_gx_kernel(cfg):
485
  blk_in = gin + Int64(r0) * (nx * 4)
486
  # ---- coalesced copy-in of the row block (rows * nx floats, contiguous)
487
  n4 = None
488
- if (tail):
489
  nv = cutlass.min(Int32(nrows) - r0, Int32(rows))
490
  n4 = (nv * nx) // 4
491
  for i in range(-(-in_f4 // NT)):
@@ -503,7 +503,7 @@ def make_gx_kernel(cfg):
503
  sts4(sbase + f * 16, v)
504
  else:
505
  sts4_if(pv, sbase + f * 16, v)
506
- if (rem_scalars != 0):
507
  # the last 1..3 floats of the tensor (only the last block reaches them)
508
  last0 = ntot - rem_scalars
509
  for s in range(rem_scalars):
@@ -516,13 +516,13 @@ def make_gx_kernel(cfg):
516
 
517
  pr = tid // T
518
  t = tid % T
519
- if (cfg.nt != NT):
520
  pr = cutlass.min(pr, Int32(cfg.prs - 1))
521
  t = cutlass.min(t, Int32(T - 1))
522
  ra = sbase + (2 * pr) * (nx * 4)
523
  rb = ra + nx * 4
524
  bok = None
525
- if (nrows % 2 == 1):
526
  bok = b2i(r0 + 2 * pr + 1 < nrows)
527
 
528
  def load(idx):
@@ -583,7 +583,7 @@ def make_gx_kernel(cfg):
583
  out_f4 = rows * nf // 2
584
  blk_out = gout + Int64(r0) * (nf * 8)
585
  lim = None
586
- if (tail):
587
  nv2 = cutlass.min(Int32(nrows) - r0, Int32(rows))
588
  lim = (nv2 * nf) // 2
589
  for i in range(-(-out_f4 // NT)):
@@ -601,7 +601,7 @@ def make_gx_kernel(cfg):
601
  stg4(blk_out + Int64(f) * 16, v)
602
  else:
603
  stg4_if(pv, blk_out + Int64(f) * 16, v)
604
- if (tail and (nrows % rows) * nf % 2 == 1):
605
  nv3 = cutlass.min(Int32(nrows) - r0, Int32(rows))
606
  last = nv3 * nf - 1
607
  q = b2i(tid == 0) & b2i((nv3 * nf) % 2 == 1)
@@ -709,17 +709,17 @@ def make_gcol_kernel(cfg, trigger=False):
709
  c = tid % W
710
  t = tid // W
711
  valid = None
712
- if (cfg.nt != NT):
713
  valid = b2i(tid < cfg.nt)
714
  t = cutlass.min(t, Int32(T - 1))
715
- if (cfg.nouter > 1):
716
  outer = bid // cfg.tpo
717
  tile = bid - outer * cfg.tpo
718
  else:
719
  outer = Int32(0)
720
  tile = bid
721
  g = tile * W + c
722
- if (tail):
723
  ok = b2i(g < cfg.ngroups)
724
  valid = ok if valid is None else (valid & ok)
725
  g = cutlass.min(g, Int32(cfg.ngroups - 1))
@@ -734,7 +734,7 @@ def make_gcol_kernel(cfg, trigger=False):
734
  cute.arch.sync_threads()
735
 
736
  raw = eng.prefetch(t, load)
737
- if (eng.blue or len(eng.plan.passes) == 1):
738
  cute.arch.sync_threads()
739
  mean = None
740
  if eng.needs_mean:
 
22
  import cutlass
23
  import torch
24
  from cutlass import Float32, Int32, Int64, cute
25
+ from cutlass.cutlass_dsl import T as _T
26
+ from cutlass.cutlass_dsl import dsl_user_op
27
 
28
  from .fft_core import as_f32
29
  from .plan import SMEM_LIMIT, Layout, choose_layout, lanes_groups, line_plan_cost, line_plans
30
  from .ptx import _asm, _iv, ldg2, ldg4, lds2, lds4, stg2, stg2_if, stg4, stg4_if, sts2, sts2_if, sts4, sts4_if
31
  from .stockham import TwSmem, access_offsets, and_pv, b2i, bfly, emit_fft, fsel, lay_off
32
 
 
 
33
 
34
  @dsl_user_op
35
  def lds1(addr, *, loc=None, ip=None):
 
485
  blk_in = gin + Int64(r0) * (nx * 4)
486
  # ---- coalesced copy-in of the row block (rows * nx floats, contiguous)
487
  n4 = None
488
+ if tail:
489
  nv = cutlass.min(Int32(nrows) - r0, Int32(rows))
490
  n4 = (nv * nx) // 4
491
  for i in range(-(-in_f4 // NT)):
 
503
  sts4(sbase + f * 16, v)
504
  else:
505
  sts4_if(pv, sbase + f * 16, v)
506
+ if rem_scalars != 0:
507
  # the last 1..3 floats of the tensor (only the last block reaches them)
508
  last0 = ntot - rem_scalars
509
  for s in range(rem_scalars):
 
516
 
517
  pr = tid // T
518
  t = tid % T
519
+ if cfg.nt != NT:
520
  pr = cutlass.min(pr, Int32(cfg.prs - 1))
521
  t = cutlass.min(t, Int32(T - 1))
522
  ra = sbase + (2 * pr) * (nx * 4)
523
  rb = ra + nx * 4
524
  bok = None
525
+ if nrows % 2 == 1:
526
  bok = b2i(r0 + 2 * pr + 1 < nrows)
527
 
528
  def load(idx):
 
583
  out_f4 = rows * nf // 2
584
  blk_out = gout + Int64(r0) * (nf * 8)
585
  lim = None
586
+ if tail:
587
  nv2 = cutlass.min(Int32(nrows) - r0, Int32(rows))
588
  lim = (nv2 * nf) // 2
589
  for i in range(-(-out_f4 // NT)):
 
601
  stg4(blk_out + Int64(f) * 16, v)
602
  else:
603
  stg4_if(pv, blk_out + Int64(f) * 16, v)
604
+ if tail and (nrows % rows) * nf % 2 == 1:
605
  nv3 = cutlass.min(Int32(nrows) - r0, Int32(rows))
606
  last = nv3 * nf - 1
607
  q = b2i(tid == 0) & b2i((nv3 * nf) % 2 == 1)
 
709
  c = tid % W
710
  t = tid // W
711
  valid = None
712
+ if cfg.nt != NT:
713
  valid = b2i(tid < cfg.nt)
714
  t = cutlass.min(t, Int32(T - 1))
715
+ if cfg.nouter > 1:
716
  outer = bid // cfg.tpo
717
  tile = bid - outer * cfg.tpo
718
  else:
719
  outer = Int32(0)
720
  tile = bid
721
  g = tile * W + c
722
+ if tail:
723
  ok = b2i(g < cfg.ngroups)
724
  valid = ok if valid is None else (valid & ok)
725
  g = cutlass.min(g, Int32(cfg.ngroups - 1))
 
734
  cute.arch.sync_threads()
735
 
736
  raw = eng.prefetch(t, load)
737
+ if eng.blue or len(eng.plan.passes) == 1:
738
  cute.arch.sync_threads()
739
  mean = None
740
  if eng.needs_mean:
build/torch-cuda/_r2c_f32/kernel.py CHANGED
@@ -41,6 +41,7 @@ import cutlass
41
  import torch
42
  from cutlass import cute
43
 
 
44
  from .fft3k import ColCfg, XCfg, make_col_kernel, make_x_kernel
45
  from .fft_gen import GColCfg, GXCfg, make_gcol_kernel, make_gx_kernel
46
  from .fft_generic import make_generic_col_kernel, make_generic_x_kernel, twiddle_f64
@@ -242,6 +243,7 @@ class _Plan:
242
  self.shape = (nz, ny, nx)
243
  self.device = device
244
  self.sync_words = 0
 
245
  if strategy is None:
246
  strategy = _default_strategy(nz, ny, nx)
247
  self.strategy = strategy
@@ -338,13 +340,19 @@ class _Plan:
338
  lambda i, o: kz(o, self.tw),
339
  ]
340
 
341
- def run(self, inp_flat, out_flat):
 
 
 
 
342
  for f in self.steps:
343
- f(inp_flat, out_flat)
344
 
345
- def run_sync(self, inp_flat, out_flat, sync):
 
 
346
  for f in self.steps:
347
- f(inp_flat, out_flat, sync)
348
 
349
 
350
  _PLANS = {}
@@ -354,12 +362,15 @@ def _get_plan(shape, device):
354
  key = (tuple(shape), str(device))
355
  pl = _PLANS.get(key)
356
  if pl is None:
357
- nz, ny, nx = shape
358
- try:
359
- pl = _Plan(nz, ny, nx, device)
360
- except Exception: # noqa: BLE001 -- a fast plan that fails to build or compile falls back to generic
361
- pl = _Plan(nz, ny, nx, device, strategy="generic")
362
- _PLANS[key] = pl
 
 
 
363
  return pl
364
 
365
 
@@ -382,25 +393,32 @@ def prepare(input):
382
  out = torch.empty((nz, ny, nx // 2 + 1, 2), device=input.device, dtype=torch.float32)
383
  inp_flat = input.view(-1)
384
  out_flat = out.view(-1)
 
 
 
 
 
 
 
 
 
 
385
 
386
  if not pl.sync_words:
387
 
388
  def launch():
 
 
 
389
  pl.run(inp_flat, out_flat)
390
  return out
391
 
392
  return launch
393
 
394
- # Sync scratch per launch object, so launches of one shape on different streams
395
- # never share it. It is zeroed on the stream of the first launch (ordered before
396
- # it); the kernels re-arm it on exit for the next launch, which writes the same
397
- # output and so is stream-ordered after this one.
398
- sync = None
399
-
400
  def launch():
401
- nonlocal sync
402
- if sync is None:
403
- sync = torch.zeros(pl.sync_words, dtype=torch.int32, device=out.device)
404
  pl.run_sync(inp_flat, out_flat, sync)
405
  return out
406
 
@@ -412,6 +430,8 @@ def run(input):
412
  _reject(input)
413
  nz, ny, nx = input.shape
414
  pl = _get_plan((nz, ny, nx), input.device)
 
 
415
  if pl.sync_words:
416
  return prepare(input)()
417
  # the common case without building a launch closure: per-call overhead counts on small grids
 
41
  import torch
42
  from cutlass import cute
43
 
44
+ from .._build import building, first_call, stream_guard
45
  from .fft3k import ColCfg, XCfg, make_col_kernel, make_x_kernel
46
  from .fft_gen import GColCfg, GXCfg, make_gcol_kernel, make_gx_kernel
47
  from .fft_generic import make_generic_col_kernel, make_generic_x_kernel, twiddle_f64
 
243
  self.shape = (nz, ny, nx)
244
  self.device = device
245
  self.sync_words = 0
246
+ self.ready = False # made its first call (under the build lock: see _build.first_call)
247
  if strategy is None:
248
  strategy = _default_strategy(nz, ny, nx)
249
  self.strategy = strategy
 
340
  lambda i, o: kz(o, self.tw),
341
  ]
342
 
343
+ def run(self, *args):
344
+ """The transform: run(inp_flat, out_flat), or run(inp_flat, out_flat, sync) if sync_words."""
345
+ if not self.ready:
346
+ first_call(self, self._steps, *args)
347
+ return
348
  for f in self.steps:
349
+ f(*args)
350
 
351
+ run_sync = run
352
+
353
+ def _steps(self, *args):
354
  for f in self.steps:
355
+ f(*args)
356
 
357
 
358
  _PLANS = {}
 
362
  key = (tuple(shape), str(device))
363
  pl = _PLANS.get(key)
364
  if pl is None:
365
+ with building(device):
366
+ pl = _PLANS.get(key)
367
+ if pl is None:
368
+ nz, ny, nx = shape
369
+ try:
370
+ pl = _Plan(nz, ny, nx, device)
371
+ except Exception: # noqa: BLE001 -- a fast plan that fails to build or compile falls back to generic
372
+ pl = _Plan(nz, ny, nx, device, strategy="generic")
373
+ _PLANS[key] = pl
374
  return pl
375
 
376
 
 
393
  out = torch.empty((nz, ny, nx // 2 + 1, 2), device=input.device, dtype=torch.float32)
394
  inp_flat = input.view(-1)
395
  out_flat = out.view(-1)
396
+ stage = None
397
+ if input.data_ptr() % 16:
398
+ # the kernels load the input in 16-byte vectors: a misaligned buffer is transformed from an aligned copy
399
+ src, stage = inp_flat, torch.empty_like(inp_flat)
400
+ inp_flat = stage
401
+ # Sync scratch per launch object, so launches of one shape on different streams never share it; zeroed
402
+ # here, before the stream guard, so that it is prepare's like the output (the kernels re-arm it on exit
403
+ # for the next launch, which writes the same output and so is stream-ordered after this one).
404
+ sync = torch.zeros(pl.sync_words, dtype=torch.int32, device=out.device) if pl.sync_words else None
405
+ guard = stream_guard(input.device)
406
 
407
  if not pl.sync_words:
408
 
409
  def launch():
410
+ guard(out, stage)
411
+ if stage is not None:
412
+ stage.copy_(src)
413
  pl.run(inp_flat, out_flat)
414
  return out
415
 
416
  return launch
417
 
 
 
 
 
 
 
418
  def launch():
419
+ guard(out, stage, sync)
420
+ if stage is not None:
421
+ stage.copy_(src)
422
  pl.run_sync(inp_flat, out_flat, sync)
423
  return out
424
 
 
430
  _reject(input)
431
  nz, ny, nx = input.shape
432
  pl = _get_plan((nz, ny, nx), input.device)
433
+ if input.data_ptr() % 16:
434
+ input = input.clone() # the kernels load the input in 16-byte vectors; a fresh copy is aligned
435
  if pl.sync_words:
436
  return prepare(input)()
437
  # the common case without building a launch closure: per-call overhead counts on small grids
build/torch-cuda/_r2c_f32/plan.py CHANGED
@@ -191,8 +191,10 @@ class TwiddleBuilder:
191
  p.tw_off = self.add_roots([(k * m) % L for k in range(p.Ns) for m in range(p.R)], L)
192
 
193
  def array(self):
194
- """float32 CPU tensor [re0, im0, re1, im1, ...]."""
195
- return torch.tensor(self.vals, dtype=torch.float64).reshape(-1).to(torch.float32)
 
 
196
 
197
 
198
  # ----------------------------------------------------------------------------- smem layouts
 
191
  p.tw_off = self.add_roots([(k * m) % L for k in range(p.Ns) for m in range(p.R)], L)
192
 
193
  def array(self):
194
+ """float32 CPU tensor [re0, im0, re1, im1, ...], padded to whole 16-byte chunks: the
195
+ kernels stage tables two entries at a time, so an odd last table reads one entry past it."""
196
+ vals = self.vals + [(0.0, 0.0)] * (len(self.vals) % 2)
197
+ return torch.tensor(vals, dtype=torch.float64).reshape(-1).to(torch.float32)
198
 
199
 
200
  # ----------------------------------------------------------------------------- smem layouts
build/torch-cuda/_r2c_f64/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (344 Bytes). View file
 
build/torch-cuda/_r2c_f64/__pycache__/bigprime.cpython-312.pyc ADDED
Binary file (50.9 kB). View file
 
build/torch-cuda/_r2c_f64/__pycache__/dsl_ops.cpython-312.pyc ADDED
Binary file (17.3 kB). View file
 
build/torch-cuda/_r2c_f64/__pycache__/fft_codelets.cpython-312.pyc ADDED
Binary file (34.8 kB). View file
 
build/torch-cuda/_r2c_f64/__pycache__/fft_direct.cpython-312.pyc ADDED
Binary file (14.1 kB). View file
 
build/torch-cuda/_r2c_f64/__pycache__/fft_passes.cpython-312.pyc ADDED
Binary file (53 kB). View file
 
build/torch-cuda/_r2c_f64/__pycache__/fft_plan.cpython-312.pyc ADDED
Binary file (11.4 kB). View file
 
build/torch-cuda/_r2c_f64/__pycache__/fft_stages.cpython-312.pyc ADDED
Binary file (34.8 kB). View file
 
build/torch-cuda/_r2c_f64/__pycache__/fftgen.cpython-312.pyc ADDED
Binary file (23.6 kB). View file
 
build/torch-cuda/_r2c_f64/__pycache__/kernel.cpython-312.pyc ADDED
Binary file (25.5 kB). View file
 
build/torch-cuda/_r2c_f64/__pycache__/planner.cpython-312.pyc ADDED
Binary file (11.4 kB). View file
 
build/torch-cuda/_r2c_f64/__pycache__/tuned.cpython-312.pyc ADDED
Binary file (5.49 kB). View file