Merge rc175 (bd7464d70) into gpumem-run
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
8f722227e8
13 files changed
+900
-543
No files matched your search
@@ -271,7 +271,7 @@ The refinement walks a coarse-to-fine ladder, 6 Å → 4.5 Å → 3.5 Å, each z
|
||||
|
||||
The refinement sees **only the working reflections**. The step is then committed only if it lowers **R-free**, computed at full resolution on the free set it never saw; otherwise the model is put back exactly where it was read and the maps are the ones it would have given. The whole addition costs about two seconds. Note that the origin is a gauge in some space groups — free in all three directions in $P1$, and along the unique axis in a polar group — so those components of the translation are undetermined; nothing is done about that beyond the Levenberg–Marquardt damping and the R-free gate, which between them make an undetermined direction harmless rather than unstable.
|
||||
|
||||
Where a CUDA GPU is present, the refinement's target is evaluated on it: the same density, the same composition of $F_\mathrm{calc}$ from one copy of the model, the same bulk-solvent mask with its islands removed, the same scale fit and the same Jacobian, computed on the device, where a fit takes a fraction of a second rather than several seconds. The device is chosen once per validation, before anything is computed, and never revisited - the real fit and every replicate of the null of §14.5 on the same one. The structure factors go to the GPU where their buffers fit a quarter of the card's total memory (judged on the total, so the same input on the same machine always takes the same path), the rigid-body engines take up to another quarter, and the scale fits of §14.2 run on the GPU too, in engines of their own that take at most an eighth of the card; a part that does not fit, or a cell too small for the GPU's gridding, runs on the CPU, as everything does where there is no GPU. A CUDA failure ends the validation, not the run: the validation reports why it did not finish, decides nothing, and the reflection files are those of a run without a model. The two agree to rounding and not bit for bit: the device measures distances in single precision and transforms with cuFFT instead of FFTW, and GEMMI's scale fit, whose stopping rule leaves it unconverged at about $10^{-4}$ of $|F|$, can respond to that rounding with a step of its own. A rigid-body step accepted or rejected on an R-free difference below about $5\cdot10^{-4}$ can therefore go either way between the two; every kernel is deterministic, so either one gives the same answer on every run.
|
||||
Where a CUDA GPU is present, the refinement's target is evaluated on it: the same density, the same composition of $F_\mathrm{calc}$ from one copy of the model, the same bulk-solvent mask with its islands removed, the same scale fit and the same Jacobian, computed on the device, where a fit takes a fraction of a second rather than several seconds. The device is chosen once per validation, before anything is computed, and never revisited - the real fit and every replicate of the null of §14.5 on the same one. What goes on the GPU is decided for all parts at once, on one budget: 80% of the card's total memory (judged on the total, so the same input on the same machine always takes the same path), less what a merge still at work holds there. Every engine is reserved up front and kept to the end, so it is their sum that has to fit: the structure factors to the data's resolution (which also make the maps), one rigid-body engine, the null's structure factors to its coarser limit and one engine for the scale fits of §14.2 each take their place in that order where they still fit, and more rigid-body engines and then more scale-fit engines are added only within half of the budget: they change only how many fits run at once, and on a large cell, where one fit already fills the card, they buy little. A part that does not fit, or a cell too small for the GPU's gridding, runs on the CPU, as everything does where there is no GPU. A CUDA failure ends the validation, not the run: the validation reports why it did not finish, decides nothing, and the reflection files are those of a run without a model. The two agree to rounding and not bit for bit: the device measures distances in single precision and transforms with cuFFT instead of FFTW, and GEMMI's scale fit, whose stopping rule leaves it unconverged at about $10^{-4}$ of $|F|$, can respond to that rounding with a step of its own. A rigid-body step accepted or rejected on an R-free difference below about $5\cdot10^{-4}$ can therefore go either way between the two; every kernel is deterministic, so either one gives the same answer on every run.
|
||||
|
||||
The rotation and translation actually taken are reported (`RIGID_BODY_ROTATION_DEG`, `RIGID_BODY_SHIFT_A`), together with the R-free before it (`R_FREE_BEFORE_RIGID_BODY`), so what the placement bought is visible.
|
||||
|
||||
|
||||
@@ -89,8 +89,8 @@ ErrorModelFit FitErrorModelGPU(const std::vector<ErrorModelSample> &pool) {
|
||||
return fit;
|
||||
const int n = static_cast<int>(pool.size());
|
||||
|
||||
// The rank sort is the peak: the pool, two key and two index arrays and the sort scratch.
|
||||
constexpr size_t BYTES_PER_SAMPLE = 32 + 2 * 8 + 2 * 4 + 16;
|
||||
// The rank sort is the peak: the pool, two key and two index arrays.
|
||||
constexpr size_t BYTES_PER_SAMPLE = 32 + 2 * 8 + 2 * 4;
|
||||
size_t free_bytes = 0;
|
||||
if (!cuda_memory_available(BYTES_PER_SAMPLE * pool.size(), free_bytes))
|
||||
throw JFJochException(JFJochExceptionCategory::GPUCUDAError,
|
||||
@@ -104,22 +104,25 @@ ErrorModelFit FitErrorModelGPU(const std::vector<ErrorModelSample> &pool) {
|
||||
stream));
|
||||
|
||||
// The samples in the host's rank order - (I2/s2, s2, I2, dev2), a total order - by four stable
|
||||
// passes, least significant key first. The equal-count bins are then consecutive stretches.
|
||||
// passes, least significant key first. The equal-count bins are then consecutive stretches. Each
|
||||
// pass goes back and forth between the two key and the two index arrays, so that cub holds no copy
|
||||
// of them of its own; the same stable sort, so the same order.
|
||||
CudaDevicePtr<int32_t> idx(n, ALLOC), idx_next(n, ALLOC);
|
||||
CudaDevicePtr<double> key(n, ALLOC), key_sorted(n, ALLOC);
|
||||
IotaKernel<<<Blocks(n), THREADS, 0, stream>>>(n, idx);
|
||||
cuda_err(cudaGetLastError());
|
||||
cub::DoubleBuffer<double> keys(key.get(), key_sorted.get());
|
||||
cub::DoubleBuffer<int32_t> order(idx.get(), idx_next.get());
|
||||
size_t bytes = 0;
|
||||
cuda_err(cub::DeviceRadixSort::SortPairs(nullptr, bytes, key.get(), key_sorted.get(), idx.get(), idx_next.get(),
|
||||
n, 0, 64, stream));
|
||||
cuda_err(cub::DeviceRadixSort::SortPairs(nullptr, bytes, keys, order, n, 0, 64, stream));
|
||||
CudaDevicePtr<uint8_t> scratch(std::max<size_t>(bytes, 1), ALLOC);
|
||||
for (int field = 0; field < 4; ++field) {
|
||||
KeyKernel<<<Blocks(n), THREADS, 0, stream>>>(n, d_pool, idx, field, key);
|
||||
KeyKernel<<<Blocks(n), THREADS, 0, stream>>>(n, d_pool, order.Current(), field, keys.Current());
|
||||
cuda_err(cudaGetLastError());
|
||||
cuda_err(cub::DeviceRadixSort::SortPairs(scratch.get(), bytes, key.get(), key_sorted.get(), idx.get(),
|
||||
idx_next.get(), n, 0, 64, stream));
|
||||
std::swap(idx, idx_next);
|
||||
cuda_err(cub::DeviceRadixSort::SortPairs(scratch.get(), bytes, keys, order, n, 0, 64, stream));
|
||||
}
|
||||
if (keys.Current() != key_sorted.get()) std::swap(key, key_sorted);
|
||||
if (order.Current() != idx.get()) std::swap(idx, idx_next);
|
||||
scratch = CudaDevicePtr<uint8_t>(); idx_next = CudaDevicePtr<int32_t>(); key = CudaDevicePtr<double>();
|
||||
// After the last pass key_sorted holds I2/s2 in rank order.
|
||||
CudaDevicePtr<double> s2(n, ALLOC), I2(n, ALLOC), dev2(n, ALLOC);
|
||||
|
||||
@@ -19,6 +19,10 @@
|
||||
#include <random>
|
||||
#include <unordered_map>
|
||||
|
||||
#if defined(_MSC_VER) && (defined(_M_X64) || defined(_M_IX86))
|
||||
#include <xmmintrin.h>
|
||||
#endif
|
||||
|
||||
#include <gemmi/unitcell.hpp>
|
||||
#include <gemmi/symmetry.hpp>
|
||||
|
||||
@@ -264,7 +268,14 @@ namespace {
|
||||
for (size_t j = 0; j < to[k].size(); ++j) to[k][j] += from[k][j];
|
||||
}
|
||||
|
||||
struct ScaleObs { double coeff, Iobs, weight; };
|
||||
// Ask for the cache line at p ahead of its use. Only a hint: it changes no result.
|
||||
inline void Prefetch(const void *p) {
|
||||
#if defined(_MSC_VER) && (defined(_M_X64) || defined(_M_IX86))
|
||||
_mm_prefetch(static_cast<const char *>(p), _MM_HINT_T0);
|
||||
#elif defined(__GNUC__) || defined(__clang__)
|
||||
__builtin_prefetch(p);
|
||||
#endif
|
||||
}
|
||||
|
||||
// Per-frame scale, linear in G: the weighted least-squares slope of the observations on their
|
||||
// reference, G = sum w^2 c I / sum w^2 c^2. PLAIN, not the Cauchy-reweighted fit ScaleOnTheFly
|
||||
@@ -281,16 +292,6 @@ namespace {
|
||||
return std::isfinite(G) ? std::max(0.0, G) : 1.0;
|
||||
}
|
||||
|
||||
double SolveScale(const std::vector<ScaleObs> &obs, double &info) {
|
||||
double num = 0.0, den = 0.0;
|
||||
for (const auto &o : obs) {
|
||||
const double w2 = o.weight * o.weight;
|
||||
num += w2 * o.coeff * o.Iobs;
|
||||
den += w2 * o.coeff * o.coeff;
|
||||
}
|
||||
return ScaleFromSums(num, den, info);
|
||||
}
|
||||
|
||||
double median_of(std::vector<double> &v) {
|
||||
std::nth_element(v.begin(), v.begin() + v.size() / 2, v.end());
|
||||
return v[v.size() / 2];
|
||||
@@ -607,18 +608,23 @@ void RotationScaleMerge::IngestHost() {
|
||||
}
|
||||
|
||||
#ifdef JFJOCH_USE_CUDA
|
||||
// The resident path's ingest. The reflections go to the card once, frame by frame, and the card measures
|
||||
// the per-frame background, sorts, cuts the raw-hkl runs and drops what the resolution range excludes
|
||||
// (RotationScaleMergeGPU::IngestUpload .. IngestSort) - the observations, the runs and the order of each
|
||||
// that BuildInRangeObservations lays down on the host, to the bit, and left where the device pipeline
|
||||
// reads them. The geometry smoothing then runs here on what the card hands back.
|
||||
// The resident path's ingest. The reflections go to the card frame by frame, and the card measures the
|
||||
// per-frame background, sorts, cuts the raw-hkl runs and drops what the resolution range excludes
|
||||
// (RotationScaleMergeGPU::IngestUpload .. IngestSort); once the scaling is known to fit, they go to the
|
||||
// card a second time for the observations the cut kept (IngestObservations) - the observations, the runs
|
||||
// and the order of each that BuildInRangeObservations lays down on the host, to the bit, and left where
|
||||
// the device pipeline reads them. The geometry smoothing then runs here on what the card hands back.
|
||||
void RotationScaleMerge::IngestOnDevice() {
|
||||
std::vector<const Reflection *> refl(n_frames);
|
||||
std::vector<int32_t> count(n_frames);
|
||||
size_t n_reflections = 0;
|
||||
for (int o = 0; o < n_frames; ++o) {
|
||||
refl[o] = partials_out[o].reflections.data();
|
||||
count[o] = static_cast<int32_t>(partials_out[o].reflections.size());
|
||||
n_reflections += count[o];
|
||||
}
|
||||
if (ScaleOnCPUWhereSortTooLarge(n_reflections))
|
||||
return;
|
||||
TimingMark upload_mark(*logger, "rsm ingest upload");
|
||||
gpu_->IngestUpload(n_frames, refl.data(), count.data(), nthreads);
|
||||
upload_mark.Stop();
|
||||
@@ -626,7 +632,7 @@ void RotationScaleMerge::IngestOnDevice() {
|
||||
std::vector<double> mean_bkg(n_frames);
|
||||
gpu_->IngestMeanBackground(mean_bkg.data());
|
||||
MeasureIncidentFlux(mean_bkg);
|
||||
const int n = gpu_->IngestSort(frame_flux.data(), d_min_limit, d_max_limit);
|
||||
const int n = gpu_->IngestSort(d_min_limit, d_max_limit);
|
||||
n_partials_obs = n;
|
||||
RotationScaleMergeGPU::IngestLayout layout;
|
||||
gpu_->IngestGetLayout(layout);
|
||||
@@ -643,9 +649,13 @@ void RotationScaleMerge::IngestOnDevice() {
|
||||
rawrun_l = std::move(layout.run_l);
|
||||
rawrun_d = std::move(layout.run_d);
|
||||
// The scaling's footprint is known from here on: where the card cannot take it, the card's work
|
||||
// ends before the smoothing.
|
||||
// ends before a single observation is on it.
|
||||
if (ScaleOnCPUWhereTooLarge())
|
||||
return;
|
||||
auto pos = std::make_shared<ObsPosition>();
|
||||
pos->px.resize(n); pos->py.resize(n);
|
||||
gpu_->IngestObservations(refl.data(), count.data(), nthreads, frame_flux.data(), pos->px.data(), pos->py.data());
|
||||
obs_position = std::move(pos);
|
||||
|
||||
const SmoothedGeometry sg = SmoothedFrameGeometry();
|
||||
int64_t n_resolved = 0;
|
||||
@@ -702,13 +712,28 @@ void RotationScaleMerge::IngestOnDevice() {
|
||||
// scales on the CPU - decided here, once, on the card's total memory, so the answer depends on the card
|
||||
// but not on the moment.
|
||||
bool RotationScaleMerge::ScaleOnCPUWhereTooLarge() {
|
||||
return ScaleOnCPUWhereOverCard(GPUScalingPeakBytes(), fmt::format("scaling {} observations of {} distinct hkl",
|
||||
n_partials_obs, rawrun_start.size()));
|
||||
}
|
||||
|
||||
// Before the sort no observation is on the card yet, nor is it known how many there are: what the sort
|
||||
// and the cut hold (IngestUpload .. IngestSort), measured at 32 bytes per reflection, or 20 and 56 per
|
||||
// raw-hkl run where the runs are many - 48 per reflection with half as many runs as reflections, the
|
||||
// most measured being 0.47 - and the two staging buffers. A set that the card cannot even sort scales
|
||||
// on the CPU without touching the card.
|
||||
bool RotationScaleMerge::ScaleOnCPUWhereSortTooLarge(size_t n_reflections) {
|
||||
constexpr size_t SORT_BYTES_PER_REFLECTION = 48, STAGING_BYTES = size_t(128) << 20;
|
||||
return ScaleOnCPUWhereOverCard(SORT_BYTES_PER_REFLECTION * n_reflections + STAGING_BYTES,
|
||||
fmt::format("sorting {} reflections", n_reflections));
|
||||
}
|
||||
|
||||
bool RotationScaleMerge::ScaleOnCPUWhereOverCard(size_t bytes, const std::string &what) {
|
||||
const size_t card = get_gpu_total_memory(gpu_device);
|
||||
if (GPUScalingPeakBytes() <= CPU_SCALING_ABOVE_CARD_FRACTION * card)
|
||||
if (bytes <= CPU_SCALING_ABOVE_CARD_FRACTION * card)
|
||||
return false;
|
||||
logger->Warning("RotationScaleMerge: scaling {} observations of {} distinct hkl on the GPU needs about "
|
||||
"{:.1f} GB, over {:.0f}% of the card's {:.1f} GB - scaling on the CPU instead",
|
||||
n_partials_obs, rawrun_start.size(), GPUScalingPeakBytes() / 1e9,
|
||||
100.0 * CPU_SCALING_ABOVE_CARD_FRACTION, card / 1e9);
|
||||
logger->Warning("RotationScaleMerge: {} on the GPU needs about {:.1f} GB, over {:.0f}% of the card's {:.1f} GB "
|
||||
"- scaling on the CPU instead", what, bytes / 1e9, 100.0 * CPU_SCALING_ABOVE_CARD_FRACTION,
|
||||
card / 1e9);
|
||||
scale_on_cpu_ = true;
|
||||
gpu_active_ = false;
|
||||
return true;
|
||||
@@ -724,12 +749,13 @@ bool RotationScaleMerge::OnGPU() const {
|
||||
}
|
||||
|
||||
size_t RotationScaleMerge::GPUScalingPeakBytes() const {
|
||||
// The device scaling's peak from this decision on, fitted to the engine's device buffers measured at
|
||||
// their peak on fourteen engines of five large data sets (23-123 M observations, 1.6-15 M distinct
|
||||
// hkl): within 12% on each, the furthest under a P1 merge of a large cell. The ingest's own peak, 82
|
||||
// to 100 bytes per reflection, has passed by the time this decides. Unlike DeviceBytes, an estimate
|
||||
// and not an upper bound - it decides where the GPU clearly cannot take the scaling.
|
||||
constexpr size_t PEAK_BYTES_PER_OBS = 63, PEAK_BYTES_PER_HKL = 115;
|
||||
// The device scaling's peak from this decision on - the observations taken from the reflections
|
||||
// (IngestObservations) included, the sort before it not - fitted to the engine's device buffers
|
||||
// measured at their peak on fourteen engines of five large data sets (23-123 M observations,
|
||||
// 1.6-15 M distinct hkl): within 9% on each, the furthest under a P1 merge of a large cell. Unlike
|
||||
// DeviceBytes, an estimate and not an upper bound - it decides where the GPU clearly cannot take the
|
||||
// scaling.
|
||||
constexpr size_t PEAK_BYTES_PER_OBS = 56, PEAK_BYTES_PER_HKL = 99;
|
||||
return PEAK_BYTES_PER_OBS * static_cast<size_t>(n_partials_obs) + PEAK_BYTES_PER_HKL * rawrun_start.size();
|
||||
}
|
||||
|
||||
@@ -737,22 +763,21 @@ size_t RotationScaleMerge::DeviceBytes() const {
|
||||
// What each costs at the peak: an observation's arrays, and its group CSR until the combine; a full's
|
||||
// arrays with its error-model sample, or with the surface terms; an hkl's raw run and its ASU group's
|
||||
// sums. Fitted as an upper bound to the engine's device buffers measured at their peak on fourteen
|
||||
// engines of five large data sets (23-123 M observations): up to 18% over. The events are counted
|
||||
// engines of five large data sets (23-123 M observations): up to 14% over. The events are counted
|
||||
// on the device path's ingest; elsewhere every observation may be an event of its own.
|
||||
constexpr size_t BYTES_PER_OBS = 66, BYTES_PER_EVENT = 94, BYTES_PER_HKL = 52;
|
||||
constexpr size_t BYTES_PER_OBS = 58, BYTES_PER_EVENT = 30, BYTES_PER_HKL = 86;
|
||||
const auto events = static_cast<size_t>(resident_ingest ? rocking_events_at_ingest : n_partials_obs);
|
||||
const size_t bytes = BYTES_PER_OBS * static_cast<size_t>(n_partials_obs) + BYTES_PER_EVENT * events
|
||||
+ BYTES_PER_HKL * rawrun_start.size();
|
||||
// The resident ingest's own peak comes before any of that, over every reflection read and every run
|
||||
// before the resolution cut, measured on the same engines. Beside the observation arrays and the
|
||||
// integrated delta_phi (58 bytes), each radix sort holds two pairs of keys and values, 82 bytes per
|
||||
// reflection in all; the cut (IngestSort) of the runs 74 per reflection and 56 per run, that of the
|
||||
// observations after it 89 per reflection and 24 per run kept. The upload before them holds the
|
||||
// observation arrays, the sort key and delta_phi (66 bytes) and the two 64 MB staging buffers.
|
||||
constexpr size_t INGEST_BYTES_PER_REFLECTION = 89, INGEST_BYTES_PER_RUN = 56;
|
||||
constexpr size_t INGEST_ARRAY_BYTES = 66, INGEST_STAGING_BYTES = size_t(160) << 20;
|
||||
const size_t ingest = std::max(INGEST_BYTES_PER_REFLECTION * ingest_reflections + INGEST_BYTES_PER_RUN * ingest_runs,
|
||||
INGEST_ARRAY_BYTES * ingest_reflections + INGEST_STAGING_BYTES);
|
||||
// The resident ingest's own peak, over every reflection read and every run before the resolution
|
||||
// cut, measured on the same engines: the observations taken from the reflections hold the
|
||||
// observation arrays, the place the cut gave each reflection and the runs it kept, 60 to 72 bytes
|
||||
// per reflection; the sort and the cut before them 32 per reflection and 56 per run. The two 64 MB
|
||||
// staging buffers beside either.
|
||||
constexpr size_t INGEST_BYTES_PER_REFLECTION = 60, INGEST_BYTES_PER_RUN = 42;
|
||||
constexpr size_t INGEST_STAGING_BYTES = size_t(160) << 20;
|
||||
const size_t ingest = INGEST_BYTES_PER_REFLECTION * ingest_reflections + INGEST_BYTES_PER_RUN * ingest_runs
|
||||
+ INGEST_STAGING_BYTES;
|
||||
return std::max(bytes + bytes / 5, ingest);
|
||||
}
|
||||
|
||||
@@ -798,7 +823,7 @@ void RotationScaleMerge::IngestDevice(const RotationScaleMerge *observations_fro
|
||||
using F = RotationScaleMergeGPU::ObsField;
|
||||
constexpr int STAGE_SLICE = 8 << 20;
|
||||
const int slice = std::min(std::max(n, 1), STAGE_SLICE);
|
||||
constexpr int NFLOAT = 12;
|
||||
constexpr int NFLOAT = 10;
|
||||
std::unique_ptr<float[]> fbuf[NFLOAT];
|
||||
for (auto &b : fbuf) b.reset(new float[slice]);
|
||||
std::unique_ptr<int32_t[]> frm(new int32_t[slice]);
|
||||
@@ -811,19 +836,25 @@ void RotationScaleMerge::IngestDevice(const RotationScaleMerge *observations_fro
|
||||
fbuf[0][i] = o.I; fbuf[1][i] = o.sigma; fbuf[2][i] = o.prescaling_corr;
|
||||
fbuf[3][i] = o.partiality; fbuf[4][i] = o.zeta; fbuf[5][i] = o.corr;
|
||||
fbuf[6][i] = o.bkg; fbuf[7][i] = o.var_bkg; fbuf[8][i] = o.image_number;
|
||||
fbuf[9][i] = o.d; fbuf[10][i] = o.px; fbuf[11][i] = o.py;
|
||||
fbuf[9][i] = o.d;
|
||||
frm[i] = o.frame; onice[i] = o.on_ice; clip[i] = o.clipped;
|
||||
}
|
||||
});
|
||||
constexpr F fields[NFLOAT] = {F::I, F::Sigma, F::PrescalingCorr, F::Partiality,
|
||||
F::Zeta, F::Corr0, F::Bkg, F::VarBkg, F::ImageNumber,
|
||||
F::D, F::Px, F::Py};
|
||||
F::D};
|
||||
for (int k = 0; k < NFLOAT; ++k)
|
||||
gpu_->SetObsField(fields[k], at, cnt, fbuf[k].get());
|
||||
gpu_->SetObsFrame(at, cnt, frm.get());
|
||||
gpu_->SetObsOnIce(at, cnt, onice.get());
|
||||
gpu_->SetObsClipped(at, cnt, clip.get());
|
||||
}
|
||||
auto pos = std::make_shared<ObsPosition>();
|
||||
pos->px.resize(n); pos->py.resize(n);
|
||||
ParallelChunks(n, nthreads, [&](int lo, int hi) {
|
||||
for (int i = lo; i < hi; ++i) { pos->px[i] = partials[i].px; pos->py[i] = partials[i].py; }
|
||||
});
|
||||
obs_position = std::move(pos);
|
||||
gpu_->SetRawRuns(static_cast<int>(rawrun_start.size()), static_cast<int>(perm.size()), perm.data(),
|
||||
rawrun_start.data(), rawrun_count.data(),
|
||||
rawrun_h.data(), rawrun_k.data(), rawrun_l.data());
|
||||
@@ -1526,26 +1557,6 @@ int RotationScaleMerge::ComputeAsuGroups(const HKLKeyGenerator &keygen) {
|
||||
return n_groups;
|
||||
}
|
||||
|
||||
void RotationScaleMerge::ReduceFullGroupMeans(int n_groups, std::vector<double> &out_mean) const {
|
||||
// Inverse-variance per-group mean of I*corr = the merge reference (no cell mask: the scaling
|
||||
// reference is built without a reference cell - only the final merge applies it). A group per task
|
||||
// over the group CSR, each summed over its fulls in index order, as the serial walk summed it.
|
||||
out_mean.assign(n_groups, NAN);
|
||||
ParallelBlocks(n_groups, nthreads, [&](int, int glo, int ghi) {
|
||||
for (int g = glo; g < ghi; ++g) {
|
||||
double sw = 0.0, swI = 0.0;
|
||||
for (int p = fulls_group_start[g]; p < fulls_group_start[g + 1]; ++p) {
|
||||
float I_corr = 0.0f;
|
||||
const double w = ReferenceWeight(fulls[fulls_group_perm[p]], min_partiality, I_corr);
|
||||
if (w <= 0.0) continue;
|
||||
sw += w;
|
||||
swI += w * I_corr;
|
||||
}
|
||||
if (sw > 0.0) out_mean[g] = swI / sw;
|
||||
}
|
||||
}, 512);
|
||||
}
|
||||
|
||||
void RotationScaleMerge::ReducePartialGroupMeans(int n_groups, std::vector<double> &out_mean) const {
|
||||
out_mean.assign(n_groups, NAN);
|
||||
ParallelChunks(n_groups, ThreadsForWork(partials.size(), nthreads), [&](int glo, int ghi) {
|
||||
@@ -1564,14 +1575,15 @@ void RotationScaleMerge::ReducePartialGroupMeans(int n_groups, std::vector<doubl
|
||||
});
|
||||
}
|
||||
|
||||
void RotationScaleMerge::ReduceScalingGroupMeans(int n_groups, const std::vector<ScalingRef> &refs,
|
||||
void RotationScaleMerge::ReduceScalingGroupMeans(int n_groups, const int32_t *group_start,
|
||||
const int32_t *group_count, const std::vector<ScalingRef> &refs,
|
||||
const std::vector<float> &corr,
|
||||
std::vector<double> &out_mean) const {
|
||||
out_mean.resize(n_groups);
|
||||
ParallelChunks(n_groups, ThreadsForWork(corr.size(), nthreads), [&](int glo, int ghi) {
|
||||
for (int g = glo; g < ghi; ++g) {
|
||||
double sw = 0.0, swI = 0.0;
|
||||
const int lo = partial_group_start[g], hi = lo + partial_group_count[g];
|
||||
const int lo = group_start[g], hi = lo + group_count[g];
|
||||
for (int p = lo; p < hi; ++p) {
|
||||
const ScalingRef &r = refs[p];
|
||||
float I_corr = 0.0f;
|
||||
@@ -1660,26 +1672,17 @@ double RotationScaleMerge::ChooseLogScaleSmoothing(const std::vector<double> &y,
|
||||
return best_lambda;
|
||||
}
|
||||
|
||||
template <class O>
|
||||
void RotationScaleMerge::FitPerFrameG(const std::vector<O> &obs, const std::vector<int32_t> &fstart,
|
||||
const std::vector<int32_t> &fcount,
|
||||
const std::vector<double> &group_mean_in,
|
||||
bool unity, std::vector<double> &g) {
|
||||
std::vector<uint8_t> scaled(fstart.size(), 0);
|
||||
std::vector<double> info(fstart.size(), 0.0);
|
||||
const int n_fr = static_cast<int>(fstart.size());
|
||||
void RotationScaleMerge::FitScalingFrames(const std::vector<ScalingFit> &fit, const std::vector<int32_t> &fit_start,
|
||||
size_t min_obs, const std::vector<double> &group_mean_in,
|
||||
std::vector<double> &g) {
|
||||
const int n_fr = static_cast<int>(fit_start.size()) - 1;
|
||||
std::vector<uint8_t> scaled(n_fr, 0);
|
||||
std::vector<double> info(n_fr, 0.0);
|
||||
ParallelFor(n_fr, nthreads, [&](int f) {
|
||||
std::vector<ScaleObs> so;
|
||||
so.reserve(fcount[f]); // grown one by one, every thread queued on the heap's lock
|
||||
for (int i = fstart[f]; i < fstart[f] + fcount[f]; ++i) {
|
||||
const auto &o = obs[i];
|
||||
if (o.group < 0) continue;
|
||||
if (o.on_ice) continue;
|
||||
// Only the observations the reference is built from (ReduceGroupMeans' partiality floor):
|
||||
// on a fine-sliced sweep half of the partials are rocking-curve tails below it, measured
|
||||
// at I/sigma ~ 0.1, and a frame's scale fitted on them is fitted on noise that the
|
||||
// reference does not answer to.
|
||||
if (o.partiality < min_partiality) continue;
|
||||
double num = 0.0, den = 0.0;
|
||||
size_t n = 0;
|
||||
for (int i = fit_start[f]; i < fit_start[f + 1]; ++i) {
|
||||
const ScalingFit &o = fit[i];
|
||||
// The reference is the group's mean WITH this observation in it. Without it the update is
|
||||
// an undamped Jacobi step on the sparse graph a P1 merge of a short sweep is, and it
|
||||
// oscillates (measured: the gauge alternating 0.56 and 1.39 every other iteration on the
|
||||
@@ -1689,46 +1692,12 @@ void RotationScaleMerge::FitPerFrameG(const std::vector<O> &obs, const std::vect
|
||||
// iterations, which is what RunScalingLoop's tolerance is for.
|
||||
const double mean = group_mean_in[o.group];
|
||||
if (!std::isfinite(mean)) continue;
|
||||
double coeff;
|
||||
if (unity) {
|
||||
coeff = mean; // partiality already folded into the full, prescaling_corr = 1
|
||||
} else {
|
||||
if (!(std::isfinite(o.zeta) && o.zeta > 0.0f)) continue; // Rotation model needs zeta > 0
|
||||
coeff = o.partiality * SafeInv(o.prescaling_corr, 1.0) * mean;
|
||||
}
|
||||
so.push_back({coeff, static_cast<double>(o.I), SafeInv(o.sigma, 1.0)});
|
||||
}
|
||||
// A partial frame needs MIN_REFLECTIONS of its own (corr is left untouched otherwise, as
|
||||
// ScaleOnTheFly does). A full is a whole rocking event filed under one frame, so on a sparse
|
||||
// sweep a frame holds a handful; its fit goes in at the information it has, and the smoothing
|
||||
// in RunFullsScalingLoop decides how far its neighbours carry it.
|
||||
if (so.empty() || (!unity && so.size() < MIN_REFLECTIONS)) return;
|
||||
g[f] = SolveScale(so, info[f]);
|
||||
scaled[f] = 1;
|
||||
});
|
||||
// Remember which frames were fitted this call (so the caller updates corr only there).
|
||||
frame_scaled_scratch = std::move(scaled);
|
||||
frame_info_scratch = std::move(info);
|
||||
}
|
||||
|
||||
void RotationScaleMerge::FitScalingFrames(const std::vector<ScalingFit> &fit, const std::vector<int32_t> &fit_start,
|
||||
const std::vector<double> &group_mean_in, std::vector<double> &g) {
|
||||
const int n_fr = static_cast<int>(fit_start.size()) - 1;
|
||||
std::vector<uint8_t> scaled(n_fr, 0);
|
||||
std::vector<double> info(n_fr, 0.0);
|
||||
ParallelFor(n_fr, nthreads, [&](int f) {
|
||||
double num = 0.0, den = 0.0;
|
||||
size_t n = 0;
|
||||
for (int i = fit_start[f]; i < fit_start[f + 1]; ++i) {
|
||||
const ScalingFit &o = fit[i];
|
||||
const double mean = group_mean_in[o.group];
|
||||
if (!std::isfinite(mean)) continue;
|
||||
const double coeff = o.coeff_per_mean * mean;
|
||||
num += o.w2 * coeff * o.Iobs;
|
||||
den += o.w2 * coeff * coeff;
|
||||
++n;
|
||||
}
|
||||
if (n < MIN_REFLECTIONS) return;
|
||||
if (n < min_obs) return;
|
||||
g[f] = ScaleFromSums(num, den, info[f]);
|
||||
scaled[f] = 1;
|
||||
});
|
||||
@@ -4001,7 +3970,7 @@ void RotationScaleMerge::ApplyCellSurface(const std::vector<int32_t> &cell, int
|
||||
// sits on the detector, so with Is as the regressor the bias is a smooth radial ramp - which
|
||||
// the gauge fix spreads over the whole surface and the n_iter rounds compound, and which no
|
||||
// even/odd cross-validation can see because both halves carry it equally. The per-frame
|
||||
// scale (FitPerFrameG) already regresses this way round.
|
||||
// scale (FitScalingFrames) already regresses this way round.
|
||||
// A NEGATIVE observation is a legitimate measurement of a weak reflection and enters both
|
||||
// sums as it stands. Both are linear in Is - there is no logarithm and no division by it
|
||||
// here, unlike the relative-B fits above, which regress log(Iref/Is) and do need Is > 0 -
|
||||
@@ -4389,11 +4358,27 @@ void RotationScaleMerge::Combine() {
|
||||
fulls.clear();
|
||||
g_full.assign(n_frames, 1.0);
|
||||
fulls_dropped_overloaded = 0;
|
||||
const int n_run = static_cast<int>(rawrun_start.size());
|
||||
|
||||
// A raw hkl's partials lie a frame apart in memory, and the work on one rocking event is long
|
||||
// enough that the CPU does not reach the next runs' loads on its own - the combine waited on a
|
||||
// cache miss for nearly every partial. So each run asks for the partials of the run
|
||||
// COMBINE_PREFETCH_RUNS ahead.
|
||||
constexpr int COMBINE_PREFETCH_RUNS = 8;
|
||||
auto prefetch_run = [&](int r) {
|
||||
if (r >= n_run) return;
|
||||
for (int p = rawrun_start[r]; p < rawrun_start[r] + rawrun_count[r]; ++p) {
|
||||
const char *o = reinterpret_cast<const char *>(&partials[perm[p]]);
|
||||
Prefetch(o);
|
||||
Prefetch(o + sizeof(Obs) - 1);
|
||||
}
|
||||
};
|
||||
|
||||
// Combine one raw-hkl run into fulls, appended to `out`. Independent per run (the events of one hkl
|
||||
// touch no shared state), so runs parallelise cleanly. Returns the number of usable partials seen.
|
||||
// `dump` (serial path only) writes each emitted full for the diagnostic observation dump.
|
||||
auto process_rawrun = [&](int r, std::vector<Obs> &out, std::ofstream *dump, int64_t &n_overloaded) -> size_t {
|
||||
prefetch_run(r + COMBINE_PREFETCH_RUNS);
|
||||
const int lo = rawrun_start[r], hi = rawrun_start[r] + rawrun_count[r];
|
||||
std::vector<int32_t> ev; // usable perm-indices of this raw hkl, in image-number order
|
||||
ev.reserve(hi - lo);
|
||||
@@ -4531,7 +4516,6 @@ void RotationScaleMerge::Combine() {
|
||||
return ev.size();
|
||||
};
|
||||
|
||||
const int n_run = static_cast<int>(rawrun_start.size());
|
||||
size_t n_used = 0;
|
||||
|
||||
if (!observation_dump_path.empty() || nthreads <= 1) {
|
||||
@@ -6453,7 +6437,11 @@ RotationScaleMerge::Result RotationScaleMerge::RunArm(bool scale_partials, bool
|
||||
}
|
||||
});
|
||||
|
||||
// FitPerFrameG's filters, all but the reference mean's, frame by frame.
|
||||
// The observations a frame's scale is fitted on, frame by frame. Only those the reference
|
||||
// is built from (ReferenceWeight's partiality floor): on a fine-sliced sweep half of the
|
||||
// partials are rocking-curve tails below it, measured at I/sigma ~ 0.1, and a frame's scale
|
||||
// fitted on them is fitted on noise that the reference does not answer to. The Rotation
|
||||
// model needs zeta > 0.
|
||||
auto fitted_obs = [&](const Obs &o) {
|
||||
return o.group >= 0 && !o.on_ice && o.partiality >= min_partiality
|
||||
&& std::isfinite(o.zeta) && o.zeta > 0.0f;
|
||||
@@ -6485,8 +6473,9 @@ RotationScaleMerge::Result RotationScaleMerge::RunArm(bool scale_partials, bool
|
||||
std::vector<uint8_t> frame_fitted;
|
||||
partial_loop = RunScalingLoop("partials", g_partial, frame_count, smooth_window,
|
||||
[&] {
|
||||
ReduceScalingGroupMeans(n_groups, scaling_refs, scaling_corr, partial_mean);
|
||||
FitScalingFrames(scaling_fit, fit_start, partial_mean, g_partial);
|
||||
ReduceScalingGroupMeans(n_groups, partial_group_start.data(), partial_group_count.data(),
|
||||
scaling_refs, scaling_corr, partial_mean);
|
||||
FitScalingFrames(scaling_fit, fit_start, MIN_REFLECTIONS, partial_mean, g_partial);
|
||||
g_fitted = g_partial;
|
||||
frame_fitted = frame_scaled_scratch;
|
||||
}, [&](const std::vector<uint8_t> &apply, const std::vector<double> &ratio) {
|
||||
@@ -6747,23 +6736,24 @@ RotationScaleMerge::Result RotationScaleMerge::RunArm(bool scale_partials, bool
|
||||
fulls.resize(nf);
|
||||
FullsStaging &st = fulls_staging;
|
||||
st.Resize(nf);
|
||||
gpu_->GetFulls(st.h.data(), st.k.data(), st.l.data(), st.I.data(), st.sigma.data(), st.d.data(),
|
||||
gpu_->GetFulls(st.run.data(), st.I.data(), st.sigma.data(), st.d.data(),
|
||||
st.image_number.data(), st.frame.data(), st.on_ice.data(), st.clipped.data(),
|
||||
st.group.data());
|
||||
gpu_->GetFullsPxPy(st.px.data(), st.py.data());
|
||||
gpu_->GetFullsPeak(st.peak.data());
|
||||
const ObsPosition &pos = *obs_position;
|
||||
gpu_->GetFullsVariance(st.var_bkg.data(), st.var_per_I.data(), st.capture.data());
|
||||
if (scaled_fulls_on_gpu) gpu_->GetFullsCorr(st.corr.data());
|
||||
gpu_->FullsDownloaded();
|
||||
ParallelChunks(nf, ThreadsForWork(nf, nthreads), [&](int lo, int hi) {
|
||||
for (int i = lo; i < hi; ++i) {
|
||||
Obs &o = fulls[i];
|
||||
o.h = st.h[i]; o.k = st.k[i]; o.l = st.l[i];
|
||||
o.h = rawrun_h[st.run[i]]; o.k = rawrun_k[st.run[i]]; o.l = rawrun_l[st.run[i]];
|
||||
o.I = st.I[i]; o.sigma = st.sigma[i]; o.d = st.d[i];
|
||||
o.var_bkg = st.var_bkg[i]; o.var_per_I = st.var_per_I[i]; o.capture = st.capture[i];
|
||||
o.prescaling_corr = 1.0f; o.partiality = 1.0f;
|
||||
o.corr = scaled_fulls_on_gpu ? st.corr[i] : 1.0f;
|
||||
o.image_number = st.image_number[i]; o.frame = st.frame[i];
|
||||
o.px = st.px[i]; o.py = st.py[i];
|
||||
o.px = pos.px[st.peak[i]]; o.py = pos.py[st.peak[i]];
|
||||
o.on_ice = st.on_ice[i]; o.clipped = st.clipped[i]; o.group = st.group[i];
|
||||
// A full has no rocking geometry of its own and carries no background; the combine on
|
||||
// the device does not produce these, and a reused buffer would keep the last chain's.
|
||||
@@ -6794,20 +6784,66 @@ RotationScaleMerge::Result RotationScaleMerge::RunArm(bool scale_partials, bool
|
||||
|
||||
// --- 4. Scale the fulls (XDS order, Unity model). ---
|
||||
if (scale_fulls && !scaled_fulls_on_gpu) {
|
||||
// On a working copy of the fulls, as the partials' loop (ScalingRef and ScalingFit in the header):
|
||||
// full_index[q] is the full at position q, in the group CSR's order and then the fulls in no group.
|
||||
const int nf = static_cast<int>(fulls.size());
|
||||
const size_t full_threads = ThreadsForWork(fulls.size(), nthreads);
|
||||
std::vector<int32_t> full_index(fulls_group_perm.begin(), fulls_group_perm.end());
|
||||
for (int i = 0; i < nf; ++i)
|
||||
if (fulls[i].group < 0) full_index.push_back(i);
|
||||
std::vector<ScalingRef> full_refs(nf);
|
||||
std::vector<float> full_corr(nf);
|
||||
ParallelChunks(nf, full_threads, [&](int lo, int hi) {
|
||||
for (int q = lo; q < hi; ++q) {
|
||||
const Obs &o = fulls[full_index[q]];
|
||||
full_refs[q] = {o.frame, o.I, o.sigma, o.partiality, o.prescaling_corr};
|
||||
full_corr[q] = o.corr;
|
||||
}
|
||||
});
|
||||
std::vector<int32_t> full_group_count(n_groups);
|
||||
for (int g = 0; g < n_groups; ++g)
|
||||
full_group_count[g] = fulls_group_start[g + 1] - fulls_group_start[g];
|
||||
// The partials' filters for the Unity model, which needs no zeta, and whose coefficient is the
|
||||
// mean itself: the partiality is folded into the full, and prescaling_corr is 1.
|
||||
auto fitted_full = [&](const Obs &o) {
|
||||
return o.group >= 0 && !o.on_ice && o.partiality >= min_partiality;
|
||||
};
|
||||
std::vector<int32_t> fit_start(n_frames + 1, 0);
|
||||
ParallelFor(n_frames, nthreads, [&](int f) {
|
||||
fit_start[f + 1] = static_cast<int32_t>(std::count_if(
|
||||
fulls.begin() + fulls_frame_start[f],
|
||||
fulls.begin() + fulls_frame_start[f] + fulls_frame_count[f], fitted_full));
|
||||
});
|
||||
for (int f = 0; f < n_frames; ++f) fit_start[f + 1] += fit_start[f];
|
||||
std::vector<ScalingFit> full_fit(fit_start.back());
|
||||
ParallelFor(n_frames, nthreads, [&](int f) {
|
||||
int32_t k = fit_start[f];
|
||||
for (int i = fulls_frame_start[f]; i < fulls_frame_start[f] + fulls_frame_count[f]; ++i) {
|
||||
const Obs &o = fulls[i];
|
||||
if (!fitted_full(o)) continue;
|
||||
const double weight = SafeInv(o.sigma, 1.0);
|
||||
full_fit[k++] = {o.group, 1.0, static_cast<double>(o.I), weight * weight};
|
||||
}
|
||||
});
|
||||
|
||||
std::vector<double> full_mean, g_fit(n_frames);
|
||||
fulls_loop = RunFullsScalingLoop(g_full, g_fit, fulls_frame_count, [&] {
|
||||
ReduceFullGroupMeans(n_groups, full_mean);
|
||||
FitPerFrameG(fulls, fulls_frame_start, fulls_frame_count, full_mean, /*unity=*/true, g_fit);
|
||||
ReduceScalingGroupMeans(n_groups, fulls_group_start.data(), full_group_count.data(), full_refs,
|
||||
full_corr, full_mean);
|
||||
FitScalingFrames(full_fit, fit_start, 1, full_mean, g_fit);
|
||||
}, [&](const std::vector<uint8_t> &apply, const std::vector<double> &ratio) {
|
||||
ParallelChunks(static_cast<int>(fulls.size()), ThreadsForWork(fulls.size(), nthreads),
|
||||
[&](int lo, int hi) {
|
||||
for (int i = lo; i < hi; ++i) {
|
||||
Obs &o = fulls[i];
|
||||
if (apply[o.frame] && std::isfinite(o.corr))
|
||||
o.corr = static_cast<float>(o.corr * ratio[o.frame]);
|
||||
ParallelChunks(nf, full_threads, [&](int lo, int hi) {
|
||||
for (int q = lo; q < hi; ++q) {
|
||||
float &corr = full_corr[q];
|
||||
const int f = full_refs[q].frame;
|
||||
if (apply[f] && std::isfinite(corr))
|
||||
corr = static_cast<float>(corr * ratio[f]);
|
||||
}
|
||||
});
|
||||
});
|
||||
ParallelChunks(nf, full_threads, [&](int lo, int hi) {
|
||||
for (int q = lo; q < hi; ++q) fulls[full_index[q]].corr = full_corr[q];
|
||||
});
|
||||
logger->Info("Scaled fulls (XDS order, Unity model)");
|
||||
}
|
||||
// The total scale each frame's fulls were amplified by - partial scale, incident flux and the fulls'
|
||||
|
||||
@@ -173,8 +173,8 @@ public:
|
||||
// card. Call after IngestHost(). It counts what the ingest knows - the observations, the rocking
|
||||
// events (the combine makes at most one full of each) and the distinct hkl (at most one ASU group
|
||||
// each) - at what each costs at the engine's peak (the correction-surface terms, or the merge with
|
||||
// its outlier test), plus a fifth. Measured on 11 data sets of 13-123 M observations, every
|
||||
// engine's peak was at most 81% of this. Where the ingest on the card peaks higher, its peak.
|
||||
// its outlier test), plus a fifth. Measured on 14 engines of 23-123 M observations, every engine's
|
||||
// peak was at most 88% of this. Where the ingest on the card peaks higher, its peak.
|
||||
// Call after IngestDevice().
|
||||
[[nodiscard]] size_t DeviceBytes() const;
|
||||
// The device scaling's estimated peak (see the .cpp). Call after the ingest.
|
||||
@@ -370,6 +370,10 @@ private:
|
||||
bool partials_released = false;
|
||||
int rocking_event_frames_at_ingest = 0;
|
||||
int64_t rocking_events_at_ingest = 0;
|
||||
// Each partial's predicted detector position, for the fulls the device path combines (GetFullsPeak):
|
||||
// only the host reads it, so the card does not hold it. Shared by the engines CloneIngest makes.
|
||||
struct ObsPosition { std::vector<float> px, py; };
|
||||
std::shared_ptr<const ObsPosition> obs_position;
|
||||
// The reflections and raw-hkl runs the resident ingest read before the resolution cut (DeviceBytes).
|
||||
size_t ingest_reflections = 0, ingest_runs = 0;
|
||||
std::vector<int32_t> frame_start, frame_count; // CSR ranges of `partials` per frame
|
||||
@@ -446,13 +450,13 @@ private:
|
||||
// scale->combine->merge chain runs several times per run and these are a few hundred megabytes
|
||||
// between them, so as locals every chain allocates, faults in and zeroes the lot again.
|
||||
struct FullsStaging {
|
||||
std::vector<int32_t> h, k, l, frame, group;
|
||||
std::vector<float> I, sigma, d, image_number, corr, px, py, var_bkg, var_per_I, capture;
|
||||
std::vector<int32_t> run, peak, frame, group;
|
||||
std::vector<float> I, sigma, d, image_number, corr, var_bkg, var_per_I, capture;
|
||||
std::vector<uint8_t> on_ice, clipped;
|
||||
void Resize(int n) {
|
||||
h.resize(n); k.resize(n); l.resize(n); frame.resize(n); group.resize(n);
|
||||
run.resize(n); peak.resize(n); frame.resize(n); group.resize(n);
|
||||
I.resize(n); sigma.resize(n); d.resize(n); image_number.resize(n); corr.resize(n);
|
||||
px.resize(n); py.resize(n); var_bkg.resize(n); var_per_I.resize(n); capture.resize(n);
|
||||
var_bkg.resize(n); var_per_I.resize(n); capture.resize(n);
|
||||
on_ice.resize(n); clipped.resize(n);
|
||||
}
|
||||
};
|
||||
@@ -514,7 +518,7 @@ private:
|
||||
std::vector<ErrorModelBinned> em_fit_pool;
|
||||
std::vector<double> em_chi2;
|
||||
|
||||
// Set by FitPerFrameG: which frames were fitted this call (so corr/G is updated only there), and
|
||||
// Set by FitScalingFrames: which frames were fitted this call (so corr/G is updated only there), and
|
||||
// the information each fit had on G, sum w^2 c^2 (0 where the frame was not fitted).
|
||||
std::vector<uint8_t> frame_scaled_scratch;
|
||||
std::vector<double> frame_info_scratch;
|
||||
@@ -605,6 +609,10 @@ private:
|
||||
// Where the scaling's estimated peak is over CPU_SCALING_ABOVE_CARD_FRACTION of the card: says so,
|
||||
// gives the device up (scale_on_cpu_) and returns true. Call once the ingest has counted.
|
||||
bool ScaleOnCPUWhereTooLarge();
|
||||
// The same for the ingest's sort of n_reflections, decided before anything is on the card.
|
||||
bool ScaleOnCPUWhereSortTooLarge(size_t n_reflections);
|
||||
// What the rule above says for `bytes` of the card, `what` naming the work in the warning.
|
||||
bool ScaleOnCPUWhereOverCard(size_t bytes, const std::string &what);
|
||||
#endif
|
||||
|
||||
// Compute the dense ASU-group id for the current space group by grouping the (pre-sorted) raw-hkl
|
||||
@@ -617,12 +625,12 @@ private:
|
||||
std::vector<int32_t> partial_group_start, partial_group_count;
|
||||
NotCopied<int32_t[]> partial_group_perm;
|
||||
|
||||
// The CPU partial scaling loop's working copy of the partials. It passes over them several times
|
||||
// per iteration and reads a handful of fields each time, so it works on these rather than on the
|
||||
// eighty-byte Obs. ScalingRef holds what the group means and the corr update read, in the CSR's
|
||||
// The CPU scaling loops' working copy of the partials, or of the fulls. A loop passes over them
|
||||
// several times per iteration and reads a handful of fields each time, so it works on these rather
|
||||
// than on the eighty-byte Obs. ScalingRef holds what the group means and the corr update read, in the CSR's
|
||||
// group order with the partials in no group after them, and corr is kept beside it in the same
|
||||
// order - so neither pass gathers. ScalingFit holds, frame by frame, the observations
|
||||
// FitScalingFrames fits: FitPerFrameG's filters, which do not change over the loop, applied once,
|
||||
// FitScalingFrames fits: the fit's filters, which do not change over the loop, applied once,
|
||||
// and the factors of its sums that do not depend on the reference worked out once. The same
|
||||
// values, so the same arithmetic in the same order.
|
||||
struct ScalingRef {
|
||||
@@ -631,7 +639,7 @@ private:
|
||||
};
|
||||
struct ScalingFit {
|
||||
int32_t group;
|
||||
double coeff_per_mean; // partiality / prescaling_corr: FitPerFrameG's coeff for a mean of 1
|
||||
double coeff_per_mean; // partiality / prescaling_corr (1 for a full): the fit's coeff for a mean of 1
|
||||
double Iobs, w2;
|
||||
};
|
||||
|
||||
@@ -651,25 +659,23 @@ private:
|
||||
static double ReferenceWeight(const Obs &o, double min_partiality, float &I_corr) {
|
||||
return ReferenceWeight(o.group, o.corr, o.partiality, o.I, o.sigma, min_partiality, I_corr);
|
||||
}
|
||||
// Inverse-variance per-group mean of I*corr over the fulls (the merge reference), by the fulls'
|
||||
// group CSR, so each group is summed in index order.
|
||||
void ReduceFullGroupMeans(int n_groups, std::vector<double> &out_mean) const;
|
||||
// The same over the partials, using the CSR above - the same sums in the same order.
|
||||
// Inverse-variance per-group mean of I*corr over the partials (the scaling reference; no cell mask -
|
||||
// only the final merge applies one), using the CSR above, each group summed in index order.
|
||||
void ReducePartialGroupMeans(int n_groups, std::vector<double> &out_mean) const;
|
||||
// The same again over the scaling loop's copy, refs and corr both in group order.
|
||||
void ReduceScalingGroupMeans(int n_groups, const std::vector<ScalingRef> &refs,
|
||||
const std::vector<float> &corr, std::vector<double> &out_mean) const;
|
||||
// The same again over a scaling loop's copy, refs and corr both in group order: group g's at
|
||||
// [group_start[g], group_start[g] + group_count[g]).
|
||||
void ReduceScalingGroupMeans(int n_groups, const int32_t *group_start, const int32_t *group_count,
|
||||
const std::vector<ScalingRef> &refs, const std::vector<float> &corr,
|
||||
std::vector<double> &out_mean) const;
|
||||
|
||||
// Robust per-frame G fit (IRLS, Cauchy k=3), unity=false uses the rotation partiality, unity=true the
|
||||
// scale-fulls (partiality already folded in). Reads out_mean[group] as the reference intensity.
|
||||
template <class O>
|
||||
void FitPerFrameG(const std::vector<O> &obs, const std::vector<int32_t> &fstart,
|
||||
const std::vector<int32_t> &fcount, const std::vector<double> &group_mean_in,
|
||||
bool unity, std::vector<double> &g);
|
||||
// FitPerFrameG(unity = false) over the scaling loop's ScalingFit, frame f's at
|
||||
// [fit_start[f], fit_start[f + 1]).
|
||||
// Per-frame G fit against the reference group_mean_in[group], over a scaling loop's ScalingFit, frame
|
||||
// f's at [fit_start[f], fit_start[f + 1]). A frame with fewer than min_obs of them keeps its G: a
|
||||
// partial frame needs MIN_REFLECTIONS of its own (as ScaleOnTheFly), while a full is a whole rocking
|
||||
// event filed under one frame, so on a sparse sweep a frame holds a handful - its fit goes in at
|
||||
// the information it has (min_obs 1), and the smoothing in RunFullsScalingLoop decides how far its
|
||||
// neighbours carry it.
|
||||
void FitScalingFrames(const std::vector<ScalingFit> &fit, const std::vector<int32_t> &fit_start,
|
||||
const std::vector<double> &group_mean_in, std::vector<double> &g);
|
||||
size_t min_obs, const std::vector<double> &group_mean_in, std::vector<double> &g);
|
||||
|
||||
// The alternating per-frame scale fit run to convergence: `iterate` fits every frame once against
|
||||
// the current reference (leaving G in `g` and the frames it fitted in frame_scaled_scratch),
|
||||
|
||||
@@ -102,7 +102,7 @@ namespace {
|
||||
|
||||
// The scale-fit coefficient of an observation (rotation model), recomputed each scaling iteration
|
||||
// once the group means are known: coeff = partiality * (1/prescaling_corr) * mean[group], or false
|
||||
// where the observation is not one the reference is built from (the host FitPerFrameG says why).
|
||||
// where the observation is not one the reference is built from (the host RunArm says why, where it fills ScalingFit).
|
||||
__device__ __forceinline__ bool ScaleCoeff(int i, double min_partiality, const int32_t *__restrict__ group,
|
||||
const ObsRecord &o, const float *__restrict__ zeta,
|
||||
const uint8_t *__restrict__ on_ice,
|
||||
@@ -117,13 +117,13 @@ namespace {
|
||||
}
|
||||
|
||||
// One block per frame: the per-frame scale G as the weighted least-squares slope over the frame's
|
||||
// contiguous obs - the same plain fit as the host SolveScale (which says why it is not robust).
|
||||
// contiguous obs - the same plain fit as the host ScaleFromSums (which says why it is not robust).
|
||||
// Leaves g/scaled untouched for frames with fewer than min_obs usable observations. `perm` (null
|
||||
// for the partials, whose arrays are already frame-contiguous) maps a position in the frame's
|
||||
// [lo,hi) range to the obs index, so the same kernel scales the fulls (emit-ordered) through a
|
||||
// frame-grouping permutation without physically reordering the fulls arrays. info[f] receives the
|
||||
// fit's information on G, sum w^2 c^2 (0 for a frame left alone). The weight is 1/sigma, as the
|
||||
// CPU's ScaleObs::weight.
|
||||
// CPU's ScalingFit::w2 is its square.
|
||||
__global__ void FitPerFrameGKernel(int n_frames,
|
||||
const int32_t *__restrict__ frame_start,
|
||||
const int32_t *__restrict__ frame_count,
|
||||
@@ -294,7 +294,7 @@ namespace {
|
||||
float max_frame_gap;
|
||||
const ObsRecord *__restrict__ obs;
|
||||
const float *__restrict__ corr, *__restrict__ bkg, *__restrict__ var_bkg,
|
||||
*__restrict__ image_number, *__restrict__ d, *__restrict__ px, *__restrict__ py;
|
||||
*__restrict__ image_number, *__restrict__ d;
|
||||
const int32_t *__restrict__ frame;
|
||||
const uint8_t *__restrict__ on_ice, *__restrict__ clipped;
|
||||
const int32_t *__restrict__ perm, *__restrict__ rr_start, *__restrict__ rr_count,
|
||||
@@ -303,8 +303,8 @@ namespace {
|
||||
int32_t *rr_nevents; // count pass output
|
||||
int32_t *rr_noverloaded; // count pass output: events dropped for a saturated pixel
|
||||
const int32_t *rr_offset; // emit pass: per-run base offset into the fulls arrays
|
||||
int32_t *f_h, *f_k, *f_l, *f_frame, *f_group;
|
||||
float *f_I, *f_sigma, *f_d, *f_img, *f_px, *f_py, *f_var_bkg, *f_var_per_I, *f_capture;
|
||||
int32_t *f_run, *f_peak, *f_frame, *f_group;
|
||||
float *f_I, *f_sigma, *f_d, *f_img, *f_var_bkg, *f_var_per_I, *f_capture;
|
||||
uint8_t *f_on_ice, *f_clipped;
|
||||
};
|
||||
|
||||
@@ -363,7 +363,7 @@ namespace {
|
||||
const int first = p.perm[ev_start];
|
||||
int peak_outcome = p.frame[first];
|
||||
float peak_frame = p.image_number[first];
|
||||
float peak_px = p.px[first], peak_py = p.py[first];
|
||||
int peak_obs = first;
|
||||
float peak_partiality = -1.0f;
|
||||
const bool on_ice = p.on_ice[first];
|
||||
uint8_t flags = 0;
|
||||
@@ -383,7 +383,7 @@ namespace {
|
||||
peak_partiality = p.obs[i].partiality;
|
||||
peak_outcome = p.frame[i];
|
||||
peak_frame = p.image_number[i];
|
||||
peak_px = p.px[i]; peak_py = p.py[i];
|
||||
peak_obs = i;
|
||||
}
|
||||
if (!isfinite(d) && isfinite(p.d[i]) && p.d[i] > 0.0f) d = p.d[i];
|
||||
}
|
||||
@@ -432,7 +432,7 @@ namespace {
|
||||
|
||||
if (Emit) {
|
||||
const int o = p.rr_offset[r] + n_emit;
|
||||
p.f_h[o] = p.rr_h[r]; p.f_k[o] = p.rr_k[r]; p.f_l[o] = p.rr_l[r];
|
||||
p.f_run[o] = r;
|
||||
p.f_I[o] = float(F);
|
||||
p.f_sigma[o] = float(sigma_full);
|
||||
p.f_var_bkg[o] = float(var_bkg_full);
|
||||
@@ -440,7 +440,7 @@ namespace {
|
||||
p.f_capture[o] = float(capture);
|
||||
p.f_d[o] = d;
|
||||
p.f_img[o] = peak_frame;
|
||||
p.f_px[o] = peak_px; p.f_py[o] = peak_py;
|
||||
p.f_peak[o] = peak_obs;
|
||||
p.f_frame[o] = peak_outcome;
|
||||
p.f_on_ice[o] = on_ice ? 1 : 0;
|
||||
p.f_clipped[o] = clipped ? 1 : 0;
|
||||
@@ -672,7 +672,7 @@ namespace {
|
||||
double min_partiality, error_model_a, error_model_b, reject_nsigma;
|
||||
double reject_up, reject_down; // the multiplicative part of the outlier band (OutlierBand.h)
|
||||
int for_search, error_model_active, reject_outliers;
|
||||
const float *I, *sigma, *corr, *partiality, *d, *reject_median, *var_bkg, *var_per_I, *capture;
|
||||
const float *I, *sigma, *corr, *d, *reject_median, *var_bkg, *var_per_I, *capture;
|
||||
const float *reject_var_add; // per group: the shell's measured share of dI^2/4
|
||||
const int32_t *group, *frame;
|
||||
const uint8_t *on_ice, *frame_cell_ok, *half;
|
||||
@@ -693,6 +693,9 @@ namespace {
|
||||
uint8_t *rejected_obs; // per-full: set by MergeAccum (outlier-rejected), read by MergeRmeas
|
||||
};
|
||||
|
||||
// A full's partiality: the device merges the fulls it scaled, in the Unity model.
|
||||
constexpr float FULL_PARTIALITY = 1.0f;
|
||||
|
||||
// A full passes the merge / error-model filter (mirrors MergeAndStats::usable_merge).
|
||||
__device__ __forceinline__ bool MergeUsable(int i, const MergeParams &p) {
|
||||
const int g = p.group[i];
|
||||
@@ -701,7 +704,7 @@ namespace {
|
||||
const float c = p.corr[i];
|
||||
if (!(c > 0.0f) || !isfinite(c)) return false;
|
||||
if (p.for_search && p.on_ice[i]) return false;
|
||||
if (p.partiality[i] < p.min_partiality) return false;
|
||||
if (FULL_PARTIALITY < p.min_partiality) return false;
|
||||
const float I_corr = p.I[i] * c, sigma_corr = p.sigma[i] * c;
|
||||
return isfinite(I_corr) && isfinite(sigma_corr) && sigma_corr > 0.0f;
|
||||
}
|
||||
@@ -713,7 +716,7 @@ namespace {
|
||||
if (!p.frame_cell_ok[p.frame[i]]) return false;
|
||||
const float c = p.corr[i];
|
||||
if (!(c > 0.0f) || !isfinite(c)) return false;
|
||||
if (p.partiality[i] < p.min_partiality) return false;
|
||||
if (FULL_PARTIALITY < p.min_partiality) return false;
|
||||
const float I_corr = p.I[i] * c, sigma_corr = p.sigma[i] * c;
|
||||
return isfinite(I_corr) && isfinite(sigma_corr) && sigma_corr > 0.0f;
|
||||
}
|
||||
@@ -838,10 +841,12 @@ namespace {
|
||||
}
|
||||
|
||||
// One thread per full: its observation key, and whether the merge can use it.
|
||||
__global__ void ObservationKeyKernel(int n_obs, MergeParams p, const int32_t *h, const int32_t *k,
|
||||
const int32_t *l, uint64_t *key, uint8_t *usable) {
|
||||
// A full's raw hkl is its run's.
|
||||
__global__ void ObservationKeyKernel(int n_obs, MergeParams p, const int32_t *run, const int32_t *h,
|
||||
const int32_t *k, const int32_t *l, uint64_t *key, uint8_t *usable) {
|
||||
for (int i = blockIdx.x * blockDim.x + threadIdx.x; i < n_obs; i += gridDim.x * blockDim.x) {
|
||||
key[i] = ObservationKeyDevice(h[i], k[i], l[i], p.frame[i]);
|
||||
const int r = run[i];
|
||||
key[i] = ObservationKeyDevice(h[r], k[r], l[r], p.frame[i]);
|
||||
usable[i] = MergeUsable(i, p) ? 1 : 0;
|
||||
}
|
||||
}
|
||||
@@ -1257,19 +1262,20 @@ struct RotationScaleMergeGPU::Impl {
|
||||
int merge_em_active = 0;
|
||||
|
||||
// combine: extra per-obs inputs + the one-time raw-hkl run layout
|
||||
CudaDevicePtr<float> bkg, var_bkg, image_number, d_obs, px_obs, py_obs;
|
||||
CudaDevicePtr<float> bkg, var_bkg, image_number, d_obs;
|
||||
int n_runs = 0, n_perm = 0;
|
||||
CudaDevicePtr<int32_t> perm, rr_start, rr_count, rr_h, rr_k, rr_l;
|
||||
// combine: resident fulls SoA (rebuilt each Combine)
|
||||
int n_fulls = 0;
|
||||
CudaDevicePtr<int32_t> f_h, f_k, f_l, f_frame, f_group;
|
||||
CudaDevicePtr<float> f_I, f_sigma, f_d, f_img, f_px, f_py, f_var_bkg, f_var_per_I, f_capture;
|
||||
// run: the raw-hkl run a full is of; peak: the partial its position is taken from
|
||||
CudaDevicePtr<int32_t> f_run, f_peak, f_frame, f_group;
|
||||
CudaDevicePtr<float> f_I, f_sigma, f_d, f_img, f_var_bkg, f_var_per_I, f_capture;
|
||||
CudaDevicePtr<uint8_t> f_on_ice, f_clipped;
|
||||
// scale-fulls (Unity model, kept resident): all-ones partiality/zeta and records with partiality and
|
||||
// prescaling_corr 1, so the shared scaling kernels yield coeff=mean, plus the working corr and the
|
||||
// fulls frame/group CSRs (built on the host from the small f_frame/f_group key arrays, over the
|
||||
// emit-ordered fulls).
|
||||
CudaDevicePtr<float> f_corr, f_partiality, f_zeta;
|
||||
CudaDevicePtr<float> f_corr, f_zeta;
|
||||
CudaDevicePtr<ObsRecord> f_obs;
|
||||
CudaDevicePtr<int32_t> f_frame_perm, f_frame_start, f_frame_count;
|
||||
CudaDevicePtr<int32_t> f_gperm, f_gstart, f_gcount;
|
||||
@@ -1285,12 +1291,22 @@ struct RotationScaleMergeGPU::Impl {
|
||||
CudaDevicePtr<int32_t> s_perm[3], s_seg_start[3];
|
||||
CudaDevicePtr<double> s_A, s_sw, s_swI, s_tcross, s_tref2, s_cross, s_ref2;
|
||||
CudaDevicePtr<double> s_w_Is, s_w_Iref, s_Iref; // per term of a subset, in segment order
|
||||
// the resident ingest (IngestUpload .. IngestFinish): each frame's first reflection
|
||||
// (host, length n_frames + 1), per observation its raw hkl as the sort key until the sort has used
|
||||
// it, and its delta_phi as integrated until the smoothing has
|
||||
// the resident ingest (IngestUpload .. IngestFinish): each frame's first reflection (host, length
|
||||
// n_frames + 1); per reflection what the sort and the cut read - its raw hkl as the sort key, its
|
||||
// frame position, resolution and background - until they have, and the place the cut gives it (as
|
||||
// an exclusive prefix over the kept ones, n_keep in all) until the observations are taken from the
|
||||
// reflections; per observation its delta_phi as integrated until the smoothing has used it
|
||||
std::vector<int32_t> in_src_start;
|
||||
CudaDevicePtr<uint64_t> in_key;
|
||||
CudaDevicePtr<float> in_img, in_d, in_bkg;
|
||||
CudaDevicePtr<int32_t> in_new_idx;
|
||||
int in_n_keep = 0;
|
||||
CudaDevicePtr<float> in_dphi;
|
||||
// The reflections of the ingest's frames, through two pinned buffers of whole frames, each filled on
|
||||
// all threads while the other is on its way to the card; take(cnt, base, src) takes cnt of them,
|
||||
// the first being reflection base, apart on the card.
|
||||
template <typename Take>
|
||||
void StageReflections(const Reflection *const *refl, const int32_t *count, size_t nthreads, Take take);
|
||||
RotationScaleMergeGPU::IngestLayout in_layout;
|
||||
};
|
||||
|
||||
@@ -1362,7 +1378,6 @@ void RotationScaleMergeGPU::Impl::AllocObservations(int n_in) {
|
||||
zeta = Alloc<float>(n); corr = Alloc<float>(n);
|
||||
bkg = Alloc<float>(n); var_bkg = Alloc<float>(n);
|
||||
image_number = Alloc<float>(n); d_obs = Alloc<float>(n);
|
||||
px_obs = Alloc<float>(n); py_obs = Alloc<float>(n);
|
||||
frame = Alloc<int32_t>(n);
|
||||
on_ice = Alloc<uint8_t>(n);
|
||||
clipped = Alloc<uint8_t>(n);
|
||||
@@ -1386,10 +1401,10 @@ void RotationScaleMergeGPU::Impl::AllocFrames(const int32_t *fstart, const int32
|
||||
|
||||
void RotationScaleMergeGPU::Impl::ReleaseFulls() {
|
||||
n_fulls = 0;
|
||||
f_h = {}; f_k = {}; f_l = {}; f_frame = {}; f_group = {};
|
||||
f_I = {}; f_sigma = {}; f_d = {}; f_img = {}; f_px = {}; f_py = {};
|
||||
f_run = {}; f_peak = {}; f_frame = {}; f_group = {};
|
||||
f_I = {}; f_sigma = {}; f_d = {}; f_img = {};
|
||||
f_var_bkg = {}; f_var_per_I = {}; f_capture = {}; f_on_ice = {}; f_clipped = {};
|
||||
f_corr = {}; f_partiality = {}; f_zeta = {}; f_obs = {};
|
||||
f_corr = {}; f_zeta = {}; f_obs = {};
|
||||
f_frame_perm = {}; f_frame_start = {}; f_frame_count = {};
|
||||
f_gperm = {}; f_gstart = {}; f_gcount = {};
|
||||
m_em_mean = {}; m_hand = {}; m_has_hands = {}; m_rejected = {};
|
||||
@@ -1434,8 +1449,6 @@ void RotationScaleMergeGPU::SetObsField(ObsField f, int offset, int count, const
|
||||
case ObsField::VarBkg: UploadChunk(d.var_bkg, offset, count, v, impl_->s()); break;
|
||||
case ObsField::ImageNumber: UploadChunk(d.image_number, offset, count, v, impl_->s()); break;
|
||||
case ObsField::D: UploadChunk(d.d_obs, offset, count, v, impl_->s()); break;
|
||||
case ObsField::Px: UploadChunk(d.px_obs, offset, count, v, impl_->s()); break;
|
||||
case ObsField::Py: UploadChunk(d.py_obs, offset, count, v, impl_->s()); break;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1457,7 +1470,7 @@ void RotationScaleMergeGPU::CopyObservationsFrom(const RotationScaleMergeGPU &fr
|
||||
const size_t n = d.n_obs;
|
||||
copy(d.obs, f.obs, n); copy(d.zeta, f.zeta, n); copy(d.corr, f.corr, n);
|
||||
copy(d.bkg, f.bkg, n); copy(d.var_bkg, f.var_bkg, n); copy(d.image_number, f.image_number, n);
|
||||
copy(d.d_obs, f.d_obs, n); copy(d.px_obs, f.px_obs, n); copy(d.py_obs, f.py_obs, n);
|
||||
copy(d.d_obs, f.d_obs, n);
|
||||
copy(d.frame, f.frame, n); copy(d.on_ice, f.on_ice, n); copy(d.clipped, f.clipped, n);
|
||||
const size_t nr = std::max(1, d.n_runs);
|
||||
d.perm = d.Alloc<int32_t>(std::max(1, d.n_perm));
|
||||
@@ -1619,7 +1632,7 @@ void RotationScaleMergeGPU::MergeEmSamples(bool for_search, double min_partialit
|
||||
MergeParams p{};
|
||||
p.n_groups = ng; p.min_partiality = min_partiality;
|
||||
p.for_search = d.merge_for_search;
|
||||
p.I = d.f_I.get(); p.sigma = d.f_sigma.get(); p.corr = d.f_corr.get(); p.partiality = d.f_partiality.get();
|
||||
p.I = d.f_I.get(); p.sigma = d.f_sigma.get(); p.corr = d.f_corr.get();
|
||||
p.d = d.f_d.get(); p.group = d.f_group.get(); p.frame = d.f_frame.get();
|
||||
p.on_ice = d.f_on_ice.get(); p.frame_cell_ok = d.frame_cell_ok.get();
|
||||
p.gperm = d.f_gperm.get(); p.gstart = d.f_gstart.get(); p.gcount = d.f_gcount.get();
|
||||
@@ -1702,7 +1715,7 @@ void RotationScaleMergeGPU::MergeAccum(double error_model_a, double error_model_
|
||||
p.reject_down = -std::expm1(-reject_nsigma * reject_mult_sd);
|
||||
p.reject_median = median.get();
|
||||
p.reject_var_add = var_add.get();
|
||||
p.I = d.f_I.get(); p.sigma = d.f_sigma.get(); p.corr = d.f_corr.get(); p.partiality = d.f_partiality.get();
|
||||
p.I = d.f_I.get(); p.sigma = d.f_sigma.get(); p.corr = d.f_corr.get();
|
||||
p.d = d.f_d.get(); p.group = d.f_group.get(); p.frame = d.f_frame.get();
|
||||
p.on_ice = d.f_on_ice.get(); p.frame_cell_ok = d.frame_cell_ok.get();
|
||||
p.half = d_half.get();
|
||||
@@ -1760,7 +1773,7 @@ void RotationScaleMergeGPU::MergeRmeas(const double *merged_I, double *absdev, d
|
||||
|
||||
MergeParams p{};
|
||||
p.n_groups = ng; p.min_partiality = d.merge_min_part;
|
||||
p.I = d.f_I.get(); p.sigma = d.f_sigma.get(); p.corr = d.f_corr.get(); p.partiality = d.f_partiality.get();
|
||||
p.I = d.f_I.get(); p.sigma = d.f_sigma.get(); p.corr = d.f_corr.get();
|
||||
p.d = d.f_d.get(); p.group = d.f_group.get(); p.frame = d.f_frame.get(); p.frame_cell_ok = d.frame_cell_ok.get();
|
||||
p.gperm = d.f_gperm.get(); p.gstart = d.f_gstart.get(); p.gcount = d.f_gcount.get();
|
||||
p.merged_I = d_merged_I.get();
|
||||
@@ -1797,7 +1810,7 @@ void RotationScaleMergeGPU::MergeBijvoetExcess(double error_model_a, double erro
|
||||
|
||||
MergeParams p{};
|
||||
p.n_groups = ng; p.min_partiality = d.merge_min_part; p.for_search = d.merge_for_search;
|
||||
p.I = d.f_I.get(); p.sigma = d.f_sigma.get(); p.corr = d.f_corr.get(); p.partiality = d.f_partiality.get();
|
||||
p.I = d.f_I.get(); p.sigma = d.f_sigma.get(); p.corr = d.f_corr.get();
|
||||
p.d = d.f_d.get(); p.group = d.f_group.get(); p.frame = d.f_frame.get();
|
||||
p.on_ice = d.f_on_ice.get(); p.frame_cell_ok = d.frame_cell_ok.get();
|
||||
p.gperm = d.f_gperm.get(); p.gstart = d.f_gstart.get(); p.gcount = d.f_gcount.get();
|
||||
@@ -1829,7 +1842,7 @@ void RotationScaleMergeGPU::MergeGroupScatter(double *sum, double *sum_sq, doubl
|
||||
|
||||
MergeParams p{};
|
||||
p.n_groups = ng; p.min_partiality = d.merge_min_part; p.for_search = d.merge_for_search;
|
||||
p.I = d.f_I.get(); p.sigma = d.f_sigma.get(); p.corr = d.f_corr.get(); p.partiality = d.f_partiality.get();
|
||||
p.I = d.f_I.get(); p.sigma = d.f_sigma.get(); p.corr = d.f_corr.get();
|
||||
p.d = d.f_d.get(); p.group = d.f_group.get(); p.frame = d.f_frame.get();
|
||||
p.on_ice = d.f_on_ice.get(); p.frame_cell_ok = d.frame_cell_ok.get();
|
||||
p.gperm = d.f_gperm.get(); p.gstart = d.f_gstart.get(); p.gcount = d.f_gcount.get();
|
||||
@@ -1856,15 +1869,15 @@ void RotationScaleMergeGPU::MergeHalves(uint64_t *obs_key, uint8_t *half) {
|
||||
|
||||
MergeParams p{};
|
||||
p.n_groups = ng; p.min_partiality = d.merge_min_part; p.for_search = d.merge_for_search;
|
||||
p.I = d.f_I.get(); p.sigma = d.f_sigma.get(); p.corr = d.f_corr.get(); p.partiality = d.f_partiality.get();
|
||||
p.I = d.f_I.get(); p.sigma = d.f_sigma.get(); p.corr = d.f_corr.get();
|
||||
p.d = d.f_d.get(); p.group = d.f_group.get(); p.frame = d.f_frame.get();
|
||||
p.on_ice = d.f_on_ice.get(); p.frame_cell_ok = d.frame_cell_ok.get();
|
||||
p.gperm = d.f_gperm.get(); p.gstart = d.f_gstart.get(); p.gcount = d.f_gcount.get();
|
||||
|
||||
const int obs_blocks = std::min(65535, (nf + BLK - 1) / BLK);
|
||||
const int grp_blocks = std::min(65535, (ng + BLK - 1) / BLK);
|
||||
ObservationKeyKernel<<<obs_blocks, BLK, 0, impl_->s()>>>(nf, p, d.f_h.get(), d.f_k.get(), d.f_l.get(), key.get(),
|
||||
usable.get());
|
||||
ObservationKeyKernel<<<obs_blocks, BLK, 0, impl_->s()>>>(nf, p, d.f_run.get(), d.rr_h.get(), d.rr_k.get(),
|
||||
d.rr_l.get(), key.get(), usable.get());
|
||||
CudaCheck(cudaGetLastError(), "observation key launch");
|
||||
CudaCheck(cudaMemsetAsync(h.get(), 0, size_t(nf), impl_->s()), "memset halves");
|
||||
HalvesKernel<<<grp_blocks, BLK, 0, impl_->s()>>>(p, key.get(), usable.get(), h.get());
|
||||
@@ -1981,7 +1994,6 @@ int RotationScaleMergeGPU::Combine(const int32_t *rawrun_group, double min_parti
|
||||
p.max_frame_gap = max_frame_gap;
|
||||
p.obs = d.obs.get(); p.corr = d.corr.get();
|
||||
p.bkg = d.bkg.get(); p.var_bkg = d.var_bkg.get(); p.image_number = d.image_number.get(); p.d = d.d_obs.get();
|
||||
p.px = d.px_obs.get(); p.py = d.py_obs.get();
|
||||
p.frame = d.frame.get(); p.on_ice = d.on_ice.get(); p.clipped = d.clipped.get();
|
||||
p.perm = d.perm.get(); p.rr_start = d.rr_start.get(); p.rr_count = d.rr_count.get();
|
||||
p.rr_h = d.rr_h.get(); p.rr_k = d.rr_k.get(); p.rr_l = d.rr_l.get(); p.rr_group = rr_group.get();
|
||||
@@ -2011,23 +2023,21 @@ int RotationScaleMergeGPU::Combine(const int32_t *rawrun_group, double min_parti
|
||||
|
||||
// Allocate the fulls SoA and emit.
|
||||
const int nf = std::max(1, d.n_fulls);
|
||||
d.f_h = d.Alloc<int32_t>(nf); d.f_k = d.Alloc<int32_t>(nf); d.f_l = d.Alloc<int32_t>(nf);
|
||||
d.f_run = d.Alloc<int32_t>(nf); d.f_peak = d.Alloc<int32_t>(nf);
|
||||
d.f_frame = d.Alloc<int32_t>(nf); d.f_group = d.Alloc<int32_t>(nf);
|
||||
d.f_I = d.Alloc<float>(nf); d.f_sigma = d.Alloc<float>(nf);
|
||||
d.f_d = d.Alloc<float>(nf); d.f_img = d.Alloc<float>(nf);
|
||||
d.f_px = d.Alloc<float>(nf); d.f_py = d.Alloc<float>(nf);
|
||||
d.f_var_bkg = d.Alloc<float>(nf); d.f_var_per_I = d.Alloc<float>(nf); d.f_capture = d.Alloc<float>(nf);
|
||||
d.f_on_ice = d.Alloc<uint8_t>(nf); d.f_clipped = d.Alloc<uint8_t>(nf);
|
||||
d.f_corr = d.Alloc<float>(nf); d.f_partiality = d.Alloc<float>(nf);
|
||||
d.f_corr = d.Alloc<float>(nf);
|
||||
d.f_zeta = d.Alloc<float>(nf);
|
||||
d.f_obs = d.Alloc<ObsRecord>(nf);
|
||||
d.Upload(rr_offset, offset.data(), d.n_runs);
|
||||
|
||||
p.rr_offset = rr_offset.get();
|
||||
p.f_h = d.f_h.get(); p.f_k = d.f_k.get(); p.f_l = d.f_l.get();
|
||||
p.f_run = d.f_run.get(); p.f_peak = d.f_peak.get();
|
||||
p.f_frame = d.f_frame.get(); p.f_group = d.f_group.get();
|
||||
p.f_I = d.f_I.get(); p.f_sigma = d.f_sigma.get(); p.f_d = d.f_d.get(); p.f_img = d.f_img.get();
|
||||
p.f_px = d.f_px.get(); p.f_py = d.f_py.get();
|
||||
p.f_var_bkg = d.f_var_bkg.get(); p.f_var_per_I = d.f_var_per_I.get(); p.f_capture = d.f_capture.get();
|
||||
p.f_on_ice = d.f_on_ice.get(); p.f_clipped = d.f_clipped.get();
|
||||
if (d.n_fulls > 0) {
|
||||
@@ -2038,7 +2048,7 @@ int RotationScaleMergeGPU::Combine(const int32_t *rawrun_group, double min_parti
|
||||
return d.n_fulls;
|
||||
}
|
||||
|
||||
void RotationScaleMergeGPU::GetFulls(int32_t *h, int32_t *k, int32_t *l, float *I, float *sigma, float *d,
|
||||
void RotationScaleMergeGPU::GetFulls(int32_t *run, float *I, float *sigma, float *d,
|
||||
float *image_number, int32_t *frame, uint8_t *on_ice,
|
||||
uint8_t *clipped, int32_t *group) const {
|
||||
DeviceGuard guard(impl_->device, impl_->available);
|
||||
@@ -2048,8 +2058,7 @@ void RotationScaleMergeGPU::GetFulls(int32_t *h, int32_t *k, int32_t *l, float *
|
||||
auto dl = [&](void *dst, const void *src, size_t bytes) {
|
||||
CopyAndWait(dst, src, bytes, cudaMemcpyDeviceToHost, impl_->s(), "download fulls");
|
||||
};
|
||||
dl(h, dd.f_h.get(), n * sizeof(int32_t)); dl(k, dd.f_k.get(), n * sizeof(int32_t));
|
||||
dl(l, dd.f_l.get(), n * sizeof(int32_t)); dl(frame, dd.f_frame.get(), n * sizeof(int32_t));
|
||||
dl(run, dd.f_run.get(), n * sizeof(int32_t)); dl(frame, dd.f_frame.get(), n * sizeof(int32_t));
|
||||
dl(group, dd.f_group.get(), n * sizeof(int32_t));
|
||||
dl(I, dd.f_I.get(), n * sizeof(float)); dl(sigma, dd.f_sigma.get(), n * sizeof(float));
|
||||
dl(d, dd.f_d.get(), n * sizeof(float)); dl(image_number, dd.f_img.get(), n * sizeof(float));
|
||||
@@ -2066,8 +2075,6 @@ void RotationScaleMergeGPU::ResetFullsScale() {
|
||||
// Unity model: partiality/prescaling_corr/zeta = 1 so coeff = mean; corr starts at 1.
|
||||
FillKernel<<<obs_blocks, BLK, 0, impl_->s()>>>(d.f_corr.get(), nf, 1.0f);
|
||||
CudaCheck(cudaGetLastError(), "FillKernel launch");
|
||||
FillKernel<<<obs_blocks, BLK, 0, impl_->s()>>>(d.f_partiality.get(), nf, 1.0f);
|
||||
CudaCheck(cudaGetLastError(), "FillKernel launch");
|
||||
FullsRecordKernel<<<obs_blocks, BLK, 0, impl_->s()>>>(nf, d.f_I.get(), d.f_sigma.get(), d.f_obs.get());
|
||||
CudaCheck(cudaGetLastError(), "FullsRecordKernel launch");
|
||||
FillKernel<<<obs_blocks, BLK, 0, impl_->s()>>>(d.f_zeta.get(), nf, 1.0f);
|
||||
@@ -2105,13 +2112,12 @@ void RotationScaleMergeGPU::GetFullsCorr(float *corr) const {
|
||||
cudaMemcpyDeviceToHost, impl_->s(), "download f_corr");
|
||||
}
|
||||
|
||||
void RotationScaleMergeGPU::GetFullsPxPy(float *px, float *py) const {
|
||||
void RotationScaleMergeGPU::GetFullsPeak(int32_t *peak) const {
|
||||
DeviceGuard guard(impl_->device, impl_->available);
|
||||
const auto &d = *impl_;
|
||||
if (d.n_fulls == 0) return;
|
||||
const size_t bytes = size_t(d.n_fulls) * sizeof(float);
|
||||
CopyAndWait(px, d.f_px.get(), bytes, cudaMemcpyDeviceToHost, impl_->s(), "download f_px");
|
||||
CopyAndWait(py, d.f_py.get(), bytes, cudaMemcpyDeviceToHost, impl_->s(), "download f_py");
|
||||
CopyAndWait(peak, d.f_peak.get(), size_t(d.n_fulls) * sizeof(int32_t), cudaMemcpyDeviceToHost, impl_->s(),
|
||||
"download f_peak");
|
||||
}
|
||||
|
||||
void RotationScaleMergeGPU::GetFullsVariance(float *var_bkg, float *var_per_I, float *capture) const {
|
||||
@@ -2128,7 +2134,7 @@ void RotationScaleMergeGPU::GetFullsVariance(float *var_bkg, float *var_per_I, f
|
||||
void RotationScaleMergeGPU::FullsDownloaded() {
|
||||
DeviceGuard guard(impl_->device, impl_->available);
|
||||
auto &d = *impl_;
|
||||
d.f_img = {}; d.f_px = {}; d.f_py = {}; d.f_clipped = {};
|
||||
d.f_img = {}; d.f_peak = {}; d.f_clipped = {};
|
||||
d.f_obs = {}; d.f_zeta = {}; d.f_frame_perm = {}; d.f_frame_start = {}; d.f_frame_count = {};
|
||||
d.group_mean = {};
|
||||
}
|
||||
@@ -2456,19 +2462,10 @@ namespace {
|
||||
return (u & 0x80000000u) ? ~u : (u | 0x80000000u);
|
||||
}
|
||||
|
||||
struct IngestArrays {
|
||||
ObsRecord *obs;
|
||||
float *zeta, *corr, *bkg, *var_bkg, *image_number, *d, *px, *py, *dphi;
|
||||
int32_t *frame;
|
||||
uint8_t *on_ice, *clipped;
|
||||
uint64_t *key;
|
||||
};
|
||||
|
||||
// One block per BLK reflections: the block reads its reflections as whole words (coalesced) into
|
||||
// shared memory and each thread takes its own apart. The deterministic correction is the product of
|
||||
// its three factors, in the host's order; the frame's flux is divided out once it is known.
|
||||
__global__ void IngestExtractKernel(int n, int base, const Reflection *__restrict__ refl, IngestArrays a) {
|
||||
__shared__ uint32_t buf[BLK * REFL_WORDS];
|
||||
// shared memory, and each thread then has its own at hand.
|
||||
__device__ __forceinline__ const Reflection *StageBlock(int n, const Reflection *__restrict__ refl,
|
||||
uint32_t *buf) {
|
||||
const int first = blockIdx.x * BLK;
|
||||
const int cnt = min(BLK, n - first);
|
||||
const uint32_t *src = reinterpret_cast<const uint32_t *>(refl + first);
|
||||
@@ -2476,9 +2473,48 @@ namespace {
|
||||
buf[w] = src[w];
|
||||
__syncthreads();
|
||||
if (int(threadIdx.x) >= cnt)
|
||||
return nullptr;
|
||||
return reinterpret_cast<const Reflection *>(buf + threadIdx.x * REFL_WORDS);
|
||||
}
|
||||
|
||||
// What the sort and the cut read of every reflection.
|
||||
struct IngestKeys {
|
||||
float *image_number, *d, *bkg;
|
||||
uint64_t *key;
|
||||
};
|
||||
__global__ void IngestKeyKernel(int n, int base, const Reflection *__restrict__ refl, IngestKeys a) {
|
||||
__shared__ uint32_t buf[BLK * REFL_WORDS];
|
||||
const Reflection *r = StageBlock(n, refl, buf);
|
||||
if (!r)
|
||||
return;
|
||||
const int i = base + blockIdx.x * BLK + threadIdx.x;
|
||||
a.image_number[i] = r->image_number;
|
||||
a.d[i] = r->d;
|
||||
a.bkg[i] = r->bkg;
|
||||
a.key[i] = RawHklKey(r->h, r->k, r->l);
|
||||
}
|
||||
|
||||
struct IngestArrays {
|
||||
ObsRecord *obs;
|
||||
float *zeta, *corr, *bkg, *var_bkg, *image_number, *d, *dphi;
|
||||
uint8_t *on_ice, *clipped;
|
||||
const int32_t *new_idx; // the cut's place of each reflection (an exclusive prefix over the kept)
|
||||
int n, n_keep; // reflections and observations
|
||||
};
|
||||
|
||||
// The observations, each at the place the cut gave its reflection (a reflection the cut dropped has
|
||||
// the place of the next kept one). The deterministic correction is the product of its three
|
||||
// factors, in the host's order; the frame's flux is divided out once the frames are laid out.
|
||||
__global__ void IngestExtractKernel(int cnt, int base, const Reflection *__restrict__ refl, IngestArrays a) {
|
||||
__shared__ uint32_t buf[BLK * REFL_WORDS];
|
||||
const Reflection *rp = StageBlock(cnt, refl, buf);
|
||||
if (!rp)
|
||||
return;
|
||||
const Reflection &r = *rp;
|
||||
const int src = base + blockIdx.x * BLK + threadIdx.x;
|
||||
const int i = a.new_idx[src];
|
||||
if ((src + 1 < a.n ? a.new_idx[src + 1] : a.n_keep) == i)
|
||||
return;
|
||||
const Reflection &r = *reinterpret_cast<const Reflection *>(buf + threadIdx.x * REFL_WORDS);
|
||||
const int i = base + first + threadIdx.x;
|
||||
a.obs[i] = ObsRecord{r.I, r.sigma, r.partiality,
|
||||
__fmul_rn(__fmul_rn(r.prescaling_corr, r.qe_corr), r.flight_corr)};
|
||||
a.zeta[i] = r.zeta;
|
||||
@@ -2487,12 +2523,9 @@ namespace {
|
||||
a.var_bkg[i] = r.var_bkg;
|
||||
a.image_number[i] = r.image_number;
|
||||
a.d[i] = r.d;
|
||||
a.px[i] = r.predicted_x;
|
||||
a.py[i] = r.predicted_y;
|
||||
a.dphi[i] = r.delta_phi_deg;
|
||||
a.on_ice[i] = r.on_ice_ring ? 1 : 0;
|
||||
a.clipped[i] = (r.clipped ? 1 : 0) | (r.overloaded ? 2 : 0); // OBS_CLIPPED | OBS_OVERLOADED
|
||||
a.key[i] = RawHklKey(r.h, r.k, r.l);
|
||||
}
|
||||
|
||||
__global__ void IngestFrameKernel(int n_frames, const int32_t *__restrict__ start, int32_t *__restrict__ frame) {
|
||||
@@ -2606,12 +2639,6 @@ namespace {
|
||||
kept[r] = keep_run[r] ? count[r] : 0;
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
__global__ void IngestCompactKernel(int n, const int32_t *__restrict__ keep, const int32_t *__restrict__ new_idx,
|
||||
const T *__restrict__ in, T *__restrict__ out) {
|
||||
for (int i = blockIdx.x * blockDim.x + threadIdx.x; i < n; i += gridDim.x * blockDim.x)
|
||||
if (keep[i]) out[new_idx[i]] = in[i];
|
||||
}
|
||||
|
||||
int Blocks(int n) { return std::max(1, std::min(65535, (n + BLK - 1) / BLK)); }
|
||||
|
||||
@@ -2796,83 +2823,85 @@ namespace {
|
||||
}
|
||||
}
|
||||
|
||||
void RotationScaleMergeGPU::IngestUpload(int n_frames, const Reflection *const *refl, const int32_t *count,
|
||||
size_t nthreads) {
|
||||
DeviceGuard guard(impl_->device, impl_->available);
|
||||
auto &d = *impl_;
|
||||
d.n_frames = n_frames;
|
||||
d.in_src_start.assign(n_frames + 1, 0);
|
||||
template <typename Take>
|
||||
void RotationScaleMergeGPU::Impl::StageReflections(const Reflection *const *refl, const int32_t *count,
|
||||
size_t nthreads, Take take) {
|
||||
int max_count = 0;
|
||||
for (int o = 0; o < n_frames; ++o) {
|
||||
d.in_src_start[o + 1] = d.in_src_start[o] + count[o];
|
||||
for (int o = 0; o < n_frames; ++o)
|
||||
max_count = std::max(max_count, count[o]);
|
||||
}
|
||||
const int n = d.in_src_start[n_frames];
|
||||
d.n_obs = n;
|
||||
size_t free_bytes = 0, total_bytes = 0;
|
||||
CudaCheck(cudaMemGetInfo(&free_bytes, &total_bytes), "memory info");
|
||||
if (size_t(n) * OBS_BYTES > total_bytes)
|
||||
ThrowTooLargeForGPU(n);
|
||||
d.AllocObservations(n);
|
||||
d.in_key = d.Alloc<uint64_t>(std::max(1, n));
|
||||
d.in_dphi = d.Alloc<float>(std::max(1, n));
|
||||
|
||||
CudaDevicePtr<int32_t> src_start;
|
||||
d.Upload(src_start, d.in_src_start.data(), n_frames + 1);
|
||||
IngestFrameKernel<<<std::max(1, std::min(n_frames, 65535)), BLK, 0, d.s()>>>(n_frames, src_start.get(),
|
||||
d.frame.get());
|
||||
CudaCheck(cudaGetLastError(), "IngestFrameKernel launch");
|
||||
|
||||
// Through two pinned buffers of whole frames, each filled on all threads while the other is on
|
||||
// its way to the card and taken apart there. Where the card reads host memory directly
|
||||
// (gpu_direct_host_read()), the kernel takes the pinned buffer apart in place, without the upload.
|
||||
// Where the card reads host memory directly (gpu_direct_host_read()), the kernel takes the pinned
|
||||
// buffer apart in place, without the upload.
|
||||
constexpr size_t STAGE_BYTES = 64 << 20;
|
||||
const bool direct = gpu_direct_host_read();
|
||||
const int cap = std::max(static_cast<int>(STAGE_BYTES / sizeof(Reflection)), max_count);
|
||||
CudaHostPtr<Reflection> stage[2] = {CudaHostPtr<Reflection>(cap), CudaHostPtr<Reflection>(cap)};
|
||||
CudaDevicePtr<Reflection> staged[2];
|
||||
if (!direct) {
|
||||
staged[0] = d.Alloc<Reflection>(cap);
|
||||
staged[1] = d.Alloc<Reflection>(cap);
|
||||
staged[0] = Alloc<Reflection>(cap);
|
||||
staged[1] = Alloc<Reflection>(cap);
|
||||
}
|
||||
CudaEvent copied[2];
|
||||
bool in_flight[2] = {false, false};
|
||||
IngestArrays a{d.obs.get(), d.zeta.get(), d.corr.get(), d.bkg.get(), d.var_bkg.get(), d.image_number.get(),
|
||||
d.d_obs.get(), d.px_obs.get(), d.py_obs.get(), d.in_dphi.get(), d.frame.get(),
|
||||
d.on_ice.get(), d.clipped.get(), d.in_key.get()};
|
||||
int b = 0;
|
||||
for (int f0 = 0; f0 < n_frames; ) {
|
||||
int f1 = f0 + 1;
|
||||
while (f1 < n_frames && d.in_src_start[f1 + 1] - d.in_src_start[f0] <= cap)
|
||||
while (f1 < n_frames && in_src_start[f1 + 1] - in_src_start[f0] <= cap)
|
||||
++f1;
|
||||
const int base = d.in_src_start[f0];
|
||||
const int cnt = d.in_src_start[f1] - base;
|
||||
const int base = in_src_start[f0];
|
||||
const int cnt = in_src_start[f1] - base;
|
||||
if (in_flight[b])
|
||||
CudaCheck(cudaEventSynchronize(copied[b]), "staging buffer");
|
||||
Reflection *dst = stage[b].get();
|
||||
ParallelFor(f1 - f0, nthreads, [&](int fo) {
|
||||
const int o = f0 + fo;
|
||||
std::copy(refl[o], refl[o] + count[o], dst + (d.in_src_start[o] - base));
|
||||
std::copy(refl[o], refl[o] + count[o], dst + (in_src_start[o] - base));
|
||||
});
|
||||
if (cnt > 0) {
|
||||
const Reflection *src = dst;
|
||||
if (!direct) {
|
||||
CudaCheck(cudaMemcpyAsync(staged[b].get(), dst, size_t(cnt) * sizeof(Reflection),
|
||||
cudaMemcpyHostToDevice, d.s()), "upload reflections");
|
||||
CudaCheck(cudaEventRecord(copied[b], d.s()), "upload reflections");
|
||||
cudaMemcpyHostToDevice, s()), "upload reflections");
|
||||
CudaCheck(cudaEventRecord(copied[b], s()), "upload reflections");
|
||||
src = staged[b].get();
|
||||
}
|
||||
in_flight[b] = true;
|
||||
IngestExtractKernel<<<(cnt + BLK - 1) / BLK, BLK, 0, d.s()>>>(cnt, base, src, a);
|
||||
CudaCheck(cudaGetLastError(), "IngestExtractKernel launch");
|
||||
take(cnt, base, src);
|
||||
// Read in place, the buffer is free again only once the kernel has run.
|
||||
if (direct)
|
||||
CudaCheck(cudaEventRecord(copied[b], d.s()), "extract reflections");
|
||||
CudaCheck(cudaEventRecord(copied[b], s()), "extract reflections");
|
||||
}
|
||||
b ^= 1;
|
||||
f0 = f1;
|
||||
}
|
||||
CudaCheck(cudaStreamSynchronize(d.s()), "upload reflections");
|
||||
CudaCheck(cudaStreamSynchronize(s()), "upload reflections");
|
||||
}
|
||||
|
||||
void RotationScaleMergeGPU::IngestUpload(int n_frames, const Reflection *const *refl, const int32_t *count,
|
||||
size_t nthreads) {
|
||||
DeviceGuard guard(impl_->device, impl_->available);
|
||||
auto &d = *impl_;
|
||||
d.n_frames = n_frames;
|
||||
d.in_src_start.assign(n_frames + 1, 0);
|
||||
for (int o = 0; o < n_frames; ++o)
|
||||
d.in_src_start[o + 1] = d.in_src_start[o] + count[o];
|
||||
const int n = d.in_src_start[n_frames];
|
||||
d.n_obs = n;
|
||||
size_t free_bytes = 0, total_bytes = 0;
|
||||
CudaCheck(cudaMemGetInfo(&free_bytes, &total_bytes), "memory info");
|
||||
if (size_t(n) * OBS_BYTES > total_bytes)
|
||||
ThrowTooLargeForGPU(n);
|
||||
// See AllocObservations: these are the first of the scaling's buffers.
|
||||
cuda_trim_allocation_pool();
|
||||
// Only what the sort and the cut read; the observations are taken from the reflections once the cut
|
||||
// has decided which they are (IngestObservations), so the two are never on the card together.
|
||||
const int na = std::max(1, n);
|
||||
d.in_img = d.Alloc<float>(na); d.in_d = d.Alloc<float>(na); d.in_bkg = d.Alloc<float>(na);
|
||||
d.in_key = d.Alloc<uint64_t>(na);
|
||||
const IngestKeys a{d.in_img.get(), d.in_d.get(), d.in_bkg.get(), d.in_key.get()};
|
||||
d.StageReflections(refl, count, nthreads, [&](int cnt, int base, const Reflection *src) {
|
||||
IngestKeyKernel<<<(cnt + BLK - 1) / BLK, BLK, 0, d.s()>>>(cnt, base, src, a);
|
||||
CudaCheck(cudaGetLastError(), "IngestKeyKernel launch");
|
||||
});
|
||||
}
|
||||
|
||||
void RotationScaleMergeGPU::IngestMeanBackground(double *mean_bkg) {
|
||||
@@ -2881,26 +2910,19 @@ void RotationScaleMergeGPU::IngestMeanBackground(double *mean_bkg) {
|
||||
CudaDevicePtr<int32_t> start;
|
||||
d.Upload(start, d.in_src_start.data(), d.n_frames + 1);
|
||||
CudaDevicePtr<double> mean = d.Alloc<double>(std::max(1, d.n_frames));
|
||||
IngestMeanBkgKernel<<<Blocks(d.n_frames), BLK, 0, d.s()>>>(d.n_frames, start.get(), d.bkg.get(), mean.get());
|
||||
IngestMeanBkgKernel<<<Blocks(d.n_frames), BLK, 0, d.s()>>>(d.n_frames, start.get(), d.in_bkg.get(), mean.get());
|
||||
CudaCheck(cudaGetLastError(), "IngestMeanBkgKernel launch");
|
||||
if (d.n_frames > 0)
|
||||
CopyAndWait(mean_bkg, mean.get(), size_t(d.n_frames) * sizeof(double), cudaMemcpyDeviceToHost, d.s(),
|
||||
"download mean background");
|
||||
d.in_bkg = {};
|
||||
}
|
||||
|
||||
int RotationScaleMergeGPU::IngestSort(const double *frame_flux, std::optional<double> d_min,
|
||||
std::optional<double> d_max) {
|
||||
int RotationScaleMergeGPU::IngestSort(std::optional<double> d_min, std::optional<double> d_max) {
|
||||
DeviceGuard guard(impl_->device, impl_->available);
|
||||
auto &d = *impl_;
|
||||
const int n = d.n_obs;
|
||||
const int na = std::max(1, n);
|
||||
{
|
||||
CudaDevicePtr<double> flux;
|
||||
d.Upload(flux, frame_flux, d.n_frames);
|
||||
IngestFluxKernel<<<Blocks(n), BLK, 0, d.s()>>>(n, d.frame.get(), flux.get(), d.obs.get());
|
||||
CudaCheck(cudaGetLastError(), "IngestFluxKernel launch");
|
||||
CudaCheck(cudaStreamSynchronize(d.s()), "flux");
|
||||
}
|
||||
|
||||
// (h, k, l, image_number, index) is a total order, so two stable radix passes - by the frame position
|
||||
// with the index as the value, then by the raw hkl - give the one permutation std::sort gives on the
|
||||
@@ -2926,10 +2948,11 @@ int RotationScaleMergeGPU::IngestSort(const double *frame_flux, std::optional<do
|
||||
{
|
||||
CudaDevicePtr<uint32_t> ikey = d.Alloc<uint32_t>(na), ikey_sorted = d.Alloc<uint32_t>(na);
|
||||
CudaDevicePtr<int32_t> idx = d.Alloc<int32_t>(na);
|
||||
IngestImageKeyKernel<<<Blocks(n), BLK, 0, d.s()>>>(n, d.image_number.get(), ikey.get(), idx.get());
|
||||
IngestImageKeyKernel<<<Blocks(n), BLK, 0, d.s()>>>(n, d.in_img.get(), ikey.get(), idx.get());
|
||||
CudaCheck(cudaGetLastError(), "IngestImageKeyKernel launch");
|
||||
if (n > 0) sort_pairs(ikey, ikey_sorted, idx, by_image, 32);
|
||||
}
|
||||
d.in_img = {};
|
||||
CudaDevicePtr<uint64_t> key = d.Alloc<uint64_t>(na);
|
||||
IngestGatherKeyKernel<<<Blocks(n), BLK, 0, d.s()>>>(n, by_image.get(), d.in_key.get(), key.get());
|
||||
CudaCheck(cudaGetLastError(), "IngestGatherKeyKernel launch");
|
||||
@@ -2984,7 +3007,7 @@ int RotationScaleMergeGPU::IngestSort(const double *frame_flux, std::optional<do
|
||||
CudaDevicePtr<int32_t> keep_run = d.Alloc<int32_t>(nra);
|
||||
const bool limited = d_min.has_value() || d_max.has_value();
|
||||
IngestRunKernel<<<Blocks(n_runs), BLK, 0, d.s()>>>(n_runs, run_start.get(), run_count.get(), perm.get(),
|
||||
d.d_obs.get(), d_min.has_value(), d_min.value_or(0.0),
|
||||
d.in_d.get(), d_min.has_value(), d_min.value_or(0.0),
|
||||
d_max.has_value(), d_max.value_or(0.0),
|
||||
run_d.get(), keep_run.get());
|
||||
CudaCheck(cudaGetLastError(), "IngestRunKernel launch");
|
||||
@@ -3043,6 +3066,7 @@ int RotationScaleMergeGPU::IngestSort(const double *frame_flux, std::optional<do
|
||||
// The runs are cut: what was kept of them is in rr_*, so the uncut ones and the old order go before
|
||||
// the observations are cut below, one field held twice at a time.
|
||||
perm = {}; run_key = {}; run_count = {}; run_start = {}; run_d = {}; keep_run = {}; run_idx = {}; run_at = {};
|
||||
d.in_d = {};
|
||||
|
||||
// The frame CSR of what survived.
|
||||
auto &L = d.in_layout;
|
||||
@@ -3063,19 +3087,9 @@ int RotationScaleMergeGPU::IngestSort(const double *frame_flux, std::optional<do
|
||||
L.frame_start.assign(d.n_frames, 0);
|
||||
for (int o = 0, at = 0; o < d.n_frames; ++o) { L.frame_start[o] = at; at += L.frame_count[o]; }
|
||||
|
||||
// The observations themselves, cut field by field, so that only one field is ever held twice.
|
||||
if (n_keep < n) {
|
||||
const auto cut = [&](auto &field) {
|
||||
using T = std::remove_reference_t<decltype(*field.get())>;
|
||||
CudaDevicePtr<T> out = d.Alloc<T>(nka);
|
||||
IngestCompactKernel<T><<<Blocks(n), BLK, 0, d.s()>>>(n, keep.get(), new_idx.get(), field.get(), out.get());
|
||||
CudaCheck(cudaGetLastError(), "IngestCompactKernel launch");
|
||||
CudaCheck(cudaStreamSynchronize(d.s()), "cut");
|
||||
field = std::move(out);
|
||||
};
|
||||
cut(d.obs); cut(d.zeta); cut(d.corr); cut(d.bkg); cut(d.var_bkg); cut(d.image_number); cut(d.d_obs);
|
||||
cut(d.px_obs); cut(d.py_obs); cut(d.frame); cut(d.on_ice); cut(d.clipped); cut(d.in_dphi);
|
||||
}
|
||||
// Where each observation goes, for IngestObservations to take them from the reflections.
|
||||
d.in_new_idx = std::move(new_idx);
|
||||
d.in_n_keep = n_keep;
|
||||
d.n_obs = n_keep;
|
||||
d.AllocFrames(L.frame_start.data(), L.frame_count.data());
|
||||
|
||||
@@ -3094,6 +3108,51 @@ void RotationScaleMergeGPU::IngestGetLayout(IngestLayout &out) const {
|
||||
out = impl_->in_layout;
|
||||
}
|
||||
|
||||
void RotationScaleMergeGPU::IngestObservations(const Reflection *const *refl, const int32_t *count, size_t nthreads,
|
||||
const double *frame_flux, float *px, float *py) {
|
||||
DeviceGuard guard(impl_->device, impl_->available);
|
||||
auto &d = *impl_;
|
||||
const int n_keep = d.in_n_keep;
|
||||
d.AllocObservations(n_keep);
|
||||
d.in_dphi = d.Alloc<float>(std::max(1, n_keep));
|
||||
const IngestArrays a{d.obs.get(), d.zeta.get(), d.corr.get(), d.bkg.get(), d.var_bkg.get(), d.image_number.get(),
|
||||
d.d_obs.get(), d.in_dphi.get(), d.on_ice.get(),
|
||||
d.clipped.get(), d.in_new_idx.get(), d.in_src_start[d.n_frames], n_keep};
|
||||
d.StageReflections(refl, count, nthreads, [&](int cnt, int base, const Reflection *src) {
|
||||
IngestExtractKernel<<<(cnt + BLK - 1) / BLK, BLK, 0, d.s()>>>(cnt, base, src, a);
|
||||
CudaCheck(cudaGetLastError(), "IngestExtractKernel launch");
|
||||
});
|
||||
// The predicted positions, which only the fulls' and only on the host read, stay there.
|
||||
const int n = d.in_src_start[d.n_frames];
|
||||
std::vector<int32_t> new_idx(n);
|
||||
if (n > 0)
|
||||
CopyAndWait(new_idx.data(), d.in_new_idx.get(), size_t(n) * sizeof(int32_t), cudaMemcpyDeviceToHost, d.s(),
|
||||
"download places");
|
||||
d.in_new_idx = {};
|
||||
ParallelFor(d.n_frames, nthreads, [&](int o) {
|
||||
for (int j = 0; j < count[o]; ++j) {
|
||||
const int src = d.in_src_start[o] + j, i = new_idx[src];
|
||||
if ((src + 1 < n ? new_idx[src + 1] : n_keep) == i) continue;
|
||||
px[i] = refl[o][j].predicted_x;
|
||||
py[i] = refl[o][j].predicted_y;
|
||||
}
|
||||
});
|
||||
|
||||
// The kept observations are in frame order, as the reflections were.
|
||||
std::vector<int32_t> start(d.n_frames + 1, n_keep);
|
||||
for (int o = 0; o < d.n_frames; ++o) start[o] = d.in_layout.frame_start[o];
|
||||
CudaDevicePtr<int32_t> d_start;
|
||||
d.Upload(d_start, start.data(), d.n_frames + 1);
|
||||
IngestFrameKernel<<<std::max(1, std::min(d.n_frames, 65535)), BLK, 0, d.s()>>>(d.n_frames, d_start.get(),
|
||||
d.frame.get());
|
||||
CudaCheck(cudaGetLastError(), "IngestFrameKernel launch");
|
||||
CudaDevicePtr<double> flux;
|
||||
d.Upload(flux, frame_flux, d.n_frames);
|
||||
IngestFluxKernel<<<Blocks(n_keep), BLK, 0, d.s()>>>(n_keep, d.frame.get(), flux.get(), d.obs.get());
|
||||
CudaCheck(cudaGetLastError(), "IngestFluxKernel launch");
|
||||
CudaCheck(cudaStreamSynchronize(d.s()), "flux");
|
||||
}
|
||||
|
||||
int64_t RotationScaleMergeGPU::IngestDeltaPhi(const DeltaPhiFrame &g) {
|
||||
DeviceGuard guard(impl_->device, impl_->available);
|
||||
auto &d = *impl_;
|
||||
@@ -3173,14 +3232,19 @@ void RotationScaleMergeGPU::BuildFullsCSRs(int32_t *frame_count, std::vector<int
|
||||
auto &d = *impl_;
|
||||
const int nf = d.n_fulls, nfr = d.n_frames, ng = d.n_groups;
|
||||
const int nfa = std::max(1, nf);
|
||||
const auto stable_sort = [&](const int32_t *key_in, int32_t *key_out, const int32_t *val_in, int32_t *val_out) {
|
||||
// The index order of the keys, stably sorted, left in val_out: back and forth between the two
|
||||
// buffers of each, as no input is needed after it, so that cub holds no copy of its own.
|
||||
const auto stable_sort = [&](CudaDevicePtr<int32_t> &key_in, CudaDevicePtr<int32_t> &key_out,
|
||||
CudaDevicePtr<int32_t> &val_in, CudaDevicePtr<int32_t> &val_out) {
|
||||
if (nf > 0) IotaKernel<<<(nf + BLK - 1) / BLK, BLK, 0, d.s()>>>(nf, val_in.get());
|
||||
CudaCheck(cudaGetLastError(), "IotaKernel launch");
|
||||
cub::DoubleBuffer<int32_t> keys(key_in.get(), key_out.get()), values(val_in.get(), val_out.get());
|
||||
size_t bytes = 0;
|
||||
CudaCheck(cub::DeviceRadixSort::SortPairs(nullptr, bytes, key_in, key_out, val_in, val_out, nf, 0, 32, d.s()),
|
||||
"sort temp size");
|
||||
CudaCheck(cub::DeviceRadixSort::SortPairs(nullptr, bytes, keys, values, nf, 0, 32, d.s()), "sort temp size");
|
||||
CudaDevicePtr<uint8_t> temp = d.Alloc<uint8_t>(std::max<size_t>(1, bytes));
|
||||
CudaCheck(cub::DeviceRadixSort::SortPairs(temp.get(), bytes, key_in, key_out, val_in, val_out, nf, 0, 32, d.s()),
|
||||
"sort");
|
||||
CudaCheck(cub::DeviceRadixSort::SortPairs(temp.get(), bytes, keys, values, nf, 0, 32, d.s()), "sort");
|
||||
CudaCheck(cudaStreamSynchronize(d.s()), "sort");
|
||||
if (values.Current() != val_out.get()) std::swap(val_in, val_out);
|
||||
};
|
||||
// The counts come back for the starts, a prefix the host forms in order.
|
||||
const auto count = [&](const int32_t *bin, int n_bins, CudaDevicePtr<int32_t> &out, std::vector<int32_t> &host) {
|
||||
@@ -3199,8 +3263,6 @@ void RotationScaleMergeGPU::BuildFullsCSRs(int32_t *frame_count, std::vector<int
|
||||
return start;
|
||||
};
|
||||
CudaDevicePtr<int32_t> idx = d.Alloc<int32_t>(nfa), key = d.Alloc<int32_t>(nfa), sorted = d.Alloc<int32_t>(nfa);
|
||||
if (nf > 0) IotaKernel<<<(nf + BLK - 1) / BLK, BLK, 0, d.s()>>>(nf, idx.get());
|
||||
CudaCheck(cudaGetLastError(), "IotaKernel launch");
|
||||
|
||||
std::vector<int32_t> fcount;
|
||||
count(d.f_frame.get(), nfr, d.f_frame_count, fcount);
|
||||
@@ -3208,7 +3270,11 @@ void RotationScaleMergeGPU::BuildFullsCSRs(int32_t *frame_count, std::vector<int
|
||||
const std::vector<int32_t> fstart = prefix(fcount);
|
||||
d.Upload(d.f_frame_start, fstart.data(), nfr);
|
||||
d.f_frame_perm = d.Alloc<int32_t>(nfa);
|
||||
if (nf > 0) stable_sort(d.f_frame.get(), key.get(), idx.get(), d.f_frame_perm.get());
|
||||
if (nf > 0) {
|
||||
CopyAndWait(key.get(), d.f_frame.get(), size_t(nf) * sizeof(int32_t), cudaMemcpyDeviceToDevice, d.s(),
|
||||
"frame key");
|
||||
stable_sort(key, sorted, idx, d.f_frame_perm);
|
||||
}
|
||||
|
||||
std::vector<int32_t> gcount;
|
||||
count(d.f_group.get(), ng, d.f_gcount, gcount);
|
||||
@@ -3218,7 +3284,7 @@ void RotationScaleMergeGPU::BuildFullsCSRs(int32_t *frame_count, std::vector<int
|
||||
FullGroupKeyKernel<<<Blocks(nf), BLK, 0, d.s()>>>(nf, d.f_group.get(), key.get());
|
||||
CudaCheck(cudaGetLastError(), "FullGroupKeyKernel launch");
|
||||
CudaDevicePtr<int32_t> by_group = d.Alloc<int32_t>(nfa);
|
||||
if (nf > 0) stable_sort(key.get(), sorted.get(), idx.get(), by_group.get());
|
||||
if (nf > 0) stable_sort(key, sorted, idx, by_group);
|
||||
d.f_gperm = d.Alloc<int32_t>(std::max(1, n_grouped));
|
||||
gperm.resize(n_grouped);
|
||||
if (n_grouped > 0) {
|
||||
|
||||
@@ -40,12 +40,12 @@ public:
|
||||
// One slice ([offset, offset+count) of n_obs) of one immutable per-observation field, so the
|
||||
// host can stage a bounded chunk at a time out of its AoS record: staged whole and all at once,
|
||||
// the fourteen arrays are more than half the entire observation payload held live again.
|
||||
// Corr0 seeds the resident, mutable corr (SetCorr refreshes it). Bkg/VarBkg/ImageNumber/D/Px/Py
|
||||
// Corr0 seeds the resident, mutable corr (SetCorr refreshes it). Bkg/VarBkg/ImageNumber/D
|
||||
// are the combine inputs (image-local background, fractional frame position for event
|
||||
// contiguity, resolution, and the predicted detector position carried to the full for the
|
||||
// absorption surface).
|
||||
// contiguity and resolution; the predicted detector position carried to the full for the
|
||||
// absorption surface stays on the host, GetFullsPeak).
|
||||
enum class ObsField { I, Sigma, PrescalingCorr, Partiality, Zeta, Corr0,
|
||||
Bkg, VarBkg, ImageNumber, D, Px, Py };
|
||||
Bkg, VarBkg, ImageNumber, D };
|
||||
void SetObsField(ObsField f, int offset, int count, const float *v);
|
||||
void SetObsFrame(int offset, int count, const int32_t *frame);
|
||||
void SetObsOnIce(int offset, int count, const uint8_t *on_ice);
|
||||
@@ -60,19 +60,20 @@ public:
|
||||
// --- the resident ingest (RotationScaleMerge::IngestDevice with no observation array on the host) ---
|
||||
// The steps below build, from the reflections, exactly the observations and raw-hkl runs that
|
||||
// RotationScaleMerge::BuildInRangeObservations builds on the host, and leave them where the uploads
|
||||
// above and SetRawRuns would: the reflections cross the bus once, and are sorted and cut on the card.
|
||||
// above and SetRawRuns would: the reflections are sorted and cut on the card, and cross the bus
|
||||
// twice - once for what the sort and the cut read, once for the observations the cut kept.
|
||||
|
||||
// The reflections of n_frames frames, frame o's count[o] of them at refl[o], uploaded in frame order;
|
||||
// every field the ingest and the merge read is kept per reflection.
|
||||
// what the sort, the cut and the background below read is kept per reflection.
|
||||
void IngestUpload(int n_frames, const Reflection *const *refl, const int32_t *count, size_t nthreads);
|
||||
// Each frame's mean background over its reflections with a finite, positive one, summed in their
|
||||
// order (NaN where there is none): the incident-flux meter. Length n_frames.
|
||||
void IngestMeanBackground(double *mean_bkg);
|
||||
// Divide every reflection's deterministic correction by its frame's flux (length n_frames); order the
|
||||
// reflections by (raw h,k,l, image_number, index) and cut that order into raw-hkl runs, each with the
|
||||
// resolution of its first member that has a usable one; and drop the runs outside [d_min, d_max]
|
||||
// (either may be absent) with their reflections. Returns how many observations are left.
|
||||
int IngestSort(const double *frame_flux, std::optional<double> d_min, std::optional<double> d_max);
|
||||
// Order the reflections by (raw h,k,l, image_number, index) and cut that order into raw-hkl runs,
|
||||
// each with the resolution of its first member that has a usable one; and drop the runs outside
|
||||
// [d_min, d_max] (either may be absent) with their reflections. Returns how many observations are
|
||||
// left. Nothing per observation is on the card yet (IngestObservations).
|
||||
int IngestSort(std::optional<double> d_min, std::optional<double> d_max);
|
||||
// The layout IngestSort left: the reflection and run counts before the resolution cut, the
|
||||
// observations' frame CSR, and the runs that survived it.
|
||||
struct IngestLayout {
|
||||
@@ -83,6 +84,12 @@ public:
|
||||
std::vector<float> run_d;
|
||||
};
|
||||
void IngestGetLayout(IngestLayout &out) const;
|
||||
// The observations IngestSort kept, taken from the same reflections (as IngestUpload had them), in
|
||||
// its order, each with its deterministic correction divided by its frame's flux (length n_frames).
|
||||
// px/py (length IngestSort's count) receive each observation's predicted position, which is not
|
||||
// kept on the card (GetFullsPeak).
|
||||
void IngestObservations(const Reflection *const *refl, const int32_t *count, size_t nthreads,
|
||||
const double *frame_flux, float *px, float *py);
|
||||
// The ingest's geometry smoothing, on the observations IngestSort left (RotationScaleMerge::IngestOnDevice):
|
||||
// each delta_phi re-solved against its frame's smoothed lattice where the frame has one - recip holds
|
||||
// a*, b*, c* per frame (9 floats), ok which frames, and the goniometer frame as SmoothedGeometry
|
||||
@@ -229,15 +236,16 @@ public:
|
||||
int Combine(const int32_t *rawrun_group, double min_partiality, double capture_uncertainty_coeff,
|
||||
double min_captured_fraction, float max_frame_gap, int64_t &n_overloaded);
|
||||
|
||||
// Download the combined fulls SoA (length = Combine()'s return). The working corr is downloaded
|
||||
// separately by GetFullsCorr (it is only meaningful after the fulls scaling; otherwise the caller sets it).
|
||||
void GetFulls(int32_t *h, int32_t *k, int32_t *l, float *I, float *sigma, float *d,
|
||||
// Download the combined fulls SoA (length = Combine()'s return); run is the raw-hkl run each full is
|
||||
// of. The working corr is downloaded separately by GetFullsCorr (it is only meaningful after the
|
||||
// fulls scaling; otherwise the caller sets it).
|
||||
void GetFulls(int32_t *run, float *I, float *sigma, float *d,
|
||||
float *image_number, int32_t *frame, uint8_t *on_ice, uint8_t *clipped,
|
||||
int32_t *group) const;
|
||||
|
||||
// Download the fulls' predicted detector position (peak partial's px/py), for the host absorption
|
||||
// surface. Length = n_fulls.
|
||||
void GetFullsPxPy(float *px, float *py) const;
|
||||
// Download the observation each full's predicted detector position is that of (its peak partial),
|
||||
// for the host absorption surface; the positions themselves stay on the host. Length = n_fulls.
|
||||
void GetFullsPeak(int32_t *peak) const;
|
||||
|
||||
// Download the fulls' variance model, var(I) = var_bkg + var_per_I * I + (capture * I)^2. Length = n_fulls.
|
||||
void GetFullsVariance(float *var_bkg, float *var_per_I, float *capture) const;
|
||||
|
||||
@@ -45,6 +45,7 @@
|
||||
#include "SigmaA.h"
|
||||
#ifdef JFJOCH_USE_CUDA
|
||||
#include "ModelStructureFactorsGPU.h"
|
||||
#include "../indexing/CUDAMemHelpers.h" // cuda_trim_allocation_pool
|
||||
#include "RigidBodyGPU.h"
|
||||
#include "RigidBodyGPUEngine.h" // RigidBodyGPUEngine::CurrentDevice
|
||||
#include "../../common/CUDAWrapper.h"
|
||||
@@ -491,71 +492,39 @@ void read_anomalous_map(const gemmi::Grid<float> &grid, double rms, gemmi::Struc
|
||||
}
|
||||
|
||||
#ifdef JFJOCH_USE_CUDA
|
||||
// The model's structure factors to the data's resolution, and the maps, on the GPU - or not, decided here,
|
||||
// once, before any of them is computed, and never revisited: nothing is moved to the CPU part way through.
|
||||
// Decided on what the GPU path needs against the card's TOTAL memory and not against what happens to be
|
||||
// free at the moment, so the same input on the same machine always takes the same path, whatever else is
|
||||
// running beside it. A validation plans at most half of its card: its structure-factor engines a quarter
|
||||
// together - `reserved` is what one of them already holds there - and its rigid-body engines a quarter
|
||||
// (RigidBodyGPUPool::Create). A second validation runs beside it only where twice that plan fits half of
|
||||
// the cards together (see on_forecast below), so validations never plan more than half of the memory.
|
||||
std::unique_ptr<ModelStructureFactorsGPU> StructureFactorsGPU(int device, const gemmi::Model &model,
|
||||
const gemmi::UnitCell &cell, const gemmi::SpaceGroup &sg,
|
||||
double d_min, size_t reserved, Logger &logger) {
|
||||
// An engine for the model's structure factors to d_min (and the maps) on `device`, nothing reserved yet;
|
||||
// null, logged, where the cell is too small for the GPU's gridding.
|
||||
std::unique_ptr<ModelStructureFactorsGPU> StructureFactorsEngine(int device, const gemmi::Model &model,
|
||||
const gemmi::UnitCell &cell,
|
||||
const gemmi::SpaceGroup &sg, double d_min,
|
||||
Logger &logger) {
|
||||
std::unique_ptr<ModelStructureFactorsGPU> sf;
|
||||
try {
|
||||
sf = std::make_unique<ModelStructureFactorsGPU>(device, model, cell, sg, d_min);
|
||||
} catch (const JFJochException &e) {
|
||||
throw RigidBodyGPUFailure(e.what());
|
||||
}
|
||||
const std::array<int, 3> n = sf->GridSize();
|
||||
if (!sf->Supported()) {
|
||||
logger.Info("Model validation: structure factors to {:.2f} A on the CPU - the cell is too small for the "
|
||||
"GPU's gridding", d_min);
|
||||
return nullptr;
|
||||
}
|
||||
const size_t total = sf->DeviceTotalMemory();
|
||||
if (reserved + sf->DeviceBytes() > total / 4) {
|
||||
logger.Info("Model validation: structure factors to {:.2f} A on the CPU - on a {}x{}x{} grid they need "
|
||||
"{:.2f} GB of GPU memory beside {:.2f} GB already reserved, over a quarter of the card's {:.2f} GB",
|
||||
d_min, n[0], n[1], n[2], sf->DeviceBytes() / 1e9, reserved / 1e9, total / 1e9);
|
||||
return nullptr;
|
||||
}
|
||||
try {
|
||||
sf->Reserve();
|
||||
} catch (const JFJochException &e) {
|
||||
throw RigidBodyGPUFailure(e.what());
|
||||
}
|
||||
logger.Info("Model validation: structure factors to {:.2f} A on the GPU - a {}x{}x{} grid, {:.2f} GB of the "
|
||||
"card's {:.2f} GB", d_min, n[0], n[1], n[2], sf->DeviceBytes() / 1e9, total / 1e9);
|
||||
return sf;
|
||||
}
|
||||
|
||||
// The scale fits on the GPU (ModelScaleGPUPool) - or not, decided here, once, on the card's total memory as
|
||||
// the structure factors are: SCALE_GPU_ENGINES engines, fewer where they would take over an eighth of the
|
||||
// card, none where not even one fits.
|
||||
constexpr size_t SCALE_GPU_ENGINES = 4;
|
||||
|
||||
std::unique_ptr<ModelScaleGPUPool> ScaleFitsGPU(int device, size_t max_points, Logger &logger) {
|
||||
const size_t total = get_gpu_total_memory(device);
|
||||
size_t engines = SCALE_GPU_ENGINES;
|
||||
while (engines > 0 && ModelScaleGPUPool::DeviceBytes(max_points, engines) > total / 8)
|
||||
engines--;
|
||||
if (engines == 0) {
|
||||
logger.Info("Model validation: scale fits on the CPU - one fit of {} reflections needs {:.2f} GB of GPU "
|
||||
"memory, over an eighth of the card's {:.2f} GB", max_points,
|
||||
ModelScaleGPUPool::DeviceBytes(max_points, 1) / 1e9, total / 1e9);
|
||||
return nullptr;
|
||||
}
|
||||
std::unique_ptr<ModelScaleGPUPool> pool;
|
||||
void Reserve(ModelStructureFactorsGPU &sf) {
|
||||
try {
|
||||
pool = std::make_unique<ModelScaleGPUPool>(device, max_points, engines);
|
||||
sf.Reserve();
|
||||
} catch (const JFJochException &e) {
|
||||
throw RigidBodyGPUFailure(e.what());
|
||||
}
|
||||
logger.Info("Model validation: scale fits on the GPU, {} engine(s), {:.2f} GB of the card's {:.2f} GB",
|
||||
engines, pool->Bytes() / 1e9, total / 1e9);
|
||||
return pool;
|
||||
}
|
||||
|
||||
// The validation's scale fits can use this many engines at once.
|
||||
constexpr size_t SCALE_GPU_ENGINES = 4;
|
||||
|
||||
std::string GBytes(size_t bytes) {
|
||||
return fmt::format("{:.2f} GB", bytes / 1e9);
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -780,22 +749,134 @@ ModelValidationResult Validate(const std::vector<MergedReflection> &merged,
|
||||
logger.Info("Model validation: {} atoms, cell a={:.2f} b={:.2f} c={:.2f}, sg {}, to {:.2f} A",
|
||||
gemmi::count_atom_sites(st.models[0]), ucell.a, ucell.b, ucell.c, sg->hm, d_min);
|
||||
|
||||
// The structure factors to d_min and the maps on the GPU, where `rigid_body_gpu` allows it and the
|
||||
// card can take them; decided here, before any is computed. The null's, to its coarser limit, get an
|
||||
// engine of their own further down, decided the same way before any replicate starts - for all of
|
||||
// them and the real model's side of the null together, so that every one is computed the same way.
|
||||
// Whether the model is asked to fit at all (see "does the model fit at all?" below), and the resolution
|
||||
// its null is scored to, which the null's structure-factor engine is sized for.
|
||||
const bool decision_pending = schedule.fit_test;
|
||||
double null_d_min = d_min;
|
||||
if (decision_pending) {
|
||||
// The null and the side of the real fit it is compared with are both scored to NULL_D_MIN,
|
||||
// not to the data's resolution. The placement already stops there (RigidBodyRefine's ladder
|
||||
// ends at 3.5 A), and whether a model is in the right orientation, or the data in its
|
||||
// indexing, is decided at low resolution: the finer shells only add reflections to the scale
|
||||
// fits, which were most of the null's cost. Both sides go through the same fits on the same
|
||||
// reflections, so the comparison stays like for like. On a small cell 3.5 A leaves too few
|
||||
// free reflections for a real indexing margin to be told from a random placement's, so the
|
||||
// limit then moves out to where NULL_MIN_FREE of them are - to the data's own on the
|
||||
// smallest, which are the cheap ones.
|
||||
std::vector<float> free_d;
|
||||
for (const MergedReflection &r : obs)
|
||||
if (r.rfree_flag && !std::isnan(r.F))
|
||||
free_d.push_back(r.d);
|
||||
std::sort(free_d.begin(), free_d.end(), std::greater<>());
|
||||
null_d_min = std::max(d_min, NULL_D_MIN);
|
||||
if (free_d.size() < NULL_MIN_FREE)
|
||||
null_d_min = d_min;
|
||||
else
|
||||
null_d_min = std::min<double>(null_d_min, free_d[NULL_MIN_FREE - 1]);
|
||||
}
|
||||
|
||||
// What runs on the GPU, where `rigid_body_gpu` allows it and there is a card: the structure factors to
|
||||
// d_min and the maps, the null's structure factors to its coarser limit (where that is not d_min), the
|
||||
// rigid body and the scale fits - all decided here, at once, by PlanModelValidationGPU, before any of
|
||||
// them is computed, and never revisited: nothing is moved to the CPU part way through. Every engine is
|
||||
// reserved now and kept to the end, the real fit and every replicate of the null on the same ones, so
|
||||
// that a verdict never depends on how full the card was when a replicate started. One card for the
|
||||
// structure factors and the scale fits, the current one; the rigid body's engines count on from it.
|
||||
ModelStructureFactorsGPU *sf_gpu = nullptr, *sf_null = nullptr;
|
||||
RigidBodyGPUPool *rigid_body_pool = nullptr;
|
||||
size_t gpu_bytes = 0;
|
||||
bool may_run_beside = true;
|
||||
#ifdef JFJOCH_USE_CUDA
|
||||
std::unique_ptr<ModelStructureFactorsGPU> sf_engine, sf_null_engine;
|
||||
// On the current device, as the rigid body's engines take it: one card for the whole validation.
|
||||
if (rigid_body_gpu && get_gpu_count() > 0)
|
||||
sf_engine = StructureFactorsGPU(RigidBodyGPUEngine::CurrentDevice(), st.models[0], ucell, *sg, d_min, 0,
|
||||
logger);
|
||||
sf_gpu = sf_engine.get();
|
||||
// The scale fits beside them, on the same card, for as many reflections as the data have.
|
||||
std::unique_ptr<RigidBodyGPUPool> rigid_body_engines;
|
||||
std::unique_ptr<ModelScaleGPUPool> scale_gpu;
|
||||
if (rigid_body_gpu && get_gpu_count() > 0)
|
||||
scale_gpu = ScaleFitsGPU(RigidBodyGPUEngine::CurrentDevice(), obs.size(), logger);
|
||||
ModelValidationGPUPlan gpu_plan;
|
||||
if (rigid_body_gpu && get_gpu_count() > 0) {
|
||||
const int device = RigidBodyGPUEngine::CurrentDevice();
|
||||
// What the stream-ordered pool holds with no buffer in it - freed by the passes before, measured
|
||||
// at 1-2 GB - goes back to the driver first: the engines below are allocated outside the pool and
|
||||
// cannot use it, and the budget counts only what is still held.
|
||||
cuda_trim_allocation_pool();
|
||||
ModelValidationGPUNeed need;
|
||||
need.card = get_gpu_total_memory(device);
|
||||
need.resident = schedule.gpu_resident_bytes;
|
||||
need.beside = schedule.gpu_beside_bytes;
|
||||
sf_engine = StructureFactorsEngine(device, st.models[0], ucell, *sg, d_min, logger);
|
||||
if (sf_engine)
|
||||
need.structure_factors = sf_engine->DeviceBytes();
|
||||
if (null_d_min != d_min) {
|
||||
sf_null_engine = StructureFactorsEngine(device, st.models[0], ucell, *sg, null_d_min, logger);
|
||||
if (sf_null_engine)
|
||||
need.null_structure_factors = sf_null_engine->DeviceBytes();
|
||||
}
|
||||
// The rigid body's engines are sized for the most observations a fit gives its finest zone,
|
||||
// counted as the zones count them: by the resolution of the index once it is in the model's
|
||||
// ASU, under each indexing the data may be placed in. The model's group need not keep the
|
||||
// data's metric - a wrong model's cubic group on an orthorhombic cell sends h to an index of
|
||||
// another resolution - so the data's own d can put a reflection on the wrong side of the zone.
|
||||
const double finest_zone = RigidBodyLadder(d_min).back();
|
||||
const gemmi::GroupOps zone_gops = sg->operations();
|
||||
const gemmi::ReciprocalAsu zone_asu(sg);
|
||||
auto in_finest_zone = [&](const std::vector<MergedReflection> &v) {
|
||||
size_t n = 0;
|
||||
for (const MergedReflection &r : v)
|
||||
if (!std::isnan(r.F) && ucell.calculate_d(zone_asu.to_asu({r.h, r.k, r.l}, zone_gops).first) >= finest_zone)
|
||||
++n;
|
||||
return n;
|
||||
};
|
||||
size_t zone_observations = in_finest_zone(obs);
|
||||
for (const gemmi::Op &law : reindex_ops)
|
||||
zone_observations = std::max(zone_observations, in_finest_zone(ReindexReflections(obs, law)));
|
||||
rigid_body_engines = RigidBodyGPUPool::Plan(st.models[0], ucell, *sg, d_min, zone_observations, logger);
|
||||
if (rigid_body_engines) {
|
||||
need.rigid_body = rigid_body_engines->EngineBytes();
|
||||
// One for the real model and one for each replicate of the null placed beside it.
|
||||
need.rigid_body_engines = std::min<size_t>(std::max<size_t>(nthreads, 1), NULL_REPLICATES) + 1;
|
||||
}
|
||||
// For as many reflections as the data have.
|
||||
need.scale_fit = ModelScaleGPUPool::DeviceBytes(obs.size(), 1);
|
||||
need.scale_fit_engines = SCALE_GPU_ENGINES;
|
||||
|
||||
gpu_plan = PlanModelValidationGPU(need, static_cast<size_t>(get_gpu_count()));
|
||||
gpu_bytes = gpu_plan.bytes;
|
||||
may_run_beside = gpu_plan.may_run_beside;
|
||||
|
||||
std::string parts;
|
||||
auto part = [&](const std::string &what, bool on_gpu, size_t bytes, size_t engines) {
|
||||
if (bytes == 0)
|
||||
return; // no such part, or one the GPU cannot grid (logged where that was found)
|
||||
parts += fmt::format("{}{} on the ", parts.empty() ? "" : ", ", what);
|
||||
if (!on_gpu)
|
||||
parts += fmt::format("CPU ({} do not fit)", GBytes(bytes));
|
||||
else if (engines > 0)
|
||||
parts += fmt::format("GPU ({} x {})", engines, GBytes(bytes));
|
||||
else
|
||||
parts += fmt::format("GPU ({})", GBytes(bytes));
|
||||
};
|
||||
part(fmt::format("structure factors to {:.2f} A", d_min), gpu_plan.structure_factors,
|
||||
need.structure_factors, 0);
|
||||
part(fmt::format("the null's to {:.2f} A", null_d_min), gpu_plan.null_structure_factors,
|
||||
need.null_structure_factors, 0);
|
||||
part("rigid body", gpu_plan.rigid_body_engines > 0, need.rigid_body, gpu_plan.rigid_body_engines);
|
||||
part("scale fits", gpu_plan.scale_fit_engines > 0, need.scale_fit, gpu_plan.scale_fit_engines);
|
||||
logger.Info("Model validation: {} - {} held of a {} budget, 80% of the card's {}{}{}", parts,
|
||||
GBytes(gpu_plan.bytes), GBytes(gpu_plan.budget), GBytes(need.card),
|
||||
need.resident > 0 ? fmt::format(" less {} held by the merge", GBytes(need.resident)) : "",
|
||||
need.beside > 0 ? fmt::format("; {} held by a validation beside", GBytes(need.beside)) : "");
|
||||
|
||||
if (!gpu_plan.structure_factors)
|
||||
sf_engine.reset();
|
||||
if (!gpu_plan.null_structure_factors)
|
||||
sf_null_engine.reset();
|
||||
if (sf_engine)
|
||||
Reserve(*sf_engine);
|
||||
if (sf_null_engine)
|
||||
Reserve(*sf_null_engine);
|
||||
}
|
||||
sf_gpu = sf_engine.get();
|
||||
sf_null = sf_null_engine.get();
|
||||
#else
|
||||
(void) rigid_body_gpu;
|
||||
#endif
|
||||
|
||||
// --- Fcalc (atomic) via electron density on a grid + FFT, plus a flat bulk-solvent mask -> Fmask.
|
||||
@@ -840,42 +921,23 @@ ModelValidationResult Validate(const std::vector<MergedReflection> &merged,
|
||||
.prepare_asu_data(dc.d_min, dc.blur, false, false, false);
|
||||
ms.fmask = fmask.get();
|
||||
};
|
||||
// The model's structure factors are made beside the reservation of the GPU engines below, which
|
||||
// does not need them.
|
||||
// The model's structure factors are made beside the reservation of the rigid body's and the scale
|
||||
// fits' engines below, which does not need them.
|
||||
std::future<void> model_factors = std::async(std::launch::async, [&] { compute_model_factors(mdl, d_min); });
|
||||
|
||||
// The rigid body's device, decided once for the whole validation - the real fit and every replicate
|
||||
// of the null on the same one, so that a verdict never depends on how full the card was when a
|
||||
// replicate started. The engines are reserved here, up front, and never grow.
|
||||
RigidBodyGPUPool *rigid_body_pool = nullptr;
|
||||
#ifdef JFJOCH_USE_CUDA
|
||||
std::unique_ptr<RigidBodyGPUPool> rigid_body_engines;
|
||||
if (rigid_body_gpu) {
|
||||
// Counted as the zones count them: by the resolution of the index once it is in the model's
|
||||
// ASU, under each indexing the data may be placed in. The model's group need not keep the
|
||||
// data's metric - a wrong model's cubic group on an orthorhombic cell sends h to an index of
|
||||
// another resolution - so the data's own d can put a reflection on the wrong side of the zone.
|
||||
const double finest_zone = RigidBodyLadder(d_min).back();
|
||||
const gemmi::GroupOps zone_gops = sg->operations();
|
||||
const gemmi::ReciprocalAsu zone_asu(sg);
|
||||
auto in_finest_zone = [&](const std::vector<MergedReflection> &v) {
|
||||
size_t n = 0;
|
||||
for (const MergedReflection &r : v)
|
||||
if (!std::isnan(r.F) && ucell.calculate_d(zone_asu.to_asu({r.h, r.k, r.l}, zone_gops).first) >= finest_zone)
|
||||
++n;
|
||||
return n;
|
||||
};
|
||||
size_t zone_observations = in_finest_zone(obs);
|
||||
for (const gemmi::Op &law : reindex_ops)
|
||||
zone_observations = std::max(zone_observations, in_finest_zone(ReindexReflections(obs, law)));
|
||||
// One engine for the real model and one for each replicate of the null placed beside it.
|
||||
rigid_body_engines = RigidBodyGPUPool::Create(st.models[0], ucell, *sg, d_min, zone_observations,
|
||||
std::min<size_t>(std::max<size_t>(nthreads, 1), NULL_REPLICATES) + 1,
|
||||
logger);
|
||||
if (rigid_body_engines && gpu_plan.rigid_body_engines > 0) {
|
||||
rigid_body_engines->Reserve(gpu_plan.rigid_body_engines);
|
||||
rigid_body_pool = rigid_body_engines.get();
|
||||
}
|
||||
#else
|
||||
(void) rigid_body_gpu;
|
||||
if (gpu_plan.scale_fit_engines > 0) {
|
||||
try {
|
||||
scale_gpu = std::make_unique<ModelScaleGPUPool>(RigidBodyGPUEngine::CurrentDevice(), obs.size(),
|
||||
gpu_plan.scale_fit_engines);
|
||||
} catch (const JFJochException &e) {
|
||||
throw RigidBodyGPUFailure(e.what());
|
||||
}
|
||||
}
|
||||
#endif
|
||||
model_factors.get();
|
||||
|
||||
@@ -1092,36 +1154,13 @@ ModelValidationResult Validate(const std::vector<MergedReflection> &merged,
|
||||
// not place is searched for by molecular replacement instead (Rugnux). Only a validation whose
|
||||
// verdict is taken from another one (KeepModelVerdict), or that is not wanted (a placement already
|
||||
// judged elsewhere, scored for its maps), skips it.
|
||||
const bool decision_pending = schedule.fit_test;
|
||||
if (schedule.on_forecast) {
|
||||
// Two validations at once take twice the engines, and are allowed where twice what this one plans -
|
||||
// its rigid-body engines, its structure-factor engine and, where a null is coming, the null's,
|
||||
// which is no larger - fits half of the cards' memory taken together (see StructureFactorsGPU).
|
||||
bool may_run_beside = true;
|
||||
#ifdef JFJOCH_USE_CUDA
|
||||
size_t planned = 0, card = 0;
|
||||
if (rigid_body_pool != nullptr) {
|
||||
planned += rigid_body_pool->PlannedBytes();
|
||||
card = rigid_body_pool->CardBytes();
|
||||
}
|
||||
if (sf_gpu != nullptr) {
|
||||
planned += (decision_pending ? 2 : 1) * sf_gpu->DeviceBytes();
|
||||
card = sf_gpu->DeviceTotalMemory();
|
||||
}
|
||||
if (scale_gpu) {
|
||||
planned += scale_gpu->Bytes();
|
||||
card = get_gpu_total_memory(RigidBodyGPUEngine::CurrentDevice());
|
||||
}
|
||||
if (planned > 0)
|
||||
may_run_beside = 2 * planned <= static_cast<size_t>(get_gpu_count()) * card / 2;
|
||||
#endif
|
||||
// A second validation is allowed beside this one where PlanModelValidationGPU says it fits.
|
||||
if (schedule.on_forecast)
|
||||
schedule.on_forecast({result.change_of_basis_op, indexing.op, result.model_enantiomorph_candidate,
|
||||
may_run_beside});
|
||||
}
|
||||
may_run_beside, gpu_bytes});
|
||||
std::vector<gemmi::Mat33> equivalent; // the orientations the crystal cannot tell from the model's
|
||||
double reach_deg = 0;
|
||||
std::vector<gemmi::Mat33> null_rotation;
|
||||
double null_d_min = d_min;
|
||||
std::vector<MergedReflection> obs_null;
|
||||
if (decision_pending) {
|
||||
// --- the null: this model, this data, in random orientations ---
|
||||
@@ -1181,36 +1220,10 @@ ModelValidationResult Validate(const std::vector<MergedReflection> &merged,
|
||||
"({:.1f} deg) of an orientation equivalent to the model's, and were drawn again",
|
||||
redraws, reach_deg);
|
||||
}
|
||||
// The null and the side of the real fit it is compared with are both scored to NULL_D_MIN,
|
||||
// not to the data's resolution. The placement already stops there (RigidBodyRefine's ladder
|
||||
// ends at 3.5 A), and whether a model is in the right orientation, or the data in its
|
||||
// indexing, is decided at low resolution: the finer shells only add reflections to the scale
|
||||
// fits, which were most of the null's cost. Both sides go through the same fits on the same
|
||||
// reflections, so the comparison stays like for like. On a small cell 3.5 A leaves too few
|
||||
// free reflections for a real indexing margin to be told from a random placement's, so the
|
||||
// limit then moves out to where NULL_MIN_FREE of them are - to the data's own on the
|
||||
// smallest, which are the cheap ones.
|
||||
std::vector<float> free_d;
|
||||
for (const MergedReflection &r : obs)
|
||||
if (r.rfree_flag && !std::isnan(r.F))
|
||||
free_d.push_back(r.d);
|
||||
std::sort(free_d.begin(), free_d.end(), std::greater<>());
|
||||
null_d_min = std::max(d_min, NULL_D_MIN);
|
||||
if (free_d.size() < NULL_MIN_FREE)
|
||||
null_d_min = d_min;
|
||||
else
|
||||
null_d_min = std::min<double>(null_d_min, free_d[NULL_MIN_FREE - 1]);
|
||||
// Scored to null_d_min (above), on its own structure-factor engine where that is not d_min.
|
||||
for (const MergedReflection &r : obs)
|
||||
if (r.d >= null_d_min)
|
||||
obs_null.push_back(r);
|
||||
#ifdef JFJOCH_USE_CUDA
|
||||
// On the card the d_min engine is on; the replicates' threads may sit on other cards, and each
|
||||
// call works on the engine's own device. Where the null is scored to d_min it shares that engine.
|
||||
if (sf_gpu != nullptr && null_d_min != d_min)
|
||||
sf_null_engine = StructureFactorsGPU(sf_gpu->Device(), st.models[0], ucell, *sg, null_d_min,
|
||||
sf_gpu->DeviceBytes(), logger);
|
||||
sf_null = sf_null_engine.get();
|
||||
#endif
|
||||
}
|
||||
const gemmi::Structure null_model = st; // the model as read, which the replicates are made from
|
||||
// Each replicate works on its own copy of the model as read and of its structure factors, and the
|
||||
@@ -1264,7 +1277,7 @@ ModelValidationResult Validate(const std::vector<MergedReflection> &merged,
|
||||
for (size_t t = 0; t < std::min<size_t>(std::max<size_t>(nthreads, 1), NULL_REPLICATES); t++)
|
||||
replicate_threads.push_back(std::async(std::launch::async, [&, t] {
|
||||
// Each on a card in turn from the one after the real fit's, which its engines are
|
||||
// spread the same way over (RigidBodyGPUPool::Create).
|
||||
// spread the same way over (RigidBodyGPUPool::Reserve).
|
||||
#ifdef JFJOCH_USE_CUDA
|
||||
if (rigid_body_pool != nullptr)
|
||||
pin_gpu((rigid_body_pool->Device() + 1 + static_cast<int>(t)) % get_gpu_count());
|
||||
@@ -1870,6 +1883,38 @@ ModelValidationResult Validate(const std::vector<MergedReflection> &merged,
|
||||
|
||||
} // namespace
|
||||
|
||||
ModelValidationGPUPlan PlanModelValidationGPU(const ModelValidationGPUNeed &need, size_t cards) {
|
||||
ModelValidationGPUPlan plan;
|
||||
const size_t usable = need.card / 5 * 4;
|
||||
plan.budget = usable > need.resident ? usable - need.resident : 0;
|
||||
auto take = [&](size_t bytes, size_t limit) {
|
||||
if (bytes == 0 || plan.bytes + bytes > limit)
|
||||
return false;
|
||||
plan.bytes += bytes;
|
||||
return true;
|
||||
};
|
||||
plan.structure_factors = take(need.structure_factors, plan.budget);
|
||||
plan.rigid_body_engines = need.rigid_body_engines > 0 && take(need.rigid_body, plan.budget) ? 1 : 0;
|
||||
plan.null_structure_factors = take(need.null_structure_factors, plan.budget);
|
||||
plan.scale_fit_engines = need.scale_fit_engines > 0 && take(need.scale_fit, plan.budget) ? 1 : 0;
|
||||
|
||||
// More engines only within half of the budget (see the declaration).
|
||||
const size_t room = std::min(plan.budget / 2, plan.budget > need.beside ? plan.budget - need.beside : 0);
|
||||
while (plan.rigid_body_engines > 0 && plan.rigid_body_engines < need.rigid_body_engines
|
||||
&& take(need.rigid_body, room))
|
||||
plan.rigid_body_engines++;
|
||||
while (plan.scale_fit_engines > 0 && plan.scale_fit_engines < need.scale_fit_engines
|
||||
&& take(need.scale_fit, room))
|
||||
plan.scale_fit_engines++;
|
||||
|
||||
const size_t whole = (plan.structure_factors ? need.structure_factors : 0)
|
||||
+ (plan.null_structure_factors ? need.null_structure_factors : 0)
|
||||
+ (plan.rigid_body_engines > 0 ? need.rigid_body * need.rigid_body_engines : 0)
|
||||
+ (plan.scale_fit_engines > 0 ? need.scale_fit * need.scale_fit_engines : 0);
|
||||
plan.may_run_beside = 2 * whole <= cards * plan.budget;
|
||||
return plan;
|
||||
}
|
||||
|
||||
ModelValidationResult ValidateAgainstModel(const std::vector<MergedReflection> &merged,
|
||||
const UnitCell &cell,
|
||||
const std::string &model_path,
|
||||
@@ -1973,8 +2018,17 @@ ModelValidationResult ReadModelAnomalousMap(const std::vector<MergedReflection>
|
||||
ModelStructureFactorsGPU *gpu = nullptr;
|
||||
#ifdef JFJOCH_USE_CUDA
|
||||
std::unique_ptr<ModelStructureFactorsGPU> engine;
|
||||
// Read beside molecular replacement's engines, which keep to a quarter of the card
|
||||
// (MolecularReplacement.cpp), so on the GPU where it fits a quarter as well.
|
||||
if (get_gpu_count() > 0)
|
||||
engine = StructureFactorsGPU(RigidBodyGPUEngine::CurrentDevice(), st.models[0], st.cell, *sg, d_min, 0, logger);
|
||||
engine = StructureFactorsEngine(RigidBodyGPUEngine::CurrentDevice(), st.models[0], st.cell, *sg, d_min, logger);
|
||||
if (engine && engine->DeviceBytes() > engine->DeviceTotalMemory() / 4) {
|
||||
logger.Info("Model validation: structure factors to {:.2f} A on the CPU - {} of GPU memory, over a quarter "
|
||||
"of the card's {}", d_min, GBytes(engine->DeviceBytes()), GBytes(engine->DeviceTotalMemory()));
|
||||
engine.reset();
|
||||
}
|
||||
if (engine)
|
||||
Reserve(*engine);
|
||||
gpu = engine.get();
|
||||
if (gpu != nullptr) {
|
||||
try {
|
||||
|
||||
@@ -257,9 +257,10 @@ struct ModelFrameForecast {
|
||||
gemmi::Op change_of_basis_op = gemmi::Op::identity();
|
||||
gemmi::Op indexing_op = gemmi::Op::identity();
|
||||
bool enantiomorph_candidate = false;
|
||||
// Whether a second validation of this size may run beside this one: decided on the sizes of its
|
||||
// GPU engines against the memory of the cards, never on what happens to be free.
|
||||
// Whether a second validation of this size may run beside this one (ModelValidationGPUPlan), and
|
||||
// what this one holds on its card meanwhile - which the second is given as gpu_beside_bytes.
|
||||
bool may_run_beside = true;
|
||||
size_t gpu_bytes = 0;
|
||||
};
|
||||
|
||||
struct ModelValidationSchedule {
|
||||
@@ -273,8 +274,54 @@ struct ModelValidationSchedule {
|
||||
// The null that says whether the model fits. False where the verdict is another validation's
|
||||
// (KeepModelVerdict) or was reached elsewhere (a molecular-replacement placement, scored for its maps).
|
||||
bool fit_test = true;
|
||||
// GPU memory held on the card for as long as the validation runs by what came before it (a merge
|
||||
// engine still at work beside it): counted against the card when what goes on the GPU is decided.
|
||||
size_t gpu_resident_bytes = 0;
|
||||
// GPU memory another validation running beside this one holds there. It limits how many engines
|
||||
// this one takes and never what runs on the GPU, so no number depends on whether the other runs.
|
||||
size_t gpu_beside_bytes = 0;
|
||||
};
|
||||
|
||||
// What a model validation needs of its card, part by part: the bytes of one engine of each, how many
|
||||
// engines of it the validation can use, and what else is on the card. 0 bytes: that part cannot run on
|
||||
// the GPU (the cell is too small for its gridding), or there is none (the null's structure factors
|
||||
// where the null is scored to the data's own resolution and shares the engine to d_min).
|
||||
struct ModelValidationGPUNeed {
|
||||
size_t card = 0; // the card's total memory
|
||||
size_t resident = 0; // ModelValidationSchedule::gpu_resident_bytes
|
||||
size_t beside = 0; // ModelValidationSchedule::gpu_beside_bytes
|
||||
size_t structure_factors = 0; // to the data's resolution, with the maps
|
||||
size_t null_structure_factors = 0; // to the null's coarser limit
|
||||
size_t rigid_body = 0;
|
||||
size_t rigid_body_engines = 0;
|
||||
size_t scale_fit = 0;
|
||||
size_t scale_fit_engines = 0;
|
||||
};
|
||||
|
||||
struct ModelValidationGPUPlan {
|
||||
size_t budget = 0; // 80% of the card, less what is resident there
|
||||
bool structure_factors = false;
|
||||
bool null_structure_factors = false;
|
||||
size_t rigid_body_engines = 0; // 0: the rigid body on the CPU
|
||||
size_t scale_fit_engines = 0; // 0: the scale fits on the CPU
|
||||
size_t bytes = 0; // what the plan holds on the card
|
||||
bool may_run_beside = false;
|
||||
};
|
||||
|
||||
// The one rule for what a validation puts on its GPU, decided before anything is reserved, from the
|
||||
// card's TOTAL memory and never from what is free at the moment, so the same input on the same card
|
||||
// always runs the same way. Everything the validation holds is alive at once - the engines are reserved
|
||||
// up front and kept to the end - so it is their sum that is held against the budget, 80% of the card
|
||||
// less what is resident. Each part takes one engine where it still fits, in the order of what it saves:
|
||||
// the structure factors to d_min, the rigid body, the null's structure factors, the scale fits; a part
|
||||
// that does not fit runs on the CPU. More rigid-body engines and then more scale-fit engines are added
|
||||
// only within half of the budget, less what a validation beside holds: they change only how many fits
|
||||
// run at once, and buy little - on a large cell a fit already fills the card (measured on a 16 GB card:
|
||||
// 13.6 s with one rigid-body engine, 13.1 s with two, 12.6 s with five) - so the card keeps headroom
|
||||
// rather than filling with them. A second validation may run beside where twice the whole of this one's GPU parts, at every
|
||||
// engine it can use, fits the budgets of the cards together.
|
||||
ModelValidationGPUPlan PlanModelValidationGPU(const ModelValidationGPUNeed &need, size_t cards = 1);
|
||||
|
||||
ModelValidationResult ValidateAgainstModel(const std::vector<MergedReflection> &merged,
|
||||
const UnitCell &cell,
|
||||
const std::string &model_path,
|
||||
|
||||
@@ -127,10 +127,9 @@ bool SameObservations(const gemmi::AsuData<gemmi::ValueSigma<float>> &a,
|
||||
|
||||
} // namespace
|
||||
|
||||
std::unique_ptr<RigidBodyGPUPool> RigidBodyGPUPool::Create(const gemmi::Model &model, const gemmi::UnitCell &cell,
|
||||
const gemmi::SpaceGroup &sg, double d_min,
|
||||
size_t max_observations, size_t max_engines,
|
||||
Logger &logger) {
|
||||
std::unique_ptr<RigidBodyGPUPool> RigidBodyGPUPool::Plan(const gemmi::Model &model, const gemmi::UnitCell &cell,
|
||||
const gemmi::SpaceGroup &sg, double d_min,
|
||||
size_t max_observations, Logger &logger) {
|
||||
if (get_gpu_count() == 0)
|
||||
return nullptr;
|
||||
try {
|
||||
@@ -155,40 +154,54 @@ std::unique_ptr<RigidBodyGPUPool> RigidBodyGPUPool::Create(const gemmi::Model &m
|
||||
cap.observations = max_observations;
|
||||
cap.rows = max_observations;
|
||||
cap.terms = max_observations * ops;
|
||||
const size_t bytes = RigidBodyGPUEngine::DeviceBytes(cap);
|
||||
|
||||
// A quarter of the card's TOTAL memory - the validation's plan (StructureFactorsGPU) - and not what
|
||||
// happens to be free: the same input on the same card always gets the same engines. A card that
|
||||
// is merely busy is waited for by the engines' allocations, never left for the CPU.
|
||||
const int device = RigidBodyGPUEngine::CurrentDevice();
|
||||
const size_t total = get_gpu_total_memory(device);
|
||||
const size_t budget = total / 4;
|
||||
const size_t fit = bytes > 0 ? budget / bytes : 0;
|
||||
const size_t want = std::min<size_t>(fit, std::max<size_t>(max_engines, 1));
|
||||
// Engine i on the i-th card from the calling thread's, so a validation uses every card there is;
|
||||
// the engines give the same bits on any card of one model, so this changes only where they run.
|
||||
const int cards = get_gpu_count();
|
||||
pool->device_ = device;
|
||||
pool->planned_bytes_ = bytes * std::max<size_t>(max_engines, 1);
|
||||
pool->card_bytes_ = total;
|
||||
for (size_t i = 0; i < want; i++)
|
||||
pool->engines_.push_back(std::make_unique<RigidBodyGPUEngine>(cap, (device + static_cast<int>(i)) % cards));
|
||||
set_gpu(device); // each engine was made on its own card
|
||||
if (pool->engines_.empty()) {
|
||||
logger.Info("Model validation: the rigid body runs on the CPU - one GPU engine needs {:.0f} MB, over a "
|
||||
"quarter of the card's {:.0f} MB", bytes / 1e6, total / 1e6);
|
||||
return nullptr;
|
||||
}
|
||||
for (auto &e : pool->engines_)
|
||||
pool->idle_.push_back(e.get());
|
||||
logger.Info("Model validation: the rigid body runs on the GPU, {} engine(s) of {:.0f} MB", pool->Engines(),
|
||||
bytes / 1e6);
|
||||
pool->cap_ = std::make_unique<RigidBodyGPUCapacity>(cap);
|
||||
pool->device_ = RigidBodyGPUEngine::CurrentDevice();
|
||||
return pool;
|
||||
} catch (const JFJochException &e) {
|
||||
throw RigidBodyGPUFailure(e.what());
|
||||
}
|
||||
}
|
||||
|
||||
size_t RigidBodyGPUPool::EngineBytes() const {
|
||||
return RigidBodyGPUEngine::DeviceBytes(*cap_);
|
||||
}
|
||||
|
||||
void RigidBodyGPUPool::Reserve(size_t engines) {
|
||||
// The engines give the same bits on any card of one model, so where they are changes only where they run.
|
||||
// A card that is merely busy is waited for by the engines' allocations, never left for the CPU.
|
||||
try {
|
||||
const int cards = get_gpu_count();
|
||||
for (size_t i = 0; i < engines; i++)
|
||||
engines_.push_back(std::make_unique<RigidBodyGPUEngine>(*cap_, (device_ + static_cast<int>(i)) % cards));
|
||||
set_gpu(device_); // each engine was made on its own card
|
||||
} catch (const JFJochException &e) {
|
||||
throw RigidBodyGPUFailure(e.what());
|
||||
}
|
||||
for (auto &e : engines_)
|
||||
idle_.push_back(e.get());
|
||||
}
|
||||
|
||||
std::unique_ptr<RigidBodyGPUPool> RigidBodyGPUPool::Create(const gemmi::Model &model, const gemmi::UnitCell &cell,
|
||||
const gemmi::SpaceGroup &sg, double d_min,
|
||||
size_t max_observations, size_t max_engines,
|
||||
Logger &logger) {
|
||||
std::unique_ptr<RigidBodyGPUPool> pool = Plan(model, cell, sg, d_min, max_observations, logger);
|
||||
if (!pool)
|
||||
return nullptr;
|
||||
const size_t bytes = pool->EngineBytes();
|
||||
const size_t total = get_gpu_total_memory(pool->device_);
|
||||
const size_t fit = bytes > 0 ? total / 4 / bytes : 0;
|
||||
if (fit == 0) {
|
||||
logger.Info("Model validation: the rigid body runs on the CPU - one GPU engine needs {:.0f} MB, over a "
|
||||
"quarter of the card's {:.0f} MB", bytes / 1e6, total / 1e6);
|
||||
return nullptr;
|
||||
}
|
||||
pool->Reserve(std::min<size_t>(fit, std::max<size_t>(max_engines, 1)));
|
||||
logger.Info("Model validation: the rigid body runs on the GPU, {} engine(s) of {:.0f} MB", pool->Engines(),
|
||||
bytes / 1e6);
|
||||
return pool;
|
||||
}
|
||||
|
||||
RigidBodyGPUPool::~RigidBodyGPUPool() = default;
|
||||
|
||||
std::shared_ptr<const RigidBodyGPUZone> RigidBodyGPUPool::ObservedZone(
|
||||
|
||||
@@ -23,6 +23,7 @@
|
||||
class Logger;
|
||||
class RigidBodyGPUEngine;
|
||||
struct RigidBodyGPUZone;
|
||||
struct RigidBodyGPUCapacity;
|
||||
|
||||
// A CUDA failure inside the rigid body, or in model validation's structure factors and maps
|
||||
// (ModelStructureFactorsGPU). Model validation catches it and reports the validation as failed.
|
||||
@@ -39,23 +40,27 @@ public:
|
||||
// radii, which the placement does not change - is worked out once per zone and kept.
|
||||
class RigidBodyGPUPool {
|
||||
public:
|
||||
// Null where there is no GPU, where not even one engine fits the budget - a quarter of the card's
|
||||
// total memory - or where the cell is too small for the gather (an atom's box wider than the cell).
|
||||
// Logged either way. Engines that cannot be set up throw RigidBodyGPUFailure.
|
||||
// A pool without engines yet, sized for the finest zone of the ladder to d_min: EngineBytes() is
|
||||
// what each engine will take, so a caller can decide how many first. Null where there is no GPU or
|
||||
// where the cell is too small for the gather (an atom's box wider than the cell), logged.
|
||||
// `max_observations`: the most working reflections any fit will be given in its finest zone.
|
||||
// `max_engines`: at most this many, however much memory there is.
|
||||
static std::unique_ptr<RigidBodyGPUPool> Plan(const gemmi::Model &model, const gemmi::UnitCell &cell,
|
||||
const gemmi::SpaceGroup &sg, double d_min,
|
||||
size_t max_observations, Logger &logger);
|
||||
// Plan(), then as many engines as fit a quarter of the card's total memory, at most `max_engines`
|
||||
// (molecular replacement's rule). Null, logged, where not even one fits.
|
||||
static std::unique_ptr<RigidBodyGPUPool> Create(const gemmi::Model &model, const gemmi::UnitCell &cell,
|
||||
const gemmi::SpaceGroup &sg, double d_min,
|
||||
size_t max_observations, size_t max_engines, Logger &logger);
|
||||
~RigidBodyGPUPool();
|
||||
|
||||
size_t EngineBytes() const;
|
||||
// Reserves `engines` engines, engine i on the i-th card from Device(), so a validation uses every
|
||||
// card there is. Engines that cannot be set up throw RigidBodyGPUFailure.
|
||||
void Reserve(size_t engines);
|
||||
size_t Engines() const { return engines_.size(); }
|
||||
// The card the pool was made from, which its first engine is on and the others count on from.
|
||||
int Device() const { return device_; }
|
||||
// What max_engines engines take, however many fitted, and the memory of the card: the sizes a
|
||||
// caller decides by whether a second validation may run beside this one.
|
||||
size_t PlannedBytes() const { return planned_bytes_; }
|
||||
size_t CardBytes() const { return card_bytes_; }
|
||||
RigidBodyGPUEngine &Acquire();
|
||||
void Release(RigidBodyGPUEngine &engine);
|
||||
|
||||
@@ -72,8 +77,7 @@ public:
|
||||
private:
|
||||
RigidBodyGPUPool() = default;
|
||||
int device_ = 0;
|
||||
size_t planned_bytes_ = 0;
|
||||
size_t card_bytes_ = 0;
|
||||
std::unique_ptr<RigidBodyGPUCapacity> cap_;
|
||||
std::vector<std::unique_ptr<RigidBodyGPUEngine>> engines_;
|
||||
std::vector<RigidBodyGPUEngine *> idle_;
|
||||
std::mutex m_;
|
||||
|
||||
@@ -1162,7 +1162,7 @@ bool Rugnux::ScaleMergeAndSymmetry(PipelineLocals &p) {
|
||||
// free: the answer must not depend on the moment. What else stays on the card meanwhile - the
|
||||
// context, the run's indexers - was measured at up to 2.3 GB; a speculative pass running beside
|
||||
// holds more, but a merge that does not fit beside it waits for it to end. On a 16 GB card that
|
||||
// is the data sets up to about 70 M observations at high multiplicity; the large ones merge
|
||||
// is the data sets up to about 90 M observations at high multiplicity; the large ones merge
|
||||
// their arms one after the other.
|
||||
if (!geometry_prepass && !experiment_.GetGemmiSpaceGroup().has_value() && rsm->GetSearchMinZeta() > 0.0
|
||||
&& cards > 0 && rsm->OnGPU()) {
|
||||
@@ -3996,6 +3996,16 @@ bool Rugnux::ScaleMergeAndSymmetry(PipelineLocals &p) {
|
||||
// for by molecular replacement below.
|
||||
bool placed_by_rigid_body = false;
|
||||
bool twin_chosen_by_model = false;
|
||||
// Nothing indexes after the merge, so the image pass's indexers - an FFT indexer keeps its transform
|
||||
// buffers and histograms on the card, 0.8 GB for the two of a rotation run - go before the model is
|
||||
// validated or searched for, once the leftover-lattice census, the last to use them, has ended.
|
||||
if (model_run) {
|
||||
if (census_future.valid()) {
|
||||
TimingMark census_mark(logger, "leftover-lattice census wait (model)");
|
||||
census_future.wait();
|
||||
}
|
||||
p.indexer_pool.reset();
|
||||
}
|
||||
if (model_run && !model_predicted && !config_.force_mr) {
|
||||
phase("Validating against model");
|
||||
Step("Model validation");
|
||||
@@ -4020,7 +4030,16 @@ bool Rugnux::ScaleMergeAndSymmetry(PipelineLocals &p) {
|
||||
std::future<ModelValidationResult> run;
|
||||
std::promise<bool> write; // destroyed before `run`, so a run left waiting on it is released
|
||||
} ahead;
|
||||
// The merge is done with its engine - nothing below reads it but the finalist ledger's P1 merge,
|
||||
// which runs on it beside the validation - so the device memory it holds goes back before the
|
||||
// validation decides, from the card's total, what goes on its GPU. Where the ledger's merge keeps
|
||||
// it, what it holds is counted against the card by every validation here, the same for each, so
|
||||
// that one started on the forecast decides as the one it stands in for would.
|
||||
if (!ledger_ahead.valid())
|
||||
rsm.reset();
|
||||
const size_t merge_on_card = rsm && rsm->OnGPU() ? rsm->DeviceBytes() : 0;
|
||||
ModelValidationSchedule first_schedule;
|
||||
first_schedule.gpu_resident_bytes = merge_on_card;
|
||||
first_schedule.on_forecast = [&](const ModelFrameForecast &f) {
|
||||
if (ahead.run.valid() || !config_.reference_data.empty() || !data_sg.has_value()
|
||||
|| !f.may_run_beside || f.enantiomorph_candidate
|
||||
@@ -4033,7 +4052,7 @@ bool Rugnux::ScaleMergeAndSymmetry(PipelineLocals &p) {
|
||||
friedel = experiment_.GetScalingSettings().GetMergeFriedel(),
|
||||
rfree_fraction = experiment_.GetScalingSettings().GetRfreeFraction(),
|
||||
wavelength = experiment_.GetWavelength_A(),
|
||||
gate = ahead.write.get_future().share()]() mutable {
|
||||
gate = ahead.write.get_future().share(), beside = f.gpu_bytes]() mutable {
|
||||
if (const int32_t cards = get_gpu_count(); cards > 0)
|
||||
pin_gpu(1 % cards);
|
||||
if (!(ahead.indexing_op == gemmi::Op::identity())) {
|
||||
@@ -4053,6 +4072,8 @@ bool Rugnux::ScaleMergeAndSymmetry(PipelineLocals &p) {
|
||||
ModelValidationSchedule schedule;
|
||||
schedule.write_gate = gate;
|
||||
schedule.fit_test = false; // the verdict is the first validation's (KeepModelVerdict)
|
||||
schedule.gpu_resident_bytes = merge_on_card;
|
||||
schedule.gpu_beside_bytes = beside;
|
||||
ahead.merged = std::move(merged);
|
||||
return ValidateAgainstModel(ahead.merged, cell, config_.model_path, config_.output_prefix, ahead.log,
|
||||
in, /*probe_indexing_ambiguity=*/false,
|
||||
@@ -4072,11 +4093,6 @@ bool Rugnux::ScaleMergeAndSymmetry(PipelineLocals &p) {
|
||||
// The ledger's P1 merge (started above) is taken before anything below acts on what the
|
||||
// validation decides: relabelling the outcomes and the group is what it must not see happen.
|
||||
// Every such relabelling reaches the P1 merge afterwards, through merge_to_written.
|
||||
// The merge is done with its engine - nothing below reads it but the finalist ledger's P1 merge,
|
||||
// which runs on it beside the validation - so the device memory it holds goes back before the
|
||||
// validation decides, from the card's total, whether its GPU path fits.
|
||||
if (!ledger_ahead.valid())
|
||||
rsm.reset();
|
||||
ModelValidationResult validation =
|
||||
ValidateAgainstModel(sm.merged, *result.consensus_cell, config_.model_path,
|
||||
config_.output_prefix, logger, data_sg ? &*data_sg : nullptr,
|
||||
@@ -4161,6 +4177,7 @@ bool Rugnux::ScaleMergeAndSymmetry(PipelineLocals &p) {
|
||||
const auto sg_now = experiment_.GetGemmiSpaceGroup();
|
||||
ModelValidationSchedule kept_verdict;
|
||||
kept_verdict.fit_test = false;
|
||||
kept_verdict.gpu_resident_bytes = merge_on_card;
|
||||
remade = ValidateAgainstModel(sm.merged, *result.consensus_cell, config_.model_path,
|
||||
config_.output_prefix, logger,
|
||||
sg_now ? &*sg_now : nullptr,
|
||||
@@ -4204,6 +4221,7 @@ bool Rugnux::ScaleMergeAndSymmetry(PipelineLocals &p) {
|
||||
return twin_r_free(v) < answer_r_free && (!model_twin_only || v.model_fits);
|
||||
};
|
||||
ModelValidationSchedule twin_schedule;
|
||||
twin_schedule.gpu_resident_bytes = merge_on_card;
|
||||
twin_schedule.maps_superseded = [&](const ModelValidationResult &v) { return !maps_from(v); };
|
||||
phase("Validating against model (twin hypothesis)");
|
||||
auto twin_validation = ValidateAgainstModel(
|
||||
|
||||
@@ -112,6 +112,100 @@ ATOM 2 C . CB GLY A 1 12.000 14.000 16.000 1.00 20.00
|
||||
// --model used to call gemmi::read_pdb unconditionally, so a deposited model handed over as mmCIF -
|
||||
// which is how the PDB serves coordinates by default - was refused outright. Both formats now go
|
||||
// through the same reader, which decides on the file's content.
|
||||
namespace {
|
||||
constexpr size_t GB = 1000000000;
|
||||
|
||||
// A validation's parts, sized as a large-cell case measures: structure factors 1.40 GB to d_min and
|
||||
// 0.89 GB to the null's limit, rigid-body engines of 1.88 GB (ten wanted), scale fits of 0.25 GB (four).
|
||||
ModelValidationGPUNeed LargeCellNeed(size_t card) {
|
||||
ModelValidationGPUNeed need;
|
||||
need.card = card;
|
||||
need.structure_factors = 1400000000;
|
||||
need.null_structure_factors = 890000000;
|
||||
need.rigid_body = 1882000000;
|
||||
need.rigid_body_engines = 10;
|
||||
need.scale_fit = 252500000;
|
||||
need.scale_fit_engines = 4;
|
||||
return need;
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("ModelValidation_GPUPlanOnCardSizes", "[ModelValidation]") {
|
||||
size_t last_rb = 0, last_scale = 0;
|
||||
for (size_t card : {8 * GB, 16 * GB, 24 * GB, 128 * GB}) {
|
||||
const ModelValidationGPUPlan plan = PlanModelValidationGPU(LargeCellNeed(card));
|
||||
CAPTURE(card, plan.rigid_body_engines, plan.scale_fit_engines, plan.bytes);
|
||||
CHECK(plan.budget == card / 5 * 4);
|
||||
CHECK(plan.bytes <= plan.budget);
|
||||
// The parts stay on the GPU on every one of these cards; only the engine counts grow with it.
|
||||
CHECK(plan.structure_factors);
|
||||
CHECK(plan.null_structure_factors);
|
||||
CHECK(plan.rigid_body_engines >= std::max<size_t>(last_rb, 1));
|
||||
CHECK(plan.scale_fit_engines >= std::max<size_t>(last_scale, 1));
|
||||
last_rb = plan.rigid_body_engines;
|
||||
last_scale = plan.scale_fit_engines;
|
||||
}
|
||||
// 8 GB, a 6.40 GB budget: one engine of each, 4.42 GB, already over half of it, so no more engines.
|
||||
const ModelValidationGPUPlan small = PlanModelValidationGPU(LargeCellNeed(8 * GB));
|
||||
CHECK(small.rigid_body_engines == 1);
|
||||
CHECK(small.scale_fit_engines == 1);
|
||||
CHECK(small.bytes == size_t(4424500000));
|
||||
// 16 GB, half of the 12.8 GB budget: a second rigid-body engine, 6.31 GB, and no second scale fit.
|
||||
const ModelValidationGPUPlan mid = PlanModelValidationGPU(LargeCellNeed(16 * GB));
|
||||
CHECK(mid.rigid_body_engines == 2);
|
||||
CHECK(mid.scale_fit_engines == 1);
|
||||
CHECK(!small.may_run_beside);
|
||||
// 128 GB: every engine wanted, and room for a second validation of the same size.
|
||||
const ModelValidationGPUPlan large = PlanModelValidationGPU(LargeCellNeed(128 * GB));
|
||||
CHECK(large.rigid_body_engines == 10);
|
||||
CHECK(large.scale_fit_engines == 4);
|
||||
CHECK(large.may_run_beside);
|
||||
}
|
||||
|
||||
TEST_CASE("ModelValidation_GPUPlanPartThatDoesNotFitGoesToTheCPU", "[ModelValidation]") {
|
||||
ModelValidationGPUNeed need = LargeCellNeed(8 * GB);
|
||||
need.structure_factors = 7 * GB; // over the 6.4 GB budget on its own
|
||||
const ModelValidationGPUPlan plan = PlanModelValidationGPU(need);
|
||||
CHECK(!plan.structure_factors);
|
||||
CHECK(plan.null_structure_factors);
|
||||
CHECK(plan.rigid_body_engines >= 1);
|
||||
CHECK(plan.scale_fit_engines >= 1);
|
||||
CHECK(plan.bytes <= plan.budget);
|
||||
|
||||
// A part the GPU cannot grid (0 bytes) is never placed.
|
||||
need = LargeCellNeed(16 * GB);
|
||||
need.null_structure_factors = 0;
|
||||
need.rigid_body = 0;
|
||||
const ModelValidationGPUPlan no_parts = PlanModelValidationGPU(need);
|
||||
CHECK(no_parts.structure_factors);
|
||||
CHECK(!no_parts.null_structure_factors);
|
||||
CHECK(no_parts.rigid_body_engines == 0);
|
||||
}
|
||||
|
||||
TEST_CASE("ModelValidation_GPUPlanBesideChangesOnlyEngines", "[ModelValidation]") {
|
||||
ModelValidationGPUNeed need = LargeCellNeed(24 * GB);
|
||||
const ModelValidationGPUPlan alone = PlanModelValidationGPU(need);
|
||||
need.beside = alone.budget; // another validation holding the whole budget
|
||||
const ModelValidationGPUPlan beside = PlanModelValidationGPU(need);
|
||||
CHECK(beside.structure_factors == alone.structure_factors);
|
||||
CHECK(beside.null_structure_factors == alone.null_structure_factors);
|
||||
CHECK(beside.rigid_body_engines == 1);
|
||||
CHECK(beside.scale_fit_engines == 1);
|
||||
CHECK(alone.rigid_body_engines > 1);
|
||||
|
||||
// What is resident does decide: with most of the card held by a merge, 2.2 GB are left, which take
|
||||
// the structure factors and the scale fits but not the rigid body or the null's structure factors.
|
||||
need = LargeCellNeed(24 * GB);
|
||||
need.resident = 17 * GB;
|
||||
const ModelValidationGPUPlan full = PlanModelValidationGPU(need);
|
||||
CHECK(full.budget == 24 * GB / 5 * 4 - 17 * GB);
|
||||
CHECK(full.bytes <= full.budget);
|
||||
CHECK(full.structure_factors);
|
||||
CHECK(full.rigid_body_engines == 0);
|
||||
CHECK(!full.null_structure_factors);
|
||||
CHECK(full.scale_fit_engines == 1);
|
||||
}
|
||||
|
||||
TEST_CASE("ModelValidation_ReadsPdbAndMmcif", "[ModelValidation]") {
|
||||
Logger logger("ModelValidation_ReadsPdbAndMmcif");
|
||||
|
||||
|
||||
@@ -97,7 +97,7 @@ TEST_CASE("RotationIngestGPU_SortAndCutMatchHost", "[RotationScale][gpu]") {
|
||||
|
||||
std::vector<double> flux(n_frames);
|
||||
for (int f = 0; f < n_frames; ++f) flux[f] = 0.9 + 0.01 * f;
|
||||
const int n_keep = gpu.IngestSort(flux.data(), d_min, d_max);
|
||||
const int n_keep = gpu.IngestSort(d_min, d_max);
|
||||
|
||||
// The host ingest: one total order, its raw-hkl runs, each with its first usable resolution, and
|
||||
// the runs the range keeps with their observations.
|
||||
@@ -160,6 +160,14 @@ TEST_CASE("RotationIngestGPU_SortAndCutMatchHost", "[RotationScale][gpu]") {
|
||||
s += c;
|
||||
}
|
||||
|
||||
std::vector<float> px(n_keep), py(n_keep);
|
||||
gpu.IngestObservations(ptr.data(), count.data(), 4, flux.data(), px.data(), py.data());
|
||||
for (int i = 0; i < n; ++i)
|
||||
if (keep[i]) {
|
||||
CHECK(px[new_idx[i]] == all[i]->predicted_x);
|
||||
CHECK(py[new_idx[i]] == all[i]->predicted_y);
|
||||
}
|
||||
|
||||
// The rocking events' spans, walked over each run's members in the sorted order, and corr as
|
||||
// integrated in the observations' order (no frame has a mosaicity to recompute partiality from).
|
||||
constexpr float GAP = 1.0f;
|
||||
|
||||
Reference in new issue
Block a user