From 39bba125875a155daa13b5704f26de4609e727fe Mon Sep 17 00:00:00 2001 From: Filip Leonarski Date: Thu, 15 Oct 2026 15:18:16 +0200 Subject: [PATCH 1/2] GPU memory: FFT indexer transforms 4096 directions at a time; first-pass and pre-scan workers sized from the card - FFTIndexerGPU makes and transforms the projection histograms FFT_BATCH_DIRECTIONS (4096) directions at a time, into one set of batch buffers, and keeps only the transposed magnitudes of all directions for the peak search, which still runs once over all of them. cuFFT's R2C gives the same bits at any batch count (checked at histogram lengths 1024-12568 and batches 1-16384), and every other step is per direction, so the result does not change. Measured: the two indexers of a first pass hold 0.83 instead of 2.48 GB, plus a quarter of the plan work area (0.2 instead of 0.8 GB each at a doubled cell bound). - Rugnux::GPUWorkersPerCard: the per-image loop's existing rule (24 bytes a detector pixel, half of the card's total memory) as one function, now also capping the first pass's spot-finding workers and the pre-scan's workers (both at most 8 a card as before). No change on a 16 GB or an 8.55 GB card with a 16-18 Mpx detector; a 4-6 GB card gets 4-6 of them. Output unchanged: p.hkl byte-identical on cytc_x10sa, myob_x10sa, 4nwv and 8qaw, on the RTX 5080 and with its total read as 8.55 GB. Co-Authored-By: Claude Opus 5.5 --- image_analysis/indexing/FFTIndexerGPU.cu | 79 +++++++++++++----------- image_analysis/indexing/FFTIndexerGPU.h | 11 ++++ rugnux/Rugnux.h | 5 ++ rugnux/RugnuxFirstPass.cpp | 3 +- rugnux/RugnuxImagePass.cpp | 23 ++++--- rugnux/RugnuxPreScan.cpp | 12 +++- 6 files changed, 85 insertions(+), 48 deletions(-) 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). From bf8f0a482d22f008965fe2f018292ca23c06edf1 Mon Sep 17 00:00:00 2001 From: Filip Leonarski Date: Thu, 15 Oct 2026 16:44:01 +0200 Subject: [PATCH 2/2] GPU memory: beam-centre point transforms in two spectra and one work area; a probe on a small card indexes with one FFT indexer - BeamCenterFFTGPU's point surfaces: each spectrum product goes in the place of a spectrum that is finished with (a.a where m's spectrum goes before it is there, a.m and m.m and a^2.m in a's), so the third spectrum buffer goes, and the forward and inverse plans share one work area - they never run at once. The same transforms and products in the same order, so the surfaces are unchanged. 2.6 -> 2.05 GB on a 16 Mpx detector, the largest single holder at the first pass's peak; DeviceMemoryNeeded counts it so. - Rugnux::FirstPassIndexerThreads: a probe pass beside the main line on a card below the take-turns size (gpu_takes_turns(), 12 GB on the first card's total) builds one FFT indexer for its pools instead of two, and indexes its two schemes one after the other. Which indexer indexes a frame does not change what it finds. Measured with the RTX 5080's total read as 8.55 GB: first-pass peak 6.50 -> 5.92 GB (8qaw), 5.76 -> 4.84 GB (4nwv) together with the batched FFT indexer; the speculative probe after the output 6.30 -> 4.35 GB (8qaw). Output unchanged: p.hkl byte-identical on cytc_x10sa, myob_x10sa, 4nwv and 8qaw on this card and on the 8.55 GB simulation; run times unchanged within noise. Co-Authored-By: Claude Opus 5.5 --- common/CUDAWrapper.cpp | 4 ++ common/CUDAWrapper.h | 4 ++ .../geom_refinement/BeamCenterFFTGPU.cu | 51 ++++++++++--------- rugnux/Rugnux.cpp | 6 ++- rugnux/Rugnux.h | 5 ++ rugnux/RugnuxFirstPass.cpp | 2 +- rugnux/RugnuxFirstPassRescues.cpp | 4 +- 7 files changed, 49 insertions(+), 27 deletions(-) diff --git a/common/CUDAWrapper.cpp b/common/CUDAWrapper.cpp index 3a71878f4..722bdc9ae 100644 --- a/common/CUDAWrapper.cpp +++ b/common/CUDAWrapper.cpp @@ -56,6 +56,10 @@ namespace { } } +bool gpu_takes_turns() { + return take_turns(); +} + GPUWorkBeside::GPUWorkBeside(bool after_merges) { std::unique_lock lock(gpu_work_m); if (take_turns()) diff --git a/common/CUDAWrapper.h b/common/CUDAWrapper.h index f772cb81f..1dd596a82 100644 --- a/common/CUDAWrapper.h +++ b/common/CUDAWrapper.h @@ -154,6 +154,10 @@ public: GPUMerge &operator=(const GPUMerge &) = delete; }; +// Whether the card is too small for a probe pass beside the main line (12 GB, decided on the first card's +// total memory), so that they take turns (GPUWorkBeside). Build-independent. +bool gpu_takes_turns(); + // Wait until no GPUImagePass is held - at once if none was. With no timeout: an image pass waits for no // probe, so it ends. void wait_for_gpu_image_passes(); diff --git a/image_analysis/geom_refinement/BeamCenterFFTGPU.cu b/image_analysis/geom_refinement/BeamCenterFFTGPU.cu index b71831cb4..f4d4be1fe 100644 --- a/image_analysis/geom_refinement/BeamCenterFFTGPU.cu +++ b/image_analysis/geom_refinement/BeamCenterFFTGPU.cu @@ -274,10 +274,13 @@ PointSurfacesDevice TransformPoint(const std::vector &a, const std::vecto PointSurfacesDevice out; out.nx = nx; out.real = CudaDevicePtr(nreal, ALLOC); - CudaDevicePtr d_a(ncomplex, ALLOC), d_m(ncomplex, ALLOC), d_prod(ncomplex, ALLOC); - - CudaFFTPlan fwd(PointForward(ny, nx)); - CudaFFTPlan inv(PointInverse(ny, nx)); + // Two spectra, a product taking the place of one that is finished with (see below); and one work + // area for both plans, which never run at the same time. + CudaDevicePtr d_a(ncomplex, ALLOC), d_m(ncomplex, ALLOC); + CudaDevicePtr work(std::max({CudaFFTPlan::WorkBytes(PointForward(ny, nx)), + CudaFFTPlan::WorkBytes(PointInverse(ny, nx)), 1}), ALLOC); + CudaFFTPlan fwd(PointForward(ny, nx), nullptr, work.get()); + CudaFFTPlan inv(PointInverse(ny, nx), nullptr, work.get()); auto upload = [&](const std::vector &src) { Check(cudaMemset(out.real.get(), 0, nreal * sizeof(float)), @@ -287,17 +290,14 @@ PointSurfacesDevice TransformPoint(const std::vector &a, const std::vecto "BeamCenterFFT: image upload failed"); }; - upload(a); - Check(cufftExecR2C(fwd, out.real, d_a), "BeamCenterFFT: forward transform failed"); - upload(m); - Check(cufftExecR2C(fwd, out.real, d_m), "BeamCenterFFT: forward transform failed"); - const float norm = 1.0f / (static_cast(ny) * static_cast(nx)); - // The inverse leaves an unnormalised ny x nx result whose 2h x 2w corner is the surface. - auto inverse_product = [&](const cufftComplex *u, const cufftComplex *v) { - MultiplySpectra<<>>(u, v, d_prod.get(), ncomplex); + // The product goes to `dst`, which may be u itself, and the inverse - which leaves an unnormalised + // ny x nx result whose 2h x 2w corner is the surface - may overwrite it, as cuFFT's C2R does with + // its input. + auto inverse_product = [&](const cufftComplex *u, const cufftComplex *v, cufftComplex *dst) { + MultiplySpectra<<>>(u, v, dst, ncomplex); CheckLastKernel("BeamCenterFFT: spectrum product failed"); - Check(cufftExecC2R(inv, d_prod, out.real), "BeamCenterFFT: inverse transform failed"); + Check(cufftExecC2R(inv, dst, out.real), "BeamCenterFFT: inverse transform failed"); }; auto take_corner = [&](CudaDevicePtr &dst) { dst = CudaDevicePtr(ncrop, ALLOC); @@ -306,18 +306,23 @@ PointSurfacesDevice TransformPoint(const std::vector &a, const std::vecto CheckLastKernel("BeamCenterFFT: surface scaling failed"); }; - inverse_product(d_a, d_a); + // a.a goes where m's spectrum will be, before it is there; a.m in the place of a's spectrum, the last + // to read it; m.m there too; and the spectrum of a^2 there after that. + upload(a); + Check(cufftExecR2C(fwd, out.real, d_a), "BeamCenterFFT: forward transform failed"); + inverse_product(d_a, d_a, d_m); take_corner(out.C); - inverse_product(d_a, d_m); + upload(m); + Check(cufftExecR2C(fwd, out.real, d_m), "BeamCenterFFT: forward transform failed"); + inverse_product(d_a, d_m, d_a); take_corner(out.S); - inverse_product(d_m, d_m); + inverse_product(d_m, d_m, d_a); take_corner(out.D); - // The spectrum of a is finished with, so a^2 goes in its place rather than in a fourth buffer. upload(a); SquareInPlace<<>>(out.real.get(), nreal); CheckLastKernel("BeamCenterFFT: squaring failed"); Check(cufftExecR2C(fwd, out.real, d_a), "BeamCenterFFT: forward transform failed"); - inverse_product(d_a, d_m); + inverse_product(d_a, d_m, d_a); ScaleCorner<<>>(out.real.get(), nx, 2 * h, 2 * w, norm); CheckLastKernel("BeamCenterFFT: surface scaling failed"); return out; @@ -511,11 +516,11 @@ size_t BeamCenterFFTGPU::DeviceMemoryNeeded(int64_t width, int64_t height) { const int64_t nxc = nx / 2 + 1; const size_t work_fwd = CudaFFTPlan::WorkBytes(PointForward(ny, nx)); const size_t work_inv = CudaFFTPlan::WorkBytes(PointInverse(ny, nx)); - // One transform buffer, three spectra, and three of the four convolution surfaces - the - // fourth stays in the transform buffer, where the last inverse leaves it. - size_t needed = ny * nx * sizeof(float) + 3 * ny * nxc * sizeof(cufftComplex) - + 3 * 4 * static_cast(width) * height * sizeof(float) + work_fwd - + work_inv; + // One transform buffer, two spectra, three of the four convolution surfaces - the fourth stays in + // the transform buffer, where the last inverse leaves it - and one work area for both plans. + size_t needed = ny * nx * sizeof(float) + 2 * ny * nxc * sizeof(cufftComplex) + + 3 * 4 * static_cast(width) * height * sizeof(float) + + std::max(work_fwd, work_inv); // The two 1D phases, the larger of them: they run after the point surfaces, with its buffers // already freed. diff --git a/rugnux/Rugnux.cpp b/rugnux/Rugnux.cpp index d52b589ba..e6e6eb076 100644 --- a/rugnux/Rugnux.cpp +++ b/rugnux/Rugnux.cpp @@ -536,6 +536,10 @@ void Rugnux::AddFirstPassMemo(const FirstPassMemo &memo) { first_pass_memo_.push_back(memo); } +int Rugnux::FirstPassIndexerThreads() const { + return gpu_work_beside_ && gpu_takes_turns() ? 1 : 2; +} + void Rugnux::StartSpeculativeGeometryProbe(std::shared_ptr run, const std::array &geometry) { // What the walk's index_at_geometry sets up on its copy of the run before it indexes at this geometry. run->prepass_detector_geometry_ = prepass_detector_geometry_; @@ -924,7 +928,7 @@ ProcessResult Rugnux::RunPipeline(RugnuxObserver *observer, bool write_output, b // those two so a rotation run doesn't pay to initialise (cuFFT plan + GPU alloc) indexers it // never uses. Stills fire the FFT once per image across all workers, so keep the default there. if (config_.rotation_indexing && config_.two_pass_rotation && experiment_.IsRotationIndexing()) { - indexing_settings.IndexingThreads(2); + indexing_settings.IndexingThreads(FirstPassIndexerThreads()); // Two indexer threads leave the rest of the machine idle for the whole first pass, which is // a third of the run. Split each scheme's candidate-cell refinement over -N/2 threads so the // two together use -N. The split is by candidate cell, so the result does not depend on it. diff --git a/rugnux/Rugnux.h b/rugnux/Rugnux.h index 2b679e8c3..e5cca61d9 100644 --- a/rugnux/Rugnux.h +++ b/rugnux/Rugnux.h @@ -1274,6 +1274,11 @@ class Rugnux { // 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 FFT indexers of a first pass's pool: two, for its two schemes at once; one for a probe pass on a + // card too small for it beside the main line, which then indexes the schemes one after the other. + // An FFT indexer holds 0.3-0.6 GB of the card, and which one indexes a frame does not change what it + // finds. + [[nodiscard]] int FirstPassIndexerThreads() 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 diff --git a/rugnux/RugnuxFirstPass.cpp b/rugnux/RugnuxFirstPass.cpp index 588b37e49..2f4840c13 100644 --- a/rugnux/RugnuxFirstPass.cpp +++ b/rugnux/RugnuxFirstPass.cpp @@ -1475,7 +1475,7 @@ void Rugnux::FirstPassRun::PrefetchCertainFrames() { IndexingSettings Rugnux::FirstPassRun::ShortAxisSettings(const DiffractionExperiment &x) const { auto settings = x.GetIndexingSettings(); settings.FFT_MinUnitCell_A(IndexingSettings::fft_min_unit_cell_limit_A); - settings.IndexingThreads(2); + settings.IndexingThreads(rx.FirstPassIndexerThreads()); settings.RefineThreads(std::clamp(rx.config_.nthreads / 2, 1, MAX_REFINE_THREADS)); return settings; } diff --git a/rugnux/RugnuxFirstPassRescues.cpp b/rugnux/RugnuxFirstPassRescues.cpp index c48a3b68e..ccc616dfe 100644 --- a/rugnux/RugnuxFirstPassRescues.cpp +++ b/rugnux/RugnuxFirstPassRescues.cpp @@ -182,7 +182,7 @@ auto Rugnux::FirstPassRun::LongAxisRescue(const FirstPass &standing) -> std::opt constexpr float RESCUE_MAX_UNIT_CELL_A = 1000.0f; if (coarse_settings.GetFFT_MaxUnitCell_A() < RESCUE_MAX_UNIT_CELL_A) coarse_settings.FFT_MaxUnitCell_A(RESCUE_MAX_UNIT_CELL_A); - coarse_settings.IndexingThreads(2); + coarse_settings.IndexingThreads(rx.FirstPassIndexerThreads()); coarse_settings.RefineThreads(std::clamp(rx.config_.nthreads / 2, 1, MAX_REFINE_THREADS)); IndexerThreadPool coarse_pool(coarse_settings, IndexerConstruction::OnFirstUse, rx.gpu_work_beside_); // Coarse first pass: keep the recovered cell with the LONGEST axis directly. Its full- @@ -208,7 +208,7 @@ auto Rugnux::FirstPassRun::LongAxisRescue(const FirstPass &standing) -> std::opt // CountIndexed forces the lattice and never touches the pool, so the existing // IndexAndRefine is reused; only the FFT needs the wider one. auto wide_settings = rx.experiment_.GetIndexingSettings(); - wide_settings.IndexingThreads(2); + wide_settings.IndexingThreads(rx.FirstPassIndexerThreads()); wide_settings.RefineThreads(std::clamp(rx.config_.nthreads / 2, 1, MAX_REFINE_THREADS)); RaiseFFTBoundForKnownCell(wide_settings, rx.experiment_); FirstPass constrained;