Files
Filip LeonarskiandClaude Opus 5.5 88330f395f Refinement gradient on the Apple GPU: the sums over the derivative map in Metal
RESULT-CHANGING (ulp level; owner approved for Metal ports where exactness costs speed)

AtomGradientsFromMap() takes a `gpu` flag; the CPU engine sets it, and on macOS the sums of every
atom's box against the FFT method's map then run on the Apple GPU (AtomGradientMetal.mm/.metal):
one SIMD group of 32 threads per atom, the lanes taking the box's points in turn, as
RefinementGPU.cu's atom_gradient_kernel does under CUDA. Each atom's box, radius and Gaussians are
the CPU's (built on the host as the CPU loops build them), and a point's place and the radius test
are spelled as GatherMapPoints() spells them with fast math and contraction off, so the GPU takes
the same points; the sums are in single precision and in another order, so the gradient is not the
CPU's bit for bit. Where the GPU does not take it (rugnux --no-gpu, no device, a box wider than the
cell) or fails (one warning, then the CPU from there on) the CPU loops run as before.

Parity (AtomGradientMetal_MatchesCPU, [portable][Metal], 2000 atoms, a quarter anisotropic, P1
triclinic and P212121): worst |GPU - CPU| over the largest |CPU| of that derivative 0.6-1.0e-6 for
x, y, z, B and 2.1-7.6e-6 for U; held to 1e-5 and 5e-5.

M6 Mac mini, rugnux --mode refine, an open-arm set (9zlo, its merged MTZ and refined model):
90.6 s -> 45.8 s wall; R-work 0.2697 both, R-free 0.2936 -> 0.2938. With --no-gpu the refined model
is byte-identical to the build before (115 s: --no-gpu also takes the density gather off the GPU).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UqXYdJDrM65gxsCn2PrbfK
2026-11-16 07:21:12 +01:00

135 lines
5.3 KiB
Metal

