diff --git a/image_analysis/indexing/FFTIndexerGPU.cu b/image_analysis/indexing/FFTIndexerGPU.cu index d86560d9f..cc72cd2a4 100644 --- a/image_analysis/indexing/FFTIndexerGPU.cu +++ b/image_analysis/indexing/FFTIndexerGPU.cu @@ -10,7 +10,8 @@ __device__ __host__ inline float complex_abs(const cufftComplex &z) { return sqrtf(z.x * z.x + z.y * z.y); } -// The magnitudes of the transform, transposed to bin-major order: mag_t[bin * directions + direction]. +// The magnitudes of the transform, transposed to bin-major order: mag_t[bin * stride + direction], for the +// `directions_size` directions of one batch (mag_t points at the batch's first column, stride is all of them). // The R2C output is direction-major, and the peak search gives each direction to one thread, so read // straight from it neighbouring lanes are a whole spectrum apart - every load a separate sector, three // streams per thread. Transposed, a warp reads 32 consecutive floats per bin. On an idle card that buys @@ -21,6 +22,7 @@ __device__ __host__ inline float complex_abs(const cufftComplex &z) { __global__ void magnitude_transpose(const cufftComplex *__restrict__ d_output, const int out_len, const int directions_size, + const int stride, float *__restrict__ mag_t) { __shared__ float tile[32][33]; const int bin0 = blockIdx.x * 32; @@ -36,7 +38,7 @@ __global__ void magnitude_transpose(const cufftComplex *__restrict__ d_output, const int bin = bin0 + r; const int dir = dir0 + threadIdx.x; if (dir < directions_size && bin < out_len) - mag_t[static_cast(bin) * directions_size + dir] = tile[threadIdx.x][r]; + mag_t[static_cast(bin) * stride + dir] = tile[threadIdx.x][r]; } } @@ -227,8 +229,11 @@ inline void cuda_err(cufftResult val) { FFTIndexerGPU::FFTIndexerGPU(const IndexingSettings &settings) : FFTIndexer(settings), result_fft_reg(result_fft) { - d_input_fft = CudaDevicePtr(input_size); - d_output_fft = CudaDevicePtr(output_size); + const int batch = std::min(nDirections, FFT_BATCH_DIRECTIONS); + const int out_len = histogram_size / 2 + 1; + d_input_fft = CudaDevicePtr(static_cast(batch) * histogram_size); + d_output_fft = CudaDevicePtr(static_cast(batch) * out_len); + d_mag_t = CudaDevicePtr(static_cast(nDirections) * out_len); d_result_fft = CudaDevicePtr(nDirections); d_spot_x = CudaDevicePtr(FFT_MAX_SPOTS); @@ -245,12 +250,16 @@ FFTIndexerGPU::FFTIndexerGPU(const IndexingSettings &settings) DirectionsChanged(); - plan = CudaFFTPlan(CudaFFTShape{.n = {static_cast(histogram_size)}, - .idist = static_cast(histogram_size), - .odist = static_cast(histogram_size / 2 + 1), - .type = CUFFT_R2C, - .batch = nDirections}, - stream); + const auto shape = [&](int n) { + return CudaFFTShape{.n = {static_cast(histogram_size)}, + .idist = static_cast(histogram_size), + .odist = out_len, + .type = CUFFT_R2C, + .batch = n}; + }; + plan = CudaFFTPlan(shape(batch), stream); + if (nDirections % batch != 0) + plan_last = CudaFFTPlan(shape(nDirections % batch), stream); } @@ -271,8 +280,7 @@ void FFTIndexerGPU::DirectionsChanged() { } void FFTIndexerGPU::ExecuteFFT(const std::vector &coord, size_t nspots) { - int l_blockDim = 128; - int l_gridDim = (direction_vectors.size() + l_blockDim - 1) / l_blockDim; + const int l_blockDim = 128; for (int i = 0; i < nspots; i++) { spot_x[i] = coord[i].x; @@ -284,38 +292,39 @@ void FFTIndexerGPU::ExecuteFFT(const std::vector &coord, size_t nspots) { cuda_err(cudaMemcpyAsync(d_spot_y, spot_y, nspots * sizeof(float), cudaMemcpyHostToDevice, stream)); cuda_err(cudaMemcpyAsync(d_spot_z, spot_z, nspots * sizeof(float), cudaMemcpyHostToDevice, stream)); + // The histograms and their transforms, FFT_BATCH_DIRECTIONS directions at a time (see the header); the + // magnitudes of all of them go to d_mag_t, which the peak search reads in one go. + const int ndir = static_cast(direction_vectors.size()); + const int out_len = static_cast(histogram_size / 2 + 1); // Shared-memory bins where they fit (they do at any sane sizing - 12.6 kB at the defaults), the // thread-per-direction kernel where they do not. const size_t hist_shared_bytes = static_cast(histogram_size) * sizeof(unsigned int); - if (hist_shared_bytes <= 48 * 1024) { - histogram_shared_kernel<<>>( - d_spot_x, d_spot_y, d_spot_z, d_dir_x, d_dir_y, d_dir_z, - histogram_spacing, histogram_size, nspots, direction_vectors.size(), d_input_fft); - } else { - histogram_kernel<<>>(d_spot_x, d_spot_y, d_spot_z, - d_dir_x, d_dir_y, d_dir_z, - histogram_spacing, histogram_size, - nspots, - direction_vectors.size(), - d_input_fft); - } - cuda_err(cudaGetLastError()); + for (int first = 0; first < ndir; first += FFT_BATCH_DIRECTIONS) { + const int n = std::min(FFT_BATCH_DIRECTIONS, ndir - first); + if (hist_shared_bytes <= 48 * 1024) { + histogram_shared_kernel<<>>( + d_spot_x, d_spot_y, d_spot_z, d_dir_x + first, d_dir_y + first, d_dir_z + first, + histogram_spacing, histogram_size, nspots, n, d_input_fft); + } else { + histogram_kernel<<<(n + l_blockDim - 1) / l_blockDim, l_blockDim, 0, stream>>>( + d_spot_x, d_spot_y, d_spot_z, d_dir_x + first, d_dir_y + first, d_dir_z + first, + histogram_spacing, histogram_size, nspots, n, d_input_fft); + } + cuda_err(cudaGetLastError()); - cuda_err(cufftExecR2C(plan, d_input_fft, d_output_fft)); + cuda_err(cufftExecR2C(n == FFT_BATCH_DIRECTIONS || n == nDirections ? plan : plan_last, + d_input_fft, d_output_fft)); + + const dim3 tr_grid((out_len + 31) / 32, (n + 31) / 32); + magnitude_transpose<<>>(d_output_fft, out_len, n, ndir, + d_mag_t + first); + cuda_err(cudaGetLastError()); + } // Background half-window ~15 A (length-based, so independent of histogram sizing); see // FFTIndexerCPU for the prominence-vs-envelope rationale and the validated optimum. const double len_coeff = 2.0 * static_cast(max_length_A) / static_cast(histogram_size); const int bg_half = std::max(1, static_cast(std::lround(15.0 / len_coeff))); - - const int out_len = static_cast(histogram_size / 2 + 1); - const dim3 tr_grid((out_len + 31) / 32, (direction_vectors.size() + 31) / 32); - // The histogram has been transformed and is not read again, so its buffer - histogram_size floats - // per direction, more than the out_len magnitudes need - holds them. - float *d_mag_t = d_input_fft; - magnitude_transpose<<>>(d_output_fft, out_len, - direction_vectors.size(), d_mag_t); - cuda_err(cudaGetLastError()); const int peak_grid = (static_cast(direction_vectors.size()) + 31) / 32; calculate_fft_result<<>>(d_mag_t, max_length_A, min_length_A, histogram_size, diff --git a/image_analysis/indexing/FFTIndexerGPU.h b/image_analysis/indexing/FFTIndexerGPU.h index 7b5fe0e2f..99cf0c3e5 100644 --- a/image_analysis/indexing/FFTIndexerGPU.h +++ b/image_analysis/indexing/FFTIndexerGPU.h @@ -16,6 +16,14 @@ #include "../common/IndexingSettings.h" #include "FFTResult.h" +// The histograms are made and transformed FFT_BATCH_DIRECTIONS directions at a time. All at once, the +// histograms, their transforms and cuFFT's work area held 0.8 GB at the default 16384 directions and 2 GB +// at a doubled cell bound, for the length of the indexer's life; a batch holds a quarter of that. A +// direction's histogram and transform do not depend on which batch it is in - cuFFT's R2C gives the same +// bits at any batch count (checked at the histogram sizes the indexer uses) - so neither does the result. +// Kept large enough that a batch still fills the card. +constexpr int FFT_BATCH_DIRECTIONS = 4096; + class FFTIndexerGPU : public FFTIndexer { CudaDevicePtr d_dir_x; CudaDevicePtr d_dir_y; @@ -29,8 +37,10 @@ class FFTIndexerGPU : public FFTIndexer { CudaHostPtr spot_y; CudaHostPtr spot_z; + // The histograms and their transforms of one batch of directions, and the magnitudes of all of them. CudaDevicePtr d_input_fft; CudaDevicePtr d_output_fft; + CudaDevicePtr d_mag_t; CudaDevicePtr d_result_fft; CudaRegisteredVector result_fft_reg; @@ -39,6 +49,7 @@ class FFTIndexerGPU : public FFTIndexer { // After the stream: it waits for the stream before the plan goes back, and goes before the stream. CudaFFTPlan plan; + CudaFFTPlan plan_last; // the last batch, where FFT_BATCH_DIRECTIONS does not divide the directions void ExecuteFFT(const std::vector &coord, size_t nspots) override; void DirectionsChanged() override; diff --git a/rugnux/Rugnux.h b/rugnux/Rugnux.h index e4ed4d694..2b679e8c3 100644 --- a/rugnux/Rugnux.h +++ b/rugnux/Rugnux.h @@ -1271,6 +1271,11 @@ class Rugnux { // Its steps and the state they share (RugnuxFirstPass.h). struct FirstPassRun; void ImagePass(PipelineLocals &p); + // How many workers with GPU engines of their own - at most `most` - one card takes: decided from + // the card's total memory and the detector, never from what is free (RugnuxImagePass.cpp). + [[nodiscard]] int GPUWorkersPerCard(int most) const; + // The pre-scan's workers (RugnuxPreScan.cpp). + [[nodiscard]] size_t PrescanWorkers() const; // After the image pass of a rotation sweep: the decisions taken on the sweep's first part // against what pass 2 measured on the rest of it. Log only (RugnuxFarEnd.cpp). void FarEndCheck(PipelineLocals &p, const RotationIndexerResult &rot); diff --git a/rugnux/RugnuxFirstPass.cpp b/rugnux/RugnuxFirstPass.cpp index 634d081ed..588b37e49 100644 --- a/rugnux/RugnuxFirstPass.cpp +++ b/rugnux/RugnuxFirstPass.cpp @@ -469,7 +469,8 @@ Rugnux::FirstPassRun::FirstPassRun(Rugnux &rx, PipelineLocals &p) indexer_pool(p.indexer_pool), indexer(p.indexer), indexing_bound_A(p.indexing_bound_A), census_future(p.census_future), spot_workers(get_gpu_count() > 0 - ? std::min(rx.config_.nthreads, std::max(8, 4 * get_gpu_count())) + ? std::min({rx.config_.nthreads, std::max(8, 4 * get_gpu_count()), + rx.GPUWorkersPerCard(8) * get_gpu_count()}) : rx.config_.nthreads), engines(std::max(spot_workers, 1)), late_validation(LateValidationFrames(p.prepass_images, p.images_to_process)), diff --git a/rugnux/RugnuxImagePass.cpp b/rugnux/RugnuxImagePass.cpp index 3ba388961..dc17a0419 100644 --- a/rugnux/RugnuxImagePass.cpp +++ b/rugnux/RugnuxImagePass.cpp @@ -87,6 +87,17 @@ using namespace rugnux_internal; +// A worker's engines hold about 24 bytes a detector pixel of its card - sixteen held 6.3 GB on a 16.8 Mpx +// detector, measured at 12-22 bytes a pixel on four data sets - and the workers keep to half of the card, +// so a small card gets fewer of them. How many there are changes only how fast a loop runs, never what it +// computes. +int Rugnux::GPUWorkersPerCard(int most) const { + constexpr int64_t WORKER_BYTES_PER_PIXEL = 24; + const auto fit = static_cast(get_gpu_total_memory(0) / 2) + / (WORKER_BYTES_PER_PIXEL * experiment_.GetPixelsNum()); + return static_cast(std::clamp(fit, 1, most)); +} + void Rugnux::ImagePass(PipelineLocals &p) { auto &logger = p.logger; auto &result = p.result; @@ -368,17 +379,9 @@ void Rugnux::ImagePass(PipelineLocals &p) { // which is what a previous attempt at this got wrong. // Only the full-analysis worker drives a card; the azimuthal one preprocesses and integrates on // the CPU and wants every thread it can have, so the cap must not reach it. - // A worker also holds about 24 bytes a detector pixel of its card - sixteen held 6.3 GB on a 16.8 Mpx - // detector - and the workers keep to half of the card, so a small card gets fewer of them. How many - // there are changes only how fast the loop runs, never what it computes. + // A worker also holds GPU memory, so a small card gets fewer of them (GPUWorkersPerCard). const int gpus = get_gpu_count(); - int workers_per_card = 16; - if (gpus > 0) { - constexpr int64_t WORKER_BYTES_PER_PIXEL = 24; - const auto fit = static_cast(get_gpu_total_memory(0) / 2) - / (WORKER_BYTES_PER_PIXEL * experiment_.GetPixelsNum()); - workers_per_card = static_cast(std::clamp(fit, 1, 16)); - } + const int workers_per_card = gpus > 0 ? GPUWorkersPerCard(16) : 16; const int image_workers = (per_image_analysis && config_.nthreads_auto && gpus > 0) ? std::min(config_.nthreads, workers_per_card * gpus) : config_.nthreads; diff --git a/rugnux/RugnuxPreScan.cpp b/rugnux/RugnuxPreScan.cpp index b2131b876..20bbdcb1b 100644 --- a/rugnux/RugnuxPreScan.cpp +++ b/rugnux/RugnuxPreScan.cpp @@ -177,6 +177,14 @@ namespace { } } +// PRESCAN_MAX_WORKERS, fewer where their GPU engines would not fit the card. +size_t Rugnux::PrescanWorkers() const { + const int gpus = get_gpu_count(); + if (gpus == 0) + return PRESCAN_MAX_WORKERS; + return std::min(PRESCAN_MAX_WORKERS, GPUWorkersPerCard(PRESCAN_MAX_WORKERS) * gpus); +} + void Rugnux::PreScan(int start_image, int images_to_process, int frame_count, RugnuxObserver *observer) { Logger logger("Rugnux"); @@ -422,7 +430,7 @@ void Rugnux::PreScan(int start_image, int images_to_process, int frame_count, Ru // is applied once both are done (finish_spot_measurement). const std::vector ordinals(shadow_set.begin(), shadow_set.end()); const size_t nworkers = std::min(std::max(config_.nthreads, 1), - std::min(PRESCAN_MAX_WORKERS, ordinals.size())); + std::min(PrescanWorkers(), ordinals.size())); // Per frame, in sample order, so the gain does not depend on how the workers interleaved. std::vector gain_levels(measure_gain ? ordinals.size() : 0); const size_t gain_frame_stride = (ordinals.size() + background_gain::GAIN_MAX_FRAMES - 1) / background_gain::GAIN_MAX_FRAMES; @@ -1137,7 +1145,7 @@ void Rugnux::MaskDefectivePixels(int start_image, const std::vector &sample finder.PrepareDevice(); #endif std::atomic next{0}; - const size_t nworkers = std::min(nthreads, std::min(PRESCAN_MAX_WORKERS, sample.size())); + const size_t nworkers = std::min(nthreads, std::min(PrescanWorkers(), sample.size())); OnWorkers(nworkers, [&](size_t) { // 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).