nlm-cuda 1.2.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
nlm_cuda-1.2.1/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Matin Mahzad
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,286 @@
1
+ Metadata-Version: 2.4
2
+ Name: nlm_cuda
3
+ Version: 1.2.1
4
+ Summary: Bitwise-exact GPU (CuPy) drop-in replacement for skimage.restoration.denoise_nl_means
5
+ License-Expression: MIT
6
+ Requires-Python: >=3.9
7
+ Description-Content-Type: text/markdown
8
+ License-File: LICENSE
9
+ Requires-Dist: numpy
10
+ Provides-Extra: cuda12
11
+ Requires-Dist: cupy-cuda12x; extra == "cuda12"
12
+ Requires-Dist: nvidia-cuda-nvrtc-cu12; extra == "cuda12"
13
+ Requires-Dist: nvidia-cuda-runtime-cu12; extra == "cuda12"
14
+ Provides-Extra: cuda13
15
+ Requires-Dist: cupy-cuda13x[ctk]; extra == "cuda13"
16
+ Provides-Extra: test
17
+ Requires-Dist: scikit-image==0.26.0; extra == "test"
18
+ Dynamic: license-file
19
+
20
+ # nlm_cuda
21
+
22
+ A GPU (CUDA / CuPy) drop-in replacement for scikit-image's
23
+ `skimage.restoration.denoise_nl_means`. Its results are **bit-for-bit identical**
24
+ to scikit-image 0.26.0 and it runs **60–78× faster** on a GTX 1080 Ti
25
+ (~1300× in classic mode).
26
+
27
+ ```python
28
+ from nlm_cuda import denoise_nl_means # instead of
29
+ # from skimage.restoration import denoise_nl_means
30
+
31
+ denoised = denoise_nl_means(volume, patch_size=7, patch_distance=3, h=0.1)
32
+ ```
33
+
34
+ It has the same parameters, defaults, return values and exceptions as scikit-image.
35
+ Existing code only needs the import changed.
36
+
37
+ ---
38
+
39
+ ## Contents
40
+
41
+ - `nlm_cuda.py`: the library, a single file whose only dependencies are NumPy and CuPy.
42
+ - `test_nlm_cuda.py`: the verification and benchmark suite. It compares against
43
+ scikit-image and writes a JSON report.
44
+ - `results.txt`: the log of the final verification run.
45
+ - `New folder (9)`: the previous version (1.0.0), its README and its results.
46
+
47
+ ## Requirements
48
+
49
+ - An NVIDIA GPU (any compute capability CuPy supports; the reference results below
50
+ come from a GTX 1080 Ti, compute capability 6.1).
51
+ - Python 3.9 or newer, NumPy, CuPy (`cupy-cuda12x` or the build that matches your CUDA).
52
+ - scikit-image 0.26.0, only to run the test suite. Exactness is defined against
53
+ this version.
54
+
55
+ Kernels are compiled at run time by NVRTC on first use and cached on disk by CuPy,
56
+ so no CUDA toolkit or C++ compiler is needed. The first call for a new configuration
57
+ therefore takes a little longer.
58
+
59
+ > On Windows, CuPy may print `UserWarning: CUDA path could not be detected`.
60
+ > It is harmless. Set the `CUDA_PATH` environment variable to silence it.
61
+
62
+ ## Scope: what is reproduced exactly
63
+
64
+ All branches of scikit-image's implementation are covered:
65
+
66
+ - **Fast mode** (the default) for 2D, 3D and 4D images, with any number of channels.
67
+ - **Classic mode** (`fast_mode=False`) for 2D (any number of channels) and 3D.
68
+ - **Data types and options:** float32 and float64 pipelines, `sigma` noise correction,
69
+ `preserve_range`, and `channel_axis` (including scikit-image's own squeeze/moveaxis
70
+ behaviour).
71
+ - **Input handling:** integer, bool and float16 inputs are converted the same way;
72
+ arguments are coerced the same way; invalid inputs raise the same exceptions.
73
+ - **Special values:** NaN, ±Inf, ±0 and float32 subnormals are handled exactly as on
74
+ the CPU. NaN *positions* match. NaN *payload bits* are not compared, because GPUs
75
+ produce canonical NaNs.
76
+
77
+ Inputs can be NumPy or CuPy arrays. With a CuPy input the result stays on the GPU.
78
+
79
+ "Bitwise identical" means identical to scikit-image's compiled x86-64 wheels
80
+ (Windows/Linux builds: SSE2, no FMA).
81
+
82
+ ## Results (GTX 1080 Ti, final verification run)
83
+
84
+ The final run of `test_nlm_cuda.py` passed **2415 of 2415 checks** (fixed exact-match
85
+ cases, every dtype and edge case, 250 random fuzz configurations, 1938 runs across
86
+ execution plans and kernel variants, the CuPy-input tests, the benchmarks and the
87
+ diagnosis). In addition, random configurations that take the new sweep path were
88
+ checked separately against scikit-image, all bit-identical: 40 in 3D (sizes 40–80³,
89
+ patch 1–9, distance 1–5) and 25 in 2D (200–700 pixels, distance up to 11), with
90
+ float32/float64, `sigma`, flat regions and injected NaN/±Inf/subnormal/−0 values
91
+ (`_work/fuzz_sweep.py`).
92
+
93
+ | Workload | 1.0.0 | **1.1.0** | gain | scikit-image (CPU) | speed-up vs CPU |
94
+ |---|---:|---:|---:|---:|---:|
95
+ | 3D float32 192³, patch 7, dist 3 (paper setting) | 0.564 s | **0.298 s** | 1.9× | 23.3 s\* | **78×** |
96
+ | 3D float32 96³, skimage defaults (patch 7, dist 11) | 3.006 s | **2.032 s** | 1.5× | 123.3 s\* | **61×** |
97
+ | 3D float64 128³, patch 5, dist 3, sigma | 0.150 s | **0.101 s** | 1.5× | 7.5 s | **74×** |
98
+ | 2D float32 2048², defaults | 0.273 s | **0.173 s** | 1.6× | 12.8 s | **74×** |
99
+ | 2D float32 RGB 1536², patch 5, dist 6 | 0.165 s | **0.068 s** | 2.4× | 3.3 s | **49×** |
100
+ | 4D float32 40⁴, patch 3, dist 2 | 1.030 s | 1.027 s | — | 38.9 s\* | 38× |
101
+ | 2D classic mode 512², patch 7, dist 7 | 0.007 s | 0.007 s | — | 8.9 s\* | ~1300× |
102
+
103
+ \* CPU time extrapolated from cropped runs (`--cpu-full` measures the full size).
104
+ Absolute times vary by roughly ±5–10% with GPU clocks and temperature.
105
+
106
+ Other sizes measured during development (same GPU, 1.0.0 → 1.1.0): 3D 64³
107
+ 43 → 23 ms, 3D 256³ 1.22 → 0.72 s, 2D 512² 35 → 15.5 ms.
108
+
109
+ ### Where the time goes now (192³, per-kernel, serialised)
110
+
111
+ | Stage | 1.0.0 | 1.1.0 |
112
+ |---|---:|---:|
113
+ | integral images | 0.292 s (26% of FP64 peak) | ~0.135 s (~57%) |
114
+ | patch distances | 0.147 s | ~0.106 s |
115
+ | accumulation | 0.067 s | ~0.045 s (~90%) |
116
+
117
+ ### The lower bound imposed by exactness
118
+
119
+ Floating-point addition is not associative. The only way to get scikit-image's
120
+ exact bits is to perform the **same float64 additions in the same order**:
121
+
122
+ - **3D integral:** 9 FP64 operations per voxel and shift (+1 with `sigma`).
123
+ - **Distance:** 7 additions + 1 multiplication.
124
+ - **Accumulation:** 2 additions per applied contribution. The weight × value product
125
+ is exact for float32 images (21 × 24 significant bits) and is now formed on the
126
+ integer pipes, so it no longer uses the FP64 unit.
127
+
128
+ So the run time can never be lower than `required FP64 operations / FP64 throughput`.
129
+ GeForce cards run FP64 at 1/32 (Pascal) or 1/64 (Turing and later) of FP32, so this is
130
+ the binding limit there. For the 192³ case that bound is **0.179 s** at the nominal
131
+ clock. 1.1.0 runs at 0.298 s, i.e. **62% of the bound** (1.0.0: 32%).
132
+
133
+ The built-in diagnosis (`diagnose()`, last section of `results.txt`) shows what
134
+ separates the integral kernel from the bound: with only its arithmetic and shuffles
135
+ it runs at 86% of FP64 peak; the remaining cost is the per-step integer work of the
136
+ image loads and the read-back of the previous plane group (removing all loads: 1.28×),
137
+ not the stores (1.02×) and not the barriers. The distance pass is limited by on-chip
138
+ (L1/L2) load throughput, not by DRAM and not by its FP64 additions (both verified by
139
+ ablation).
140
+
141
+ ## How it works
142
+
143
+ 1. **Integral pass: one thread block sweeps a whole shift** (2D, 3D single-channel).
144
+ - Lanes are 32 consecutive rows, time is columns, each lane one column behind the
145
+ previous one. In 3D the warps of a block are consecutive planes; in 2D the row
146
+ blocks rotate over the warps.
147
+ - The row neighbour comes from a warp shuffle. The plane neighbour comes from a
148
+ tiny shared exchange with the previous warp (barrier every K steps). Lane 0
149
+ gets the last row of the previous row block from a shared ring.
150
+ - Warp 0 reads the previous plane group's last plane back from the buffer.
151
+ - There is **no synchronisation between thread blocks at all**. Each block
152
+ processes the full region of its shift, and a batch of G shifts runs as G blocks.
153
+ - Image and integral use **diagonal-blocked layouts**, in which such a skewed run
154
+ of 32 rows is contiguous. Every load and store is therefore a full-width access.
155
+ - The recurrence is evaluated in exactly scikit-image's order.
156
+ 2. **Stale-buffer semantics (3D).** scikit-image reuses one integral buffer and never
157
+ clears it, so shifts with `t_row <= -2` read rows left by shift
158
+ `(t_pln-1, d, min(d, ncol-1-c))`. These rows are archived explicitly. The integral
159
+ kernel now writes the archive itself; there is no separate copy kernel.
160
+ 3. **Distance pass.** It reads the 8 integral corners per centre from
161
+ **shared-memory tiles**. In 3D a block of 8×32 centres walks a chunk of planes with
162
+ a ring of 2o+1 plane slabs, so each integral value is fetched about once per block.
163
+ It then applies skimage's `_fast_exp` weight through an exact integer certificate
164
+ (IEEE division only in ambiguous cases).
165
+ 4. **Accumulation.** Gather form, in skimage's exact per-voxel order.
166
+ - All loads are issued unconditionally, so the loads of several shifts are in
167
+ flight together. The updates themselves stay conditional, as in skimage.
168
+ - The exact weight × value product is formed with integer instructions.
169
+ 5. **Float32 subnormals.** CuPy compiles every kernel with `-ftz=true`, which would
170
+ flush float32 subnormals to zero. All float32 arithmetic and conversions are
171
+ therefore written as PTX instructions without `.ftz`, or done bitwise.
172
+ 6. **No FMA** is ever emitted (checked in the generated PTX).
173
+
174
+ 4D and multichannel 3D use the 1.0.0 tiled-wavefront integral kernel (unchanged).
175
+ So do volumes too small for the 3D plane-group hand-over (small volumes are
176
+ milliseconds anyway).
177
+
178
+ ## Automatic tuning
179
+
180
+ Every execution plan produces identical bits, so tuning affects speed only.
181
+
182
+ - **Sweep kernels** (warps per block and barrier interval):
183
+ - The first batches of the first call for a problem class are timed with each
184
+ candidate (kernels precompiled first).
185
+ - With too few batches, the candidates are tried over the following calls, one per
186
+ call, by wall time; the first call of the process is never sampled because it
187
+ includes JIT compilation.
188
+ - The winner is remembered.
189
+ - **Tiled-wavefront kernel** (4D, multichannel 3D): as in 1.0.0 (tile shape, shifts per
190
+ thread, prefetch, staged stores, register cap, batch sizes).
191
+ - **Where it's stored:** in memory, and in `~/.cache/nlm_cuda/tuning.json`, or the path
192
+ in `NLM_CUDA_TUNE_FILE`. The cache format version changed in 1.1.0 (`v10`), so old
193
+ entries are ignored.
194
+ - `autotune(image, ...)` runs an exhaustive offline search for the tiled kernel.
195
+
196
+ ## API
197
+
198
+ ```python
199
+ denoise_nl_means(image, patch_size=7, patch_distance=11, h=0.1, fast_mode=True,
200
+ sigma=0.0, *, preserve_range=False, channel_axis=None)
201
+ ```
202
+ Same as scikit-image. Returns a NumPy array, or a CuPy array if `image` was a CuPy array.
203
+
204
+ ```python
205
+ last_run_info()
206
+ ```
207
+ A dict describing the last call: the mode, the plan (`('sweep', W, K, L, CPS)` for the
208
+ sweep path) and where it came from, the required FP64 operations and the achieved
209
+ fraction of FP64 peak, the integral kernel's registers and occupancy, the distance
210
+ kernel used, online-tuning timings, and the per-kernel profile when profiling is on.
211
+
212
+ ```python
213
+ set_profiling(True) # or environment variable NLM_CUDA_PROFILE=1
214
+ ```
215
+ Per-kernel timing for the following calls (kernels are serialised while profiling).
216
+
217
+ ```python
218
+ autotune(image, patch_size=7, patch_distance=11, h=0.1, sigma=0.0, *,
219
+ channel_axis=None, preserve_range=False, max_shifts=None, save=True, verbose=True)
220
+ ```
221
+ Exhaustive plan search for the tiled-wavefront kernel; returns `(best_plan, timings)`.
222
+
223
+ ```python
224
+ diagnose(shape=(128, 128, 128), patch_size=7, patch_distance=3, h=0.1, dtype=np.float32)
225
+ ```
226
+ Bottleneck analysis: the GPU's real FP64 add throughput and latency, and the integral
227
+ kernel timed with one cost removed at a time (diagnostic variants, results discarded),
228
+ plus the previous kernel for comparison. Returns a JSON-serialisable dict.
229
+
230
+ ### Environment variables
231
+
232
+ | Variable | Effect |
233
+ |---|---|
234
+ | `NLM_CUDA_TUNE_FILE` | Location of the tuning cache. Default: `~/.cache/nlm_cuda/tuning.json`. |
235
+ | `NLM_CUDA_AUTOTUNE=0` | Disable online tuning (use the model's / default plan). |
236
+ | `NLM_CUDA_PROFILE=1` | Enable per-kernel profiling. |
237
+ | `NLM_CUDA_SWEEP=0` | Use the 1.0.0 tiled-wavefront path everywhere (for comparison). |
238
+ | `NLM_CUDA_SW_W`, `NLM_CUDA_SW_K` / `NLM_CUDA_SW2_W`, `NLM_CUDA_SW2_K` | Fix the 3D / 2D sweep parameters (disables their tuning). |
239
+ | `NLM_CUDA_PERSIST_TUNE=1` | Experimental, tiled kernel only: persistent integral blocks. |
240
+
241
+ ## Running the tests
242
+
243
+ ```bash
244
+ python test_nlm_cuda.py # full suite (~4-5 min on a GTX 1080 Ti)
245
+ python test_nlm_cuda.py --quick # smaller sizes
246
+ python test_nlm_cuda.py --only bench # sections: env api exact dtypes edge fuzz sweep cupy bench diagnose
247
+ python test_nlm_cuda.py --no-profile # skip the per-kernel profile in the benchmark
248
+ python test_nlm_cuda.py --cpu-full # measure scikit-image at full size instead of extrapolating
249
+ ```
250
+
251
+ The suite prints a log and writes `nlm_cuda_test_report.json` next to the script.
252
+ Every result is compared bit for bit against scikit-image 0.26.0. Many of the suite's
253
+ volumes are small and run on the tiled path; the sweep path is exercised by the
254
+ benchmarks and larger cases. (The per-kernel profile printed in the benchmark section
255
+ is a serialised diagnostic run and can read high after the earlier sections; the GPU
256
+ times above are the real, overlapped runs.)
257
+
258
+ ## What was tried and did not help (GTX 1080 Ti)
259
+
260
+ These are recorded so that the "fastest" claim can be checked:
261
+
262
+ - **Integer-only corner sums in the distance pass** (exact certificate, FP64 fallback):
263
+ bitwise exact but slower. Removing the 7 FP64 additions entirely (a diagnostic) does
264
+ not speed the pass up at all, so its FP64 additions are not the bottleneck.
265
+ - **Plane-sweep distance with register FIFOs, and parallelogram lane mappings**:
266
+ slower than shared-memory tiles.
267
+ - **Processing 2 or 4 columns per step in the integral sweep**: slower, because the
268
+ dependent chain per step grows.
269
+ - **More concurrent shifts (2 blocks per SM)**: no gain, so the integral kernel is not
270
+ latency-bound at 16 warps per SM.
271
+ - **Integral ring in global memory, longer prefetch, float64 image storage**: no gain
272
+ or more registers.
273
+
274
+ ## Notes and limitations
275
+
276
+ - Exactness is defined against **scikit-image 0.26.0** on x86-64. Other skimage
277
+ versions may differ wherever skimage itself changed.
278
+ - Classic mode (`fast_mode=False`) covers 2D and 3D, the same as scikit-image.
279
+ - GPU memory decides how many shifts run concurrently. Large volumes run in more
280
+ batches but give the same results.
281
+ - On Pascal the per-block shared-memory limit (48 KB) reduces the warps per block of the
282
+ 3D sweep for wide volumes (width above about 220). The results are the same, only
283
+ less parallel.
284
+ - Speed depends mainly on the GPU's FP64 throughput. Data-centre GPUs (V100, A100,
285
+ H100, with FP64 at 1/2 of FP32) are expected to be much faster than GeForce cards.
286
+ That is not measured here.
@@ -0,0 +1,267 @@
1
+ # nlm_cuda
2
+
3
+ A GPU (CUDA / CuPy) drop-in replacement for scikit-image's
4
+ `skimage.restoration.denoise_nl_means`. Its results are **bit-for-bit identical**
5
+ to scikit-image 0.26.0 and it runs **60–78× faster** on a GTX 1080 Ti
6
+ (~1300× in classic mode).
7
+
8
+ ```python
9
+ from nlm_cuda import denoise_nl_means # instead of
10
+ # from skimage.restoration import denoise_nl_means
11
+
12
+ denoised = denoise_nl_means(volume, patch_size=7, patch_distance=3, h=0.1)
13
+ ```
14
+
15
+ It has the same parameters, defaults, return values and exceptions as scikit-image.
16
+ Existing code only needs the import changed.
17
+
18
+ ---
19
+
20
+ ## Contents
21
+
22
+ - `nlm_cuda.py`: the library, a single file whose only dependencies are NumPy and CuPy.
23
+ - `test_nlm_cuda.py`: the verification and benchmark suite. It compares against
24
+ scikit-image and writes a JSON report.
25
+ - `results.txt`: the log of the final verification run.
26
+ - `New folder (9)`: the previous version (1.0.0), its README and its results.
27
+
28
+ ## Requirements
29
+
30
+ - An NVIDIA GPU (any compute capability CuPy supports; the reference results below
31
+ come from a GTX 1080 Ti, compute capability 6.1).
32
+ - Python 3.9 or newer, NumPy, CuPy (`cupy-cuda12x` or the build that matches your CUDA).
33
+ - scikit-image 0.26.0, only to run the test suite. Exactness is defined against
34
+ this version.
35
+
36
+ Kernels are compiled at run time by NVRTC on first use and cached on disk by CuPy,
37
+ so no CUDA toolkit or C++ compiler is needed. The first call for a new configuration
38
+ therefore takes a little longer.
39
+
40
+ > On Windows, CuPy may print `UserWarning: CUDA path could not be detected`.
41
+ > It is harmless. Set the `CUDA_PATH` environment variable to silence it.
42
+
43
+ ## Scope: what is reproduced exactly
44
+
45
+ All branches of scikit-image's implementation are covered:
46
+
47
+ - **Fast mode** (the default) for 2D, 3D and 4D images, with any number of channels.
48
+ - **Classic mode** (`fast_mode=False`) for 2D (any number of channels) and 3D.
49
+ - **Data types and options:** float32 and float64 pipelines, `sigma` noise correction,
50
+ `preserve_range`, and `channel_axis` (including scikit-image's own squeeze/moveaxis
51
+ behaviour).
52
+ - **Input handling:** integer, bool and float16 inputs are converted the same way;
53
+ arguments are coerced the same way; invalid inputs raise the same exceptions.
54
+ - **Special values:** NaN, ±Inf, ±0 and float32 subnormals are handled exactly as on
55
+ the CPU. NaN *positions* match. NaN *payload bits* are not compared, because GPUs
56
+ produce canonical NaNs.
57
+
58
+ Inputs can be NumPy or CuPy arrays. With a CuPy input the result stays on the GPU.
59
+
60
+ "Bitwise identical" means identical to scikit-image's compiled x86-64 wheels
61
+ (Windows/Linux builds: SSE2, no FMA).
62
+
63
+ ## Results (GTX 1080 Ti, final verification run)
64
+
65
+ The final run of `test_nlm_cuda.py` passed **2415 of 2415 checks** (fixed exact-match
66
+ cases, every dtype and edge case, 250 random fuzz configurations, 1938 runs across
67
+ execution plans and kernel variants, the CuPy-input tests, the benchmarks and the
68
+ diagnosis). In addition, random configurations that take the new sweep path were
69
+ checked separately against scikit-image, all bit-identical: 40 in 3D (sizes 40–80³,
70
+ patch 1–9, distance 1–5) and 25 in 2D (200–700 pixels, distance up to 11), with
71
+ float32/float64, `sigma`, flat regions and injected NaN/±Inf/subnormal/−0 values
72
+ (`_work/fuzz_sweep.py`).
73
+
74
+ | Workload | 1.0.0 | **1.1.0** | gain | scikit-image (CPU) | speed-up vs CPU |
75
+ |---|---:|---:|---:|---:|---:|
76
+ | 3D float32 192³, patch 7, dist 3 (paper setting) | 0.564 s | **0.298 s** | 1.9× | 23.3 s\* | **78×** |
77
+ | 3D float32 96³, skimage defaults (patch 7, dist 11) | 3.006 s | **2.032 s** | 1.5× | 123.3 s\* | **61×** |
78
+ | 3D float64 128³, patch 5, dist 3, sigma | 0.150 s | **0.101 s** | 1.5× | 7.5 s | **74×** |
79
+ | 2D float32 2048², defaults | 0.273 s | **0.173 s** | 1.6× | 12.8 s | **74×** |
80
+ | 2D float32 RGB 1536², patch 5, dist 6 | 0.165 s | **0.068 s** | 2.4× | 3.3 s | **49×** |
81
+ | 4D float32 40⁴, patch 3, dist 2 | 1.030 s | 1.027 s | — | 38.9 s\* | 38× |
82
+ | 2D classic mode 512², patch 7, dist 7 | 0.007 s | 0.007 s | — | 8.9 s\* | ~1300× |
83
+
84
+ \* CPU time extrapolated from cropped runs (`--cpu-full` measures the full size).
85
+ Absolute times vary by roughly ±5–10% with GPU clocks and temperature.
86
+
87
+ Other sizes measured during development (same GPU, 1.0.0 → 1.1.0): 3D 64³
88
+ 43 → 23 ms, 3D 256³ 1.22 → 0.72 s, 2D 512² 35 → 15.5 ms.
89
+
90
+ ### Where the time goes now (192³, per-kernel, serialised)
91
+
92
+ | Stage | 1.0.0 | 1.1.0 |
93
+ |---|---:|---:|
94
+ | integral images | 0.292 s (26% of FP64 peak) | ~0.135 s (~57%) |
95
+ | patch distances | 0.147 s | ~0.106 s |
96
+ | accumulation | 0.067 s | ~0.045 s (~90%) |
97
+
98
+ ### The lower bound imposed by exactness
99
+
100
+ Floating-point addition is not associative. The only way to get scikit-image's
101
+ exact bits is to perform the **same float64 additions in the same order**:
102
+
103
+ - **3D integral:** 9 FP64 operations per voxel and shift (+1 with `sigma`).
104
+ - **Distance:** 7 additions + 1 multiplication.
105
+ - **Accumulation:** 2 additions per applied contribution. The weight × value product
106
+ is exact for float32 images (21 × 24 significant bits) and is now formed on the
107
+ integer pipes, so it no longer uses the FP64 unit.
108
+
109
+ So the run time can never be lower than `required FP64 operations / FP64 throughput`.
110
+ GeForce cards run FP64 at 1/32 (Pascal) or 1/64 (Turing and later) of FP32, so this is
111
+ the binding limit there. For the 192³ case that bound is **0.179 s** at the nominal
112
+ clock. 1.1.0 runs at 0.298 s, i.e. **62% of the bound** (1.0.0: 32%).
113
+
114
+ The built-in diagnosis (`diagnose()`, last section of `results.txt`) shows what
115
+ separates the integral kernel from the bound: with only its arithmetic and shuffles
116
+ it runs at 86% of FP64 peak; the remaining cost is the per-step integer work of the
117
+ image loads and the read-back of the previous plane group (removing all loads: 1.28×),
118
+ not the stores (1.02×) and not the barriers. The distance pass is limited by on-chip
119
+ (L1/L2) load throughput, not by DRAM and not by its FP64 additions (both verified by
120
+ ablation).
121
+
122
+ ## How it works
123
+
124
+ 1. **Integral pass: one thread block sweeps a whole shift** (2D, 3D single-channel).
125
+ - Lanes are 32 consecutive rows, time is columns, each lane one column behind the
126
+ previous one. In 3D the warps of a block are consecutive planes; in 2D the row
127
+ blocks rotate over the warps.
128
+ - The row neighbour comes from a warp shuffle. The plane neighbour comes from a
129
+ tiny shared exchange with the previous warp (barrier every K steps). Lane 0
130
+ gets the last row of the previous row block from a shared ring.
131
+ - Warp 0 reads the previous plane group's last plane back from the buffer.
132
+ - There is **no synchronisation between thread blocks at all**. Each block
133
+ processes the full region of its shift, and a batch of G shifts runs as G blocks.
134
+ - Image and integral use **diagonal-blocked layouts**, in which such a skewed run
135
+ of 32 rows is contiguous. Every load and store is therefore a full-width access.
136
+ - The recurrence is evaluated in exactly scikit-image's order.
137
+ 2. **Stale-buffer semantics (3D).** scikit-image reuses one integral buffer and never
138
+ clears it, so shifts with `t_row <= -2` read rows left by shift
139
+ `(t_pln-1, d, min(d, ncol-1-c))`. These rows are archived explicitly. The integral
140
+ kernel now writes the archive itself; there is no separate copy kernel.
141
+ 3. **Distance pass.** It reads the 8 integral corners per centre from
142
+ **shared-memory tiles**. In 3D a block of 8×32 centres walks a chunk of planes with
143
+ a ring of 2o+1 plane slabs, so each integral value is fetched about once per block.
144
+ It then applies skimage's `_fast_exp` weight through an exact integer certificate
145
+ (IEEE division only in ambiguous cases).
146
+ 4. **Accumulation.** Gather form, in skimage's exact per-voxel order.
147
+ - All loads are issued unconditionally, so the loads of several shifts are in
148
+ flight together. The updates themselves stay conditional, as in skimage.
149
+ - The exact weight × value product is formed with integer instructions.
150
+ 5. **Float32 subnormals.** CuPy compiles every kernel with `-ftz=true`, which would
151
+ flush float32 subnormals to zero. All float32 arithmetic and conversions are
152
+ therefore written as PTX instructions without `.ftz`, or done bitwise.
153
+ 6. **No FMA** is ever emitted (checked in the generated PTX).
154
+
155
+ 4D and multichannel 3D use the 1.0.0 tiled-wavefront integral kernel (unchanged).
156
+ So do volumes too small for the 3D plane-group hand-over (small volumes are
157
+ milliseconds anyway).
158
+
159
+ ## Automatic tuning
160
+
161
+ Every execution plan produces identical bits, so tuning affects speed only.
162
+
163
+ - **Sweep kernels** (warps per block and barrier interval):
164
+ - The first batches of the first call for a problem class are timed with each
165
+ candidate (kernels precompiled first).
166
+ - With too few batches, the candidates are tried over the following calls, one per
167
+ call, by wall time; the first call of the process is never sampled because it
168
+ includes JIT compilation.
169
+ - The winner is remembered.
170
+ - **Tiled-wavefront kernel** (4D, multichannel 3D): as in 1.0.0 (tile shape, shifts per
171
+ thread, prefetch, staged stores, register cap, batch sizes).
172
+ - **Where it's stored:** in memory, and in `~/.cache/nlm_cuda/tuning.json`, or the path
173
+ in `NLM_CUDA_TUNE_FILE`. The cache format version changed in 1.1.0 (`v10`), so old
174
+ entries are ignored.
175
+ - `autotune(image, ...)` runs an exhaustive offline search for the tiled kernel.
176
+
177
+ ## API
178
+
179
+ ```python
180
+ denoise_nl_means(image, patch_size=7, patch_distance=11, h=0.1, fast_mode=True,
181
+ sigma=0.0, *, preserve_range=False, channel_axis=None)
182
+ ```
183
+ Same as scikit-image. Returns a NumPy array, or a CuPy array if `image` was a CuPy array.
184
+
185
+ ```python
186
+ last_run_info()
187
+ ```
188
+ A dict describing the last call: the mode, the plan (`('sweep', W, K, L, CPS)` for the
189
+ sweep path) and where it came from, the required FP64 operations and the achieved
190
+ fraction of FP64 peak, the integral kernel's registers and occupancy, the distance
191
+ kernel used, online-tuning timings, and the per-kernel profile when profiling is on.
192
+
193
+ ```python
194
+ set_profiling(True) # or environment variable NLM_CUDA_PROFILE=1
195
+ ```
196
+ Per-kernel timing for the following calls (kernels are serialised while profiling).
197
+
198
+ ```python
199
+ autotune(image, patch_size=7, patch_distance=11, h=0.1, sigma=0.0, *,
200
+ channel_axis=None, preserve_range=False, max_shifts=None, save=True, verbose=True)
201
+ ```
202
+ Exhaustive plan search for the tiled-wavefront kernel; returns `(best_plan, timings)`.
203
+
204
+ ```python
205
+ diagnose(shape=(128, 128, 128), patch_size=7, patch_distance=3, h=0.1, dtype=np.float32)
206
+ ```
207
+ Bottleneck analysis: the GPU's real FP64 add throughput and latency, and the integral
208
+ kernel timed with one cost removed at a time (diagnostic variants, results discarded),
209
+ plus the previous kernel for comparison. Returns a JSON-serialisable dict.
210
+
211
+ ### Environment variables
212
+
213
+ | Variable | Effect |
214
+ |---|---|
215
+ | `NLM_CUDA_TUNE_FILE` | Location of the tuning cache. Default: `~/.cache/nlm_cuda/tuning.json`. |
216
+ | `NLM_CUDA_AUTOTUNE=0` | Disable online tuning (use the model's / default plan). |
217
+ | `NLM_CUDA_PROFILE=1` | Enable per-kernel profiling. |
218
+ | `NLM_CUDA_SWEEP=0` | Use the 1.0.0 tiled-wavefront path everywhere (for comparison). |
219
+ | `NLM_CUDA_SW_W`, `NLM_CUDA_SW_K` / `NLM_CUDA_SW2_W`, `NLM_CUDA_SW2_K` | Fix the 3D / 2D sweep parameters (disables their tuning). |
220
+ | `NLM_CUDA_PERSIST_TUNE=1` | Experimental, tiled kernel only: persistent integral blocks. |
221
+
222
+ ## Running the tests
223
+
224
+ ```bash
225
+ python test_nlm_cuda.py # full suite (~4-5 min on a GTX 1080 Ti)
226
+ python test_nlm_cuda.py --quick # smaller sizes
227
+ python test_nlm_cuda.py --only bench # sections: env api exact dtypes edge fuzz sweep cupy bench diagnose
228
+ python test_nlm_cuda.py --no-profile # skip the per-kernel profile in the benchmark
229
+ python test_nlm_cuda.py --cpu-full # measure scikit-image at full size instead of extrapolating
230
+ ```
231
+
232
+ The suite prints a log and writes `nlm_cuda_test_report.json` next to the script.
233
+ Every result is compared bit for bit against scikit-image 0.26.0. Many of the suite's
234
+ volumes are small and run on the tiled path; the sweep path is exercised by the
235
+ benchmarks and larger cases. (The per-kernel profile printed in the benchmark section
236
+ is a serialised diagnostic run and can read high after the earlier sections; the GPU
237
+ times above are the real, overlapped runs.)
238
+
239
+ ## What was tried and did not help (GTX 1080 Ti)
240
+
241
+ These are recorded so that the "fastest" claim can be checked:
242
+
243
+ - **Integer-only corner sums in the distance pass** (exact certificate, FP64 fallback):
244
+ bitwise exact but slower. Removing the 7 FP64 additions entirely (a diagnostic) does
245
+ not speed the pass up at all, so its FP64 additions are not the bottleneck.
246
+ - **Plane-sweep distance with register FIFOs, and parallelogram lane mappings**:
247
+ slower than shared-memory tiles.
248
+ - **Processing 2 or 4 columns per step in the integral sweep**: slower, because the
249
+ dependent chain per step grows.
250
+ - **More concurrent shifts (2 blocks per SM)**: no gain, so the integral kernel is not
251
+ latency-bound at 16 warps per SM.
252
+ - **Integral ring in global memory, longer prefetch, float64 image storage**: no gain
253
+ or more registers.
254
+
255
+ ## Notes and limitations
256
+
257
+ - Exactness is defined against **scikit-image 0.26.0** on x86-64. Other skimage
258
+ versions may differ wherever skimage itself changed.
259
+ - Classic mode (`fast_mode=False`) covers 2D and 3D, the same as scikit-image.
260
+ - GPU memory decides how many shifts run concurrently. Large volumes run in more
261
+ batches but give the same results.
262
+ - On Pascal the per-block shared-memory limit (48 KB) reduces the warps per block of the
263
+ 3D sweep for wide volumes (width above about 220). The results are the same, only
264
+ less parallel.
265
+ - Speed depends mainly on the GPU's FP64 throughput. Data-centre GPUs (V100, A100,
266
+ H100, with FP64 at 1/2 of FP32) are expected to be much faster than GeForce cards.
267
+ That is not measured here.