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/Refinement.cpp b/image_analysis/structure_refinement/Refinement.cpp index 0e45bd9ad..7e8034a1e 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 @@ -1200,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++) @@ -1297,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))); @@ -1353,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, @@ -1633,8 +1640,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 +1666,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 +2248,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 +2506,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 +3320,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 +3357,16 @@ void DecideTwin(const gemmi::Structure &placed, const std::vector 1) { RefinementSettings score = settings; @@ -3342,8 +3382,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; 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.