From 3aa67a60597513c883d2411ae4d3e096eacc6492 Mon Sep 17 00:00:00 2001 From: Filip Leonarski Date: Fri, 16 Oct 2026 17:55:30 +0200 Subject: [PATCH] MR GPU: corner-packed molecular transform for the rotation function Each sample of the molecular transform interpolates over 8 grid corners that lie in four u-rows of the half-l grid, 4-5 32-byte sectors per sample. On the GPU the transform can now be held packed: every point (i, j, l) stores its four (v, w) corners, so the two neighbouring records hold all eight, read from two places. The packed grid is cut to |u| <= reach as the plain one already is in v, and has the conjugate plane l = -1 in front; below l = -1 the eight corners are read mirrored about -i0 - 1 and conjugated. Same floats, same accumulation order: rotation and translation functions give the same bits (checked in MolecularReplacement_GPUMatchesCPU). The layout is chosen up front from the budget (PackMolecularTransformGPU): packed where the answer merge's plan holds every part beside it that it holds beside the plain transform, and the budget holds both grids while the packed one is made from the plain one on the device; logged either way. The upload no longer stages a host copy of the grid. The CPU At() is unchanged: a microbenchmark gained 1.3x single-threaded and ~1.0-1.1x at 16-32 threads, not worth 2.7x the host memory. 4nwv (moved model, timing benchmark), RTX 5080: rotation 5.56 -> 2.48 s, MR step 20.9 -> 16.7 s; transform on the card 0.84 -> 2.28 GB. p.hkl, p_model.pdb and the MR_ report block byte-identical on the timing sets (GPU and --no-gpu) and on 4nwv, 8tyy, 6oel, 3inp. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01PXc1zD1yxHqaR1DGdCTHL4 --- .../MolecularReplacement.cpp | 30 +++++- .../MolecularReplacement.h | 5 + .../MolecularReplacementGPU.cu | 98 ++++++++++++++++--- .../MolecularReplacementGPU.h | 9 +- tests/MolecularReplacementTest.cpp | 28 ++++++ 5 files changed, 150 insertions(+), 20 deletions(-) diff --git a/image_analysis/structure_refinement/MolecularReplacement.cpp b/image_analysis/structure_refinement/MolecularReplacement.cpp index 47d165261..782afc499 100644 --- a/image_analysis/structure_refinement/MolecularReplacement.cpp +++ b/image_analysis/structure_refinement/MolecularReplacement.cpp @@ -2377,18 +2377,35 @@ MolecularReplacementResult search_model(const SearchModel &model, const std::vec return result; } const MolecularTransform &ft = *ft_made; - [[maybe_unused]] const size_t transform_bytes = ft.Grid().data.size() * sizeof(std::complex); + [[maybe_unused]] size_t transform_bytes = ft.Grid().data.size() * sizeof(std::complex); #ifdef JFJOCH_USE_CUDA // The rotation and translation functions on the GPU where the transform fits the budget (the plan's first // part, PlanMolecularReplacementGPU); the rest of the search is the same either way. std::unique_ptr gpu; if (get_gpu_count() > 0 && transform_bytes <= gpu_budget) { + // Packed where the answer merge's plan holds as much beside it (PackMolecularTransformGPU), decided on + // that merge's sizes, which its plan then takes as they are. + MergeGPUSize size = sized[0].get(); + MolecularReplacementGPUNeed need; + need.budget = gpu_budget; + need.transform = transform_bytes; + need.rigid_body = size.rigid_body; + need.rigid_body_engines = size.rigid_body_engines; + need.structure_factors = size.structure_factors; + const size_t packed_bytes = MolecularReplacementGPU::TransformBytes(ft, true); + const bool packed = PackMolecularTransformGPU(need, packed_bytes); + sized[0] = std::async(std::launch::deferred, [size = std::move(size)]() mutable { return std::move(size); }); + logger.Info("Molecular replacement: the transform on the GPU {}", packed + ? fmt::format("packed, {} in place of {}", in_gb(packed_bytes), in_gb(transform_bytes)) + : fmt::format("plain, {} (packed, {}, does not fit beside the rest of the plan)", in_gb(transform_bytes), + in_gb(packed_bytes))); try { - gpu = std::make_unique(ft); + gpu = std::make_unique(ft, packed); } catch (const JFJochException &e) { result.failure_reason = std::string("GPU: ") + e.what(); return result; } + transform_bytes = MolecularReplacementGPU::TransformBytes(ft, packed); } result.gpu_search = gpu != nullptr; #endif @@ -3323,6 +3340,15 @@ MolecularReplacementGPUPlan PlanMolecularReplacementGPU(const MolecularReplaceme return plan; } +bool PackMolecularTransformGPU(const MolecularReplacementGPUNeed &need, size_t packed) { + MolecularReplacementGPUNeed with_packed = need; + with_packed.transform = packed; + const MolecularReplacementGPUPlan plain = PlanMolecularReplacementGPU(need); + const MolecularReplacementGPUPlan plan = PlanMolecularReplacementGPU(with_packed); + return plan.search && plan.rigid_body_engines == plain.rigid_body_engines + && plan.structure_factors == plain.structure_factors && need.transform + packed <= need.budget; +} + MolecularReplacementResult RunMolecularReplacement(const std::string &model_path, const std::vector &merges, Logger &logger, size_t nthreads, size_t gpu_resident_bytes) { const auto t0 = std::chrono::steady_clock::now(); diff --git a/image_analysis/structure_refinement/MolecularReplacement.h b/image_analysis/structure_refinement/MolecularReplacement.h index ea163349a..87bd779e3 100644 --- a/image_analysis/structure_refinement/MolecularReplacement.h +++ b/image_analysis/structure_refinement/MolecularReplacement.h @@ -405,6 +405,11 @@ struct MolecularReplacementGPUPlan { // to be done rather than spilling past it. MolecularReplacementGPUPlan PlanMolecularReplacementGPU(const MolecularReplacementGPUNeed &need); +// Whether the molecular transform goes on the GPU packed (MolecularReplacementGPU), `packed` bytes in place of +// the plain one's need.transform: where the plan with it holds every part the plain plan holds, and the budget +// both grids while the packed one is made from the plain one. +bool PackMolecularTransformGPU(const MolecularReplacementGPUNeed &need, size_t packed); + // Search `merges` (the answer's first) for the predicted model at `model_path`, in every space group with // the rotations of each merge's group - one copy, then further copies one at a time while each new one // stands out, packs and lowers R-free - and decide. A candidate is PLACED where a copy's translation diff --git a/image_analysis/structure_refinement/MolecularReplacementGPU.cu b/image_analysis/structure_refinement/MolecularReplacementGPU.cu index 23cf234f0..bb0f92a04 100644 --- a/image_analysis/structure_refinement/MolecularReplacementGPU.cu +++ b/image_analysis/structure_refinement/MolecularReplacementGPU.cu @@ -31,8 +31,17 @@ constexpr int MAX_BINS = 16; // SEARCH_BINS (MolecularReplacement.cpp) is 10 // The rotation function's per-reflection scratch is made for this many orientations at a time. constexpr size_t ROTATION_BATCH = 2048; +// The eight corners of an interpolation in the half-l grid lie in four rows of u. Packed, every point (i, j, l) +// holds the four (v, w) corners about it, so that two neighbouring records hold all eight: the same values, +// read from two places instead of four, for four times the memory per point. The packed grid is cut to the indices +// the plain one is read at in u as it is in v (2 reach + 1, so nv), and has the conjugate plane l = -1 in front. +struct Corners { + float2 v[4]; // (j, l), (j, l + 1), (j + 1, l), (j + 1, l + 1) +}; + struct Transform { - const float2 *data; + const float2 *data; // the plain half-l grid, or null + const Corners *corners; // the packed one, or null: nv x nv x (nwh + 1), the plane l = -1 first int nu, nv, nwh; float box, blur; }; @@ -69,18 +78,57 @@ __device__ float2 transform_interpolate(const Transform &g, const Rot &r, float3 f[a] = u - i0[a]; } float2 out = make_float2(0, 0); - for (int dx = 0; dx < 2; dx++) - for (int dy = 0; dy < 2; dy++) - for (int dz = 0; dz < 2; dz++) { - const float w = (dx ? f[0] : 1 - f[0]) * (dy ? f[1] : 1 - f[1]) * (dz ? f[2] : 1 - f[2]); - const float2 v = transform_at(g, i0[0] + dx, i0[1] + dy, i0[2] + dz); - out.x += w * v.x; - out.y += w * v.y; - } + if (g.corners) { + // Below l = -1 every corner is the conjugate of one about the opposite point, -i0 - 1: read there, + // in the mirrored order. + const bool mirror = i0[2] < -1; + int i = mirror ? -i0[0] - 1 : i0[0], j = mirror ? -i0[1] - 1 : i0[1]; + const int l = mirror ? -i0[2] - 1 : i0[2]; + if (i < 0 || i >= g.nv) { i %= g.nv; if (i < 0) i += g.nv; } + if (j < 0 || j >= g.nv) { j %= g.nv; if (j < 0) j += g.nv; } + const size_t row = static_cast(g.nv) * (j + static_cast(g.nv) * (l + 1)); + const Corners c[2] = {g.corners[i + row], g.corners[(i + 1 < g.nv ? i + 1 : 0) + row]}; + for (int dx = 0; dx < 2; dx++) + for (int dy = 0; dy < 2; dy++) + for (int dz = 0; dz < 2; dz++) { + const float w = (dx ? f[0] : 1 - f[0]) * (dy ? f[1] : 1 - f[1]) * (dz ? f[2] : 1 - f[2]); + float2 v = mirror ? c[1 - dx].v[2 * (1 - dy) + 1 - dz] : c[dx].v[2 * dy + dz]; + if (mirror) + v.y = -v.y; + out.x += w * v.x; + out.y += w * v.y; + } + } else { + for (int dx = 0; dx < 2; dx++) + for (int dy = 0; dy < 2; dy++) + for (int dz = 0; dz < 2; dz++) { + const float w = (dx ? f[0] : 1 - f[0]) * (dy ? f[1] : 1 - f[1]) * (dz ? f[2] : 1 - f[2]); + const float2 v = transform_at(g, i0[0] + dx, i0[1] + dy, i0[2] + dz); + out.x += w * v.x; + out.y += w * v.y; + } + } const float unblur = expf(g.blur * (s[0] * s[0] + s[1] * s[1] + s[2] * s[2]) / 4.0f); return make_float2(out.x * unblur, out.y * unblur); } +// The packed grid from the plain one: record (i, j, l) holds transform_at() of its four (v, w) corners, i the +// index of u's frequency in a grid of nv as j is of v's; zero past the last plane, which is never read. +__global__ void pack_corners(Transform g, Corners *out) { + const size_t n = static_cast(g.nv) * g.nv * (g.nwh + 1); + const size_t r = static_cast(blockIdx.x) * blockDim.x + threadIdx.x; + if (r >= n) + return; + const int i = static_cast(r % g.nv), j = static_cast((r / g.nv) % g.nv); + const int l = static_cast(r / (static_cast(g.nv) * g.nv)) - 1; + const int u = i <= g.nv / 2 ? i : i - g.nv; + Corners c; + for (int dy = 0; dy < 2; dy++) + for (int dz = 0; dz < 2; dz++) + c.v[2 * dy + dz] = l + dz < g.nwh ? transform_at(g, u, j + dy, l + dz) : make_float2(0, 0); + out[r] = c; +} + // A block-wide sum in a fixed order: each thread's value into shared memory, then a tree. __device__ double block_sum(double v, double *sh) { sh[threadIdx.x] = v; @@ -352,18 +400,38 @@ gemmi::FPhiGrid MapToFPhiGPU(const gemmi::Grid &map, int reach) { struct MolecularReplacementGPUState { CudaStream stream; CudaDevicePtr grid; + CudaDevicePtr corners; Transform transform{}; }; -MolecularReplacementGPU::MolecularReplacementGPU(const MolecularTransform &ft) +size_t MolecularReplacementGPU::TransformBytes(const MolecularTransform &ft, bool packed) { + const gemmi::FPhiGrid &g = ft.Grid(); + if (packed) + return static_cast(g.nv) * g.nv * (g.nw + 1) * sizeof(Corners); + return g.data.size() * sizeof(float2); +} + +MolecularReplacementGPU::MolecularReplacementGPU(const MolecularTransform &ft, bool packed) : state_(std::make_unique()) { const gemmi::FPhiGrid &g = ft.Grid(); - std::vector host(g.data.size()); - for (size_t i = 0; i < host.size(); i++) - host[i] = make_float2(g.data[i].real(), g.data[i].imag()); - state_->grid = upload(host, state_->stream); - state_->transform = {state_->grid.get(), g.nu, g.nv, g.nw, static_cast(ft.Box()), + static_assert(sizeof(std::complex) == sizeof(float2)); + state_->grid = CudaDevicePtr(std::max(g.data.size(), 1)); + cuda_err(cudaMemcpyAsync(state_->grid.get(), g.data.data(), g.data.size() * sizeof(float2), + cudaMemcpyHostToDevice, state_->stream)); + state_->transform = {state_->grid.get(), nullptr, g.nu, g.nv, g.nw, static_cast(ft.Box()), static_cast(ft.Blur())}; + if (packed) { + // Made from the plain grid on the device, which is then given back. + const size_t n = TransformBytes(ft, true) / sizeof(Corners); + state_->corners = CudaDevicePtr(n); + pack_corners<<((n + THREADS - 1) / THREADS), THREADS, 0, state_->stream>>>( + state_->transform, state_->corners); + cuda_err(cudaGetLastError()); + cuda_err(cudaStreamSynchronize(state_->stream)); + state_->grid = CudaDevicePtr(); + state_->transform.data = nullptr; + state_->transform.corners = state_->corners.get(); + } cuda_err(cudaStreamSynchronize(state_->stream)); } diff --git a/image_analysis/structure_refinement/MolecularReplacementGPU.h b/image_analysis/structure_refinement/MolecularReplacementGPU.h index 1d68e31e0..2e48f3207 100644 --- a/image_analysis/structure_refinement/MolecularReplacementGPU.h +++ b/image_analysis/structure_refinement/MolecularReplacementGPU.h @@ -28,9 +28,10 @@ struct TranslationSetupGPU; class MolecularReplacementGPU { public: - // Uploads the molecular transform, on the calling thread's current device. Throws JFJochException on - // a CUDA failure, as every call below does. - explicit MolecularReplacementGPU(const MolecularTransform &ft); + // Uploads the molecular transform, on the calling thread's current device; `packed`: with each point's + // interpolation corners together, read from two places instead of four, for more memory (TransformBytes) + // and to the same bits. Throws JFJochException on a CUDA failure, as every call below does. + explicit MolecularReplacementGPU(const MolecularTransform &ft, bool packed = false); ~MolecularReplacementGPU(); std::vector RotationFunction(const SearchReflections &refl, const gemmi::UnitCell &cell, @@ -48,6 +49,8 @@ public: std::unique_ptr Prepare(const TranslationSetup &setup, bool known_part); + // The device memory the transform is held in, plain or packed; while the packed one is made, both. + static size_t TransformBytes(const MolecularTransform &ft, bool packed); // The device memory a call takes for as long as it runs, and gives back when it returns: RotationFunction() // of `rotations` against `refl`'s reflections in `sg`, and TranslationFunction() of `rotations` (with // `known`, beside a known partial structure). diff --git a/tests/MolecularReplacementTest.cpp b/tests/MolecularReplacementTest.cpp index e03353a9f..c7a335f3b 100644 --- a/tests/MolecularReplacementTest.cpp +++ b/tests/MolecularReplacementTest.cpp @@ -159,6 +159,23 @@ TEST_CASE("MolecularReplacement_GPUPlanPartThatDoesNotFitGoesToTheCPU", "[Molecu CHECK(plan.room == 0); } +TEST_CASE("MolecularReplacement_GPUPackedTransformWhereThePlanHoldsAsMuch", "[MolecularReplacement]") { + // The large cell's transform packed, 2.28 GB: beside one rigid-body engine and a score engine on a 16 GB + // and on an 8 GB card, but on a 6 GB card the score engine would no longer fit. + const size_t packed = 2276000000; + CHECK(PackMolecularTransformGPU(LargeCellNeed(16 * GB), packed)); + CHECK(PackMolecularTransformGPU(LargeCellNeed(8 * GB), packed)); + CHECK(!PackMolecularTransformGPU(LargeCellNeed(6 * GB), packed)); + // On 24 GB the plain transform leaves room for a third rigid-body engine within half the budget; packed, + // it would not. + CHECK(PlanMolecularReplacementGPU(LargeCellNeed(24 * GB)).rigid_body_engines == 3); + CHECK(!PackMolecularTransformGPU(LargeCellNeed(24 * GB), packed)); + // No budget: nothing on the GPU, so nothing packed. + MolecularReplacementGPUNeed none = LargeCellNeed(16 * GB); + none.budget = 0; + CHECK(!PackMolecularTransformGPU(none, packed)); +} + TEST_CASE("MolecularReplacement_UniformRotationsCoverSO3", "[MolecularReplacement]") { const auto rotations = UniformRotations(6.0); const double step = 6.0 * M_PI / 180.0; @@ -551,6 +568,17 @@ TEST_CASE("MolecularReplacement_GPUMatchesCPU", "[MolecularReplacement]") { for (double d : {tf_gpu[i].t.x - cpu.t.x, tf_gpu[i].t.y - cpu.t.y, tf_gpu[i].t.z - cpu.t.z}) CHECK(std::fabs(2 * d - std::round(2 * d)) < 1e-6); } + // The packed transform gives the same bits as the plain one. + MolecularReplacementGPU packed(ft, true); + CHECK(packed.RotationFunction(refl, cell, sg, rotations) == rf_gpu); + const auto tf_packed = packed.TranslationFunction(setup, orientations); + for (size_t i = 0; i < orientations.size(); i++) { + CHECK(tf_packed[i].z == tf_gpu[i].z); + CHECK(tf_packed[i].t.x == tf_gpu[i].t.x); + CHECK(tf_packed[i].t.y == tf_gpu[i].t.y); + CHECK(tf_packed[i].t.z == tf_gpu[i].t.z); + } + CHECK(MolecularReplacementGPU::TransformBytes(ft, true) > MolecularReplacementGPU::TransformBytes(ft, false)); // The molecular transform's FFT. gemmi::DensityCalculator, float> dc; dc.d_min = 4.0;