Build Packages / build:viewer-tgz:cpu (push) Successful in 8m17s
Build Packages / build:viewer-tgz:cuda (push) Successful in 9m11s
Build Packages / build:rpm (ubuntu2404_nocuda) (push) Successful in 13m38s
Build Packages / build:rpm (rocky8_nocuda) (push) Successful in 13m57s
Build Packages / build:rpm (rocky8_sls9) (push) Successful in 13m57s
Build Packages / build:rpm (ubuntu2204_nocuda) (push) Successful in 14m13s
Build Packages / build:rpm (rocky9_nocuda) (push) Successful in 14m15s
Build Packages / build:rpm (rocky8) (push) Successful in 11m22s
Build Packages / build:rpm (rocky9_sls9) (push) Successful in 12m51s
Build Packages / XDS test (durin plugin) (push) Successful in 7m56s
Build Packages / Generate python client (push) Successful in 32s
Build Packages / Build documentation (push) Successful in 1m4s
Build Packages / Create release (push) Skipped
Build Packages / build:rpm (rocky9) (push) Successful in 13m23s
Build Packages / build:rpm (ubuntu2404) (push) Successful in 13m15s
Build Packages / build:rpm (ubuntu2204) (push) Successful in 13m53s
Build Packages / DIALS test (push) Successful in 14m21s
Build Packages / XDS test (neggia plugin) (push) Successful in 8m36s
Build Packages / XDS test (JFJoch plugin) (push) Successful in 9m16s
Build Packages / Unit tests (push) Successful in 1h15m16s
Build Packages / build:windows:nocuda (push) Failing after 2s
Build Packages / build:windows:cuda (push) Failing after 2s
Three independent costs, each measured, none changing a result. Across the 37-crystal regression set the run time halves (median per crystal 2.0x, total 2.3x) and every crystal's merge statistics are unchanged. The image copy back from the device moved the whole preprocessed frame - 72 MB on a large detector, every frame, per worker - to serve a single host consumer that reads only the strong pixels, at most a few hundred kilobytes of it. Give the buffer a Gather() so that consumer asks for the values it actually wants (a host loop on the CPU, a small kernel on the GPU), and copy the frame back only when a CPU spot finder will genuinely read it. The copy the other way was worse: it came from an unregistered vector, so the driver staged it through its own pinned pool with a host-side memcpy on the calling thread, which does not overlap and collapses under concurrency - 11.6 GB/s at one worker, 1.6 GB/s at eight. That, not any hardware limit, is why throughput stopped improving past four to eight workers. Pinning the decompression buffer once per worker fixes it: on a 18 Mpx dataset the image loop goes from 13.6 to 7.9 ms per image at 32 workers, and 32 workers now beat 8 instead of losing to them. Ceres was computing seventeen partial derivatives where five are free. The per-image rotation refinement frees the beam and the orientation and holds distance, detector angles, rotation axis and cell constant, but the cost function declared all seven blocks, so every residual evaluated in Jet<17> arithmetic. A residual exposing only the two free blocks - the same arithmetic, the constants baked in - halves refinement, and it is exact rather than merely close: dual coordinates evolve independently, so the residuals and the free Jacobian columns are unchanged bit for bit. The merge sorted an index array with a comparator that dereferenced a 1.6 GB array of 72-byte records, i.e. a random walk over memory, single-threaded, twice per two-pass run. Sorting a packed key instead is 2.4x. French-Wilson allocated its integration scratch per reflection and ran serially; it now takes caller-owned scratch and runs over chunks, 4.2x. The correction surfaces re-tested every observation for usability and parity on each of ~22 passes and re-allocated their accumulators each time; bucket the indices once and hoist the buffers. Also convert std::round to std::rint where the rounded value only ever enters a squared residual. The tie rules differ - away from zero against to even - so this is safe exactly where a tie flips the sign but not the magnitude, and unsafe wherever the value becomes a Miller index; those sites keep std::round. Verified over all 2^32 float bit patterns: 8388608 exact ties exist, and the squared residual is bitwise equal for every one of them. Worth little on its own here, because the rounding that dominates is in candidate refinement, where the value is an index and the substitution is not available. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
270 lines
14 KiB
C++
270 lines
14 KiB
C++
// SPDX-FileCopyrightText: 2024 Filip Leonarski, Paul Scherrer Institute <filip.leonarski@psi.ch>
|
|
// SPDX-License-Identifier: GPL-3.0-only
|
|
|
|
#include "MXAnalysisWithoutFPGA.h"
|
|
|
|
#include <algorithm>
|
|
|
|
#include "spot_finding/StrongPixelSet.h"
|
|
#include "../compression/JFJochDecompress.h"
|
|
|
|
#include "spot_finding/SpotUtils.h"
|
|
#include "bragg_prediction/BraggPredictionFactory.h"
|
|
#include "image_preprocessing/ImagePreprocessorCPU.h"
|
|
|
|
#include "azint/AzIntEngineCPU.h"
|
|
#include "roi/ROIIntegrationCPU.h"
|
|
#include "spot_finding/ImageSpotFinderCPU.h"
|
|
#include "spot_finding/AdaptiveSpotFinderCPU.h"
|
|
#include "bragg_integration/BraggIntegrationEngineCPU.h"
|
|
#ifdef JFJOCH_USE_CUDA
|
|
#include "azint/AzIntEngineGPU.h"
|
|
#include "roi/ROIIntegrationGPU.h"
|
|
#include "spot_finding/ImageSpotFinderGPU.h"
|
|
#include "spot_finding/AdaptiveSpotFinderGPU.h"
|
|
#include "image_preprocessing/ImagePreprocessorGPU.h"
|
|
#include "image_preprocessing/ImagePreprocessorBufferGPU.h"
|
|
#include "bragg_integration/BraggIntegrationEngineGPU.h"
|
|
#include "../common/CUDAWrapper.h"
|
|
#endif
|
|
|
|
|
|
MXAnalysisWithoutFPGA::MXAnalysisWithoutFPGA(const DiffractionExperiment &in_experiment,
|
|
const AzimuthalIntegrationMapping &in_integration,
|
|
const PixelMask &in_mask,
|
|
IndexAndRefine &in_indexer,
|
|
bool in_enable_fused_adaptive_gpu)
|
|
: experiment(in_experiment),
|
|
integration(in_integration),
|
|
enable_fused_adaptive_gpu(in_enable_fused_adaptive_gpu),
|
|
npixels(experiment.GetPixelsNum()),
|
|
xpixels(experiment.GetXPixelsNum()),
|
|
indexer(in_indexer),
|
|
prediction(CreateBraggPrediction(experiment.IsRotationIndexing())),
|
|
mask(in_mask),
|
|
mask_resolution(experiment.GetPixelsNum(), false),
|
|
mask_high_res(-1),
|
|
mask_low_res(-1) {
|
|
#ifdef JFJOCH_USE_CUDA
|
|
if (get_gpu_count() == 0) {
|
|
#endif
|
|
preprocessor_buffer = std::make_unique<ImagePreprocessorBuffer>(experiment.GetPixelsNum());
|
|
spotFinder = std::make_unique<ImageSpotFinderCPU>(experiment.GetXPixelsNum(), experiment.GetYPixelsNum());
|
|
azint = std::make_unique<AzIntEngineCPU>(integration);
|
|
preprocessor = std::make_unique<ImagePreprocessorCPU>(in_experiment, in_mask);
|
|
bragg_engine = std::make_unique<BraggIntegrationEngineCPU>(in_experiment);
|
|
if (experiment.ROI().size() >= 1)
|
|
roi = std::make_unique<ROIIntegrationCPU>(experiment);
|
|
#ifdef JFJOCH_USE_CUDA
|
|
} else {
|
|
stream = std::make_shared<CudaStream>();
|
|
preprocessor_buffer = std::make_unique<ImagePreprocessorBufferGPU>(experiment.GetPixelsNum());
|
|
// The preprocessed image only has to come back to the host if a CPU engine reads it. Every
|
|
// engine built below runs on the GPU, except the CPU adaptive finder that is kept when the fused
|
|
// GPU engine is off (the online receiver) - so that is the one case that needs the copy.
|
|
preprocessor = std::make_unique<ImagePreprocessorGPU>(in_experiment, in_mask, stream,
|
|
/*copy_image_to_host=*/!enable_fused_adaptive_gpu);
|
|
spotFinder = std::make_unique<ImageSpotFinderGPU>(experiment.GetXPixelsNum(), experiment.GetYPixelsNum(), stream);
|
|
azint = std::make_unique<AzIntEngineGPU>(integration, stream);
|
|
bragg_engine = std::make_unique<BraggIntegrationEngineGPU>(in_experiment, stream);
|
|
if (experiment.ROI().size() >= 1)
|
|
roi = std::make_unique<ROIIntegrationGPU>(experiment, stream);
|
|
if (enable_fused_adaptive_gpu) {
|
|
// One GPU engine that computes the azimuthal profile and the adaptive spot mask in a single
|
|
// image pass. fused_adaptive aliases it so Analyze() can lift the profile out of it.
|
|
auto fused = std::make_unique<AdaptiveSpotFinderGPU>(integration, stream);
|
|
fused_adaptive = fused.get();
|
|
adaptiveSpotFinder = std::move(fused);
|
|
}
|
|
}
|
|
#endif
|
|
if (!adaptiveSpotFinder)
|
|
adaptiveSpotFinder = std::make_unique<AdaptiveSpotFinderCPU>(integration);
|
|
}
|
|
|
|
void MXAnalysisWithoutFPGA::Analyze(DataMessage &output,
|
|
AzimuthalIntegrationProfile &profile,
|
|
const SpotFindingSettings &spot_finding_settings) {
|
|
if ((output.image.GetWidth() != xpixels)
|
|
|| (output.image.GetWidth() * output.image.GetHeight() != npixels))
|
|
throw JFJochException(JFJochExceptionCategory::InputParameterInvalid,
|
|
"Mismatch in pixel size");
|
|
|
|
const auto compression_start_time = std::chrono::steady_clock::now();
|
|
const uint8_t *image_ptr = Decompress(output.image);
|
|
const auto compression_end_time = std::chrono::steady_clock::now();
|
|
if (output.image.GetCompressionAlgorithm() != CompressionAlgorithm::NO_COMPRESSION)
|
|
output.compression_time_s = std::chrono::duration<float>(compression_end_time - compression_start_time).count();
|
|
|
|
const auto preprocessing_start_time = std::chrono::steady_clock::now();
|
|
auto ret = preprocessor->Analyze(*preprocessor_buffer, image_ptr, output.image.GetMode());
|
|
const auto preprocessing_end_time = std::chrono::steady_clock::now();
|
|
output.preprocessing_time_s = std::chrono::duration<float>(preprocessing_end_time - preprocessing_start_time).count();
|
|
|
|
// The fused GPU engine (rugnux offline, GPU, adaptive detection) produces the azimuthal profile as
|
|
// a byproduct of spot finding, so the separate azint pass is skipped in that case and the profile is
|
|
// lifted out of the finder below.
|
|
const bool fused = enable_fused_adaptive_gpu && spot_finding_settings.enable
|
|
&& spot_finding_settings.adaptive_threshold && fused_adaptive != nullptr;
|
|
|
|
if (!fused) {
|
|
const auto azint_start_time = std::chrono::steady_clock::now();
|
|
azint->Run(*preprocessor_buffer, profile);
|
|
const auto azint_end_time = std::chrono::steady_clock::now();
|
|
output.azint_time_s = std::chrono::duration<float>(azint_end_time - azint_start_time).count();
|
|
}
|
|
|
|
if (roi)
|
|
roi->Run(*preprocessor_buffer, output.roi);
|
|
|
|
if (spot_finding_settings.enable) {
|
|
// Update resolution mask
|
|
if (mask_high_res != spot_finding_settings.high_resolution_limit
|
|
|| mask_low_res != spot_finding_settings.low_resolution_limit)
|
|
UpdateMaskResolution(spot_finding_settings);
|
|
|
|
ImageSpotFinder &finder = spot_finding_settings.adaptive_threshold
|
|
? static_cast<ImageSpotFinder &>(*adaptiveSpotFinder)
|
|
: *spotFinder;
|
|
const auto integrate_fn = [this](const std::vector<Reflection> &predicted, size_t npredicted,
|
|
int64_t image_number) {
|
|
return bragg_engine->Run(*preprocessor_buffer, predicted, npredicted, image_number);
|
|
};
|
|
|
|
// A missing min-pix (std::nullopt) means "choose it per image". This applies only to the stills
|
|
// indexing path (each frame is indexed independently); rotation indexing builds one lattice from
|
|
// all frames, so it keeps the fixed min-pix and the single-pass finder.
|
|
const bool adaptive_min_pix = !spot_finding_settings.min_pix_per_spot.has_value()
|
|
&& spot_finding_settings.indexing
|
|
&& !experiment.IsRotationIndexing();
|
|
if (adaptive_min_pix) {
|
|
// Choose the per-image min-pix adaptively instead of a fixed one. min-pix filters connected
|
|
// components AFTER detection, so detection (the expensive per-pixel pass) runs ONCE and only
|
|
// the cheap CCL + spot filter is repeated; the azimuthal profile is the one Detect() computed.
|
|
// Index at 3/2/1 (index-only, no integration/accumulation), keep whichever maximises
|
|
// n_indexed^2 / n_total (indexed count weighted by indexed fraction) together with its spot
|
|
// list, and integrate that one. Keeping the list also means the frame integrated is exactly
|
|
// the frame scored, which re-extracting could not guarantee on the GPU (atomic-order sums).
|
|
const auto detect_start_time = std::chrono::steady_clock::now();
|
|
finder.Detect(*preprocessor_buffer, spot_finding_settings);
|
|
float spot_finding_time_s =
|
|
std::chrono::duration<float>(std::chrono::steady_clock::now() - detect_start_time).count();
|
|
float indexing_time_s = 0.0f;
|
|
|
|
SpotFindingSettings s = spot_finding_settings;
|
|
std::vector<DiffractionSpot> best_spots;
|
|
int best_mp = 0;
|
|
double best_score = -1.0;
|
|
for (int mp : {3, 2, 1}) {
|
|
s.min_pix_per_spot = mp;
|
|
const auto extract_start_time = std::chrono::steady_clock::now();
|
|
std::vector<DiffractionSpot> spots = finder.ExtractSpots(*preprocessor_buffer, s, mask_resolution);
|
|
spot_finding_time_s +=
|
|
std::chrono::duration<float>(std::chrono::steady_clock::now() - extract_start_time).count();
|
|
SpotAnalyze(experiment, s, spots, output);
|
|
const bool indexed = indexer.IndexFrameOnly(output, s);
|
|
indexing_time_s += output.indexing_time_s.value_or(0.0f);
|
|
if (indexed) {
|
|
const double n_idx = static_cast<double>(output.spot_count_indexed.value_or(0));
|
|
const double n_tot = static_cast<double>(std::max<int64_t>(1, output.spot_count.value_or(1)));
|
|
const double score = n_idx * n_idx / n_tot;
|
|
if (score > best_score) {
|
|
best_score = score;
|
|
best_mp = mp;
|
|
best_spots = std::move(spots);
|
|
}
|
|
}
|
|
}
|
|
if (best_mp != 0) {
|
|
// Index and integrate the winning spot list; no spot finding left to do.
|
|
s.min_pix_per_spot = best_mp;
|
|
SpotAnalyze(experiment, s, best_spots, output);
|
|
indexer.ProcessImage(output, s, *prediction, integrate_fn);
|
|
indexing_time_s += output.indexing_time_s.value_or(0.0f);
|
|
}
|
|
// Each indexer call reports only its own time, so the escalation's total is summed here.
|
|
output.spot_finding_time_s = spot_finding_time_s;
|
|
output.indexing_time_s = indexing_time_s;
|
|
} else {
|
|
const auto spot_finding_start_time = std::chrono::steady_clock::now();
|
|
const std::vector<DiffractionSpot> spots = finder.Run(*preprocessor_buffer, spot_finding_settings, mask_resolution);
|
|
SpotAnalyze(experiment, spot_finding_settings, spots, output);
|
|
output.spot_finding_time_s = std::chrono::duration<float>(std::chrono::steady_clock::now() - spot_finding_start_time).count();
|
|
if (spot_finding_settings.indexing)
|
|
indexer.ProcessImage(output, spot_finding_settings, *prediction, integrate_fn);
|
|
}
|
|
|
|
#ifdef JFJOCH_USE_CUDA
|
|
if (fused) {
|
|
// Lift the azimuthal profile the fused engine computed in the same detection pass; its azint
|
|
// cost is folded into spot_finding_time_s above.
|
|
profile.Clear(integration);
|
|
profile += fused_adaptive->GetProfile();
|
|
output.azint_time_s = 0.0f;
|
|
}
|
|
#endif
|
|
}
|
|
|
|
output.max_viable_pixel_value = ret.max_value;
|
|
output.min_viable_pixel_value = ret.min_value;
|
|
output.error_pixel_count = ret.error_pixel_count;
|
|
output.saturated_pixel_count = ret.saturated_pixel_count;
|
|
output.az_int_profile = profile.GetResult();
|
|
output.az_int_profile_count = profile.GetPixelCount();
|
|
output.az_int_profile_std = profile.GetStd();
|
|
|
|
output.bkg_estimate = profile.GetBkgEstimate(integration.Settings());
|
|
output.ice_ring_score = profile.GetIceRingScore(integration.Settings(),
|
|
spot_finding_settings.ice_ring_width_Q_recipA);
|
|
}
|
|
|
|
void MXAnalysisWithoutFPGA::RebuildROI() {
|
|
if (experiment.ROI().empty()) {
|
|
roi.reset();
|
|
return;
|
|
}
|
|
#ifdef JFJOCH_USE_CUDA
|
|
if (stream) {
|
|
roi = std::make_unique<ROIIntegrationGPU>(experiment, stream);
|
|
return;
|
|
}
|
|
#endif
|
|
roi = std::make_unique<ROIIntegrationCPU>(experiment);
|
|
}
|
|
|
|
void MXAnalysisWithoutFPGA::AnalyzeROIOnly(DataMessage &output) {
|
|
if ((output.image.GetWidth() != xpixels)
|
|
|| (output.image.GetWidth() * output.image.GetHeight() != npixels))
|
|
throw JFJochException(JFJochExceptionCategory::InputParameterInvalid,
|
|
"Mismatch in pixel size");
|
|
|
|
const uint8_t *image_ptr = Decompress(output.image);
|
|
preprocessor->Analyze(*preprocessor_buffer, image_ptr, output.image.GetMode());
|
|
RunROIOnly(output);
|
|
}
|
|
|
|
const uint8_t *MXAnalysisWithoutFPGA::Decompress(const CompressedImage &image) {
|
|
// An uncompressed image is read straight out of the message and never touches decompression_buffer,
|
|
// so it stays in pageable memory - the buffer is only worth page-locking when it is actually used.
|
|
if (image.GetCompressionAlgorithm() != CompressionAlgorithm::NO_COMPRESSION)
|
|
preprocessor->PinInputBuffer(decompression_buffer, image.GetUncompressedSize());
|
|
return image.GetUncompressedPtr(decompression_buffer);
|
|
}
|
|
|
|
void MXAnalysisWithoutFPGA::RunROIOnly(DataMessage &output) {
|
|
output.roi.clear();
|
|
if (roi)
|
|
roi->Run(*preprocessor_buffer, output.roi);
|
|
}
|
|
|
|
void MXAnalysisWithoutFPGA::UpdateMaskResolution(const SpotFindingSettings &settings) {
|
|
mask_low_res = settings.low_resolution_limit;
|
|
mask_high_res = settings.high_resolution_limit;
|
|
// No high-resolution limit requested -> mask nothing at the high-resolution end: no pixel has d < 0,
|
|
// and the detector's own edge is where the pixels stop anyway.
|
|
const float high_res = mask_high_res.value_or(0.0f);
|
|
auto const &resolution_map = integration.Resolution();
|
|
for (int i = 0; i < mask_resolution.size(); i++)
|
|
mask_resolution[i] = (resolution_map[i] > mask_low_res) || (resolution_map[i] < high_res);
|
|
}
|