diff --git a/rugnux/CMakeLists.txt b/rugnux/CMakeLists.txt index bdc15301c..b9a9c4835 100644 --- a/rugnux/CMakeLists.txt +++ b/rugnux/CMakeLists.txt @@ -27,6 +27,8 @@ ADD_LIBRARY(JFJochRugnux STATIC SpotWidth.h HotPixels.cpp HotPixels.h + $<$:HotPixelsGPU.cu> + HotPixelsGPU.h DiagnosticOutput.cpp DiagnosticOutput.h SpindleCuspLoss.cpp diff --git a/rugnux/HotPixels.cpp b/rugnux/HotPixels.cpp index 83e6450fd..0af35f712 100644 --- a/rugnux/HotPixels.cpp +++ b/rugnux/HotPixels.cpp @@ -74,9 +74,12 @@ HotPixelFinder::HotPixelFinder(const DiffractionExperiment &experiment, const Pi : geometry(experiment.GetDiffractionGeometry()), axis(experiment.GetGoniometer() ? experiment.GetGoniometer()->GetAxis().Normalize() : Coord(0, 0, 0)), width(experiment.GetXPixelsNumConv()), height(experiment.GetYPixelsNumConv()), - key(width * height, -1), - n_lit(width * height, 0), n_error(width * height, 0), sum_value(width * height, 0), - n_error_ring_ok(width * height, 0), error_level_sum(width * height, 0) { + key(std::make_unique_for_overwrite(width * height)), + n_lit(std::make_unique_for_overwrite(width * height)), + n_error(std::make_unique_for_overwrite(width * height)), + sum_value(std::make_unique_for_overwrite(width * height)), + n_error_ring_ok(std::make_unique_for_overwrite(width * height)), + error_level_sum(std::make_unique_for_overwrite(width * height)) { const auto &m = mask.GetMask(); // Rings of equal 2theta, RING_WIDTH_PX wide where the beam meets the detector. const float ring_rad = RING_WIDTH_PX * geometry.GetPixelSize_mm() / geometry.GetDetectorDistance_mm(); @@ -84,6 +87,9 @@ HotPixelFinder::HotPixelFinder(const DiffractionExperiment &experiment, const Pi for (size_t y = y0; y < static_cast(y1); y++) for (size_t x = 0; x < width; x++) { const size_t i = y * width + x; + n_lit[i] = n_error[i] = n_error_ring_ok[i] = 0; + sum_value[i] = error_level_sum[i] = 0; + key[i] = -1; if (m[i] != 0) continue; const float fx = static_cast(x), fy = static_cast(y); const int ring = static_cast(geometry.TwoTheta_rad(fx, fy) / ring_rad); @@ -92,17 +98,17 @@ HotPixelFinder::HotPixelFinder(const DiffractionExperiment &experiment, const Pi key[i] = ring * SECTORS + sector; } }); - for (const int32_t k : key) - if (k >= 0) { - nrings = std::max(nrings, k / SECTORS + 1); + for (size_t i = 0; i < width * height; i++) + if (key[i] >= 0) { + nrings = std::max(nrings, key[i] / SECTORS + 1); unmasked++; } key_frames.assign(static_cast(nrings) * SECTORS, 0); key_level_sum.assign(static_cast(nrings) * SECTORS, 0); key_begin.assign(static_cast(nrings) * SECTORS + 1, 0); - for (const int32_t k : key) - if (k >= 0) key_begin[k + 1]++; + for (size_t i = 0; i < width * height; i++) + if (key[i] >= 0) key_begin[key[i] + 1]++; for (size_t k = 1; k < key_begin.size(); k++) key_begin[k] += key_begin[k - 1]; } @@ -170,25 +176,10 @@ void HotPixelFinder::AddImage(const int32_t *image, std::vector &scratc ring_spread[r] = 1.4826f * static_cast(median_of(ring, n)); } - std::vector level(nkeys, 0); - std::vector threshold(nkeys, 0.0f); - for (size_t k = 0; k < nkeys; k++) { - const int r = static_cast(k / SECTORS); - level[k] = std::max(ring_level[r], sector_level[k]); - const float noise = std::max(std::sqrt(static_cast(std::max(level[k], 0))), ring_spread[r]); - threshold[k] = static_cast(level[k]) + LIT_NSIGMA * noise + LIT_OFFSET; - } + std::vector level; + std::vector threshold; + AddLevels(sector_level, ring_level, ring_spread, ring_ok, level, threshold); - // Every sum is an integer, so the result does not depend on the order the frames arrive in. - { - std::lock_guard lock(m); - frames++; - for (size_t k = 0; k < nkeys; k++) - if (ring_ok[k / SECTORS]) { - key_frames[k]++; - key_level_sum[k] += level[k]; - } - } const size_t rows_per_band = (height + BANDS - 1) / BANDS; const size_t first = next_band.fetch_add(1); for (size_t b = 0; b < BANDS; b++) { @@ -215,9 +206,74 @@ void HotPixelFinder::AddImage(const int32_t *image, std::vector &scratc } } -HotPixelFinder::Result HotPixelFinder::GetMask(double oscillation_deg, double spacing_deg, - size_t nthreads) const { +void HotPixelFinder::AddLevels(const std::vector §or_level, const std::vector &ring_level, + const std::vector &ring_spread, const std::vector &ring_ok, + std::vector &level, std::vector &threshold) { + const size_t nkeys = static_cast(nrings) * SECTORS; + level.assign(nkeys, 0); + threshold.assign(nkeys, 0.0f); + for (size_t k = 0; k < nkeys; k++) { + const int r = static_cast(k / SECTORS); + level[k] = std::max(ring_level[r], sector_level[k]); + const float noise = std::max(std::sqrt(static_cast(std::max(level[k], 0))), ring_spread[r]); + threshold[k] = static_cast(level[k]) + LIT_NSIGMA * noise + LIT_OFFSET; + } + + // Every sum is an integer, so the result does not depend on the order the frames arrive in. std::lock_guard lock(m); + frames++; + for (size_t k = 0; k < nkeys; k++) + if (ring_ok[k / SECTORS]) { + key_frames[k]++; + key_level_sum[k] += level[k]; + } +} + +#ifdef JFJOCH_USE_CUDA +void HotPixelFinder::AddDeviceImage(const int32_t *device_image, HotPixelFinderGPU::Frame &frame) { + HotPixelFinderGPU *device; + { + std::lock_guard lock(m); + if (!gpu) + gpu = std::make_unique(key.get(), width * height, key_begin, nrings, SECTORS); + device = gpu.get(); + } + std::vector count; + std::vector sector_median, ring_median, ring_mad; + device->Statistics(device_image, frame, count, sector_median, ring_median, ring_mad); + + // The same levels AddImage takes off its scratch buffer, and under the same pixel minima. + const size_t nkeys = static_cast(nrings) * SECTORS; + std::vector sector_level(nkeys, 0); + for (size_t k = 0; k < nkeys; k++) + if (count[k] >= MIN_SECTOR_PIXELS) + sector_level[k] = sector_median[k]; + std::vector ring_level(nrings, 0); + std::vector ring_spread(nrings, 0.0f); + std::vector ring_ok(nrings, 0); + for (int r = 0; r < nrings; r++) { + size_t n = 0; + for (int s = 0; s < SECTORS; s++) + n += count[r * SECTORS + s]; + if (n < MIN_RING_PIXELS) continue; + ring_ok[r] = 1; + ring_level[r] = ring_median[r]; + ring_spread[r] = 1.4826f * static_cast(ring_mad[r]); + } + + std::vector level; + std::vector threshold; + AddLevels(sector_level, ring_level, ring_spread, ring_ok, level, threshold); + device->Accumulate(device_image, frame, level, threshold, ring_ok); +} +#endif + +HotPixelFinder::Result HotPixelFinder::GetMask(double oscillation_deg, double spacing_deg, size_t nthreads) { + std::lock_guard lock(m); +#ifdef JFJOCH_USE_CUDA + if (gpu) + gpu->Download(n_lit.get(), n_error.get(), sum_value.get(), n_error_ring_ok.get(), error_level_sum.get()); +#endif Result ret; ret.frames = frames; ret.mask.assign(width * height, 0); @@ -226,7 +282,7 @@ HotPixelFinder::Result HotPixelFinder::GetMask(double oscillation_deg, double sp // The chance rate per ring, from the pixels lit on no more than half of their frames: whatever // lights those - reflections, zingers, noise above the bound - lights a defect-free pixel too. std::vector lit(nrings, 0.0), seen(nrings, 0.0); - for (size_t i = 0; i < key.size(); i++) + for (size_t i = 0; i < width * height; i++) if (key[i] >= 0 && n_valid(i) > 0 && 2 * n_lit[i] <= n_valid(i)) { lit[key[i] / SECTORS] += n_lit[i]; seen[key[i] / SECTORS] += n_valid(i); diff --git a/rugnux/HotPixels.h b/rugnux/HotPixels.h index bd183ad0d..16e6e965b 100644 --- a/rugnux/HotPixels.h +++ b/rugnux/HotPixels.h @@ -40,11 +40,15 @@ #include #include +#include #include #include #include "../common/DiffractionExperiment.h" #include "../common/PixelMask.h" +#ifdef JFJOCH_USE_CUDA +#include "HotPixelsGPU.h" +#endif class HotPixelFinder { public: @@ -83,9 +87,16 @@ public: // safe; `scratch` is the caller's own, reused across its calls. void AddImage(const int32_t *image, std::vector &scratch); +#ifdef JFJOCH_USE_CUDA + // The same for a frame preprocessed on the device, on `frame`'s stream - the caller's own, as + // `scratch` above. The per-pixel sums are then kept on the device and replace the host's when the + // mask is read, so a finder is fed one way or the other, not both. Thread safe. + void AddDeviceImage(const int32_t *device_image, HotPixelFinderGPU::Frame &frame); +#endif + // The mask, from the frames added so far. oscillation_deg is the rotation per image and // spacing_deg the rotation between two consecutive sampled frames. - [[nodiscard]] Result GetMask(double oscillation_deg, double spacing_deg, size_t nthreads) const; + [[nodiscard]] Result GetMask(double oscillation_deg, double spacing_deg, size_t nthreads); private: const DiffractionGeometry geometry; @@ -93,8 +104,10 @@ private: const size_t width, height; int nrings = 0; - // Ring * SECTORS + sector of every pixel, -1 where the pixel is already masked. - std::vector key; + // Ring * SECTORS + sector of every pixel, -1 where the pixel is already masked. The per-pixel + // arrays are hundreds of megabytes on a large detector, so they are left unwritten when allocated + // and first written by the constructor's parallel pass rather than zeroed on one thread. + std::unique_ptr key; // Where each ring-sector's pixels start in a scratch buffer laid out by key. std::vector key_begin; size_t unmasked = 0; @@ -106,16 +119,25 @@ private: std::atomic next_band{0}; mutable std::mutex m; uint32_t frames = 0; - std::vector n_lit, n_error; - std::vector sum_value; + std::unique_ptr n_lit, n_error; + std::unique_ptr sum_value; // A pixel's valid frames and the sum of its ring-sector level over them, kept per ring-sector - the // frames its ring had a level on, and the sum of the level over those - less what the pixel's own // error frames among them took out. Integers, so exactly the per-pixel sums, at a fraction of the // memory traffic per frame. std::vector key_frames; std::vector key_level_sum; - std::vector n_error_ring_ok; - std::vector error_level_sum; + std::unique_ptr n_error_ring_ok; + std::unique_ptr error_level_sum; +#ifdef JFJOCH_USE_CUDA + std::unique_ptr gpu; // built by the first device frame +#endif + + // Each ring-sector's level and lit threshold, from the frame's order statistics, and the frame's + // share of the per-key sums. The host and the device path both come through here. + void AddLevels(const std::vector §or_level, const std::vector &ring_level, + const std::vector &ring_spread, const std::vector &ring_ok, + std::vector &level, std::vector &threshold); [[nodiscard]] int n_valid(size_t i) const { return key_frames[key[i]] - n_error_ring_ok[i]; } [[nodiscard]] int64_t sum_level(size_t i) const { return key_level_sum[key[i]] - error_level_sum[i]; } }; diff --git a/rugnux/HotPixelsGPU.cu b/rugnux/HotPixelsGPU.cu new file mode 100644 index 000000000..b17ecb098 --- /dev/null +++ b/rugnux/HotPixelsGPU.cu @@ -0,0 +1,234 @@ +// SPDX-FileCopyrightText: 2026 Filip Leonarski, Paul Scherrer Institute +// SPDX-License-Identifier: GPL-3.0-only + +#include "HotPixelsGPU.h" + +#include "../common/JFJochException.h" + +namespace { + +void cuda_err(cudaError_t val) { + if (val != cudaSuccess) + throw JFJochException(JFJochExceptionCategory::GPUCUDAError, cudaGetErrorString(val)); +} + +constexpr int THREADS = 256; + +// Masked or error value, and saturated: neither has a count to rank. +__device__ bool is_valid(int32_t v) { + return v != INT32_MIN && v != INT32_MAX; +} + +// The rank-th smallest of the keys a block's elements j in [begin, end) give, where key_of(j, key) +// says whether element j has one. Radix selection, eight bits at a time from the top: a histogram of +// the next digit among the keys that share the digits already fixed says which digit the rank-th +// falls in. Exact for any keys, so no range has to be assumed. Called by all THREADS of the block. +template +__device__ uint32_t block_select(uint32_t begin, uint32_t end, uint32_t rank, F key_of) { + __shared__ uint32_t hist[256]; + __shared__ uint32_t s_prefix, s_rank; + uint32_t prefix = 0; + for (int shift = 24; shift >= 0; shift -= 8) { + hist[threadIdx.x] = 0; + __syncthreads(); + const uint32_t fixed = shift == 24 ? 0u : ~0u << (shift + 8); + for (uint32_t j = begin + threadIdx.x; j < end; j += THREADS) { + uint32_t k; + if (key_of(j, k) && (k & fixed) == prefix) + atomicAdd(&hist[(k >> shift) & 255u], 1u); + } + __syncthreads(); + if (threadIdx.x == 0) { + uint32_t d = 0; + while (rank >= hist[d]) { + rank -= hist[d]; + d++; + } + s_prefix = prefix | (d << shift); + s_rank = rank; + } + __syncthreads(); + prefix = s_prefix; + rank = s_rank; + } + return prefix; +} + +// int32 to a uint32 that sorts the same way, and back. +__device__ uint32_t order_key(int32_t v) { return static_cast(v) ^ 0x80000000u; } +__device__ int32_t from_order_key(uint32_t k) { return static_cast(k ^ 0x80000000u); } + +// One block per ring-sector: its valid pixels and their lower median. +__global__ void sector_kernel(const int32_t *__restrict__ image, const uint32_t *__restrict__ pixels, + const uint32_t *__restrict__ key_begin, uint32_t *__restrict__ count, + int32_t *__restrict__ median) { + const uint32_t begin = key_begin[blockIdx.x], end = key_begin[blockIdx.x + 1]; + __shared__ uint32_t s_n; + if (threadIdx.x == 0) s_n = 0; + __syncthreads(); + uint32_t n = 0; + for (uint32_t j = begin + threadIdx.x; j < end; j += THREADS) + n += is_valid(image[pixels[j]]); + atomicAdd(&s_n, n); + __syncthreads(); + n = s_n; + if (threadIdx.x == 0) { + count[blockIdx.x] = n; + median[blockIdx.x] = 0; + } + if (n == 0) + return; + const uint32_t m = block_select(begin, end, n / 2, [&](uint32_t j, uint32_t &k) { + const int32_t v = image[pixels[j]]; + k = order_key(v); + return is_valid(v); + }); + if (threadIdx.x == 0) + median[blockIdx.x] = from_order_key(m); +} + +// One block per ring: the lower median of its valid pixels, and the lower median of their absolute +// deviations from it - written as the host writes it, |v - median| in int. +__global__ void ring_kernel(const int32_t *__restrict__ image, const uint32_t *__restrict__ pixels, + const uint32_t *__restrict__ key_begin, const uint32_t *__restrict__ count, + int sectors, int32_t *__restrict__ ring_median, int32_t *__restrict__ ring_mad) { + const int first = blockIdx.x * sectors; + const uint32_t begin = key_begin[first], end = key_begin[first + sectors]; + uint32_t n = 0; + for (int s = 0; s < sectors; s++) + n += count[first + s]; + if (threadIdx.x == 0) { + ring_median[blockIdx.x] = 0; + ring_mad[blockIdx.x] = 0; + } + if (n == 0) + return; + const int32_t m = from_order_key(block_select(begin, end, n / 2, [&](uint32_t j, uint32_t &k) { + const int32_t v = image[pixels[j]]; + k = order_key(v); + return is_valid(v); + })); + const uint32_t mad = block_select(begin, end, n / 2, [&](uint32_t j, uint32_t &k) { + const int32_t v = image[pixels[j]]; + k = static_cast(abs(v - m)); + return is_valid(v); + }); + if (threadIdx.x == 0) { + ring_median[blockIdx.x] = m; + ring_mad[blockIdx.x] = static_cast(mad); + } +} + +// HotPixelFinder::AddImage's per-pixel loop, line for line. +__global__ void accumulate_kernel(const int32_t *__restrict__ image, const int32_t *__restrict__ key, + size_t npixels, int sectors, const int32_t *__restrict__ level, + const float *__restrict__ threshold, const char *__restrict__ ring_ok, + uint16_t *__restrict__ n_lit, uint16_t *__restrict__ n_error, + int64_t *__restrict__ sum_value, uint16_t *__restrict__ n_error_ring_ok, + int64_t *__restrict__ error_level_sum) { + for (size_t i = blockIdx.x * static_cast(blockDim.x) + threadIdx.x; i < npixels; + i += static_cast(blockDim.x) * gridDim.x) { + const int32_t k = key[i], v = image[i]; + if (k < 0) continue; + if (v == INT32_MIN) { + n_error[i]++; + if (ring_ok[k / sectors]) { + n_error_ring_ok[i]++; + error_level_sum[i] += level[k]; + } + continue; + } + if (!ring_ok[k / sectors]) continue; + sum_value[i] += v; + if (v == INT32_MAX || static_cast(v) > threshold[k]) + n_lit[i]++; + } +} + +} // namespace + +HotPixelFinderGPU::HotPixelFinderGPU(const int32_t *host_key, size_t npixels, + const std::vector &host_key_begin, int nrings, int sectors) + : npixels(npixels), nkeys(static_cast(nrings) * sectors), nrings(nrings), + sectors(sectors), + key(npixels), pixels_by_key(host_key_begin.back()), key_begin(host_key_begin.size()), + n_lit(npixels), n_error(npixels), n_error_ring_ok(npixels), + sum_value(npixels), error_level_sum(npixels) { + std::vector pixels(host_key_begin.back()); + std::vector filled(host_key_begin.begin(), host_key_begin.end() - 1); + for (size_t i = 0; i < npixels; i++) + if (host_key[i] >= 0) + pixels[filled[host_key[i]]++] = static_cast(i); + + CudaStream stream; + cuda_err(cudaMemcpyAsync(key, host_key, npixels * sizeof(int32_t), cudaMemcpyHostToDevice, stream)); + cuda_err(cudaMemcpyAsync(pixels_by_key, pixels.data(), pixels.size() * sizeof(uint32_t), + cudaMemcpyHostToDevice, stream)); + cuda_err(cudaMemcpyAsync(key_begin, host_key_begin.data(), host_key_begin.size() * sizeof(uint32_t), + cudaMemcpyHostToDevice, stream)); + cuda_err(cudaMemsetAsync(n_lit, 0, npixels * sizeof(uint16_t), stream)); + cuda_err(cudaMemsetAsync(n_error, 0, npixels * sizeof(uint16_t), stream)); + cuda_err(cudaMemsetAsync(n_error_ring_ok, 0, npixels * sizeof(uint16_t), stream)); + cuda_err(cudaMemsetAsync(sum_value, 0, npixels * sizeof(int64_t), stream)); + cuda_err(cudaMemsetAsync(error_level_sum, 0, npixels * sizeof(int64_t), stream)); + cuda_err(cudaStreamSynchronize(stream)); +} + +void HotPixelFinderGPU::Statistics(const int32_t *device_image, Frame &frame, std::vector &count, + std::vector §or_median, std::vector &ring_median, + std::vector &ring_mad) { + if (!frame.count.get()) { + frame.count = CudaDevicePtr(nkeys); + frame.sector_median = CudaDevicePtr(nkeys); + frame.ring_median = CudaDevicePtr(nrings); + frame.ring_mad = CudaDevicePtr(nrings); + frame.level = CudaDevicePtr(nkeys); + frame.threshold = CudaDevicePtr(nkeys); + frame.ring_ok = CudaDevicePtr(nrings); + } + const cudaStream_t stream = *frame.stream; + sector_kernel<<(nkeys), THREADS, 0, stream>>>(device_image, pixels_by_key, key_begin, frame.count, + frame.sector_median); + cuda_err(cudaGetLastError()); + ring_kernel<<>>(device_image, pixels_by_key, key_begin, frame.count, sectors, + frame.ring_median, frame.ring_mad); + cuda_err(cudaGetLastError()); + + count.resize(nkeys); + sector_median.resize(nkeys); + ring_median.resize(nrings); + ring_mad.resize(nrings); + cuda_err(cudaMemcpyAsync(count.data(), frame.count, nkeys * sizeof(uint32_t), cudaMemcpyDeviceToHost, stream)); + cuda_err(cudaMemcpyAsync(sector_median.data(), frame.sector_median, nkeys * sizeof(int32_t), + cudaMemcpyDeviceToHost, stream)); + cuda_err(cudaMemcpyAsync(ring_median.data(), frame.ring_median, nrings * sizeof(int32_t), + cudaMemcpyDeviceToHost, stream)); + cuda_err(cudaMemcpyAsync(ring_mad.data(), frame.ring_mad, nrings * sizeof(int32_t), + cudaMemcpyDeviceToHost, stream)); + cuda_err(cudaStreamSynchronize(stream)); +} + +void HotPixelFinderGPU::Accumulate(const int32_t *device_image, Frame &frame, const std::vector &level, + const std::vector &threshold, const std::vector &ring_ok) { + const cudaStream_t stream = *frame.stream; + cuda_err(cudaMemcpyAsync(frame.level, level.data(), nkeys * sizeof(int32_t), cudaMemcpyHostToDevice, stream)); + cuda_err(cudaMemcpyAsync(frame.threshold, threshold.data(), nkeys * sizeof(float), cudaMemcpyHostToDevice, + stream)); + cuda_err(cudaMemcpyAsync(frame.ring_ok, ring_ok.data(), nrings * sizeof(char), cudaMemcpyHostToDevice, stream)); + + std::lock_guard lock(accumulate_mutex); + accumulate_kernel<<((npixels + THREADS - 1) / THREADS), THREADS, 0, stream>>>( + device_image, key, npixels, sectors, frame.level, frame.threshold, frame.ring_ok, + n_lit, n_error, sum_value, n_error_ring_ok, error_level_sum); + cuda_err(cudaGetLastError()); + cuda_err(cudaStreamSynchronize(stream)); +} + +void HotPixelFinderGPU::Download(uint16_t *host_n_lit, uint16_t *host_n_error, int64_t *host_sum_value, + uint16_t *host_n_error_ring_ok, int64_t *host_error_level_sum) { + cuda_err(cudaMemcpy(host_n_lit, n_lit, npixels * sizeof(uint16_t), cudaMemcpyDeviceToHost)); + cuda_err(cudaMemcpy(host_n_error, n_error, npixels * sizeof(uint16_t), cudaMemcpyDeviceToHost)); + cuda_err(cudaMemcpy(host_sum_value, sum_value, npixels * sizeof(int64_t), cudaMemcpyDeviceToHost)); + cuda_err(cudaMemcpy(host_n_error_ring_ok, n_error_ring_ok, npixels * sizeof(uint16_t), cudaMemcpyDeviceToHost)); + cuda_err(cudaMemcpy(host_error_level_sum, error_level_sum, npixels * sizeof(int64_t), cudaMemcpyDeviceToHost)); +} diff --git a/rugnux/HotPixelsGPU.h b/rugnux/HotPixelsGPU.h new file mode 100644 index 000000000..f062e64cf --- /dev/null +++ b/rugnux/HotPixelsGPU.h @@ -0,0 +1,66 @@ +// SPDX-FileCopyrightText: 2026 Filip Leonarski, Paul Scherrer Institute +// SPDX-License-Identifier: GPL-3.0-only + +#pragma once + +#include +#include +#include +#include + +#include "../image_analysis/indexing/CUDAMemHelpers.h" + +// The device half of HotPixelFinder, for frames already preprocessed on the GPU: the per-frame order +// statistics (each ring-sector's median, each ring's median and median absolute deviation) and the +// per-pixel sums run where the image already is, and only the per-key statistics - tens of thousands +// of numbers - come to the host, which turns them into levels and thresholds with the very code the +// host path uses. Every statistic is an exact order statistic of integers and every sum an integer, +// so the sums, and with them the mask, are identical to what HotPixelFinder::AddImage produces. +class HotPixelFinderGPU { + const size_t npixels; + const size_t nkeys; + const int nrings; + const int sectors; + + CudaDevicePtr key; // ring * sectors + sector of each pixel, -1 masked + CudaDevicePtr pixels_by_key; // the unmasked pixels, grouped by key + CudaDevicePtr key_begin; // where each key's pixels start in pixels_by_key + + // The per-pixel sums, exactly those of HotPixelFinder. + CudaDevicePtr n_lit, n_error, n_error_ring_ok; + CudaDevicePtr sum_value, error_level_sum; + // Frames are selected on their workers' streams in parallel, but each pixel's sums are plain + // read-modify-writes, so one frame at a time adds to them. + std::mutex accumulate_mutex; + +public: + // One worker's buffers, on the stream its frames are preprocessed on. + struct Frame { + explicit Frame(std::shared_ptr stream) : stream(std::move(stream)) {} + std::shared_ptr stream; + CudaDevicePtr count; // valid pixels per key + CudaDevicePtr sector_median; // per key + CudaDevicePtr ring_median, ring_mad; + CudaDevicePtr level; + CudaDevicePtr threshold; + CudaDevicePtr ring_ok; + }; + + HotPixelFinderGPU(const int32_t *key, size_t npixels, const std::vector &key_begin, int nrings, + int sectors); + + // The lower median of the valid values of each key (count[k] of them, 0 where there are none), and + // of each ring the median and the lower median of the absolute deviations from it. + void Statistics(const int32_t *device_image, Frame &frame, std::vector &count, + std::vector §or_median, std::vector &ring_median, + std::vector &ring_mad); + + // Add the frame to the per-pixel sums, with each key's level and lit threshold and each ring's + // verdict on whether it has a level at all - as HotPixelFinder::AddImage does. + void Accumulate(const int32_t *device_image, Frame &frame, const std::vector &level, + const std::vector &threshold, const std::vector &ring_ok); + + // The per-pixel sums, npixels each. + void Download(uint16_t *n_lit, uint16_t *n_error, int64_t *sum_value, uint16_t *n_error_ring_ok, + int64_t *error_level_sum); +}; diff --git a/rugnux/Rugnux.cpp b/rugnux/Rugnux.cpp index b79718c88..8e42f8c4b 100644 --- a/rugnux/Rugnux.cpp +++ b/rugnux/Rugnux.cpp @@ -54,6 +54,10 @@ #include "../image_analysis/azint/AzIntEngineCPU.h" #include "../image_analysis/image_preprocessing/ImagePreprocessorCPU.h" #include "../image_analysis/image_preprocessing/ImagePreprocessorBuffer.h" +#ifdef JFJOCH_USE_CUDA +#include "../image_analysis/image_preprocessing/ImagePreprocessorGPU.h" +#include "../image_analysis/image_preprocessing/ImagePreprocessorBufferGPU.h" +#endif #include "../image_analysis/scale_merge/Merge.h" #include "../image_analysis/scale_merge/RfreeFlags.h" #include "../image_analysis/scale_merge/RotationScaleMerge.h" @@ -1652,8 +1656,25 @@ void Rugnux::MaskDefectivePixels(int start_image, const std::vector &sample const size_t nworkers = std::min(nthreads, std::min(PRESCAN_MAX_WORKERS, sample.size())); for (size_t t = 0; t < nworkers; t++) futures.emplace_back(std::async(std::launch::async, [&] { - ImagePreprocessorCPU preprocessor(experiment_, pixel_mask_); - ImagePreprocessorBuffer image(experiment_.GetPixelsNum()); + // With a GPU the frame is decoded, preprocessed and analysed on the device - only the + // compressed chunk crosses PCIe - and the result is the same to the bit (HotPixelsGPU.h). + std::unique_ptr preprocessor; + std::unique_ptr image; +#ifdef JFJOCH_USE_CUDA + std::optional frame; + if (get_gpu_count() > 0) { + auto stream = std::make_shared(); + preprocessor = std::make_unique(experiment_, pixel_mask_, stream, + /*copy_image_to_host=*/false); + image = std::make_unique(experiment_.GetPixelsNum(), + /*host_mirror=*/false); + frame.emplace(stream); + } +#endif + if (!preprocessor) { + preprocessor = std::make_unique(experiment_, pixel_mask_); + image = std::make_unique(experiment_.GetPixelsNum()); + } JFJochReaderRawImage raw; std::vector buffer; std::vector scratch; @@ -1661,13 +1682,21 @@ void Rugnux::MaskDefectivePixels(int start_image, const std::vector &sample const int image_idx = start_image + sample[i] * config_.stride; try { if (!reader_.ReadRawImage(image_idx, raw)) continue; - preprocessor.Analyze(image, raw.image.GetUncompressedPtr(buffer), raw.image.GetMode()); + ImageStatistics stats; + if (!preprocessor->AnalyzeCompressed(*image, raw.image, stats)) + preprocessor->Analyze(*image, raw.image.GetUncompressedPtr(buffer), raw.image.GetMode()); } catch (const std::exception &e) { if (IsFatalResourceError(e)) throw; logger.Warning("Defective pixels: failed to read image {}: {}", image_idx, e.what()); continue; } - finder.AddImage(image.data(), scratch); +#ifdef JFJOCH_USE_CUDA + if (frame) { + finder.AddDeviceImage(image->getGPUBuffer(), *frame); + continue; + } +#endif + finder.AddImage(image->data(), scratch); } })); for (auto &f : futures) f.get(); diff --git a/tests/HotPixelFinderTest.cpp b/tests/HotPixelFinderTest.cpp index 6fc72fcb1..a90adfb49 100644 --- a/tests/HotPixelFinderTest.cpp +++ b/tests/HotPixelFinderTest.cpp @@ -7,6 +7,7 @@ #include #include +#include "../common/CUDAWrapper.h" #include "../common/DetectorSetup.h" #include "../common/DiffractionExperiment.h" #include "../common/PixelMask.h" @@ -63,3 +64,72 @@ TEST_CASE("HotPixelFinder_PersistentPixelNotBragg", "[HotPixelFinder]") { CHECK(result.hot == 1); CHECK(result.error == 1); } + +#ifdef JFJOCH_USE_CUDA +// The device path against the host one, on frames that take every branch of both: a background bright +// enough on one annulus that the host reads its rings' statistics off the exact selection rather than +// its histogram, negative counts, saturated and error pixels scattered at random, masked pixels, and a +// few hundred planted pixels whose excess and persistence straddle every threshold, so that a level or +// a threshold one count off would move some of them across. The masks must be identical. +TEST_CASE("HotPixelFinder_DeviceMatchesHost", "[HotPixelFinder]") { + if (get_gpu_count() == 0) { + WARN("No CUDA GPU present. Skipping HotPixelFinder_DeviceMatchesHost"); + return; + } + DiffractionExperiment x(DetDECTRIS(W, H, "Test detector", "")); + x.IncidentEnergy_keV(WVL_1A_IN_KEV).DetectorDistance_mm(10.0f); + x.BeamX_pxl(static_cast(C) + 0.3f).BeamY_pxl(static_cast(C) - 0.6f); + x.Goniometer(GoniometerAxis("omega", 0.0f, static_cast(OSC_DEG), Coord(1, 0, 0), std::nullopt)); + PixelMask pixel_mask(x); + std::vector masked(static_cast(W) * H, 0); + for (int y = 100; y < 110; y++) + masked[I(30, y)] = 1; + pixel_mask.LoadUserMask(x, masked); + + HotPixelFinder host(x, pixel_mask, 4), device(x, pixel_mask, 4); + HotPixelFinderGPU::Frame frame(std::make_shared()); + CudaDevicePtr device_image(static_cast(W) * H); + + std::mt19937 rng(7); + std::uniform_int_distribution coord(0, W - 1); + struct Planted { size_t i; int excess; double rate; }; + std::vector planted; + for (int p = 0; p < 300; p++) + planted.push_back({I(coord(rng), coord(rng)), 5 + p / 3, 0.2 + 0.8 * (p % 7) / 6.0}); + + std::vector image(static_cast(W) * H), scratch; + std::uniform_real_distribution u(0.0, 1.0); + for (int f = 0; f < NFRAMES; f++) { + for (int y = 0; y < H; y++) + for (int x_ = 0; x_ < W; x_++) { + const double r = std::hypot(x_ - C, y - C); + const double mean = 5.0 + 45.0 * std::exp(-0.5 * (r - 82.0) * (r - 82.0) / 16.0) + + (r > 40.0 && r < 50.0 ? 3000.0 : 0.0); + int32_t v = std::poisson_distribution(mean)(rng) - (r > 110.0 ? 3 : 0); + const double d = u(rng); + if (d < 0.002) v = INT32_MIN; + else if (d < 0.003) v = INT32_MAX; + image[I(x_, y)] = v; + } + for (const auto &p : planted) + if (u(rng) < p.rate && image[p.i] != INT32_MIN && image[p.i] != INT32_MAX) + image[p.i] += p.excess; + for (size_t i = 0; i < image.size(); i++) + if (pixel_mask.GetMask()[i] != 0) + image[i] = INT32_MIN; // as the preprocessor leaves a masked pixel + + host.AddImage(image.data(), scratch); + REQUIRE(cudaMemcpy(device_image, image.data(), image.size() * sizeof(int32_t), cudaMemcpyHostToDevice) + == cudaSuccess); + device.AddDeviceImage(device_image, frame); + } + + const auto expected = host.GetMask(OSC_DEG, SPACING_DEG, 4); + const auto result = device.GetMask(OSC_DEG, SPACING_DEG, 4); + CHECK(expected.hot > 10); + CHECK(result.frames == expected.frames); + CHECK(result.hot == expected.hot); + CHECK(result.error == expected.error); + CHECK(result.mask == expected.mask); +} +#endif