HotPixelFinder: the defective-pixel pass on the GPU, bit-identical
MaskDefectivePixels re-read its 60 sample frames with 8 CPU workers - host bitshuffle/LZ4 decode, CPU preprocessing, then per frame a scatter by ring-sector, nth_element medians and per-pixel sums over ~22 B/px of state - and was bound by memory bandwidth: 2.9 s wall on an EIGER2 16M sweep, the largest single step left in the pre-scan. With a GPU each worker now decodes and preprocesses the frame on the device (ImagePreprocessorGPU::AnalyzeCompressed, as the image loops do), and HotPixelFinderGPU takes the order statistics there: one block per ring-sector and per ring, radix selection eight bits at a time, which is exact for any values, so the histogram-plus-fallback of the host path is not needed. Only the per-key statistics (count, sector median, ring median and MAD) come back; levels and thresholds are computed on the host by the same function the CPU path now calls (AddLevels), uploaded, and a per-pixel kernel does AddImage's loop line for line, including the float comparison. The per-pixel sums stay on the device and are downloaded once when the mask is read. The CPU path is unchanged. The constructor's ~470 MB of per-pixel arrays are no longer zeroed on the calling thread: they are allocated unwritten and first written by the existing parallel key pass. Exactness: a temporary check that ran both finders side by side on the same frames (CPU decode + preprocess against GPU decode + preprocess) found every per-pixel and per-key sum identical on myob, cytc, lyso and sparse; the new test HotPixelFinder_DeviceMatchesHost compares the masks on synthetic frames that take every branch (histogram fallback, negatives, saturated/error/masked pixels, 134 masked). p.hkl, p.mtz, p_P1.mtz and p_unmerged.mtz are byte-identical to the previous GPU build on myob and cytc; the masked counts (3/2/0) are unchanged. myob GPU, quiet box: MaskDefectivePixels 2.90 s -> 0.42 s, total 20.4 -> 19.4 s, peak RSS 3.52 -> 3.60 GB. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01D1G8gJVAy6gp1K5Dz3NE5C
This commit is contained in:
1 parent
d71cd5b85e
commit
a804cf61b7
7 files changed
+519
-40
No files matched your search
@@ -27,6 +27,8 @@ ADD_LIBRARY(JFJochRugnux STATIC
|
||||
SpotWidth.h
|
||||
HotPixels.cpp
|
||||
HotPixels.h
|
||||
$<$<BOOL:${JFJOCH_CUDA_AVAILABLE}>:HotPixelsGPU.cu>
|
||||
HotPixelsGPU.h
|
||||
DiagnosticOutput.cpp
|
||||
DiagnosticOutput.h
|
||||
SpindleCuspLoss.cpp
|
||||
|
||||
+85
-29
@@ -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<int32_t[]>(width * height)),
|
||||
n_lit(std::make_unique_for_overwrite<uint16_t[]>(width * height)),
|
||||
n_error(std::make_unique_for_overwrite<uint16_t[]>(width * height)),
|
||||
sum_value(std::make_unique_for_overwrite<int64_t[]>(width * height)),
|
||||
n_error_ring_ok(std::make_unique_for_overwrite<uint16_t[]>(width * height)),
|
||||
error_level_sum(std::make_unique_for_overwrite<int64_t[]>(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<size_t>(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<float>(x), fy = static_cast<float>(y);
|
||||
const int ring = static_cast<int>(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<size_t>(nrings) * SECTORS, 0);
|
||||
key_level_sum.assign(static_cast<size_t>(nrings) * SECTORS, 0);
|
||||
key_begin.assign(static_cast<size_t>(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<int32_t> &scratc
|
||||
ring_spread[r] = 1.4826f * static_cast<float>(median_of(ring, n));
|
||||
}
|
||||
|
||||
std::vector<int32_t> level(nkeys, 0);
|
||||
std::vector<float> threshold(nkeys, 0.0f);
|
||||
for (size_t k = 0; k < nkeys; k++) {
|
||||
const int r = static_cast<int>(k / SECTORS);
|
||||
level[k] = std::max(ring_level[r], sector_level[k]);
|
||||
const float noise = std::max(std::sqrt(static_cast<float>(std::max(level[k], 0))), ring_spread[r]);
|
||||
threshold[k] = static_cast<float>(level[k]) + LIT_NSIGMA * noise + LIT_OFFSET;
|
||||
}
|
||||
std::vector<int32_t> level;
|
||||
std::vector<float> 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<int32_t> &scratc
|
||||
}
|
||||
}
|
||||
|
||||
HotPixelFinder::Result HotPixelFinder::GetMask(double oscillation_deg, double spacing_deg,
|
||||
size_t nthreads) const {
|
||||
void HotPixelFinder::AddLevels(const std::vector<int32_t> §or_level, const std::vector<int32_t> &ring_level,
|
||||
const std::vector<float> &ring_spread, const std::vector<char> &ring_ok,
|
||||
std::vector<int32_t> &level, std::vector<float> &threshold) {
|
||||
const size_t nkeys = static_cast<size_t>(nrings) * SECTORS;
|
||||
level.assign(nkeys, 0);
|
||||
threshold.assign(nkeys, 0.0f);
|
||||
for (size_t k = 0; k < nkeys; k++) {
|
||||
const int r = static_cast<int>(k / SECTORS);
|
||||
level[k] = std::max(ring_level[r], sector_level[k]);
|
||||
const float noise = std::max(std::sqrt(static_cast<float>(std::max(level[k], 0))), ring_spread[r]);
|
||||
threshold[k] = static_cast<float>(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<HotPixelFinderGPU>(key.get(), width * height, key_begin, nrings, SECTORS);
|
||||
device = gpu.get();
|
||||
}
|
||||
std::vector<uint32_t> count;
|
||||
std::vector<int32_t> 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<size_t>(nrings) * SECTORS;
|
||||
std::vector<int32_t> 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<int32_t> ring_level(nrings, 0);
|
||||
std::vector<float> ring_spread(nrings, 0.0f);
|
||||
std::vector<char> 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<float>(ring_mad[r]);
|
||||
}
|
||||
|
||||
std::vector<int32_t> level;
|
||||
std::vector<float> 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<double> 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);
|
||||
|
||||
+29
-7
@@ -40,11 +40,15 @@
|
||||
|
||||
#include <atomic>
|
||||
#include <cstdint>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <vector>
|
||||
|
||||
#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<int32_t> &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<int32_t> 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<int32_t[]> key;
|
||||
// Where each ring-sector's pixels start in a scratch buffer laid out by key.
|
||||
std::vector<uint32_t> key_begin;
|
||||
size_t unmasked = 0;
|
||||
@@ -106,16 +119,25 @@ private:
|
||||
std::atomic<size_t> next_band{0};
|
||||
mutable std::mutex m;
|
||||
uint32_t frames = 0;
|
||||
std::vector<uint16_t> n_lit, n_error;
|
||||
std::vector<int64_t> sum_value;
|
||||
std::unique_ptr<uint16_t[]> n_lit, n_error;
|
||||
std::unique_ptr<int64_t[]> 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<uint16_t> key_frames;
|
||||
std::vector<int64_t> key_level_sum;
|
||||
std::vector<uint16_t> n_error_ring_ok;
|
||||
std::vector<int64_t> error_level_sum;
|
||||
std::unique_ptr<uint16_t[]> n_error_ring_ok;
|
||||
std::unique_ptr<int64_t[]> error_level_sum;
|
||||
#ifdef JFJOCH_USE_CUDA
|
||||
std::unique_ptr<HotPixelFinderGPU> 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<int32_t> §or_level, const std::vector<int32_t> &ring_level,
|
||||
const std::vector<float> &ring_spread, const std::vector<char> &ring_ok,
|
||||
std::vector<int32_t> &level, std::vector<float> &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]; }
|
||||
};
|
||||
@@ -0,0 +1,234 @@
|
||||
// SPDX-FileCopyrightText: 2026 Filip Leonarski, Paul Scherrer Institute <filip.leonarski@psi.ch>
|
||||
// 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 <class F>
|
||||
__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<uint32_t>(v) ^ 0x80000000u; }
|
||||
__device__ int32_t from_order_key(uint32_t k) { return static_cast<int32_t>(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<uint32_t>(abs(v - m));
|
||||
return is_valid(v);
|
||||
});
|
||||
if (threadIdx.x == 0) {
|
||||
ring_median[blockIdx.x] = m;
|
||||
ring_mad[blockIdx.x] = static_cast<int32_t>(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<size_t>(blockDim.x) + threadIdx.x; i < npixels;
|
||||
i += static_cast<size_t>(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<float>(v) > threshold[k])
|
||||
n_lit[i]++;
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
HotPixelFinderGPU::HotPixelFinderGPU(const int32_t *host_key, size_t npixels,
|
||||
const std::vector<uint32_t> &host_key_begin, int nrings, int sectors)
|
||||
: npixels(npixels), nkeys(static_cast<size_t>(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<uint32_t> pixels(host_key_begin.back());
|
||||
std::vector<uint32_t> 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<uint32_t>(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<uint32_t> &count,
|
||||
std::vector<int32_t> §or_median, std::vector<int32_t> &ring_median,
|
||||
std::vector<int32_t> &ring_mad) {
|
||||
if (!frame.count.get()) {
|
||||
frame.count = CudaDevicePtr<uint32_t>(nkeys);
|
||||
frame.sector_median = CudaDevicePtr<int32_t>(nkeys);
|
||||
frame.ring_median = CudaDevicePtr<int32_t>(nrings);
|
||||
frame.ring_mad = CudaDevicePtr<int32_t>(nrings);
|
||||
frame.level = CudaDevicePtr<int32_t>(nkeys);
|
||||
frame.threshold = CudaDevicePtr<float>(nkeys);
|
||||
frame.ring_ok = CudaDevicePtr<char>(nrings);
|
||||
}
|
||||
const cudaStream_t stream = *frame.stream;
|
||||
sector_kernel<<<static_cast<unsigned>(nkeys), THREADS, 0, stream>>>(device_image, pixels_by_key, key_begin, frame.count,
|
||||
frame.sector_median);
|
||||
cuda_err(cudaGetLastError());
|
||||
ring_kernel<<<nrings, THREADS, 0, stream>>>(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<int32_t> &level,
|
||||
const std::vector<float> &threshold, const std::vector<char> &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<<<static_cast<unsigned>((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));
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
// SPDX-FileCopyrightText: 2026 Filip Leonarski, Paul Scherrer Institute <filip.leonarski@psi.ch>
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <vector>
|
||||
|
||||
#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<int32_t> key; // ring * sectors + sector of each pixel, -1 masked
|
||||
CudaDevicePtr<uint32_t> pixels_by_key; // the unmasked pixels, grouped by key
|
||||
CudaDevicePtr<uint32_t> key_begin; // where each key's pixels start in pixels_by_key
|
||||
|
||||
// The per-pixel sums, exactly those of HotPixelFinder.
|
||||
CudaDevicePtr<uint16_t> n_lit, n_error, n_error_ring_ok;
|
||||
CudaDevicePtr<int64_t> 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<CudaStream> stream) : stream(std::move(stream)) {}
|
||||
std::shared_ptr<CudaStream> stream;
|
||||
CudaDevicePtr<uint32_t> count; // valid pixels per key
|
||||
CudaDevicePtr<int32_t> sector_median; // per key
|
||||
CudaDevicePtr<int32_t> ring_median, ring_mad;
|
||||
CudaDevicePtr<int32_t> level;
|
||||
CudaDevicePtr<float> threshold;
|
||||
CudaDevicePtr<char> ring_ok;
|
||||
};
|
||||
|
||||
HotPixelFinderGPU(const int32_t *key, size_t npixels, const std::vector<uint32_t> &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<uint32_t> &count,
|
||||
std::vector<int32_t> §or_median, std::vector<int32_t> &ring_median,
|
||||
std::vector<int32_t> &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<int32_t> &level,
|
||||
const std::vector<float> &threshold, const std::vector<char> &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);
|
||||
};
|
||||
+33
-4
@@ -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<int> &sample
|
||||
const size_t nworkers = std::min<size_t>(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<ImagePreprocessor> preprocessor;
|
||||
std::unique_ptr<ImagePreprocessorBuffer> image;
|
||||
#ifdef JFJOCH_USE_CUDA
|
||||
std::optional<HotPixelFinderGPU::Frame> frame;
|
||||
if (get_gpu_count() > 0) {
|
||||
auto stream = std::make_shared<CudaStream>();
|
||||
preprocessor = std::make_unique<ImagePreprocessorGPU>(experiment_, pixel_mask_, stream,
|
||||
/*copy_image_to_host=*/false);
|
||||
image = std::make_unique<ImagePreprocessorBufferGPU>(experiment_.GetPixelsNum(),
|
||||
/*host_mirror=*/false);
|
||||
frame.emplace(stream);
|
||||
}
|
||||
#endif
|
||||
if (!preprocessor) {
|
||||
preprocessor = std::make_unique<ImagePreprocessorCPU>(experiment_, pixel_mask_);
|
||||
image = std::make_unique<ImagePreprocessorBuffer>(experiment_.GetPixelsNum());
|
||||
}
|
||||
JFJochReaderRawImage raw;
|
||||
std::vector<uint8_t> buffer;
|
||||
std::vector<int32_t> scratch;
|
||||
@@ -1661,13 +1682,21 @@ void Rugnux::MaskDefectivePixels(int start_image, const std::vector<int> &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();
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
#include <random>
|
||||
#include <vector>
|
||||
|
||||
#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<float>(C) + 0.3f).BeamY_pxl(static_cast<float>(C) - 0.6f);
|
||||
x.Goniometer(GoniometerAxis("omega", 0.0f, static_cast<float>(OSC_DEG), Coord(1, 0, 0), std::nullopt));
|
||||
PixelMask pixel_mask(x);
|
||||
std::vector<uint32_t> masked(static_cast<size_t>(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<CudaStream>());
|
||||
CudaDevicePtr<int32_t> device_image(static_cast<size_t>(W) * H);
|
||||
|
||||
std::mt19937 rng(7);
|
||||
std::uniform_int_distribution<int> coord(0, W - 1);
|
||||
struct Planted { size_t i; int excess; double rate; };
|
||||
std::vector<Planted> 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<int32_t> image(static_cast<size_t>(W) * H), scratch;
|
||||
std::uniform_real_distribution<double> 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<int>(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
|
||||
Reference in new issue
Block a user