Files
Filip LeonarskiandClaude Opus 5.5 3a4dcba3bd Side-chain field on the Apple GPU: the states' direct sums in Metal, bit for bit
RESULT-CHANGING on the CPU (ulp level): the B factor's exp in EvaluatorCPU::Contribution is
BraggExp (bragg_integration/BraggExp.h, at most 0.53 ulp) instead of the libm expf, so that the
Apple GPU, whose exp no host function reproduces, computes the same bits.

MakeSideChainFieldEvaluatorCPU takes a `gpu` flag (the refinement passes settings.gpu); on macOS the
evaluator's Contribution() and the per-state sums of Evaluate() then run on the Apple GPU
(SideChainFieldMetal.mm/.metal): one thread per reflection and state, as SideChainFieldGPU.cu's
contribution_kernel, the evaluator's tables uploaded once, states in batches of 32 so that the
GPU's buffer stays small beside the states' own. Fast math and contraction off - also over the
BraggExp prepended to the kernel source, which a first version left contracted (91 of 60000
values 1-2 ulp off). The likelihood over the combinations stays on the CPU (double). Where the
GPU is hidden (--no-gpu) or fails (one warning) the CPU does the same sums.

SideChainFieldMetal_BitIdenticalToCPU ([portable][Metal]): 20000 reflections, P212121, 70
six-atom states (three batches): every contribution the same bits, every combination's -ln L equal.

M6 Mac mini, rugnux --mode refine of an open-arm set's merged MTZ and refined model, on top of the
Metal gradient (previous commit):
  9s02 (20355 atoms, 306298 reflections, 5 NCS copies): side-chain field 149.0 -> 30.4 s, refinement
       309 -> 184 s wall; R-work 0.2254 / R-free 0.2390 both.
  9zlo: field 7.6 -> 2.4 s, 45.8 -> 41.3 s; R unchanged.
  --no-gpu on 9zlo: the refined model byte-identical to the build before (the field moved nothing).
Not run here: SideChainFieldTest.cpp's [Refinement] cases (jfjoch_test is not built on macOS).

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

157 lines
6.7 KiB
Plaintext

