Files
Filip LeonarskiandClaude Opus 5.5 1178452466 Bulk-solvent mask shrink on the Apple GPU, bit for bit
PutMaskOnGrid() takes a `gpu` flag (default on, as PutModelDensityOnGrid's): on macOS the shrink by
the 0.8 A radius (ShrinkMask) runs on the Apple GPU (ShrinkMaskMetal.mm/.metal), one thread per point
applying the CPU's rule - a masked point becomes solvent where a near offset is solvent, or a far
offset is a solvent point with a masked near offset - read from the mask as it was, with the CPU's
offsets; the mask and its copy handed to the GPU in place where page aligned. The atoms, the
symmetrize and gemmi's island removal stay on the CPU. --no-gpu, no device, or a failure (one
warning) keep the CPU's loop.

ShrinkMaskMetal_BitIdenticalToCPU ([portable][Metal]): clustered atoms, 0.4 A mask grids of a
triclinic P1 and a P212121 cell - every point the same bits.

M6 Mac mini, rugnux --mode refine (open-arm sets' merged MTZ and refined model), on top of the two
previous Metal commits: 9s02 184.2 -> 175.6 s, 9zlo 41.3 -> 39.0 s; the refined models
byte-identical to the build before on both.

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

139 lines
5.5 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 "ShrinkMaskMetal.h"
#include <algorithm>
#include <atomic>
#include <cstdint>
#include <cstring>
#include <limits>
#include <string>
#include <unistd.h>
#include "../../common/CUDAWrapper.h" // gpus_are_hidden
#include "../../common/JFJochException.h"
// The kernel's source, ShrinkMaskMetal.metal, copied in at configure time (CMakeLists.txt).
extern const char *const shrink_mask_metal_source;
namespace {
std::atomic<size_t> calls_on_gpu{0};
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];
options.languageVersion = MTLLanguageVersion3_0;
NSError *error = nil;
id<MTLLibrary> library = [k.device newLibraryWithSource:@(shrink_mask_metal_source) options:options
error:&error];
if (library == nil)
throw JFJochException(JFJochExceptionCategory::GPUMetalError,
std::string("mask shrink kernel: ") + error.localizedDescription.UTF8String);
id<MTLFunction> function = [library newFunctionWithName:@"shrink_mask"];
k.pipeline = [k.device newComputePipelineStateWithFunction:function error:&error];
if (k.pipeline == nil)
throw JFJochException(JFJochExceptionCategory::GPUMetalError,
std::string("shrink_mask: ") + 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, "mask shrink: out of GPU memory");
return b;
}
// `data` as it is where its pages can be handed to the GPU, nil otherwise.
id<MTLBuffer> InPlace(id<MTLDevice> device, const float *data, size_t bytes) {
const size_t page = static_cast<size_t>(getpagesize());
if (reinterpret_cast<uintptr_t>(data) % page != 0)
return nil;
return [device newBufferWithBytesNoCopy:const_cast<float *>(data) length:(bytes + page - 1) / page * page
options:MTLResourceStorageModeShared deallocator:nil];
}
struct Params {
int32_t nu, nv, nw, n_near, n_far;
};
} // namespace
bool ShrinkMaskMetal(int nu, int nv, int nw, const std::vector<std::array<int, 3>> &near,
const std::vector<std::array<int, 3>> &far, const float *in, float *out) {
// In a pool of its own, as ModelDensityMetal(): the threads this runs on have none.
@autoreleasepool {
const size_t points = static_cast<size_t>(nu) * nv * nw;
if (gpus_are_hidden() || points > std::numeric_limits<uint32_t>::max())
return false;
const Kernel &k = GetKernel();
if (k.device == nil)
return false;
const size_t bytes = points * sizeof(float);
id<MTLBuffer> d_in = InPlace(k.device, in, bytes);
if (d_in == nil) {
d_in = NewBuffer(k.device, bytes);
std::memcpy(d_in.contents, in, bytes);
}
id<MTLBuffer> d_out = InPlace(k.device, out, bytes);
const bool out_in_place = d_out != nil;
if (!out_in_place)
d_out = NewBuffer(k.device, bytes);
// the offsets as int3, which Metal pads to four ints
id<MTLBuffer> d_offsets = NewBuffer(k.device, (near.size() + far.size()) * 4 * sizeof(int32_t));
auto *o = static_cast<int32_t *>(d_offsets.contents);
size_t n = 0;
for (const auto *v : {&near, &far})
for (const std::array<int, 3> &d : *v) {
o[4 * n] = d[0];
o[4 * n + 1] = d[1];
o[4 * n + 2] = d[2];
o[4 * n + 3] = 0;
n++;
}
const Params p{nu, nv, nw, static_cast<int32_t>(near.size()), static_cast<int32_t>(far.size())};
id<MTLCommandBuffer> cb = [k.queue commandBuffer];
id<MTLComputeCommandEncoder> e = [cb computeCommandEncoder];
[e setComputePipelineState:k.pipeline];
[e setBuffer:d_in offset:0 atIndex:0];
[e setBuffer:d_out offset:0 atIndex:1];
[e setBuffer:d_offsets offset:0 atIndex:2];
[e setBytes:&p length:sizeof(p) atIndex:3];
[e dispatchThreads:MTLSizeMake(points, 1, 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
: "mask shrink: command buffer failed");
if (!out_in_place)
std::memcpy(out, d_out.contents, bytes);
calls_on_gpu++;
return true;
}
}
size_t ShrinkMaskMetalCalls() {
return calls_on_gpu;
}