diff --git a/image_analysis/structure_refinement/MolecularReplacement.cpp b/image_analysis/structure_refinement/MolecularReplacement.cpp index e18add1a2..7e5fdc3b1 100644 --- a/image_analysis/structure_refinement/MolecularReplacement.cpp +++ b/image_analysis/structure_refinement/MolecularReplacement.cpp @@ -2384,19 +2384,40 @@ 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; const int device = get_gpu_count() > 0 ? RigidBodyGPUEngine::CurrentDevice() : 0; + bool packed = false; if (get_gpu_count() > 0 && transform_bytes <= gpu_budget) { + // Packed - here and in every copy on the other cards - where the answer merge's plan holds as much beside + // it on every card (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.other_budgets = other_budgets; + 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); + 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)), + other_budgets.empty() ? "" : ", the same in each copy on the other cards"); 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; // The transform's copies on the other cards the plan gives one (made by the first merge's plan, the same for @@ -2468,7 +2489,7 @@ MolecularReplacementResult search_model(const SearchModel &model, const std::vec for (size_t i = 0; i < on.size(); i++) uploading.push_back(std::async(std::launch::async, [&, i] { const ScopedGpuPin pin(on[i]); - copies[i] = std::make_unique(ft); + copies[i] = std::make_unique(ft, packed); })); for (auto &u : uploading) u.get(); @@ -3406,6 +3427,21 @@ 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); + bool same = plan.search && plan.rigid_body_engines == plain.rigid_body_engines + && plan.structure_factors == plain.structure_factors && need.transform + packed <= need.budget; + // Every other card keeps its copy and its engines. A copy is made after the card's engines are reserved, and + // the two within half of its budget leave room for the plain grid it is made from. + for (size_t k = 1; k < plan.cards.size(); k++) + same = same && plan.cards[k].transform == plain.cards[k].transform + && plan.cards[k].rigid_body_engines == plain.cards[k].rigid_body_engines; + return same; +} + #ifdef JFJOCH_USE_CUDA namespace { diff --git a/image_analysis/structure_refinement/MolecularReplacement.h b/image_analysis/structure_refinement/MolecularReplacement.h index c3820666c..f60ab15dc 100644 --- a/image_analysis/structure_refinement/MolecularReplacement.h +++ b/image_analysis/structure_refinement/MolecularReplacement.h @@ -421,6 +421,12 @@ struct MolecularReplacementGPUPlan { // where the work runs, never a number. 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, on this card and in every copy on the other cards: where the plan with it holds +// every part the plain plan holds on every card, 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 c8f3ad538..47e323fc8 100644 --- a/image_analysis/structure_refinement/MolecularReplacementGPU.h +++ b/image_analysis/structure_refinement/MolecularReplacementGPU.h @@ -30,9 +30,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, @@ -50,6 +51,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 cf8f3054e..a131efd74 100644 --- a/tests/MolecularReplacementTest.cpp +++ b/tests/MolecularReplacementTest.cpp @@ -201,6 +201,30 @@ 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)); + // Four cards of 15.6 GB: packed, each other card's copy would leave room for one engine in place of two. + MolecularReplacementGPUNeed four = LargeCellNeed(15600000000); + four.other_budgets = {four.budget, four.budget, four.budget}; + CHECK(!PackMolecularTransformGPU(four, packed)); + // With 24 GB cards beside it, every copy keeps its engines (the nine the search can use): packed. + four.other_budgets.assign(3, LargeCellNeed(24 * GB).budget); + CHECK(PackMolecularTransformGPU(four, 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; @@ -593,6 +617,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;