// SPDX-FileCopyrightText: 2026 Filip Leonarski, Paul Scherrer Institute <filip.leonarski@psi.ch>
// SPDX-License-Identifier: GPL-3.0-only AND MPL-2.0
// The refinement gradient's sums over the map (AtomGradientMetal.h), compiled when it is first used from this source,
// which CMakeLists.txt copies into the binary. The place of a point and the test against the radius are spelled as
// GatherMapPoints() (RefinementXray.cpp) spells them, with no a*b+c contracted, so that the GPU takes the CPU's points.
#include <metal_stdlib>
using namespace metal;
#pragma clang fp contract(off)
struct Atom { // ModelDensityMetalAtom
float nctr[3];
int c[3], d[3];
float max_r2;
float occ;
int aniso;
float a[5];
float b[5][6];
};
struct Grid { // ModelDensityMetalGrid
int nu, nv, nw;
float m00, m01, m02, m11, m12, m22;
};
struct Sums { // AtomGradientMetalSums
float s[9];
};
// gemmi's unsafe_expapprox() (formfact.hpp, MPL-2.0; https://github.com/project-gemmi/gemmi), as in
// ModelDensityMetal.metal.
static float expapprox(float x) {
const float val = 12102203.1615614f * x + 1065353216.f;
const int vali = static_cast<int>(val);
const int xu1 = vali & 0x7F800000;
const int xu2 = (vali & 0x7FFFFF) | 0x3F800000;
const float a = as_type<float>(xu1);
const float b = as_type<float>(xu2);
return a * (0.509871020f + b * (0.312146713f + b * (0.166617139f + b *
(-2.190619930e-3f + b * 1.3555747234e-2f))));
}
static int wrap(int i, int n) {
const int m = i % n;
return m < 0 ? m + n : m;
}
// One SIMD group of 32 threads per atom: the lanes take the box's points in turn, u fastest, each summing its own,
// and the group's sums are added at the end.
kernel void atom_gradient(device const Atom *atoms [[buffer(0)]], constant Grid &g [[buffer(1)]],
device const float *map [[buffer(2)]], device Sums *out [[buffer(3)]],
constant uint &n [[buffer(4)]],
uint group [[threadgroup_position_in_grid]], uint sg [[simdgroup_index_in_threadgroup]],
uint groups_per_tg [[simdgroups_per_threadgroup]], uint lane [[thread_index_in_simdgroup]]) {
const uint i = group * groups_per_tg + sg;
if (i >= n)
return;
device const Atom &at = atoms[i];
const int span[3] = {2 * at.d[0] + 1, 2 * at.d[1] + 1, 2 * at.d[2] + 1};
const int lo[3] = {at.c[0] - at.d[0], at.c[1] - at.d[1], at.c[2] - at.d[2]};
const int total = span[0] * span[1] * span[2];
float s[9] = {0, 0, 0, 0, 0, 0, 0, 0, 0};
// the lane's point, as offsets in the box, moved on by 32 points at a time
int iu = int(lane), iv = 0, iw = 0;
while (iu >= span[0]) {
iu -= span[0];
if (++iv == span[1]) {
iv = 0;
iw++;
}
}
for (int t = int(lane); t < total; t += 32) {
const int u = lo[0] + iu, v = lo[1] + iv, w = lo[2] + iw;
iu += 32;
while (iu >= span[0]) {
iu -= span[0];
if (++iv == span[1]) {
iv = 0;
iw++;
}
}
// GatherMapPoints()'s place and test
const float fz = at.nctr[2] - float(w);
const float z = g.m22 * fz;
const float fy = at.nctr[1] - float(v);
const float y = g.m11 * fy + g.m12 * fz;
const float yz = y * y + z * z;
const float x_yz = g.m01 * fy + g.m02 * fz;
const float x = g.m00 * (at.nctr[0] - float(u)) + x_yz;
const float r2 = yz + x * x;
if (r2 > at.max_r2)
continue;
const float value = map[uint(wrap(u, g.nu)) + uint(g.nu) * (uint(wrap(v, g.nv)) + uint(g.nv) * uint(wrap(w, g.nw)))];
if (at.aniso == 0) {
float dr2 = 0, db = 0;
for (int q = 0; q < 5; q++) {
const float b = at.b[q][0];
const float e = at.a[q] * expapprox(max(b * r2, -88.f));
dr2 += e * b;
db += e * b * (1.5f + b * r2);
}
s[0] += value * dr2 * x;
s[1] += value * dr2 * y;
s[2] += value * dr2 * z;
s[3] += value * db;
} else {
for (int q = 0; q < 5; q++) {
device const float *m = at.b[q]; // u11 u22 u33 u12 u13 u23
// gemmi's SMat33::r_u_r(), in its order
const float rur = x * x * m[0] + y * y * m[1] + z * z * m[2] + 2 * (x * y * m[3] + x * z * m[4] + y * z * m[5]);
const float e = value * at.a[q] * expapprox(max(rur, -88.f));
const float mr0 = m[0] * x + m[3] * y + m[4] * z;
const float mr1 = m[3] * x + m[1] * y + m[5] * z;
const float mr2 = m[4] * x + m[5] * y + m[2] * z;
s[0] += e * mr0;
s[1] += e * mr1;
s[2] += e * mr2;
s[3] += e * (m[0] + 2 * mr0 * mr0);
s[4] += e * (m[1] + 2 * mr1 * mr1);
s[5] += e * (m[2] + 2 * mr2 * mr2);
s[6] += e * (m[3] + 2 * mr0 * mr1);
s[7] += e * (m[4] + 2 * mr0 * mr2);
s[8] += e * (m[5] + 2 * mr1 * mr2);
}
}
}
for (int k = 0; k < 9; k++)
s[k] = simd_sum(s[k]);
if (lane == 0)
for (int k = 0; k < 9; k++)
out[i].s[k] = s[k];
}