diff --git a/.gitattributes b/.gitattributes index 6b7a283f6a9d189d65bccdb859c6f80016f52228..17ff7c64d17192c48092dcd466ea72cbec75777d 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,3 +1,4 @@ *.so filter=lfs diff=lfs merge=lfs -text *.pyd filter=lfs diff=lfs merge=lfs -text *.dylib filter=lfs diff=lfs merge=lfs -text +build/torch-cuda/_c2r_f64/__pycache__/kernel.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text diff --git a/README.md b/README.md index f4ee95cdae41af0d9d9872fe6109e36ef04c71ff..edd3f626a5c1ecc27ebcc77d3714621aea666480 100644 --- a/README.md +++ b/README.md @@ -62,17 +62,23 @@ spectrum = launch() # ...then transform its current contents `launch()`, which transforms the buffer's current contents into one output tensor that it reuses on every call. Calls of one `launch` must be ordered (one stream). Keep `launch` alive as long as a CUDA graph captured from it. - fp64 r2c has no two-phase form; its `launch()` calls `r2c(x)`. + fp64 r2c has no two-phase form; its `launch()` calls `r2c(x)`. A `launch()` + on another stream than the one `prepare_*` ran on waits for `prepare_*`'s + work and keeps its output and workspaces reserved for that stream's work, + even if the launch object is dropped before the work ran. - Calls on different CUDA streams may run concurrently, including calls of the - same shape. + same shape. Calls may also come from several threads: CuTe DSL is not + thread-safe while it compiles or makes the first call of a compiled function, + so a new shape's plan is built, and makes its first call, under a lock that + all kda kernels share (later calls take no lock). - A call costs about 13 to 17 us of host time (TVM-FFI launches on the current stream). Timed per call as the requests' benchmark does (flashinfer-bench: synchronize, event, call, event), every kernel is faster than `torch.fft` on every grid tried, the smallest included (see Performance). - The first call for a new shape compiles its kernels (CuTe DSL JIT), typically in 1 to 15 s, up to about 4 minutes for a very long z axis over a tiny y-x - plane (such as 4096x8x16). Make that first call outside CUDA graph capture; - later calls can be captured. + plane (such as 4096x8x16). That first call may itself be inside CUDA graph + capture. - `c2r` expects a Hermitian-consistent half-spectrum, such as the output of `r2c` or Fourier-space data that keeps its symmetry. On other input the result 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 above 13 (fp64, such as 289) still take slow generic kernels. fp64 r2c raises `NotImplementedError` when a y or z axis needs a direct DFT longer than 6336 points; fp64 c2r raises it for nz from 1280 to 4096, ny from 3072 to 4096 or - nx / 2 from 3072 to 4096. + nx / 2 from 3072 to 4096. The fp64 kernels address with 32-bit offsets: fp64 + r2c raises `ValueError` past 2^30 complex outputs and fp64 c2r on 2^31 or more + half-spectrum elements. ## Accuracy @@ -236,6 +244,34 @@ two-stream checks): The eight grids keep their plans and their outputs are bitwise unchanged. +Updated on 2026-10-27 with the fixes of a second audit on RTX 5090s and B300s +(threads, streams, CUDA graph capture, 32-bit limits; no wrong result was found +within 256 per axis): + +- Threads making first calls at once failed: CuTe DSL is not thread-safe while + it compiles or makes the first call of a TVM-FFI function. Concurrent plan + builds raised MLIR errors or ended the process, and two first calls of one + shape at once left a spin lock held, so that the next first call of any + kernel in the process hung for good. Plans are now built, and make their first + call, under one process-wide lock; later calls take none. +- The first call of a shape inside CUDA graph capture raised; its tables are + now copied on a stream of the package's own, outside the graph. +- A `launch()` right after `prepare_*` on another stream could run before work + still queued on `prepare_*`'s stream, which then overwrote its output, and a + launch object dropped before its kernels ran handed its buffers to new tensors + on `prepare_*`'s stream. Such a launch now waits for `prepare_*`'s stream and + keeps its buffers until its work is done; same-stream launches are unchanged. +- fp32 r2c transforms a contiguous input that is not 16-byte aligned from an + aligned copy instead of raising. +- fp64 r2c past 2^30 complex outputs (an illegal memory access) and fp64 c2r + on 2^31 or more half-spectrum elements (a wrong result) now raise + `ValueError`, beyond 256 per axis. +- fp64 axes of 1529 points and more whose big-prime tile does not fit in + shared memory failed to compile (such as 8x6329x16); they keep the direct + DFT. + +The eight grids keep their plans; their outputs and speeds are unchanged. + ## Source and licensing 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), and accepted by the KDA judge. Published from commit `e539498` of `humanfia/kda-kernels-internal`, directory `rtx5090/fft3d/` (now `sm120/fft3d/`), which also holds its tests and the fixes made after the -judge's checks; updated from commit `b0811f8` (see [Changes](#changes)). +judge's checks; updated from commits `b0811f8` and `2238a9e` (see +[Changes](#changes)). MIT-licensed. ## Available functions diff --git a/build/torch-cuda/__pycache__/__init__.cpython-312.pyc b/build/torch-cuda/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e0ed4b148fbe700852167d8d8a821a506e9746b6 Binary files /dev/null and b/build/torch-cuda/__pycache__/__init__.cpython-312.pyc differ diff --git a/build/torch-cuda/__pycache__/_build.cpython-312.pyc b/build/torch-cuda/__pycache__/_build.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..21443ddd2747c23bde9a1492c7508a4408801b2a Binary files /dev/null and b/build/torch-cuda/__pycache__/_build.cpython-312.pyc differ diff --git a/build/torch-cuda/_build.py b/build/torch-cuda/_build.py new file mode 100644 index 0000000000000000000000000000000000000000..88ccfbeca535f17314df5f44f23c45104ede85d4 --- /dev/null +++ b/build/torch-cuda/_build.py @@ -0,0 +1,87 @@ +"""Plan building for the fp32 kernel packages: under the CuTe lock all kda kernels share, and outside CUDA +graph capture.""" + +import contextlib +import threading + +import cuda.bindings.driver as cuda +import cutlass +import torch + +# CuTe DSL is not thread-safe while it compiles (also across packages) or, for --enable-tvm-ffi +# functions, while a function is first called: every kda kernel package shares this lock. +# (Concurrent compiles fail with MLIR errors or end the process; two first calls of one function at once +# leave a process-wide spin lock held, so the next first call of any CuTe function spins forever.) +# The fp32 packages build their plans, and make each plan's first call, under it; later calls take no lock. +_CUTE_LOCK = cutlass.__dict__.setdefault("_kda_compile_lock", threading.RLock()) +_SIDE = {} # device -> the private side stream plans are built on during a capture + + +def _private_stream(device): + """A stream of this module's own (cuStreamCreate, non-blocking), one per device. torch.cuda.Stream() hands out + one of a pool of 32 streams per device, which can be the very stream being captured (or another thread's).""" + side = _SIDE.get(device) + if side is None: + with torch.cuda.device(device): + err, h = cuda.cuStreamCreate(cuda.CUstream_flags.CU_STREAM_NON_BLOCKING.value) + if err != cuda.CUresult.CUDA_SUCCESS: + raise RuntimeError(f"cuStreamCreate failed: {err}") + side = _SIDE.setdefault(device, torch.cuda.ExternalStream(int(h), device=device)) + return side + + +@contextlib.contextmanager +def building(device): + """Hold _CUTE_LOCK while a plan is built. If the current stream is being captured into a CUDA graph (the + first call of a shape inside capture), the plan's tables are copied to the GPU now, on a side stream + with this thread in relaxed capture mode: they are filled before the first replay and stay valid + for eager calls (torch refuses pageable copies on a capturing stream).""" + with _CUTE_LOCK: + if not torch.cuda.is_current_stream_capturing(): + yield + return + err, mode = cuda.cuThreadExchangeStreamCaptureMode(cuda.CUstreamCaptureMode.CU_STREAM_CAPTURE_MODE_RELAXED) + if err != cuda.CUresult.CUDA_SUCCESS: + raise RuntimeError(f"fft3d: cuThreadExchangeStreamCaptureMode failed: {err}") + try: + side = _private_stream(torch.device(device)) + with torch.cuda.stream(side): + yield + side.synchronize() + finally: + cuda.cuThreadExchangeStreamCaptureMode(mode) + + +def first_call(plan, fn, *args): + """fn(*args), the first call of `plan`'s compiled functions, under _CUTE_LOCK; then marks the plan ready.""" + with _CUTE_LOCK: + fn(*args) + plan.ready = True + + +def stream_guard(device): + """For a launch object made by prepare(), made with no GPU work queued since prepare allocated its buffers: + guard(*buffers) at + each launch. The buffers come from the memory pool of the stream prepare ran on, so on another stream it + first waits until the work queued there before prepare has finished with that memory, then marks the + launch object's own buffers (output, workspaces) as used by its stream, so that dropping the launch + object before its kernels ran cannot hand their memory to a new allocation on prepare's stream while the + kernels still use it. (A capture cannot wait for outside work; torch.cuda.graph synchronizes before + capturing.) One integer compare on prepare's stream.""" + index = device.index + home = torch._C._cuda_getCurrentRawStream(index) + ready = None + if not torch.cuda.is_current_stream_capturing(): + ready = torch.cuda.Event() + ready.record(torch.cuda.current_stream(index)) + + def guard(*buffers): + if torch._C._cuda_getCurrentRawStream(index) != home: + stream = torch.cuda.current_stream(index) + if ready is not None and not torch.cuda.is_current_stream_capturing(): + stream.wait_event(ready) + for b in buffers: + if b is not None: + b.record_stream(stream) + + return guard diff --git a/build/torch-cuda/_c2r_f32/__pycache__/__init__.cpython-312.pyc b/build/torch-cuda/_c2r_f32/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a7f5943e65ad71be2945efdb8db375ed2cdb1d2f Binary files /dev/null and b/build/torch-cuda/_c2r_f32/__pycache__/__init__.cpython-312.pyc differ diff --git a/build/torch-cuda/_c2r_f32/__pycache__/anyfft.cpython-312.pyc b/build/torch-cuda/_c2r_f32/__pycache__/anyfft.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7196440529cc72873473b4dc23127ec15a4d8884 Binary files /dev/null and b/build/torch-cuda/_c2r_f32/__pycache__/anyfft.cpython-312.pyc differ diff --git a/build/torch-cuda/_c2r_f32/__pycache__/fftgen.cpython-312.pyc b/build/torch-cuda/_c2r_f32/__pycache__/fftgen.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d35caf4e10b43609e45c09b3fb277acc0d805b16 Binary files /dev/null and b/build/torch-cuda/_c2r_f32/__pycache__/fftgen.cpython-312.pyc differ diff --git a/build/torch-cuda/_c2r_f32/__pycache__/inplace.cpython-312.pyc b/build/torch-cuda/_c2r_f32/__pycache__/inplace.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..222e84a88bfb0c9796ca6af7695a1164793b8f71 Binary files /dev/null and b/build/torch-cuda/_c2r_f32/__pycache__/inplace.cpython-312.pyc differ diff --git a/build/torch-cuda/_c2r_f32/__pycache__/kernel.cpython-312.pyc b/build/torch-cuda/_c2r_f32/__pycache__/kernel.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dab13cdba98808ce88a8ca150f969dea1d5d8089 Binary files /dev/null and b/build/torch-cuda/_c2r_f32/__pycache__/kernel.cpython-312.pyc differ diff --git a/build/torch-cuda/_c2r_f32/__pycache__/tables.cpython-312.pyc b/build/torch-cuda/_c2r_f32/__pycache__/tables.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..47b5d8a6b424562a684cd9019f720347c82a1699 Binary files /dev/null and b/build/torch-cuda/_c2r_f32/__pycache__/tables.cpython-312.pyc differ diff --git a/build/torch-cuda/_c2r_f32/__pycache__/twopass.cpython-312.pyc b/build/torch-cuda/_c2r_f32/__pycache__/twopass.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4567b0082a9c546a8c644be4a8667197397bdd2a Binary files /dev/null and b/build/torch-cuda/_c2r_f32/__pycache__/twopass.cpython-312.pyc differ diff --git a/build/torch-cuda/_c2r_f32/anyfft.py b/build/torch-cuda/_c2r_f32/anyfft.py index 64be7a4430211a485c31e58533b5ec07aa89837a..36831a8b9f97bf2827ffd8b952b56941cb6aad70 100644 --- a/build/torch-cuda/_c2r_f32/anyfft.py +++ b/build/torch-cuda/_c2r_f32/anyfft.py @@ -25,7 +25,7 @@ import math import cutlass import torch -from cutlass import Float32, Int32, cute +from cutlass import Float32, cute from .fftgen import cmul, dft, ld_c, st_c @@ -374,7 +374,6 @@ def _col_nl(N, cap=None): if cap is not None: while NL > 8 and NL // 2 >= cap: NL //= 2 - plan = line_plan(N) nbuf = 1 while NL >= 4 and N * NL * 8 * nbuf + 2 * (N + 256) * 8 > _SMEM_LIMIT - 2048: NL //= 2 @@ -394,6 +393,7 @@ def _threads(NL, N, plan): w = max(work) if work else 64 return max(64, min(256, _cdiv(w, 32) * 32)) + class ZPassG: """z line FFTs over the C = ny * nf input columns; kx < M into u, kx = M into nyq.""" @@ -540,10 +540,8 @@ class YPassG: eng.emit(tid, A, stw, 0, store, None) def kernel(self): - nz, ny, M, NL, T = self.nz, self.ny, self.M, self.NL, self.T + nz, ny, NL, T = self.nz, self.ny, self.NL, self.T NU, NB = self.NU, self.NB - eng = self.eng - n_el = ny * NL TWF = self.table.numel() SF = ny * NL * 2 @@ -887,7 +885,13 @@ class AnyPlan: @cute.jit def launch3( - x: cute.Tensor, u: cute.Tensor, nq: cute.Tensor, tz: cute.Tensor, ty: cute.Tensor, tx: cute.Tensor, stream + x: cute.Tensor, + u: cute.Tensor, + nq: cute.Tensor, + tz: cute.Tensor, + ty: cute.Tensor, + tx: cute.Tensor, + stream, ): zk(x, u, nq, tz).launch(grid=(zp.grid, 1, 1), block=(zp.T, 1, 1), stream=stream) yk(u, nq, ty).launch(grid=(yp.grid, 1, 1), block=(yp.T, 1, 1), stream=stream, use_pdl=True) diff --git a/build/torch-cuda/_c2r_f32/kernel.py b/build/torch-cuda/_c2r_f32/kernel.py index 6509ef69a04086bde02dab5a8023d2b72b928964..f425efdca095a4cfac7b294acef0755aeedaa170 100644 --- a/build/torch-cuda/_c2r_f32/kernel.py +++ b/build/torch-cuda/_c2r_f32/kernel.py @@ -42,18 +42,16 @@ Routing (one plan per (shape, device), compiled on first use and cached): from __future__ import annotations -import threading - import torch from cutlass import Float32, cute +from .._build import building, first_call, stream_guard from .anyfft import AnyPlan, any_config from .fftgen import factor2 from .inplace import XPassIP, YPassIP, YXFusedIP, ZPassIP from .twopass import TwoPassPlan, two_pass_config _SMEM_LIMIT = 99 * 1024 -_LOCK = threading.Lock() _PLANS: dict = {} @@ -233,7 +231,7 @@ def _get_plan(nz, ny, nx, device): plan = _PLANS.get(key) if plan is not None: return plan - with _LOCK: + with building(device): plan = _PLANS.get(key) if plan is None: cfg = _fast_config(nz, ny, nx) @@ -252,10 +250,18 @@ def _get_plan(nz, ny, nx, device): from .generic import GenericPlan # only shapes no other path can plan need it plan = GenericPlan(nz, ny, nx, device) + plan.ready = False # made its first call (under the build lock: see _build.first_call) _PLANS[key] = plan return plan +def _launch(plan, *args): + if plan.ready: + plan(*args) + else: + first_call(plan, plan, *args) + + def _check(input): if input.dim() != 4 or input.shape[-1] != 2: raise ValueError("input must be [nz, ny, nf, 2]") @@ -276,24 +282,28 @@ def _prepare(input): extra = () if hasattr(plan, "nyq_numel"): extra = (torch.empty(plan.nyq_numel, dtype=torch.float32, device=input.device),) + guard = stream_guard(input.device) if input.is_contiguous() and input.data_ptr() % 16 == 0: x_flat = input.view(-1) def launch(): - plan(x_flat, out_flat, *extra) + guard(out, *extra) + _launch(plan, x_flat, out_flat, *extra) return out elif input.is_contiguous(): # kernels assume a 16-byte aligned input; stage misaligned views stage = torch.empty(input.numel(), dtype=torch.float32, device=input.device) def launch(): + guard(out, stage, *extra) stage.copy_(input.view(-1)) - plan(stage, out_flat, *extra) + _launch(plan, stage, out_flat, *extra) return out else: def launch(): - plan(input.contiguous().view(-1), out_flat, *extra) + guard(out, *extra) + _launch(plan, input.contiguous().view(-1), out_flat, *extra) return out return launch @@ -331,7 +341,7 @@ def run(input): plan = _get_plan(nz, ny, nx, dev) out = torch.empty((nz, ny, nx), dtype=torch.float32, device=dev) if hasattr(plan, "nyq_numel"): - plan(input.view(-1), out.view(-1), torch.empty(plan.nyq_numel, dtype=torch.float32, device=dev)) + _launch(plan, input.view(-1), out.view(-1), torch.empty(plan.nyq_numel, dtype=torch.float32, device=dev)) else: - plan(input.view(-1), out.view(-1)) + _launch(plan, input.view(-1), out.view(-1)) return out diff --git a/build/torch-cuda/_c2r_f64/__pycache__/__init__.cpython-312.pyc b/build/torch-cuda/_c2r_f64/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..71129efdf5de7157b70a9eae07cf18934353e853 Binary files /dev/null and b/build/torch-cuda/_c2r_f64/__pycache__/__init__.cpython-312.pyc differ diff --git a/build/torch-cuda/_c2r_f64/__pycache__/bigprime.cpython-312.pyc b/build/torch-cuda/_c2r_f64/__pycache__/bigprime.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..939edc99f5cb2957d329eed044a0a771c0deac69 Binary files /dev/null and b/build/torch-cuda/_c2r_f64/__pycache__/bigprime.cpython-312.pyc differ diff --git a/build/torch-cuda/_c2r_f64/__pycache__/fftgen.cpython-312.pyc b/build/torch-cuda/_c2r_f64/__pycache__/fftgen.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0984b73934b36940e668abb0a182ea47bb8152be Binary files /dev/null and b/build/torch-cuda/_c2r_f64/__pycache__/fftgen.cpython-312.pyc differ diff --git a/build/torch-cuda/_c2r_f64/__pycache__/kernel.cpython-312.pyc b/build/torch-cuda/_c2r_f64/__pycache__/kernel.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6bac73575faa9ee46ee3c26a311021423c926e40 --- /dev/null +++ b/build/torch-cuda/_c2r_f64/__pycache__/kernel.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:553f5dd4062e171bda3a28bdb6fc21430ea89e184c5eb624bce7e125251d8da3 +size 177493 diff --git a/build/torch-cuda/_c2r_f64/__pycache__/softfp.cpython-312.pyc b/build/torch-cuda/_c2r_f64/__pycache__/softfp.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..189ed7207ec21d2c8b1260b6e80e4decf81fea5b Binary files /dev/null and b/build/torch-cuda/_c2r_f64/__pycache__/softfp.cpython-312.pyc differ diff --git a/build/torch-cuda/_c2r_f64/__pycache__/twiddles.cpython-312.pyc b/build/torch-cuda/_c2r_f64/__pycache__/twiddles.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..860029eb7b7ed1b56e0298b35d9b6aad28f2751d Binary files /dev/null and b/build/torch-cuda/_c2r_f64/__pycache__/twiddles.cpython-312.pyc differ diff --git a/build/torch-cuda/_c2r_f64/bigprime.py b/build/torch-cuda/_c2r_f64/bigprime.py index d3fac3413cdf691a7fa73d535f0f1cd27a516e14..ff448d5cb3283e717e74e15ccb4740d23cc78de9 100644 --- a/build/torch-cuda/_c2r_f64/bigprime.py +++ b/build/torch-cuda/_c2r_f64/bigprime.py @@ -84,8 +84,22 @@ def split(n): return P, m +# the most shared memory one CTA can have on the RTX 5090 +SMEM_MAX = 99 * 1024 + + def supported(n): - return split(n) is not None + """n has a big-prime split whose one-sequence tile fits in a CTA's shared memory (PassCfg._smem, + S = 1, for the direct sums and for the model's convolution); longer axes keep the direct DFT.""" + sp = split(n) + if sp is None: + return False + P, m = sp + meth, L, _ = p_stage_method(P) + need = (2 * n + P) * 16 + 64 + if meth != "direct": + need = max(need, (2 * max(n, m * L) + 2 * m) * 16 + 64) + return need <= SMEM_MAX _PI = Decimal("3.14159265358979323846264338327950288419716939937510582097494459230781640628620899") diff --git a/build/torch-cuda/_c2r_f64/kernel.py b/build/torch-cuda/_c2r_f64/kernel.py index 8cf470a243f1ec3d25488dbcdc0b597cdcec6e98..af335ebaefc2e564ff805cab8e35a88096909d0c 100644 --- a/build/torch-cuda/_c2r_f64/kernel.py +++ b/build/torch-cuda/_c2r_f64/kernel.py @@ -35,6 +35,7 @@ NaN may carry another payload), so where an addition runs changes no result. # ruff: noqa: SIM102 import math +import threading import cuda.bindings.driver as cuda import cutlass @@ -2726,7 +2727,8 @@ def _make_passC_loop(yzd, ny, M, S, NT, soft, twnc_off, PDL, U, POL): def _has_plan(n): - return bool(_radix_lists(n)) + # an axis of length 1 has no stages to plan; a grid with one takes the direct passes + return n > 1 and bool(_radix_lists(n)) def make_kernels_direct(nz, ny, M): @@ -2837,7 +2839,39 @@ def make_tables_2d(nz, ny, M, yzd): return torch.cat([make_tables(nz, ny, M), yzd.nc_table(), yzd.twiddle_table()]) +# CuTe DSL is not thread-safe while it compiles (also across packages) or, for --enable-tvm-ffi +# functions, while a function is first called: every kda kernel package shares this lock. +_CUTE_LOCK = cutlass.__dict__.setdefault("_kda_compile_lock", threading.RLock()) + +_raw_stream = torch._C._cuda_getCurrentRawStream # device index -> current stream handle _PLANS = {} +_SIDE = {} # device -> stream that uploads tables while a CUDA graph is being captured + + +def _outside_capture(fn, device): + """fn() while the current stream is capturing a CUDA graph (the first call of a shape), without + adding its copies to the graph, which torch refuses from pageable memory: it runs on a private + side stream with this thread in relaxed capture mode and has completed before this returns, so + the plan's tables serve the graph and later eager calls alike.""" + err, prev = cuda.cuThreadExchangeStreamCaptureMode(cuda.CUstreamCaptureMode.CU_STREAM_CAPTURE_MODE_RELAXED) + if err != cuda.CUresult.CUDA_SUCCESS: + raise RuntimeError(f"cuThreadExchangeStreamCaptureMode failed: {err}") + try: + side = _SIDE.get(device) + if side is None: + # a stream of its own: torch.cuda.Stream() hands out one of a pool of 32 per device, which can be + # the very stream being captured + with torch.cuda.device(device): + err, h = cuda.cuStreamCreate(cuda.CUstream_flags.CU_STREAM_NON_BLOCKING.value) + if err != cuda.CUresult.CUDA_SUCCESS: + raise RuntimeError(f"cuStreamCreate failed: {err}") + side = _SIDE.setdefault(device, torch.cuda.ExternalStream(int(h), device=device)) + with torch.cuda.stream(side): + res = fn() + side.synchronize() + finally: + cuda.cuThreadExchangeStreamCaptureMode(prev) + return res def _fake(n): @@ -2875,7 +2909,10 @@ class _Plan: tables = make_tables_2d(nz, ny, M, YZ2D(ny, yz["A"], yz["rc"], yz.get("N1", 1))) else: tables = torch.cat([make_tables(nz, ny, M)] + [cfg.table() for cfg in big.values()]) - self.tables = tables.to(device).contiguous() + if torch.cuda.is_current_stream_capturing(): + self.tables = _outside_capture(lambda: tables.to(device).contiguous(), device) + else: + self.tables = tables.to(device).contiguous() nx_, no_ = nz * ny * nf * 2, nz * ny * M * 2 args = [_fake(nx_), _fake(no_), _fake(self.tables.numel())] if self.direct: @@ -2884,36 +2921,48 @@ class _Plan: # few microseconds of host time (the shapes and the 16-byte alignment are checked at the call) stream = cute.runtime.make_fake_stream(use_tvm_ffi_env_stream=True) self.fn = cute.compile(launch, *args, stream, options="--enable-tvm-ffi") + self.loaded = False # self.fn has been called once (under _CUTE_LOCK) + + def _call(self, *args): + if not self.loaded: + with _CUTE_LOCK: + self.fn(*args) + self.loaded = True + return + self.fn(*args) def bind(self, xin, out): - xf, of, fn, tw = xin.view(-1), out.view(-1), self.fn, self.tables + xf, of, tw = xin.view(-1), out.view(-1), self.tables if self.direct: ws = torch.empty_like(of) def go(): - fn(xf, of, tw, ws) + (self.fn if self.loaded else self._call)(xf, of, tw, ws) go.ws = ws return go def go(): - fn(xf, of, tw) + (self.fn if self.loaded else self._call)(xf, of, tw) return go def run_into(self, xin, out): + fn = self.fn if self.loaded else self._call if self.direct: - self.fn(xin.view(-1), out.view(-1), self.tables, torch.empty_like(out).view(-1)) + fn(xin.view(-1), out.view(-1), self.tables, torch.empty_like(out).view(-1)) else: - self.fn(xin.view(-1), out.view(-1), self.tables) + fn(xin.view(-1), out.view(-1), self.tables) def _get_plan(nz, ny, nf, device): key = (nz, ny, nf, device) p = _PLANS.get(key) if p is None: - p = _Plan(nz, ny, nf, device) - _PLANS[key] = p + with _CUTE_LOCK: + p = _PLANS.get(key) + if p is None: + p = _PLANS[key] = _Plan(nz, ny, nf, device) return p @@ -2924,12 +2973,17 @@ def _check(x): raise TypeError(f"this c2r takes float64, not {x.dtype}") if x.dim() != 4 or x.shape[-1] != 2 or min(x.shape[:2]) < 1 or x.shape[2] < 2: raise ValueError(f"c2r takes a [nz, ny, nf, 2] half-spectrum with nf >= 2, not {tuple(x.shape)}") + if x.shape[0] * x.shape[1] * x.shape[2] >= 2**31: + # the kernels index complex elements with 32-bit offsets + raise ValueError("the half-spectrum has 2^31 or more complex elements, which the kernels cannot address") def run(input): """Inverse real 3D FFT of input (float64 [nz, ny, nf, 2]) into a new float64 [nz, ny, 2*(nf-1)].""" + _check(input) x = input.contiguous() - _check(x) + if x.is_neg(): # a negated view (torch's neg bit): the kernels read the stored values + x = x.resolve_neg() nz, ny, nf, _ = x.shape plan = _get_plan(nz, ny, nf, x.device) if x.data_ptr() % 16: @@ -2946,12 +3000,32 @@ def prepare(input): raise ValueError("prepare binds the input buffer itself, so it must be contiguous") if input.data_ptr() % 16: raise ValueError("prepare binds the input buffer itself, so it must be 16-byte aligned") + if input.is_neg(): + raise ValueError("prepare binds the input buffer itself, so it cannot be a negated view (resolve_neg() it)") nz, ny, nf, _ = input.shape plan = _get_plan(nz, ny, nf, input.device) out = torch.empty((nz, ny, 2 * (nf - 1)), dtype=torch.float64, device=input.device) go = plan.bind(input, out) + # out (and the direct passes' workspace) come from this stream's memory pool: a launch on another + # stream waits until this stream's work queued before prepare has finished with that memory, and + # marks the buffers as used by its stream, so that dropping the launch early cannot hand them back + # to this stream while its kernels run. (A capture cannot wait for outside work; torch.cuda.graph + # synchronizes before capturing.) + dev = input.get_device() + home = _raw_stream(dev) + ready = None + if not torch.cuda.is_current_stream_capturing(): + ready = torch.cuda.Event() + ready.record() + buffers = (out, go.ws) if hasattr(go, "ws") else (out,) def launch(): + if _raw_stream(dev) != home: + stream = torch.cuda.current_stream(dev) + if ready is not None and not torch.cuda.is_current_stream_capturing(): + stream.wait_event(ready) + for t in buffers: + t.record_stream(stream) go() return out diff --git a/build/torch-cuda/_r2c_f32/__pycache__/__init__.cpython-312.pyc b/build/torch-cuda/_r2c_f32/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8ca0a7d34721354e4d35755577236bfa252e7b70 Binary files /dev/null and b/build/torch-cuda/_r2c_f32/__pycache__/__init__.cpython-312.pyc differ diff --git a/build/torch-cuda/_r2c_f32/__pycache__/fft3k.cpython-312.pyc b/build/torch-cuda/_r2c_f32/__pycache__/fft3k.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ce481aac107566f236669c30351b37ee6d52fe0f Binary files /dev/null and b/build/torch-cuda/_r2c_f32/__pycache__/fft3k.cpython-312.pyc differ diff --git a/build/torch-cuda/_r2c_f32/__pycache__/fft_core.cpython-312.pyc b/build/torch-cuda/_r2c_f32/__pycache__/fft_core.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..026e7df994b201267e82ca6d8896ce8ee158c206 Binary files /dev/null and b/build/torch-cuda/_r2c_f32/__pycache__/fft_core.cpython-312.pyc differ diff --git a/build/torch-cuda/_r2c_f32/__pycache__/fft_gen.cpython-312.pyc b/build/torch-cuda/_r2c_f32/__pycache__/fft_gen.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..52483f27de5a398f4ab3eebabfaf1dffeda3a164 Binary files /dev/null and b/build/torch-cuda/_r2c_f32/__pycache__/fft_gen.cpython-312.pyc differ diff --git a/build/torch-cuda/_r2c_f32/__pycache__/fft_generic.cpython-312.pyc b/build/torch-cuda/_r2c_f32/__pycache__/fft_generic.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..16ea424fbcc929ed86f07afb17edb6f19bcda81a Binary files /dev/null and b/build/torch-cuda/_r2c_f32/__pycache__/fft_generic.cpython-312.pyc differ diff --git a/build/torch-cuda/_r2c_f32/__pycache__/fft_plane2.cpython-312.pyc b/build/torch-cuda/_r2c_f32/__pycache__/fft_plane2.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cfeabfb424f3a0b31f0d1a78d6251c08d88191fe Binary files /dev/null and b/build/torch-cuda/_r2c_f32/__pycache__/fft_plane2.cpython-312.pyc differ diff --git a/build/torch-cuda/_r2c_f32/__pycache__/fft_xy.cpython-312.pyc b/build/torch-cuda/_r2c_f32/__pycache__/fft_xy.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..122452e00a9fc78a890373f420ac4a4cedbb7dcf Binary files /dev/null and b/build/torch-cuda/_r2c_f32/__pycache__/fft_xy.cpython-312.pyc differ diff --git a/build/torch-cuda/_r2c_f32/__pycache__/fft_ys1w.cpython-312.pyc b/build/torch-cuda/_r2c_f32/__pycache__/fft_ys1w.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ea52b7cac3f4821d884f16d0da6e0252d6e03349 Binary files /dev/null and b/build/torch-cuda/_r2c_f32/__pycache__/fft_ys1w.cpython-312.pyc differ diff --git a/build/torch-cuda/_r2c_f32/__pycache__/fft_ysplit.cpython-312.pyc b/build/torch-cuda/_r2c_f32/__pycache__/fft_ysplit.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c260a4b8755989a1e7229656e307d6c544904768 Binary files /dev/null and b/build/torch-cuda/_r2c_f32/__pycache__/fft_ysplit.cpython-312.pyc differ diff --git a/build/torch-cuda/_r2c_f32/__pycache__/kernel.cpython-312.pyc b/build/torch-cuda/_r2c_f32/__pycache__/kernel.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f33644d9420db6e6ee592d94320f09992f6b9061 Binary files /dev/null and b/build/torch-cuda/_r2c_f32/__pycache__/kernel.cpython-312.pyc differ diff --git a/build/torch-cuda/_r2c_f32/__pycache__/plan.cpython-312.pyc b/build/torch-cuda/_r2c_f32/__pycache__/plan.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..75a98d340e83335894fdc1887e220fa1a938f6f9 Binary files /dev/null and b/build/torch-cuda/_r2c_f32/__pycache__/plan.cpython-312.pyc differ diff --git a/build/torch-cuda/_r2c_f32/__pycache__/ptx.cpython-312.pyc b/build/torch-cuda/_r2c_f32/__pycache__/ptx.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3052e5a0ca0f82bc740b9f9a4a234edc22bdb5f8 Binary files /dev/null and b/build/torch-cuda/_r2c_f32/__pycache__/ptx.cpython-312.pyc differ diff --git a/build/torch-cuda/_r2c_f32/__pycache__/stockham.cpython-312.pyc b/build/torch-cuda/_r2c_f32/__pycache__/stockham.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ecb2f2cf2f8017dc6450d0f3d7d90b3e0c860e2a Binary files /dev/null and b/build/torch-cuda/_r2c_f32/__pycache__/stockham.cpython-312.pyc differ diff --git a/build/torch-cuda/_r2c_f32/fft_gen.py b/build/torch-cuda/_r2c_f32/fft_gen.py index 604edaa0134711249b3004d57b289483e1cfcdb0..1dbc3d99d3eb716cfe90d8844688845595902692 100644 --- a/build/torch-cuda/_r2c_f32/fft_gen.py +++ b/build/torch-cuda/_r2c_f32/fft_gen.py @@ -22,14 +22,14 @@ import math import cutlass import torch from cutlass import Float32, Int32, Int64, cute +from cutlass.cutlass_dsl import T as _T +from cutlass.cutlass_dsl import dsl_user_op from .fft_core import as_f32 from .plan import SMEM_LIMIT, Layout, choose_layout, lanes_groups, line_plan_cost, line_plans from .ptx import _asm, _iv, ldg2, ldg4, lds2, lds4, stg2, stg2_if, stg4, stg4_if, sts2, sts2_if, sts4, sts4_if from .stockham import TwSmem, access_offsets, and_pv, b2i, bfly, emit_fft, fsel, lay_off -from cutlass.cutlass_dsl import T as _T, dsl_user_op - @dsl_user_op def lds1(addr, *, loc=None, ip=None): @@ -485,7 +485,7 @@ def make_gx_kernel(cfg): blk_in = gin + Int64(r0) * (nx * 4) # ---- coalesced copy-in of the row block (rows * nx floats, contiguous) n4 = None - if (tail): + if tail: nv = cutlass.min(Int32(nrows) - r0, Int32(rows)) n4 = (nv * nx) // 4 for i in range(-(-in_f4 // NT)): @@ -503,7 +503,7 @@ def make_gx_kernel(cfg): sts4(sbase + f * 16, v) else: sts4_if(pv, sbase + f * 16, v) - if (rem_scalars != 0): + if rem_scalars != 0: # the last 1..3 floats of the tensor (only the last block reaches them) last0 = ntot - rem_scalars for s in range(rem_scalars): @@ -516,13 +516,13 @@ def make_gx_kernel(cfg): pr = tid // T t = tid % T - if (cfg.nt != NT): + if cfg.nt != NT: pr = cutlass.min(pr, Int32(cfg.prs - 1)) t = cutlass.min(t, Int32(T - 1)) ra = sbase + (2 * pr) * (nx * 4) rb = ra + nx * 4 bok = None - if (nrows % 2 == 1): + if nrows % 2 == 1: bok = b2i(r0 + 2 * pr + 1 < nrows) def load(idx): @@ -583,7 +583,7 @@ def make_gx_kernel(cfg): out_f4 = rows * nf // 2 blk_out = gout + Int64(r0) * (nf * 8) lim = None - if (tail): + if tail: nv2 = cutlass.min(Int32(nrows) - r0, Int32(rows)) lim = (nv2 * nf) // 2 for i in range(-(-out_f4 // NT)): @@ -601,7 +601,7 @@ def make_gx_kernel(cfg): stg4(blk_out + Int64(f) * 16, v) else: stg4_if(pv, blk_out + Int64(f) * 16, v) - if (tail and (nrows % rows) * nf % 2 == 1): + if tail and (nrows % rows) * nf % 2 == 1: nv3 = cutlass.min(Int32(nrows) - r0, Int32(rows)) last = nv3 * nf - 1 q = b2i(tid == 0) & b2i((nv3 * nf) % 2 == 1) @@ -709,17 +709,17 @@ def make_gcol_kernel(cfg, trigger=False): c = tid % W t = tid // W valid = None - if (cfg.nt != NT): + if cfg.nt != NT: valid = b2i(tid < cfg.nt) t = cutlass.min(t, Int32(T - 1)) - if (cfg.nouter > 1): + if cfg.nouter > 1: outer = bid // cfg.tpo tile = bid - outer * cfg.tpo else: outer = Int32(0) tile = bid g = tile * W + c - if (tail): + if tail: ok = b2i(g < cfg.ngroups) valid = ok if valid is None else (valid & ok) g = cutlass.min(g, Int32(cfg.ngroups - 1)) @@ -734,7 +734,7 @@ def make_gcol_kernel(cfg, trigger=False): cute.arch.sync_threads() raw = eng.prefetch(t, load) - if (eng.blue or len(eng.plan.passes) == 1): + if eng.blue or len(eng.plan.passes) == 1: cute.arch.sync_threads() mean = None if eng.needs_mean: diff --git a/build/torch-cuda/_r2c_f32/kernel.py b/build/torch-cuda/_r2c_f32/kernel.py index 6dcbbe10be0844a5e221db0f0feebe8163807ed1..fa04d6895e6229ea738c6e17956b07728f9e75b1 100644 --- a/build/torch-cuda/_r2c_f32/kernel.py +++ b/build/torch-cuda/_r2c_f32/kernel.py @@ -41,6 +41,7 @@ import cutlass import torch from cutlass import cute +from .._build import building, first_call, stream_guard from .fft3k import ColCfg, XCfg, make_col_kernel, make_x_kernel from .fft_gen import GColCfg, GXCfg, make_gcol_kernel, make_gx_kernel from .fft_generic import make_generic_col_kernel, make_generic_x_kernel, twiddle_f64 @@ -242,6 +243,7 @@ class _Plan: self.shape = (nz, ny, nx) self.device = device self.sync_words = 0 + self.ready = False # made its first call (under the build lock: see _build.first_call) if strategy is None: strategy = _default_strategy(nz, ny, nx) self.strategy = strategy @@ -338,13 +340,19 @@ class _Plan: lambda i, o: kz(o, self.tw), ] - def run(self, inp_flat, out_flat): + def run(self, *args): + """The transform: run(inp_flat, out_flat), or run(inp_flat, out_flat, sync) if sync_words.""" + if not self.ready: + first_call(self, self._steps, *args) + return for f in self.steps: - f(inp_flat, out_flat) + f(*args) - def run_sync(self, inp_flat, out_flat, sync): + run_sync = run + + def _steps(self, *args): for f in self.steps: - f(inp_flat, out_flat, sync) + f(*args) _PLANS = {} @@ -354,12 +362,15 @@ def _get_plan(shape, device): key = (tuple(shape), str(device)) pl = _PLANS.get(key) if pl is None: - nz, ny, nx = shape - try: - pl = _Plan(nz, ny, nx, device) - except Exception: # noqa: BLE001 -- a fast plan that fails to build or compile falls back to generic - pl = _Plan(nz, ny, nx, device, strategy="generic") - _PLANS[key] = pl + with building(device): + pl = _PLANS.get(key) + if pl is None: + nz, ny, nx = shape + try: + pl = _Plan(nz, ny, nx, device) + except Exception: # noqa: BLE001 -- a fast plan that fails to build or compile falls back to generic + pl = _Plan(nz, ny, nx, device, strategy="generic") + _PLANS[key] = pl return pl @@ -382,25 +393,32 @@ def prepare(input): out = torch.empty((nz, ny, nx // 2 + 1, 2), device=input.device, dtype=torch.float32) inp_flat = input.view(-1) out_flat = out.view(-1) + stage = None + if input.data_ptr() % 16: + # the kernels load the input in 16-byte vectors: a misaligned buffer is transformed from an aligned copy + src, stage = inp_flat, torch.empty_like(inp_flat) + inp_flat = stage + # Sync scratch per launch object, so launches of one shape on different streams never share it; zeroed + # here, before the stream guard, so that it is prepare's like the output (the kernels re-arm it on exit + # for the next launch, which writes the same output and so is stream-ordered after this one). + sync = torch.zeros(pl.sync_words, dtype=torch.int32, device=out.device) if pl.sync_words else None + guard = stream_guard(input.device) if not pl.sync_words: def launch(): + guard(out, stage) + if stage is not None: + stage.copy_(src) pl.run(inp_flat, out_flat) return out return launch - # Sync scratch per launch object, so launches of one shape on different streams - # never share it. It is zeroed on the stream of the first launch (ordered before - # it); the kernels re-arm it on exit for the next launch, which writes the same - # output and so is stream-ordered after this one. - sync = None - def launch(): - nonlocal sync - if sync is None: - sync = torch.zeros(pl.sync_words, dtype=torch.int32, device=out.device) + guard(out, stage, sync) + if stage is not None: + stage.copy_(src) pl.run_sync(inp_flat, out_flat, sync) return out @@ -412,6 +430,8 @@ def run(input): _reject(input) nz, ny, nx = input.shape pl = _get_plan((nz, ny, nx), input.device) + if input.data_ptr() % 16: + input = input.clone() # the kernels load the input in 16-byte vectors; a fresh copy is aligned if pl.sync_words: return prepare(input)() # the common case without building a launch closure: per-call overhead counts on small grids diff --git a/build/torch-cuda/_r2c_f32/plan.py b/build/torch-cuda/_r2c_f32/plan.py index 95ebcb6c37c6b0504a663e2e974a0cd4cfd55bd4..ba038d1aef91f603482cfc86d85ecbba7a54bf76 100644 --- a/build/torch-cuda/_r2c_f32/plan.py +++ b/build/torch-cuda/_r2c_f32/plan.py @@ -191,8 +191,10 @@ class TwiddleBuilder: p.tw_off = self.add_roots([(k * m) % L for k in range(p.Ns) for m in range(p.R)], L) def array(self): - """float32 CPU tensor [re0, im0, re1, im1, ...].""" - return torch.tensor(self.vals, dtype=torch.float64).reshape(-1).to(torch.float32) + """float32 CPU tensor [re0, im0, re1, im1, ...], padded to whole 16-byte chunks: the + kernels stage tables two entries at a time, so an odd last table reads one entry past it.""" + vals = self.vals + [(0.0, 0.0)] * (len(self.vals) % 2) + return torch.tensor(vals, dtype=torch.float64).reshape(-1).to(torch.float32) # ----------------------------------------------------------------------------- smem layouts diff --git a/build/torch-cuda/_r2c_f64/__pycache__/__init__.cpython-312.pyc b/build/torch-cuda/_r2c_f64/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..58211a61270f5feea073be95d6cafdafd4a066e2 Binary files /dev/null and b/build/torch-cuda/_r2c_f64/__pycache__/__init__.cpython-312.pyc differ diff --git a/build/torch-cuda/_r2c_f64/__pycache__/bigprime.cpython-312.pyc b/build/torch-cuda/_r2c_f64/__pycache__/bigprime.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..48b604ca0aa83da3955184d6ab3f919b8ebf5db7 Binary files /dev/null and b/build/torch-cuda/_r2c_f64/__pycache__/bigprime.cpython-312.pyc differ diff --git a/build/torch-cuda/_r2c_f64/__pycache__/dsl_ops.cpython-312.pyc b/build/torch-cuda/_r2c_f64/__pycache__/dsl_ops.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b914401ceacb71223838a0eceed21ed1568c8cad Binary files /dev/null and b/build/torch-cuda/_r2c_f64/__pycache__/dsl_ops.cpython-312.pyc differ diff --git a/build/torch-cuda/_r2c_f64/__pycache__/fft_codelets.cpython-312.pyc b/build/torch-cuda/_r2c_f64/__pycache__/fft_codelets.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ece5b97dd2362a70041448cbf5704ab478ffeba3 Binary files /dev/null and b/build/torch-cuda/_r2c_f64/__pycache__/fft_codelets.cpython-312.pyc differ diff --git a/build/torch-cuda/_r2c_f64/__pycache__/fft_direct.cpython-312.pyc b/build/torch-cuda/_r2c_f64/__pycache__/fft_direct.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c546629c1365e622e99e7c1f875d52dfd1087ecb Binary files /dev/null and b/build/torch-cuda/_r2c_f64/__pycache__/fft_direct.cpython-312.pyc differ diff --git a/build/torch-cuda/_r2c_f64/__pycache__/fft_passes.cpython-312.pyc b/build/torch-cuda/_r2c_f64/__pycache__/fft_passes.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7c001b03d8366a7d2008ce5788c23a410a418711 Binary files /dev/null and b/build/torch-cuda/_r2c_f64/__pycache__/fft_passes.cpython-312.pyc differ diff --git a/build/torch-cuda/_r2c_f64/__pycache__/fft_plan.cpython-312.pyc b/build/torch-cuda/_r2c_f64/__pycache__/fft_plan.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3088d9f9eb80dca018fadaa716d3ccc237fb62f4 Binary files /dev/null and b/build/torch-cuda/_r2c_f64/__pycache__/fft_plan.cpython-312.pyc differ diff --git a/build/torch-cuda/_r2c_f64/__pycache__/fft_stages.cpython-312.pyc b/build/torch-cuda/_r2c_f64/__pycache__/fft_stages.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2b862c7796f03b1b16c0737f4b0a64f09c07154b Binary files /dev/null and b/build/torch-cuda/_r2c_f64/__pycache__/fft_stages.cpython-312.pyc differ diff --git a/build/torch-cuda/_r2c_f64/__pycache__/fftgen.cpython-312.pyc b/build/torch-cuda/_r2c_f64/__pycache__/fftgen.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ae7ec27daad66f66dee4ce96dcb4d9bae797a3cb Binary files /dev/null and b/build/torch-cuda/_r2c_f64/__pycache__/fftgen.cpython-312.pyc differ diff --git a/build/torch-cuda/_r2c_f64/__pycache__/kernel.cpython-312.pyc b/build/torch-cuda/_r2c_f64/__pycache__/kernel.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8f988b9330ad2d402139ea8ea00925fda3266a6e Binary files /dev/null and b/build/torch-cuda/_r2c_f64/__pycache__/kernel.cpython-312.pyc differ diff --git a/build/torch-cuda/_r2c_f64/__pycache__/planner.cpython-312.pyc b/build/torch-cuda/_r2c_f64/__pycache__/planner.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..33a46af8ad4bb8a8f0a767ea9543388b265a160d Binary files /dev/null and b/build/torch-cuda/_r2c_f64/__pycache__/planner.cpython-312.pyc differ diff --git a/build/torch-cuda/_r2c_f64/__pycache__/tuned.cpython-312.pyc b/build/torch-cuda/_r2c_f64/__pycache__/tuned.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..88d2675396c3173775a1baa8aa4d3cb720ca0a06 Binary files /dev/null and b/build/torch-cuda/_r2c_f64/__pycache__/tuned.cpython-312.pyc differ diff --git a/build/torch-cuda/_r2c_f64/bigprime.py b/build/torch-cuda/_r2c_f64/bigprime.py index d3fac3413cdf691a7fa73d535f0f1cd27a516e14..ff448d5cb3283e717e74e15ccb4740d23cc78de9 100644 --- a/build/torch-cuda/_r2c_f64/bigprime.py +++ b/build/torch-cuda/_r2c_f64/bigprime.py @@ -84,8 +84,22 @@ def split(n): return P, m +# the most shared memory one CTA can have on the RTX 5090 +SMEM_MAX = 99 * 1024 + + def supported(n): - return split(n) is not None + """n has a big-prime split whose one-sequence tile fits in a CTA's shared memory (PassCfg._smem, + S = 1, for the direct sums and for the model's convolution); longer axes keep the direct DFT.""" + sp = split(n) + if sp is None: + return False + P, m = sp + meth, L, _ = p_stage_method(P) + need = (2 * n + P) * 16 + 64 + if meth != "direct": + need = max(need, (2 * max(n, m * L) + 2 * m) * 16 + 64) + return need <= SMEM_MAX _PI = Decimal("3.14159265358979323846264338327950288419716939937510582097494459230781640628620899") diff --git a/build/torch-cuda/_r2c_f64/fft_passes.py b/build/torch-cuda/_r2c_f64/fft_passes.py index 4cb9401ab641a6e906b9d59af23b99f26ef271ed..ee901f44bbb221f8f80ee54cfdc8187bec395722 100644 --- a/build/torch-cuda/_r2c_f64/fft_passes.py +++ b/build/torch-cuda/_r2c_f64/fft_passes.py @@ -221,15 +221,16 @@ def _setup_stagger(ctx, cfg, warp): def nthr(r): # threads meeting at barrier r (ranks r-1 and r) return 32 * (min(4, W - 4 * (r - 1)) + min(4, W - 4 * r)) + # barrier.sync / barrier.arrive without .aligned (bar.sync is barrier.sync.aligned): the warps + # of a rank meet at barrier r from different instructions, a working tile's and an idle one's + # (_guard_tile), which the aligned form does not allow def before(): for r in range(1, nr): - cutlass.if_generate(rank == r, lambda r=r: cute.arch.barrier(barrier_id=r, number_of_threads=nthr(r))) + cutlass.if_generate(rank == r, lambda r=r: cute.arch.inline_ptx(f"barrier.sync {r}, {nthr(r)};")) def after(): for r in range(nr - 1): - cutlass.if_generate( - rank == r, lambda r=r: cute.arch.barrier_arrive(barrier_id=r + 1, number_of_threads=nthr(r + 1)) - ) + cutlass.if_generate(rank == r, lambda r=r: cute.arch.inline_ptx(f"barrier.arrive {r + 1}, {nthr(r + 1)};")) ctx.before_first_loads = before ctx.after_first_loads = after diff --git a/build/torch-cuda/_r2c_f64/kernel.py b/build/torch-cuda/_r2c_f64/kernel.py index 11f952643196d324feb71897b72db3005b5bba7c..752914eb8d3215af7c1deadc26c1f15382607ffc 100644 --- a/build/torch-cuda/_r2c_f64/kernel.py +++ b/build/torch-cuda/_r2c_f64/kernel.py @@ -40,7 +40,10 @@ Calls made while a CUDA graph is being captured get a buffer of their own per ca stream, zeroed outside the graph, so concurrent graph replays never share one either. """ +import threading + import cuda.bindings.driver as cuda +import cutlass import torch from cutlass import cute from cutlass.cute.runtime import from_dlpack @@ -51,12 +54,17 @@ from .fft_passes import FLAG_PAD, build_colpass, build_r2c, build_r2c_pack2 from .planner import default_cfgs from .tuned import TUNED +# CuTe DSL is not thread-safe while it compiles (also across packages) or, for --enable-tvm-ffi +# functions, while a function is first called: every kda kernel package shares this lock. +_CUTE_LOCK = cutlass.__dict__.setdefault("_kda_compile_lock", threading.RLock()) + _CACHE = {} -_SIDE = {} # device -> stream that zeroes counter buffers during graph capture +_SIDE = {} # device -> stream for the buffers made while a CUDA graph is being captured _raw_stream = torch._C._cuda_getCurrentRawStream # device index -> current stream handle _capturing = torch._C._cuda_isCurrentStreamCapturing _current_device = torch._C._cuda_getDevice +_MAX_OUT = 1 << 30 # complex outputs; the passes' 32-bit float64 offsets reach 2^31 def _ffi(t): @@ -65,7 +73,9 @@ def _ffi(t): def _compile(fn, *args): - return cute.compile(fn, *args, cute.runtime.make_fake_stream(use_tvm_ffi_env_stream=True), options="--enable-tvm-ffi") + return cute.compile( + fn, *args, cute.runtime.make_fake_stream(use_tvm_ffi_env_stream=True), options="--enable-tvm-ffi" + ) def _fused_launcher(xl, yl, zl, ntabs, xmap, ymap, zmap): @@ -80,7 +90,7 @@ def _fused_launcher(xl, yl, zl, ntabs, xmap, ymap, zmap): f" zl(gout, {''.join(a + ', ' for a in zmap)}stream)\n" ) ns = {"xl": xl, "yl": yl, "zl": zl, "cute": cute, "cuda": cuda} - exec(src, ns) + exec(src, ns) # noqa: S102 - the launcher source is generated just above return cute.jit(preprocess=False)(ns["launch"]) @@ -100,10 +110,10 @@ def _capture_id(handle): return int(cid) -def _zeros_outside_capture(n, device): - """A zeroed int32 [n] tensor while the current stream is capturing a CUDA graph, without - adding a memset node to the graph: the fill runs on a private side stream (relaxed capture - mode for this thread) and has completed before this returns.""" +def _outside_capture(fn, device): + """fn() run while the current stream is capturing a CUDA graph, without adding its copies and + fills to the graph: it runs on a private side stream (relaxed capture mode for this thread) and + has completed before this returns, so its buffers serve the graph and eager calls alike.""" err, prev = cuda.cuThreadExchangeStreamCaptureMode(cuda.CUstreamCaptureMode.CU_STREAM_CAPTURE_MODE_RELAXED) _check(err, "cuThreadExchangeStreamCaptureMode") try: @@ -113,11 +123,22 @@ def _zeros_outside_capture(n, device): _check(err, "cuStreamCreate") side = _SIDE[device] = torch.cuda.ExternalStream(int(h), device=device) with torch.cuda.stream(side): - buf = torch.zeros(n, dtype=torch.int32, device=device) + res = fn() side.synchronize() finally: cuda.cuThreadExchangeStreamCaptureMode(prev) - return buf + return res + + +def _on_device(fn, device): + """fn(), outside the CUDA graph when the current stream is capturing one (_outside_capture).""" + return _outside_capture(fn, device) if _capturing() else fn() + + +def _zeros_outside_capture(n, device): + """A zeroed int32 [n] tensor while the current stream is capturing a CUDA graph, without + adding a memset node to the graph.""" + return _outside_capture(lambda: torch.zeros(n, dtype=torch.int32, device=device), device) def _bigprime_cols(cfg): @@ -178,7 +199,9 @@ class FFT3DPlan: # counters: one 128-byte line per z plane + the Y exit counter. Without mode 3 no # kernel touches them and this one tensor fills the argument of every launch; in mode 3 # it only serves compilation and each launch stream gets its own (_launch_args). - self.sync = torch.zeros((nz + 1) * FLAG_PAD, dtype=torch.int32, device=device) + # (made outside the graph when the first call of a shape is being captured: torch refuses + # pageable host-to-device copies during capture, and the plan outlives the graph) + self.sync = _on_device(lambda: torch.zeros((nz + 1) * FLAG_PAD, dtype=torch.int32, device=device), device) # the "r2c" X pass reads input row pairs as f64x2 vectors (16-byte aligned); pack2 and # the direct DFT read scalars self.in_align = 16 if xcfg is not None and xcfg.kind == "r2c" else 8 @@ -219,8 +242,9 @@ class FFT3DPlan: self.xl, *xtabs = build_direct_rows(DirectRowCfg(nx, nz * ny)) self.x_prefetch = False self.nx_t, self.ny_t = len(xtabs), len(ytabs) - self.tabs = [_dev(t, device) for t in list(xtabs) + list(ytabs) + list(ztabs)] + self.tabs = _on_device(lambda: [_dev(t, device) for t in list(xtabs) + list(ytabs) + list(ztabs)], device) self.compiled = None + self.loaded = False # the compiled function has been called once (under _CUTE_LOCK) self._args = None # table + counter arguments, when they do not depend on the stream self._stream_args = {} # mode 3: launch key (stream, or (stream, capture id)) -> arguments @@ -259,8 +283,14 @@ class FFT3DPlan: return args def launch(self, inp, out): - if self.compiled is None: - self.compile(inp, out) + if not self.loaded: + with _CUTE_LOCK: + if self.compiled is None: + self.compile(inp, out) + if not self.loaded: + self.compiled(inp.view(-1), out.view(-1), *(self._args or self._launch_args(inp))) + self.loaded = True + return self.compiled(inp.view(-1), out.view(-1), *(self._args or self._launch_args(inp))) @@ -268,7 +298,10 @@ def _get_plan(x): key = (x.shape, x.get_device()) p = _CACHE.get(key) if p is None: - p = _CACHE[key] = FFT3DPlan(*x.shape, x.device) + with _CUTE_LOCK: + p = _CACHE.get(key) + if p is None: + p = _CACHE[key] = FFT3DPlan(*x.shape, x.device) return p @@ -285,6 +318,8 @@ def _validate(x): raise ValueError(f"run() expects a 3-D tensor [nz, ny, nx], got shape {tuple(x.shape)}") if 0 in x.shape: raise ValueError(f"run() needs every dimension >= 1, got shape {tuple(x.shape)}") + if x.shape[0] * x.shape[1] * (x.shape[2] // 2 + 1) > _MAX_OUT: + raise ValueError(f"shape {tuple(x.shape)} has more than 2^30 complex outputs, which the kernels cannot address") if x.get_device() != _current_device(): raise ValueError( f"input is on {x.device} but the current CUDA device is cuda:{_current_device()}; " @@ -308,6 +343,7 @@ def _ready(x): and not x.requires_grad and not x.is_neg() and 0 not in x.shape + and x.shape[0] * x.shape[1] * (x.shape[2] // 2 + 1) <= _MAX_OUT and x.get_device() == _current_device() ) diff --git a/build/torch-cuda/metadata.json b/build/torch-cuda/metadata.json index a6034b726b518a50384b328bea6a4054f65f05b9..19c6da3ec26f880c919ae1a564da7b4381834c21 100644 --- a/build/torch-cuda/metadata.json +++ b/build/torch-cuda/metadata.json @@ -18,44 +18,45 @@ "files": { "LICENSE.txt": "AIyEysQ0a1okjH0MEq1kTbdKj938zWEHbQJBfSkK23s=", "__init__.py": "q3wlQ/Ew0+FfsBtKwNvoOH9sRHaZbLGqgCBortEP+XU=", + "_build.py": "g9CMDCXzE4s2O6rvOexerXud8Ven7Wxk+EQdSGwEwC0=", "_c2r_f32/__init__.py": "XBy0pSUwgUTmssbhC7XEt/ELeTb4ayilaHy7B/V0pHw=", - "_c2r_f32/anyfft.py": "ehbLwanScRoMLeAvopBDiFfJlVhlpimFcRuoqKgpFy0=", + "_c2r_f32/anyfft.py": "uGwJFfsENnn1JHTiUr1cgVdQnnufh8aUEbDTnMOCDX8=", "_c2r_f32/fftgen.py": "vlccjhLwsmKsoyZ+C8DPeR7fIe7LPMxEVsq1cDF5faE=", "_c2r_f32/generic.py": "F286vgjce5gqBY+L9ZzqY8kAauvLc0tvxUTAYBJBfrA=", "_c2r_f32/inplace.py": "J+tnMJWGaiz3Gug+wbJzgqgskLgHxnbqHWNb9h1GSCU=", - "_c2r_f32/kernel.py": "hX4XP44Cd2BE06j95sIF8RJd8nwq7sik86DIM+6uLc0=", + "_c2r_f32/kernel.py": "cFlvU0OgC5KWF2eGg4IgcrkmXAPrwLm8A2JupMnQU7U=", "_c2r_f32/tables.py": "RvVnytUIHgceogs37Z8lcjI5mxWclCA8D7kqC2YKm9w=", "_c2r_f32/twopass.py": "zI/xziZlOyfjNByjxB9Lag16rgClQVEn9kwlcoKQXT0=", "_c2r_f64/__init__.py": "6NiqCxU8/XZoiu7IY/nThfL5G3EovojIu+BSdpPGqEk=", - "_c2r_f64/bigprime.py": "02gw/YOCiA32nxWpmrF1spuAExE4M5f3JgYj/zJaI5U=", + "_c2r_f64/bigprime.py": "AvlFtIic90MD097O9sR7/lBVgD13hljLZ30FC9MYj0U=", "_c2r_f64/fftgen.py": "1Fn09b4uYmDSwItnhAycTXZVDWcmvXmf28BdjtMjsEQ=", - "_c2r_f64/kernel.py": "F/KBXDpll4RdODgvHEsdqqU+vMxeNrJumfmiIMDOnY0=", + "_c2r_f64/kernel.py": "nm9/akKKtsvwWXDMamBJt1E4gEr6IWxffIcWj9Ss4rg=", "_c2r_f64/softfp.py": "B4zzVG3AA7dtfqYCCORehavfX7Xz8ypzqiML/W5hgBE=", "_c2r_f64/twiddles.py": "WXaDgblQUWoX/1Qoofd5mD5aUpG1EkjYsdKD3YAUPW4=", "_ops.py": "wpRc/vzJsXg3CcTlM6GxXCVZFLCb6nJ0ocSnhY/mvK8=", "_r2c_f32/__init__.py": "b+FuhAkJolHH1YTeeRAb4NMHe+7YQId1VYOQ+W+vqsI=", "_r2c_f32/fft3k.py": "ZoLp8dkbyHLI57MrUAhd06t3+lDM+kIavTOk7YPaVPc=", "_r2c_f32/fft_core.py": "WThy1Zi8S9R5zSQgluOWnrhge+zXreeLR5OjysAgXNc=", - "_r2c_f32/fft_gen.py": "YfOq5cHq+eS6gOwr73oRjMYQUTiVBPB0hB9UE1o5UJE=", + "_r2c_f32/fft_gen.py": "RFtnvOt6ZaeJMBNQiVQ67cRTfIKVH7iIXQ7KDlOyhv8=", "_r2c_f32/fft_generic.py": "FCzLSrddYV38yRsIL/rPWwIgcSZDdNElpLWo30C6oCA=", "_r2c_f32/fft_plane2.py": "jkEtDEO5n2htSNz6tTcExrwoWUuWcTAAZu+uvhJXq+M=", "_r2c_f32/fft_xy.py": "Z4nZN7GM9AbNVr9JYgckfPifxfybumN5tMcmqgm/ePo=", "_r2c_f32/fft_ys1w.py": "4Vske6f2ATSSTb//EkpoHS5E3s0m9xGWOLuH3KWJSC8=", "_r2c_f32/fft_ysplit.py": "ukVz02AMlODEqFb/0qvSwAs5rA4CMFlqpI1YSRY0yqQ=", - "_r2c_f32/kernel.py": "k/jj+b9XOwBzf/Uug9hwXg0JUqOTjVJ6mhalZs1PNi8=", - "_r2c_f32/plan.py": "eSTB1bK8zgHLcjpMf04C5F5LVHjqot2JdFXnm8/VRes=", + "_r2c_f32/kernel.py": "KxVRurbHTqMIfNxL1xBgf+he+6oRqulPID7898nfvbY=", + "_r2c_f32/plan.py": "+g5nNHHdHUpoPKjU5rpota26DVaZC8iX0YbJs1vbfsU=", "_r2c_f32/ptx.py": "3mKM+qkQfpV6NCAXz4V4FLf6Z35LtiONgb5oSGF09fw=", "_r2c_f32/stockham.py": "5lS6YIDy/WKT4gTUgsQsrJHBEaAWAyjELVhD6uHJysM=", "_r2c_f64/__init__.py": "rHmKPjGcG8wbZnWqgo9OQD4lcZYRVFCcsgC3c5sFq3s=", - "_r2c_f64/bigprime.py": "02gw/YOCiA32nxWpmrF1spuAExE4M5f3JgYj/zJaI5U=", + "_r2c_f64/bigprime.py": "AvlFtIic90MD097O9sR7/lBVgD13hljLZ30FC9MYj0U=", "_r2c_f64/dsl_ops.py": "XmM8HcIg/vaNo6pdrTBgLdMBT6YsFo50OUpOXkApnLc=", "_r2c_f64/fft_codelets.py": "Np96zEz++x7McIuE7+aUz6HGkIk81aNt+Zs2TyrvXKA=", "_r2c_f64/fft_direct.py": "bImy5bLyOOWrUTeAmTJaeUsznyQzlljKDqMuKmTvLQQ=", - "_r2c_f64/fft_passes.py": "9eCrb1yOd2+qDoB3ziu6pgotdhWCJybd7rvX1Aqbra0=", + "_r2c_f64/fft_passes.py": "OBdSwR8OSCi6LtDJ97E5qdrcDuwazVOavL3wqYkMdYg=", "_r2c_f64/fft_plan.py": "OqPrkiahnt/XreodPMi90N7+kHinYgYbLuWAdVd8eqI=", "_r2c_f64/fft_stages.py": "5ylt/t+bA+9ILsAG5P9CCJkwdJmfvvx/oB29w1LoO9A=", "_r2c_f64/fftgen.py": "1Fn09b4uYmDSwItnhAycTXZVDWcmvXmf28BdjtMjsEQ=", - "_r2c_f64/kernel.py": "3DZZyoLqdJnlS9WRS+ujv0M+aMAhAN1/B1zvpSSbdBY=", + "_r2c_f64/kernel.py": "WlebETSr9K9PraEob66ayyYTRHy20nFzMZ4aWPXYTl8=", "_r2c_f64/planner.py": "VgtohOIirLvHoK/AAciicLFmPD5nJSOCYxOomeYQZEY=", "_r2c_f64/tuned.py": "YtEsBZO9C63haDWFVnMBtIpTXwSKuvxAF6ffpz9wrd0=" } @@ -68,7 +69,7 @@ }, "kernel": { "commit": "9e7519bbed9eaea4ef8f23df5cdc6654543f8f72", - "dirty": false + "dirty": true } } -} \ No newline at end of file +}