// SPDX-FileCopyrightText: 2026 Filip Leonarski, Paul Scherrer Institute <filip.leonarski@psi.ch>
// SPDX-License-Identifier: GPL-3.0-only
#import <Metal/Metal.h>
#include "SideChainFieldMetal.h"
#include <algorithm>
#include <atomic>
#include <cstdint>
#include <cstring>
#include <limits>
#include <string>
#include "../../common/CUDAWrapper.h" // gpus_are_hidden
#include "../../common/JFJochException.h"
// The kernel's source, SideChainFieldMetal.metal, copied in at configure time (CMakeLists.txt).
extern const char *const side_chain_field_metal_source;
namespace {
std::atomic<size_t> states_on_gpu{0};
static_assert(sizeof(FieldAtom) == 6 * 4, "the kernel's Atom is six words");
struct Kernel {
id<MTLDevice> device = nil; // nil: no Metal device
id<MTLComputePipelineState> pipeline = nil;
id<MTLCommandQueue> queue = nil;
};
// Compiled once per process, the first time it is asked for.
const Kernel &GetKernel() {
static const Kernel kernel = [] {
Kernel k;
k.device = MTLCreateSystemDefaultDevice();
if (k.device == nil)
return k;
MTLCompileOptions *options = [MTLCompileOptions new];
// Fast math off: nothing reassociated or approximated, as on the CPU.
options.fastMathEnabled = NO;
options.languageVersion = MTLLanguageVersion3_0;
NSError *error = nil;
id<MTLLibrary> library = [k.device newLibraryWithSource:@(side_chain_field_metal_source) options:options
error:&error];
if (library == nil)
throw JFJochException(JFJochExceptionCategory::GPUMetalError,
std::string("side-chain field kernel: ") + error.localizedDescription.UTF8String);
id<MTLFunction> function = [library newFunctionWithName:@"contribution"];
k.pipeline = [k.device newComputePipelineStateWithFunction:function error:&error];
if (k.pipeline == nil)
throw JFJochException(JFJochExceptionCategory::GPUMetalError,
std::string("contribution: ") + error.localizedDescription.UTF8String);
k.queue = [k.device newCommandQueue];
return k;
}();
return kernel;
}
id<MTLBuffer> NewBuffer(id<MTLDevice> device, size_t bytes) {
id<MTLBuffer> b = [device newBufferWithLength:std::max<size_t>(bytes, 4) options:MTLResourceStorageModeShared];
if (b == nil)
throw JFJochException(JFJochExceptionCategory::GPUMetalError, "side-chain field: out of GPU memory");
return b;
}
id<MTLBuffer> Upload(id<MTLDevice> device, const std::vector<float> &v) {
id<MTLBuffer> b = NewBuffer(device, v.size() * sizeof(float));
std::memcpy(b.contents, v.data(), v.size() * sizeof(float));
return b;
}
struct Params {
uint32_t rows, n_ops, first;
};
} // namespace
struct SideChainFieldMetal::Impl {
uint32_t rows, n_ops;
id<MTLBuffer> hx, hy, hz, ht, f0, stol2;
};
SideChainFieldMetal::SideChainFieldMetal(std::unique_ptr<Impl> impl) : impl_(std::move(impl)) {}
SideChainFieldMetal::~SideChainFieldMetal() = default;
std::unique_ptr<SideChainFieldMetal> SideChainFieldMetal::Make(size_t rows, size_t n_ops, const std::vector<float> &hx,
const std::vector<float> &hy,
const std::vector<float> &hz,
const std::vector<float> &ht,
const std::vector<float> &f0,
const std::vector<float> &stol2) {
@autoreleasepool {
if (gpus_are_hidden() || rows * std::max<size_t>(n_ops, 1) > std::numeric_limits<uint32_t>::max())
return nullptr;
const Kernel &k = GetKernel();
if (k.device == nil)
return nullptr;
auto impl = std::make_unique<Impl>();
impl->rows = static_cast<uint32_t>(rows);
impl->n_ops = static_cast<uint32_t>(n_ops);
impl->hx = Upload(k.device, hx);
impl->hy = Upload(k.device, hy);
impl->hz = Upload(k.device, hz);
impl->ht = Upload(k.device, ht);
impl->f0 = Upload(k.device, f0);
impl->stol2 = Upload(k.device, stol2);
return std::unique_ptr<SideChainFieldMetal>(new SideChainFieldMetal(std::move(impl)));
}
}
void SideChainFieldMetal::Contributions(const FieldStates &states, int first,
std::vector<std::vector<std::complex<float>>> &out) {
// In a pool of its own, as ModelDensityMetal(): the threads this runs on have none.
@autoreleasepool {
const Kernel &k = GetKernel();
const size_t rows = impl_->rows, count = out.size();
if (count == 0)
return;
id<MTLBuffer> d_atoms = NewBuffer(k.device, states.atoms.size() * sizeof(FieldAtom));
std::memcpy(d_atoms.contents, states.atoms.data(), states.atoms.size() * sizeof(FieldAtom));
id<MTLBuffer> d_start = NewBuffer(k.device, states.start.size() * sizeof(int));
std::memcpy(d_start.contents, states.start.data(), states.start.size() * sizeof(int));
id<MTLBuffer> d_out = NewBuffer(k.device, count * rows * sizeof(std::complex<float>));
const Params p{impl_->rows, impl_->n_ops, static_cast<uint32_t>(first)};
id<MTLCommandBuffer> cb = [k.queue commandBuffer];
id<MTLComputeCommandEncoder> e = [cb computeCommandEncoder];
[e setComputePipelineState:k.pipeline];
id<MTLBuffer> tables[] = {impl_->hx, impl_->hy, impl_->hz, impl_->ht, impl_->f0, impl_->stol2};
for (int i = 0; i < 6; i++)
[e setBuffer:tables[i] offset:0 atIndex:i];
[e setBuffer:d_atoms offset:0 atIndex:6];
[e setBuffer:d_start offset:0 atIndex:7];
[e setBytes:&p length:sizeof(p) atIndex:8];
[e setBuffer:d_out offset:0 atIndex:9];
[e dispatchThreads:MTLSizeMake(rows, count, 1) threadsPerThreadgroup:MTLSizeMake(256, 1, 1)];
[e endEncoding];
[cb commit];
[cb waitUntilCompleted];
if (cb.status != MTLCommandBufferStatusCompleted)
throw JFJochException(JFJochExceptionCategory::GPUMetalError,
cb.error ? cb.error.localizedDescription.UTF8String
: "side-chain field: command buffer failed");
const auto *f = static_cast<const std::complex<float> *>(d_out.contents);
for (size_t s = 0; s < count; s++)
out[s].assign(f + s * rows, f + (s + 1) * rows);
states_on_gpu += count;
}
}
size_t SideChainFieldMetal::States() {
return states_on_gpu;
}