diff --git a/image_analysis/structure_refinement/ModelMaskGPU.cu b/image_analysis/structure_refinement/ModelMaskGPU.cu index 627da9aa8..d4fc89bb5 100644 --- a/image_analysis/structure_refinement/ModelMaskGPU.cu +++ b/image_analysis/structure_refinement/ModelMaskGPU.cu @@ -206,12 +206,15 @@ __global__ void shrink_edges(const float *mask, int *edge, const int3 *stencil, edge[i] = is_edge; } -// The stencil is symmetric (an offset and its negative are the same distance), so a macromolecule point -// that an edge point reaches is one that reaches an edge point. +// The stencil is symmetric (an offset and its negative are the same distance), so a macromolecule point within +// it of an edge point is one an edge point reaches: each edge point marks its stencil as solvent. The edge points +// are a thin shell, so this visits far fewer points than asking every macromolecule point for an edge within +// reach; every write is the same store of 1, made only to points the edge pass did not change, so the mask is +// the same bit for bit (a solvent point written again stays 1). __global__ void shrink_margin(float *mask, const int *edge, const int3 *stencil, int n_stencil, int nu, int nv, int nw) { const size_t n = static_cast(nu) * nv * nw; const size_t i = blockIdx.x * static_cast(blockDim.x) + threadIdx.x; - if (i >= n || mask[i] >= 1.0f) + if (i >= n || !edge[i]) return; const int u = static_cast(i % nu); const int v = static_cast((i / nu) % nv); @@ -220,10 +223,7 @@ __global__ void shrink_margin(float *mask, const int *edge, const int3 *stencil, const size_t j = wrap(u + stencil[k].x, nu) + static_cast(nu) * (wrap(v + stencil[k].y, nv) + static_cast(nv) * wrap(w + stencil[k].z, nw)); - if (edge[j]) { - mask[i] = 1.0f; - return; - } + mask[j] = 1.0f; } } diff --git a/image_analysis/structure_refinement/Refinement.cpp b/image_analysis/structure_refinement/Refinement.cpp index e5547eda1..981e2b5e5 100644 --- a/image_analysis/structure_refinement/Refinement.cpp +++ b/image_analysis/structure_refinement/Refinement.cpp @@ -179,7 +179,12 @@ struct Context { } { const RefinementStage s2("refit.fmask"); - mask->Fmask(Model(), refl.hkl, fmask); + // the GPU engine masks on the same grid as BulkSolventMask (bit for bit but at points on an atom's + // radius, ModelMaskGPU.h) + if (engine->OnGPU()) + engine->Fmask(Model(), fmask); + else + mask->Fmask(Model(), refl.hkl, fmask); } std::optional s3("refit.scale"); diff --git a/image_analysis/structure_refinement/RefinementGPU.cpp b/image_analysis/structure_refinement/RefinementGPU.cpp index 642fcf319..f08b1df17 100644 --- a/image_analysis/structure_refinement/RefinementGPU.cpp +++ b/image_analysis/structure_refinement/RefinementGPU.cpp @@ -61,6 +61,12 @@ public: setup_.grid.frac[3 * i + j] = cell.frac.mat[i][j]; } setup_.volume = cell.volume; + // the mask on a grid of its own, as BulkSolventMask has it + const gemmi::Grid mask_grid = BulkSolventMask::MaskGrid(cell, sg, d_min); + setup_.mask_grid = setup_.grid; + setup_.mask_grid.nu = mask_grid.nu; + setup_.mask_grid.nv = mask_grid.nv; + setup_.mask_grid.nw = mask_grid.nw; const gemmi::GroupOps gops = sg.operations(); setup_.den = gemmi::Op::DEN; setup_.centring = static_cast(gops.cen_ops.size()); @@ -135,7 +141,7 @@ public: supported_ = !setup_.rows.empty() && ModelDensityGPU::Supports(setup_.grid, widest) && setup_.mask_ops.size() <= ModelMaskGPU::MAX_OPS; if (supported_) { - fft_work_ = RefinementGPUEngine::FFTWorkBytes(device, setup_.grid); + fft_work_ = RefinementGPUEngine::FFTWorkBytes(device, setup_); // the restraints: about thirty records and slots per atom bytes_ = RefinementGPUEngine::DeviceBytes(setup_, fft_work_, 30 * widest.size(), 60 * widest.size()); } diff --git a/image_analysis/structure_refinement/RefinementGPU.cu b/image_analysis/structure_refinement/RefinementGPU.cu index 78ba751f0..5c3ce356c 100644 --- a/image_analysis/structure_refinement/RefinementGPU.cu +++ b/image_analysis/structure_refinement/RefinementGPU.cu @@ -292,6 +292,10 @@ CudaFFTShape ForwardShape(const ModelDensityGrid &g) { .type = CUFFT_R2C}; } +bool SameGrid(const ModelDensityGrid &a, const ModelDensityGrid &b) { + return a.nu == b.nu && a.nv == b.nv && a.nw == b.nw; +} + CudaFFTShape InverseShape(const ModelDensityGrid &g) { return {.n = {g.nw, g.nv, g.nu}, .idist = (g.nu / 2 + 1) * g.nv * g.nw, .odist = g.nu * g.nv * g.nw, .type = CUFFT_C2R}; @@ -372,6 +376,10 @@ struct RefinementGPUEngineImpl { CudaDevicePtr grid; CudaDevicePtr spectrum; CudaDevicePtr fft_work; + // The mask's grid, spectrum and transform where its grid is not the structure factors' (grid, spectrum, + // forward otherwise). + CudaDevicePtr mask_grid; + CudaDevicePtr mask_spectrum; CudaDevicePtr ops, row_hkl; CudaDevicePtr row_scale; CudaDevicePtr k_total, ml_d, ml_var, fo; @@ -384,7 +392,7 @@ struct RefinementGPUEngineImpl { CudaDevicePtr grad; std::unique_ptr density; std::unique_ptr mask; - CudaFFTPlan forward, inverse; + CudaFFTPlan forward, inverse, mask_forward; ModelDensityGPU::Geometry geom{}; Restraints restraints[2]; @@ -424,14 +432,18 @@ struct RefinementGPUEngineImpl { scatter_term = CudaDevicePtr(std::max(setup.scatter_term.size(), 1), sync); density = std::make_unique(stream, setup.max_atoms, setup.max_pairs, ModelDensityGPU::Bricks(setup.grid.nu, setup.grid.nv, setup.grid.nw)); - mask = std::make_unique(stream, GridPoints(setup.grid)); - ModelMaskGrid mask_grid; - mask_grid.nu = setup.grid.nu; - mask_grid.nv = setup.grid.nv; - mask_grid.nw = setup.grid.nw; - std::copy(setup.grid.orth, setup.grid.orth + 9, mask_grid.orth); - mask_grid.volume = setup.volume; - mask->SetGrid(mask_grid, setup.mask_ops); + mask = std::make_unique(stream, GridPoints(setup.mask_grid)); + ModelMaskGrid mg; + mg.nu = setup.mask_grid.nu; + mg.nv = setup.mask_grid.nv; + mg.nw = setup.mask_grid.nw; + std::copy(setup.mask_grid.orth, setup.mask_grid.orth + 9, mg.orth); + mg.volume = setup.volume; + mask->SetGrid(mg, setup.mask_ops); + if (!SameGrid(setup.mask_grid, setup.grid)) { + mask_grid = CudaDevicePtr(GridPoints(setup.mask_grid), sync); + mask_spectrum = CudaDevicePtr(ComplexPoints(setup.mask_grid), sync); + } std::vector flat_ops; for (const auto &o : setup.sym_ops) @@ -461,7 +473,10 @@ struct RefinementGPUEngineImpl { forward = CudaFFTPlan(ForwardShape(setup.grid), stream, fft_work); inverse = CudaFFTPlan(InverseShape(setup.grid), stream, fft_work); - if (forward.WorkBytes() > work_bytes || inverse.WorkBytes() > work_bytes) + if (!SameGrid(setup.mask_grid, setup.grid)) + mask_forward = CudaFFTPlan(ForwardShape(setup.mask_grid), stream, fft_work); + if (forward.WorkBytes() > work_bytes || inverse.WorkBytes() > work_bytes || + (mask_grid.get() != nullptr && mask_forward.WorkBytes() > work_bytes)) throw JFJochException(JFJochExceptionCategory::GPUCUDAError, "refinement: cuFFT work area over the reserve"); cuda_err(cudaStreamSynchronize(stream)); } @@ -469,6 +484,9 @@ struct RefinementGPUEngineImpl { ~RefinementGPUEngineImpl() { cudaStreamSynchronize(stream); } float Norm() const { return static_cast(setup.volume / static_cast(GridPoints(setup.grid))); } + float MaskNorm() const { + return static_cast(setup.volume / static_cast(GridPoints(setup.mask_grid))); + } // The atoms' density on the grid and its transform into the spectrum. void Transform() { @@ -560,9 +578,13 @@ void CopyOut(const float4 *from, int n, std::vector> &to) { } // namespace -size_t RefinementGPUEngine::FFTWorkBytes(int device, const ModelDensityGrid &grid) { +size_t RefinementGPUEngine::FFTWorkBytes(int device, const RefinementGPUSetup &setup) { DeviceGuard guard(device); - return std::max(CudaFFTPlan::WorkBytes(ForwardShape(grid)), CudaFFTPlan::WorkBytes(InverseShape(grid))); + size_t bytes = std::max(CudaFFTPlan::WorkBytes(ForwardShape(setup.grid)), + CudaFFTPlan::WorkBytes(InverseShape(setup.grid))); + if (!SameGrid(setup.mask_grid, setup.grid)) + bytes = std::max(bytes, CudaFFTPlan::WorkBytes(ForwardShape(setup.mask_grid))); + return bytes; } size_t RefinementGPUEngine::DeviceBytes(const RefinementGPUSetup &s, size_t fft_work_bytes, size_t max_records, @@ -573,7 +595,9 @@ size_t RefinementGPUEngine::DeviceBytes(const RefinementGPUSetup &s, size_t fft_ bytes += nr * (3 * sizeof(int) + 2 * sizeof(double) + 4 * sizeof(float) + 4 * sizeof(float2) + 2); bytes += (s.scatter_point.size() + s.scatter_start.size() + s.scatter_term.size()) * sizeof(int); bytes += ModelDensityGPU::DeviceBytes(s.max_atoms, s.max_pairs, ModelDensityGPU::Bricks(s.grid.nu, s.grid.nv, s.grid.nw)); - bytes += ModelMaskGPU::DeviceBytes(GridPoints(s.grid)); + bytes += ModelMaskGPU::DeviceBytes(GridPoints(s.mask_grid)); + if (!SameGrid(s.mask_grid, s.grid)) + bytes += GridPoints(s.mask_grid) * sizeof(float) + ComplexPoints(s.mask_grid) * sizeof(float2); bytes += max_records * (sizeof(RestraintRecord) + sizeof(double)) + max_slots * (sizeof(float4) + sizeof(int)) + na * (2 * sizeof(float4) + sizeof(int)); return bytes; @@ -654,13 +678,17 @@ void RefinementGPUEngine::Fmask(const std::vector &mask_atoms, st if (!mask_atoms.empty()) cuda_err(cudaMemcpyAsync(e.mask_atoms, mask_atoms.data(), mask_atoms.size() * sizeof(ModelMaskAtom), cudaMemcpyHostToDevice, e.stream)); - e.mask->Compute(e.mask_atoms, static_cast(mask_atoms.size()), e.grid); - cufft_err(e.forward.R2C(e.grid, reinterpret_cast(e.spectrum.get()))); + const bool own = e.mask_grid.get() != nullptr; + float *grid = own ? e.mask_grid.get() : e.grid.get(); + float2 *spectrum = own ? e.mask_spectrum.get() : e.spectrum.get(); + e.mask->Compute(e.mask_atoms, static_cast(mask_atoms.size()), grid); + cufft_err((own ? e.mask_forward : e.forward).R2C(grid, reinterpret_cast(spectrum))); const int rows = static_cast(e.setup.rows.size()); f.resize(rows); if (rows > 0) { - fmask_kernel<<>>(e.spectrum, e.Norm(), e.row_hkl, rows, e.setup.grid.nu, - e.setup.grid.nv, e.setup.grid.nw, e.fm); + const ModelDensityGrid &g = e.setup.mask_grid; + fmask_kernel<<>>(spectrum, e.MaskNorm(), e.row_hkl, rows, g.nu, g.nv, g.nw, + e.fm); cuda_err(cudaGetLastError()); cuda_err(cudaMemcpyAsync(f.data(), e.fm, rows * sizeof(float2), cudaMemcpyDeviceToHost, e.stream)); } diff --git a/image_analysis/structure_refinement/RefinementGPUEngine.h b/image_analysis/structure_refinement/RefinementGPUEngine.h index 71eef17ff..c64677c78 100644 --- a/image_analysis/structure_refinement/RefinementGPUEngine.h +++ b/image_analysis/structure_refinement/RefinementGPUEngine.h @@ -22,6 +22,7 @@ // Everything an engine needs that does not depend on the atoms. struct RefinementGPUSetup { ModelDensityGrid grid; // the structure-factor grid, u fastest + ModelDensityGrid mask_grid; // the bulk-solvent mask's (BulkSolventMask::MaskGrid), u fastest double volume = 0; std::vector> sym_ops; // gemmi's Op: rot row-major and tran, in units of 1 / den int den = 24; @@ -43,7 +44,7 @@ class RefinementGPUEngine { public: static size_t DeviceBytes(const RefinementGPUSetup &setup, size_t fft_work_bytes, size_t max_records, size_t max_slots); - static size_t FFTWorkBytes(int device, const ModelDensityGrid &grid); + static size_t FFTWorkBytes(int device, const RefinementGPUSetup &setup); RefinementGPUEngine(int device, const RefinementGPUSetup &setup, size_t fft_work_bytes); ~RefinementGPUEngine(); @@ -61,7 +62,7 @@ public: void SetPositions(const std::vector> &pos); // F of the atoms at the rows. void Fcalc(std::vector> &f); - // The bulk-solvent mask's F at the rows (the mask atoms fractional, wrapped). + // The bulk-solvent mask's F at the rows (the mask atoms fractional, wrapped), on the mask's own grid. void Fmask(const std::vector &mask_atoms, std::vector> &f); // -ln L over the working rows for the atoms last set and, with `grad`, dT/d(x, y, z, B) per atom. double Evaluate(std::vector> *grad); diff --git a/image_analysis/structure_refinement/RefinementXray.cpp b/image_analysis/structure_refinement/RefinementXray.cpp index aa981dd0b..7db2ae0d0 100644 --- a/image_analysis/structure_refinement/RefinementXray.cpp +++ b/image_analysis/structure_refinement/RefinementXray.cpp @@ -230,16 +230,22 @@ RefinementReflections PrepareRefinementReflections(const std::vector BulkSolventMask::MaskGrid(const gemmi::UnitCell &cell, const gemmi::SpaceGroup &sg, double d_min) { + gemmi::Grid grid; + grid.unit_cell = cell; + grid.spacegroup = &sg; + const double spacing = std::max(std::min(d_min / 3.0, MASK_SPACING_MAX), std::cbrt(cell.volume / MASK_POINTS_MAX)); + grid.set_size_from_spacing(spacing, gemmi::GridSizeRounding::Up); + return grid; } void BulkSolventMask::Fmask(const gemmi::Model &model, const std::vector &hkl, std::vector> &f) const { + if (orbit_leaders_.empty()) // at the first mask: a GPU engine's refinement never draws one here + orbit_leaders_ = OrbitLeaders(grid_, nthreads_); gemmi::Grid mask = grid_; PutMaskOnGrid(mask, model, orbit_leaders_, nthreads_); const gemmi::FPhiGrid fm = MapToFPhi(mask); diff --git a/image_analysis/structure_refinement/RefinementXray.h b/image_analysis/structure_refinement/RefinementXray.h index 336cc6d16..4b3e9571c 100644 --- a/image_analysis/structure_refinement/RefinementXray.h +++ b/image_analysis/structure_refinement/RefinementXray.h @@ -66,6 +66,8 @@ public: static constexpr double MASK_SPACING_MAX = 0.4; // A static constexpr double MASK_POINTS_MAX = 1 << 26; BulkSolventMask(const gemmi::UnitCell &cell, const gemmi::SpaceGroup &sg, double d_min, size_t nthreads); + // The mask's grid (sizes and spacing set, values not allocated) - also the GPU engine's (RefinementGPU.cpp). + static gemmi::Grid MaskGrid(const gemmi::UnitCell &cell, const gemmi::SpaceGroup &sg, double d_min); // Fmask (unscaled) of `model` at `hkl`. void Fmask(const gemmi::Model &model, const std::vector &hkl, std::vector> &f) const; @@ -73,7 +75,7 @@ public: private: gemmi::Grid grid_; - std::vector orbit_leaders_; + mutable std::vector orbit_leaders_; // made at the first Fmask() size_t nthreads_; double spacing_; };