From 40e2462bde34d4db2f1cb81db705b76f93f883b8 Mon Sep 17 00:00:00 2001 From: Filip Leonarski Date: Sun, 8 Nov 2026 21:49:09 +0100 Subject: [PATCH 1/3] Refinement: the twinned arm runs beside the untwinned one DecideTwin's twinned refinement reads only the placed model and the data, never the untwinned result, so RefineModel now starts it on a thread of its own as soon as the untwinned arm has placed its engine and slots, on the next card where there is more than one. DecideTwin touches the shared result only once the untwinned arm is done, and decides nothing where that arm failed or was cancelled. The twinned arm logs to a buffered logger that is replayed after the untwinned arm's lines, so the log reads as before. The per-stage TIMING sums of the two arms are no longer separated. The engines are made exactly as they would be alone: each arm's GPU/CPU decision uses the same budget as before, and the arms overlap only where twice what the untwinned arm holds of its busiest card fits that budget (OwnSlotPlaces now reports it); otherwise the twinned arm waits for the untwinned one, as before. Trial outcomes do not depend on the slots, so the result is unchanged. Measured on one RTX 5080, -N 28, two runs each (Step 11 wall, s): cytochrome C (P3x21, twin law -h,-k,l): 6.0 / 6.1 -> 4.5 / 4.6 thaumatin, lysozyme (no twin law): unchanged Every output (model, maps, MTZ, report, refinement log lines) is identical to the rc184-port binary on all three sets. With two or more cards the twinned arm gets a card of its own, so the step should drop to about the longer arm (~3.3 s here). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HVeDQsU5a8AJUdJPgWevAK --- .../structure_refinement/Refinement.cpp | 113 +++++++++++++++--- 1 file changed, 95 insertions(+), 18 deletions(-) diff --git a/image_analysis/structure_refinement/Refinement.cpp b/image_analysis/structure_refinement/Refinement.cpp index 0e45bd9ad..184e671ed 100644 --- a/image_analysis/structure_refinement/Refinement.cpp +++ b/image_analysis/structure_refinement/Refinement.cpp @@ -10,6 +10,7 @@ #include #include #include +#include #include #include #include @@ -1633,8 +1634,11 @@ struct SlotPlace { // puts the long trials. A slot takes its engine's own part and a lane of its own where both fit, else its engine // alone on a lane it shares (one evaluation at a time: lanes side by side keep the card busier, more slots overlap // more host work); the first one on another card also the part the engines there share and a scale pool. On the -// CPU, the main one and those beside it are no more than the threads. -std::vector OwnSlotPlaces(const Context &main, int wanted, const RefinementSettings &settings) { +// CPU, the main one and those beside it are no more than the threads. `busiest`: what the main engine and the slots +// hold of the card that holds the most of them (0 on the CPU). +std::vector OwnSlotPlaces(const Context &main, int wanted, const RefinementSettings &settings, + size_t &busiest) { + busiest = 0; #ifdef JFJOCH_USE_CUDA if (main.engine->OnGPU()) { const int n = get_gpu_count(); @@ -1656,6 +1660,7 @@ std::vector OwnSlotPlaces(const Context &main, int wanted, const Refi places.push_back({d, false}); } } + busiest = *std::max_element(used.begin(), used.end()); return places; } #endif @@ -2237,10 +2242,20 @@ double RefinementDMin(double max_inv_d2) { // One refinement of a model, with the solvent build in it where settings.solvent asks for it. // `twin_laws`: against the data as twinned by them (one domain each beside the model's own), empty for untwinned; // `null_first`: the first of them the null (TwinNull) replaces the mates of. +// What a refinement holds of the card that holds the most of it (OwnSlotPlaces), said once (RefineModel). +struct CardHeld { + std::promise bytes; + std::once_flag said; + void Say(size_t b) { + std::call_once(said, [&] { bytes.set_value(b); }); + } +}; + RefinementResult RefineOnce(const gemmi::Structure &placed, const std::vector &merged, const gemmi::UnitCell &cell, const gemmi::SpaceGroup &sg, double wavelength_A, Logger &logger, const RefinementSettings &settings, - const std::vector &twin_laws = {}, size_t null_first = 0) { + const std::vector &twin_laws = {}, size_t null_first = 0, + CardHeld *held = nullptr) { const auto start = std::chrono::steady_clock::now(); RefinementResult result; Context ctx; @@ -2485,8 +2500,10 @@ RefinementResult RefineOnce(const gemmi::Structure &placed, const std::vector 0) wanted = std::min(wanted, static_cast(settings.max_trials_at_once)); - const std::vector devices = settings.restrained ? OwnSlotPlaces(ctx, wanted - 1, settings) - : std::vector(); + size_t busiest = 0; + const std::vector devices = OwnSlotPlaces(ctx, settings.restrained ? wanted - 1 : 0, settings, busiest); + if (held != nullptr) + held->Say(busiest); const size_t slot_threads = std::max(1, settings.nthreads / (devices.size() + 1)); ScalePools pools; #ifdef JFJOCH_USE_CUDA @@ -3297,15 +3314,31 @@ double FinalRWork(const RefinementResult &r) { // standard errors, each added domain at a fraction of TWIN_DOMAIN_MIN at least. void DecideTwin(const gemmi::Structure &placed, const std::vector &merged, const gemmi::UnitCell &cell, const gemmi::SpaceGroup &sg, double wavelength_A, Logger &logger, - const RefinementSettings &settings, RefinementResult &result) { + const RefinementSettings &settings, RefinementResult &result, const std::shared_future &untwinned) { const RefinementStage stage("twin"); - result.untwinned_r_work = FinalRWork(result); - result.untwinned_r_free = FinalRFree(result); const std::vector laws = RefinementTwinLaws(cell, sg); const std::vector domains = RefinementTwinDomains(cell, sg); - result.twin_laws = static_cast(laws.size()); + // The twinned arm reads only the placed model and the data, so it runs beside the untwinned refinement + // (RefineModel): `result` is read and written only once `untwinned` says that refinement is in it, and + // nothing is decided where it failed or was cut short. + std::string split_law; + int split_pairs = 0; + auto take_untwinned = [&]() { + untwinned.wait(); + if (!result.ok || result.cancelled) + return false; + result.untwinned_r_work = FinalRWork(result); + result.untwinned_r_free = FinalRFree(result); + result.twin_laws = static_cast(laws.size()); + if (!split_law.empty()) { + result.twin_law = split_law; + result.twin_split_pairs = split_pairs; + } + return true; + }; if (laws.empty()) { - result.twin_decision = "NO_TWIN_LAW"; + if (take_untwinned()) + result.twin_decision = "NO_TWIN_LAW"; return; } // the laws whose twin pairs the free set keeps together @@ -3318,15 +3351,16 @@ void DecideTwin(const gemmi::Structure &placed, const std::vector 1) { RefinementSettings score = settings; @@ -3342,8 +3376,11 @@ void DecideTwin(const gemmi::Structure &placed, const std::vector &data = moved > 0 ? closed : merged; - RefinementResult result = RefineOnce(placed, data, cell, sg, wavelength_A, logger, settings); // Each arm, untwinned and twinned, is a whole refinement - the solvent built and the displacement model chosen // against its own target - and the decision is taken on where they ended. A model only scored is scored both // ways and decided by the same rule, so the R-free it reports is not an untwinned one by default. - if (settings.twin && result.ok && !result.cancelled) - DecideTwin(placed, data, cell, sg, wavelength_A, logger, settings, result); + // The arms run side by side, the twinned one on the next card where there is more than one, once the untwinned + // one has placed its engines and slots - and where twice what it holds of its busiest card does not fit the + // budget, after it, so that the twinned arm's engines are made as they would be alone. Its log is kept and + // follows the untwinned one's, as when they ran one after the other. + RefinementResult result; + if (!settings.twin) + result = RefineOnce(placed, data, cell, sg, wavelength_A, logger, settings); + else { + Logger twin_logger = Logger::Buffered(); + CardHeld held; + std::future held_bytes = held.bytes.get_future(); + std::promise untwinned_done; + const std::shared_future untwinned = untwinned_done.get_future().share(); + size_t budget = 0; +#ifdef JFJOCH_USE_CUDA + const int twin_card = get_gpu_count() > 1 ? (get_gpu() + 1) % get_gpu_count() : get_gpu(); + if (get_gpu_count() > 0) { + const size_t usable = get_gpu_total_memory(twin_card) / 5 * 4; + budget = usable > settings.gpu_resident_bytes ? usable - settings.gpu_resident_bytes : 0; + } +#endif + std::future twin_arm = std::async(std::launch::async, [&]() { +#ifdef JFJOCH_USE_CUDA + const ScopedGpuPin pin(twin_card); +#endif + if (2 * held_bytes.get() > budget) + untwinned.wait(); + DecideTwin(placed, data, cell, sg, wavelength_A, twin_logger, settings, result, untwinned); + }); + try { + result = RefineOnce(placed, data, cell, sg, wavelength_A, logger, settings, {}, 0, &held); + } catch (...) { + result = RefinementResult(); // not ok: the twinned arm decides nothing + held.Say(0); + untwinned_done.set_value(); + twin_arm.wait(); + throw; + } + held.Say(0); // where it stopped before placing its slots + untwinned_done.set_value(); + twin_arm.get(); + twin_logger.ReplayInto(logger); + } result.twin_free_closed = moved; result.map.reset(); return result; From 8e2d656b487dc2df8e8c7969e4163178bd73aed8 Mon Sep 17 00:00:00 2001 From: Filip Leonarski Date: Sun, 8 Nov 2026 21:49:24 +0100 Subject: [PATCH 2/3] Refinement: the final maps' missing reflections beside the map transforms MakeMaps filled FWT at the reflections the data do not have only after the three map transforms, and MissingReflections computed the atoms' Fcalc (CPU, anisotropic atoms included) and the solvent mask's Fmask one after the other. Neither reads the other: MissingReflections now runs beside the difference and 2mFo-DFc transforms and the anomalous map, and inside it Fcalc runs beside Fmask. Both are serial-heavy (a single-threaded FFTW transform each, the mask's flood fill), so the tail shortens to about the mask alone. Measured on one RTX 5080, -N 28, two runs each (Step 11 wall, s; with the twinned arm beside the untwinned one): thaumatin (anisotropic U chosen): 3.24 / 3.23 -> 3.04 / 3.08 lysozyme: 2.38 / 2.38 -> 2.25 / 2.28 cytochrome C (two arms): 4.53 / 4.58 -> 4.49 / 4.57 Every output (model, maps, MTZ, report, refinement log lines) is identical to the rc184-port binary on all three sets. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HVeDQsU5a8AJUdJPgWevAK --- image_analysis/structure_refinement/Refinement.cpp | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/image_analysis/structure_refinement/Refinement.cpp b/image_analysis/structure_refinement/Refinement.cpp index 184e671ed..7e8034a1e 100644 --- a/image_analysis/structure_refinement/Refinement.cpp +++ b/image_analysis/structure_refinement/Refinement.cpp @@ -1201,9 +1201,11 @@ std::vector MissingReflections(Context &ctx, const gemmi::SMa std::unique_ptr engine = MakeRefinementEngineCPU(ctx.cell, *ctx.sg, ctx.d_min, missing, ctx.nthreads); engine->SetBlur(RefinementBlur(ctx.cell, *ctx.sg, ctx.d_min, ctx.b_floor)); engine->SetAniso(&ctx.aniso); + // the atoms and the solvent side by side: neither reads the other std::vector> fcalc, fmask; - engine->Fcalc(ctx.Model(), fcalc); + std::future atoms = std::async(std::launch::async, [&] { engine->Fcalc(ctx.Model(), fcalc); }); ctx.mask->Fmask(ctx.Model(), missing.hkl, fmask); + atoms.get(); std::vector> d_by_s; // (1/d^2, D) of the observed reflections, by resolution for (size_t m = 0; m < ctx.refl.Size(); m++) @@ -1298,7 +1300,11 @@ void MakeMaps(Context &ctx, const std::vector &merged, double fwt_data.v.push_back({ctx.refl.hkl[m], std::polar(static_cast(fwt), static_cast(phi))}); } result.maps = maps; - // The difference map and the 2mFo-DFc map beside the anomalous one below: none reads another. + // The reflections the data do not have, the difference map and the 2mFo-DFc map beside the anomalous one below: + // none reads another. + std::future> missing = std::async(std::launch::async, [&ctx, &b_aniso] { + return MissingReflections(ctx, b_aniso); + }); const std::array size = gemmi::get_size_for_hkl(diff, {{0, 0, 0}}, 3.0); std::future difference_map = std::async(std::launch::async, [&diff, &size, &result] { result.difference_map = std::make_shared>(MapFromFPhi(gemmi::get_f_phi_on_grid(diff, size, true))); @@ -1354,7 +1360,7 @@ void MakeMaps(Context &ctx, const std::vector &merged, double } // The filled reflections after the observed ones: FWT/PHWT and the model's FC/PHIC, every other column missing. const float nan = std::numeric_limits::quiet_NaN(); - for (const MissingReflection &r : MissingReflections(ctx, b_aniso)) { + for (const MissingReflection &r : missing.get()) { const double phi_deg = std::arg(r.f_model) * 180.0 / PI; const double k_aniso = std::exp(-0.25 * b_aniso.r_u_r(r.hkl)); const float row[] = {static_cast(r.hkl[0]), static_cast(r.hkl[1]), static_cast(r.hkl[2]), nan, From c286e47583f3bb0720e3598f3ddeb5fabe9fc96a Mon Sep 17 00:00:00 2001 From: Filip Leonarski Date: Sun, 8 Nov 2026 22:57:41 +0100 Subject: [PATCH 3/3] Refinement: its GPU modules loaded in the model warm-up, not at Step 11 The intermittent 1.1-2.7 s stall at the start of live refinement (TIMING refine.engine) is the CUDA driver's lazy module load. Stack samples of the broker in a stalled run show the engine's first kernel launch (phase_table_kernel in RefinementGPUCard) inside cuLibraryLoadData for the whole stall, and per-thread /proc samples show the process using no CPU meanwhile: it is waiting for the executable's pages. On this machine the binaries are on a busy, nearly full HDD and the page cache is under pressure, so pages of the executable touched for the first time late in a run - the refinement's fatbin, and in the worst runs other code and data too (refine.topology 0.015 -> 2.5 s, refine.placement 0.15 -> 2.3 s) - can take seconds to come back. Reproduced on purpose: dropping the broker's unmapped pages from the page cache with a 4 GB write to /data beside it gives refine.engine 0.45 / 0.85 s (0.02 s normally). WarmUpModelValidation, which the broker runs when a model is uploaded, now also loads the modules of the refinement engine's and the scale fit's kernels (the two refinement TUs a validation does not launch) on every card. With that, the same induced load gives refine.engine 0.020 / 0.020 / 0.021 s. Other cold pages can still stall under such load; keeping the binaries on a local SSD avoids all of it. Live thau replays, no load added: refine.engine 0.020 s in 3 of 3, refinement 2.9 s (rc184-port 3.1-3.2 s, with the two previous levers in). The warm-up only loads modules, so the results are unchanged (same R-work/R-free and evaluations live; ModelValidation_WarmUpChangesNothing passes). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HVeDQsU5a8AJUdJPgWevAK --- image_analysis/structure_refinement/ModelScaleGPU.cu | 5 +++++ image_analysis/structure_refinement/ModelScaleGPU.h | 2 ++ image_analysis/structure_refinement/ModelValidation.cpp | 8 ++++++++ image_analysis/structure_refinement/RefinementGPU.cu | 7 +++++++ image_analysis/structure_refinement/RefinementGPUEngine.h | 3 +++ 5 files changed, 25 insertions(+) diff --git a/image_analysis/structure_refinement/ModelScaleGPU.cu b/image_analysis/structure_refinement/ModelScaleGPU.cu index 35ebf187f..4c94139fb 100644 --- a/image_analysis/structure_refinement/ModelScaleGPU.cu +++ b/image_analysis/structure_refinement/ModelScaleGPU.cu @@ -402,6 +402,11 @@ size_t ModelScaleGPU::RobustBytes(size_t max_points) { return MAX_ROBUST_FITS * max_points * sizeof(float) + MAX_ROBUST_FITS * sizeof(double); } +void ModelScaleGPU::LoadModule() { + cudaFuncAttributes attributes; + cuda_err(cudaFuncGetAttributes(&attributes, solvent_amplitudes)); +} + size_t ModelScaleGPU::DeviceBytes(size_t max_points) { return max_points * (3 * sizeof(int) + sizeof(double) + sizeof(float) + sizeof(unsigned char)) + MAX_FITS * max_points * sizeof(float) diff --git a/image_analysis/structure_refinement/ModelScaleGPU.h b/image_analysis/structure_refinement/ModelScaleGPU.h index 77cf23be1..7e27934cd 100644 --- a/image_analysis/structure_refinement/ModelScaleGPU.h +++ b/image_analysis/structure_refinement/ModelScaleGPU.h @@ -43,6 +43,8 @@ struct ModelScaleFitState { class ModelScaleGPU { public: static size_t DeviceBytes(size_t max_points); + // The module of its kernels loaded on the current device now, not at their first launch (lazy loading). + static void LoadModule(); ModelScaleGPU(cudaStream_t stream, size_t max_points); // Per zone: the Scaling points in gemmi prepare_points() order, adp_symmetry_constraints(sg) rows diff --git a/image_analysis/structure_refinement/ModelValidation.cpp b/image_analysis/structure_refinement/ModelValidation.cpp index 592974f51..1f8913118 100644 --- a/image_analysis/structure_refinement/ModelValidation.cpp +++ b/image_analysis/structure_refinement/ModelValidation.cpp @@ -51,6 +51,7 @@ #include "../indexing/CUDAMemHelpers.h" // cuda_trim_allocation_pool #include "RigidBodyGPU.h" #include "RigidBodyGPUEngine.h" // RigidBodyGPUEngine::CurrentDevice +#include "RefinementGPUEngine.h" // RefinementGPUEngine::LoadModules #include "../../common/CUDAWrapper.h" #include "../../common/JFJochException.h" #else @@ -2188,6 +2189,13 @@ void WarmUpModelValidation(std::shared_ptr model, size_t nthr const auto start = std::chrono::steady_clock::now(); // Held for as long as it runs: work beside a run waits for it where the card is too small for both. GPUWorkBeside beside; + // The refinement's kernels that a validation does not launch, on every card: lazily their modules would be + // loaded at their first launch, in the refinement, from the executable - 1-3 s in a live run where its + // pages had left the page cache and the disk was busy. + for (int d = 0; d < get_gpu_count(); d++) { + const ScopedGpuPin pin(d); + RefinementGPUEngine::LoadModules(); + } Logger quiet = Logger::Buffered(); if (const SearchModel search = PrepareSearchModel(*model); search.failure_reason.empty() && search.predicted) { std::string failure; diff --git a/image_analysis/structure_refinement/RefinementGPU.cu b/image_analysis/structure_refinement/RefinementGPU.cu index 91f789990..d92c7011f 100644 --- a/image_analysis/structure_refinement/RefinementGPU.cu +++ b/image_analysis/structure_refinement/RefinementGPU.cu @@ -12,6 +12,7 @@ #include "../../common/JFJochException.h" #include "../indexing/CUDAMemHelpers.h" +#include "ModelScaleGPU.h" // ModelScaleGPU::LoadModule namespace { @@ -1015,6 +1016,12 @@ size_t RefinementGPUEngine::DeviceBytes(const RefinementGPUSetup &s, size_t reco return bytes; } +void RefinementGPUEngine::LoadModules() { + cudaFuncAttributes attributes; + cuda_err(cudaFuncGetAttributes(&attributes, phase_table_kernel)); + ModelScaleGPU::LoadModule(); +} + std::shared_ptr RefinementGPUEngine::MakeCard(int device, const RefinementGPUSetup &setup) { DeviceGuard guard(device); return std::make_shared(device, setup); diff --git a/image_analysis/structure_refinement/RefinementGPUEngine.h b/image_analysis/structure_refinement/RefinementGPUEngine.h index 978dc8a23..25cbba952 100644 --- a/image_analysis/structure_refinement/RefinementGPUEngine.h +++ b/image_analysis/structure_refinement/RefinementGPUEngine.h @@ -57,6 +57,9 @@ public: static size_t DeviceBytes(const RefinementGPUSetup &setup, size_t records, size_t slots); static size_t FFTWorkBytes(int device, const RefinementGPUSetup &setup); static std::shared_ptr MakeCard(int device, const RefinementGPUSetup &setup); + // The modules of the engines' kernels and of the scale fit's (ModelScaleGPU) loaded on the current device now: + // lazily the driver loads each at its first launch, reading it from the executable. + static void LoadModules(); // `setup` is read for as long as the engine lives; `card` is MakeCard(device, setup)'s. `own_lane`: on a lane of // working buffers of its own, else on the card's lane with the fewest engines.