From 92f6bcdc750bf583fa7302ad18a6d9c429171a86 Mon Sep 17 00:00:00 2001 From: Filip Leonarski Date: Mon, 16 Nov 2026 18:13:08 +0100 Subject: [PATCH] Refinement minimiser: a per-atom trust floor on the normal matrix, a per-residue preconditioner, a fixed CG count Traced: with the X-ray curvature per atom as the only curvature of a soft mode (a high-B side chain turning about a single bond, which the restraints leave free), the normal matrix's inverse made steps of tens to hundreds of A there, and the global step bound then scaled every other atom's step down to a few percent; a rounding difference of 1e-7 in the gradient moved a trial's R-free by up to 0.004. - Each atom's diagonal is raised, once per call, to at least |g_i| over the step bound, so that such an atom's step is held by its own curvature: the first trial's iterations take the full step, and a 1e-7 perturbation stays at 1e-7. - The CG is preconditioned per residue (the residue's own J^T J and X-ray diagonal, by Cholesky), and runs a fixed 20 iterations instead of to a tolerance, whose iteration count a rounding difference can flip. - The per-atom 3 x 3 blocks (CPU and GPU) are gone with the preconditioner they served. GPU, 19 sets, against the rc188-merge protocol and minimiser: R-free -0.0014 mean, -0.0008 median, worse by > 0.002 on 2 and better on 7 (the experiment's build); 158k -> 47k evaluations. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01UqXYdJDrM65gxsCn2PrbfK --- .../structure_refinement/Refinement.cpp | 170 +++++++++++------- .../RefinementNewtonGPU.cu | 36 ---- .../RefinementNewtonGPU.h | 3 +- tests/RefinementTest.cpp | 30 +--- 4 files changed, 109 insertions(+), 130 deletions(-) diff --git a/image_analysis/structure_refinement/Refinement.cpp b/image_analysis/structure_refinement/Refinement.cpp index 7637610a8..d05c9c53d 100644 --- a/image_analysis/structure_refinement/Refinement.cpp +++ b/image_analysis/structure_refinement/Refinement.cpp @@ -18,6 +18,7 @@ #include #include +#include #include #include #include @@ -1006,26 +1007,26 @@ std::vector FlooredDiagonal(std::vector d) { // The minimisers' initial inverse Hessian (RefinementMinimiser::SetInverseHessian) is the Gauss-Newton normal matrix of // the target, as REFMAC refines on its sparse normal matrix: the X-ray target's curvature per atom on the diagonal and -// the restraints' J^T J in full, solved for each direction by conjugate gradients to a tenth of the residual. +// the restraints' J^T J in full, solved for each direction by a fixed number of conjugate-gradient iterations - not to a +// tolerance, whose iteration count, and with it the direction, a rounding difference can flip. // Following Murshudov, Vagin & Dodson (1997) Acta Cryst. D53, 240-255 -constexpr int NORMAL_CG_ITERATIONS = 50; -constexpr double NORMAL_CG_TOLERANCE = 0.1; +constexpr int NORMAL_CG_ITERATIONS = 20; -// `target` by `minimiser` (its memory from the call before) from where it is, H0 the inverse of the normal matrix: at(x) -// takes the matrix at x (where the minimiser stands), then hv = H v (product) and z = M^-1 r for a preconditioner M of -// it (precondition). +// `target` by `minimiser` (its memory from the call before) from where it is, H0 the inverse of the normal matrix: at(x, q) +// takes the matrix at x (where the minimiser stands; q the vector H0 is about to be applied to), then hv = H v +// (product) and z = M^-1 r for a preconditioner M of it (precondition). template void MinimiseWithNormalMatrix(Context &ctx, const Target &target, RefinementMinimiser &minimiser, int iterations, - const std::function &)> &at, + const std::function &, const std::vector &)> &at, const std::function &, std::vector &)> &product, const std::function &, std::vector &)> &precondition) { std::vector p = target.Get(); if (p.empty()) return; minimiser.SetInverseHessian([&](const std::vector &x, std::vector &q) { - at(x); + at(x, q); std::vector z; - ConjugateGradients(product, precondition, q, z, NORMAL_CG_ITERATIONS, NORMAL_CG_TOLERANCE, ctx.nthreads); + ConjugateGradients(product, precondition, q, z, NORMAL_CG_ITERATIONS, 0.0, ctx.nthreads); q.swap(z); }); minimiser.Minimise([&](const std::vector &x, double &f, std::vector &g) { @@ -1112,26 +1113,6 @@ public: }); } - // Per parameter atom the 3 x 3 block of J^T J on its x y z (xx yy zz xy xz yz); positions only. - std::vector> Blocks() const { -#ifdef JFJOCH_USE_CUDA - if (gpu_) - return gpu_->Blocks(); -#endif - std::vector> b(n_params_, {0, 0, 0, 0, 0, 0}); - for (size_t k = 0; k < n_params_; k++) - for (int q = entry_start_[k]; q < entry_start_[k + 1]; q++) { - const std::array &j = jac_.j[entry_[q]]; - b[k][0] += j[0] * j[0]; - b[k][1] += j[1] * j[1]; - b[k][2] += j[2] * j[2]; - b[k][3] += j[0] * j[1]; - b[k][4] += j[0] * j[2]; - b[k][5] += j[1] * j[2]; - } - return b; - } - std::vector Diagonal() const { #ifdef JFJOCH_USE_CUDA if (gpu_) @@ -1157,33 +1138,76 @@ private: #endif }; -// z = M^-1 r for M symmetric positive definite (xx yy zz xy xz yz), by its adjugate. -std::array Solve3(const std::array &m, double r0, double r1, double r2) { - const double a = m[0], b = m[1], c = m[2], d = m[3], e = m[4], f = m[5]; - const double c00 = b * c - f * f, c01 = e * f - d * c, c02 = d * f - b * e; - const double c11 = a * c - e * e, c12 = d * e - a * f, c22 = a * b - d * d; - const double det = a * c00 + d * c01 + e * c02; - return {(c00 * r0 + c01 * r1 + c02 * r2) / det, (c01 * r0 + c11 * r1 + c12 * r2) / det, - (c02 * r0 + c12 * r1 + c22 * r2) / det}; -} +// The positions' preconditioner: per residue the dense block of H over its atoms' x y z - the restraints within the +// residue (J^T J of the rows whose atoms it holds, at the point given) and the X-ray diagonal `h` - by its Cholesky +// factor. What couples residues (peptide bonds, NCS, contacts) is left to the conjugate gradients; the stiff bonds +// and angles within a residue, which a diagonal or a block per atom leaves to them too, are solved here. +class ResidueBlocks { +public: + ResidueBlocks(Context &ctx, const std::vector ¶m_atoms, const RestraintSet &set, const std::vector &h) { + std::vector residue_of; // per atom, in model order + for (const gemmi::Chain &ch : ctx.Model().chains) + for (const gemmi::Residue &r : ch.residues) { + residue_of.insert(residue_of.end(), r.atoms.size(), static_cast(params_.size())); + params_.emplace_back(); + } + std::vector local(param_atoms.size()), group(param_atoms.size()), param_of(ctx.atoms.size(), -1); + for (size_t k = 0; k < param_atoms.size(); k++) { + group[k] = residue_of[param_atoms[k]]; + local[k] = static_cast(params_[group[k]].size()); + params_[group[k]].push_back(static_cast(k)); + param_of[param_atoms[k]] = static_cast(k); + } + std::vector block(params_.size()); + for (size_t g = 0; g < params_.size(); g++) { + const int m = 3 * static_cast(params_[g].size()); + block[g] = Eigen::MatrixXd::Zero(m, m); + for (size_t l = 0; l < params_[g].size(); l++) + for (int c = 0; c < 3; c++) + block[g](3 * l + c, 3 * l + c) = h[3 * params_[g][l] + c]; + } + const RestraintJacobian jac = RestraintGaussNewton(set, ctx.XyzB()); + for (size_t row = 0; row + 1 < jac.start.size(); row++) + for (int e1 = jac.start[row]; e1 < jac.start[row + 1]; e1++) + for (int e2 = jac.start[row]; e2 < jac.start[row + 1]; e2++) { + const int k1 = param_of[jac.atom[e1]], k2 = param_of[jac.atom[e2]]; + if (k1 < 0 || k2 < 0 || group[k1] != group[k2]) + continue; + Eigen::MatrixXd &b = block[group[k1]]; + for (int a = 0; a < 3; a++) + for (int c = 0; c < 3; c++) + b(3 * local[k1] + a, 3 * local[k2] + c) += jac.j[e1][a] * jac.j[e2][c]; + } + llt_.resize(params_.size()); + ParallelFor(static_cast(params_.size()), ctx.nthreads, [&](int g) { llt_[g].compute(block[g]); }); + } -// The positions' preconditioner: per atom its 3 x 3 block of H, the restraints' (`blocks`) plus the X-ray curvature `h`. -void PreconditionBlocks(const std::vector> &blocks, const std::vector &h, - const std::vector &r, std::vector &z, size_t nthreads) { - refine_vec::Each(blocks.size(), nthreads, [&](size_t k) { - std::array m = blocks[k]; - for (int c = 0; c < 3; c++) - m[c] += h[3 * k + c]; - const std::array s = Solve3(m, r[3 * k], r[3 * k + 1], r[3 * k + 2]); - z[3 * k] = s[0]; - z[3 * k + 1] = s[1]; - z[3 * k + 2] = s[2]; - }); -} + void Apply(const std::vector &r, std::vector &z, size_t nthreads) const { + z.resize(r.size()); + ParallelFor(static_cast(params_.size()), nthreads, [&](int g) { + const std::vector &p = params_[g]; + Eigen::VectorXd rg(3 * p.size()); + for (size_t l = 0; l < p.size(); l++) + for (int c = 0; c < 3; c++) + rg(3 * l + c) = r[3 * p[l] + c]; + const Eigen::VectorXd zg = llt_[g].solve(rg); + for (size_t l = 0; l < p.size(); l++) + for (int c = 0; c < 3; c++) + z[3 * p[l] + c] = zg(3 * l + c); + }); + } + +private: + std::vector> params_; // per residue its parameter atoms (their index among the parameters) + std::vector> llt_; +}; // The positions or the B factors: H = diag(xray) (per atom, already times the weight) + the restraints' J^T J of `set`, -// the Jacobian at the point of the product. Preconditioned per atom: by its 3 x 3 block of H at the start for the -// positions, by the diagonal for the B factors. +// the Jacobian at the point of each direction. The diagonal is raised per atom, once per call, to at least |g_i| over the +// step bound (g_i the atom's part of the first direction's gradient): where nothing else curves the target (a high-B +// side chain turning about a single bond, which the restraints leave free and the X-ray target hardly sees) the step +// is then held to the bound by the atom's own curvature, instead of one such atom scaling down the whole step. +// Preconditioned per residue for the positions (ResidueBlocks), by the diagonal for the B factors. void MinimiseAtoms(Context &ctx, const AtomTarget &target, RefinementMinimiser &minimiser, const std::vector &xray, const RestraintSet &set, int iterations) { const bool xyz = target.GetMode() == AtomTarget::Mode::Xyz; @@ -1196,12 +1220,25 @@ void MinimiseAtoms(Context &ctx, const AtomTarget &target, RefinementMinimiser & RestraintNormalMatrix normal(ctx, target.Atoms(), xyz); target.Set(x_at.data()); normal.At(set, ctx.XyzB()); - std::vector diagonal = normal.Diagonal(); - for (size_t k = 0; k < n; k++) - diagonal[k] += h[k]; - diagonal = FlooredDiagonal(diagonal); - const std::vector> blocks = xyz ? normal.Blocks() : std::vector>(); - auto at = [&](const std::vector &x) { + const std::vector restraint_diagonal = normal.Diagonal(); + std::vector diagonal; + std::unique_ptr residues; + auto at = [&](const std::vector &x, const std::vector &q) { + if (diagonal.empty()) { // the first direction: the floor, then the preconditioner with it + for (size_t a = 0; a < n / per; a++) { + double g2 = 0; + for (int c = 0; c < per; c++) + g2 += q[per * a + c] * q[per * a + c]; + for (int c = 0; c < per; c++) + h[per * a + c] = std::max(h[per * a + c], std::sqrt(g2) / target.MaxStep()); + } + diagonal.resize(n); + for (size_t k = 0; k < n; k++) + diagonal[k] = restraint_diagonal[k] + h[k]; + diagonal = FlooredDiagonal(diagonal); + if (xyz) + residues = std::make_unique(ctx, target.Atoms(), set, h); + } if (x != x_at) { x_at = x; target.Set(x.data()); @@ -1213,11 +1250,12 @@ void MinimiseAtoms(Context &ctx, const AtomTarget &target, RefinementMinimiser & refine_vec::Each(n, ctx.nthreads, [&](size_t k) { hv[k] += h[k] * v[k]; }); }; auto precondition = [&](const std::vector &r, std::vector &z) { - z.resize(r.size()); - if (xyz) - PreconditionBlocks(blocks, h, r, z, ctx.nthreads); - else + if (residues) + residues->Apply(r, z, ctx.nthreads); + else { + z.resize(r.size()); refine_vec::Each(n, ctx.nthreads, [&](size_t k) { z[k] = r[k] / diagonal[k]; }); + } }; MinimiseWithNormalMatrix(ctx, target, minimiser, iterations, at, product, precondition); } @@ -1228,7 +1266,7 @@ void MinimiseU(Context &ctx, const AdpTarget &target, RefinementMinimiser &minim const std::vector &diagonal, int iterations) { const size_t n = xray.size(); std::vector x_at, g_at(n), xp(n), gp(n); - auto at = [&](const std::vector &x) { + auto at = [&](const std::vector &x, const std::vector &) { if (x != x_at) { x_at = x; target.RestraintGradient(x.data(), g_at.data()); @@ -1296,8 +1334,8 @@ void MinimiseTls(Context &ctx, const AdpTarget &target, RefinementMinimiser &min for (size_t k = 0; k < r.size(); k++) z[k] = r[k] / diagonal[k]; }; - MinimiseWithNormalMatrix(ctx, target, minimiser, iterations, [](const std::vector &) {}, product, - precondition); + MinimiseWithNormalMatrix(ctx, target, minimiser, iterations, + [](const std::vector &, const std::vector &) {}, product, precondition); } // Groups of atoms that move as rigid bodies (one per chain) against the X-ray target: per body an angle-axis diff --git a/image_analysis/structure_refinement/RefinementNewtonGPU.cu b/image_analysis/structure_refinement/RefinementNewtonGPU.cu index a3c61554e..a11281e46 100644 --- a/image_analysis/structure_refinement/RefinementNewtonGPU.cu +++ b/image_analysis/structure_refinement/RefinementNewtonGPU.cu @@ -197,24 +197,6 @@ __global__ void DiagonalKernel(const int *entry_start, const int *entry, const f } } -__global__ void BlocksKernel(const int *entry_start, const int *entry, const float4 *j, float *b, int n) { - const int k = blockIdx.x * blockDim.x + threadIdx.x; - if (k >= n) - return; - float s[6] = {0, 0, 0, 0, 0, 0}; - for (int q = entry_start[k]; q < entry_start[k + 1]; q++) { - const float4 x = j[entry[q]]; - s[0] += x.x * x.x; - s[1] += x.y * x.y; - s[2] += x.z * x.z; - s[3] += x.x * x.y; - s[4] += x.x * x.z; - s[5] += x.y * x.z; - } - for (int c = 0; c < 6; c++) - b[6 * k + c] = s[c]; -} - template CudaDevicePtr Up(const std::vector &host, cudaStream_t stream) { CudaDevicePtr d(std::max(host.size(), 1)); @@ -335,21 +317,3 @@ std::vector RestraintNormalMatrixGPU::Diagonal() const { return out; } -std::vector> RestraintNormalMatrixGPU::Blocks() const { - DeviceGuard guard(dev_->device); - Device &d = *dev_; - const int n = static_cast(n_params_); - std::vector> out(n_params_); - if (n == 0) - return out; - CudaDevicePtr b(6 * n_params_); - std::vector host(6 * n_params_); - BlocksKernel<<>>(d.entry_start, d.entry, d.j, b, n); - cuda_err(cudaGetLastError()); - cuda_err(cudaMemcpyAsync(host.data(), b.get(), host.size() * sizeof(float), cudaMemcpyDeviceToHost, d.stream)); - cuda_err(cudaStreamSynchronize(d.stream)); - for (size_t k = 0; k < n_params_; k++) - for (int c = 0; c < 6; c++) - out[k][c] = host[6 * k + c]; - return out; -} diff --git a/image_analysis/structure_refinement/RefinementNewtonGPU.h b/image_analysis/structure_refinement/RefinementNewtonGPU.h index 3136ed029..317cfa8f9 100644 --- a/image_analysis/structure_refinement/RefinementNewtonGPU.h +++ b/image_analysis/structure_refinement/RefinementNewtonGPU.h @@ -31,8 +31,7 @@ public: void At(const RestraintSet &set, const std::vector> &xyzb); // hv = J^T J v void Multiply(const std::vector &v, std::vector &hv); - // Per parameter atom the 3 x 3 block of J^T J on its x y z (xx yy zz xy xz yz); positions only. - std::vector> Blocks() const; + // The diagonal of J^T J. std::vector Diagonal() const; private: diff --git a/tests/RefinementTest.cpp b/tests/RefinementTest.cpp index 4597972f6..c53a232e3 100644 --- a/tests/RefinementTest.cpp +++ b/tests/RefinementTest.cpp @@ -1071,9 +1071,8 @@ TEST_CASE("RefinementNewton_product_GPU_vs_CPU", "[Refinement]") { std::vector v(n); for (size_t i = 0; i < n; i++) v[i] = smooth ? 0.3 + 0.2 * (i % per) + 1e-3 * uniform(gen) : uniform(gen); - // J^T J v, the diagonal and the 3 x 3 blocks on the CPU, each entry in turn + // J^T J v and the diagonal on the CPU, each entry in turn std::vector hv(n, 0.0), diagonal(n, 0.0); - std::vector> blocks(params.size(), {0, 0, 0, 0, 0, 0}); for (size_t r = 0; r + 1 < jac.start.size(); r++) { double t = 0; for (int e = jac.start[r]; e < jac.start[r + 1]; e++) @@ -1090,12 +1089,6 @@ TEST_CASE("RefinementNewton_product_GPU_vs_CPU", "[Refinement]") { const std::array &j = jac.j[e]; for (int c = 0; c < per; c++) diagonal[per * k + c] += j[c0 + c] * j[c0 + c]; - blocks[k][0] += j[0] * j[0]; - blocks[k][1] += j[1] * j[1]; - blocks[k][2] += j[2] * j[2]; - blocks[k][3] += j[0] * j[1]; - blocks[k][4] += j[0] * j[2]; - blocks[k][5] += j[1] * j[2]; } RestraintNormalMatrixGPU gpu(0, params, atoms.size(), xyz); gpu.At(set, xyzb); @@ -1105,32 +1098,17 @@ TEST_CASE("RefinementNewton_product_GPU_vs_CPU", "[Refinement]") { REQUIRE(hv_gpu.size() == n); REQUIRE(diagonal_gpu.size() == n); // In float, from float positions: within a few float epsilons of the double product in norm (in refinement - // its error is 2e-7 on average, 7e-6 at most), each element of the diagonal relative to itself, each block - // relative to its own size. - double num = 0, den = 0, worst_diagonal = 0, worst_block = 0; + // its error is 2e-7 on average, 7e-6 at most), each element of the diagonal relative to itself. + double num = 0, den = 0, worst_diagonal = 0; for (size_t i = 0; i < n; i++) { num += (hv_gpu[i] - hv[i]) * (hv_gpu[i] - hv[i]); den += hv[i] * hv[i]; if (diagonal[i] > 0) worst_diagonal = std::max(worst_diagonal, std::fabs(diagonal_gpu[i] - diagonal[i]) / diagonal[i]); } - if (xyz) { - const std::vector> blocks_gpu = gpu.Blocks(); - REQUIRE(blocks_gpu.size() == params.size()); - for (size_t k = 0; k < params.size(); k++) { - double d2 = 0, b2 = 0; - for (int c = 0; c < 6; c++) { - d2 += (blocks_gpu[k][c] - blocks[k][c]) * (blocks_gpu[k][c] - blocks[k][c]); - b2 += blocks[k][c] * blocks[k][c]; - } - if (b2 > 0) - worst_block = std::max(worst_block, std::sqrt(d2 / b2)); - } - } - CAPTURE(std::sqrt(num / den), worst_diagonal, worst_block); + CAPTURE(std::sqrt(num / den), worst_diagonal); CHECK(std::sqrt(num / den) < 1e-5); CHECK(worst_diagonal < 1e-5); - CHECK(worst_block < 1e-5); } }