From 6e08ac65fa435e4151b6aaedd37d3db20e5ec7eb Mon Sep 17 00:00:00 2001 From: David Rohr Date: Tue, 1 Dec 2026 11:10:34 +0100 Subject: [PATCH 01/41] GPU: Clear some TODOs --- GPU/GPUTracking/Refit/GPUTrackingRefit.cxx | 4 ++-- GPU/GPUTracking/SectorTracker/GPUTPCTrackletConstructor.cxx | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/GPU/GPUTracking/Refit/GPUTrackingRefit.cxx b/GPU/GPUTracking/Refit/GPUTrackingRefit.cxx index 906e943bb1743..16ce371176704 100644 --- a/GPU/GPUTracking/Refit/GPUTrackingRefit.cxx +++ b/GPU/GPUTracking/Refit/GPUTrackingRefit.cxx @@ -84,7 +84,7 @@ struct refitTrackTypes { } // namespace o2::gpu::internal template <> -GPUd() void GPUTrackingRefit::initProp(GPUTPCGMPropagator& prop) // FIXME: GPUgeneric() needed to make the clang spirv output link correctly +GPUd() void GPUTrackingRefit::initProp(GPUTPCGMPropagator& prop) // GPUgeneric() needed due to C++ for OpenCL template deduction { prop.SetMaterialTPC(); prop.SetMaxSinPhi(constants::MAX_SIN_PHI); @@ -96,7 +96,7 @@ GPUd() void GPUTrackingRefit::initProp(GPUTPCGM } template <> -GPUd() void GPUTrackingRefit::initProp(const Propagator*& prop) // FIXME: GPUgeneric() needed to make the clang spirv output link correctly +GPUd() void GPUTrackingRefit::initProp(const Propagator*& prop) // GPUgeneric() needed due to C++ for OpenCL template deduction { prop = mPpropagator; } diff --git a/GPU/GPUTracking/SectorTracker/GPUTPCTrackletConstructor.cxx b/GPU/GPUTracking/SectorTracker/GPUTPCTrackletConstructor.cxx index b076a0a9c0417..171ce17008807 100644 --- a/GPU/GPUTracking/SectorTracker/GPUTPCTrackletConstructor.cxx +++ b/GPU/GPUTracking/SectorTracker/GPUTPCTrackletConstructor.cxx @@ -476,7 +476,7 @@ GPUdii() void GPUTPCTrackletConstructor::Thread(int32_t nBlocks, int32_t nThread } } -template <> // FIXME: GPUgeneric() needed to make the clang spirv output link correctly +template <> // GPUgeneric() needed due to C++ for OpenCL template deduction GPUd() int32_t GPUTPCTrackletConstructor::GPUTPCTrackletConstructorExtrapolationTracking(GPUconstantref() GPUTPCTracker& GPUrestrict() tracker, GPUsharedref() GPUTPCExtrapolationTracking::GPUSharedMemory& sMem, GPUTPCTrackParam& GPUrestrict() tParam, int32_t row, int32_t increment, int32_t iTracklet, calink* rowHits) { GPUTPCThreadMemory rMem; From afe2f389aa378f933a7f8a3da6feff9085e4e1fe Mon Sep 17 00:00:00 2001 From: David Rohr Date: Tue, 1 Dec 2026 13:58:31 +0100 Subject: [PATCH 02/41] GPU: Fix a data type, missing initialization, dangling reference --- GPU/GPUTracking/Base/GPUReconstruction.cxx | 4 ++-- GPU/GPUTracking/Base/GPUReconstructionConvert.cxx | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/GPU/GPUTracking/Base/GPUReconstruction.cxx b/GPU/GPUTracking/Base/GPUReconstruction.cxx index 2ddabe4d52c94..022963dacfba6 100644 --- a/GPU/GPUTracking/Base/GPUReconstruction.cxx +++ b/GPU/GPUTracking/Base/GPUReconstruction.cxx @@ -222,7 +222,7 @@ int32_t GPUReconstruction::InitPhaseBeforeDevice() if (mSlaves.size() || mMaster) { printf("\nConfig Dump %s\n", mMaster ? "Slave" : "Master"); } - const GPUChainTracking* chTrk; + const GPUChainTracking* chTrk = nullptr; for (uint32_t i = 0; i < mChains.size(); i++) { if ((chTrk = dynamic_cast(mChains[i].get()))) { break; @@ -1379,7 +1379,7 @@ void GPUReconstruction::SetDebugLevelTmp(int32_t level, int32_t silent) ThrustVolatileAllocator::ThrustVolatileAllocator(GPUReconstruction* r) { - mAlloc = [&r](size_t n) { return (char*)r->AllocateVolatileDeviceMemory(n); }; + mAlloc = [r](size_t n) { return (char*)r->AllocateVolatileDeviceMemory(n); }; } ThrustVolatileAllocator GPUReconstruction::getThrustVolatileDeviceAllocator() { diff --git a/GPU/GPUTracking/Base/GPUReconstructionConvert.cxx b/GPU/GPUTracking/Base/GPUReconstructionConvert.cxx index c2eb1c4cd44dc..52b347e82b20e 100644 --- a/GPU/GPUTracking/Base/GPUReconstructionConvert.cxx +++ b/GPU/GPUTracking/Base/GPUReconstructionConvert.cxx @@ -842,7 +842,7 @@ void zsEncoderDenseLinkBased::decodePage(std::vector& outputBuff std::vector tmpBuffer; bool extendFailure = false; uint32_t nOutput = 0; - uint32_t minTimeBin = -1, maxTimeBin = 0; + int32_t minTimeBin = 0x7FFFFFFF, maxTimeBin = 0; for (uint32_t i = 0; i < decHDR->nTimebinHeaders; i++) { int32_t sizeLeftInPage = payloadEnd - decPagePtr; if (sizeLeftInPage <= 0) { From 601c943fb33079c5a2abcd0f2b543da467c14c73 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Tue, 1 Dec 2026 13:59:06 +0100 Subject: [PATCH 03/41] GPU: Fix some debug / info messages --- GPU/GPUTracking/Base/GPUReconstruction.cxx | 2 +- GPU/GPUTracking/Base/cuda/GPUReconstructionCUDA.cu | 2 +- GPU/GPUTracking/Base/opencl/GPUReconstructionOCL.cxx | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/GPU/GPUTracking/Base/GPUReconstruction.cxx b/GPU/GPUTracking/Base/GPUReconstruction.cxx index 022963dacfba6..89da4e0f8508a 100644 --- a/GPU/GPUTracking/Base/GPUReconstruction.cxx +++ b/GPU/GPUTracking/Base/GPUReconstruction.cxx @@ -1125,7 +1125,7 @@ constexpr static inline int32_t getStepNum(T step, bool validCheck, int32_t N, c if (!validCheck) { return -1; } - throw std::runtime_error("Invalid General Step"); + throw std::runtime_error(err); } return retVal; } diff --git a/GPU/GPUTracking/Base/cuda/GPUReconstructionCUDA.cu b/GPU/GPUTracking/Base/cuda/GPUReconstructionCUDA.cu index 13ca28bac7a7e..0d50c1a02093e 100644 --- a/GPU/GPUTracking/Base/cuda/GPUReconstructionCUDA.cu +++ b/GPU/GPUTracking/Base/cuda/GPUReconstructionCUDA.cu @@ -275,7 +275,7 @@ int32_t GPUReconstructionCUDA::InitDevice_Runtime() return (1); } if (GPUChkErrI(cudaDeviceSetLimit(cudaLimitMallocHeapSize, GetProcessingSettings().deterministicGPUReconstruction ? std::max(1024 * 1024 * 1024, constants::GPU_HEAP_SIZE) : constants::GPU_HEAP_SIZE))) { - GPUError("Error setting CUDA stack size"); + GPUError("Error setting CUDA heap size"); GPUChkErrI(cudaDeviceReset()); return (1); } diff --git a/GPU/GPUTracking/Base/opencl/GPUReconstructionOCL.cxx b/GPU/GPUTracking/Base/opencl/GPUReconstructionOCL.cxx index d4169f5d5dbb2..f67c7f054d9af 100644 --- a/GPU/GPUTracking/Base/opencl/GPUReconstructionOCL.cxx +++ b/GPU/GPUTracking/Base/opencl/GPUReconstructionOCL.cxx @@ -114,7 +114,7 @@ int32_t GPUReconstructionOCL::InitDevice_Runtime() cl_uint device_freq, device_shaders, device_nbits; cl_bool device_endian; auto queryDevice = [&](auto device) { - platform_name = query(clGetDeviceInfo, device, CL_DEVICE_NAME); + device_name = query(clGetDeviceInfo, device, CL_DEVICE_NAME); device_vendor = query(clGetDeviceInfo, device, CL_DEVICE_VENDOR); device_il_version = query(clGetDeviceInfo, device, CL_DEVICE_IL_VERSION); clGetDeviceInfo(device, CL_DEVICE_TYPE, sizeof(device_type), &device_type, nullptr); From eab9c060f544e1d91357ea87d5e697b685b80777 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Tue, 1 Dec 2026 14:01:38 +0100 Subject: [PATCH 04/41] GPU: Fix dead code / wrong pragma --- GPU/GPUTracking/Base/GPUReconstructionProcessingKernels.inc | 2 +- GPU/GPUTracking/Base/GPUReconstructionTimeframe.cxx | 3 --- 2 files changed, 1 insertion(+), 4 deletions(-) diff --git a/GPU/GPUTracking/Base/GPUReconstructionProcessingKernels.inc b/GPU/GPUTracking/Base/GPUReconstructionProcessingKernels.inc index b303cb7c8d39c..6365dfd14d2ee 100644 --- a/GPU/GPUTracking/Base/GPUReconstructionProcessingKernels.inc +++ b/GPU/GPUTracking/Base/GPUReconstructionProcessingKernels.inc @@ -41,7 +41,7 @@ void GPUReconstructionProcessing::KernelInterface::runKernelVirtual(const } // clang-format on } -#pragma GCC diagnostic push +#pragma GCC diagnostic pop } // namespace o2::gpu diff --git a/GPU/GPUTracking/Base/GPUReconstructionTimeframe.cxx b/GPU/GPUTracking/Base/GPUReconstructionTimeframe.cxx index 1c56502ebe189..fe1a50327dc10 100644 --- a/GPU/GPUTracking/Base/GPUReconstructionTimeframe.cxx +++ b/GPU/GPUTracking/Base/GPUReconstructionTimeframe.cxx @@ -64,9 +64,6 @@ GPUReconstructionTimeframe::GPUReconstructionTimeframe(GPUChainTracking* chain, mEventStride = configStandalone.seed; mSimBunchNoRepeatEvent = configStandalone.StartEvent; mEventUsed.resize(mNEventsInDirectory); - if (config.noEventRepeat == 2) { - memset(mEventUsed.data(), 0, mNEventsInDirectory * sizeof(mEventUsed[0])); - } } int32_t GPUReconstructionTimeframe::ReadEventShifted(int32_t iEvent, float shiftZ, float minZ, float maxZ, bool silent) From c5ce6af507b08800219d50f42856a9434209c9c8 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Tue, 1 Dec 2026 14:01:57 +0100 Subject: [PATCH 05/41] GPU: Use stdspinlock instead of broken manual implementation --- GPU/GPUTracking/Base/GPUReconstructionProcessing.cxx | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) diff --git a/GPU/GPUTracking/Base/GPUReconstructionProcessing.cxx b/GPU/GPUTracking/Base/GPUReconstructionProcessing.cxx index 08695b80ccef7..4a943bc2bc98f 100644 --- a/GPU/GPUTracking/Base/GPUReconstructionProcessing.cxx +++ b/GPU/GPUTracking/Base/GPUReconstructionProcessing.cxx @@ -18,6 +18,7 @@ #include "GPUReconstructionKernelIncludes.h" #include "GPUSettings.h" #include "GPULogging.h" +#include "utils/stdspinlock.h" using namespace o2::gpu; @@ -98,8 +99,7 @@ std::atomic_flag GPUReconstructionProcessing::mTimerFlag = ATOMIC_FLAG_INIT; GPUReconstructionProcessing::timerMeta* GPUReconstructionProcessing::insertTimer(uint32_t id, std::string&& name, int32_t J, int32_t num, int32_t type, RecoStep step) { - while (mTimerFlag.test_and_set()) { - } + stdspinlock spinlock(mTimerFlag); if (mTimers.size() <= id) { mTimers.resize(id + 1); } @@ -111,21 +111,17 @@ GPUReconstructionProcessing::timerMeta* GPUReconstructionProcessing::insertTimer } else { mTimers[id]->count++; } - timerMeta* retVal = mTimers[id].get(); - mTimerFlag.clear(); - return retVal; + return mTimers[id].get(); } GPUReconstructionProcessing::timerMeta* GPUReconstructionProcessing::getTimerById(uint32_t id, bool increment) { timerMeta* retVal = nullptr; - while (mTimerFlag.test_and_set()) { - } + stdspinlock spinlock(mTimerFlag); if (mTimers.size() > id && mTimers[id]) { retVal = mTimers[id].get(); retVal->count += increment; } - mTimerFlag.clear(); return retVal; } From cfd712a9b0d701e0d1c2428c4c94163cae86a9a7 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Tue, 1 Dec 2026 14:02:23 +0100 Subject: [PATCH 06/41] GPU OpenCL: Find best device over all platforms --- GPU/GPUTracking/Base/opencl/GPUReconstructionOCL.cxx | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/GPU/GPUTracking/Base/opencl/GPUReconstructionOCL.cxx b/GPU/GPUTracking/Base/opencl/GPUReconstructionOCL.cxx index f67c7f054d9af..cdc51bc5d311b 100644 --- a/GPU/GPUTracking/Base/opencl/GPUReconstructionOCL.cxx +++ b/GPU/GPUTracking/Base/opencl/GPUReconstructionOCL.cxx @@ -125,6 +125,7 @@ int32_t GPUReconstructionOCL::InitDevice_Runtime() }; cl_uint deviceCount, bestDevice = (cl_uint)-1, bestPlatform = (cl_uint)-1; + double bestDeviceSpeed = -1; for (uint32_t iPlatform = 0; iPlatform < num_platforms; iPlatform++) { if (GetProcessingSettings().backend.platformNum >= 0) { if (GetProcessingSettings().backend.platformNum >= (int32_t)num_platforms) { @@ -200,7 +201,7 @@ int32_t GPUReconstructionOCL::InitDevice_Runtime() } } - double bestDeviceSpeed = -1, deviceSpeed = (double)device_freq * (double)device_shaders; + double deviceSpeed = (double)device_freq * (double)device_shaders; if (GetProcessingSettings().debugLevel >= 2 && !GetProcessingSettings().debugSilent) { GPUInfo(" Device %s%2d: %s %s (Frequency %d, Shaders %d, %d bit) (Speed Value: %ld)%s %s", deviceOK ? " " : "[", i, device_vendor.c_str(), device_name.c_str(), (int32_t)device_freq, (int32_t)device_shaders, (int32_t)device_nbits, (int64_t)deviceSpeed, deviceOK ? " " : " ]", deviceOK ? "" : deviceFailure.c_str()); } From d9fbc07e10056d5c4cc33d5ac359f35e7124d696 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Tue, 1 Dec 2026 14:34:12 +0100 Subject: [PATCH 07/41] GPU: Use std::move where possible --- GPU/GPUTracking/Base/GPUReconstructionDebug.cxx | 2 +- GPU/GPUTracking/Base/GPUReconstructionProcessing.cxx | 2 +- GPU/GPUTracking/DataTypes/GPUO2ConfigurableParam.cxx | 8 ++++---- GPU/GPUTracking/Global/GPUChainTracking.h | 2 +- .../TPCClusterFinder/GPUTPCNNClusterizerHost.cxx | 2 +- .../display/frontend/GPUDisplayFrontendConfig.cxx | 4 ++-- .../display/frontend/GPUDisplayFrontendConfigQtGUI.inc | 2 +- GPU/GPUTracking/display/helpers/GPUDisplayROOT.cxx | 2 +- GPU/GPUTracking/utils/qconfig.cxx | 10 +++++----- GPU/Utils/MultivariatePolynomialHelper.cxx | 2 +- GPU/Workflow/include/GPUWorkflow/O2GPUDPLDisplay.h | 2 +- GPU/Workflow/src/GPUWorkflowSpec.cxx | 2 +- GPU/Workflow/src/gpu-reco-workflow.cxx | 4 ++-- 13 files changed, 22 insertions(+), 22 deletions(-) diff --git a/GPU/GPUTracking/Base/GPUReconstructionDebug.cxx b/GPU/GPUTracking/Base/GPUReconstructionDebug.cxx index e69030c4c96b8..463310c631a07 100644 --- a/GPU/GPUTracking/Base/GPUReconstructionDebug.cxx +++ b/GPU/GPUTracking/Base/GPUReconstructionDebug.cxx @@ -115,7 +115,7 @@ void GPUReconstruction::setDebugDumpCallback(std::function&& callback) } mMaster->setDebugDumpCallback(std::move(callback)); } else if (mDebugEnabled && mDebugData) { - mDebugData->debugCallback = callback; + mDebugData->debugCallback = std::move(callback); } } diff --git a/GPU/GPUTracking/Base/GPUReconstructionProcessing.cxx b/GPU/GPUTracking/Base/GPUReconstructionProcessing.cxx index 4a943bc2bc98f..db6f6f8e70e9e 100644 --- a/GPU/GPUTracking/Base/GPUReconstructionProcessing.cxx +++ b/GPU/GPUTracking/Base/GPUReconstructionProcessing.cxx @@ -107,7 +107,7 @@ GPUReconstructionProcessing::timerMeta* GPUReconstructionProcessing::insertTimer if (J >= 0) { name += std::to_string(J); } - mTimers[id].reset(new timerMeta{std::unique_ptr{new HighResTimer[num]}, name, num, type, 1u, step, (size_t)0}); + mTimers[id].reset(new timerMeta{std::unique_ptr{new HighResTimer[num]}, std::move(name), num, type, 1u, step, (size_t)0}); } else { mTimers[id]->count++; } diff --git a/GPU/GPUTracking/DataTypes/GPUO2ConfigurableParam.cxx b/GPU/GPUTracking/DataTypes/GPUO2ConfigurableParam.cxx index 3820b8c4f0054..259915937a933 100644 --- a/GPU/GPUTracking/DataTypes/GPUO2ConfigurableParam.cxx +++ b/GPU/GPUTracking/DataTypes/GPUO2ConfigurableParam.cxx @@ -101,10 +101,10 @@ GPUSettingsO2 GPUO2InterfaceConfiguration::ReadConfigurableParam(GPUO2InterfaceC #undef AddHelp #undef AddShortcut - obj.configProcessing = proc; - obj.configReconstruction = rec; - obj.configDisplay = display; - obj.configQA = QA; + obj.configProcessing = std::move(proc); + obj.configReconstruction = std::move(rec); + obj.configDisplay = std::move(display); + obj.configQA = std::move(QA); if (obj.configGRP.grpContinuousMaxTimeBin < 0) { if (global.setMaxTimeBin != -2) { obj.configGRP.grpContinuousMaxTimeBin = global.setMaxTimeBin; diff --git a/GPU/GPUTracking/Global/GPUChainTracking.h b/GPU/GPUTracking/Global/GPUChainTracking.h index 21e3494295c5f..d325c9d9ddac7 100644 --- a/GPU/GPUTracking/Global/GPUChainTracking.h +++ b/GPU/GPUTracking/Global/GPUChainTracking.h @@ -198,7 +198,7 @@ class GPUChainTracking : public GPUChain void SetCalibObjects(const GPUCalibObjects& obj); void SetUpdateCalibObjects(const GPUCalibObjectsConst& obj, const GPUNewCalibValues& vals); void SetSubOutputControl(int32_t i, GPUOutputControl* v) { mSubOutputControls[i] = v; } - void SetFinalInputCallback(std::function v) { mWaitForFinalInputs = v; } + void SetFinalInputCallback(std::function v) { mWaitForFinalInputs = std::move(v); } const GPUSettingsDisplay* mConfigDisplay = nullptr; // Abstract pointer to Standalone Display Configuration Structure const GPUSettingsQA* mConfigQA = nullptr; // Abstract pointer to Standalone QA Configuration Structure diff --git a/GPU/GPUTracking/TPCClusterFinder/GPUTPCNNClusterizerHost.cxx b/GPU/GPUTracking/TPCClusterFinder/GPUTPCNNClusterizerHost.cxx index 1098bbe92f2e8..632b0ce958a3d 100644 --- a/GPU/GPUTracking/TPCClusterFinder/GPUTPCNNClusterizerHost.cxx +++ b/GPU/GPUTracking/TPCClusterFinder/GPUTPCNNClusterizerHost.cxx @@ -48,7 +48,7 @@ void GPUTPCNNClusterizerHost::init(const GPUSettingsProcessingNNclusterizer& set } mOrtOptions = { - {"model-path", class_model_path}, + {"model-path", std::move(class_model_path)}, {"device-type", settings.nnInferenceDevice}, {"allocate-device-memory", std::to_string(settings.nnInferenceAllocateDevMem)}, {"intra-op-num-threads", std::to_string(settings.nnInferenceIntraOpNumThreads)}, diff --git a/GPU/GPUTracking/display/frontend/GPUDisplayFrontendConfig.cxx b/GPU/GPUTracking/display/frontend/GPUDisplayFrontendConfig.cxx index 8ec2ff6f11924..6ace7b4c83f7a 100644 --- a/GPU/GPUTracking/display/frontend/GPUDisplayFrontendConfig.cxx +++ b/GPU/GPUTracking/display/frontend/GPUDisplayFrontendConfig.cxx @@ -460,11 +460,11 @@ void GPUDisplayFrontend::add_gui_binding(Args&&... args) auto addElement = [&](auto& element) { using Type = GPUDisplayGUIChannel::ElementType; if (element.type.bitMask) { // The element sets / shows only these bits of the option - element.set = [this, set = element.set, get = element.get, mask = element.type.bitMask](const GPUDisplayGUIValue& v) { + element.set = [this, set = std::move(element.set), get = element.get, mask = element.type.bitMask](const GPUDisplayGUIValue& v) { const int64_t current = std::get(get({mDisplay->mCfgH, mDisplay->mCfgL, mDisplay->mCfgR, mDisplay->mCfgO, mDisplay->mCfgC})); set(std::get(v) ? (current | mask) : (current & ~mask)); }; - element.get = [get = element.get, mask = element.type.bitMask](const GPUDisplayGUIChannel::Settings& cfg) -> GPUDisplayGUIValue { return (int64_t)((std::get(get(cfg)) & mask) != 0); }; + element.get = [get = std::move(element.get), mask = element.type.bitMask](const GPUDisplayGUIChannel::Settings& cfg) -> GPUDisplayGUIValue { return (int64_t)((std::get(get(cfg)) & mask) != 0); }; } static const GPUDisplayGUIChannel::Settings defaults; // Only for the types of the values const uint32_t id = mConfiguration->guiElements.size(); diff --git a/GPU/GPUTracking/display/frontend/GPUDisplayFrontendConfigQtGUI.inc b/GPU/GPUTracking/display/frontend/GPUDisplayFrontendConfigQtGUI.inc index 70231f53514a8..325a7d5c677fe 100644 --- a/GPU/GPUTracking/display/frontend/GPUDisplayFrontendConfigQtGUI.inc +++ b/GPU/GPUTracking/display/frontend/GPUDisplayFrontendConfigQtGUI.inc @@ -133,7 +133,7 @@ void GPUDisplay::buildConfigQtGUI() GUI_LAMBDA("TOF", mCfgH, drawTOFTracks, GUI_CHECKBOX), GUI_LAMBDA("ITS", mCfgH, drawITSTracks, GUI_CHECKBOX), GUI_LAMBDA("", mCfgH, drawTracksAndFilter, GUI_RADIO_BUTTONS({"AND", 1}, {"OR", 0})), - GUI_LAMBDA("Filter Macro", mCfgH, trackFilter, guiType(GPUDisplayGUIChannel::ElementType::DROPDOWN, filterChoices)), + GUI_LAMBDA("Filter Macro", mCfgH, trackFilter, guiType(GPUDisplayGUIChannel::ElementType::DROPDOWN, std::move(filterChoices))), GUI_LAMBDA("Custom Macro", mCfgO, filterMacroCustom, GUI_TEXTEDIT(1), { // ROOT macro code, reload and apply the custom filter if selected, the change is not visible in the config structs guiAssign(val, guiVal); if ((uint32_t)mCfgH.trackFilter == mConfig.filterMacros.size() + 1) { diff --git a/GPU/GPUTracking/display/helpers/GPUDisplayROOT.cxx b/GPU/GPUTracking/display/helpers/GPUDisplayROOT.cxx index 58da1216bcfe2..be78c3f00199a 100644 --- a/GPU/GPUTracking/display/helpers/GPUDisplayROOT.cxx +++ b/GPU/GPUTracking/display/helpers/GPUDisplayROOT.cxx @@ -69,7 +69,7 @@ int32_t GPUDisplay::buildTrackFilter() GPUError("Error loading trackFilter macro %s", name.c_str()); return 1; } - mTrackFilterMacroLoaded = name; + mTrackFilterMacroLoaded = std::move(name); } TMethodCall call; call.InitWithPrototype("gpuDisplayTrackFilter", "std::vector*, const o2::gpu::GPUTrackingInOutPointers*, const o2::gpu::GPUConstantMem*"); diff --git a/GPU/GPUTracking/utils/qconfig.cxx b/GPU/GPUTracking/utils/qconfig.cxx index 74c1ef8262c3e..275c254ea9d42 100644 --- a/GPU/GPUTracking/utils/qconfig.cxx +++ b/GPU/GPUTracking/utils/qconfig.cxx @@ -75,7 +75,7 @@ inline int32_t qConfigTypeSpecialized::qAddOptionMain(qConfigSettings& set int32_t iOrg = i; if (settings.doSet) { ref = settings.set; - } else if ((retVal = qAddOptionType(settings, ref, i, argv, argc, def))) { + } else if ((retVal = qAddOptionType(settings, ref, i, argv, argc, std::move(def)))) { return (retVal); } if ((retVal = qAddOptionMinMax(settings, ref, iOrg < argc ? argv[iOrg] : ""))) { @@ -89,7 +89,7 @@ static inline int32_t qAddOptionMainTupleElem(qConfigSettings settings = settingsTup; - return (qAddOptionType(settings, ref, i, argv, argc, def)); + return (qAddOptionType(settings, ref, i, argv, argc, std::move(def))); } template > struct qAddOptionMainTupleStruct { @@ -158,7 +158,7 @@ struct qConfigType : public qConfigSettingsParser { return (retVal != qcrArgMissing || i == iFirst ? retVal : 0); } if (i == iFirst || i != iLast) { - ref.push_back(tmp); + ref.push_back(std::move(tmp)); } } while (i != iLast); return (0); @@ -182,7 +182,7 @@ struct qConfigType : public qConfigSettingsParser { return (qcrArrayOverflow); } if (i == iFirst || i != iLast) { - ref[i == iFirst ? 0 : i - iFirst - 1] = tmp; // i points to the argument just read + ref[i == iFirst ? 0 : i - iFirst - 1] = std::move(tmp); // i points to the argument just read } } while (i != iLast); return (0); @@ -253,7 +253,7 @@ static inline int32_t qAddOptionGeneric(qConfigSettings& settings, T& ref, in ref = func(arg); return (0); } else if (allowDefault) { - ref = def; + ref = std::move(def); return (0); } if (!settings.allowEmpty) { diff --git a/GPU/Utils/MultivariatePolynomialHelper.cxx b/GPU/Utils/MultivariatePolynomialHelper.cxx index d7bd6ff8bc90c..93e341fe4823b 100644 --- a/GPU/Utils/MultivariatePolynomialHelper.cxx +++ b/GPU/Utils/MultivariatePolynomialHelper.cxx @@ -151,7 +151,7 @@ Type MultivariatePolynomialHelper<0, 0, false>::combination_with_repetiton(const term += fmt::format("x[{}] * ", pos[i]); } term += fmt::format("par[{}]", indexPar++); - val.emplace_back(term); + val.emplace_back(std::move(term)); } } diff --git a/GPU/Workflow/include/GPUWorkflow/O2GPUDPLDisplay.h b/GPU/Workflow/include/GPUWorkflow/O2GPUDPLDisplay.h index 517e82480565b..f5a04ff9b5fda 100644 --- a/GPU/Workflow/include/GPUWorkflow/O2GPUDPLDisplay.h +++ b/GPU/Workflow/include/GPUWorkflow/O2GPUDPLDisplay.h @@ -45,7 +45,7 @@ struct GPUSettingsO2; class O2GPUDPLDisplaySpec : public o2::framework::Task { public: - O2GPUDPLDisplaySpec(bool useMC, o2::dataformats::GlobalTrackID::mask_t trkMask, o2::dataformats::GlobalTrackID::mask_t clMask, std::shared_ptr dataRequest, std::shared_ptr ggr) : mUseMC(useMC), mTrkMask(trkMask), mClMask(clMask), mDataRequest(dataRequest), mGGR(ggr) {} + O2GPUDPLDisplaySpec(bool useMC, o2::dataformats::GlobalTrackID::mask_t trkMask, o2::dataformats::GlobalTrackID::mask_t clMask, std::shared_ptr dataRequest, std::shared_ptr ggr) : mUseMC(useMC), mTrkMask(trkMask), mClMask(clMask), mDataRequest(std::move(dataRequest)), mGGR(std::move(ggr)) {} ~O2GPUDPLDisplaySpec() override = default; void init(o2::framework::InitContext& ic) final; void run(o2::framework::ProcessingContext& pc) final; diff --git a/GPU/Workflow/src/GPUWorkflowSpec.cxx b/GPU/Workflow/src/GPUWorkflowSpec.cxx index 9f2a5a5a9041e..0f6759df7bf0f 100644 --- a/GPU/Workflow/src/GPUWorkflowSpec.cxx +++ b/GPU/Workflow/src/GPUWorkflowSpec.cxx @@ -1153,7 +1153,7 @@ Options GPURecoWorkflowSpec::options() char* numaid = getenv("NUMAID"); int32_t chanid = o2jobid ? atoi(o2jobid) : (numaid ? atoi(numaid) : 0); std::string chan = std::string("name=gpu-prepare-channel,type=") + (send ? "push" : "pull") + ",method=" + (send ? "connect" : "bind") + ",address=ipc://@gpu-prepare-channel-" + std::to_string(chanid) + "-{timeslice0},transport=shmem,rateLogging=0"; - opts.emplace_back(o2::framework::ConfigParamSpec{"channel-config", o2::framework::VariantType::String, chan, {"Out-of-band channel config"}}); + opts.emplace_back(o2::framework::ConfigParamSpec{"channel-config", o2::framework::VariantType::String, std::move(chan), {"Out-of-band channel config"}}); } if (mSpecConfig.enableDoublePipeline == 2) { return opts; diff --git a/GPU/Workflow/src/gpu-reco-workflow.cxx b/GPU/Workflow/src/gpu-reco-workflow.cxx index 847ddf95b3da9..bcde8c9b5889b 100644 --- a/GPU/Workflow/src/gpu-reco-workflow.cxx +++ b/GPU/Workflow/src/gpu-reco-workflow.cxx @@ -201,7 +201,7 @@ WorkflowSpec defineDataProcessing(ConfigContext const& cfgc) specs.emplace_back(DataProcessorSpec{ "gpu-reconstruction", - taskInputs, + std::move(taskInputs), task->outputs(), AlgorithmSpec{adoptTask(task)}, task->options()}); @@ -215,7 +215,7 @@ WorkflowSpec defineDataProcessing(ConfigContext const& cfgc) std::move(ggInputsPrepare.begin(), ggInputsPrepare.end(), std::back_inserter(taskInputsPrepare)); specs.emplace_back(DataProcessorSpec{ "gpu-reconstruction-prepare", - taskInputsPrepare, + std::move(taskInputsPrepare), taskPrepare->outputs(), AlgorithmSpec{adoptTask(taskPrepare)}, taskPrepare->options()}); From 27f28f4ad3d971d677f66e3d8e7d203d9ab3aade Mon Sep 17 00:00:00 2001 From: David Rohr Date: Tue, 1 Dec 2026 14:34:26 +0100 Subject: [PATCH 08/41] GPU: Switch several function arguments to const ref --- GPU/GPUTracking/Base/GPUReconstructionCPU.h | 2 +- GPU/GPUTracking/Base/GPUReconstructionConvert.cxx | 6 +++--- GPU/GPUTracking/Base/GPUReconstructionConvert.h | 2 +- GPU/GPUTracking/Base/GPUReconstructionDebug.cxx | 2 +- .../DataCompression/TPCClusterDecompressor.cxx | 4 ++-- .../DataCompression/TPCClusterDecompressor.h | 4 ++-- GPU/GPUTracking/Global/GPUChain.h | 2 +- GPU/GPUTracking/Global/GPUChainTrackingDebug.h | 2 +- GPU/GPUTracking/Interface/GPUO2InterfaceUtils.cxx | 4 ++-- GPU/GPUTracking/Interface/GPUO2InterfaceUtils.h | 4 ++-- GPU/GPUTracking/qa/GPUQA.cxx | 2 +- .../devtools/IrregularSpline2D3DCalibrator.cxx | 4 ++-- .../devtools/IrregularSpline2D3DCalibrator.h | 4 ++-- GPU/Utils/Spline1DHelper.cxx | 8 ++++---- GPU/Utils/Spline1DHelper.h | 8 ++++---- GPU/Utils/Spline1DHelperOld.cxx | 10 +++++----- GPU/Utils/Spline1DHelperOld.h | 10 +++++----- GPU/Utils/Spline1DSpec.cxx | 2 +- GPU/Utils/Spline1DSpec.h | 2 +- GPU/Utils/Spline2DHelper.cxx | 6 +++--- GPU/Utils/Spline2DHelper.h | 10 +++++----- GPU/Utils/Spline2DSpec.cxx | 4 ++-- GPU/Utils/Spline2DSpec.h | 4 ++-- GPU/Utils/SplineHelper.cxx | 4 ++-- GPU/Utils/SplineHelper.h | 8 ++++---- GPU/Utils/SplineSpec.cxx | 2 +- GPU/Utils/SplineSpec.h | 2 +- 27 files changed, 61 insertions(+), 61 deletions(-) diff --git a/GPU/GPUTracking/Base/GPUReconstructionCPU.h b/GPU/GPUTracking/Base/GPUReconstructionCPU.h index 6b3e04b0a8c41..3d61da59366df 100644 --- a/GPU/GPUTracking/Base/GPUReconstructionCPU.h +++ b/GPU/GPUTracking/Base/GPUReconstructionCPU.h @@ -109,7 +109,7 @@ class GPUReconstructionCPU : public GPUReconstructionProcessing::KernelInterface struct debugWriter { debugWriter(std::string filenameCSV, bool markdown, uint32_t statNEvents, bool silent); void header(); - void row(char type, uint32_t count, std::string name, double gpu_time, double cpu_time, double total_time, std::size_t memSize, std::string nEventReport = ""); + void row(char type, uint32_t count, const std::string& name, double gpu_time, double cpu_time, double total_time, std::size_t memSize, const std::string& nEventReport = ""); private: std::ofstream streamCSV; diff --git a/GPU/GPUTracking/Base/GPUReconstructionConvert.cxx b/GPU/GPUTracking/Base/GPUReconstructionConvert.cxx index 52b347e82b20e..144a094a48d06 100644 --- a/GPU/GPUTracking/Base/GPUReconstructionConvert.cxx +++ b/GPU/GPUTracking/Base/GPUReconstructionConvert.cxx @@ -1276,7 +1276,7 @@ size_t zsEncoderRun::compare(std::vector* buffer, std::vector -void GPUReconstructionConvert::RunZSEncoder(const S& in, std::unique_ptr* outBuffer, uint32_t* outSizes, o2::raw::RawFileWriter* raw, const o2::InteractionRecord* ir, const GPUParam& param, int32_t version, bool verify, float threshold, bool padding, std::function&)> digitsFilter) +void GPUReconstructionConvert::RunZSEncoder(const S& in, std::unique_ptr* outBuffer, uint32_t* outSizes, o2::raw::RawFileWriter* raw, const o2::InteractionRecord* ir, const GPUParam& param, int32_t version, bool verify, float threshold, bool padding, const std::function&)>& digitsFilter) { // Pass in either outBuffer / outSizes, to fill standalone output buffers, or raw to use RawFileWriter // ir is the interaction record for time bin 0 @@ -1372,9 +1372,9 @@ void GPUReconstructionConvert::RunZSEncoder(const S& in, std::unique_ptr(const GPUTrackingInOutDigits&, std::unique_ptr*, uint32_t*, o2::raw::RawFileWriter*, const o2::InteractionRecord*, const GPUParam&, int32_t, bool, float, bool, std::function&)> digitsFilter); +template void GPUReconstructionConvert::RunZSEncoder(const GPUTrackingInOutDigits&, std::unique_ptr*, uint32_t*, o2::raw::RawFileWriter*, const o2::InteractionRecord*, const GPUParam&, int32_t, bool, float, bool, const std::function&)>& digitsFilter); #ifndef GPUCA_STANDALONE -template void GPUReconstructionConvert::RunZSEncoder(const DigitArray&, std::unique_ptr*, uint32_t*, o2::raw::RawFileWriter*, const o2::InteractionRecord*, const GPUParam&, int32_t, bool, float, bool, std::function&)> digitsFilter); +template void GPUReconstructionConvert::RunZSEncoder(const DigitArray&, std::unique_ptr*, uint32_t*, o2::raw::RawFileWriter*, const o2::InteractionRecord*, const GPUParam&, int32_t, bool, float, bool, const std::function&)>& digitsFilter); #endif void GPUReconstructionConvert::RunZSEncoderCreateMeta(const uint64_t* buffer, const uint32_t* sizes, void** ptrs, GPUTrackingInOutZS* out) diff --git a/GPU/GPUTracking/Base/GPUReconstructionConvert.h b/GPU/GPUTracking/Base/GPUReconstructionConvert.h index bcf621e379884..6c2d283257c5e 100644 --- a/GPU/GPUTracking/Base/GPUReconstructionConvert.h +++ b/GPU/GPUTracking/Base/GPUReconstructionConvert.h @@ -52,7 +52,7 @@ class GPUReconstructionConvert constexpr static uint32_t NSECTORS = o2::tpc::constants::MAXSECTOR; static void ConvertRun2RawToNative(o2::tpc::ClusterNativeAccess& native, std::unique_ptr& nativeBuffer, const AliHLTTPCRawCluster** rawClusters, uint32_t* nRawClusters); template - static void RunZSEncoder(const S& in, std::unique_ptr* outBuffer, uint32_t* outSizes, o2::raw::RawFileWriter* raw, const o2::InteractionRecord* ir, const GPUParam& param, int32_t version, bool verify, float threshold = 0.f, bool padding = false, std::function&)> digitsFilter = nullptr); + static void RunZSEncoder(const S& in, std::unique_ptr* outBuffer, uint32_t* outSizes, o2::raw::RawFileWriter* raw, const o2::InteractionRecord* ir, const GPUParam& param, int32_t version, bool verify, float threshold = 0.f, bool padding = false, const std::function&)>& digitsFilter = nullptr); static void RunZSEncoderCreateMeta(const uint64_t* buffer, const uint32_t* sizes, void** ptrs, GPUTrackingInOutZS* out); static void RunZSFilter(std::unique_ptr* buffers, const o2::tpc::Digit* const* ptrs, size_t* nsb, const size_t* ns, const GPUParam& param, bool zs12bit, float threshold); static int32_t GetMaxTimeBin(const o2::tpc::ClusterNativeAccess& native); diff --git a/GPU/GPUTracking/Base/GPUReconstructionDebug.cxx b/GPU/GPUTracking/Base/GPUReconstructionDebug.cxx index 463310c631a07..0163c5dd20fbf 100644 --- a/GPU/GPUTracking/Base/GPUReconstructionDebug.cxx +++ b/GPU/GPUTracking/Base/GPUReconstructionDebug.cxx @@ -209,7 +209,7 @@ void GPUReconstructionCPU::debugWriter::header() } } -void GPUReconstructionCPU::debugWriter::row(char type, uint32_t count, std::string name, double gpu_time, double cpu_time, double total_time, std::size_t memSize, std::string nEventReport) +void GPUReconstructionCPU::debugWriter::row(char type, uint32_t count, const std::string& name, double gpu_time, double cpu_time, double total_time, std::size_t memSize, const std::string& nEventReport) { double scale = 1000000.0 / mStatNEvents; diff --git a/GPU/GPUTracking/DataCompression/TPCClusterDecompressor.cxx b/GPU/GPUTracking/DataCompression/TPCClusterDecompressor.cxx index e28b4c476f815..78e2bd20496ce 100644 --- a/GPU/GPUTracking/DataCompression/TPCClusterDecompressor.cxx +++ b/GPU/GPUTracking/DataCompression/TPCClusterDecompressor.cxx @@ -27,7 +27,7 @@ using namespace o2::gpu; using namespace o2::tpc; -int32_t TPCClusterDecompressor::decompress(const CompressedClustersFlat* clustersCompressed, o2::tpc::ClusterNativeAccess& clustersNative, std::function allocator, const GPUParam& param, bool deterministicRec) +int32_t TPCClusterDecompressor::decompress(const CompressedClustersFlat* clustersCompressed, o2::tpc::ClusterNativeAccess& clustersNative, const std::function& allocator, const GPUParam& param, bool deterministicRec) { CompressedClusters c; const CompressedClusters* p; @@ -40,7 +40,7 @@ int32_t TPCClusterDecompressor::decompress(const CompressedClustersFlat* cluster return decompress(p, clustersNative, allocator, param, deterministicRec); } -int32_t TPCClusterDecompressor::decompress(const CompressedClusters* clustersCompressed, o2::tpc::ClusterNativeAccess& clustersNative, std::function allocator, const GPUParam& param, bool deterministicRec) +int32_t TPCClusterDecompressor::decompress(const CompressedClusters* clustersCompressed, o2::tpc::ClusterNativeAccess& clustersNative, const std::function& allocator, const GPUParam& param, bool deterministicRec) { if (clustersCompressed->nTracks && clustersCompressed->solenoidBz != -1e6f && clustersCompressed->solenoidBz != param.bzkG) { throw std::runtime_error("Configured solenoid Bz " + std::to_string(param.bzkG) + " does not match value used for track model encoding " + std::to_string(clustersCompressed->solenoidBz)); diff --git a/GPU/GPUTracking/DataCompression/TPCClusterDecompressor.h b/GPU/GPUTracking/DataCompression/TPCClusterDecompressor.h index 723a97341a53b..47c235d3567cb 100644 --- a/GPU/GPUTracking/DataCompression/TPCClusterDecompressor.h +++ b/GPU/GPUTracking/DataCompression/TPCClusterDecompressor.h @@ -33,8 +33,8 @@ class TPCClusterDecompressor { public: static constexpr uint32_t NSECTORS = GPUTPCGeometry::NSECTORS; - static int32_t decompress(const o2::tpc::CompressedClustersFlat* clustersCompressed, o2::tpc::ClusterNativeAccess& clustersNative, std::function allocator, const GPUParam& param, bool deterministicRec); - static int32_t decompress(const o2::tpc::CompressedClusters* clustersCompressed, o2::tpc::ClusterNativeAccess& clustersNative, std::function allocator, const GPUParam& param, bool deterministicRec); + static int32_t decompress(const o2::tpc::CompressedClustersFlat* clustersCompressed, o2::tpc::ClusterNativeAccess& clustersNative, const std::function& allocator, const GPUParam& param, bool deterministicRec); + static int32_t decompress(const o2::tpc::CompressedClusters* clustersCompressed, o2::tpc::ClusterNativeAccess& clustersNative, const std::function& allocator, const GPUParam& param, bool deterministicRec); }; } // namespace o2::gpu diff --git a/GPU/GPUTracking/Global/GPUChain.h b/GPU/GPUTracking/Global/GPUChain.h index e97880a9beaa3..7593cd17cd167 100644 --- a/GPU/GPUTracking/Global/GPUChain.h +++ b/GPU/GPUTracking/Global/GPUChain.h @@ -243,7 +243,7 @@ class GPUChain template bool DoDebugAndDump(RecoStep step, uint32_t mask, bool transfer, T& processor, S T::* func, Args&&... args); template - bool DoDebugDump(uint32_t mask, std::function func, Args&... args); + bool DoDebugDump(uint32_t mask, const std::function& func, Args&... args); template bool DoDebugDump(uint32_t mask, S* func, Args&&... args) { diff --git a/GPU/GPUTracking/Global/GPUChainTrackingDebug.h b/GPU/GPUTracking/Global/GPUChainTrackingDebug.h index 466fcf1312f76..c9eff9e9347de 100644 --- a/GPU/GPUTracking/Global/GPUChainTrackingDebug.h +++ b/GPU/GPUTracking/Global/GPUChainTrackingDebug.h @@ -68,7 +68,7 @@ inline bool GPUChain::DoDebugAndDump(GPUChain::RecoStep step, uint32_t mask, boo } template -inline bool GPUChain::DoDebugDump(uint32_t mask, std::function func, Args&... args) +inline bool GPUChain::DoDebugDump(uint32_t mask, const std::function& func, Args&... args) { if (GetProcessingSettings().debugLevel >= 6 && (mask == 0 || (GetProcessingSettings().debugMask & mask))) { func(args...); diff --git a/GPU/GPUTracking/Interface/GPUO2InterfaceUtils.cxx b/GPU/GPUTracking/Interface/GPUO2InterfaceUtils.cxx index 7c48898965422..92230d053294a 100644 --- a/GPU/GPUTracking/Interface/GPUO2InterfaceUtils.cxx +++ b/GPU/GPUTracking/Interface/GPUO2InterfaceUtils.cxx @@ -49,14 +49,14 @@ std::unique_ptr GPUO2InterfaceUtils::getCalibdEdxCo } template <> -void GPUO2InterfaceUtils::RunZSEncoder(const DigitArray& in, std::unique_ptr* outBuffer, uint32_t* outSizes, o2::raw::RawFileWriter* raw, const o2::InteractionRecord* ir, int32_t version, bool verify, float threshold, bool padding, std::function&)> digitsFilter) +void GPUO2InterfaceUtils::RunZSEncoder(const DigitArray& in, std::unique_ptr* outBuffer, uint32_t* outSizes, o2::raw::RawFileWriter* raw, const o2::InteractionRecord* ir, int32_t version, bool verify, float threshold, bool padding, const std::function&)>& digitsFilter) { GPUParam param; param.SetDefaults(5.00668); o2::gpu::GPUReconstructionConvert::RunZSEncoder(in, outBuffer, outSizes, raw, ir, param, version, verify, threshold, padding, digitsFilter); } template <> -void GPUO2InterfaceUtils::RunZSEncoder(const DigitArray& in, std::unique_ptr* outBuffer, uint32_t* outSizes, o2::raw::RawFileWriter* raw, const o2::InteractionRecord* ir, GPUO2InterfaceConfiguration& config, int32_t version, bool verify, bool padding, std::function&)> digitsFilter) +void GPUO2InterfaceUtils::RunZSEncoder(const DigitArray& in, std::unique_ptr* outBuffer, uint32_t* outSizes, o2::raw::RawFileWriter* raw, const o2::InteractionRecord* ir, GPUO2InterfaceConfiguration& config, int32_t version, bool verify, bool padding, const std::function&)>& digitsFilter) { GPUParam param; param.SetDefaults(&config.configGRP, &config.configReconstruction, &config.configProcessing, nullptr); diff --git a/GPU/GPUTracking/Interface/GPUO2InterfaceUtils.h b/GPU/GPUTracking/Interface/GPUO2InterfaceUtils.h index 92f87cee66232..60f9bdc7616ee 100644 --- a/GPU/GPUTracking/Interface/GPUO2InterfaceUtils.h +++ b/GPU/GPUTracking/Interface/GPUO2InterfaceUtils.h @@ -48,9 +48,9 @@ class GPUO2InterfaceUtils static std::unique_ptr getPadGainCalib(const o2::tpc::CalDet& in); static std::unique_ptr getCalibdEdxContainerDefault(); template - static void RunZSEncoder(const S& in, std::unique_ptr* outBuffer, uint32_t* outSizes, o2::raw::RawFileWriter* raw, const o2::InteractionRecord* ir, int32_t version, bool verify, float threshold = 0.f, bool padding = false, std::function&)> digitsFilter = nullptr); + static void RunZSEncoder(const S& in, std::unique_ptr* outBuffer, uint32_t* outSizes, o2::raw::RawFileWriter* raw, const o2::InteractionRecord* ir, int32_t version, bool verify, float threshold = 0.f, bool padding = false, const std::function&)>& digitsFilter = nullptr); template - static void RunZSEncoder(const S& in, std::unique_ptr* outBuffer, uint32_t* outSizes, o2::raw::RawFileWriter* raw, const o2::InteractionRecord* ir, GPUO2InterfaceConfiguration& config, int32_t version, bool verify, bool padding = false, std::function&)> digitsFilter = nullptr); + static void RunZSEncoder(const S& in, std::unique_ptr* outBuffer, uint32_t* outSizes, o2::raw::RawFileWriter* raw, const o2::InteractionRecord* ir, GPUO2InterfaceConfiguration& config, int32_t version, bool verify, bool padding = false, const std::function&)>& digitsFilter = nullptr); template static float getNominalGPUBz(T& src) { diff --git a/GPU/GPUTracking/qa/GPUQA.cxx b/GPU/GPUTracking/qa/GPUQA.cxx index de8a174f0063a..1a62cc269b010 100644 --- a/GPU/GPUTracking/qa/GPUQA.cxx +++ b/GPU/GPUTracking/qa/GPUQA.cxx @@ -2093,7 +2093,7 @@ void GPUQA::RunQA(bool matchOnly, const std::vector* tracksEx missing.emplace_back(i); } } - auto printer = [](std::vector m, const char* name) { + auto printer = [](const std::vector& m, const char* name) { if (m.size()) { printf("Missing in %s reconstruction: (%zu)\n", name, m.size()); for (uint32_t i = 0; i < m.size(); i++) { diff --git a/GPU/TPCFastTransformation/devtools/IrregularSpline2D3DCalibrator.cxx b/GPU/TPCFastTransformation/devtools/IrregularSpline2D3DCalibrator.cxx index 7eea34c19ec25..94eaea16ace7e 100644 --- a/GPU/TPCFastTransformation/devtools/IrregularSpline2D3DCalibrator.cxx +++ b/GPU/TPCFastTransformation/devtools/IrregularSpline2D3DCalibrator.cxx @@ -63,7 +63,7 @@ void IrregularSpline2D3DCalibrator::setMaxNKnots(int32_t nKnotsU, int32_t nKnots } } -void IrregularSpline2D3DCalibrator::startCalibration(std::function F) +void IrregularSpline2D3DCalibrator::startCalibration(const std::function& F) { // initialize everything for the calibration @@ -355,7 +355,7 @@ bool IrregularSpline2D3DCalibrator::doCalibrationStep() } std::unique_ptr IrregularSpline2D3DCalibrator::calibrateSpline(IrregularSpline2D3D& spline_uv, - std::function F) + const std::function& F) { // main method: spline calibration diff --git a/GPU/TPCFastTransformation/devtools/IrregularSpline2D3DCalibrator.h b/GPU/TPCFastTransformation/devtools/IrregularSpline2D3DCalibrator.h index 8ba8a2c22fa5e..4abe69f6aa229 100644 --- a/GPU/TPCFastTransformation/devtools/IrregularSpline2D3DCalibrator.h +++ b/GPU/TPCFastTransformation/devtools/IrregularSpline2D3DCalibrator.h @@ -75,7 +75,7 @@ class IrregularSpline2D3DCalibrator /// \param spline_uv - calibrated spline /// \param F - input function - std::unique_ptr calibrateSpline(IrregularSpline2D3D& spline_uv, std::function F); + std::unique_ptr calibrateSpline(IrregularSpline2D3D& spline_uv, const std::function& F); // some getters and step-by-step calibration methods. Only for debugging. @@ -98,7 +98,7 @@ class IrregularSpline2D3DCalibrator return mSplineData.data(); } - void startCalibration(std::function F); + void startCalibration(const std::function& F); bool doCalibrationStep(); private: diff --git a/GPU/Utils/Spline1DHelper.cxx b/GPU/Utils/Spline1DHelper.cxx index 8afe907ff3631..2f924b181bd9a 100644 --- a/GPU/Utils/Spline1DHelper.cxx +++ b/GPU/Utils/Spline1DHelper.cxx @@ -299,7 +299,7 @@ void Spline1DHelper::approximateDerivatives( template void Spline1DHelper::approximateFunctionClassic(Spline1DContainer& spline, - double xMin, double xMax, std::function F) + double xMin, double xMax, const std::function& F) { /// Create classic spline parameters for a given input function F /// set slopes at the knots such, that the second derivative of the spline is continious. @@ -422,7 +422,7 @@ void Spline1DHelper::approximateFunctionClassic(Spline1DContainer void Spline1DHelper::makeDataPoints( - Spline1DContainer& spline, double xMin, double xMax, std::function F, + Spline1DContainer& spline, double xMin, double xMax, const std::function& F, int32_t nAuxiliaryDataPoints, std::vector& vx, std::vector& vf) { /// Create best-fit spline parameters for a given input function F @@ -451,7 +451,7 @@ void Spline1DHelper::makeDataPoints( template void Spline1DHelper::approximateFunction( - Spline1DContainer& spline, double xMin, double xMax, std::function F, + Spline1DContainer& spline, double xMin, double xMax, const std::function& F, int32_t nAuxiliaryDataPoints) { /// Create best-fit spline parameters for a given input function F @@ -463,7 +463,7 @@ void Spline1DHelper::approximateFunction( template void Spline1DHelper::approximateFunctionGradually( - Spline1DContainer& spline, double xMin, double xMax, std::function F, + Spline1DContainer& spline, double xMin, double xMax, const std::function& F, int32_t nAuxiliaryDataPoints) { /// Create best-fit spline parameters for a given input function F diff --git a/GPU/Utils/Spline1DHelper.h b/GPU/Utils/Spline1DHelper.h index d2997936cad81..3715f6b3006c3 100644 --- a/GPU/Utils/Spline1DHelper.h +++ b/GPU/Utils/Spline1DHelper.h @@ -56,7 +56,7 @@ class Spline1DHelper /// Create best-fit spline parameters for a function F void approximateFunction( - Spline1DContainer& spline, double xMin, double xMax, std::function F, + Spline1DContainer& spline, double xMin, double xMax, const std::function& F, int32_t nAuxiliaryDataPoints = 4); /// Approximate only derivatives assuming the spline values at knozts are already set @@ -64,12 +64,12 @@ class Spline1DHelper const double vx[], const double vf[], int32_t nDataPoints); void approximateFunctionGradually( - Spline1DContainer& spline, double xMin, double xMax, std::function F, + Spline1DContainer& spline, double xMin, double xMax, const std::function& F, int32_t nAuxiliaryDataPoints); /// Create classic spline parameters for a given input function F void approximateFunctionClassic(Spline1DContainer& spline, - double xMin, double xMax, std::function F); + double xMin, double xMax, const std::function& F); /// _______________ Utilities ________________________ @@ -110,7 +110,7 @@ class Spline1DHelper void setSpline(const Spline1DContainer& spline); - void makeDataPoints(Spline1DContainer& spline, double xMin, double xMax, std::function F, + void makeDataPoints(Spline1DContainer& spline, double xMin, double xMax, const std::function& F, int32_t nAuxiliaryDataPoints, std::vector& vx, std::vector& vf); /// helpers for the construction of 1D spline diff --git a/GPU/Utils/Spline1DHelperOld.cxx b/GPU/Utils/Spline1DHelperOld.cxx index 96ba46c66c791..35eb862de8072 100644 --- a/GPU/Utils/Spline1DHelperOld.cxx +++ b/GPU/Utils/Spline1DHelperOld.cxx @@ -130,7 +130,7 @@ void Spline1DHelperOld::getDDDScoefficients(const typename Spline1D void Spline1DHelperOld::approximateFunctionClassic(Spline1DContainer& spline, - double xMin, double xMax, std::function F) + double xMin, double xMax, const std::function& F) { /// Create classic spline parameters for a given input function F /// set slopes at the knots such, that the second derivative of the spline is continious. @@ -266,7 +266,7 @@ void Spline1DHelperOld::approximateDataPoints( template void Spline1DHelperOld::approximateFunction( - Spline1DContainer& spline, double xMin, double xMax, std::function F, + Spline1DContainer& spline, double xMin, double xMax, const std::function& F, int32_t nAuxiliaryDataPoints) { /// Create best-fit spline parameters for a given input function F @@ -277,7 +277,7 @@ void Spline1DHelperOld::approximateFunction( template void Spline1DHelperOld::approximateFunctionGradually( - Spline1DContainer& spline, double xMin, double xMax, std::function F, + Spline1DContainer& spline, double xMin, double xMax, const std::function& F, int32_t nAuxiliaryDataPoints) { /// Create best-fit spline parameters gradually for a given input function F @@ -288,7 +288,7 @@ void Spline1DHelperOld::approximateFunctionGradually( template void Spline1DHelperOld::approximateFunction( - DataT* Sparameters, double xMin, double xMax, std::function F) const + DataT* Sparameters, double xMin, double xMax, const std::function& F) const { /// Create best-fit spline parameters for a given input function F /// output in Sparameters @@ -302,7 +302,7 @@ void Spline1DHelperOld::approximateFunction( template void Spline1DHelperOld::approximateFunctionGradually( - DataT* Sparameters, double xMin, double xMax, std::function F) const + DataT* Sparameters, double xMin, double xMax, const std::function& F) const { /// Create best-fit spline parameters gradually for a given input function F /// output in Sparameters diff --git a/GPU/Utils/Spline1DHelperOld.h b/GPU/Utils/Spline1DHelperOld.h index c9f4d1ba42e7d..f009f47f7f390 100644 --- a/GPU/Utils/Spline1DHelperOld.h +++ b/GPU/Utils/Spline1DHelperOld.h @@ -73,17 +73,17 @@ class Spline1DHelperOld /// Create best-fit spline parameters for a given input function F void approximateFunction(Spline1DContainer& spline, - double xMin, double xMax, std::function F, + double xMin, double xMax, const std::function& F, int32_t nAuxiliaryDataPoints = 4); /// Create best-fit spline parameters gradually for a given input function F void approximateFunctionGradually(Spline1DContainer& spline, - double xMin, double xMax, std::function F, + double xMin, double xMax, const std::function& F, int32_t nAuxiliaryDataPoints = 4); /// Create classic spline parameters for a given input function F void approximateFunctionClassic(Spline1DContainer& spline, - double xMin, double xMax, std::function F); + double xMin, double xMax, const std::function& F); /// _______________ Interface for a step-wise construction of the best-fit spline ________________________ @@ -94,10 +94,10 @@ class Spline1DHelperOld int32_t setSpline(const Spline1DContainer& spline, int32_t nFdimensions, double xMin, double xMax, double vx[], int32_t nDataPoints); /// approximate std::function, output in Fparameters - void approximateFunction(DataT* Fparameters, double xMin, double xMax, std::function F) const; + void approximateFunction(DataT* Fparameters, double xMin, double xMax, const std::function& F) const; /// approximate std::function gradually, output in Fparameters - void approximateFunctionGradually(DataT* Fparameters, double xMin, double xMax, std::function F) const; + void approximateFunctionGradually(DataT* Fparameters, double xMin, double xMax, const std::function& F) const; /// number of data points int32_t getNumberOfDataPoints() const { return mDataPoints.size(); } diff --git a/GPU/Utils/Spline1DSpec.cxx b/GPU/Utils/Spline1DSpec.cxx index 374849177a0f8..68fbc6204a478 100644 --- a/GPU/Utils/Spline1DSpec.cxx +++ b/GPU/Utils/Spline1DSpec.cxx @@ -157,7 +157,7 @@ void Spline1DContainer::print() const template void Spline1DContainer::approximateFunction( double xMin, double xMax, - std::function F, + const std::function& F, int32_t nAxiliaryDataPoints) { /// approximate a function F with this spline diff --git a/GPU/Utils/Spline1DSpec.h b/GPU/Utils/Spline1DSpec.h index b3f895cbde4ed..66fa7a1ffc4d5 100644 --- a/GPU/Utils/Spline1DSpec.h +++ b/GPU/Utils/Spline1DSpec.h @@ -166,7 +166,7 @@ class Spline1DContainer : public Spline1DContainerBase F, int32_t nAuxiliaryDataPoints = 4); + void approximateFunction(double xMin, double xMax, const std::function& F, int32_t nAuxiliaryDataPoints = 4); /// write a class object to the file int32_t writeToFile(TFile& outf, const char* name); diff --git a/GPU/Utils/Spline2DHelper.cxx b/GPU/Utils/Spline2DHelper.cxx index 9934704481001..440a816498618 100644 --- a/GPU/Utils/Spline2DHelper.cxx +++ b/GPU/Utils/Spline2DHelper.cxx @@ -53,7 +53,7 @@ int32_t Spline2DHelper::storeError(int32_t code, const char* msg) template void Spline2DHelper::approximateFunction( DataT* Fparameters, double x1Min, double x1Max, double x2Min, double x2Max, - std::function F) const + const std::function& F) const { /// Create best-fit spline parameters for a given input function F /// output in Fparameters @@ -76,7 +76,7 @@ void Spline2DHelper::approximateFunction( template void Spline2DHelper::approximateFunctionBatch( DataT* Fparameters, double x1Min, double x1Max, double x2Min, double x2Max, - std::function& x1, const std::vector& x2, std::vector f[/*mFdimensions*/])> F, + const std::function& x1, const std::vector& x2, std::vector f[/*mFdimensions*/])>& F, uint32_t batchsize) const { /// Create best-fit spline parameters for a given input function F. @@ -232,7 +232,7 @@ template void Spline2DHelper::approximateFunctionViaDataPoints( Spline2DContainerBase& spline, double x1Min, double x1Max, double x2Min, double x2Max, - std::function F, + const std::function& F, int32_t nAuxiliaryDataPointsU1, int32_t nAuxiliaryDataPointsU2) { /// Create best-fit spline parameters for a given input function F diff --git a/GPU/Utils/Spline2DHelper.h b/GPU/Utils/Spline2DHelper.h index 1eada3146bfbb..6bb2262b69576 100644 --- a/GPU/Utils/Spline2DHelper.h +++ b/GPU/Utils/Spline2DHelper.h @@ -58,14 +58,14 @@ class Spline2DHelper void approximateFunction( Spline2DContainerBase& spline, double x1Min, double x1Max, double x2Min, double x2Max, - std::function F, + const std::function& F, int32_t nAuxiliaryDataPointsU1 = 4, int32_t nAuxiliaryDataPointsU2 = 4); // A wrapper around approximateDataPoints() void approximateFunctionViaDataPoints( Spline2DContainerBase& spline, double x1Min, double x1Max, double x2Min, double x2Max, - std::function F, + const std::function& F, int32_t nAuxiliaryDataPointsU1 = 4, int32_t nAuxiliaryDataPointsU2 = 4); /// Create best-fit spline parameters for a given set of data points @@ -82,12 +82,12 @@ class Spline2DHelper /// approximate std::function, output in Fparameters void approximateFunction( DataT* Fparameters, double x1Min, double x1Max, double x2Min, double x2Max, - std::function F) const; + const std::function& F) const; /// approximate std::function, output in Fparameters. F calculates values for a batch of points. void approximateFunctionBatch( DataT* Fparameters, double x1Min, double x1Max, double x2Min, double x2Max, - std::function& x1, const std::vector& x2, std::vector f[/*mFdimensions*/])> F, + const std::function& x1, const std::vector& x2, std::vector f[/*mFdimensions*/])>& F, uint32_t batchsize) const; /// approximate a function given as an array of values at data points @@ -135,7 +135,7 @@ template void Spline2DHelper::approximateFunction( Spline2DContainerBase& spline, double x1Min, double x1Max, double x2Min, double x2Max, - std::function F, + const std::function& F, int32_t nAuxiliaryDataPointsU1, int32_t nAuxiliaryDataPointsU2) { /// Create best-fit spline parameters for a given input function F diff --git a/GPU/Utils/Spline2DSpec.cxx b/GPU/Utils/Spline2DSpec.cxx index 6622c45e3ffed..0e7f3b1d2e4a6 100644 --- a/GPU/Utils/Spline2DSpec.cxx +++ b/GPU/Utils/Spline2DSpec.cxx @@ -210,7 +210,7 @@ void Spline2DContainerBase::recreate(int32_t nYdim, template void Spline2DContainerBase::approximateFunction( double x1Min, double x1Max, double x2Min, double x2Max, - std::function F, + const std::function& F, int32_t nAuxiliaryDataPointsX1, int32_t nAuxiliaryDataPointsX2) { /// approximate a function F with this spline @@ -221,7 +221,7 @@ void Spline2DContainerBase::approximateFunction( template void Spline2DContainerBase::approximateFunctionViaDataPoints( double x1Min, double x1Max, double x2Min, double x2Max, - std::function F, + const std::function& F, int32_t nAuxiliaryDataPointsX1, int32_t nAuxiliaryDataPointsX2) { /// approximate a function F with this spline diff --git a/GPU/Utils/Spline2DSpec.h b/GPU/Utils/Spline2DSpec.h index 6f369b56722d0..f85348e0eb167 100644 --- a/GPU/Utils/Spline2DSpec.h +++ b/GPU/Utils/Spline2DSpec.h @@ -69,11 +69,11 @@ class Spline2DContainerBase : public FlatBase #if !defined(GPUCA_GPUCODE) && !defined(GPUCA_STANDALONE) /// approximate a function F with this spline void approximateFunction(double x1Min, double x1Max, double x2Min, double x2Max, - std::function F, + const std::function& F, int32_t nAuxiliaryDataPointsU1 = 4, int32_t nAuxiliaryDataPointsU2 = 4); void approximateFunctionViaDataPoints(double x1Min, double x1Max, double x2Min, double x2Max, - std::function F, + const std::function& F, int32_t nAuxiliaryDataPointsX1, int32_t nAuxiliaryDataPointsX2); #endif diff --git a/GPU/Utils/SplineHelper.cxx b/GPU/Utils/SplineHelper.cxx index 642c6817064a1..2c45b5fa610a1 100644 --- a/GPU/Utils/SplineHelper.cxx +++ b/GPU/Utils/SplineHelper.cxx @@ -89,7 +89,7 @@ int32_t SplineHelper::arraytopoints(int32_t point, int32_t result[], cons template void SplineHelper::approximateFunction( DataT* Fparameters, const double xMin[/* mXdimensions */], const double xMax[/* mXdimensions */], - std::function F) const + const std::function& F) const { /// Create best-fit spline parameters for a given input function F /// output in Fparameter @@ -156,7 +156,7 @@ void SplineHelper::approximateFunction( template void SplineHelper::approximateFunctionBatch( DataT* Fparameters, const double xMin[], const double xMax[], - std::function x[], double f[/*mFdimensions*/])> F, + const std::function x[], double f[/*mFdimensions*/])>& F, uint32_t batchsize) const { /// Create best-fit spline parameters for a given input function F. diff --git a/GPU/Utils/SplineHelper.h b/GPU/Utils/SplineHelper.h index 7e54fa4eb676d..7ca1a307c4cb5 100644 --- a/GPU/Utils/SplineHelper.h +++ b/GPU/Utils/SplineHelper.h @@ -57,7 +57,7 @@ class SplineHelper /// Create best-fit spline parameters for a given input function F void approximateFunction(SplineContainer& spline, const double xMin[/* Xdim */], const double xMax[/* Xdim */], - std::function F, + const std::function& F, const int32_t nAxiliaryDataPoints[/* Xdim */] = nullptr); /// _______________ Interface for a step-wise construction of the best-fit spline ________________________ @@ -68,12 +68,12 @@ class SplineHelper /// approximate std::function, output in Fparameters void approximateFunction( DataT* Fparameters, const double xMin[/* mXdimensions */], const double xMax[/* mXdimensions */], - std::function F) const; + const std::function& F) const; /// approximate std::function, output in Fparameters. F calculates values for a batch of points. void approximateFunctionBatch( DataT* Fparameters, const double xMin[/* mXdimensions */], const double xMax[/* mXdimensions */], - std::function x[/* mXdimensions */], double f[/*mFdimensions*/])> F, + const std::function x[/* mXdimensions */], double f[/*mFdimensions*/])>& F, uint32_t batchsize) const; /// approximate a function given as an array of values at data points @@ -116,7 +116,7 @@ template void SplineHelper::approximateFunction( SplineContainer& spline, const double xMin[/* Xdim */], const double xMax[/* Xdim */], - std::function F, + const std::function& F, const int32_t nAxiliaryDataPoints[/* Xdim */]) { /// Create best-fit spline parameters for a given input function F diff --git a/GPU/Utils/SplineSpec.cxx b/GPU/Utils/SplineSpec.cxx index 373c6005f643a..a2f09cc2c8f6b 100644 --- a/GPU/Utils/SplineSpec.cxx +++ b/GPU/Utils/SplineSpec.cxx @@ -192,7 +192,7 @@ void SplineContainer::recreate( template void SplineContainer:: approximateFunction(const double xMin[/* mXdim */], const double xMax[/* mXdim */], - std::function F, + const std::function& F, const int32_t nAuxiliaryDataPoints[/* mXdim */]) { /// approximate a function F with this spline diff --git a/GPU/Utils/SplineSpec.h b/GPU/Utils/SplineSpec.h index a8f7a885f2aa1..c306ae4240e03 100644 --- a/GPU/Utils/SplineSpec.h +++ b/GPU/Utils/SplineSpec.h @@ -68,7 +68,7 @@ class SplineContainer : public FlatObject #if !defined(GPUCA_GPUCODE) && !defined(GPUCA_STANDALONE) /// approximate a function F with this spline void approximateFunction(const double xMin[/* mXdim */], const double xMax[/* mXdim */], - std::function F, + const std::function& F, const int32_t nAuxiliaryDataPoints[/* mXdim */] = nullptr); #endif From d271e929d7dc9b88230bb791b7051cfe5bb739f9 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Tue, 1 Dec 2026 14:55:41 +0100 Subject: [PATCH 09/41] GPU: Modernize C++: Use std::format instead of snprintf, to_string, stringstream, and replace many std::cout << ... --- GPU/GPUTracking/Base/GPUReconstruction.cxx | 25 +-- GPU/GPUTracking/Base/GPUReconstructionCPU.cxx | 3 +- .../Base/GPUReconstructionConvert.cxx | 61 +++--- .../Base/GPUReconstructionDebug.cxx | 59 +----- .../Base/GPUReconstructionRTCHelpers.inc | 28 +-- .../cpudevice/GPUReconstructionCPUDevice.cxx | 3 +- .../GPUReconstructionCPUDeviceGenRTC.cxx | 5 +- .../Base/cuda/GPUReconstructionCUDAGenRTC.cxx | 3 +- .../GPUReconstructionMetalIncludesHost.h | 6 +- .../metal/GPUReconstructionMetalKernels.mm | 2 +- .../Base/opencl/GPUReconstructionOCL.cxx | 3 +- .../TPCClusterDecompressor.cxx | 5 +- GPU/GPUTracking/DataTypes/GPUConfigDump.cxx | 6 +- GPU/GPUTracking/Global/GPUChainTracking.cxx | 3 +- .../Global/GPUChainTrackingClusterizer.cxx | 16 +- .../Global/GPUChainTrackingCompression.cxx | 5 +- .../GPUChainTrackingDebugAndProfiling.cxx | 11 +- GPU/GPUTracking/Interface/GPUO2Interface.cxx | 8 +- GPU/GPUTracking/Merger/GPUTPCGMMerger.cxx | 7 +- .../SectorTracker/GPUTPCTrackerDump.cxx | 6 +- .../Standalone/Benchmark/standalone.cxx | 22 +-- .../GPUTPCClusterFinderDump.cxx | 3 +- .../TPCClusterFinder/GPUTPCNNClusterizer.cxx | 16 +- GPU/GPUTracking/display/GPUDisplay.cxx | 7 +- .../display/frontend/GPUDisplayConsole.cxx | 7 +- .../frontend/GPUDisplayFrontendConfig.cxx | 11 +- .../GPUDisplayFrontendConfigConsole.inc | 5 +- .../frontend/GPUDisplayFrontendConfigInfo.inc | 6 +- .../GPUDisplayFrontendConfigQtGUI.inc | 4 +- .../display/helpers/GPUDisplayHelpers.cxx | 3 +- .../display/helpers/GPUDisplayROOT.cxx | 3 +- GPU/GPUTracking/qa/GPUQA.cxx | 176 +++++++++--------- GPU/GPUTracking/qa/GPUQA.h | 2 +- GPU/GPUTracking/qa/genEvents.cxx | 14 +- .../TPCFastSpaceChargeCorrection.cxx | 6 +- GPU/Utils/SymMatrixSolver.cxx | 4 +- GPU/Workflow/src/GPUWorkflowSpec.cxx | 7 +- 37 files changed, 246 insertions(+), 315 deletions(-) diff --git a/GPU/GPUTracking/Base/GPUReconstruction.cxx b/GPU/GPUTracking/Base/GPUReconstruction.cxx index 89da4e0f8508a..974a4aa4ae908 100644 --- a/GPU/GPUTracking/Base/GPUReconstruction.cxx +++ b/GPU/GPUTracking/Base/GPUReconstruction.cxx @@ -22,6 +22,7 @@ #include #include #include +#include #include "GPUReconstruction.h" #include "GPUReconstructionIncludes.h" @@ -603,7 +604,7 @@ size_t GPUReconstruction::AllocateRegisteredMemoryHelper(GPUMemoryResource* res, throw std::bad_alloc(); } if (GetProcessingSettings().allocDebugLevel >= 2 && !GetProcessingSettings().debugSilent) { - std::cout << "Reused (" << device << ") " << res->mName << ": " << retVal << "\n"; + std::cout << std::format("Reused ({}) {}: {}\n", device, res->mName, retVal); } return retVal; } @@ -634,11 +635,11 @@ size_t GPUReconstruction::AllocateRegisteredMemoryHelper(GPUMemoryResource* res, memorypool = (void*)((char*)memorypool + GPUProcessor::getAlignment(memorypool)); } if (memorypoolend ? (memorypool > memorypoolend) : ((size_t)ptrDiff(memorypool, memorybase) > memorysize)) { - std::cerr << "Memory pool size exceeded (" << device << ") (" << res->mName << ": " << (memorypoolend ? (memorysize + ptrDiff(memorypool, memorypoolend)) : ptrDiff(memorypool, memorybase)) << " > " << memorysize << "\n"; + std::cerr << std::format("Memory pool size exceeded ({}) ({}: {} > {}\n", device, res->mName, memorypoolend ? (memorysize + ptrDiff(memorypool, memorypoolend)) : ptrDiff(memorypool, memorybase), memorysize); throw std::bad_alloc(); } if (GetProcessingSettings().allocDebugLevel >= 2 && !GetProcessingSettings().debugSilent) { - std::cout << "Allocated (" << device << ") " << res->mName << ": " << retVal << " - available: " << (memorypoolend ? ptrDiff(memorypoolend, memorypool) : (memorysize - ptrDiff(memorypool, memorybase))) << "\n"; + std::cout << std::format("Allocated ({}) {}: {} - available: {}\n", device, res->mName, retVal, memorypoolend ? ptrDiff(memorypoolend, memorypool) : (memorysize - ptrDiff(memorypool, memorybase))); } return retVal; } @@ -663,7 +664,7 @@ void GPUReconstruction::AllocateRegisteredMemoryInternal(GPUMemoryResource* res, res->mPtr = GPUProcessor::alignPointer(res->mPtrDevice); res->SetPointers(res->mPtr); if (GetProcessingSettings().allocDebugLevel >= 2 && !GetProcessingSettings().debugSilent) { - std::cout << (res->mReuse >= 0 ? "Reused " : "Allocated ") << res->mName << ": " << res->mSize << " (individual" << ((res->mType & GPUMemoryResource::MEMORY_STACK) ? " stack" : "") << ")\n"; + std::cout << std::format("{} {}: {} (individual{})\n", res->mReuse >= 0 ? "Reused" : "Allocated", res->mName, res->mSize, (res->mType & GPUMemoryResource::MEMORY_STACK) ? " stack" : ""); } if (res->mType & GPUMemoryResource::MEMORY_STACK) { stdspinlock spinlock(mMemoryMutex); @@ -689,7 +690,7 @@ void GPUReconstruction::AllocateRegisteredMemoryInternal(GPUMemoryResource* res, res->mPtr = control->allocator(CAMath::nextMultipleOf(res->mSize)); res->mSize = std::max(ptrDiff(res->SetPointers(res->mPtr), res->mPtr), res->mOverrideSize); if (GetProcessingSettings().allocDebugLevel >= 2 && !GetProcessingSettings().debugSilent) { - std::cout << "Allocated (from callback) " << res->mName << ": " << res->mSize << "\n"; + std::cout << std::format("Allocated (from callback) {}: {}\n", res->mName, res->mSize); } } else { void* dummy = nullptr; @@ -785,7 +786,7 @@ void* GPUReconstruction::AllocateDirectMemory(size_t size, int32_t type) } UpdateMaxMemoryUsed(); if (GetProcessingSettings().allocDebugLevel >= 2 && !GetProcessingSettings().debugSilent) { - std::cout << "Allocated (direct " << ((type & GPUMemoryResource::MEMORY_GPU) ? "gpu" : "host") << "): " << size << " - available: " << ptrDiff(poolend, pool) << "\n"; + std::cout << std::format("Allocated (direct {}): {} - available: {}\n", (type & GPUMemoryResource::MEMORY_GPU) ? "gpu" : "host", size, ptrDiff(poolend, pool)); } return retVal; } @@ -807,7 +808,7 @@ void* GPUReconstruction::AllocateVolatileDeviceMemory(size_t size) } UpdateMaxMemoryUsed(); if (GetProcessingSettings().allocDebugLevel >= 2 && !GetProcessingSettings().debugSilent) { - std::cout << "Allocated (volatile GPU): " << size << " - available: " << ptrDiff(mDeviceMemoryPoolEnd, mDeviceMemoryPool) << "\n"; + std::cout << std::format("Allocated (volatile GPU): {} - available: {}\n", size, ptrDiff(mDeviceMemoryPoolEnd, mDeviceMemoryPool)); } return retVal; } @@ -837,7 +838,7 @@ void GPUReconstruction::ReturnVolatileDeviceMemory() mVolatileMemoryStart = nullptr; } if (GetProcessingSettings().allocDebugLevel >= 2 && !GetProcessingSettings().debugSilent) { - std::cout << "Freed (volatile GPU) - available: " << ptrDiff(mDeviceMemoryPoolEnd, mDeviceMemoryPool) << "\n"; + std::cout << std::format("Freed (volatile GPU) - available: {}\n", ptrDiff(mDeviceMemoryPoolEnd, mDeviceMemoryPool)); } } @@ -863,7 +864,7 @@ void GPUReconstruction::ResetRegisteredMemoryPointers(int16_t ires) void* basePtr = res->mReuse >= 0 ? mMemoryResources[res->mReuse].mPtr : res->mPtr; size_t size = ptrDiff(res->SetPointers(basePtr), basePtr); if (basePtr && size > std::max(res->mSize, res->mOverrideSize)) { - std::cerr << "Updated pointers exceed available memory size: " << size << " > " << std::max(res->mSize, res->mOverrideSize) << " - host - " << res->mName << "\n"; + std::cerr << std::format("Updated pointers exceed available memory size: {} > {} - host - {}\n", size, std::max(res->mSize, res->mOverrideSize), res->mName); throw std::bad_alloc(); } } @@ -871,7 +872,7 @@ void GPUReconstruction::ResetRegisteredMemoryPointers(int16_t ires) void* basePtr = res->mReuse >= 0 ? mMemoryResources[res->mReuse].mPtrDevice : res->mPtrDevice; size_t size = ptrDiff(res->SetDevicePointers(basePtr), basePtr); if (basePtr && size > std::max(res->mSize, res->mOverrideSize)) { - std::cerr << "Updated pointers exceed available memory size: " << size << " > " << std::max(res->mSize, res->mOverrideSize) << " - GPU - " << res->mName << "\n"; + std::cerr << std::format("Updated pointers exceed available memory size: {} > {} - GPU - {}\n", size, std::max(res->mSize, res->mOverrideSize), res->mName); throw std::bad_alloc(); } } @@ -894,7 +895,7 @@ void GPUReconstruction::FreeRegisteredMemory(int16_t ires) void GPUReconstruction::FreeRegisteredMemory(GPUMemoryResource* res) { if (GetProcessingSettings().allocDebugLevel >= 2 && !GetProcessingSettings().debugSilent && (res->mPtr || res->mPtrDevice)) { - std::cout << "Freeing " << res->mName << ": size " << res->mSize << " (reused " << res->mReuse << ")\n"; + std::cout << std::format("Freeing {}: size {} (reused {})\n", res->mName, res->mSize, res->mReuse); } if (GetProcessingSettings().memoryAllocationStrategy == GPUMemoryResource::ALLOCATION_INDIVIDUAL && res->mReuse < 0) { alignedDefaultBufferDeleter()(res->mPtrDevice); @@ -934,7 +935,7 @@ void GPUReconstruction::PopNonPersistentMemory(RecoStep step, uint64_t tag, cons continue; } if (GetProcessingSettings().allocDebugLevel >= 2 && !GetProcessingSettings().debugSilent && (res->mPtr || res->mPtrDevice)) { - std::cout << "Freeing NonPersistent " << res->mName << ": size " << res->mSize << " (reused " << res->mReuse << ")\n"; + std::cout << std::format("Freeing NonPersistent {}: size {} (reused {})\n", res->mName, res->mSize, res->mReuse); } if (res->mReuse < 0) { alignedDefaultBufferDeleter()(res->mPtrDevice); diff --git a/GPU/GPUTracking/Base/GPUReconstructionCPU.cxx b/GPU/GPUTracking/Base/GPUReconstructionCPU.cxx index d394a65d4f50e..22a0e0013a59a 100644 --- a/GPU/GPUTracking/Base/GPUReconstructionCPU.cxx +++ b/GPU/GPUTracking/Base/GPUReconstructionCPU.cxx @@ -35,6 +35,7 @@ #include #include +#include #include #ifndef _WIN32 @@ -317,7 +318,7 @@ int32_t GPUReconstructionCPU::RunChains() mStatWallTime = (mTimerTotal.GetElapsedTime() * 1000000. / mStatNEvents); std::string nEventReport; if (GetProcessingSettings().debugLevel >= 0 && mStatNEvents > 1) { - nEventReport += " (avergage of " + std::to_string(mStatNEvents) + " runs)"; + nEventReport += std::format(" (average of {} runs)", mStatNEvents); } double kernelTotal = 0; std::vector kernelStepTimes(gpudatatypes::N_RECO_STEPS, 0.); diff --git a/GPU/GPUTracking/Base/GPUReconstructionConvert.cxx b/GPU/GPUTracking/Base/GPUReconstructionConvert.cxx index 144a094a48d06..15f18774abd80 100644 --- a/GPU/GPUTracking/Base/GPUReconstructionConvert.cxx +++ b/GPU/GPUTracking/Base/GPUReconstructionConvert.cxx @@ -31,6 +31,8 @@ #include #include #include +#include +#include #include "clusterFinderDefs.h" #include "DataFormatsTPC/ZeroSuppression.h" @@ -47,7 +49,6 @@ using namespace o2::gpu; using namespace o2::tpc; using namespace o2::tpc::constants; -using namespace std::string_literals; void GPUReconstructionConvert::ConvertRun2RawToNative(o2::tpc::ClusterNativeAccess& native, std::unique_ptr& nativeBuffer, const AliHLTTPCRawCluster** rawClusters, uint32_t* nRawClusters) { @@ -360,7 +361,7 @@ void zsEncoderRow::decodePage(std::vector& outputBuffer, const z const TPCZSHDR* decHDR = reinterpret_cast(decPagePtr); decPagePtr += sizeof(*decHDR); if (decHDR->version != 1 && decHDR->version != 2) { - throw std::runtime_error("invalid ZS version "s + std::to_string(decHDR->version) + " (1 or 2 expected)"s); + throw std::runtime_error(std::format("invalid ZS version {} (1 or 2 expected)", decHDR->version)); } const float decodeBitsFactor = 1.f / (1 << (encodeBits - 10)); uint32_t mask = (1 << encodeBits) - 1; @@ -617,7 +618,7 @@ void zsEncoderImprovedLinkBased::decodePage(std::vector& outputB const TPCZSHDRV2* decHDR = reinterpret_cast(decPagePtr); decPagePtr += sizeof(*decHDR); if (decHDR->version != ZSVersion::ZSVersionLinkBasedWithMeta) { - throw std::runtime_error("invalid ZS version "s + std::to_string(decHDR->version) + " ("s + std::to_string(ZSVersion::ZSVersionLinkBasedWithMeta) + " expected)"s); + throw std::runtime_error(std::format("invalid ZS version {} ({} expected)", decHDR->version, (int32_t)ZSVersion::ZSVersionLinkBasedWithMeta)); } if (decHDR->magicWord != o2::tpc::zerosupp_link_based::CommonHeader::MagicWordLinkZSMetaHeader) { throw std::runtime_error("Magic word missing"); @@ -694,7 +695,7 @@ struct zsEncoderDenseLinkBased : public zsEncoderLinkBased { void decodePage(std::vector& outputBuffer, const zsPage* page, uint32_t endpoint, uint32_t firstOrbit, uint32_t triggerBC = 0); bool writeSubPage(); void initPage(); - void amendPageErrorMessage(std::ostringstream& oss, const o2::header::RAWDataHeader* rdh, const TPCZSHDRV2* decHDR, const uint8_t* payloadEnd, const uint8_t* decPagePtr, uint32_t nOutput); + void amendPageErrorMessage(std::string& msg, const o2::header::RAWDataHeader* rdh, const TPCZSHDRV2* decHDR, const uint8_t* payloadEnd, const uint8_t* decPagePtr, uint32_t nOutput); uint16_t curTimeBin = 0; std::vector sequenceBuffer; @@ -825,7 +826,7 @@ void zsEncoderDenseLinkBased::decodePage(std::vector& outputBuff const TPCZSHDRV2* decHDR = reinterpret_cast(decPagePtr + o2::raw::RDHUtils::getMemorySize(*rdh) - sizeof(TPCZSHDRV2)); decPagePtr += sizeof(o2::header::RAWDataHeader); if (decHDR->version < ZSVersion::ZSVersionDenseLinkBased || decHDR->version > ZSVersion::ZSVersionDenseLinkBasedV2) { - throw std::runtime_error("invalid ZS version "s + std::to_string(decHDR->version) + " ("s + std::to_string(ZSVersion::ZSVersionDenseLinkBased) + " - "s + std::to_string(ZSVersion::ZSVersionDenseLinkBasedV2) + " expected)"s); + throw std::runtime_error(std::format("invalid ZS version {} ({} - {} expected)", decHDR->version, (int32_t)ZSVersion::ZSVersionDenseLinkBased, (int32_t)ZSVersion::ZSVersionDenseLinkBasedV2)); } if (decHDR->magicWord != o2::tpc::zerosupp_link_based::CommonHeader::MagicWordLinkZSMetaHeader) { throw std::runtime_error("Magic word missing"); @@ -963,50 +964,46 @@ void zsEncoderDenseLinkBased::decodePage(std::vector& outputBuff int32_t hdrMaxTimeBin = hdrMinTimeBin + decHDR->nTimeBinSpan + ((decHDR->flags & TPCZSHDRV2::ZSFlags::nTimeBinSpanBit8) ? 256 : 0); if (!extendFailure && nOutput != decHDR->nADCsamples) { - std::ostringstream oss; - oss << "Number of decoded digits " << nOutput << " does not match value from MetaInfo " << decHDR->nADCsamples; - amendPageErrorMessage(oss, rdh, decHDR, nullptr, nullptr, nOutput); - throw std::runtime_error(oss.str()); + std::string msg = std::format("Number of decoded digits {} does not match value from MetaInfo {}", nOutput, decHDR->nADCsamples); + amendPageErrorMessage(msg, rdh, decHDR, nullptr, nullptr, nOutput); + throw std::runtime_error(msg); } if (decHDR->nADCsamples && (minTimeBin < hdrMinTimeBin || maxTimeBin > hdrMaxTimeBin)) { - std::ostringstream oss; - oss << "Incorrect time bin range in MetaInfo, header reports " << hdrMinTimeBin << " - " << hdrMaxTimeBin << "(timeOffset: " << decHDR->timeOffset << " + (orbit: " << o2::raw::RDHUtils::getHeartBeatOrbit(*rdh) << " - firstOrbit " << firstOrbit << ") * LHCMaxBunches - triggerBC: " << triggerBC << ", decoded data is " << minTimeBin << " - " << maxTimeBin; - amendPageErrorMessage(oss, rdh, decHDR, payloadEnd, decPagePtr, nOutput); - throw std::runtime_error(oss.str()); + std::string msg = std::format("Incorrect time bin range in MetaInfo, header reports {} - {}(timeOffset: {} + (orbit: {} - firstOrbit {}) * LHCMaxBunches - triggerBC: {}, decoded data is {} - {}", hdrMinTimeBin, hdrMaxTimeBin, decHDR->timeOffset, o2::raw::RDHUtils::getHeartBeatOrbit(*rdh), firstOrbit, triggerBC, minTimeBin, maxTimeBin); + amendPageErrorMessage(msg, rdh, decHDR, payloadEnd, decPagePtr, nOutput); + throw std::runtime_error(msg); } if (decHDR->nTimebinHeaders && payloadEnd - decPagePtr < 0) { - std::ostringstream oss; - oss << "Decoding ran over end of page"; - amendPageErrorMessage(oss, rdh, decHDR, payloadEnd, decPagePtr, nOutput); - throw std::runtime_error(oss.str()); + std::string msg = "Decoding ran over end of page"; + amendPageErrorMessage(msg, rdh, decHDR, payloadEnd, decPagePtr, nOutput); + throw std::runtime_error(msg); } if (decHDR->nTimebinHeaders && payloadEnd - decPagePtr >= 2 * o2::raw::RDHUtils::GBTWord128) { - std::ostringstream oss; - oss << "Decoding didn't reach end of page"; - amendPageErrorMessage(oss, rdh, decHDR, payloadEnd, decPagePtr, nOutput); - throw std::runtime_error(oss.str()); + std::string msg = "Decoding didn't reach end of page"; + amendPageErrorMessage(msg, rdh, decHDR, payloadEnd, decPagePtr, nOutput); + throw std::runtime_error(msg); } } -void zsEncoderDenseLinkBased::amendPageErrorMessage(std::ostringstream& oss, const o2::header::RAWDataHeader* rdh, const TPCZSHDRV2* decHDR, const uint8_t* payloadEnd, const uint8_t* decPagePtr, uint32_t nOutput) +void zsEncoderDenseLinkBased::amendPageErrorMessage(std::string& msg, const o2::header::RAWDataHeader* rdh, const TPCZSHDRV2* decHDR, const uint8_t* payloadEnd, const uint8_t* decPagePtr, uint32_t nOutput) { + auto out = std::back_inserter(msg); if (payloadEnd && decPagePtr) { - oss << " (payloadEnd " << (void*)payloadEnd << " - decPagePtr " << (void*)decPagePtr << " - " << (payloadEnd - decPagePtr) << " bytes left, " << nOutput << " of " << decHDR->nADCsamples << " digits decoded)\n"; + std::format_to(out, " (payloadEnd {} - decPagePtr {} - {} bytes left, {} of {} digits decoded)\n", (const void*)payloadEnd, (const void*)decPagePtr, payloadEnd - decPagePtr, nOutput, decHDR->nADCsamples); } else { - oss << "\n"; + msg += "\n"; } - constexpr size_t bufferSize = 3 * std::max(sizeof(*rdh), sizeof(*decHDR)) + 1; - char dumpBuffer[bufferSize]; + msg += "RDH of page: "; for (size_t i = 0; i < sizeof(*rdh); i++) { - snprintf(dumpBuffer + 3 * i, 4, "%02X ", (int32_t)((uint8_t*)rdh)[i]); + std::format_to(out, "{:02X} ", ((const uint8_t*)rdh)[i]); } - oss << "RDH of page: " << dumpBuffer << "\n"; + msg += "\nMeta header of page: "; for (size_t i = 0; i < sizeof(*decHDR); i++) { - snprintf(dumpBuffer + 3 * i, 4, "%02X ", (int32_t)((uint8_t*)decHDR)[i]); + std::format_to(out, "{:02X} ", ((const uint8_t*)decHDR)[i]); } - oss << "Meta header of page: " << dumpBuffer << "\n"; + msg += "\n"; } #endif // !GPUCA_STANDALONE @@ -1340,7 +1337,7 @@ void GPUReconstructionConvert::RunZSEncoder(const S& in, std::unique_ptr&, const void*, uint32_t, uint32_t } else if (version >= o2::tpc::ZSVersion::ZSVersionDenseLinkBased && version <= o2::tpc::ZSVersion::ZSVersionDenseLinkBasedV2) { return o2::gpu::internal::GetDecoder_internal(param, version); } else { - throw std::runtime_error("Invalid ZS version "s + std::to_string(version) + ", cannot create decoder"s); + throw std::runtime_error(std::format("Invalid ZS version {}, cannot create decoder", version)); } } #endif diff --git a/GPU/GPUTracking/Base/GPUReconstructionDebug.cxx b/GPU/GPUTracking/Base/GPUReconstructionDebug.cxx index 0163c5dd20fbf..7d0bb7ef3a998 100644 --- a/GPU/GPUTracking/Base/GPUReconstructionDebug.cxx +++ b/GPU/GPUTracking/Base/GPUReconstructionDebug.cxx @@ -152,9 +152,7 @@ std::string GPUReconstruction::getDebugFolder(const std::string& prefix) return ""; } - auto currentTime = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); - std::ostringstream dateTime; - dateTime << std::put_time(std::localtime(¤tTime), "%Y-%m-%d_%H-%M-%S"); + const std::string dateTime = std::format("{:%Y-%m-%d_%H-%M-%S}_UTC", std::chrono::floor(std::chrono::system_clock::now())); // UTC, since std::chrono::current_zone() can throw int32_t attempt = 0; std::string outname; @@ -164,7 +162,7 @@ std::string GPUReconstruction::getDebugFolder(const std::string& prefix) return ""; } - outname = GetProcessingSettings().debugOnFailureDirectory + "/debug_" + prefix + (prefix == "" ? "" : "_") + dateTime.str() + "_" + std::to_string(attempt); + outname = std::format("{}/debug_{}{}{}_{}", GetProcessingSettings().debugOnFailureDirectory, prefix, prefix == "" ? "" : "_", dateTime, attempt); std::error_code ec; bool created = std::filesystem::create_directory(outname, ec); if (!ec && created) { @@ -212,29 +210,12 @@ void GPUReconstructionCPU::debugWriter::header() void GPUReconstructionCPU::debugWriter::row(char type, uint32_t count, const std::string& name, double gpu_time, double cpu_time, double total_time, std::size_t memSize, const std::string& nEventReport) { double scale = 1000000.0 / mStatNEvents; + auto cell = [](bool valid, double v, int32_t width, int32_t prec, const char* sep) { return valid ? std::format("{:{}.{}f}{}", v, width, prec, sep) : std::format("{:{}}{}", "", width, sep); }; + const std::string countStr = count ? std::to_string(count) : ""; + const bool hasGPU = gpu_time != -1.0, hasCPU = cpu_time != -1.0, hasTotal = total_time != -1.0; if (streamCSV.is_open()) { - streamCSV << type << ","; - if (count != 0) { - streamCSV << count; - } - streamCSV << "," << name << ","; - if (gpu_time != -1.0) { - streamCSV << std::format("{:.0f}", gpu_time * scale); - } - streamCSV << ","; - if (cpu_time != -1.0) { - streamCSV << std::format("{:.0f}", cpu_time * scale); - } - streamCSV << ","; - if (cpu_time != -1.0 && total_time != -1.0) { - streamCSV << std::format("{:.2f}", cpu_time / total_time); - } - streamCSV << ","; - if (total_time != -1.0) { - streamCSV << std::format("{:.0f}", total_time * scale); - } - streamCSV << ","; + streamCSV << std::format("{},{},{},{}{}{}{}", type, countStr, name, cell(hasGPU, gpu_time * scale, 0, 0, ","), cell(hasCPU, cpu_time * scale, 0, 0, ","), cell(hasCPU && hasTotal, cpu_time / total_time, 0, 2, ","), cell(hasTotal, total_time * scale, 0, 0, ",")); if (memSize != 0 && count != 0) { streamCSV << std::format("{:.3f},{},{}", memSize / gpu_time * 1e-9, memSize / mStatNEvents, memSize / mStatNEvents / count); } else { @@ -244,33 +225,7 @@ void GPUReconstructionCPU::debugWriter::row(char type, uint32_t count, const std } if (mMarkdown) { - std::cout << "| " << type << " | "; - if (count != 0) { - std::cout << std::format("{:6} |", count); - } else { - std::cout << " |"; - } - std::cout << std::format(" {:42}|", name); - if (gpu_time != -1.0) { - std::cout << std::format("{:10.0f} |", gpu_time * scale); - } else { - std::cout << " |"; - } - if (cpu_time != -1.0) { - std::cout << std::format("{:10.0f} |", cpu_time * scale); - } else { - std::cout << " |"; - } - if (cpu_time != -1.0 && total_time != -1.0) { - std::cout << std::format("{:8.2f} |", cpu_time / total_time); - } else { - std::cout << " |"; - } - if (total_time != -1.0) { - std::cout << std::format("{:10.0f} |", total_time * scale); - } else { - std::cout << " |"; - } + std::cout << std::format("| {} | {:>6} | {:42}|{}{}{}{}", type, countStr, name, cell(hasGPU, gpu_time * scale, 10, 0, " |"), cell(hasCPU, cpu_time * scale, 10, 0, " |"), cell(hasCPU && hasTotal, cpu_time / total_time, 8, 2, " |"), cell(hasTotal, total_time * scale, 10, 0, " |")); if (memSize != 0 && count != 0) { std::cout << std::format("{:10.3f} |{:14} |{:14} |", memSize / gpu_time * 1e-9, memSize / mStatNEvents, memSize / mStatNEvents / count); } else { diff --git a/GPU/GPUTracking/Base/GPUReconstructionRTCHelpers.inc b/GPU/GPUTracking/Base/GPUReconstructionRTCHelpers.inc index d7de633b82818..49ccbabc35c58 100644 --- a/GPU/GPUTracking/Base/GPUReconstructionRTCHelpers.inc +++ b/GPU/GPUTracking/Base/GPUReconstructionRTCHelpers.inc @@ -27,6 +27,8 @@ #include #include #include +#include +#include #include #include #include @@ -53,7 +55,7 @@ static std::string paramCode(const GPUSettingsProcessing& proc, const GPUParam& static void tmpFilename(std::string& filename, const char* defaultPrefix) { - filename = (filename == "" ? defaultPrefix : filename) + std::to_string(getpid()) + "_" + std::to_string(rand()); + filename = std::format("{}{}_{}", filename == "" ? defaultPrefix : filename, getpid(), rand()); } static std::string joinKernels(const std::vector& kernels) @@ -103,7 +105,7 @@ static void loadLaunchBounds(const GPUSettingsProcessing& proc, GPUDefParameters static std::string launchBoundsCode(const GPUSettingsProcessing& proc, const GPUDefParameters& par, int32_t minBlockFactor, uint32_t warpSize) { - std::string retVal = GPUDefParametersExport(par, true, minBlockFactor) + "#define GPUCA_WARP_SIZE " + std::to_string(warpSize) + "\n"; + std::string retVal = std::format("{}#define GPUCA_WARP_SIZE {}\n", GPUDefParametersExport(par, true, minBlockFactor), warpSize); if (proc.rtctech.printLaunchBounds || (proc.debugLevel >= 3 && !proc.debugSilent)) { GPUInfo("RTC Launch Bounds:\n%s", retVal.c_str()); fflush(stdout); @@ -187,9 +189,7 @@ class Cache // RTC cache file /rtc..cache. (no id with id ^= block; } } - char idStr[11]; - snprintf(idStr, sizeof(idStr), "%010llX", (unsigned long long)id); - mFileName = mProc.rtctech.ignoreCacheValid ? mPrefix.substr(0, mPrefix.size() - 1) : (mPrefix + idStr); // Without id for ignoreCacheValid, to find the cache file for any input + mFileName = mProc.rtctech.ignoreCacheValid ? mPrefix.substr(0, mPrefix.size() - 1) : std::format("{}{:010X}", mPrefix, id); // Without id for ignoreCacheValid, to find the cache file for any input mFile = mProc.rtctech.cacheFolder + "/" + mFileName; if (mProc.rtctech.cacheFolder != ".") { std::filesystem::create_directories(mProc.rtctech.cacheFolder); @@ -259,7 +259,7 @@ class Cache // RTC cache file /rtc..cache. (no id with } std::vector buffer; for (uint32_t i = 0; i < nCompile; i++) { - FILE* fp2 = fopen((filename + "_" + std::to_string(i) + binExtension).c_str(), "rb"); + FILE* fp2 = fopen(std::format("{}_{}{}", filename, i, binExtension).c_str(), "rb"); if (fp2 == nullptr) { throw std::runtime_error("Cannot open RTC binary file"); } @@ -311,12 +311,14 @@ class Cache // RTC cache file /rtc..cache. (no id with throw std::runtime_error("Cache file corrupt"); } if (mProc.debugLevel >= 3) { - char shaprint1[41], shaprint2[41]; - for (uint32_t j = 0; j < 20; j++) { - snprintf(shaprint1 + 2 * j, 3, "%02X", (uint8_t)mSHA[i][j]); - snprintf(shaprint2 + 2 * j, 3, "%02X", (uint8_t)sharead[j]); - } - GPUInfo("SHA for %s: expected %s, read %s", names[i], shaprint1, shaprint2); + auto hex = [](const char* sha) { + std::string retVal; + for (uint32_t j = 0; j < 20; j++) { + std::format_to(std::back_inserter(retVal), "{:02X}", (uint8_t)sha[j]); + } + return retVal; + }; + GPUInfo("SHA for %s: expected %s, read %s", names[i], hex(mSHA[i]).c_str(), hex(sharead).c_str()); } if (!mProc.rtctech.ignoreCacheValid && memcmp(sharead, mSHA[i], 20)) { GPUInfo("Cache file content outdated (%s)", names[i]); @@ -342,7 +344,7 @@ class Cache // RTC cache file /rtc..cache. (no id with if (fread(buffer.data(), 1, len, fp) != len) { throw std::runtime_error("Cache file corrupt"); } - FILE* fp2 = fopen((filename + "_" + std::to_string(i) + binExtension).c_str(), "w+b"); + FILE* fp2 = fopen(std::format("{}_{}{}", filename, i, binExtension).c_str(), "w+b"); if (fp2 == nullptr) { throw std::runtime_error("Cannot open tmp file"); } diff --git a/GPU/GPUTracking/Base/cpudevice/GPUReconstructionCPUDevice.cxx b/GPU/GPUTracking/Base/cpudevice/GPUReconstructionCPUDevice.cxx index 475c372c4eeee..d9cc7af3966a5 100644 --- a/GPU/GPUTracking/Base/cpudevice/GPUReconstructionCPUDevice.cxx +++ b/GPU/GPUTracking/Base/cpudevice/GPUReconstructionCPUDevice.cxx @@ -23,6 +23,7 @@ #include #include +#include #include #include #include @@ -254,7 +255,7 @@ void GPUReconstructionCPUDeviceInternals::completeEvent(GPUReconstructionCPUDevi void GPUReconstructionCPUDevice::EnqueueTask(int32_t stream, deviceEvent* evList, int32_t nEvents, deviceEvent* ev, std::function&& work) { if (stream < 0 || stream >= mNStreams) { - throw std::runtime_error("CPUDevice: invalid stream " + std::to_string(stream)); + throw std::runtime_error(std::format("CPUDevice: invalid stream {}", stream)); } GPUReconstructionCPUDeviceTask task; if (evList) { // Capture the event states at enqueue time, such that the queue waits for the markers recorded so far, like cudaStreamWaitEvent diff --git a/GPU/GPUTracking/Base/cpudevice/GPUReconstructionCPUDeviceGenRTC.cxx b/GPU/GPUTracking/Base/cpudevice/GPUReconstructionCPUDeviceGenRTC.cxx index d944562faca0b..e0fd79c2a0043 100644 --- a/GPU/GPUTracking/Base/cpudevice/GPUReconstructionCPUDeviceGenRTC.cxx +++ b/GPU/GPUTracking/Base/cpudevice/GPUReconstructionCPUDeviceGenRTC.cxx @@ -15,6 +15,7 @@ #include "GPUReconstructionCPUDevice.h" #include "GPULogging.h" +#include #include #include @@ -72,7 +73,7 @@ int32_t GPUReconstructionCPUDevice::genRTC(std::string& filename, uint32_t& nCom rtchelpers::Cache cache(proc, "cpudevice", {rtcSource, rtcparam, baseCommand, kernelsall, launchBounds, compilerVersions}); if (!cache.load(filename, RTC_BIN_EXTENSION, nCompile)) { rtchelpers::compile(proc, nCompile, "CPUDevice", [&](uint32_t i) { - const std::string fileBase = filename + "_" + std::to_string(i); + const std::string fileBase = std::format("{}_{}", filename, i); if (proc.debugLevel >= 3 && !proc.debugSilent) { printf("Compiling %s\n", (fileBase + RTC_SRC_EXTENSION).c_str()); } @@ -102,7 +103,7 @@ void GPUReconstructionCPUDevice::genAndLoadRTC() throw std::runtime_error("Runtime compilation failed"); } for (uint32_t i = 0; i < nCompile; i++) { - const std::string fileBase = filename + "_" + std::to_string(i); + const std::string fileBase = std::format("{}_{}", filename, i); if (GetProcessingSettings().rtctech.runTest != 2) { void* lib = dlopen((fileBase + RTC_BIN_EXTENSION).c_str(), RTLD_NOW | RTLD_LOCAL); if (lib == nullptr) { diff --git a/GPU/GPUTracking/Base/cuda/GPUReconstructionCUDAGenRTC.cxx b/GPU/GPUTracking/Base/cuda/GPUReconstructionCUDAGenRTC.cxx index 5e366f15f6c1b..419c2818899fa 100644 --- a/GPU/GPUTracking/Base/cuda/GPUReconstructionCUDAGenRTC.cxx +++ b/GPU/GPUTracking/Base/cuda/GPUReconstructionCUDAGenRTC.cxx @@ -18,6 +18,7 @@ #include "GPUReconstructionRTCHelpers.inc" #include "GPUKernelsWith1Warp.inc" #include +#include using namespace o2::gpu; namespace rtchelpers = o2::gpu::internal::rtchelpers; @@ -66,7 +67,7 @@ int32_t GPUReconstructionCUDA::genRTC(std::string& filename, uint32_t& nCompile) rtchelpers::Cache cache(proc, "cuda", {rtcSource, rtcparam, baseCommand, kernelsall, launchBounds, compilerVersions}); if (!cache.load(filename, mRtcBinExtension, nCompile)) { rtchelpers::compile(proc, nCompile, "CUDA", [&](uint32_t i) { - const std::string fileBase = filename + "_" + std::to_string(i); + const std::string fileBase = std::format("{}_{}", filename, i); if (proc.debugLevel >= 3 && !proc.debugSilent) { printf("Compiling %s\n", (fileBase + mRtcSrcExtension).c_str()); } diff --git a/GPU/GPUTracking/Base/metal/GPUReconstructionMetalIncludesHost.h b/GPU/GPUTracking/Base/metal/GPUReconstructionMetalIncludesHost.h index 82389e3053c25..02c54f86396ec 100644 --- a/GPU/GPUTracking/Base/metal/GPUReconstructionMetalIncludesHost.h +++ b/GPU/GPUTracking/Base/metal/GPUReconstructionMetalIncludesHost.h @@ -33,6 +33,8 @@ #include #include #include +#include +#include #include #include "GPULogging.h" @@ -154,9 +156,7 @@ inline double metalHostTime() inline void metalTimelineAdd(GPUReconstructionMetalInternals* internals, int32_t stream, const char* op, const void* id, uint64_t value) { if (internals->timeline) { - char buf[96]; - snprintf(buf, sizeof(buf), " %s:%p=%llu", op, id, (unsigned long long)value); - internals->timelineOps[stream] += buf; + std::format_to(std::back_inserter(internals->timelineOps[stream]), " {}:{}={}", op, id, value); } } // Runs after each kernel in its encoder, so a kernel that ran while the pool diff --git a/GPU/GPUTracking/Base/metal/GPUReconstructionMetalKernels.mm b/GPU/GPUTracking/Base/metal/GPUReconstructionMetalKernels.mm index b9c532485cba1..689e93a2d1abd 100644 --- a/GPU/GPUTracking/Base/metal/GPUReconstructionMetalKernels.mm +++ b/GPU/GPUTracking/Base/metal/GPUReconstructionMetalKernels.mm @@ -60,7 +60,7 @@ threadGroupSize = mInternals->maxThreadsPerGroup[num]; } if (mInternals->timeline) { - mInternals->timelineOps[kExec.stream] += std::string(" k:") + GetKernelName() + "/" + std::to_string(kExec.nBlocks); + std::format_to(std::back_inserter(mInternals->timelineOps[kExec.stream]), " k:{}/{}", GetKernelName(), kExec.nBlocks); mInternals->timelineKernels[kExec.stream]++; } [computeEncoder dispatchThreadgroups:MTLSizeMake(kExec.nBlocks, 1, 1) diff --git a/GPU/GPUTracking/Base/opencl/GPUReconstructionOCL.cxx b/GPU/GPUTracking/Base/opencl/GPUReconstructionOCL.cxx index cdc51bc5d311b..2c18b8dd08129 100644 --- a/GPU/GPUTracking/Base/opencl/GPUReconstructionOCL.cxx +++ b/GPU/GPUTracking/Base/opencl/GPUReconstructionOCL.cxx @@ -17,6 +17,7 @@ #include "GPUConstantMem.h" #include +#include static_assert(std::is_convertible_v, "OpenCL event type incompatible to deviceEvent"); @@ -197,7 +198,7 @@ int32_t GPUReconstructionOCL::InitDevice_Runtime() } if (pos == std::string::npos) { deviceOK = false; - deviceFailure += " - No SPIR-V " + std::to_string(GPUCA_OCL_SPIRV_VERSION) + " (" + device_il_version + ")"; + deviceFailure += std::format(" - No SPIR-V {} ({})", GPUCA_OCL_SPIRV_VERSION, device_il_version); } } diff --git a/GPU/GPUTracking/DataCompression/TPCClusterDecompressor.cxx b/GPU/GPUTracking/DataCompression/TPCClusterDecompressor.cxx index 78e2bd20496ce..528b4b3b902b9 100644 --- a/GPU/GPUTracking/DataCompression/TPCClusterDecompressor.cxx +++ b/GPU/GPUTracking/DataCompression/TPCClusterDecompressor.cxx @@ -20,6 +20,7 @@ #include #include #include +#include #include "TPCClusterDecompressionCore.inc" #include @@ -43,10 +44,10 @@ int32_t TPCClusterDecompressor::decompress(const CompressedClustersFlat* cluster int32_t TPCClusterDecompressor::decompress(const CompressedClusters* clustersCompressed, o2::tpc::ClusterNativeAccess& clustersNative, const std::function& allocator, const GPUParam& param, bool deterministicRec) { if (clustersCompressed->nTracks && clustersCompressed->solenoidBz != -1e6f && clustersCompressed->solenoidBz != param.bzkG) { - throw std::runtime_error("Configured solenoid Bz " + std::to_string(param.bzkG) + " does not match value used for track model encoding " + std::to_string(clustersCompressed->solenoidBz)); + throw std::runtime_error(std::format("Configured solenoid Bz {:f} does not match value used for track model encoding {:f}", param.bzkG, clustersCompressed->solenoidBz)); } if (clustersCompressed->nTracks && clustersCompressed->maxTimeBin != -1e6 && clustersCompressed->maxTimeBin != param.continuousMaxTimeBin) { - throw std::runtime_error("Configured max time bin " + std::to_string(param.continuousMaxTimeBin) + " does not match value used for track model encoding " + std::to_string(clustersCompressed->maxTimeBin)); + throw std::runtime_error(std::format("Configured max time bin {} does not match value used for track model encoding {}", param.continuousMaxTimeBin, clustersCompressed->maxTimeBin)); } std::vector clusters[NSECTORS][GPUTPCGeometry::NROWS]; std::atomic_flag locks[NSECTORS][GPUTPCGeometry::NROWS]; diff --git a/GPU/GPUTracking/DataTypes/GPUConfigDump.cxx b/GPU/GPUTracking/DataTypes/GPUConfigDump.cxx index 2a338cc53fce5..e3dca6624d6fe 100644 --- a/GPU/GPUTracking/DataTypes/GPUConfigDump.cxx +++ b/GPU/GPUTracking/DataTypes/GPUConfigDump.cxx @@ -25,6 +25,7 @@ #include #include #include +#include #include "utils/qconfig_helpers.h" #include "utils/qconfig_internal_helpers.h" @@ -53,10 +54,7 @@ void GPUConfigDump::dumpConfig(const GPUSettingsRec* rec, const GPUSettingsProce qConfigPrint(*display, "display."); } if (device) { - std::cout << "\n\tGPUSettingsDeviceBackend:\n" - << "\tdeviceType = " << (int32_t)device->deviceType << "\n" - << "\tforceDeviceType = " << (device->forceDeviceType ? "true" : "false") << "\n" - << "\tslave = " << (device->master ? "true" : "false") << "\n"; + std::cout << std::format("\n\tGPUSettingsDeviceBackend:\n\tdeviceType = {}\n\tforceDeviceType = {}\n\tslave = {}\n", (int32_t)device->deviceType, (bool)device->forceDeviceType, (bool)device->master); } if (workflow) { printf("\n\tReconstruction steps / inputs / outputs:\n\tReco Steps = 0x%08x\n\tReco Steps GPU = 0x%08x\n\tInputs = 0x%08x\n\tOutputs = 0x%08x\n", (uint32_t)workflow->steps, (uint32_t)workflow->stepsGPUMask, (uint32_t)workflow->inputs, (uint32_t)workflow->outputs); diff --git a/GPU/GPUTracking/Global/GPUChainTracking.cxx b/GPU/GPUTracking/Global/GPUChainTracking.cxx index 16d40b934e18a..f8b54c3f50ba2 100644 --- a/GPU/GPUTracking/Global/GPUChainTracking.cxx +++ b/GPU/GPUTracking/Global/GPUChainTracking.cxx @@ -16,6 +16,7 @@ #include "SimulationDataFormat/MCTruthContainer.h" #include #include +#include #include "GPUChainTracking.h" #include "GPUChainTrackingGetters.inc" @@ -392,7 +393,7 @@ int32_t GPUChainTracking::Init() } if (GetProcessingSettings().debugLevel >= 6 || GetProcessingSettings().debugDumpFinal) { - std::string filename = std::string(mRec->IsGPU() ? "GPU" : "CPU") + (mRec->slaveId() != -1 ? (std::string("_slave") + std::to_string(mRec->slaveId())) : std::string(mRec->slavesExist() ? "_master" : "")) + GetProcessingSettings().debugLogSuffix + ".out"; + std::string filename = std::format("{}{}{}.out", mRec->IsGPU() ? "GPU" : "CPU", mRec->slaveId() != -1 ? std::format("_slave{}", mRec->slaveId()) : std::string(mRec->slavesExist() ? "_master" : ""), GetProcessingSettings().debugLogSuffix); bool hashOnly = GetProcessingSettings().debugDumpChecksum; diff --git a/GPU/GPUTracking/Global/GPUChainTrackingClusterizer.cxx b/GPU/GPUTracking/Global/GPUChainTrackingClusterizer.cxx index 718d22b30f61c..4575bf538c0c8 100644 --- a/GPU/GPUTracking/Global/GPUChainTrackingClusterizer.cxx +++ b/GPU/GPUTracking/Global/GPUChainTrackingClusterizer.cxx @@ -61,6 +61,8 @@ #include #include #include +#include +#include // #define INSERT_SATURATED_SIGNALS @@ -391,18 +393,16 @@ std::pair GPUChainTracking::TPCClusterizerDecodeZSCount(uint } } else if (mCFContext->zsVersion != (int32_t)hdr->version) { GPUError("Received TPC ZS 8kb page of mixed versions, expected %d, received %d (linkid %d, feeCRU %d, feeEndpoint %d, feelinkid %d)", mCFContext->zsVersion, (int32_t)hdr->version, (int32_t)o2::raw::RDHUtils::getLinkID(*rdh), (int32_t)rdh_utils::getCRU(*rdh), (int32_t)rdh_utils::getEndPoint(*rdh), (int32_t)rdh_utils::getLink(*rdh)); - constexpr size_t bufferSize = 3 * std::max(sizeof(*rdh), sizeof(*hdr)) + 1; - char dumpBuffer[bufferSize]; + std::string dumpBuffer; for (size_t i = 0; i < sizeof(*rdh); i++) { - // "%02X " guaranteed to be 3 chars + ending 0. - snprintf(dumpBuffer + 3 * i, 4, "%02X ", (int32_t)((uint8_t*)rdh)[i]); + std::format_to(std::back_inserter(dumpBuffer), "{:02X} ", ((uint8_t*)rdh)[i]); } - GPUAlarm("RDH of page: %s", dumpBuffer); + GPUAlarm("RDH of page: %s", dumpBuffer.c_str()); + dumpBuffer.clear(); for (size_t i = 0; i < sizeof(*hdr); i++) { - // "%02X " guaranteed to be 3 chars + ending 0. - snprintf(dumpBuffer + 3 * i, 4, "%02X ", (int32_t)((uint8_t*)hdr)[i]); + std::format_to(std::back_inserter(dumpBuffer), "{:02X} ", ((uint8_t*)hdr)[i]); } - GPUAlarm("Metainfo of page: %s", dumpBuffer); + GPUAlarm("Metainfo of page: %s", dumpBuffer.c_str()); if (GetProcessingSettings().ignoreNonFatalGPUErrors) { mCFContext->abandonTimeframe = true; return {0, 0}; diff --git a/GPU/GPUTracking/Global/GPUChainTrackingCompression.cxx b/GPU/GPUTracking/Global/GPUChainTrackingCompression.cxx index b41aaba066544..37be7cba7df5e 100644 --- a/GPU/GPUTracking/Global/GPUChainTrackingCompression.cxx +++ b/GPU/GPUTracking/Global/GPUChainTrackingCompression.cxx @@ -29,6 +29,7 @@ #include "utils/strtag.h" #include +#include using namespace o2::gpu; using namespace o2::tpc; @@ -284,10 +285,10 @@ int32_t GPUChainTracking::RunTPCDecompression() CompressedClusters& inputGPUShadow = DecompressorShadow.mInputGPU; if (cmprClsHost.nTracks && cmprClsHost.solenoidBz != -1e6f && cmprClsHost.solenoidBz != param().bzkG) { - throw std::runtime_error("Configured solenoid Bz " + std::to_string(param().bzkG) + " does not match value used for track model encoding " + std::to_string(cmprClsHost.solenoidBz)); + throw std::runtime_error(std::format("Configured solenoid Bz {:f} does not match value used for track model encoding {:f}", param().bzkG, cmprClsHost.solenoidBz)); } if (cmprClsHost.nTracks && cmprClsHost.maxTimeBin != -1e6 && cmprClsHost.maxTimeBin != param().continuousMaxTimeBin) { - throw std::runtime_error("Configured max time bin " + std::to_string(param().continuousMaxTimeBin) + " does not match value used for track model encoding " + std::to_string(cmprClsHost.maxTimeBin)); + throw std::runtime_error(std::format("Configured max time bin {} does not match value used for track model encoding {}", param().continuousMaxTimeBin, cmprClsHost.maxTimeBin)); } int32_t unattachedStream = mRec->NStreams() - 1; diff --git a/GPU/GPUTracking/Global/GPUChainTrackingDebugAndProfiling.cxx b/GPU/GPUTracking/Global/GPUChainTrackingDebugAndProfiling.cxx index d3ac2acb035d1..be5e9690fb20b 100644 --- a/GPU/GPUTracking/Global/GPUChainTrackingDebugAndProfiling.cxx +++ b/GPU/GPUTracking/Global/GPUChainTrackingDebugAndProfiling.cxx @@ -21,6 +21,7 @@ #include #include #include +#include #ifdef GPUCA_TRACKLET_CONSTRUCTOR_DO_PROFILE #include "bitmapfile.h" @@ -246,7 +247,7 @@ void GPUChainTracking::PrintOutputStat() nCompressedClusters = c.nAttachedClusters + c.nUnattachedClusters; } - char trdText[1024] = ""; + std::string trdText; if (GetRecoSteps() & gpudatatypes::RecoStep::TRDTracking) { int32_t nTRDTracks = 0; int32_t nTRDTracklets = 0; @@ -261,15 +262,15 @@ void GPUChainTracking::PrintOutputStat() nTRDTracks += trk.getNtracklets() != 0; } } - snprintf(trdText, 1024, " - TRD Tracker reconstructed %d tracks (%d tracklets)", nTRDTracks, nTRDTracklets); + trdText = std::format(" - TRD Tracker reconstructed {} tracks ({} tracklets)", nTRDTracks, nTRDTracklets); } - GPUInfo("Output Tracks (%s): %d - Clusters: %d / %d / %d / %d / %d (attached / total / compressed / fitted / adjacent)%s", outputType, nTracks, nAttachedClusters, nCls, nCompressedClusters, nAttachedClustersFitted, nAdjacentClusters, trdText); + GPUInfo("Output Tracks (%s): %d - Clusters: %d / %d / %d / %d / %d (attached / total / compressed / fitted / adjacent)%s", outputType, nTracks, nAttachedClusters, nCls, nCompressedClusters, nAttachedClustersFitted, nAdjacentClusters, trdText.c_str()); } void GPUChainTracking::DumpOccupancyMap(std::ostream& out) { const uint32_t* map = mInputsHost->mTPCClusterOccupancyMap; - out << "\nTPC Occupancy Map: total " << map[0] << ", bins " << (map[1] >> 16) << ", average " << (map[1] & 0xFFFF) << ", entries " << mInputsHost->mTPCClusterOccupancyMapSize << "\n"; + out << std::format("\nTPC Occupancy Map: total {}, bins {}, average {}, entries {}\n", map[0], map[1] >> 16, map[1] & 0xFFFF, mInputsHost->mTPCClusterOccupancyMapSize); for (uint32_t i = 0; i < mInputsHost->mTPCClusterOccupancyMapSize; i++) { out << map[2 + i] << (i % 100 == 99 ? "\n" : " "); } @@ -398,7 +399,7 @@ void GPUChainTracking::DumpClusters(std::ostream& out, const o2::tpc::ClusterNat out << " Row: " << i << ": " << clusters->nClusters[iSec][i] << " clusters:\n"; for (uint32_t j = 0; j < clusters->nClusters[iSec][i]; j++) { const auto& cl = clusters->clusters[iSec][i][j]; - out << " " << std::hex << cl.timeFlagsPacked << std::dec << " " << cl.padPacked << " " << int32_t{cl.sigmaTimePacked} << " " << int32_t{cl.sigmaPadPacked} << " " << cl.qMax << " " << cl.qTotPacked << "\n"; + out << std::format(" {:x} {} {} {} {} {}\n", cl.timeFlagsPacked, cl.padPacked, cl.sigmaTimePacked, cl.sigmaPadPacked, cl.qMax, cl.qTotPacked); } } } diff --git a/GPU/GPUTracking/Interface/GPUO2Interface.cxx b/GPU/GPUTracking/Interface/GPUO2Interface.cxx index 8b4eec4c3fae6..96fba2c6ff3d9 100644 --- a/GPU/GPUTracking/Interface/GPUO2Interface.cxx +++ b/GPU/GPUTracking/Interface/GPUO2Interface.cxx @@ -30,6 +30,7 @@ #include #include #include +#include using namespace o2::gpu; @@ -144,16 +145,13 @@ void GPUO2Interface::DumpEvent(int32_t nEvent, GPUTrackingInOutPointers* data, u { const auto oldPtrs = mCtx[iThread].mChain->mIOPtrs; mCtx[iThread].mChain->mIOPtrs = *data; - char fname[1024]; - snprintf(fname, 1024, "%sevent.%d.dump", dir, nEvent); - mCtx[iThread].mChain->DumpData(fname); + mCtx[iThread].mChain->DumpData(std::format("{}event.{}.dump", dir, nEvent).c_str()); if (nEvent == 0) { #ifdef GPUCA_BUILD_QA if (mConfig->configProcessing.runMC) { mCtx[iThread].mChain->ForceInitQA(); - snprintf(fname, 1024, "mc.%d.dump", nEvent); mCtx[iThread].mChain->GetQA()->UpdateChain(mCtx[iThread].mChain); - mCtx[iThread].mChain->GetQA()->DumpO2MCData(fname); + mCtx[iThread].mChain->GetQA()->DumpO2MCData(std::format("mc.{}.dump", nEvent).c_str()); } #endif } diff --git a/GPU/GPUTracking/Merger/GPUTPCGMMerger.cxx b/GPU/GPUTracking/Merger/GPUTPCGMMerger.cxx index d8f321657320d..e51002396c8e6 100644 --- a/GPU/GPUTracking/Merger/GPUTPCGMMerger.cxx +++ b/GPU/GPUTracking/Merger/GPUTPCGMMerger.cxx @@ -59,6 +59,7 @@ #ifndef GPUCA_GPUCODE #include "SimulationDataFormat/ConstMCTruthContainer.h" #include "SimulationDataFormat/MCCompLabel.h" +#include #endif using namespace o2::gpu; @@ -363,11 +364,9 @@ void GPUTPCGMMerger::PrintMergeGraph(const GPUTPCGMSectorTrack* trk, std::ostrea while (nextId >= 0) { GPUTPCGMSectorTrack* trk2 = &mSectorTrackInfos[nextId]; if (trk != trk2 && (trk2->PrevNeighbour() >= 0 || trk2->NextNeighbour() >= 0)) { - out << " (TRACK TREE INVALID!!! " << trk2->PrevNeighbour() << " <-- " << nextId << " --> " << trk2->NextNeighbour() << ") "; + out << std::format(" (TRACK TREE INVALID!!! {} <-- {} --> {}) ", trk2->PrevNeighbour(), nextId, trk2->NextNeighbour()); } - char tmp[128]; - snprintf(tmp, 128, " %s%5d(%5.2f)", trk2 == orgTrack ? "!" : " ", nextId, trk2->QPt()); - out << tmp; + out << std::format(" {}{:5d}({:5.2f})", trk2 == orgTrack ? "!" : " ", nextId, trk2->QPt()); nextId = trk2->NextSegmentNeighbour(); } out << "\n"; diff --git a/GPU/GPUTracking/SectorTracker/GPUTPCTrackerDump.cxx b/GPU/GPUTracking/SectorTracker/GPUTPCTrackerDump.cxx index 98537f0f1a1b4..38140f8282264 100644 --- a/GPU/GPUTracking/SectorTracker/GPUTPCTrackerDump.cxx +++ b/GPU/GPUTracking/SectorTracker/GPUTPCTrackerDump.cxx @@ -20,9 +20,9 @@ #include #include -#include #include #include +#include using namespace o2::gpu; @@ -144,10 +144,10 @@ void GPUTPCTracker::DumpTrackletHits(std::ostream& out) for (int32_t jj = 0; jj < nTracklets; jj++) { const int32_t j = Ids[jj]; const auto& tracklet = Tracklets()[j]; - out << "Tracklet " << std::setw(4) << jj << " (Rows: " << Tracklets()[j].FirstRow() << " - " << tracklet.LastRow() << ", Weight " << Tracklets()[j].HitWeight() << ") "; + out << std::format("Tracklet {:4} (Rows: {} - {}, Weight {}) ", jj, tracklet.FirstRow(), tracklet.LastRow(), tracklet.HitWeight()); if (tracklet.LastRow() > tracklet.FirstRow() && (tracklet.FirstRow() >= GPUTPCGeometry::NROWS || tracklet.LastRow() >= GPUTPCGeometry::NROWS)) { GPUError("Error: Tracklet %d First %d Last %d", j, tracklet.FirstRow(), tracklet.LastRow()); - out << " (Error: Tracklet " << j << " First " << tracklet.FirstRow() << " Last " << tracklet.LastRow() << ") "; + out << std::format(" (Error: Tracklet {} First {} Last {}) ", j, tracklet.FirstRow(), tracklet.LastRow()); for (uint32_t i = 0; i < GPUTPCGeometry::NROWS; i++) { // if (tracklet.RowHit(i) != CALINK_INVAL) out << i << "-" << mTrackletRowHits[tracklet.FirstHit() + (i - tracklet.FirstRow())] << ", "; diff --git a/GPU/GPUTracking/Standalone/Benchmark/standalone.cxx b/GPU/GPUTracking/Standalone/Benchmark/standalone.cxx index 7b850e174f32d..65640ba3a26b1 100644 --- a/GPU/GPUTracking/Standalone/Benchmark/standalone.cxx +++ b/GPU/GPUTracking/Standalone/Benchmark/standalone.cxx @@ -61,6 +61,7 @@ #include #include #include +#include #ifndef _WIN32 #include @@ -682,7 +683,7 @@ int32_t ReadEvent(int32_t n) if (configStandalone.inputcontrolmem && !configStandalone.preloadEvents) { rec->SetInputControl(inputmemory.get(), configStandalone.inputcontrolmem); } - int32_t r = chainTracking->ReadData((eventsDir + GPUCA_EVDUMP_FILE "." + std::to_string(n) + ".dump").c_str()); + int32_t r = chainTracking->ReadData(std::format("{}" GPUCA_EVDUMP_FILE ".{}.dump", eventsDir, n).c_str()); if (r) { return r; } @@ -691,7 +692,7 @@ int32_t ReadEvent(int32_t n) GPUChainTracking* chain = (configStandalone.testSyncAsyncMC && !configStandalone.testSyncAsyncQcInSync) ? chainTrackingAsync : chainTracking; chain->ForceInitQA(); chain->GetQA()->UpdateChain(chain); - if (chain->GetQA()->ReadO2MCData((eventsDir + "mc." + std::to_string(n) + ".dump").c_str()) && + if (chain->GetQA()->ReadO2MCData(std::format("{}mc.{}.dump", eventsDir, n).c_str()) && chain->GetQA()->ReadO2MCData((eventsDir + "mc.0.dump").c_str()) && configStandalone.proc.runQA) { throw std::runtime_error("Error reading O2 MC dump"); } @@ -855,9 +856,7 @@ int32_t RunBenchmark(GPUReconstruction* recUse, GPUChainTracking* chainTrackingU chainTrackingAsync->GenerateCompressionMCLabels(*chainTracking); } if (configStandalone.dumpEvents == 2 && iRun == 0) { - char fname[1024]; - snprintf(fname, 1024, "event.%d.dump", iEvent - configStandalone.StartEvent); - chainTrackingAsync->DumpData(fname); + chainTrackingAsync->DumpData(std::format("event.{}.dump", iEvent - configStandalone.StartEvent).c_str()); if (iEvent == configStandalone.StartEvent) { GPUSettingsGRP grpAsync = recAsync->GetGRPSettings(); grpAsync.needsClusterer = 0; @@ -976,7 +975,7 @@ int32_t main(int argc, char** argv) if (!configStandalone.noEvents) { while (true) { std::ifstream in; - in.open((eventsDir + GPUCA_EVDUMP_FILE "." + std::to_string(nEventsInDirectory) + ".dump").c_str(), std::ifstream::binary); + in.open(std::format("{}" GPUCA_EVDUMP_FILE ".{}.dump", eventsDir, nEventsInDirectory), std::ifstream::binary); if (in.fail()) { break; } @@ -1065,9 +1064,7 @@ int32_t main(int argc, char** argv) goto breakrun; } if (configStandalone.dumpEvents == 1) { - char fname[1024]; - snprintf(fname, 1024, "event.%d.dump", nEventsProcessed); - chainTracking->DumpData(fname); + chainTracking->DumpData(std::format("event.{}.dump", nEventsProcessed).c_str()); if (nEventsProcessed == 0) { rec->DumpSettings(); } @@ -1127,13 +1124,12 @@ int32_t main(int argc, char** argv) const double nClsPerTF = 755851. * nOrbits * colRate / orbitRate; double timePerTF = (configStandalone.proc.doublePipeline ? pipelineWalltime : ((configStandalone.proc.debugLevel ? rec->GetStatKernelTime() : rec->GetStatWallTime()) / 1000000.)) * nClsPerTF / nClusters; const double nGPUsReq = timePerTF * orbitRate / nOrbits; - char stat[1024]; - snprintf(stat, 1024, "Sync phase: %.2f sec per %d orbit TF, %.1f GPUs required", timePerTF, nOrbits, nGPUsReq); + std::string stat = std::format("Sync phase: {:.2f} sec per {} orbit TF, {:.1f} GPUs required", timePerTF, nOrbits, nGPUsReq); if (configStandalone.testSyncAsync) { timePerTF = (configStandalone.proc.debugLevel ? recAsync->GetStatKernelTime() : recAsync->GetStatWallTime()) / 1000000. * nClsPerTF / nClusters; - snprintf(stat + strlen(stat), 1024 - strlen(stat), " - Async phase: %f sec per TF", timePerTF); + stat += std::format(" - Async phase: {:f} sec per TF", timePerTF); } - printf("%s (Measured %s time - Extrapolated from %d clusters to %d)\n", stat, configStandalone.proc.debugLevel ? "kernel" : "wall", (int32_t)nClusters, (int32_t)nClsPerTF); + printf("%s (Measured %s time - Extrapolated from %d clusters to %d)\n", stat.c_str(), configStandalone.proc.debugLevel ? "kernel" : "wall", (int32_t)nClusters, (int32_t)nClsPerTF); } } if (configStandalone.testSyncAsync && chainTracking->mIOPtrs.clustersNative && chainTrackingAsync->mIOPtrs.clustersNative) { diff --git a/GPU/GPUTracking/TPCClusterFinder/GPUTPCClusterFinderDump.cxx b/GPU/GPUTracking/TPCClusterFinder/GPUTPCClusterFinderDump.cxx index 6ca6b250a1648..3d246f2eab237 100644 --- a/GPU/GPUTracking/TPCClusterFinder/GPUTPCClusterFinderDump.cxx +++ b/GPU/GPUTracking/TPCClusterFinder/GPUTPCClusterFinderDump.cxx @@ -17,6 +17,7 @@ #include "CfArray2D.h" #include "DataFormatsTPC/ClusterNative.h" #include "GPUSettings.h" +#include using namespace o2::gpu; using namespace o2::gpu::tpccf; @@ -171,7 +172,7 @@ void GPUTPCClusterFinder::DumpClusters(std::ostream& out) if (cl.isSaturated()) { sigmaTime = cl.getSaturatedTailLength(); } - out << std::hex << cl.timeFlagsPacked << std::dec << " " << cl.padPacked << " " << sigmaTime << " " << int32_t{cl.sigmaPadPacked} << " " << cl.qMax << " " << qTot << "\n"; + out << std::format("{:x} {} {} {} {} {}\n", cl.timeFlagsPacked, cl.padPacked, sigmaTime, cl.sigmaPadPacked, cl.qMax, qTot); } } } diff --git a/GPU/GPUTracking/TPCClusterFinder/GPUTPCNNClusterizer.cxx b/GPU/GPUTracking/TPCClusterFinder/GPUTPCNNClusterizer.cxx index 5edc3afbc75e4..e34c44f83f704 100644 --- a/GPU/GPUTracking/TPCClusterFinder/GPUTPCNNClusterizer.cxx +++ b/GPU/GPUTracking/TPCClusterFinder/GPUTPCNNClusterizer.cxx @@ -16,6 +16,7 @@ #include "GPUTPCNNClusterizer.h" #include "GPUSettings.h" #include "GPUCommonLogger.h" +#include using namespace o2::gpu; @@ -67,12 +68,7 @@ void* GPUTPCNNClusterizer::setIOPointers(void* mem) if (mNnClusterizerVerbosity > 2) { if (mNnClusterizerVerbosity > 3) { - auto fmt = [](size_t bytes) -> const char* { - static char buf[64]; - double mb = (double)bytes / (1024.0 * 1024.0); - [[maybe_unused]] int n = snprintf(buf, sizeof(buf), "%zu bytes (%.3f MB)", bytes, mb); - return buf; - }; + auto fmt = [](size_t bytes) { return std::format("{} bytes ({:.3f} MB)", bytes, (double)bytes / (1024.0 * 1024.0)); }; // Element counts (number of array entries, not bytes) size_t elemsClusterFlags = (mClusterFlags && mNnClusterizerBatchedMode > 0) ? (size_t)2 * mNnClusterizerBatchedMode : 0; @@ -133,13 +129,7 @@ void* GPUTPCNNClusterizer::setIOPointers(void* mem) // Compute allocated bytes (difference between advanced pointer and start pointer) size_t allocatedBytes = static_cast(reinterpret_cast(mem) - reinterpret_cast(startMem)); double allocatedMB = static_cast(allocatedBytes) / (1024.0 * 1024.0); - { - char allocMsg[256]; - [[maybe_unused]] int nn = snprintf(allocMsg, sizeof(allocMsg), - "(NNCLUS, GPUTPCNNClusterizer, this=%p) Total scratch allocation in setIOPointers: %zu bytes (%.3f MB)", - (void*)this, (size_t)allocatedBytes, allocatedMB); - LOG(info) << allocMsg; - } + LOG(info) << std::format("(NNCLUS, GPUTPCNNClusterizer, this={}) Total scratch allocation in setIOPointers: {} bytes ({:.3f} MB)", (void*)this, allocatedBytes, allocatedMB); } return mem; diff --git a/GPU/GPUTracking/display/GPUDisplay.cxx b/GPU/GPUTracking/display/GPUDisplay.cxx index d8455b44cf74b..f4534e1e6f8a7 100644 --- a/GPU/GPUTracking/display/GPUDisplay.cxx +++ b/GPU/GPUTracking/display/GPUDisplay.cxx @@ -24,6 +24,7 @@ #include #include #include +#include #ifndef _WIN32 #include "../utils/linux_helpers.h" @@ -765,11 +766,7 @@ void GPUDisplay::DrawGLScene_internal(bool suspended, float animateTime, bool re if (doScreenshot) { mCfgC.requestScreenshot = false; std::vector pixels = mBackend->getPixels(); - char tmpFileName[48]; - if (animateScreenshot) { - snprintf(tmpFileName, 48, "%d_%05d.bmp", mAnimationExport, mAnimationFrame); - } - DoScreenshot(animateScreenshot ? (mCfgO.mscreenShotName + tmpFileName).c_str() : mScreenshotFile.c_str(), pixels); + DoScreenshot(animateScreenshot ? std::format("{}{}_{:05d}.bmp", mCfgO.mscreenShotName, mAnimationExport, mAnimationFrame).c_str() : mScreenshotFile.c_str(), pixels); } } diff --git a/GPU/GPUTracking/display/frontend/GPUDisplayConsole.cxx b/GPU/GPUTracking/display/frontend/GPUDisplayConsole.cxx index c925bb84c5495..275cedbcad3e5 100644 --- a/GPU/GPUTracking/display/frontend/GPUDisplayConsole.cxx +++ b/GPU/GPUTracking/display/frontend/GPUDisplayConsole.cxx @@ -20,6 +20,7 @@ #include #include #include +#include #include #include @@ -214,7 +215,7 @@ std::tuple nFixed)) { - throw consoleArgumentError(name, std::to_string(nFixed) + (more ? " or more" : "") + " arguments expected, got " + std::to_string(nArgs), types); + throw consoleArgumentError(name, std::format("{}{} arguments expected, got {}", nFixed, more ? " or more" : "", nArgs), types); } auto autoType = [](const std::string& text, bool plain) -> consoleArg { // int64_t for [+-]digits, double for other decimal numbers (also with exponent, as saveSettings writes them), string otherwise or if plain text const char *begin = text.c_str() + (text[0] == '+' || text[0] == '-'), *end = text.c_str() + text.size(); @@ -237,12 +238,12 @@ std::tuple(value)) { - throw consoleArgumentError(name, "argument " + std::to_string(i + 1) + " (" + text + ") must be an integer", types); + throw consoleArgumentError(name, std::format("argument {} ({}) must be an integer", i + 1, text), types); } else if (type == 'd') { if (std::holds_alternative(value)) { value = (double)std::get(value); } else if (!std::holds_alternative(value)) { - throw consoleArgumentError(name, "argument " + std::to_string(i + 1) + " (" + text + ") must be a number", types); + throw consoleArgumentError(name, std::format("argument {} ({}) must be a number", i + 1, text), types); } } else if (type != 's' && type != 'i' && type != 'a' && type != '+') { throw std::runtime_error(name + ": invalid argument types " + types); diff --git a/GPU/GPUTracking/display/frontend/GPUDisplayFrontendConfig.cxx b/GPU/GPUTracking/display/frontend/GPUDisplayFrontendConfig.cxx index 6ace7b4c83f7a..aab0119eded62 100644 --- a/GPU/GPUTracking/display/frontend/GPUDisplayFrontendConfig.cxx +++ b/GPU/GPUTracking/display/frontend/GPUDisplayFrontendConfig.cxx @@ -31,15 +31,14 @@ #include #include #include +#include #include #include #include -#include #include #include #include #include -#include #include #include #include @@ -593,9 +592,7 @@ void GPUDisplayFrontend::listKeys(const std::function& print(""); print("Key down mappings (id, name, key):"); for (uint32_t i = 0; i < KEY_MAP_MAX; i++) { - char line[128]; - snprintf(line, sizeof(line), " %2u %-28s %s", i, rtti.keyMapNames[i].c_str(), rtti.currentMappedKeys[i] < 0 ? "[N/A]" : ("[" + rtti.getKeyName(rtti.currentMappedKeys[i]) + "]").c_str()); - print(line); + print(std::format(" {:2} {:<28} {}", i, rtti.keyMapNames[i], rtti.currentMappedKeys[i] < 0 ? "[N/A]" : "[" + rtti.getKeyName(rtti.currentMappedKeys[i]) + "]")); } } @@ -841,9 +838,7 @@ std::optional GPUDisplayFrontend::GPUDisplayConfiguration::valueStr return qConfig::print_type(*(const bool*)ptr); } else if (e.type == "float") { if (precise) { - std::ostringstream s; - s << std::setprecision(std::numeric_limits::max_digits10) << *(const float*)ptr; - return s.str(); + return std::format("{:.{}g}", *(const float*)ptr, std::numeric_limits::max_digits10); } return qConfig::print_type(*(const float*)ptr); } else if (e.type == "int8_t") { diff --git a/GPU/GPUTracking/display/frontend/GPUDisplayFrontendConfigConsole.inc b/GPU/GPUTracking/display/frontend/GPUDisplayFrontendConfigConsole.inc index 6f03b8bbbfab1..288f58940e974 100644 --- a/GPU/GPUTracking/display/frontend/GPUDisplayFrontendConfigConsole.inc +++ b/GPU/GPUTracking/display/frontend/GPUDisplayFrontendConfigConsole.inc @@ -354,9 +354,8 @@ void GPUDisplayFrontend::buildConsoleCommands() out << "set " << optionName(i) << " " << text << "\n"; } const float toDeg = 180.f / CAMath::Pi(); - out << std::setprecision(std::numeric_limits::max_digits10); // Camera position exact, angles up to the conversion to degrees - out << "setXYZ " << mDisplay->mXYZ[0] << " " << mDisplay->mXYZ[1] << " " << mDisplay->mXYZ[2] << "\n"; - out << "setCameraAngles " << mDisplay->mAngle[1] * toDeg << " " << mDisplay->mAngle[0] * toDeg << " " << mDisplay->mAngle[2] * toDeg << "\n"; + out << std::format("setXYZ {:.9g} {:.9g} {:.9g}\n", mDisplay->mXYZ[0], mDisplay->mXYZ[1], mDisplay->mXYZ[2]); // max_digits10 of float: camera position exact, angles up to the conversion to degrees + out << std::format("setCameraAngles {:.9g} {:.9g} {:.9g}\n", mDisplay->mAngle[1] * toDeg, mDisplay->mAngle[0] * toDeg, mDisplay->mAngle[2] * toDeg); }); }, "s", "Save all settings and the camera as console script (run it with runScript)"}; diff --git a/GPU/GPUTracking/display/frontend/GPUDisplayFrontendConfigInfo.inc b/GPU/GPUTracking/display/frontend/GPUDisplayFrontendConfigInfo.inc index a5f84063409e2..7c47b13989eb9 100644 --- a/GPU/GPUTracking/display/frontend/GPUDisplayFrontendConfigInfo.inc +++ b/GPU/GPUTracking/display/frontend/GPUDisplayFrontendConfigInfo.inc @@ -85,10 +85,8 @@ void GPUDisplay::buildConfigInfo() if (val == GPUDisplayBackend::FPS_LIMIT_RATE) { SetInfo("FPS limit: %d FPS", mCfgR.fpsRate); } else if (val == GPUDisplayBackend::FPS_LIMIT_VSYNC) { - char rate[32] = "unknown rate"; - if (mFrontend->getRefreshRate() > 0.f) { - snprintf(rate, sizeof(rate), "%.1f Hz", mFrontend->getRefreshRate()); - } + const std::string rateStr = mFrontend->getRefreshRate() > 0.f ? std::format("{:.1f} Hz", mFrontend->getRefreshRate()) : "unknown rate"; + const char* rate = rateStr.c_str(); const int32_t mode = mBackend->fpsLimitMode(); if (mode == GPUDisplayBackend::FPS_LIMIT_NONE) { SetInfo("FPS limit: refresh rate (%s) - VSync disabled, no limit", rate); diff --git a/GPU/GPUTracking/display/frontend/GPUDisplayFrontendConfigQtGUI.inc b/GPU/GPUTracking/display/frontend/GPUDisplayFrontendConfigQtGUI.inc index 325a7d5c677fe..c665e597f763b 100644 --- a/GPU/GPUTracking/display/frontend/GPUDisplayFrontendConfigQtGUI.inc +++ b/GPU/GPUTracking/display/frontend/GPUDisplayFrontendConfigQtGUI.inc @@ -124,9 +124,9 @@ void GPUDisplay::buildConfigQtGUI() for (uint32_t i = 0; i < mConfig.filterMacros.size(); i++) { std::string name = mConfig.filterMacros[i]; std::erase_if(name, [](char c) { return c == '\n' || c == '\r'; }); - filterChoices.emplace_back(std::to_string(i + 1) + ": " + name.substr(0, 16), (int64_t)(i + 1)); + filterChoices.emplace_back(std::format("{}: {}", i + 1, name.substr(0, 16)), (int64_t)(i + 1)); } - filterChoices.emplace_back(std::to_string(mConfig.filterMacros.size() + 1) + ": Custom Macro", (int64_t)(mConfig.filterMacros.size() + 1)); + filterChoices.emplace_back(std::format("{}: Custom Macro", mConfig.filterMacros.size() + 1), (int64_t)(mConfig.filterMacros.size() + 1)); mFrontend->add_gui_binding( GUI_LAMBDA("TPC", mCfgH, drawTPCTracks, GUI_CHECKBOX), GUI_LAMBDA("TRD", mCfgH, drawTRDTracks, GUI_CHECKBOX), diff --git a/GPU/GPUTracking/display/helpers/GPUDisplayHelpers.cxx b/GPU/GPUTracking/display/helpers/GPUDisplayHelpers.cxx index 217a11bdbc54f..0bff0bf121c73 100644 --- a/GPU/GPUTracking/display/helpers/GPUDisplayHelpers.cxx +++ b/GPU/GPUTracking/display/helpers/GPUDisplayHelpers.cxx @@ -24,6 +24,7 @@ #endif #include "oneapi/tbb.h" +#include using namespace o2::gpu; @@ -60,7 +61,7 @@ void GPUDisplay::takeScreenshot() { static int32_t nScreenshot = 1; mCfgC.requestScreenshot = true; - mScreenshotFile = mCfgO.mscreenShotName + std::to_string(nScreenshot++) + ".bmp"; + mScreenshotFile = std::format("{}{}.bmp", mCfgO.mscreenShotName, nScreenshot++); } void GPUDisplay::SaveGLPos() diff --git a/GPU/GPUTracking/display/helpers/GPUDisplayROOT.cxx b/GPU/GPUTracking/display/helpers/GPUDisplayROOT.cxx index be78c3f00199a..133d507d12a4c 100644 --- a/GPU/GPUTracking/display/helpers/GPUDisplayROOT.cxx +++ b/GPU/GPUTracking/display/helpers/GPUDisplayROOT.cxx @@ -29,6 +29,7 @@ using namespace o2::gpu; #include "TMethodCall.h" #include "TInterpreter.h" #include +#include #include #include @@ -46,7 +47,7 @@ int32_t GPUDisplay::buildTrackFilter() return 1; } static uint32_t nCustomMacro = 0; - name = (std::filesystem::temp_directory_path() / ("o2_gpu_display_track_filter_" + std::to_string(getpid()) + "_" + std::to_string(nCustomMacro++) + ".C")).string(); + name = (std::filesystem::temp_directory_path() / std::format("o2_gpu_display_track_filter_{}_{}.C", getpid(), nCustomMacro++)).string(); std::ofstream(name) << mCfgO.filterMacroCustom << "\n"; } if (!mTrackFilterMacroLoaded.empty()) { // All macros define gpuDisplayTrackFilter, the previous one must be unloaded diff --git a/GPU/GPUTracking/qa/GPUQA.cxx b/GPU/GPUTracking/qa/GPUQA.cxx index 1a62cc269b010..95846241e0137 100644 --- a/GPU/GPUTracking/qa/GPUQA.cxx +++ b/GPU/GPUTracking/qa/GPUQA.cxx @@ -74,6 +74,7 @@ #include #include #include +#include #include "utils/timer.h" @@ -436,26 +437,26 @@ void GPUQA::SetMCTrackRange(int32_t min, int32_t max) int32_t GPUQA::InitQACreateHistograms() { - char name[2048], fname[1024]; + std::string name, fname; if (mQATasks & taskTrackingEff) { // Create Efficiency Histograms for (int32_t i = 0; i < 6; i++) { for (int32_t j = 0; j < 2; j++) { for (int32_t k = 0; k < 2; k++) { for (int32_t l = 0; l < 5; l++) { - snprintf(name, 2048, "%s%s%s%sVs%s", "tracks", EFF_TYPES[i], FINDABLE_NAMES[j], PRIM_NAMES[k], VSPARAMETER_NAMES[l]); + name = std::format("tracks{}{}{}Vs{}", EFF_TYPES[i], FINDABLE_NAMES[j], PRIM_NAMES[k], VSPARAMETER_NAMES[l]); if (l == 4) { std::unique_ptr binsPt{CreateLogAxis(AXIS_BINS[4], k == 0 ? PT_MIN_PRIM : AXES_MIN[4], AXES_MAX[4])}; - createHist(mEff[i][j][k][l], name, name, AXIS_BINS[l], binsPt.get()); + createHist(mEff[i][j][k][l], name.c_str(), name.c_str(), AXIS_BINS[l], binsPt.get()); } else { - createHist(mEff[i][j][k][l], name, name, AXIS_BINS[l], AXES_MIN[l], AXES_MAX[l]); + createHist(mEff[i][j][k][l], name.c_str(), name.c_str(), AXIS_BINS[l], AXES_MIN[l], AXES_MAX[l]); } if (!mHaveExternalHists) { mEff[i][j][k][l]->Sumw2(); } - strcat(name, "_eff"); + name += "_eff"; if (i < 4) { - createHist(mEffResult[i][j][k][l], name); + createHist(mEffResult[i][j][k][l], name.c_str()); } } } @@ -467,24 +468,24 @@ int32_t GPUQA::InitQACreateHistograms() if (mQATasks & taskTrackingRes) { for (int32_t i = 0; i < 5; i++) { for (int32_t j = 0; j < 5; j++) { - snprintf(name, 2048, "rms_%s_vs_%s", VSPARAMETER_NAMES[i], VSPARAMETER_NAMES[j]); - snprintf(fname, 1024, "mean_%s_vs_%s", VSPARAMETER_NAMES[i], VSPARAMETER_NAMES[j]); + name = std::format("rms_{}_vs_{}", VSPARAMETER_NAMES[i], VSPARAMETER_NAMES[j]); + fname = std::format("mean_{}_vs_{}", VSPARAMETER_NAMES[i], VSPARAMETER_NAMES[j]); if (j == 4) { std::unique_ptr binsPt{CreateLogAxis(AXIS_BINS[4], mConfig.resPrimaries == 1 ? PT_MIN_PRIM : AXES_MIN[4], AXES_MAX[4])}; - createHist(mRes[i][j][0], name, name, AXIS_BINS[j], binsPt.get()); - createHist(mRes[i][j][1], fname, fname, AXIS_BINS[j], binsPt.get()); + createHist(mRes[i][j][0], name.c_str(), name.c_str(), AXIS_BINS[j], binsPt.get()); + createHist(mRes[i][j][1], fname.c_str(), fname.c_str(), AXIS_BINS[j], binsPt.get()); } else { - createHist(mRes[i][j][0], name, name, AXIS_BINS[j], AXES_MIN[j], AXES_MAX[j]); - createHist(mRes[i][j][1], fname, fname, AXIS_BINS[j], AXES_MIN[j], AXES_MAX[j]); + createHist(mRes[i][j][0], name.c_str(), name.c_str(), AXIS_BINS[j], AXES_MIN[j], AXES_MAX[j]); + createHist(mRes[i][j][1], fname.c_str(), fname.c_str(), AXIS_BINS[j], AXES_MIN[j], AXES_MAX[j]); } - snprintf(name, 2048, "res_%s_vs_%s", VSPARAMETER_NAMES[i], VSPARAMETER_NAMES[j]); + name = std::format("res_{}_vs_{}", VSPARAMETER_NAMES[i], VSPARAMETER_NAMES[j]); const float* axis = mConfig.nativeFitResolutions ? RES_AXES_NATIVE : RES_AXES; const int32_t nbins = i == 4 && mConfig.nativeFitResolutions ? (10 * RES_AXIS_BINS[0]) : RES_AXIS_BINS[0]; if (j == 4) { std::unique_ptr binsPt{CreateLogAxis(AXIS_BINS[4], mConfig.resPrimaries == 1 ? PT_MIN_PRIM : AXES_MIN[4], AXES_MAX[4])}; - createHist(mRes2[i][j], name, name, nbins, -axis[i], axis[i], AXIS_BINS[j], binsPt.get()); + createHist(mRes2[i][j], name.c_str(), name.c_str(), nbins, -axis[i], axis[i], AXIS_BINS[j], binsPt.get()); } else { - createHist(mRes2[i][j], name, name, nbins, -axis[i], axis[i], AXIS_BINS[j], AXES_MIN[j], AXES_MAX[j]); + createHist(mRes2[i][j], name.c_str(), name.c_str(), nbins, -axis[i], axis[i], AXIS_BINS[j], AXES_MIN[j], AXES_MAX[j]); } } } @@ -494,22 +495,22 @@ int32_t GPUQA::InitQACreateHistograms() if (mQATasks & taskTrackingResPull) { for (int32_t i = 0; i < 5; i++) { for (int32_t j = 0; j < 5; j++) { - snprintf(name, 2048, "pull_rms_%s_vs_%s", VSPARAMETER_NAMES[i], VSPARAMETER_NAMES[j]); - snprintf(fname, 1024, "pull_mean_%s_vs_%s", VSPARAMETER_NAMES[i], VSPARAMETER_NAMES[j]); + name = std::format("pull_rms_{}_vs_{}", VSPARAMETER_NAMES[i], VSPARAMETER_NAMES[j]); + fname = std::format("pull_mean_{}_vs_{}", VSPARAMETER_NAMES[i], VSPARAMETER_NAMES[j]); if (j == 4) { std::unique_ptr binsPt{CreateLogAxis(AXIS_BINS[4], AXES_MIN[4], AXES_MAX[4])}; - createHist(mPull[i][j][0], name, name, AXIS_BINS[j], binsPt.get()); - createHist(mPull[i][j][1], fname, fname, AXIS_BINS[j], binsPt.get()); + createHist(mPull[i][j][0], name.c_str(), name.c_str(), AXIS_BINS[j], binsPt.get()); + createHist(mPull[i][j][1], fname.c_str(), fname.c_str(), AXIS_BINS[j], binsPt.get()); } else { - createHist(mPull[i][j][0], name, name, AXIS_BINS[j], AXES_MIN[j], AXES_MAX[j]); - createHist(mPull[i][j][1], fname, fname, AXIS_BINS[j], AXES_MIN[j], AXES_MAX[j]); + createHist(mPull[i][j][0], name.c_str(), name.c_str(), AXIS_BINS[j], AXES_MIN[j], AXES_MAX[j]); + createHist(mPull[i][j][1], fname.c_str(), fname.c_str(), AXIS_BINS[j], AXES_MIN[j], AXES_MAX[j]); } - snprintf(name, 2048, "pull_%s_vs_%s", VSPARAMETER_NAMES[i], VSPARAMETER_NAMES[j]); + name = std::format("pull_{}_vs_{}", VSPARAMETER_NAMES[i], VSPARAMETER_NAMES[j]); if (j == 4) { std::unique_ptr binsPt{CreateLogAxis(AXIS_BINS[4], AXES_MIN[4], AXES_MAX[4])}; - createHist(mPull2[i][j], name, name, RES_AXIS_BINS[0], -PULL_AXIS, PULL_AXIS, AXIS_BINS[j], binsPt.get()); + createHist(mPull2[i][j], name.c_str(), name.c_str(), RES_AXIS_BINS[0], -PULL_AXIS, PULL_AXIS, AXIS_BINS[j], binsPt.get()); } else { - createHist(mPull2[i][j], name, name, RES_AXIS_BINS[0], -PULL_AXIS, PULL_AXIS, AXIS_BINS[j], AXES_MIN[j], AXES_MAX[j]); + createHist(mPull2[i][j], name.c_str(), name.c_str(), RES_AXIS_BINS[0], -PULL_AXIS, PULL_AXIS, AXIS_BINS[j], AXES_MIN[j], AXES_MAX[j]); } } } @@ -520,9 +521,9 @@ int32_t GPUQA::InitQACreateHistograms() for (int32_t i = 0; i < N_CLS_TYPE * N_CLS_HIST - 1; i++) { int32_t ioffset = i >= (2 * N_CLS_HIST - 1) ? (2 * N_CLS_HIST - 1) : (i >= N_CLS_HIST ? N_CLS_HIST : 0); int32_t itype = i >= (2 * N_CLS_HIST - 1) ? 2 : (i >= N_CLS_HIST ? 1 : 0); - snprintf(name, 2048, "clusters%s%s", CLUSTER_NAMES_SHORT[i - ioffset], CLUSTER_TYPES[itype]); + name = std::format("clusters{}{}", CLUSTER_NAMES_SHORT[i - ioffset], CLUSTER_TYPES[itype]); std::unique_ptr binsPt{CreateLogAxis(AXIS_BINS[4], PT_MIN_CLUST, PT_MAX)}; - createHist(mClusters[i], name, name, AXIS_BINS[4], binsPt.get()); + createHist(mClusters[i], name.c_str(), name.c_str(), AXIS_BINS[4], binsPt.get()); } const int32_t maxPads = GPUTPCGeometry::NPads(GPUTPCGeometry::NROWS - 1); @@ -538,14 +539,14 @@ int32_t GPUQA::InitQACreateHistograms() if (mQATasks & taskTrackStatistics) { // Create Tracks Histograms for (int32_t i = 0; i < 2; i++) { - snprintf(name, 2048, i ? "nrows_with_cluster" : "nclusters"); - createHist(mNCl[i], name, name, GPUTPCGeometry::NROWS + 1, 0, GPUTPCGeometry::NROWS); + name = i ? "nrows_with_cluster" : "nclusters"; + createHist(mNCl[i], name.c_str(), name.c_str(), GPUTPCGeometry::NROWS + 1, 0, GPUTPCGeometry::NROWS); } std::unique_ptr binsPt{CreateLogAxis(AXIS_BINS[4], PT_MIN_CLUST, PT_MAX)}; createHist(mTrackPt, "tracks_pt", "tracks_pt", AXIS_BINS[4], binsPt.get()); for (int32_t i = 0; i < 2; i++) { - snprintf(name, 2048, i ? "tracks_dedx_max" : "tracks_dedx_tot"); - createHist(mTrackdEdx[i], name, name, 200, -3, 1, 1000, 0, i ? 1500 : 5000); + name = i ? "tracks_dedx_max" : "tracks_dedx_tot"; + createHist(mTrackdEdx[i], name.c_str(), name.c_str(), 200, -3, 1, 1000, 0, i ? 1500 : 5000); } const uint32_t maxTime = (mTracking && mTracking->GetParam().continuousMaxTimeBin > 0) ? mTracking->GetParam().continuousMaxTimeBin : constants::TPC_MAX_TIME_BIN_TRIGGERED; createHist(mT0[0], "tracks_t0", "tracks_t0", (maxTime + 1) / 10, 0, maxTime); @@ -555,8 +556,8 @@ int32_t GPUQA::InitQACreateHistograms() if (mQATasks & taskClusterRejection) { const int padCount = GPUTPCGeometry::NPads(GPUTPCGeometry::NROWS - 1); for (int32_t i = 0; i < 3; i++) { - snprintf(name, 2048, "clrej_%d", i); - createHist(mClRej[i], name, name, 2 * padCount, -padCount / 2 + 0.5f, padCount / 2 - 0.5f, GPUTPCGeometry::NROWS, 0, GPUTPCGeometry::NROWS - 1); + name = std::format("clrej_{}", i); + createHist(mClRej[i], name.c_str(), name.c_str(), 2 * padCount, -padCount / 2 + 0.5f, padCount / 2 - 0.5f, GPUTPCGeometry::NROWS, 0, GPUTPCGeometry::NROWS - 1); } createHist(mClRejP, "clrejp", "clrejp", GPUTPCGeometry::NROWS, 0, GPUTPCGeometry::NROWS - 1); } @@ -2114,26 +2115,24 @@ void GPUQA::RunQA(bool matchOnly, const std::vector* tracksEx mTrackingScratchBuffer.shrink_to_fit(); } -void GPUQA::GetName(char* fname, int32_t k, bool noDash) +std::string GPUQA::GetName(int32_t k, bool noDash) { const int32_t nNewInput = mConfig.inputHistogramsOnly ? 0 : 1; - if (k || mConfig.inputHistogramsOnly || mConfig.name.size()) { - if (!(mConfig.inputHistogramsOnly || k)) { - snprintf(fname, 1024, "%s%s", mConfig.name.c_str(), noDash ? "" : " - "); - } else if (mConfig.compareInputNames.size() > (unsigned)(k - nNewInput)) { - snprintf(fname, 1024, "%s%s", mConfig.compareInputNames[k - nNewInput].c_str(), noDash ? "" : " - "); - } else { - strcpy(fname, mConfig.compareInputs[k - nNewInput].c_str()); - if (strlen(fname) > 5 && strcmp(fname + strlen(fname) - 5, ".root") == 0) { - fname[strlen(fname) - 5] = 0; - } - if (!noDash) { - strcat(fname, " - "); - } - } + if (!(k || mConfig.inputHistogramsOnly || mConfig.name.size())) { + return ""; + } + std::string name; + if (!(mConfig.inputHistogramsOnly || k)) { + name = mConfig.name; + } else if (mConfig.compareInputNames.size() > (unsigned)(k - nNewInput)) { + name = mConfig.compareInputNames[k - nNewInput]; } else { - fname[0] = 0; + name = mConfig.compareInputs[k - nNewInput]; + if (name.size() > 5 && name.ends_with(".root")) { + name.resize(name.size() - 5); + } } + return noDash ? name : name + " - "; } template @@ -2197,7 +2196,7 @@ int32_t GPUQA::DrawQAHistograms(TObjArray* qcout) } bool mcAvail = mcPresent(); - char name[2048], fname[1024]; + std::string name, fname; const int32_t nNewInput = mConfig.inputHistogramsOnly ? 0 : 1; const int32_t ConfigNumInputs = nNewInput + mConfig.compareInputs.size(); @@ -2214,17 +2213,17 @@ int32_t GPUQA::DrawQAHistograms(TObjArray* qcout) if (mConfig.enableLocalOutput || mConfig.shipToQCAsCanvas) { float legendSpacingString = 0.025; for (int32_t i = 0; i < ConfigNumInputs; i++) { - GetName(fname, i); - if (strlen(fname) * 0.006 > legendSpacingString) { - legendSpacingString = strlen(fname) * 0.006; + fname = GetName(i); + if (fname.size() * 0.006 > legendSpacingString) { + legendSpacingString = fname.size() * 0.006; } } // Create Canvas / Pads for Efficiency Histograms if (mQATasks & taskTrackingEff) { for (int32_t ii = 0; ii < 6; ii++) { - snprintf(name, 1024, "eff_vs_%s_layout", VSPARAMETER_NAMES[ii]); - mCEff[ii] = createGarbageCollected(name, name, 0, 0, 700, 700. * 2. / 3.); + name = std::format("eff_vs_{}_layout", VSPARAMETER_NAMES[ii]); + mCEff[ii] = createGarbageCollected(name.c_str(), name.c_str(), 0, 0, 700, 700. * 2. / 3.); mCEff[ii]->cd(); float dy = 1. / 2.; mPEff[ii][0] = createGarbageCollected("p0", "", 0.0, dy * 0, 0.5, dy * 1); @@ -2248,11 +2247,11 @@ int32_t GPUQA::DrawQAHistograms(TObjArray* qcout) if (mQATasks & taskTrackingRes) { for (int32_t ii = 0; ii < 7; ii++) { if (ii == 6) { - snprintf(name, 1024, "res_integral_layout"); + name = "res_integral_layout"; } else { - snprintf(name, 1024, "res_vs_%s_layout", VSPARAMETER_NAMES[ii]); + name = std::format("res_vs_{}_layout", VSPARAMETER_NAMES[ii]); } - mCRes[ii] = createGarbageCollected(name, name, 0, 0, 700, 700. * 2. / 3.); + mCRes[ii] = createGarbageCollected(name.c_str(), name.c_str(), 0, 0, 700, 700. * 2. / 3.); mCRes[ii]->cd(); gStyle->SetOptFit(1); @@ -2286,11 +2285,11 @@ int32_t GPUQA::DrawQAHistograms(TObjArray* qcout) if (mQATasks & taskTrackingResPull) { for (int32_t ii = 0; ii < 7; ii++) { if (ii == 6) { - snprintf(name, 1024, "pull_integral_layout"); + name = "pull_integral_layout"; } else { - snprintf(name, 1024, "pull_vs_%s_layout", VSPARAMETER_NAMES[ii]); + name = std::format("pull_vs_{}_layout", VSPARAMETER_NAMES[ii]); } - mCPull[ii] = createGarbageCollected(name, name, 0, 0, 700, 700. * 2. / 3.); + mCPull[ii] = createGarbageCollected(name.c_str(), name.c_str(), 0, 0, 700, 700. * 2. / 3.); mCPull[ii]->cd(); gStyle->SetOptFit(1); @@ -2323,8 +2322,8 @@ int32_t GPUQA::DrawQAHistograms(TObjArray* qcout) // Create Canvas for Cluster Histos if (mQATasks & taskClusterAttach) { for (int32_t i = 0; i < 3; i++) { - snprintf(name, 1024, "clusters_%s_layout", CLUSTER_TYPES[i]); - mCClust[i] = createGarbageCollected(name, name, 0, 0, 700, 700. * 2. / 3.); + name = std::format("clusters_{}_layout", CLUSTER_TYPES[i]); + mCClust[i] = createGarbageCollected(name.c_str(), name.c_str(), 0, 0, 700, 700. * 2. / 3.); mCClust[i]->cd(); mPClust[i] = createGarbageCollected("p0", "", 0.0, 0.0, 1.0, 1.0); mPClust[i]->Draw(); @@ -2337,8 +2336,8 @@ int32_t GPUQA::DrawQAHistograms(TObjArray* qcout) // Create Canvas for track statistic histos if (mQATasks & taskTrackStatistics) { for (int32_t i = 0; i < 3; i++) { - snprintf(name, 2048, "ctracks%s", i ? (i == 2 ? "dedxmax" : "dedxtot") : "pt"); - mCTracks[i] = createGarbageCollected(name, name, 0, 0, 700, 700. * 2. / 3.); + name = std::format("ctracks{}", i ? (i == 2 ? "dedxmax" : "dedxtot") : "pt"); + mCTracks[i] = createGarbageCollected(name.c_str(), name.c_str(), 0, 0, 700, 700. * 2. / 3.); mCTracks[i]->cd(); mPTracks[i] = createGarbageCollected("p0", "", 0.0, 0.0, 1.0, 1.0); mPTracks[i]->Draw(); @@ -2347,16 +2346,16 @@ int32_t GPUQA::DrawQAHistograms(TObjArray* qcout) } for (int32_t i = 0; i < 2; i++) { - snprintf(name, 2048, "ctrackst0%d", i); - mCT0[i] = createGarbageCollected(name, name, 0, 0, 700, 700. * 2. / 3.); + name = std::format("ctrackst0{}", i); + mCT0[i] = createGarbageCollected(name.c_str(), name.c_str(), 0, 0, 700, 700. * 2. / 3.); mCT0[i]->cd(); mPT0[i] = createGarbageCollected("p0", "", 0.0, 0.0, 1.0, 1.0); mPT0[i]->Draw(); mLT0[i] = createGarbageCollected(0.9 - legendSpacingString * 1.45, 0.93 - (0.93 - 0.86) / 2. * (float)ConfigNumInputs, 0.98, 0.949); SetLegend(mLT0[i]); - snprintf(name, 2048, "cncl%d", i); - mCNCl[i] = createGarbageCollected(name, name, 0, 0, 700, 700. * 2. / 3.); + name = std::format("cncl{}", i); + mCNCl[i] = createGarbageCollected(name.c_str(), name.c_str(), 0, 0, 700, 700. * 2. / 3.); mCNCl[i]->cd(); mPNCl[i] = createGarbageCollected("p0", "", 0.0, 0.0, 1.0, 1.0); mPNCl[i]->Draw(); @@ -2372,8 +2371,8 @@ int32_t GPUQA::DrawQAHistograms(TObjArray* qcout) if (mQATasks & taskClusterRejection) { for (int32_t i = 0; i < 3; i++) { - snprintf(name, 2048, "cnclrej%d", i); - mCClRej[i] = createGarbageCollected(name, name, 0, 0, 700, 700. * 2. / 3.); + name = std::format("cnclrej{}", i); + mCClRej[i] = createGarbageCollected(name.c_str(), name.c_str(), 0, 0, 700, 700. * 2. / 3.); mCClRej[i]->cd(); mPClRej[i] = createGarbageCollected("p0", "", 0.0, 0.0, 1.0, 1.0); mPClRej[i]->Draw(); @@ -2386,8 +2385,8 @@ int32_t GPUQA::DrawQAHistograms(TObjArray* qcout) if (mQATasks & taskClusterAttach) { for (int32_t i = 0; i < 4; i++) { - snprintf(name, 2048, "cpadrow%d", i); - mCPadRow[i] = createGarbageCollected(name, name, 0, 0, 700, 700. * 2. / 3.); + name = std::format("cpadrow{}", i); + mCPadRow[i] = createGarbageCollected(name.c_str(), name.c_str(), 0, 0, 700, 700. * 2. / 3.); mCPadRow[i]->cd(); mPPadRow[i] = createGarbageCollected("p0", "", 0.0, 0.0, 1.0, 1.0); mPPadRow[i]->Draw(); @@ -2493,8 +2492,8 @@ int32_t GPUQA::DrawQAHistograms(TObjArray* qcout) e->GetHistogram()->GetYaxis()->SetRangeUser(-0.02, 1.02); e->Draw(k || l ? "same P" : "AP"); if (j == 0) { - GetName(fname, k); - mLEff[ii]->AddEntry(e, Form("%s%s", fname, EFF_NAMES[l]), "l"); + fname = GetName(k); + mLEff[ii]->AddEntry(e, Form("%s%s", fname.c_str(), EFF_NAMES[l]), "l"); } } if (!mConfig.enableLocalOutput && !mConfig.shipToQCAsCanvas) { @@ -2717,8 +2716,8 @@ int32_t GPUQA::DrawQAHistograms(TObjArray* qcout) e->SetLineColor(colorNums[numColor++ % COLORCOUNT]); e->Draw(k || l ? "same" : ""); if (j == 0) { - GetName(fname, k); - leg->AddEntry(e, Form("%s%s", fname, l ? "Mean" : (p ? "Pull" : "Resolution")), "l"); + fname = GetName(k); + leg->AddEntry(e, Form("%s%s", fname.c_str(), l ? "Mean" : (p ? "Pull" : "Resolution")), "l"); } } } @@ -2948,8 +2947,8 @@ int32_t GPUQA::DrawQAHistograms(TObjArray* qcout) e->SetMarkerColor(kBlack); e->SetLineColor(colorNums[numColor++ % COLORCOUNT]); e->Draw(j == end - 1 && k == 0 ? "" : "same"); - GetName(fname, k); - mLClust[i]->AddEntry(e, Form("%s%s", fname, CLUSTER_NAMES[j - begin]), "l"); + fname = GetName(k); + mLClust[i]->AddEntry(e, Form("%s%s", fname.c_str(), CLUSTER_NAMES[j - begin]), "l"); } } if (ConfigNumInputs == 1) { @@ -3079,8 +3078,8 @@ int32_t GPUQA::DrawQAHistograms(TObjArray* qcout) e->SetMarkerColor(kBlack); e->SetLineColor(colorNums[k % COLORCOUNT]); e->Draw(k == 0 ? "" : "same"); - GetName(fname, k, mConfig.inputHistogramsOnly); - mLTracks[0]->AddEntry(e, Form(mConfig.inputHistogramsOnly ? "%s" : "%sTrack #it{p}_{T}", fname), "l"); + fname = GetName(k, mConfig.inputHistogramsOnly); + mLTracks[0]->AddEntry(e, Form(mConfig.inputHistogramsOnly ? "%s" : "%sTrack #it{p}_{T}", fname.c_str()), "l"); } mLTracks[0]->Draw(); doPerfFigure(0.63, 0.7, 0.030); @@ -3147,8 +3146,8 @@ int32_t GPUQA::DrawQAHistograms(TObjArray* qcout) e->SetMarkerColor(kBlack); e->SetLineColor(colorNums[k % COLORCOUNT]); e->Draw(k == 0 ? "" : "same"); - GetName(fname, k, mConfig.inputHistogramsOnly); - mLT0[i]->AddEntry(e, Form(mConfig.inputHistogramsOnly ? "%s (%s)" : "%sTrack t_{0} %s", fname, i ? "" : "resolution"), "l"); + fname = GetName(k, mConfig.inputHistogramsOnly); + mLT0[i]->AddEntry(e, Form(mConfig.inputHistogramsOnly ? "%s (%s)" : "%sTrack t_{0} %s", fname.c_str(), i ? "" : "resolution"), "l"); } mLT0[i]->Draw(); doPerfFigure(0.63, 0.7, 0.030); @@ -3191,8 +3190,8 @@ int32_t GPUQA::DrawQAHistograms(TObjArray* qcout) e->SetMarkerColor(kBlack); e->SetLineColor(colorNums[k % COLORCOUNT]); e->Draw(k == 0 ? "" : "same"); - GetName(fname, k, mConfig.inputHistogramsOnly); - mLNCl[i]->AddEntry(e, Form(mConfig.inputHistogramsOnly ? "%s" : (i ? "%sN_{Clusters}" : "%sN_{Rows with Clusters}"), fname), "l"); + fname = GetName(k, mConfig.inputHistogramsOnly); + mLNCl[i]->AddEntry(e, Form(mConfig.inputHistogramsOnly ? "%s" : (i ? "%sN_{Clusters}" : "%sN_{Rows with Clusters}"), fname.c_str()), "l"); } mLNCl[i]->Draw(); doPerfFigure(0.6, 0.7, 0.030); @@ -3298,16 +3297,13 @@ void GPUQA::PrintClusterCount(int32_t mode, int32_t& num, const char* name, uint if (mode == 2) { // do nothing, just count num } else if (mode == 1) { - char name2[128]; - snprintf(name2, 128, "clusterCount%d_", num); - char* ptr = name2 + strlen(name2); + std::string name2 = std::format("clusterCount{}_", num); for (uint32_t i = 0; i < strlen(name); i++) { if ((name[i] >= 'a' && name[i] <= 'z') || (name[i] >= 'A' && name[i] <= 'Z') || (name[i] >= '0' && name[i] <= '9')) { - *(ptr++) = name[i]; + name2 += name[i]; } } - *ptr = 0; - createHist(mHistClusterCount[num], name2, name, 1000, 0, mConfig.histMaxNClusters, 1000, 0, 100); + createHist(mHistClusterCount[num], name2.c_str(), name, 1000, 0, mConfig.histMaxNClusters, 1000, 0, 100); } else if (mode == 0) { if (normalization && mConfig.enableLocalOutput) { for (uint32_t i = 0; i < 1 + (mTextDump != nullptr); i++) { diff --git a/GPU/GPUTracking/qa/GPUQA.h b/GPU/GPUTracking/qa/GPUQA.h index a92cf0173d35f..ad013890814f5 100644 --- a/GPU/GPUTracking/qa/GPUQA.h +++ b/GPU/GPUTracking/qa/GPUQA.h @@ -171,7 +171,7 @@ class GPUQA void ChangePadTitleSize(TPad* p, float size); void DrawHisto(TH1* histo, char* filename, char* options); void doPerfFigure(float x, float y, float size); - void GetName(char* fname, int32_t k, bool noDash = false); + std::string GetName(int32_t k, bool noDash = false); template T* GetHist(T*& ee, std::vector>& tin, int32_t k, int32_t nNewInput); diff --git a/GPU/GPUTracking/qa/genEvents.cxx b/GPU/GPUTracking/qa/genEvents.cxx index 2e7fb10706476..777e8bb414166 100644 --- a/GPU/GPUTracking/qa/genEvents.cxx +++ b/GPU/GPUTracking/qa/genEvents.cxx @@ -27,6 +27,7 @@ #include #include #include +#include #include "genEvents.h" #include "GPUTPCClusterData.h" @@ -105,13 +106,8 @@ void genEvents::InitEventGenerator(const std::string& dir) { for (int32_t i = 0; i < 3; i++) { for (int32_t j = 0; j < 2; j++) { - char name[1024], title[1024]; - - snprintf(name, 1024, "clError%s%d", (j == 0 ? "Y" : "Z"), i); - - snprintf(title, 1024, "Cluster %s Error for row region %d", (j == 0 ? "Y" : "Z"), i); - - mClusterError[i][j] = new TH1F(name, title, 1000, 0., .7); + const char* yz = j == 0 ? "Y" : "Z"; + mClusterError[i][j] = new TH1F(std::format("clError{}{}", yz, i).c_str(), std::format("Cluster {} Error for row region {}", yz, i).c_str(), 1000, 0., .7); mClusterError[i][j]->GetXaxis()->SetTitle("Cluster Error [cm]"); } } @@ -244,7 +240,7 @@ int32_t genEvents::GenerateEvent(const GPUParam& param, const char* filename) if (!isNewSector) { break; } else { - std::cout << "track " << itr << ": new sector " << iSector << " at row " << iRow << std::endl; + std::cout << std::format("track {}: new sector {} at row {}", itr, iSector, iRow) << std::endl; } } if (err) { @@ -362,7 +358,7 @@ void genEvents::RunEventGenerator(GPUChainTracking* rec, const std::string& dir) for (int32_t i = 0; i < (configStandalone.nEvents == -1 ? 10 : configStandalone.nEvents); i++) { GPUInfo("Generating event %d/%d", i, configStandalone.nEvents == -1 ? 10 : configStandalone.nEvents); - gen->GenerateEvent(rec->GetParam(), (dir + GPUCA_EVDUMP_FILE "." + std::to_string(i) + ".dump").c_str()); + gen->GenerateEvent(rec->GetParam(), std::format("{}" GPUCA_EVDUMP_FILE ".{}.dump", dir, i).c_str()); } gen->FinishEventGenerator(); } diff --git a/GPU/TPCFastTransformation/TPCFastSpaceChargeCorrection.cxx b/GPU/TPCFastTransformation/TPCFastSpaceChargeCorrection.cxx index 68b8d302d67e4..76d11710fe67c 100644 --- a/GPU/TPCFastTransformation/TPCFastSpaceChargeCorrection.cxx +++ b/GPU/TPCFastTransformation/TPCFastSpaceChargeCorrection.cxx @@ -20,7 +20,7 @@ #include #include #include -#include +#include #include "Spline2DHelper.h" using namespace o2::gpu; @@ -635,9 +635,7 @@ double TPCFastSpaceChargeCorrection::testInverse(bool prn) std::string toString() { - std::stringstream ss; - ss << V << "(" << Sector << "," << Row << ")"; - return ss.str(); + return std::format("{:g}({},{})", V, Sector, Row); } }; diff --git a/GPU/Utils/SymMatrixSolver.cxx b/GPU/Utils/SymMatrixSolver.cxx index ea574eeec01b6..73c2dd9c34c70 100644 --- a/GPU/Utils/SymMatrixSolver.cxx +++ b/GPU/Utils/SymMatrixSolver.cxx @@ -19,7 +19,9 @@ #include #include -#include +#include +#include +#include #include using namespace std; diff --git a/GPU/Workflow/src/GPUWorkflowSpec.cxx b/GPU/Workflow/src/GPUWorkflowSpec.cxx index 0f6759df7bf0f..44da7908dc4f5 100644 --- a/GPU/Workflow/src/GPUWorkflowSpec.cxx +++ b/GPU/Workflow/src/GPUWorkflowSpec.cxx @@ -102,6 +102,7 @@ #include #include #include +#include using namespace o2::framework; using namespace o2::header; @@ -850,7 +851,7 @@ void GPURecoWorkflowSpec::run(ProcessingContext& pc) if (debugTFDump && mNDebugDumps < mConfParam->dumpBadTFs) { mNDebugDumps++; if (mConfParam->dumpBadTFMode <= 1) { - std::string filename = std::string("tpc_dump_") + std::to_string(pc.services().get().inputTimesliceId) + "_" + std::to_string(mNDebugDumps) + ".dump"; + std::string filename = std::format("tpc_dump_{}_{}.dump", pc.services().get().inputTimesliceId, mNDebugDumps); FILE* fp = fopen(filename.c_str(), "w+b"); std::vector filter = {{"check", ConcreteDataTypeMatcher{gDataOriginTPC, "RAWDATA"}, Lifetime::Timeframe}}; for (auto const& ref : InputRecordWalker(pc.inputs(), filter)) { @@ -1132,7 +1133,7 @@ void GPURecoWorkflowSpec::doCalibUpdates(o2::framework::ProcessingContext& pc, c for (int i = 0; i < 3; i++) { newCalibObjects.nnClusterizerNetworks[i] = mConfig->configCalib.nnClusterizerNetworks[i]; if (mSpecConfig.nnDumpToFile && newCalibObjects.nnClusterizerNetworks[i]) { - std::string path = "tpc_nn_clusterizer_" + std::to_string(i) + ".onnx"; + std::string path = std::format("tpc_nn_clusterizer_{}.onnx", i); dumpToFile(newCalibObjects.nnClusterizerNetworks[i]->getONNXModel(), newCalibObjects.nnClusterizerNetworks[i]->getONNXModelSize(), path); LOG(info) << "Dumped TPC clusterizer NN " << i << " to file " << path; } @@ -1152,7 +1153,7 @@ Options GPURecoWorkflowSpec::options() char* o2jobid = getenv("O2JOBID"); char* numaid = getenv("NUMAID"); int32_t chanid = o2jobid ? atoi(o2jobid) : (numaid ? atoi(numaid) : 0); - std::string chan = std::string("name=gpu-prepare-channel,type=") + (send ? "push" : "pull") + ",method=" + (send ? "connect" : "bind") + ",address=ipc://@gpu-prepare-channel-" + std::to_string(chanid) + "-{timeslice0},transport=shmem,rateLogging=0"; + std::string chan = std::format("name=gpu-prepare-channel,type={},method={},address=ipc://@gpu-prepare-channel-{}-{{timeslice0}},transport=shmem,rateLogging=0", send ? "push" : "pull", send ? "connect" : "bind", chanid); opts.emplace_back(o2::framework::ConfigParamSpec{"channel-config", o2::framework::VariantType::String, std::move(chan), {"Out-of-band channel config"}}); } if (mSpecConfig.enableDoublePipeline == 2) { From eed6d93a160422bb922fcec18b0e5589584c4bd8 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Tue, 1 Dec 2026 15:04:20 +0100 Subject: [PATCH 10/41] GPU: Fix mc data dump going to wrong directory --- GPU/GPUTracking/Interface/GPUO2Interface.cxx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/GPU/GPUTracking/Interface/GPUO2Interface.cxx b/GPU/GPUTracking/Interface/GPUO2Interface.cxx index 96fba2c6ff3d9..a88a2358dc6f1 100644 --- a/GPU/GPUTracking/Interface/GPUO2Interface.cxx +++ b/GPU/GPUTracking/Interface/GPUO2Interface.cxx @@ -151,7 +151,7 @@ void GPUO2Interface::DumpEvent(int32_t nEvent, GPUTrackingInOutPointers* data, u if (mConfig->configProcessing.runMC) { mCtx[iThread].mChain->ForceInitQA(); mCtx[iThread].mChain->GetQA()->UpdateChain(mCtx[iThread].mChain); - mCtx[iThread].mChain->GetQA()->DumpO2MCData(std::format("mc.{}.dump", nEvent).c_str()); + mCtx[iThread].mChain->GetQA()->DumpO2MCData(std::format("{}mc.{}.dump", dir, nEvent).c_str()); } #endif } From ee0ed9d7d11d9915733b6dba7cc3bfb19a43df9e Mon Sep 17 00:00:00 2001 From: David Rohr Date: Tue, 1 Dec 2026 15:05:09 +0100 Subject: [PATCH 11/41] GPU: Fix debug printout of shared memory for CUDA/HIP --- GPU/GPUbenchmark/cuda/Kernels.cu | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/GPU/GPUbenchmark/cuda/Kernels.cu b/GPU/GPUbenchmark/cuda/Kernels.cu index b8dedfd8145b1..a10fcd357d81b 100644 --- a/GPU/GPUbenchmark/cuda/Kernels.cu +++ b/GPU/GPUbenchmark/cuda/Kernels.cu @@ -335,11 +335,10 @@ void printDeviceProp(int32_t deviceId) << " Mhz" << std::endl; std::cout << std::setw(w1) << "totalGlobalMem: " << std::fixed << std::setprecision(2) << bytesToGB(props.totalGlobalMem) << " GB" << std::endl; -#if !defined(__CUDACC__) +#ifndef __HIPCC__ // CUDA std::cout << std::setw(w1) << "maxSharedMemoryPerMultiProcessor: " << std::fixed << std::setprecision(2) << bytesToconfig(props.sharedMemPerMultiprocessor) << " config" << std::endl; -#endif -#if defined(__HIPCC__) +#else std::cout << std::setw(w1) << "maxSharedMemoryPerMultiProcessor: " << std::fixed << std::setprecision(2) << bytesToconfig(props.maxSharedMemoryPerMultiProcessor) << " config" << std::endl; #endif From 8ffd2e29813a7ddc92853ad55cf3d08a8dfc4d90 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Tue, 1 Dec 2026 15:05:29 +0100 Subject: [PATCH 12/41] GPU: Fix debug printout of matrices in MatrixSolver --- GPU/Utils/BandMatrixSolver.cxx | 16 +++++++++------- GPU/Utils/SymMatrixSolver.cxx | 16 ++++++++-------- 2 files changed, 17 insertions(+), 15 deletions(-) diff --git a/GPU/Utils/BandMatrixSolver.cxx b/GPU/Utils/BandMatrixSolver.cxx index d05d1ed221b4e..c6fbd94885f69 100644 --- a/GPU/Utils/BandMatrixSolver.cxx +++ b/GPU/Utils/BandMatrixSolver.cxx @@ -17,7 +17,9 @@ #include "BandMatrixSolver.h" #include "GPUCommonLogger.h" #include -#include +#include +#include +#include #include using namespace std; @@ -89,20 +91,20 @@ int32_t BandMatrixSolver<0>::test(bool prn) if (prn && iter == nTries - 1) { LOG(info) << "Matrix A:"; for (int32_t i = 0; i < n; i++) { - LOG(info) << ""; + std::string row; for (int32_t j = 0; j < n; j++) { - LOG(info) << std::fixed << std::setw(5) << std::setprecision(2) << A[i][j] << " "; + std::format_to(std::back_inserter(row), "{:5.2f} ", A[i][j]); } + LOG(info) << row; } - LOG(info) << ""; LOG(info) << "\nMatrix A type 1:"; for (int32_t i = 0; i < n; i++) { - LOG(info) << ""; + std::string row; for (int32_t j = 0; j < n; j++) { - LOG(info) << std::fixed << std::setw(5) << std::setprecision(2) << Atype1[i][j] << " "; + std::format_to(std::back_inserter(row), "{:5.2f} ", Atype1[i][j]); } + LOG(info) << row; } - LOG(info) << ""; } double B[n][d]; diff --git a/GPU/Utils/SymMatrixSolver.cxx b/GPU/Utils/SymMatrixSolver.cxx index 73c2dd9c34c70..3a8f50383c3a5 100644 --- a/GPU/Utils/SymMatrixSolver.cxx +++ b/GPU/Utils/SymMatrixSolver.cxx @@ -68,16 +68,16 @@ void SymMatrixSolver::solve() void SymMatrixSolver::print() { for (int32_t i = 0; i < mN; i++) { - LOG(info) << ""; + std::string row; for (int32_t j = 0; j < mN; j++) { - LOG(info) << std::fixed << std::setw(5) << std::setprecision(2) << A(i, j) << " "; + std::format_to(std::back_inserter(row), "{:5.2f} ", A(i, j)); } - LOG(info) << " | "; + row += " | "; for (int32_t j = 0; j < mM; j++) { - LOG(info) << std::fixed << std::setw(5) << std::setprecision(2) << B(i, j) << " "; + std::format_to(std::back_inserter(row), "{:5.2f} ", B(i, j)); } + LOG(info) << row; } - LOG(info) << std::setprecision(-1); } int32_t SymMatrixSolver::test(bool prn) @@ -120,12 +120,12 @@ int32_t SymMatrixSolver::test(bool prn) } if (prn && iter == nTries - 1) { for (int32_t i = 0; i < n; i++) { - LOG(info) << ""; + std::string row; for (int32_t j = 0; j < n; j++) { - LOG(info) << std::fixed << std::setw(5) << std::setprecision(2) << A[i][j] << " "; + std::format_to(std::back_inserter(row), "{:5.2f} ", A[i][j]); } + LOG(info) << row; } - LOG(info) << ""; } } double b[n][d]; From f9f7c2aec68fa3fe7caf1fbaa3b19c1807574ad6 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Tue, 1 Dec 2026 15:18:58 +0100 Subject: [PATCH 13/41] GPU: Modernize C++: Use RAII to close files --- GPU/GPUTracking/Base/GPUReconstruction.cxx | 6 +- GPU/GPUTracking/Base/GPUReconstructionIO.h | 70 ++++++++----------- .../Base/GPUReconstructionRTCHelpers.inc | 57 +++++++-------- .../GPUReconstructionCPUDeviceGenRTC.cxx | 5 +- .../GPUChainTrackingDebugAndProfiling.cxx | 14 ++-- GPU/GPUTracking/Global/GPUChainTrackingIO.cxx | 11 ++- .../display/helpers/GPUDisplayHelpers.cxx | 34 +++++---- GPU/GPUTracking/qa/GPUQA.cxx | 53 ++++++-------- GPU/GPUTracking/qa/GPUQA.h | 3 +- GPU/GPUTracking/utils/unique_file.h | 29 ++++++++ GPU/Workflow/src/GPUWorkflowSpec.cxx | 22 +++--- 11 files changed, 151 insertions(+), 153 deletions(-) create mode 100644 GPU/GPUTracking/utils/unique_file.h diff --git a/GPU/GPUTracking/Base/GPUReconstruction.cxx b/GPU/GPUTracking/Base/GPUReconstruction.cxx index 974a4aa4ae908..afd6d04630849 100644 --- a/GPU/GPUTracking/Base/GPUReconstruction.cxx +++ b/GPU/GPUTracking/Base/GPUReconstruction.cxx @@ -43,6 +43,7 @@ #include "GPULogging.h" #include "utils/strtag.h" #include "utils/stdspinlock.h" +#include "utils/unique_file.h" #ifndef GPUCA_STANDALONE #include "GPUO2InterfaceConfiguration.h" @@ -1019,15 +1020,14 @@ void GPUReconstruction::QueryHostMemoryUSS(const char* where) { #ifdef __linux__ size_t uss = 0; - if (FILE* fp = fopen("/proc/self/smaps_rollup", "r")) { + if (unique_file fp(fopen("/proc/self/smaps_rollup", "r")); fp) { char line[256]; - while (fgets(line, sizeof(line), fp)) { + while (fgets(line, sizeof(line), fp.get())) { size_t val; if (sscanf(line, "Private_Clean: %zu kB", &val) == 1 || sscanf(line, "Private_Dirty: %zu kB", &val) == 1 || sscanf(line, "Private_Hugetlb: %zu kB", &val) == 1) { uss += val * 1024; } } - fclose(fp); } stdspinlock spinlock(mMemoryMutex); if (uss > mHostMemoryUSSMax) { diff --git a/GPU/GPUTracking/Base/GPUReconstructionIO.h b/GPU/GPUTracking/Base/GPUReconstructionIO.h index 7d8a87b310d96..d90b368697356 100644 --- a/GPU/GPUTracking/Base/GPUReconstructionIO.h +++ b/GPU/GPUTracking/Base/GPUReconstructionIO.h @@ -17,6 +17,7 @@ #include "GPUReconstruction.h" #include "GPUSettings.h" +#include "utils/unique_file.h" #include namespace o2::gpu @@ -116,37 +117,34 @@ inline size_t GPUReconstruction::ReadData(FILE* fp, const T** entries, S* num, s template inline void GPUReconstruction::DumpFlatObjectToFile(const T* obj, const char* file) { - FILE* fp = fopen(file, "w+b"); - if (fp == nullptr) { + unique_file fp(fopen(file, "w+b")); + if (!fp) { return; } size_t size[2] = {sizeof(*obj), obj->getFlatBufferSize()}; - fwrite(size, sizeof(size[0]), 2, fp); - fwrite(obj, 1, size[0], fp); - fwrite(obj->getFlatBufferPtr(), 1, size[1], fp); - fclose(fp); + fwrite(size, sizeof(size[0]), 2, fp.get()); + fwrite(obj, 1, size[0], fp.get()); + fwrite(obj->getFlatBufferPtr(), 1, size[1], fp.get()); } template inline std::unique_ptr GPUReconstruction::ReadFlatObjectFromFile(const char* file) { - FILE* fp = fopen(file, "rb"); - if (fp == nullptr) { + unique_file fp(fopen(file, "rb")); + if (!fp) { return nullptr; } size_t size[2] = {0}, r; - r = fread(size, sizeof(size[0]), 2, fp); + r = fread(size, sizeof(size[0]), 2, fp.get()); if (r == 0 || size[0] != sizeof(T)) { - fclose(fp); GPUError("ERROR reading %s, invalid size: %zu (%zu expected)", file, size[0], sizeof(T)); throw std::runtime_error("invalid size"); } std::unique_ptr retVal(new T); retVal->destroy(); char* buf = new char[size[1]]; // Not deleted as ownership is transferred to FlatObject - r = fread((void*)retVal.get(), 1, size[0], fp); - r = fread(buf, 1, size[1], fp); - fclose(fp); + r = fread((void*)retVal.get(), 1, size[0], fp.get()); + r = fread(buf, 1, size[1], fp.get()); if (GetProcessingSettings().debugLevel >= 2 && !GetProcessingSettings().debugSilent) { GPUInfo("Read %zu bytes from %s", r, file); } @@ -159,30 +157,28 @@ inline std::unique_ptr GPUReconstruction::ReadFlatObjectFromFile(const char* template inline void GPUReconstruction::DumpStructToFile(const T* obj, const char* file) { - FILE* fp = fopen(file, "w+b"); - if (fp == nullptr) { + unique_file fp(fopen(file, "w+b")); + if (!fp) { return; } size_t size = sizeof(*obj); - fwrite(&size, sizeof(size), 1, fp); - fwrite(obj, 1, size, fp); - fclose(fp); + fwrite(&size, sizeof(size), 1, fp.get()); + fwrite(obj, 1, size, fp.get()); } template inline std::unique_ptr GPUReconstruction::ReadStructFromFile(const char* file, T* obj, bool* errorOnMissing, bool allowSmaller) { - FILE* fp = fopen(file, "rb"); - if (fp == nullptr) { + unique_file fp(fopen(file, "rb")); + if (!fp) { if (errorOnMissing) { *errorOnMissing = true; } return nullptr; } size_t size, r; - r = fread(&size, sizeof(size), 1, fp); + r = fread(&size, sizeof(size), 1, fp.get()); if (r == 0 || (!allowSmaller && size != sizeof(T))) { - fclose(fp); GPUError("ERROR reading %s, invalid size: %zu (%zu expected)", file, size, sizeof(T)); throw std::runtime_error("invalid size"); } @@ -191,8 +187,7 @@ inline std::unique_ptr GPUReconstruction::ReadStructFromFile(const char* file retVal = std::make_unique(); obj = retVal.get(); } - r = fread(obj, 1, size, fp); - fclose(fp); + r = fread(obj, 1, size, fp.get()); if (r != size) { GPUError("ERROR reading %s, read %zu (%zu expected)", file, r, size); throw std::runtime_error("invalid size"); @@ -209,48 +204,43 @@ inline std::unique_ptr GPUReconstruction::ReadStructFromFile(const char* file template inline void GPUReconstruction::DumpDynamicStructToFile(const T* obj, size_t dynamicSize, const char* file) { - FILE* fp = fopen(file, "w+b"); - if (fp == nullptr) { + unique_file fp(fopen(file, "w+b")); + if (!fp) { return; } size_t size = sizeof(*obj); - fwrite(&size, sizeof(size), 1, fp); - fwrite(&dynamicSize, sizeof(dynamicSize), 1, fp); - fwrite(obj, 1, dynamicSize, fp); - fclose(fp); + fwrite(&size, sizeof(size), 1, fp.get()); + fwrite(&dynamicSize, sizeof(dynamicSize), 1, fp.get()); + fwrite(obj, 1, dynamicSize, fp.get()); } template inline aligned_unique_buffer_ptr GPUReconstruction::ReadDynamicStructFromFile(const char* file) { - FILE* fp = fopen(file, "rb"); - if (fp == nullptr) { + unique_file fp(fopen(file, "rb")); + if (!fp) { return nullptr; } size_t size, dynsize, r, r2; - r = fread(&size, sizeof(size), 1, fp); - r2 = fread(&dynsize, sizeof(dynsize), 1, fp); + r = fread(&size, sizeof(size), 1, fp.get()); + r2 = fread(&dynsize, sizeof(dynsize), 1, fp.get()); if (r == 0 || r2 == 0 || size != sizeof(T) || dynsize < size) { - fclose(fp); GPUError("ERROR reading %s, invalid size: %zu (%zu buffer size, %zu object size expected)", file, size, dynsize, sizeof(T)); throw std::runtime_error("invalid size"); } std::unique_ptr tmp = std::make_unique(); - r = fread(tmp.get(), sizeof(T), 1, fp); + r = fread(tmp.get(), sizeof(T), 1, fp.get()); if (r == 0) { - fclose(fp); GPUError("ERROR reading %s %zu (%zu expected)", file, size, sizeof(T)); throw std::runtime_error("read error"); } if ((tmp.get()->*F)() != dynsize) { - fclose(fp); GPUError("ERROR in %s: invalid size: %zu (%zu expected)", file, dynsize, (tmp.get()->*F)()); throw std::runtime_error("invalid size"); } aligned_unique_buffer_ptr newObj(dynsize); memcpy(newObj.get(), tmp.get(), sizeof(T)); - r = fread(newObj.getraw() + sizeof(T), 1, dynsize - sizeof(T), fp); - fclose(fp); + r = fread(newObj.getraw() + sizeof(T), 1, dynsize - sizeof(T), fp.get()); if (r != dynsize - sizeof(T)) { GPUError("ERROR in %s: File Read error: %zu (%zu expected)", file, r, dynsize - sizeof(T)); throw std::runtime_error("invalid size"); diff --git a/GPU/GPUTracking/Base/GPUReconstructionRTCHelpers.inc b/GPU/GPUTracking/Base/GPUReconstructionRTCHelpers.inc index 49ccbabc35c58..a9cbd01a54292 100644 --- a/GPU/GPUTracking/Base/GPUReconstructionRTCHelpers.inc +++ b/GPU/GPUTracking/Base/GPUReconstructionRTCHelpers.inc @@ -21,6 +21,7 @@ #include "GPULogging.h" #include "Framework/SHA1.h" #include "utils/timer.h" +#include "utils/unique_file.h" #include #include @@ -76,20 +77,16 @@ static std::string baseCommand(const GPUSettingsProcessing& proc, std::string_vi static void loadLaunchBounds(const GPUSettingsProcessing& proc, GPUDefParameters& par) { if (proc.rtctech.loadLaunchBoundsFromFile.size()) { - FILE* fp = fopen(proc.rtctech.loadLaunchBoundsFromFile.c_str(), "rb"); - if (fp == nullptr) { + unique_file fp(fopen(proc.rtctech.loadLaunchBoundsFromFile.c_str(), "rb")); + if (!fp) { throw std::runtime_error("Cannot open launch bounds parameter module file"); } - fseek(fp, 0, SEEK_END); - size_t size = ftell(fp); - if (size != sizeof(par)) { + if (std::filesystem::file_size(proc.rtctech.loadLaunchBoundsFromFile) != sizeof(par)) { throw std::runtime_error("launch bounds parameter file has incorrect size"); } - fseek(fp, 0, SEEK_SET); - if (fread(&par, 1, size, fp) != size) { + if (fread(&par, 1, sizeof(par), fp.get()) != sizeof(par)) { throw std::runtime_error("Error reading launch bounds parameter file"); } - fclose(fp); } std::vector overrides; const std::string& str = proc.rtctech.overrideRTCParameters; @@ -121,16 +118,15 @@ static bool deterministic(const GPUSettingsProcessing& proc, const std::string& static void writeSource(const std::string& file, bool deterministic, const std::string& param, const std::string& launchBounds, std::string_view source, const std::string& kernel) { const std::string deterministicStr = deterministic ? "#define GPUCA_DETERMINISTIC_CODE(det, indet) det\n" : "#define GPUCA_DETERMINISTIC_CODE(det, indet) indet\n"; - FILE* fp = fopen(file.c_str(), "w+b"); - if (fp == nullptr) { + unique_file fp(fopen(file.c_str(), "w+b")); + if (!fp) { throw std::runtime_error("Error opening file"); } for (std::string_view part : {std::string_view(deterministicStr), std::string_view(param), std::string_view(launchBounds), source, std::string_view(kernel)}) { - if (fwrite(part.data(), 1, part.size(), fp) != part.size()) { + if (fwrite(part.data(), 1, part.size(), fp.get()) != part.size()) { throw std::runtime_error("Error writing file"); } } - fclose(fp); } static void runCommand(const GPUSettingsProcessing& proc, std::string command, const std::string& sourceFile, const char* errorMessage) @@ -225,12 +221,11 @@ class Cache // RTC cache file /rtc..cache. (no id with if (!mProc.rtc.cacheOutput) { return false; } - FILE* fp = fopen(mFile.c_str(), "rb"); - if (fp == nullptr) { + unique_file fp(fopen(mFile.c_str(), "rb")); + if (!fp) { return false; } - bool retVal = read(fp, filename, binExtension, nCompile); - fclose(fp); + bool retVal = read(fp.get(), filename, binExtension, nCompile); if (retVal) { GPUInfo("Using RTC cache file %s", mFileName.c_str()); std::error_code ec; @@ -244,38 +239,35 @@ class Cache // RTC cache file /rtc..cache. (no id with if (!mProc.rtc.cacheOutput) { return; } - FILE* fp = fopen(mFile.c_str(), "w+b"); - if (fp == nullptr) { + unique_file fp(fopen(mFile.c_str(), "w+b")); + if (!fp) { throw std::runtime_error("Cannot open cache file for writing"); } GPUInfo("Storing RTC compilation result in cache file %s", mFileName.c_str()); for (uint32_t i = 0; i < N_SHA; i++) { - if (fwrite(mSHA[i], 1, 20, fp) != 20) { + if (fwrite(mSHA[i], 1, 20, fp.get()) != 20) { throw std::runtime_error("Error writing cache file"); } } - if (fwrite(&mProc.rtc, sizeof(mProc.rtc), 1, fp) != 1) { + if (fwrite(&mProc.rtc, sizeof(mProc.rtc), 1, fp.get()) != 1) { throw std::runtime_error("Error writing cache file"); } std::vector buffer; for (uint32_t i = 0; i < nCompile; i++) { - FILE* fp2 = fopen(std::format("{}_{}{}", filename, i, binExtension).c_str(), "rb"); - if (fp2 == nullptr) { + const std::string binFile = std::format("{}_{}{}", filename, i, binExtension); + unique_file fp2(fopen(binFile.c_str(), "rb")); + if (!fp2) { throw std::runtime_error("Cannot open RTC binary file"); } - fseek(fp2, 0, SEEK_END); - size_t size = ftell(fp2); + size_t size = std::filesystem::file_size(binFile); buffer.resize(size); - fseek(fp2, 0, SEEK_SET); - if (fread(buffer.data(), 1, size, fp2) != size) { + if (fread(buffer.data(), 1, size, fp2.get()) != size) { throw std::runtime_error("Error reading RTC binary file"); } - fclose(fp2); - if (fwrite(&size, sizeof(size), 1, fp) != 1 || fwrite(buffer.data(), 1, size, fp) != size) { + if (fwrite(&size, sizeof(size), 1, fp.get()) != 1 || fwrite(buffer.data(), 1, size, fp.get()) != size) { throw std::runtime_error("Error writing cache file"); } } - fclose(fp); removeOldFiles(); } @@ -344,14 +336,13 @@ class Cache // RTC cache file /rtc..cache. (no id with if (fread(buffer.data(), 1, len, fp) != len) { throw std::runtime_error("Cache file corrupt"); } - FILE* fp2 = fopen(std::format("{}_{}{}", filename, i, binExtension).c_str(), "w+b"); - if (fp2 == nullptr) { + unique_file fp2(fopen(std::format("{}_{}{}", filename, i, binExtension).c_str(), "w+b")); + if (!fp2) { throw std::runtime_error("Cannot open tmp file"); } - if (fwrite(buffer.data(), 1, len, fp2) != len) { + if (fwrite(buffer.data(), 1, len, fp2.get()) != len) { throw std::runtime_error("Error writing file"); } - fclose(fp2); } return true; } diff --git a/GPU/GPUTracking/Base/cpudevice/GPUReconstructionCPUDeviceGenRTC.cxx b/GPU/GPUTracking/Base/cpudevice/GPUReconstructionCPUDeviceGenRTC.cxx index e0fd79c2a0043..94ba0dadfa78f 100644 --- a/GPU/GPUTracking/Base/cpudevice/GPUReconstructionCPUDeviceGenRTC.cxx +++ b/GPU/GPUTracking/Base/cpudevice/GPUReconstructionCPUDeviceGenRTC.cxx @@ -81,11 +81,10 @@ int32_t GPUReconstructionCPUDevice::genRTC(std::string& filename, uint32_t& nCom rtchelpers::writeSource(fileBase + RTC_SRC_EXTENSION, deterministic, rtcparam, launchBounds, rtcSource, proc.rtc.compilePerKernel ? kernels[i] : kernelsall); // Export only the kernel entry points, everything else stays local to the RTC library to avoid symbol collisions - FILE* fp = fopen((fileBase + RTC_MAP_EXTENSION).c_str(), "w+b"); - if (fp == nullptr || fprintf(fp, "{ global: krnl_*; local: *; };\n") < 0) { + unique_file fp(fopen((fileBase + RTC_MAP_EXTENSION).c_str(), "w+b")); + if (!fp || fprintf(fp.get(), "{ global: krnl_*; local: *; };\n") < 0) { throw std::runtime_error("Error writing version script"); } - fclose(fp); const std::string command = baseCommand + (deterministic ? " " + noFastMath : "") + " -Wl,--version-script=" + fileBase + RTC_MAP_EXTENSION + " -x c++ " + fileBase + RTC_SRC_EXTENSION + " -o " + fileBase + RTC_BIN_EXTENSION; rtchelpers::runCommand(proc, command, fileBase + RTC_SRC_EXTENSION, "Error during CPUDevice RTC compilation"); diff --git a/GPU/GPUTracking/Global/GPUChainTrackingDebugAndProfiling.cxx b/GPU/GPUTracking/Global/GPUChainTrackingDebugAndProfiling.cxx index be5e9690fb20b..a976559fed566 100644 --- a/GPU/GPUTracking/Global/GPUChainTrackingDebugAndProfiling.cxx +++ b/GPU/GPUTracking/Global/GPUChainTrackingDebugAndProfiling.cxx @@ -17,6 +17,7 @@ #include "GPUMemorySizeScalers.h" #include "GPUConstantMem.h" #include "GPUTPCClusterFilter.h" +#include "utils/unique_file.h" #include #include #include @@ -49,8 +50,8 @@ int32_t GPUChainTracking::DoProfile() std::unique_ptr stageAtSync{new char[PROFILE_MAX_SIZE]}; mRec->GPUMemCpy(stageAtSync.get(), processorsShadow()->tpcTrackers[0].mStageAtSync, PROFILE_MAX_SIZE, -1, false); - FILE* fp = fopen("profile.txt", "w+"); - FILE* fp2 = fopen("profile.bmp", "w+b"); + unique_file file(fopen("profile.txt", "w+")), file2(fopen("profile.bmp", "w+b")); + FILE *fp = file.get(), *fp2 = file2.get(); const int32_t bmpheight = 8192; BITMAPFILEHEADER bmpFH; @@ -107,8 +108,6 @@ int32_t GPUChainTracking::DoProfile() // if (nEmptySync == GPUCA_SCHED_ROW_STEP + 2) break; } - fclose(fp); - fclose(fp2); #endif return 0; } @@ -478,13 +477,12 @@ void GPUChainTracking::DoDebugMergerNClDump(const GPUTPCGMMerger& merger) if (GetRecoStepsGPU() & RecoStep::TPCMerging) { SynchronizeGPU(); } - FILE* fout = fopen("merger_tracks_ncl.txt", "w+"); - if (fout == nullptr) { + unique_file fout(fopen("merger_tracks_ncl.txt", "w+")); + if (!fout) { throw std::runtime_error("Error Opening Debug File"); } for (int32_t i = 0; i < merger.NMergedTracks(); i++) { - fprintf(fout, "Track %7d NCl %5u\n", i, merger.MergedTracks()[i].OK() ? merger.MergedTracks()[i].NClustersFitted() : 0u); + fprintf(fout.get(), "Track %7d NCl %5u\n", i, merger.MergedTracks()[i].OK() ? merger.MergedTracks()[i].NClustersFitted() : 0u); } - fclose(fout); } } diff --git a/GPU/GPUTracking/Global/GPUChainTrackingIO.cxx b/GPU/GPUTracking/Global/GPUChainTrackingIO.cxx index f498f27532fa4..c7efb52523f20 100644 --- a/GPU/GPUTracking/Global/GPUChainTrackingIO.cxx +++ b/GPU/GPUTracking/Global/GPUChainTrackingIO.cxx @@ -32,6 +32,7 @@ #include "GPUReconstructionConvert.h" #include "GPUMemorySizeScalers.h" #include "GPUTrackingInputProvider.h" +#include "utils/unique_file.h" #include "TPCZSLinkMapping.h" #include "GPUTriggerOutputs.h" #include "GPUConstantMem.h" @@ -66,7 +67,8 @@ GPUChainTracking::InOutMemory& GPUChainTracking::InOutMemory::operator=(GPUChain void GPUChainTracking::DumpData(const char* filename, const GPUTrackingInOutPointers* ioPtrs) { - FILE* fp = fopen(filename, "w+b"); + unique_file file(fopen(filename, "w+b")); + FILE* fp = file.get(); if (fp == nullptr) { return; } @@ -158,13 +160,13 @@ void GPUChainTracking::DumpData(const char* filename, const GPUTrackingInOutPoin DumpData(fp, &ioPtrs->trdTriggerTimes, &ioPtrs->nTRDTriggerRecords, InOutPointerType::TRD_TRIGGERRECORDS); DumpData(fp, &ioPtrs->trdTrackletIdxFirst, &ioPtrs->nTRDTriggerRecords, InOutPointerType::TRD_TRIGGERRECORDS); DumpData(fp, &ioPtrs->trdTrigRecMask, &ioPtrs->nTRDTriggerRecords, InOutPointerType::TRD_TRIGGERRECORDS); - fclose(fp); } int32_t GPUChainTracking::ReadData(const char* filename) { ClearIOPointers(); - FILE* fp = fopen(filename, "rb"); + unique_file file(fopen(filename, "rb")); + FILE* fp = file.get(); if (fp == nullptr) { return (1); } @@ -173,14 +175,12 @@ int32_t GPUChainTracking::ReadData(const char* filename) [[maybe_unused]] size_t r = fread(buf, 1, DUMP_HEADER_SIZE, fp); if (strncmp(DUMP_HEADER, buf, DUMP_HEADER_SIZE)) { GPUError("Invalid file header"); - fclose(fp); return -1; } GeometryType geo; r = fread(&geo, sizeof(geo), 1, fp); if (geo != GPUReconstruction::geometryType) { GPUError("File has invalid geometry (%s v.s. %s)", GPUReconstruction::GEOMETRY_TYPE_NAMES[(int32_t)geo], GPUReconstruction::GEOMETRY_TYPE_NAMES[(int32_t)GPUReconstruction::geometryType]); - fclose(fp); return 1; } GPUTPCClusterData* ptrClusterData[NSECTORS]; @@ -262,7 +262,6 @@ int32_t GPUChainTracking::ReadData(const char* filename) size_t fptr = ftell(fp); fseek(fp, 0, SEEK_END); size_t fend = ftell(fp); - fclose(fp); if (fptr != fend) { GPUError("Error reading data file, reading incomplete"); return 1; diff --git a/GPU/GPUTracking/display/helpers/GPUDisplayHelpers.cxx b/GPU/GPUTracking/display/helpers/GPUDisplayHelpers.cxx index 0bff0bf121c73..9554e8ee53b2d 100644 --- a/GPU/GPUTracking/display/helpers/GPUDisplayHelpers.cxx +++ b/GPU/GPUTracking/display/helpers/GPUDisplayHelpers.cxx @@ -18,6 +18,7 @@ #include "GPUChainTracking.h" #include "GPULogging.h" #include "GPUParam.h" +#include "utils/unique_file.h" #ifndef _WIN32 #include "bitmapfile.h" @@ -80,14 +81,13 @@ void GPUDisplay::SaveGLPos() void GPUDisplay::LoadGLPos() { const char* file = mCfgO.glPosFile.c_str(); - FILE* ftmp = fopen(file, "rb"); + unique_file ftmp(fopen(file, "rb")); if (!ftmp) { SetInfo("Error opening file %s", file); return; } hmm_mat4 matrix; - const bool ok = fread(&matrix, sizeof(matrix), 1, ftmp) == 1; - fclose(ftmp); + const bool ok = fread(&matrix, sizeof(matrix), 1, ftmp.get()) == 1; if (ok) { *mViewMatrix = matrix; } @@ -114,25 +114,25 @@ void GPUDisplay::LoadGLAnimation() { StopAnimation(); const char* file = mCfgO.glAnimationFile.c_str(); - FILE* ftmp = fopen(file, "rb"); + unique_file ftmp(fopen(file, "rb")); if (!ftmp) { SetInfo("Error opening file %s", file); return; } GPUSettingsDisplayLight cfg; int32_t size = 0; - bool ok = fread(&cfg, sizeof(cfg), 1, ftmp) == 1 && fread(&size, sizeof(size), 1, ftmp) == 1 && size >= 0; + bool ok = fread(&cfg, sizeof(cfg), 1, ftmp.get()) == 1 && fread(&size, sizeof(size), 1, ftmp.get()) == 1 && size >= 0; if (ok) { - const long start = ftell(ftmp); - fseek(ftmp, 0, SEEK_END); - ok = (size_t)ftell(ftmp) == start + (size_t)size * (sizeof(float) + sizeof(animationVector)); - fseek(ftmp, start, SEEK_SET); + const long start = ftell(ftmp.get()); + fseek(ftmp.get(), 0, SEEK_END); + ok = (size_t)ftell(ftmp.get()) == start + (size_t)size * (sizeof(float) + sizeof(animationVector)); + fseek(ftmp.get(), start, SEEK_SET); } if (ok) { mCfgC.animationPoints.values.resize(size); mAnimationVectors.resize(size); - ok = ok && fread(mCfgC.animationPoints.values.data(), sizeof(float), size, ftmp) == (size_t)size; - ok = ok && fread(mAnimationVectors.data(), sizeof(mAnimationVectors[0]), size, ftmp) == (size_t)size; + ok = ok && fread(mCfgC.animationPoints.values.data(), sizeof(float), size, ftmp.get()) == (size_t)size; + ok = ok && fread(mAnimationVectors.data(), sizeof(mAnimationVectors[0]), size, ftmp.get()) == (size_t)size; mCfgC.animationPoints.selected = -1; if (ok) { mCfgL = cfg; @@ -141,7 +141,6 @@ void GPUDisplay::LoadGLAnimation() resetAnimation(); // Read error after the size check: no incomplete path } } - fclose(ftmp); SetInfo(ok ? "Animation path loaded from file %s" : "Error reading animation path from file %s", file); } @@ -164,8 +163,8 @@ void GPUDisplay::DoScreenshot(const char* filename, std::vector& pixels, f } if (filename) { - FILE* fp = fopen(filename, "w+b"); - if (fp == nullptr) { + unique_file fp(fopen(filename, "w+b")); + if (!fp) { GPUError("Error opening screenshot file %s", filename); return; } @@ -189,10 +188,9 @@ void GPUDisplay::DoScreenshot(const char* filename, std::vector& pixels, f bmpIH.biXPelsPerMeter = 5670; bmpIH.biYPelsPerMeter = 5670; - fwrite(&bmpFH, 1, sizeof(bmpFH), fp); - fwrite(&bmpIH, 1, sizeof(bmpIH), fp); - fwrite(pixels.data(), 1, size, fp); - fclose(fp); + fwrite(&bmpFH, 1, sizeof(bmpFH), fp.get()); + fwrite(&bmpIH, 1, sizeof(bmpIH), fp.get()); + fwrite(pixels.data(), 1, size, fp.get()); } } diff --git a/GPU/GPUTracking/qa/GPUQA.cxx b/GPU/GPUTracking/qa/GPUQA.cxx index 95846241e0137..6fd5c4fd2d901 100644 --- a/GPU/GPUTracking/qa/GPUQA.cxx +++ b/GPU/GPUTracking/qa/GPUQA.cxx @@ -614,61 +614,53 @@ int32_t GPUQA::loadHistograms(std::vector& i1, std::vector& i2, std: void GPUQA::DumpO2MCData(const char* filename) const { - FILE* fp = fopen(filename, "w+b"); - if (fp == nullptr) { + unique_file fp(fopen(filename, "w+b")); + if (!fp) { return; } uint32_t n = mMCInfos.size(); - fwrite(&n, sizeof(n), 1, fp); - fwrite(mMCInfos.data(), sizeof(mMCInfos[0]), n, fp); + fwrite(&n, sizeof(n), 1, fp.get()); + fwrite(mMCInfos.data(), sizeof(mMCInfos[0]), n, fp.get()); n = mMCInfosCol.size(); - fwrite(&n, sizeof(n), 1, fp); - fwrite(mMCInfosCol.data(), sizeof(mMCInfosCol[0]), n, fp); + fwrite(&n, sizeof(n), 1, fp.get()); + fwrite(mMCInfosCol.data(), sizeof(mMCInfosCol[0]), n, fp.get()); n = mMCEventOffset.size(); - fwrite(&n, sizeof(n), 1, fp); - fwrite(mMCEventOffset.data(), sizeof(mMCEventOffset[0]), n, fp); - fclose(fp); + fwrite(&n, sizeof(n), 1, fp.get()); + fwrite(mMCEventOffset.data(), sizeof(mMCEventOffset[0]), n, fp.get()); } int32_t GPUQA::ReadO2MCData(const char* filename) { - FILE* fp = fopen(filename, "rb"); - if (fp == nullptr) { + unique_file fp(fopen(filename, "rb")); + if (!fp) { return 1; } uint32_t n; uint32_t x; - if ((x = fread(&n, sizeof(n), 1, fp)) != 1) { - fclose(fp); + if ((x = fread(&n, sizeof(n), 1, fp.get())) != 1) { return 1; } mMCInfos.resize(n); - if (fread(mMCInfos.data(), sizeof(mMCInfos[0]), n, fp) != n) { - fclose(fp); + if (fread(mMCInfos.data(), sizeof(mMCInfos[0]), n, fp.get()) != n) { return 1; } - if ((x = fread(&n, sizeof(n), 1, fp)) != 1) { - fclose(fp); + if ((x = fread(&n, sizeof(n), 1, fp.get())) != 1) { return 1; } mMCInfosCol.resize(n); - if (fread(mMCInfosCol.data(), sizeof(mMCInfosCol[0]), n, fp) != n) { - fclose(fp); + if (fread(mMCInfosCol.data(), sizeof(mMCInfosCol[0]), n, fp.get()) != n) { return 1; } - if ((x = fread(&n, sizeof(n), 1, fp)) != 1) { - fclose(fp); + if ((x = fread(&n, sizeof(n), 1, fp.get())) != 1) { return 1; } mMCEventOffset.resize(n); - if (fread(mMCEventOffset.data(), sizeof(mMCEventOffset[0]), n, fp) != n) { - fclose(fp); + if (fread(mMCEventOffset.data(), sizeof(mMCEventOffset[0]), n, fp.get()) != n) { return 1; } if (mTracking && mTracking->GetProcessingSettings().debugLevel >= 2) { - printf("Read %ld bytes MC Infos\n", ftell(fp)); + printf("Read %ld bytes MC Infos\n", ftell(fp.get())); } - fclose(fp); if (mTracking) { CopyO2MCtoIOPtr(&mTracking->mIOPtrs); } @@ -3306,8 +3298,8 @@ void GPUQA::PrintClusterCount(int32_t mode, int32_t& num, const char* name, uint createHist(mHistClusterCount[num], name2.c_str(), name, 1000, 0, mConfig.histMaxNClusters, 1000, 0, 100); } else if (mode == 0) { if (normalization && mConfig.enableLocalOutput) { - for (uint32_t i = 0; i < 1 + (mTextDump != nullptr); i++) { - fprintf(i ? mTextDump : stdout, "\t%40s: %'12" PRIu64 " (%6.2f%%)\n", name, n, 100.f * n / normalization); + for (uint32_t i = 0; i < (mTextDump ? 2u : 1u); i++) { + fprintf(i ? mTextDump.get() : stdout, "\t%40s: %'12" PRIu64 " (%6.2f%%)\n", name, n, 100.f * n / normalization); } } if (mConfig.clusterRejectionHistograms) { @@ -3321,7 +3313,7 @@ void GPUQA::PrintClusterCount(int32_t mode, int32_t& num, const char* name, uint int32_t GPUQA::DoClusterCounts(uint64_t* attachClusterCounts, int32_t mode) { if (mConfig.enableLocalOutput && !mConfig.inputHistogramsOnly && mConfig.plotsDir != "") { - mTextDump = fopen((mConfig.plotsDir + "/clusterCounts.txt").c_str(), "w+"); + mTextDump.reset(fopen((mConfig.plotsDir + "/clusterCounts.txt").c_str(), "w+")); } int32_t num = 0; if (mcPresent() && (mQATasks & taskClusterAttach) && attachClusterCounts) { @@ -3363,10 +3355,7 @@ int32_t GPUQA::DoClusterCounts(uint64_t* attachClusterCounts, int32_t mode) PrintClusterCount(mode, num, "Correctly Attached all-trk row-normalized", mClusterCounts.nCorrectlyAttachedNormalized, mClusterCounts.nTotal); PrintClusterCount(mode, num, "Correctly Attached non-fake row-normalized", mClusterCounts.nCorrectlyAttachedNormalizedNonFake, mClusterCounts.nTotal); } - if (mTextDump) { - fclose(mTextDump); - mTextDump = nullptr; - } + mTextDump.reset(); return num; } diff --git a/GPU/GPUTracking/qa/GPUQA.h b/GPU/GPUTracking/qa/GPUQA.h index ad013890814f5..b5ca36001f9d6 100644 --- a/GPU/GPUTracking/qa/GPUQA.h +++ b/GPU/GPUTracking/qa/GPUQA.h @@ -64,6 +64,7 @@ class GPUQA #include "GPUTPCDef.h" #include "GPUDataTypesIO.h" +#include "utils/unique_file.h" #include #include #include @@ -365,7 +366,7 @@ class GPUQA int32_t mMCTrackMin = -1, mMCTrackMax = -1; const o2::tpc::ClusterNativeAccess* mClNative = nullptr; - FILE* mTextDump = nullptr; + unique_file mTextDump; }; inline bool GPUQA::SuppressTrack(int32_t iTrack) const { return (mConfig.matchMCLabels.size() && !mGoodTracks[mNEvents][iTrack]); } diff --git a/GPU/GPUTracking/utils/unique_file.h b/GPU/GPUTracking/utils/unique_file.h new file mode 100644 index 0000000000000..18531ada7ff84 --- /dev/null +++ b/GPU/GPUTracking/utils/unique_file.h @@ -0,0 +1,29 @@ +// Copyright 2019-2026 CERN and copyright holders of ALICE O2. +// See https://alice-o2.web.cern.ch/copyright for details of the copyright holders. +// All rights not expressly granted are reserved. +// +// This software is distributed under the terms of the GNU General Public +// License v3 (GPL Version 3), copied verbatim in the file "COPYING". +// +// In applying this license CERN does not waive the privileges and immunities +// granted to it by virtue of its status as an Intergovernmental Organization +// or submit itself to any jurisdiction. + +/// \file unique_file.h +/// \author David Rohr + +#ifndef Q_UNIQUE_FILE_H +#define Q_UNIQUE_FILE_H + +#include +#include + +namespace o2::gpu +{ +struct unique_file_deleter { + void operator()(FILE* fp) const { fclose(fp); } +}; +using unique_file = std::unique_ptr; // FILE* closed with fclose when going out of scope: unique_file fp(fopen(name, mode)); +} // namespace o2::gpu + +#endif // Q_UNIQUE_FILE_H diff --git a/GPU/Workflow/src/GPUWorkflowSpec.cxx b/GPU/Workflow/src/GPUWorkflowSpec.cxx index 44da7908dc4f5..579da0b43b071 100644 --- a/GPU/Workflow/src/GPUWorkflowSpec.cxx +++ b/GPU/Workflow/src/GPUWorkflowSpec.cxx @@ -52,6 +52,7 @@ #include "CommonUtils/NameConf.h" #include "TPCBase/RDHUtils.h" #include "GPUO2InterfaceConfiguration.h" +#include "utils/unique_file.h" #include "GPUO2InterfaceQA.h" #include "GPUO2Interface.h" #include "GPUO2InterfaceUtils.h" @@ -852,17 +853,20 @@ void GPURecoWorkflowSpec::run(ProcessingContext& pc) mNDebugDumps++; if (mConfParam->dumpBadTFMode <= 1) { std::string filename = std::format("tpc_dump_{}_{}.dump", pc.services().get().inputTimesliceId, mNDebugDumps); - FILE* fp = fopen(filename.c_str(), "w+b"); - std::vector filter = {{"check", ConcreteDataTypeMatcher{gDataOriginTPC, "RAWDATA"}, Lifetime::Timeframe}}; - for (auto const& ref : InputRecordWalker(pc.inputs(), filter)) { - auto data = pc.inputs().get>(ref); - if (mConfParam->dumpBadTFMode == 1) { - uint64_t size = data.size(); - fwrite(&size, 1, sizeof(size), fp); + unique_file fp(fopen(filename.c_str(), "w+b")); + if (!fp) { + LOG(error) << "Error opening TF dump file " << filename; + } else { + std::vector filter = {{"check", ConcreteDataTypeMatcher{gDataOriginTPC, "RAWDATA"}, Lifetime::Timeframe}}; + for (auto const& ref : InputRecordWalker(pc.inputs(), filter)) { + auto data = pc.inputs().get>(ref); + if (mConfParam->dumpBadTFMode == 1) { + uint64_t size = data.size(); + fwrite(&size, 1, sizeof(size), fp.get()); + } + fwrite(data.data(), 1, data.size(), fp.get()); } - fwrite(data.data(), 1, data.size(), fp); } - fclose(fp); } else if (mConfParam->dumpBadTFMode == 2) { mGPUReco->DumpEvent(mNDebugDumps - 1, ptrsDump.get(), threadIndex); } From 03bc68cd913dece56b4a291301c929452c4be340 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Tue, 1 Dec 2026 18:06:23 +0100 Subject: [PATCH 14/41] GPU: Modernize C++: Improve initialization of some members --- GPU/GPUTracking/Base/GPUReconstruction.cxx | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/GPU/GPUTracking/Base/GPUReconstruction.cxx b/GPU/GPUTracking/Base/GPUReconstruction.cxx index afd6d04630849..c057b231992af 100644 --- a/GPU/GPUTracking/Base/GPUReconstruction.cxx +++ b/GPU/GPUTracking/Base/GPUReconstruction.cxx @@ -58,8 +58,8 @@ namespace // anonymous struct GPUReconstructionPipelineQueue { uint32_t op = 0; // For now, 0 = process, 1 = terminate GPUChain* chain = nullptr; - std::mutex m; - std::condition_variable c; + std::mutex m{}; + std::condition_variable c{}; bool done = false; int32_t retVal = 0; }; @@ -82,7 +82,7 @@ constexpr GPUReconstruction::GeometryType GPUReconstruction::geometryType; static ptrdiff_t ptrDiff(void* a, void* b) { return (char*)a - (char*)b; } -GPUReconstruction::GPUReconstruction(const GPUSettingsDeviceBackend& cfg) : mHostConstantMem(new GPUConstantMem), mGRPSettings(new GPUSettingsGRP), mDeviceBackendSettings(new GPUSettingsDeviceBackend(cfg)), mProcessingSettings(new GPUSettingsProcessing) +GPUReconstruction::GPUReconstruction(const GPUSettingsDeviceBackend& cfg) : mHostConstantMem(std::make_unique()), mGRPSettings(std::make_unique()), mDeviceBackendSettings(std::make_unique(cfg)), mProcessingSettings(std::make_unique()), mMemoryScalers(std::make_unique()) { if (cfg.master) { if (cfg.master->GetDeviceBackendSettings().deviceType != cfg.deviceType) { @@ -96,7 +96,6 @@ GPUReconstruction::GPUReconstruction(const GPUSettingsDeviceBackend& cfg) : mHos cfg.master->mSlaves.emplace_back(this); } param().SetDefaults(mGRPSettings.get()); - mMemoryScalers.reset(new GPUMemorySizeScalers); } GPUReconstruction::~GPUReconstruction() From 8646d9b43d6dc0668a406d1edfc010185825dde3 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Tue, 1 Dec 2026 18:07:24 +0100 Subject: [PATCH 15/41] GPU: Modernize C++: Use make_unique_for_overwrite where possible --- GPU/GPUTracking/Base/GPUReconstructionCPU.cxx | 2 +- GPU/GPUTracking/Base/GPUReconstructionConvert.cxx | 4 ++-- GPU/GPUTracking/Base/GPUReconstructionIO.h | 4 ++-- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/GPU/GPUTracking/Base/GPUReconstructionCPU.cxx b/GPU/GPUTracking/Base/GPUReconstructionCPU.cxx index 22a0e0013a59a..a2157347275bb 100644 --- a/GPU/GPUTracking/Base/GPUReconstructionCPU.cxx +++ b/GPU/GPUTracking/Base/GPUReconstructionCPU.cxx @@ -121,7 +121,7 @@ GPUConstantMem* GPUReconstructionCPU::DeviceProcessorOnHostView(const krnlSetupT return mDeviceConstantMem; } static_assert(alignof(GPUConstantMem) <= __STDCPP_DEFAULT_NEW_ALIGNMENT__); - copy = std::make_unique(sizeof(GPUConstantMem)); + copy = std::make_unique_for_overwrite(sizeof(GPUConstantMem)); GPUConstantMem* mem = (GPUConstantMem*)copy.get(); memcpy((void*)mem, (const void*)mProcessorsShadow, sizeof(GPUConstantMem)); auto onHost = [&](const GPUProcessor* p) { diff --git a/GPU/GPUTracking/Base/GPUReconstructionConvert.cxx b/GPU/GPUTracking/Base/GPUReconstructionConvert.cxx index 15f18774abd80..37528664f3eac 100644 --- a/GPU/GPUTracking/Base/GPUReconstructionConvert.cxx +++ b/GPU/GPUTracking/Base/GPUReconstructionConvert.cxx @@ -59,7 +59,7 @@ void GPUReconstructionConvert::ConvertRun2RawToNative(o2::tpc::ClusterNativeAcce } native.nClustersTotal += nRawClusters[i]; } - nativeBuffer.reset(new ClusterNative[native.nClustersTotal]); + nativeBuffer = std::make_unique_for_overwrite(native.nClustersTotal); native.clustersLinear = nativeBuffer.get(); native.setOffsetPtrs(); for (uint32_t i = 0; i < NSECTORS; i++) { @@ -1350,7 +1350,7 @@ void GPUReconstructionConvert::RunZSEncoder(const S& in, std::unique_ptrreset(new uint64_t[reduced.totalPages * TPCZSHDR::TPC_ZS_PAGE_SIZE / sizeof(uint64_t)]); + *outBuffer = std::make_unique_for_overwrite(reduced.totalPages * TPCZSHDR::TPC_ZS_PAGE_SIZE / sizeof(uint64_t)); uint64_t offset = 0; for (uint32_t i = 0; i < NSECTORS; i++) { for (uint32_t j = 0; j < GPUTrackingInOutZS::NENDPOINTS; j++) { diff --git a/GPU/GPUTracking/Base/GPUReconstructionIO.h b/GPU/GPUTracking/Base/GPUReconstructionIO.h index d90b368697356..628b11dddc7b4 100644 --- a/GPU/GPUTracking/Base/GPUReconstructionIO.h +++ b/GPU/GPUTracking/Base/GPUReconstructionIO.h @@ -40,7 +40,7 @@ inline T* GPUReconstruction::AllocateIOMemoryHelper(size_t n, const T*& ptr, std } } else { if constexpr (std::is_same_v>) { - u.reset(new T[n]); + u = std::make_unique_for_overwrite(n); } else { u.reset(alignedAllocator::allocate(n * sizeof(T))); } @@ -140,7 +140,7 @@ inline std::unique_ptr GPUReconstruction::ReadFlatObjectFromFile(const char* GPUError("ERROR reading %s, invalid size: %zu (%zu expected)", file, size[0], sizeof(T)); throw std::runtime_error("invalid size"); } - std::unique_ptr retVal(new T); + std::unique_ptr retVal = std::make_unique_for_overwrite(); retVal->destroy(); char* buf = new char[size[1]]; // Not deleted as ownership is transferred to FlatObject r = fread((void*)retVal.get(), 1, size[0], fp.get()); From 5b94d527d0a4ce78bcb548e3b4f514bf6ce2911a Mon Sep 17 00:00:00 2001 From: David Rohr Date: Tue, 1 Dec 2026 18:07:56 +0100 Subject: [PATCH 16/41] GPU: Modernize C++: Use unique_ptr instead of C pointers --- GPU/GPUTracking/Base/GPUReconstruction.cxx | 25 ++++++------- GPU/GPUTracking/Base/GPUReconstruction.h | 8 ++-- .../Base/GPUReconstructionProcessing.cxx | 16 +++----- .../Base/GPUReconstructionProcessing.h | 1 + .../cpudevice/GPUReconstructionCPUDevice.cxx | 37 +++++++++---------- .../cpudevice/GPUReconstructionCPUDevice.h | 1 + .../GPUReconstructionCPUDeviceGenRTC.cxx | 16 ++++---- .../GPUReconstructionCPUDeviceInternals.h | 13 ++++--- .../Base/cuda/GPUReconstructionCUDA.cu | 6 +-- .../Base/cuda/GPUReconstructionCUDA.h | 1 + .../Base/metal/GPUReconstructionMetal.h | 1 + .../Base/metal/GPUReconstructionMetal.mm | 6 +-- .../Base/opencl/GPUReconstructionOCL.cxx | 16 ++------ .../Base/opencl/GPUReconstructionOCL.h | 1 + 14 files changed, 68 insertions(+), 80 deletions(-) diff --git a/GPU/GPUTracking/Base/GPUReconstruction.cxx b/GPU/GPUTracking/Base/GPUReconstruction.cxx index c057b231992af..46cfc3e1cf730 100644 --- a/GPU/GPUTracking/Base/GPUReconstruction.cxx +++ b/GPU/GPUTracking/Base/GPUReconstruction.cxx @@ -110,13 +110,13 @@ GPUReconstruction::~GPUReconstruction() void GPUReconstruction::GetITSTraits(std::unique_ptr>* trackerTraits, std::unique_ptr>* vertexerTraits, std::unique_ptr>* timeFrame) { if (trackerTraits) { - trackerTraits->reset(new o2::its::TrackerTraits<7>); + *trackerTraits = std::make_unique>(); } if (vertexerTraits) { - vertexerTraits->reset(new o2::its::VertexerTraits<7>); + *vertexerTraits = std::make_unique>(); } if (timeFrame) { - timeFrame->reset(new o2::its::TimeFrame<7>); + *timeFrame = std::make_unique>(); } } @@ -365,7 +365,7 @@ int32_t GPUReconstruction::InitPhaseBeforeDevice() return 1; } if (mMaster == nullptr && GetProcessingSettings().doublePipeline) { - mPipelineContext.reset(new GPUReconstructionPipelineContext); + mPipelineContext = std::make_unique(); } if (mMaster && GetProcessingSettings().rtc.enable && (GetProcessingSettings().rtc.optConstexpr || GetProcessingSettings().rtc.optSpecialCode) && !GetProcessingSettings().rtctech.allowOptimizedSlaveReconstruction) { @@ -1192,26 +1192,23 @@ int32_t GPUReconstruction::EnqueuePipeline(bool terminate) { ClearAllocatedMemory(true); GPUReconstruction* rec = mMaster ? mMaster : this; - std::unique_ptr qu(new GPUReconstructionPipelineQueue); - GPUReconstructionPipelineQueue* q = qu.get(); - q->chain = terminate ? nullptr : mChains[0].get(); - q->op = terminate ? 1 : 0; - std::unique_lock lkdone(q->m); + GPUReconstructionPipelineQueue q{.op = terminate ? 1u : 0u, .chain = terminate ? nullptr : mChains[0].get()}; + std::unique_lock lkdone(q.m); { std::lock_guard lkpipe(rec->mPipelineContext->mutex); if (rec->mPipelineContext->terminate) { throw std::runtime_error("Must not enqueue work after termination request"); } - rec->mPipelineContext->pipelineQueue.push(q); + rec->mPipelineContext->pipelineQueue.push(&q); rec->mPipelineContext->terminate = terminate; rec->mPipelineContext->cond.notify_one(); } - q->c.wait(lkdone, [&q]() { return q->done; }); - if (terminate || (q->retVal && (q->retVal != 3 || !GetProcessingSettings().ignoreNonFatalGPUErrors))) { - return q->retVal; + q.c.wait(lkdone, [&q]() { return q.done; }); + if (terminate || (q.retVal && (q.retVal != 3 || !GetProcessingSettings().ignoreNonFatalGPUErrors))) { + return q.retVal; } int32_t retVal2 = mChains[0]->FinalizePipelinedProcessing(); - return retVal2 ? retVal2 : q->retVal; + return retVal2 ? retVal2 : q.retVal; } GPUChain* GPUReconstruction::GetNextChainInQueue() diff --git a/GPU/GPUTracking/Base/GPUReconstruction.h b/GPU/GPUTracking/Base/GPUReconstruction.h index 8a9e4989e3d57..4fbe0cd2a259d 100644 --- a/GPU/GPUTracking/Base/GPUReconstruction.h +++ b/GPU/GPUTracking/Base/GPUReconstruction.h @@ -140,7 +140,7 @@ class GPUReconstruction // Global steering functions template - T* AddChain(Args... args); + T* AddChain(Args&&... args); int32_t Init(); int32_t Finalize(); @@ -445,10 +445,10 @@ class GPUReconstruction }; template -inline T* GPUReconstruction::AddChain(Args... args) +inline T* GPUReconstruction::AddChain(Args&&... args) { - mChains.emplace_back(new T(this, args...)); - return (T*)mChains.back().get(); + std::unique_ptr chain(new T(this, std::forward(args)...)); // Not make_unique: the chain constructors are protected + return (T*)mChains.emplace_back(std::move(chain)).get(); } template diff --git a/GPU/GPUTracking/Base/GPUReconstructionProcessing.cxx b/GPU/GPUTracking/Base/GPUReconstructionProcessing.cxx index db6f6f8e70e9e..fbb211f794981 100644 --- a/GPU/GPUTracking/Base/GPUReconstructionProcessing.cxx +++ b/GPU/GPUTracking/Base/GPUReconstructionProcessing.cxx @@ -25,8 +25,10 @@ using namespace o2::gpu; GPUReconstructionProcessing::GPUReconstructionProcessing(const GPUSettingsDeviceBackend& cfg) : GPUReconstruction(cfg) { if (mMaster == nullptr) { - mParCPU = new GPUDefParameters(o2::gpu::internal::GPUDefParametersLoad()); - mParDevice = new GPUDefParameters(); + mParCPUOwner = std::make_unique(o2::gpu::internal::GPUDefParametersLoad()); + mParDeviceOwner = std::make_unique(); + mParCPU = mParCPUOwner.get(); + mParDevice = mParDeviceOwner.get(); } else { GPUReconstructionProcessing* master = dynamic_cast(mMaster); mParCPU = master->mParCPU; @@ -34,13 +36,7 @@ GPUReconstructionProcessing::GPUReconstructionProcessing(const GPUSettingsDevice } } -GPUReconstructionProcessing::~GPUReconstructionProcessing() -{ - if (mMaster == nullptr) { - delete mParCPU; - delete mParDevice; - } -} +GPUReconstructionProcessing::~GPUReconstructionProcessing() = default; int32_t GPUReconstructionProcessing::getNKernelHostThreads(bool splitCores) { @@ -107,7 +103,7 @@ GPUReconstructionProcessing::timerMeta* GPUReconstructionProcessing::insertTimer if (J >= 0) { name += std::to_string(J); } - mTimers[id].reset(new timerMeta{std::unique_ptr{new HighResTimer[num]}, std::move(name), num, type, 1u, step, (size_t)0}); + mTimers[id] = std::make_unique(std::make_unique(num), std::move(name), num, type, 1u, step, (size_t)0); } else { mTimers[id]->count++; } diff --git a/GPU/GPUTracking/Base/GPUReconstructionProcessing.h b/GPU/GPUTracking/Base/GPUReconstructionProcessing.h index 1c4c45f410410..9c2a437f68a2a 100644 --- a/GPU/GPUTracking/Base/GPUReconstructionProcessing.h +++ b/GPU/GPUTracking/Base/GPUReconstructionProcessing.h @@ -200,6 +200,7 @@ class GPUReconstructionProcessing : public GPUReconstruction template HighResTimer& getTimer(const char* name, int32_t num = -1); + std::unique_ptr mParCPUOwner, mParDeviceOwner; GPUDefParameters* mParCPU = nullptr; GPUDefParameters* mParDevice = nullptr; diff --git a/GPU/GPUTracking/Base/cpudevice/GPUReconstructionCPUDevice.cxx b/GPU/GPUTracking/Base/cpudevice/GPUReconstructionCPUDevice.cxx index d9cc7af3966a5..db2cd8eedb656 100644 --- a/GPU/GPUTracking/Base/cpudevice/GPUReconstructionCPUDevice.cxx +++ b/GPU/GPUTracking/Base/cpudevice/GPUReconstructionCPUDevice.cxx @@ -39,7 +39,8 @@ GPUReconstruction* GPUReconstruction_Create_CPUDEVICE(const GPUSettingsDeviceBac GPUReconstructionCPUDevice::GPUReconstructionCPUDevice(const GPUSettingsDeviceBackend& cfg) : GPUReconstructionProcessing::KernelInterface(cfg, sizeof(GPUReconstructionDeviceBase)) { if (mMaster == nullptr) { - mInternals = new GPUReconstructionCPUDeviceInternals; + mInternalsOwner = std::make_unique(); + mInternals = mInternalsOwner.get(); *mParDevice = *mParCPU; // We run the host-compiled CPU kernels on the "device", so the device parameters must be the CPU kernel parameters. Other values are possible only with RTC (genRTC), checked in InitDevice_Runtime for (auto& v : mParDevice->par_LB_maxThreads) { v = 1; @@ -51,9 +52,13 @@ GPUReconstructionCPUDevice::GPUReconstructionCPUDevice(const GPUSettingsDeviceBa GPUReconstructionCPUDevice::~GPUReconstructionCPUDevice() { Exit(); - if (mMaster == nullptr) { - delete mInternals; - } +} + +void GPUReconstructionCPUDeviceInternals::libraryDeleter::operator()(void* lib) const +{ +#ifndef _WIN32 + dlclose(lib); +#endif } int32_t GPUReconstructionCPUDevice::GPUChkErrInternal(const int64_t retval, const char* file, int32_t line) const @@ -95,16 +100,16 @@ int32_t GPUReconstructionCPUDevice::InitDevice_Runtime() // The arena does not own threads, it limits the concurrency of the command queues and kernels to the configured number of host threads mInternals->arena = std::make_unique(std::max(1, mMaxHostThreads)); - mInternals->deviceMemory = alignedDefaultBufferAllocator(mDeviceMemorySize); - mInternals->hostMemory = alignedDefaultBufferAllocator(mHostMemorySize); - mInternals->constantMemory = alignedDefaultBufferAllocator(sizeof(GPUConstantMem)); + mInternals->deviceMemory.reset(alignedDefaultBufferAllocator(mDeviceMemorySize)); + mInternals->hostMemory.reset(alignedDefaultBufferAllocator(mHostMemorySize)); + mInternals->constantMemory.reset(alignedDefaultBufferAllocator(sizeof(GPUConstantMem))); if ((mDeviceMemorySize && mInternals->deviceMemory == nullptr) || (mHostMemorySize && mInternals->hostMemory == nullptr) || mInternals->constantMemory == nullptr) { GPUError("CPUDevice memory allocation error (trying %ld bytes device / %ld bytes host memory)", (int64_t)mDeviceMemorySize, (int64_t)mHostMemorySize); return 1; } - mDeviceMemoryBase = mDeviceMemoryHostView = mInternals->deviceMemory; - mHostMemoryBase = mInternals->hostMemory; - mDeviceConstantMem = (GPUConstantMem*)mInternals->constantMemory; + mDeviceMemoryBase = mDeviceMemoryHostView = mInternals->deviceMemory.get(); + mHostMemoryBase = mInternals->hostMemory.get(); + mDeviceConstantMem = (GPUConstantMem*)mInternals->constantMemory.get(); if (GetProcessingSettings().debugLevel >= 1) { GPUInfo("Memory ptrs: Device (%ld bytes): %p - Host (%ld bytes): %p", (int64_t)mDeviceMemorySize, mDeviceMemoryBase, (int64_t)mHostMemorySize, mHostMemoryBase); memset(mHostMemoryBase, 0xDD, mHostMemorySize); @@ -145,18 +150,12 @@ int32_t GPUReconstructionCPUDevice::ExitDevice_Runtime() mEventStorage.clear(); if (mMaster == nullptr) { -#ifndef _WIN32 - for (auto* lib : mInternals->rtcLibraries) { - dlclose(lib); - } -#endif mInternals->rtcLibraries.clear(); mInternals->rtcKernels.clear(); mInternals->arena.reset(); - alignedDefaultBufferDeleter()(mInternals->deviceMemory); - alignedDefaultBufferDeleter()(mInternals->hostMemory); - alignedDefaultBufferDeleter()(mInternals->constantMemory); - mInternals->deviceMemory = mInternals->hostMemory = mInternals->constantMemory = nullptr; + mInternals->deviceMemory.reset(); + mInternals->hostMemory.reset(); + mInternals->constantMemory.reset(); GPUInfo("CPUDevice Uninitialized"); } mDeviceMemoryBase = mDeviceMemoryHostView = nullptr; diff --git a/GPU/GPUTracking/Base/cpudevice/GPUReconstructionCPUDevice.h b/GPU/GPUTracking/Base/cpudevice/GPUReconstructionCPUDevice.h index 745a01d7e377f..317209f76d175 100644 --- a/GPU/GPUTracking/Base/cpudevice/GPUReconstructionCPUDevice.h +++ b/GPU/GPUTracking/Base/cpudevice/GPUReconstructionCPUDevice.h @@ -64,6 +64,7 @@ class GPUReconstructionCPUDevice : public GPUReconstructionProcessing::KernelInt void ReleaseEvent(deviceEvent ev) override {} void RecordMarker(deviceEvent* ev, int32_t stream) override; + std::unique_ptr mInternalsOwner; GPUReconstructionCPUDeviceInternals* mInternals = nullptr; private: diff --git a/GPU/GPUTracking/Base/cpudevice/GPUReconstructionCPUDeviceGenRTC.cxx b/GPU/GPUTracking/Base/cpudevice/GPUReconstructionCPUDeviceGenRTC.cxx index 94ba0dadfa78f..08dd59e6565aa 100644 --- a/GPU/GPUTracking/Base/cpudevice/GPUReconstructionCPUDeviceGenRTC.cxx +++ b/GPU/GPUTracking/Base/cpudevice/GPUReconstructionCPUDeviceGenRTC.cxx @@ -123,14 +123,14 @@ void GPUReconstructionCPUDevice::genAndLoadRTC() const bool perKernel = GetProcessingSettings().rtc.compilePerKernel; mInternals->rtcKernels.resize(GetNKernels()); uint32_t j = 0; -#define GPUCA_KRNL(x_class, ...) \ - if (GetKernelNum() != j) { \ - GPUFatal("kernel numbers out of sync"); \ - } \ - mInternals->rtcKernels[j] = dlsym(mInternals->rtcLibraries[perKernel ? j : 0], GPUCA_M_STR(GPUCA_M_CAT(krnl_, GPUCA_M_KRNL_NAME(x_class)))); \ - if (mInternals->rtcKernels[j] == nullptr && !kernelWithoutRTC(GetKernelName(j))) { \ - GPUFatal("Error loading RTC kernel %s", GPUCA_M_STR(GPUCA_M_CAT(krnl_, GPUCA_M_KRNL_NAME(x_class)))); \ - } \ +#define GPUCA_KRNL(x_class, ...) \ + if (GetKernelNum() != j) { \ + GPUFatal("kernel numbers out of sync"); \ + } \ + mInternals->rtcKernels[j] = dlsym(mInternals->rtcLibraries[perKernel ? j : 0].get(), GPUCA_M_STR(GPUCA_M_CAT(krnl_, GPUCA_M_KRNL_NAME(x_class)))); \ + if (mInternals->rtcKernels[j] == nullptr && !kernelWithoutRTC(GetKernelName(j))) { \ + GPUFatal("Error loading RTC kernel %s", GPUCA_M_STR(GPUCA_M_CAT(krnl_, GPUCA_M_KRNL_NAME(x_class)))); \ + } \ j++; #include "GPUReconstructionKernelList.h" #undef GPUCA_KRNL diff --git a/GPU/GPUTracking/Base/cpudevice/GPUReconstructionCPUDeviceInternals.h b/GPU/GPUTracking/Base/cpudevice/GPUReconstructionCPUDeviceInternals.h index 1499fa98847a3..b2696243081c2 100644 --- a/GPU/GPUTracking/Base/cpudevice/GPUReconstructionCPUDeviceInternals.h +++ b/GPU/GPUTracking/Base/cpudevice/GPUReconstructionCPUDeviceInternals.h @@ -70,12 +70,15 @@ struct GPUReconstructionCPUDeviceInternals { std::array queues; std::atomic error{0}; // Set if a command in a command queue has failed - char* deviceMemory = nullptr; // "Device" memory, a separate host memory region - char* hostMemory = nullptr; // Host memory, corresponds to page-locked host memory of real GPUs - char* constantMemory = nullptr; // "Device" constant memory, holding the device copy of GPUConstantMem + std::unique_ptr deviceMemory; // "Device" memory, a separate host memory region + std::unique_ptr hostMemory; // Host memory, corresponds to page-locked host memory of real GPUs + std::unique_ptr constantMemory; // "Device" constant memory, holding the device copy of GPUConstantMem - std::vector rtcLibraries; // dlopen handles of RTC-compiled kernel libraries - std::vector rtcKernels; // RTC kernel entry points, indexed by kernel number + struct libraryDeleter { + void operator()(void* lib) const; + }; + std::vector> rtcLibraries; // dlopen handles of RTC-compiled kernel libraries + std::vector rtcKernels; // RTC kernel entry points, indexed by kernel number void enqueue(int32_t stream, GPUReconstructionCPUDeviceTask&& task); void startQueue(int32_t stream); diff --git a/GPU/GPUTracking/Base/cuda/GPUReconstructionCUDA.cu b/GPU/GPUTracking/Base/cuda/GPUReconstructionCUDA.cu index 0d50c1a02093e..0aa72b54e0c28 100644 --- a/GPU/GPUTracking/Base/cuda/GPUReconstructionCUDA.cu +++ b/GPU/GPUTracking/Base/cuda/GPUReconstructionCUDA.cu @@ -62,7 +62,8 @@ __global__ void dummyInitKernel(void*) {} GPUReconstructionCUDA::GPUReconstructionCUDA(const GPUSettingsDeviceBackend& cfg) : GPUReconstructionProcessing::KernelInterface(cfg, sizeof(GPUReconstructionDeviceBase)) { if (mMaster == nullptr) { - mInternals = new GPUReconstructionCUDAInternals; + mInternalsOwner = std::make_unique(); + mInternals = mInternalsOwner.get(); *mParDevice = o2::gpu::internal::GPUDefParametersLoad(); } mDeviceBackendSettings->deviceType = DeviceType::CUDA; @@ -78,9 +79,6 @@ GPUReconstructionCUDA::GPUReconstructionCUDA(const GPUSettingsDeviceBackend& cfg GPUReconstructionCUDA::~GPUReconstructionCUDA() { Exit(); // Make sure we destroy everything (in particular the ITS tracker) before we exit CUDA - if (mMaster == nullptr) { - delete mInternals; - } } static_assert(sizeof(cudaError_t) <= sizeof(int64_t) && cudaSuccess == 0); diff --git a/GPU/GPUTracking/Base/cuda/GPUReconstructionCUDA.h b/GPU/GPUTracking/Base/cuda/GPUReconstructionCUDA.h index 3acf2d9c58af5..3525a257cb090 100644 --- a/GPU/GPUTracking/Base/cuda/GPUReconstructionCUDA.h +++ b/GPU/GPUTracking/Base/cuda/GPUReconstructionCUDA.h @@ -56,6 +56,7 @@ class GPUReconstructionCUDA : public GPUReconstructionProcessing::KernelInterfac friend GPUh() void GPUCommonAlgorithm::sortOnDevice(auto* rec, int32_t stream, T* begin, size_t N, const S& comp); protected: + std::unique_ptr mInternalsOwner; GPUReconstructionCUDAInternals* mInternals; int32_t InitDevice_Runtime() override; diff --git a/GPU/GPUTracking/Base/metal/GPUReconstructionMetal.h b/GPU/GPUTracking/Base/metal/GPUReconstructionMetal.h index 247ae6657c01e..0306539eb804d 100644 --- a/GPU/GPUTracking/Base/metal/GPUReconstructionMetal.h +++ b/GPU/GPUTracking/Base/metal/GPUReconstructionMetal.h @@ -54,6 +54,7 @@ class GPUReconstructionMetal : public GPUReconstructionProcessing::KernelInterfa template int32_t AddKernel(); + std::unique_ptr mInternalsOwner; GPUReconstructionMetalInternals* mInternals; template diff --git a/GPU/GPUTracking/Base/metal/GPUReconstructionMetal.mm b/GPU/GPUTracking/Base/metal/GPUReconstructionMetal.mm index eaa053585e06a..217616a71c308 100644 --- a/GPU/GPUTracking/Base/metal/GPUReconstructionMetal.mm +++ b/GPU/GPUTracking/Base/metal/GPUReconstructionMetal.mm @@ -86,7 +86,8 @@ uint32_t metalGPUCoreCount() GPUReconstructionMetal::GPUReconstructionMetal(const GPUSettingsDeviceBackend& cfg) : GPUReconstructionProcessing::KernelInterface(cfg, sizeof(GPUReconstructionDeviceBase)) { if (mMaster == nullptr) { - mInternals = new GPUReconstructionMetalInternals; + mInternalsOwner = std::make_unique(); + mInternals = mInternalsOwner.get(); *mParDevice = o2::gpu::internal::GPUDefParametersLoad(); } mDeviceBackendSettings->deviceType = DeviceType::METAL; @@ -95,9 +96,6 @@ uint32_t metalGPUCoreCount() GPUReconstructionMetal::~GPUReconstructionMetal() { Exit(); // Make sure we destroy everything (in particular the ITS tracker) before we exit - if (mMaster == nullptr) { - delete mInternals; - } } int32_t GPUReconstructionMetal::InitDevice_Runtime() diff --git a/GPU/GPUTracking/Base/opencl/GPUReconstructionOCL.cxx b/GPU/GPUTracking/Base/opencl/GPUReconstructionOCL.cxx index 2c18b8dd08129..95d6b680a0a8b 100644 --- a/GPU/GPUTracking/Base/opencl/GPUReconstructionOCL.cxx +++ b/GPU/GPUTracking/Base/opencl/GPUReconstructionOCL.cxx @@ -38,7 +38,8 @@ GPUReconstruction* GPUReconstruction_Create_OCL(const GPUSettingsDeviceBackend& GPUReconstructionOCL::GPUReconstructionOCL(const GPUSettingsDeviceBackend& cfg) : GPUReconstructionProcessing::KernelInterface(cfg, sizeof(GPUReconstructionDeviceBase)) { if (mMaster == nullptr) { - mInternals = new GPUReconstructionOCLInternals; + mInternalsOwner = std::make_unique(); + mInternals = mInternalsOwner.get(); *mParDevice = o2::gpu::internal::GPUDefParametersLoad(); } mDeviceBackendSettings->deviceType = DeviceType::OCL; @@ -47,9 +48,6 @@ GPUReconstructionOCL::GPUReconstructionOCL(const GPUSettingsDeviceBackend& cfg) GPUReconstructionOCL::~GPUReconstructionOCL() { Exit(); // Make sure we destroy everything (in particular the ITS tracker) before we exit - if (mMaster == nullptr) { - delete mInternals; - } } static_assert(sizeof(cl_int) <= sizeof(int64_t) && CL_SUCCESS == 0); @@ -85,9 +83,8 @@ int32_t GPUReconstructionOCL::InitDevice_Runtime() } // Query platforms and devices - std::unique_ptr platforms; - platforms.reset(new cl_platform_id[num_platforms]); - if (GPUChkErrI(clGetPlatformIDs(num_platforms, platforms.get(), nullptr))) { + std::vector platforms(num_platforms); + if (GPUChkErrI(clGetPlatformIDs(num_platforms, platforms.data(), nullptr))) { GPUErrorReturn("Error getting OpenCL Platforms"); } @@ -390,11 +387,6 @@ int32_t GPUReconstructionOCL::InitDevice_Runtime() mInternals = master->mInternals; } - for (uint32_t i = 0; i < mEvents.size(); i++) { - cl_event* events = (cl_event*)mEvents[i].data(); - new (events) cl_event[mEvents[i].size()]; - } - return (0); } diff --git a/GPU/GPUTracking/Base/opencl/GPUReconstructionOCL.h b/GPU/GPUTracking/Base/opencl/GPUReconstructionOCL.h index 919526e357e81..d75dc794f9a05 100644 --- a/GPU/GPUTracking/Base/opencl/GPUReconstructionOCL.h +++ b/GPU/GPUTracking/Base/opencl/GPUReconstructionOCL.h @@ -59,6 +59,7 @@ class GPUReconstructionOCL : public GPUReconstructionProcessing::KernelInterface template int32_t AddKernel(); + std::unique_ptr mInternalsOwner; GPUReconstructionOCLInternals* mInternals; float mOclVersion; bool mOclPoCL = false; From 8f702f045883e203deccc907652ed8ae5730c6a6 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Tue, 1 Dec 2026 18:09:41 +0100 Subject: [PATCH 17/41] ITS: Fix double delete --- Detectors/ITSMFT/ITS/workflow/include/ITSWorkflow/TrackerSpec.h | 2 +- Detectors/ITSMFT/ITS/workflow/src/TrackerSpec.cxx | 2 +- .../Upgrades/ITS3/workflow/include/ITS3Workflow/TrackerSpec.h | 2 +- Detectors/Upgrades/ITS3/workflow/src/TrackerSpec.cxx | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Detectors/ITSMFT/ITS/workflow/include/ITSWorkflow/TrackerSpec.h b/Detectors/ITSMFT/ITS/workflow/include/ITSWorkflow/TrackerSpec.h index 22a8092ec69c5..4ff77a3e650de 100644 --- a/Detectors/ITSMFT/ITS/workflow/include/ITSWorkflow/TrackerSpec.h +++ b/Detectors/ITSMFT/ITS/workflow/include/ITSWorkflow/TrackerSpec.h @@ -59,7 +59,7 @@ class TrackerDPL : public framework::Task void updateTimeDependentParams(framework::ProcessingContext& pc); void storeConfigs(framework::ProcessingContext& pc); std::unique_ptr mRecChain = nullptr; - std::unique_ptr mChainITS = nullptr; + o2::gpu::GPUChainITS* mChainITS = nullptr; // Owned by mRecChain std::shared_ptr mGGCCDBRequest; ITSTrackingInterface mITSTrackingInterface; TStopwatch mTimer; diff --git a/Detectors/ITSMFT/ITS/workflow/src/TrackerSpec.cxx b/Detectors/ITSMFT/ITS/workflow/src/TrackerSpec.cxx index cb53dae1ed905..c429d782759af 100644 --- a/Detectors/ITSMFT/ITS/workflow/src/TrackerSpec.cxx +++ b/Detectors/ITSMFT/ITS/workflow/src/TrackerSpec.cxx @@ -44,7 +44,7 @@ void TrackerDPL::init(InitContext& ic) mTimer.Stop(); mTimer.Reset(); o2::base::GRPGeomHelper::instance().setRequest(mGGCCDBRequest); - mChainITS.reset(mRecChain->AddChain()); + mChainITS = mRecChain->AddChain(); mITSTrackingInterface.setTraitsFromProvider(mChainITS->GetITSVertexerTraits(), mChainITS->GetITSTrackerTraits(), mChainITS->GetITSTimeframe()); diff --git a/Detectors/Upgrades/ITS3/workflow/include/ITS3Workflow/TrackerSpec.h b/Detectors/Upgrades/ITS3/workflow/include/ITS3Workflow/TrackerSpec.h index 4b8c286f6c9fb..b15942c7c0dee 100644 --- a/Detectors/Upgrades/ITS3/workflow/include/ITS3Workflow/TrackerSpec.h +++ b/Detectors/Upgrades/ITS3/workflow/include/ITS3Workflow/TrackerSpec.h @@ -62,7 +62,7 @@ class TrackerDPL : public framework::Task private: void updateTimeDependentParams(framework::ProcessingContext& pc); std::unique_ptr mRecChain = nullptr; - std::unique_ptr mChainITS = nullptr; + o2::gpu::GPUChainITS* mChainITS = nullptr; // Owned by mRecChain std::shared_ptr mGGCCDBRequest; ITS3TrackingInterface mITS3TrackingInterface; TStopwatch mTimer; diff --git a/Detectors/Upgrades/ITS3/workflow/src/TrackerSpec.cxx b/Detectors/Upgrades/ITS3/workflow/src/TrackerSpec.cxx index 7c1a87a778c8d..e667b8b007526 100644 --- a/Detectors/Upgrades/ITS3/workflow/src/TrackerSpec.cxx +++ b/Detectors/Upgrades/ITS3/workflow/src/TrackerSpec.cxx @@ -57,7 +57,7 @@ void TrackerDPL::init(InitContext& ic) mTimer.Stop(); mTimer.Reset(); o2::base::GRPGeomHelper::instance().setRequest(mGGCCDBRequest); - mChainITS.reset(mRecChain->AddChain()); + mChainITS = mRecChain->AddChain(); mITS3TrackingInterface.setTraitsFromProvider(mChainITS->GetITSVertexerTraits(), mChainITS->GetITSTrackerTraits(), mChainITS->GetITSTimeframe()); From e94b2f4f33ab8dca0808bae21dd7a6726e1b72c6 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Tue, 1 Dec 2026 18:20:32 +0100 Subject: [PATCH 18/41] GPU: Modernize C++: Replace template specialization with if constexpr --- GPU/GPUTracking/Base/GPUConstantMem.h | 22 +- .../Base/GPUReconstructionConvert.cxx | 6 +- .../GPUTPCCompressionKernels.cxx | 130 +++------ .../GPUTPCCompressionKernels.h | 3 + .../Global/GPUChainTrackingTRD.cxx | 8 +- GPU/GPUTracking/Merger/GPUTPCGMMerger.cxx | 21 +- .../Merger/GPUTPCGMSectorTrack.cxx | 167 ++++++------ GPU/GPUTracking/Refit/GPUTrackingRefit.cxx | 229 +++++++--------- GPU/GPUTracking/Refit/GPUTrackingRefit.h | 8 +- GPU/GPUTracking/TRDTracking/GPUTRDTracker.cxx | 14 +- .../display/render/GPUDisplayDraw.cxx | 18 +- GPU/GPUTracking/qa/GPUQA.cxx | 31 +-- GPU/GPUTracking/utils/qconfig.cxx | 250 ++++++------------ GPU/GPUTracking/utils/qconfig_helpers.h | 38 +-- GPU/GPUbenchmark/cuda/Kernels.cu | 65 ++--- GPU/Utils/MultivariatePolynomialHelper.cxx | 4 +- GPU/Utils/Spline1DSpec.h | 8 +- 17 files changed, 400 insertions(+), 622 deletions(-) diff --git a/GPU/GPUTracking/Base/GPUConstantMem.h b/GPU/GPUTracking/Base/GPUConstantMem.h index 061f482581805..0c1441672e6f7 100644 --- a/GPU/GPUTracking/Base/GPUConstantMem.h +++ b/GPU/GPUTracking/Base/GPUConstantMem.h @@ -60,20 +60,18 @@ struct GPUConstantMem { GPUTPCNNClusterizer tpcNNClusterer[GPUTPCGeometry::NSECTORS]; #endif template - GPUd() auto& getTRDTracker(); + GPUdi() auto& getTRDTracker() + { + if constexpr (I == 0) { + return trdTrackerGPU; + } else if constexpr (I == 1) { + return trdTrackerO2; + } else { + static_assert(I == 0 || I == 1, "Invalid TRD tracker version"); + } + } }; -template <> -GPUdi() auto& GPUConstantMem::getTRDTracker<0>() -{ - return trdTrackerGPU; -} -template <> -GPUdi() auto& GPUConstantMem::getTRDTracker<1>() -{ - return trdTrackerO2; -} - union GPUConstantMemCopyable { #if !defined(__OPENCL__) || defined(__OPENCL_HOST__) GPUh() GPUConstantMemCopyable() {} // NOLINT: We want an empty constructor, not a default one diff --git a/GPU/GPUTracking/Base/GPUReconstructionConvert.cxx b/GPU/GPUTracking/Base/GPUReconstructionConvert.cxx index 37528664f3eac..d4fc30dccef17 100644 --- a/GPU/GPUTracking/Base/GPUReconstructionConvert.cxx +++ b/GPU/GPUTracking/Base/GPUReconstructionConvert.cxx @@ -551,7 +551,7 @@ bool zsEncoderImprovedLinkBased::checkInput(std::vector& tmpBuff if (!finishPage) { uint32_t sizeChk = (uint32_t)(pagePtr - reinterpret_cast(page)); sizeChk += sizeof(o2::tpc::zerosupp_link_based::CommonHeader); - if (TPCZSHDRV2::TIGHTLY_PACKED_V3) { + if constexpr (TPCZSHDRV2::TIGHTLY_PACKED_V3) { sizeChk += (nSamples * TPCZSHDRV2::TPC_ZS_NBITS_V34 + 127) / 128 * 16; } else { sizeChk += (nSamples + 2 * TPCZSHDRV2::SAMPLESPER64BIT - 1) / (2 * TPCZSHDRV2::SAMPLESPER64BIT) * 16; @@ -575,7 +575,7 @@ uint32_t zsEncoderImprovedLinkBased::encodeSequence(std::vector& tbHdr->fecInPartition = link; hdr->nTimeBinSpan = tmpBuffer[k].getTimeStamp() - firstTimebinInPage; hdr->nTimebinHeaders++; - if (TPCZSHDRV2::TIGHTLY_PACKED_V3) { + if constexpr (TPCZSHDRV2::TIGHTLY_PACKED_V3) { tbHdr->numWordsPayload = (nSamples * TPCZSHDRV2::TPC_ZS_NBITS_V34 + 127) / 128; // tightly packed ADC samples uint32_t tmp = 0; uint32_t tmpIn = nSamples; @@ -656,7 +656,7 @@ void zsEncoderImprovedLinkBased::decodePage(std::vector& outputB const auto& bitmask = tbHdr->getChannelBits(); int32_t nADC = bitmask.count(); std::vector decBuffer(nADC); - if (TPCZSHDRV2::TIGHTLY_PACKED_V3) { + if constexpr (TPCZSHDRV2::TIGHTLY_PACKED_V3) { uint32_t byte = 0, bits = 0, posXbits = 0; while (posXbits < nADC) { byte |= *(adcData++) << bits; diff --git a/GPU/GPUTracking/DataCompression/GPUTPCCompressionKernels.cxx b/GPU/GPUTracking/DataCompression/GPUTPCCompressionKernels.cxx index b51825edc5a0e..419465b502e13 100644 --- a/GPU/GPUTracking/DataCompression/GPUTPCCompressionKernels.cxx +++ b/GPU/GPUTracking/DataCompression/GPUTPCCompressionKernels.cxx @@ -150,46 +150,25 @@ GPUdii() void GPUTPCCompressionKernels::Thread -GPUd() bool GPUTPCCompressionKernels::GPUTPCCompressionKernels_Compare::operator()(uint32_t a, uint32_t b) const +template +GPUd() bool GPUTPCCompressionKernels::GPUTPCCompressionKernels_Compare::operator()(uint32_t a, uint32_t b) const { - return mClsPtr[a].getTimePacked() < mClsPtr[b].getTimePacked(); -} - -template <> -GPUd() bool GPUTPCCompressionKernels::GPUTPCCompressionKernels_Compare::operator()(uint32_t a, uint32_t b) const -{ - return mClsPtr[a].padPacked < mClsPtr[b].padPacked; -} - -template <> -GPUd() bool GPUTPCCompressionKernels::GPUTPCCompressionKernels_Compare::operator()(uint32_t a, uint32_t b) const -{ - if (mClsPtr[a].getTimePacked() >> 3 == mClsPtr[b].getTimePacked() >> 3) { - return mClsPtr[a].padPacked < mClsPtr[b].padPacked; - } - return mClsPtr[a].getTimePacked() < mClsPtr[b].getTimePacked(); -} - -template <> -GPUd() bool GPUTPCCompressionKernels::GPUTPCCompressionKernels_Compare::operator()(uint32_t a, uint32_t b) const -{ - if (mClsPtr[a].padPacked >> 3 == mClsPtr[b].padPacked >> 3) { + if constexpr (I == GPUSettings::SortTime) { return mClsPtr[a].getTimePacked() < mClsPtr[b].getTimePacked(); - } - return mClsPtr[a].padPacked < mClsPtr[b].padPacked; -} - -template <> // Deterministic comparison -GPUd() bool GPUTPCCompressionKernels::GPUTPCCompressionKernels_Compare<4>::operator()(uint32_t a, uint32_t b) const -{ - if (mClsPtr[a].getTimePacked() != mClsPtr[b].getTimePacked()) { + } else if constexpr (I == GPUSettings::SortPad) { + return mClsPtr[a].padPacked < mClsPtr[b].padPacked; + } else if constexpr (I == GPUSettings::SortZTimePad) { + if (mClsPtr[a].getTimePacked() >> 3 == mClsPtr[b].getTimePacked() >> 3) { + return mClsPtr[a].padPacked < mClsPtr[b].padPacked; + } return mClsPtr[a].getTimePacked() < mClsPtr[b].getTimePacked(); - } - if (mClsPtr[a].padPacked != mClsPtr[b].padPacked) { + } else { + static_assert(I == GPUSettings::SortZPadTime); + if (mClsPtr[a].padPacked >> 3 == mClsPtr[b].padPacked >> 3) { + return mClsPtr[a].getTimePacked() < mClsPtr[b].getTimePacked(); + } return mClsPtr[a].padPacked < mClsPtr[b].padPacked; } - return mClsPtr[a].qTotPacked < mClsPtr[b].qTotPacked; } GPUd() bool GPUTPCCompression::rejectCluster(int32_t idx, const GPUParam& GPUrestrict() param, const GPUTrackingInOutPointers& GPUrestrict() ioPtrs) const @@ -339,22 +318,17 @@ GPUdii() void GPUTPCCompressionKernels::Thread -GPUdi() GPUTPCCompressionGatherKernels::Vec32* GPUTPCCompressionGatherKernels::GPUSharedMemory::getBuffer(int32_t iWarp) -{ - return buf32[iWarp]; -} - -template <> -GPUdi() GPUTPCCompressionGatherKernels::Vec64* GPUTPCCompressionGatherKernels::GPUSharedMemory::getBuffer(int32_t iWarp) -{ - return buf64[iWarp]; -} - -template <> -GPUdi() GPUTPCCompressionGatherKernels::Vec128* GPUTPCCompressionGatherKernels::GPUSharedMemory::getBuffer(int32_t iWarp) +template +GPUdi() V* GPUTPCCompressionGatherKernels::GPUSharedMemory::getBuffer(int32_t iWarp) { - return buf128[iWarp]; + if constexpr (std::is_same_v) { + return buf32[iWarp]; + } else if constexpr (std::is_same_v) { + return buf64[iWarp]; + } else { + static_assert(std::is_same_v); + return buf128[iWarp]; + } } template @@ -368,58 +342,26 @@ GPUdi() bool GPUTPCCompressionGatherKernels::isAlignedTo(const S* ptr) } } -template <> -GPUdi() void GPUTPCCompressionGatherKernels::compressorMemcpy(uint8_t* GPUrestrict() dst, const uint8_t* GPUrestrict() src, uint32_t size, int32_t nThreads, int32_t iThread) +template +GPUdi() void GPUTPCCompressionGatherKernels::compressorMemcpyVec(T* GPUrestrict() dst, const T* GPUrestrict() src, uint32_t size, int32_t nThreads, int32_t iThread) { - constexpr const int32_t vec128Elems = CpyVector::Size; - constexpr const int32_t vec64Elems = CpyVector::Size; - constexpr const int32_t vec32Elems = CpyVector::Size; - constexpr const int32_t vec16Elems = CpyVector::Size; - - if (size >= uint32_t(nThreads * vec128Elems)) { - compressorMemcpyVectorised(dst, src, size, nThreads, iThread); - } else if (size >= uint32_t(nThreads * vec64Elems)) { - compressorMemcpyVectorised(dst, src, size, nThreads, iThread); - } else if (size >= uint32_t(nThreads * vec32Elems)) { - compressorMemcpyVectorised(dst, src, size, nThreads, iThread); - } else if (size >= uint32_t(nThreads * vec16Elems)) { - compressorMemcpyVectorised(dst, src, size, nThreads, iThread); - } else { - compressorMemcpyBasic(dst, src, size, nThreads, iThread); + if constexpr (sizeof(V) > sizeof(T)) { + if (size >= uint32_t(nThreads * CpyVector::Size)) { + compressorMemcpyVectorised(dst, src, size, nThreads, iThread); + return; + } } -} - -template <> -GPUdi() void GPUTPCCompressionGatherKernels::compressorMemcpy(uint16_t* GPUrestrict() dst, const uint16_t* GPUrestrict() src, uint32_t size, int32_t nThreads, int32_t iThread) -{ - constexpr const int32_t vec128Elems = CpyVector::Size; - constexpr const int32_t vec64Elems = CpyVector::Size; - constexpr const int32_t vec32Elems = CpyVector::Size; - - if (size >= uint32_t(nThreads * vec128Elems)) { - compressorMemcpyVectorised(dst, src, size, nThreads, iThread); - } else if (size >= uint32_t(nThreads * vec64Elems)) { - compressorMemcpyVectorised(dst, src, size, nThreads, iThread); - } else if (size >= uint32_t(nThreads * vec32Elems)) { - compressorMemcpyVectorised(dst, src, size, nThreads, iThread); + if constexpr (sizeof...(Vs) > 0) { + compressorMemcpyVec(dst, src, size, nThreads, iThread); } else { compressorMemcpyBasic(dst, src, size, nThreads, iThread); } } -template <> -GPUdi() void GPUTPCCompressionGatherKernels::compressorMemcpy(uint32_t* GPUrestrict() dst, const uint32_t* GPUrestrict() src, uint32_t size, int32_t nThreads, int32_t iThread) +template +GPUdi() void GPUTPCCompressionGatherKernels::compressorMemcpy(GPUgeneric() T* GPUrestrict() dst, GPUgeneric() const T* GPUrestrict() src, uint32_t size, int32_t nThreads, int32_t iThread) { - constexpr const int32_t vec128Elems = CpyVector::Size; - constexpr const int32_t vec64Elems = CpyVector::Size; - - if (size >= uint32_t(nThreads * vec128Elems)) { - compressorMemcpyVectorised(dst, src, size, nThreads, iThread); - } else if (size >= uint32_t(nThreads * vec64Elems)) { - compressorMemcpyVectorised(dst, src, size, nThreads, iThread); - } else { - compressorMemcpyBasic(dst, src, size, nThreads, iThread); - } + compressorMemcpyVec(dst, src, size, nThreads, iThread); } template diff --git a/GPU/GPUTracking/DataCompression/GPUTPCCompressionKernels.h b/GPU/GPUTracking/DataCompression/GPUTPCCompressionKernels.h index ac8fc72376ecf..8ec8e22bd22e8 100644 --- a/GPU/GPUTracking/DataCompression/GPUTPCCompressionKernels.h +++ b/GPU/GPUTracking/DataCompression/GPUTPCCompressionKernels.h @@ -106,6 +106,9 @@ class GPUTPCCompressionGatherKernels : public GPUKernelTemplate template GPUdi() static void compressorMemcpy(GPUgeneric() T* dst, GPUgeneric() const T* src, uint32_t size, int32_t nThreads, int32_t iThread); + template + GPUdi() static void compressorMemcpyVec(T* dst, const T* src, uint32_t size, int32_t nThreads, int32_t iThread); + template GPUdi() static void compressorMemcpyVectorised(Scalar* dst, const Scalar* src, uint32_t size, int32_t nThreads, int32_t iThread); diff --git a/GPU/GPUTracking/Global/GPUChainTrackingTRD.cxx b/GPU/GPUTracking/Global/GPUChainTrackingTRD.cxx index 038b98066a848..f4381bc48ddc0 100644 --- a/GPU/GPUTracking/Global/GPUChainTrackingTRD.cxx +++ b/GPU/GPUTracking/Global/GPUChainTrackingTRD.cxx @@ -87,7 +87,7 @@ int32_t GPUChainTracking::RunTRDTrackingInternal() return 1; } } - } else { + } else if constexpr (I == GPUTRDTrackerKernels::o2Version) { for (uint32_t i = 0; i < mIOPtrs.nOutputTracksTPCO2; i++) { const auto& trk = mIOPtrs.outputTracksTPCO2[i]; @@ -116,6 +116,8 @@ int32_t GPUChainTracking::RunTRDTrackingInternal() return 1; } } + } else { + static_assert(I == GPUTRDTrackerKernels::gpuVersion || I == GPUTRDTrackerKernels::o2Version, "Invalid TRD tracker version"); } DoTRDGPUTracking(); @@ -124,9 +126,11 @@ int32_t GPUChainTracking::RunTRDTrackingInternal() if constexpr (I == GPUTRDTrackerKernels::gpuVersion) { mIOPtrs.trdTracks = Tracker.Tracks(); mIOPtrs.trdTracksO2 = nullptr; - } else { + } else if constexpr (I == GPUTRDTrackerKernels::o2Version) { mIOPtrs.trdTracks = nullptr; mIOPtrs.trdTracksO2 = Tracker.Tracks(); + } else { + static_assert(I == GPUTRDTrackerKernels::gpuVersion || I == GPUTRDTrackerKernels::o2Version, "Invalid TRD tracker version"); } mRec->PopNonPersistentMemory(RecoStep::TRDTracking, qStr2Tag("TRDTRACK")); diff --git a/GPU/GPUTracking/Merger/GPUTPCGMMerger.cxx b/GPU/GPUTracking/Merger/GPUTPCGMMerger.cxx index e51002396c8e6..ad100256cd887 100644 --- a/GPU/GPUTracking/Merger/GPUTPCGMMerger.cxx +++ b/GPU/GPUTracking/Merger/GPUTPCGMMerger.cxx @@ -176,12 +176,13 @@ GPUTPCGMMerger::GPUTPCGMMerger() template inline const auto* resolveMCLabels(const o2::dataformats::ConstMCTruthContainerView* a, const AliHLTTPCClusterMCLabel* b) { - return a; -} -template <> -inline const auto* resolveMCLabels(const o2::dataformats::ConstMCTruthContainerView* a, const AliHLTTPCClusterMCLabel* b) -{ - return b; + if constexpr (std::is_same_v) { + return b; + } else if constexpr (std::is_same_v>) { + return a; + } else { + static_assert(sizeof(T) == 0, "Invalid template"); + } } template @@ -192,8 +193,10 @@ int64_t GPUTPCGMMerger::GetTrackLabelA(const S& trk) const if constexpr (std::is_same_v) { sectorTrack = &mSectorTrackInfos[trk.TrackID()]; nClusters = sectorTrack->OrigTrack(this)->NHits(); - } else { + } else if constexpr (std::is_same_v) { nClusters = trk.NClusters(); + } else { + static_assert(sizeof(S) == 0, "Invalid template"); } auto acc = GPUTPCTrkLbl(resolveMCLabels(GetConstantMem()->ioPtrs.clustersNative ? GetConstantMem()->ioPtrs.clustersNative->clustersMCTruth : nullptr, GetConstantMem()->ioPtrs.mcLabelsTPC), 0.5f); for (int32_t i = 0; i < nClusters; i++) { @@ -202,8 +205,10 @@ int64_t GPUTPCGMMerger::GetTrackLabelA(const S& trk) const const GPUTPCTracker& tracker = GetConstantMem()->tpcTrackers[sectorTrack->Sector()]; const GPUTPCHitId& ic = tracker.TrackHits()[sectorTrack->OrigTrack(this)->FirstHitID() + i]; id = tracker.Data().ClusterDataIndex(tracker.Data().Row(ic.RowIndex()), ic.HitIndex()) + GetConstantMem()->ioPtrs.clustersNative->clusterOffset[sectorTrack->Sector()][0]; - } else { + } else if constexpr (std::is_same_v) { id = mClusters[trk.FirstClusterRef() + i].num; + } else { + static_assert(sizeof(S) == 0, "Invalid template"); } acc.addLabel(id); } diff --git a/GPU/GPUTracking/Merger/GPUTPCGMSectorTrack.cxx b/GPU/GPUTracking/Merger/GPUTPCGMSectorTrack.cxx index e488666288c84..0f38d13cecac5 100644 --- a/GPU/GPUTracking/Merger/GPUTPCGMSectorTrack.cxx +++ b/GPU/GPUTracking/Merger/GPUTPCGMSectorTrack.cxx @@ -270,108 +270,109 @@ GPUd() bool GPUTPCGMSectorTrack::FilterErrors(const GPUTPCGMMerger* merger, int3 return ok; } -template <> -GPUd() bool GPUTPCGMSectorTrack::TransportToX<2>(GPUTPCGMMerger* merger, float x, float Bz, GPUTPCGMBorderTrack& b, float maxSinPhi, bool doCov) const -{ - if (CAMath::Abs(x - mParam2.mX) < CAMath::Abs(x - mParam.mX) && mParam2.mX > 0) { - return TransportToX<1>(merger, x, Bz, b, maxSinPhi, doCov); - } else { - return TransportToX<0>(merger, x, Bz, b, maxSinPhi, doCov); - } -} - template GPUd() bool GPUTPCGMSectorTrack::TransportToX(GPUTPCGMMerger* merger, float x, float Bz, GPUTPCGMBorderTrack& b, float maxSinPhi, bool doCov) const { - const auto& param = I ? mParam2 : mParam; - Bz = -Bz; - float ex = param.mCosPhi; - float ey = param.mSinPhi; - float k = param.mQPt * Bz; - float dx = x - param.mX; - float ey1 = k * dx + ey; - - if (CAMath::Abs(ey1) > maxSinPhi) { - return 0; - } - - float ex1 = CAMath::Sqrt(1.f - ey1 * ey1); - float dxBz = dx * Bz; + if constexpr (I == 2) { + if (CAMath::Abs(x - mParam2.mX) < CAMath::Abs(x - mParam.mX) && mParam2.mX > 0) { + return TransportToX<1>(merger, x, Bz, b, maxSinPhi, doCov); + } else { + return TransportToX<0>(merger, x, Bz, b, maxSinPhi, doCov); + } + } else if constexpr (I == 0 || I == 1) { + const auto& param = I ? mParam2 : mParam; + Bz = -Bz; + float ex = param.mCosPhi; + float ey = param.mSinPhi; + float k = param.mQPt * Bz; + float dx = x - param.mX; + float ey1 = k * dx + ey; + + if (CAMath::Abs(ey1) > maxSinPhi) { + return 0; + } - float ss = ey + ey1; - float cc = ex + ex1; - float dxcci = dx / cc; - float norm2 = 1.f + ey * ey1 + ex * ex1; + float ex1 = CAMath::Sqrt(1.f - ey1 * ey1); + float dxBz = dx * Bz; - float dy = dxcci * ss; + float ss = ey + ey1; + float cc = ex + ex1; + float dxcci = dx / cc; + float norm2 = 1.f + ey * ey1 + ex * ex1; - float dS; - { - float dl = dxcci * CAMath::Sqrt(norm2 + norm2); - float dSin = 0.5f * k * dl; - float a = dSin * dSin; - const float k2 = 1.f / 6.f; - const float k4 = 3.f / 40.f; - // const float k6 = 5.f/112.f; - dS = dl + dl * a * (k2 + a * (k4)); //+ k6*a) ); - } + float dy = dxcci * ss; - float dz = dS * param.mDzDs; + float dS; + { + float dl = dxcci * CAMath::Sqrt(norm2 + norm2); + float dSin = 0.5f * k * dl; + float a = dSin * dSin; + const float k2 = 1.f / 6.f; + const float k4 = 3.f / 40.f; + // const float k6 = 5.f/112.f; + dS = dl + dl * a * (k2 + a * (k4)); //+ k6*a) ); + } - b.SetPar(0, param.mY + dy); - b.SetPar(1, param.mZ + dz); - b.SetPar(2, ey1); - b.SetPar(3, param.mDzDs); - b.SetPar(4, param.mQPt); - b.SetZOffsetLinear(merger->Param().par.continuousTracking ? merger->GetConstantMem()->calibObjects.fastTransform->convVertexTimeToZOffset(mSector, mTOffset, merger->Param().continuousMaxTimeBin) : 0); + float dz = dS * param.mDzDs; - if (!doCov) { - return (1); - } + b.SetPar(0, param.mY + dy); + b.SetPar(1, param.mZ + dz); + b.SetPar(2, ey1); + b.SetPar(3, param.mDzDs); + b.SetPar(4, param.mQPt); + b.SetZOffsetLinear(merger->Param().par.continuousTracking ? merger->GetConstantMem()->calibObjects.fastTransform->convVertexTimeToZOffset(mSector, mTOffset, merger->Param().continuousMaxTimeBin) : 0); - float ex1i = 1.f / ex1; - float hh = dxcci * ex1i * norm2; - float h2 = hh * param.mSecPhi; - float h4 = Bz * dxcci * hh; + if (!doCov) { + return (1); + } - float c20 = param.mC3; - float c22 = param.mC5; - float c31 = param.mC7; - float c33 = param.mC9; - float c40 = param.mC10; - float c42 = param.mC12; - float c44 = param.mC14; + float ex1i = 1.f / ex1; + float hh = dxcci * ex1i * norm2; + float h2 = hh * param.mSecPhi; + float h4 = Bz * dxcci * hh; + + float c20 = param.mC3; + float c22 = param.mC5; + float c31 = param.mC7; + float c33 = param.mC9; + float c40 = param.mC10; + float c42 = param.mC12; + float c44 = param.mC14; + + float c20ph4c42 = c20 + h4 * c42; + float h2c22 = h2 * c22; + float h4c44 = h4 * c44; + float n7 = c31 + dS * c33; + + if (CAMath::Abs(param.mQPt) > 6.66f) // Special treatment for low Pt + { + b.SetCov(0, CAMath::Max(param.mC0, param.mC0 + h2 * h2c22 + h4 * h4c44 + 2.f * (h2 * c20ph4c42 + h4 * c40))); // Do not decrease Y cov for matching! + float C2tmp = dS * 2.f * c31; + if (C2tmp < 0) { + C2tmp = 0; + } + b.SetCov(1, param.mC2 + C2tmp + dS * dS * c33); // Incorrect formula, correct would be "dS * (c31 + n7)", but we need to make sure cov(Z) increases regardless of the direction of the propagation + } else { + b.SetCov(0, param.mC0 + h2 * h2c22 + h4 * h4c44 + 2.f * (h2 * c20ph4c42 + h4 * c40)); + b.SetCov(1, param.mC2 + dS * (c31 + n7)); + } + b.SetCov(2, c22 + dxBz * (c42 + c42 + dxBz * c44)); + b.SetCov(3, c33); + b.SetCov(4, c44); + b.SetCovD(0, c20ph4c42 + h2c22 + dxBz * (c40 + h2 * c42 + h4c44)); + b.SetCovD(1, n7); - float c20ph4c42 = c20 + h4 * c42; - float h2c22 = h2 * c22; - float h4c44 = h4 * c44; - float n7 = c31 + dS * c33; + b.LimitCov(); - if (CAMath::Abs(param.mQPt) > 6.66f) // Special treatment for low Pt - { - b.SetCov(0, CAMath::Max(param.mC0, param.mC0 + h2 * h2c22 + h4 * h4c44 + 2.f * (h2 * c20ph4c42 + h4 * c40))); // Do not decrease Y cov for matching! - float C2tmp = dS * 2.f * c31; - if (C2tmp < 0) { - C2tmp = 0; - } - b.SetCov(1, param.mC2 + C2tmp + dS * dS * c33); // Incorrect formula, correct would be "dS * (c31 + n7)", but we need to make sure cov(Z) increases regardless of the direction of the propagation + return 1; } else { - b.SetCov(0, param.mC0 + h2 * h2c22 + h4 * h4c44 + 2.f * (h2 * c20ph4c42 + h4 * c40)); - b.SetCov(1, param.mC2 + dS * (c31 + n7)); + static_assert(I == 0 || I == 1 || I == 2, "Invalid I"); } - b.SetCov(2, c22 + dxBz * (c42 + c42 + dxBz * c44)); - b.SetCov(3, c33); - b.SetCov(4, c44); - b.SetCovD(0, c20ph4c42 + h2c22 + dxBz * (c40 + h2 * c42 + h4c44)); - b.SetCovD(1, n7); - - b.LimitCov(); - - return 1; } template GPUdni() bool GPUTPCGMSectorTrack::TransportToX<0>(GPUTPCGMMerger* merger, float x, float Bz, GPUTPCGMBorderTrack& b, float maxSinPhi, bool doCov) const; template GPUdni() bool GPUTPCGMSectorTrack::TransportToX<1>(GPUTPCGMMerger* merger, float x, float Bz, GPUTPCGMBorderTrack& b, float maxSinPhi, bool doCov) const; +template GPUdni() bool GPUTPCGMSectorTrack::TransportToX<2>(GPUTPCGMMerger* merger, float x, float Bz, GPUTPCGMBorderTrack& b, float maxSinPhi, bool doCov) const; GPUd() bool GPUTPCGMSectorTrack::TransportToXAlpha(GPUTPCGMMerger* merger, float newX, float sinAlpha, float cosAlpha, float Bz, GPUTPCGMBorderTrack& b, float maxSinPhi) const { diff --git a/GPU/GPUTracking/Refit/GPUTrackingRefit.cxx b/GPU/GPUTracking/Refit/GPUTrackingRefit.cxx index 16ce371176704..2edc6e155b58e 100644 --- a/GPU/GPUTracking/Refit/GPUTrackingRefit.cxx +++ b/GPU/GPUTracking/Refit/GPUTrackingRefit.cxx @@ -70,141 +70,108 @@ namespace o2::gpu::internal { namespace // anonymous { -template -struct refitTrackTypes; -template <> -struct refitTrackTypes { - using propagator = GPUTPCGMPropagator; -}; -template <> -struct refitTrackTypes { - using propagator = const Propagator*; -}; +template +using refitPropagator = std::conditional_t, GPUTPCGMPropagator, const Propagator*>; } // anonymous namespace } // namespace o2::gpu::internal -template <> -GPUd() void GPUTrackingRefit::initProp(GPUTPCGMPropagator& prop) // GPUgeneric() needed due to C++ for OpenCL template deduction +template +GPUd() void GPUTrackingRefit::loadTrack(S& trk, const T& trkX, P& prop, float& chi2) { - prop.SetMaterialTPC(); - prop.SetMaxSinPhi(constants::MAX_SIN_PHI); - prop.SetSeedingErrors(false); - prop.SetFitInProjections(mPparam->rec.fitInProjections != 0); - prop.SetPropagateBzOnly(false); - prop.SetPolynomialField(&mPparam->polynomialField); - prop.SetMatLUT(mPmatLUT); -} - -template <> -GPUd() void GPUTrackingRefit::initProp(const Propagator*& prop) // GPUgeneric() needed due to C++ for OpenCL template deduction -{ - prop = mPpropagator; -} - -template -GPUd() void GPUTrackingRefit::convertTrack(T& trk, const S& trkX, U& prop, float* chi2) -{ - trk = trkX; -} - -// Generic -template <> -GPUd() void GPUTrackingRefit::convertTrack(GPUTPCGMTrackParam& trk, const TrackParCov& trkX, GPUTPCGMPropagator& prop, float* chi2) -{ - convertTrackParam(trk, trkX); - prop.SetTrack(&trk, trkX.getAlpha()); -} -template <> -GPUd() void GPUTrackingRefit::convertTrack(TrackParCov& trk, const GPUTPCGMTrackParam& trkX, GPUTPCGMPropagator& prop, float* chi2) -{ - convertTrackParam(trk, trkX); - trk.setAlpha(prop.GetAlpha()); -} -// GPUTPCGMMergedTrack input -template <> -GPUd() void GPUTrackingRefit::convertTrack(TrackParCov& trk, const GPUTPCGMMergedTrack& trkX, const Propagator*& prop, float* chi2) -{ - initProp(prop); - convertTrackParam(trk, trkX.GetParam()); - trk.setAlpha(trkX.GetAlpha()); - *chi2 = trkX.GetParam().GetChi2(); -} -template <> -GPUd() void GPUTrackingRefit::convertTrack(GPUTPCGMMergedTrack& trk, const TrackParCov& trkX, const Propagator*& prop, float* chi2) -{ - convertTrackParam(trk.Param(), trkX); - trk.SetAlpha(trkX.getAlpha()); - trk.Param().SetChi2(*chi2); -} -template <> -GPUd() void GPUTrackingRefit::convertTrack(GPUTPCGMTrackParam& trk, const GPUTPCGMMergedTrack& trkX, GPUTPCGMPropagator& prop, float* chi2) -{ - initProp(prop); - trk = trkX.GetParam(); - prop.SetTrack(&trk, trkX.GetAlpha()); -} -template <> -GPUd() void GPUTrackingRefit::convertTrack(GPUTPCGMMergedTrack& trk, const GPUTPCGMTrackParam& trkX, GPUTPCGMPropagator& prop, float* chi2) -{ - trk.SetParam(trkX); - trk.SetAlpha(prop.GetAlpha()); -} -// TrackTPC input -template <> -GPUd() void GPUTrackingRefit::convertTrack(TrackParCov& trk, const TrackTPC& trkX, const Propagator*& prop, float* chi2) -{ - initProp(prop); - convertTrack(trk, trkX, prop, nullptr); - *chi2 = trkX.getChi2(); -} -template <> -GPUd() void GPUTrackingRefit::convertTrack(TrackTPC& trk, const TrackParCov& trkX, const Propagator*& prop, float* chi2) -{ - convertTrack(trk, trkX, prop, nullptr); - trk.setChi2(*chi2); -} -template <> -GPUd() void GPUTrackingRefit::convertTrack(GPUTPCGMTrackParam& trk, const TrackTPC& trkX, GPUTPCGMPropagator& prop, float* chi2) -{ - initProp(prop); - convertTrack(trk, trkX, prop, nullptr); - trk.SetChi2(trkX.getChi2()); -} -template <> -GPUd() void GPUTrackingRefit::convertTrack(TrackTPC& trk, const GPUTPCGMTrackParam& trkX, GPUTPCGMPropagator& prop, float* chi2) -{ - convertTrack(trk, trkX, prop, nullptr); - trk.setChi2(trkX.GetChi2()); -} -// TrackParCovWithArgs input -template <> -GPUd() void GPUTrackingRefit::convertTrack(TrackParCov& trk, const GPUTrackingRefit::TrackParCovWithArgs& trkX, const Propagator*& prop, float* chi2) -{ - initProp(prop); - convertTrack(trk, trkX.trk, prop, nullptr); - *chi2 = trkX.chi2 ? *trkX.chi2 : 0.f; -} -template <> -GPUd() void GPUTrackingRefit::convertTrack(GPUTrackingRefit::TrackParCovWithArgs& trk, const TrackParCov& trkX, const Propagator*& prop, float* chi2) -{ - convertTrack(trk.trk, trkX, prop, nullptr); - if (trk.chi2) { - *trk.chi2 = *chi2; + if constexpr (std::is_same_v) { + prop.SetMaterialTPC(); + prop.SetMaxSinPhi(constants::MAX_SIN_PHI); + prop.SetSeedingErrors(false); + prop.SetFitInProjections(mPparam->rec.fitInProjections != 0); + prop.SetPropagateBzOnly(false); + prop.SetPolynomialField(&mPparam->polynomialField); + prop.SetMatLUT(mPmatLUT); + } else if constexpr (std::is_same_v) { + prop = mPpropagator; + } else { + static_assert(sizeof(S) == 0, "Invalid template"); + } + if constexpr (std::is_same_v) { + if constexpr (std::is_same_v) { + trk = trkX.GetParam(); + prop.SetTrack(&trk, trkX.GetAlpha()); + } else if constexpr (std::is_same_v) { + convertTrackParam(trk, trkX.GetParam()); + trk.setAlpha(trkX.GetAlpha()); + chi2 = trkX.GetParam().GetChi2(); + } else { + static_assert(sizeof(S) == 0, "Invalid template"); + } + } else if constexpr (std::is_same_v || std::is_same_v) { + const TrackParCov* src; // TrackParCov part of TrackTPC / TrackParCovWithArgs + float srcChi2; + if constexpr (std::is_same_v) { + src = &trkX; + srcChi2 = trkX.getChi2(); + } else if constexpr (std::is_same_v) { + src = &trkX.trk; + srcChi2 = trkX.chi2 ? *trkX.chi2 : 0.f; + } else { + static_assert(sizeof(T) == 0, "Invalid template"); + } + if constexpr (std::is_same_v) { + convertTrackParam(trk, *src); + prop.SetTrack(&trk, src->getAlpha()); + trk.SetChi2(srcChi2); + } else if constexpr (std::is_same_v) { + trk = *src; + chi2 = srcChi2; + } else { + static_assert(sizeof(S) == 0, "Invalid template"); + } + } else { + static_assert(sizeof(T) == 0, "Invalid template"); } } -template <> -GPUd() void GPUTrackingRefit::convertTrack(GPUTPCGMTrackParam& trk, const GPUTrackingRefit::TrackParCovWithArgs& trkX, GPUTPCGMPropagator& prop, float* chi2) -{ - initProp(prop); - convertTrack(trk, trkX.trk, prop, nullptr); - trk.SetChi2(trkX.chi2 ? *trkX.chi2 : 0.f); -} -template <> -GPUd() void GPUTrackingRefit::convertTrack(GPUTrackingRefit::TrackParCovWithArgs& trk, const GPUTPCGMTrackParam& trkX, GPUTPCGMPropagator& prop, float* chi2) + +template +GPUd() void GPUTrackingRefit::storeTrack(T& trkX, const S& trk, const P& prop, float chi2) { - convertTrack(trk.trk, trkX, prop, chi2); - if (trk.chi2) { - *trk.chi2 = trkX.GetChi2(); + if constexpr (std::is_same_v) { + if constexpr (std::is_same_v) { + trkX.SetParam(trk); + trkX.SetAlpha(prop.GetAlpha()); + } else if constexpr (std::is_same_v) { + convertTrackParam(trkX.Param(), trk); + trkX.SetAlpha(trk.getAlpha()); + trkX.Param().SetChi2(chi2); + } else { + static_assert(sizeof(S) == 0, "Invalid template"); + } + } else if constexpr (std::is_same_v || std::is_same_v) { + TrackParCov* dst; // only the TrackParCov part of TrackTPC is assigned + if constexpr (std::is_same_v) { + dst = &trkX; + } else if constexpr (std::is_same_v) { + dst = &trkX.trk; + } else { + static_assert(sizeof(T) == 0, "Invalid template"); + } + if constexpr (std::is_same_v) { + convertTrackParam(*dst, trk); + dst->setAlpha(prop.GetAlpha()); + chi2 = trk.GetChi2(); + } else if constexpr (std::is_same_v) { + *dst = trk; + } else { + static_assert(sizeof(S) == 0, "Invalid template"); + } + if constexpr (std::is_same_v) { + trkX.setChi2(chi2); + } else if constexpr (std::is_same_v) { + if (trkX.chi2) { + *trkX.chi2 = chi2; + } + } else { + static_assert(sizeof(T) == 0, "Invalid template"); + } + } else { + static_assert(sizeof(T) == 0, "Invalid template"); } } @@ -215,10 +182,10 @@ template GPUd() int32_t GPUTrackingRefit::RefitTrack(T& trkX, bool outward, bool resetCov) { CADEBUG(int32_t ii; printf("\nRefitting track\n")); - typename internal::refitTrackTypes::propagator prop; + internal::refitPropagator prop; S trk; float TrackParCovChi2 = 0.f; - convertTrack::propagator>(trk, trkX, prop, &TrackParCovChi2); + loadTrack>(trk, trkX, prop, TrackParCovChi2); int32_t begin = 0, count; float tOffset; [[maybe_unused]] int32_t eLossSign = 0; // energy-loss sign of the TrackParCov propagations (0: from the direction, outward = loss) @@ -414,7 +381,7 @@ GPUd() int32_t GPUTrackingRefit::RefitTrack(T& trkX, bool outward, bool resetCov static_assert("Invalid template"); } - convertTrack::propagator>(trkX, trk, prop, &TrackParCovChi2); + storeTrack>(trkX, trk, prop, TrackParCovChi2); return nFitted; } diff --git a/GPU/GPUTracking/Refit/GPUTrackingRefit.h b/GPU/GPUTracking/Refit/GPUTrackingRefit.h index 71f8f11bee3eb..10b537781370b 100644 --- a/GPU/GPUTracking/Refit/GPUTrackingRefit.h +++ b/GPU/GPUTracking/Refit/GPUTrackingRefit.h @@ -99,10 +99,10 @@ class GPUTrackingRefit const GPUParam* mPparam = nullptr; // Ptr to GPUParam template GPUd() int32_t RefitTrack(T& trk, bool outward, bool resetCov); - template - GPUd() void convertTrack(T& trk, const S& trkX, U& prop, float* chi2); - template - GPUd() void initProp(U& prop); + template + GPUd() void loadTrack(S& trk, const T& trkX, P& prop, float& chi2); // init propagator and convert input track T to fit track S + template + GPUd() void storeTrack(T& trkX, const S& trk, const P& prop, float chi2); }; class GPUTrackingRefitProcessor : public GPUTrackingRefit, public GPUProcessor diff --git a/GPU/GPUTracking/TRDTracking/GPUTRDTracker.cxx b/GPU/GPUTracking/TRDTracking/GPUTRDTracker.cxx index 50e2aa192e3c9..52fcb2f795c94 100644 --- a/GPU/GPUTracking/TRDTracking/GPUTRDTracker.cxx +++ b/GPU/GPUTracking/TRDTracking/GPUTRDTracker.cxx @@ -243,16 +243,16 @@ void GPUTRDTracker_t::StartDebugging() #endif //! GPUCA_GPUCODE -template <> -GPUdi() const GPUTRDPropagatorGPU::propagatorParam* GPUTRDTracker_t::getPropagatorParam() -{ - return &Param().polynomialField; -} - template GPUdi() const typename PROP::propagatorParam* GPUTRDTracker_t::getPropagatorParam() { - return GetConstantMem()->calibObjects.o2Propagator; + if constexpr (std::is_same_v) { + return &Param().polynomialField; + } else if constexpr (std::is_same_v) { + return GetConstantMem()->calibObjects.o2Propagator; + } else { + static_assert(sizeof(PROP) == 0, "Invalid template"); + } } template diff --git a/GPU/GPUTracking/display/render/GPUDisplayDraw.cxx b/GPU/GPUTracking/display/render/GPUDisplayDraw.cxx index 4af2af4f3147c..1e1bae353a522 100644 --- a/GPU/GPUTracking/display/render/GPUDisplayDraw.cxx +++ b/GPU/GPUTracking/display/render/GPUDisplayDraw.cxx @@ -368,7 +368,7 @@ void GPUDisplay::DrawFinal(int32_t iSector, int32_t /*iCol*/, const GPUTPCGMProp break; } } else { - throw std::runtime_error("invalid type"); + static_assert(sizeof(T) == 0, "Invalid template"); } size_t startCountInner = mVertexBuffer[iSector].size(); @@ -457,8 +457,10 @@ void GPUDisplay::DrawFinal(int32_t iSector, int32_t /*iCol*/, const GPUTPCGMProp int32_t cid; if constexpr (std::is_same_v) { cid = mIOPtrs->mergedTrackHits[track->FirstClusterRef() + k].num; - } else { + } else if constexpr (std::is_same_v) { cid = &track->getCluster(mIOPtrs->outputClusRefsTPCO2, k, *mIOPtrs->clustersNative) - mIOPtrs->clustersNative->clustersLinear; + } else { + static_assert(sizeof(T) == 0, "Invalid template"); } int32_t w = mGlobalPos[cid].w; if (drawing) { @@ -482,8 +484,10 @@ void GPUDisplay::DrawFinal(int32_t iSector, int32_t /*iCol*/, const GPUTPCGMProp int32_t lastcid; if constexpr (std::is_same_v) { lastcid = mIOPtrs->mergedTrackHits[track->FirstClusterRef() + lastCluster].num; - } else { + } else if constexpr (std::is_same_v) { lastcid = &track->getCluster(mIOPtrs->outputClusRefsTPCO2, lastCluster, *mIOPtrs->clustersNative) - mIOPtrs->clustersNative->clustersLinear; + } else { + static_assert(sizeof(T) == 0, "Invalid template"); } drawPointLinestrip(iSector, lastcid, tFINALTRACK, separateExtrapolatedTracksLimit); } @@ -546,11 +550,13 @@ void GPUDisplay::DrawFinal(int32_t iSector, int32_t /*iCol*/, const GPUTPCGMProp if constexpr (std::is_same_v) { trkParam.Set(track->GetParam()); alphaOrg = mParam->Alpha(iSector); - } else { + } else if constexpr (std::is_same_v) { GPUTPCGMTrackParam t; convertTrackParam(t, *track); alphaOrg = track->getAlpha(); trkParam.Set(t); + } else { + static_assert(sizeof(T) == 0, "Invalid template"); } float y, z; @@ -559,11 +565,13 @@ void GPUDisplay::DrawFinal(int32_t iSector, int32_t /*iCol*/, const GPUTPCGMProp const auto& cln = mIOPtrs->clustersNative->clustersLinear[cl.num]; GPUTPCConvertImpl::convert(*mCalib->fastTransform, *mParam, cl.sector, cl.row, cln.getPad(), cln.getTime(), x, y, z); ZOffset = mCalib->fastTransform->convVertexTimeToZOffset(iSector, track->GetParam().GetTOffset(), mParam->continuousMaxTimeBin); - } else { + } else if constexpr (std::is_same_v) { uint8_t sector, row; auto cln = track->getCluster(mIOPtrs->outputClusRefsTPCO2, lastCluster, *mIOPtrs->clustersNative, sector, row); GPUTPCConvertImpl::convert(*mCalib->fastTransform, *mParam, sector, row, cln.getPad(), cln.getTime(), x, y, z); ZOffset = mCalib->fastTransform->convVertexTimeToZOffset(sector, track->getTime0(), mParam->continuousMaxTimeBin); + } else { + static_assert(sizeof(T) == 0, "Invalid template"); } } else { const GPUTPCMCInfo& mc = mIOPtrs->mcInfosTPC[i]; diff --git a/GPU/GPUTracking/qa/GPUQA.cxx b/GPU/GPUTracking/qa/GPUQA.cxx index 6fd5c4fd2d901..906073e9bc599 100644 --- a/GPU/GPUTracking/qa/GPUQA.cxx +++ b/GPU/GPUTracking/qa/GPUQA.cxx @@ -266,25 +266,20 @@ inline auto& GPUQA::GetMCTrackObj(T& obj, const GPUQA::mcLabelI_t& l) return obj[mMCEventOffset[l.getSourceID()] + l.getEventID()][l.getTrackID()]; } -template <> -auto GPUQA::getHistArray() -{ - return std::make_pair(mHist1D, &mHist1D_pos); -} -template <> -auto GPUQA::getHistArray() -{ - return std::make_pair(mHist2D, &mHist2D_pos); -} -template <> -auto GPUQA::getHistArray() -{ - return std::make_pair(mHist1Dd, &mHist1Dd_pos); -} -template <> -auto GPUQA::getHistArray() +template +auto GPUQA::getHistArray() { - return std::make_pair(mHistGraph, &mHistGraph_pos); + if constexpr (std::is_same_v) { + return std::make_pair(mHist1D, &mHist1D_pos); + } else if constexpr (std::is_same_v) { + return std::make_pair(mHist2D, &mHist2D_pos); + } else if constexpr (std::is_same_v) { + return std::make_pair(mHist1Dd, &mHist1Dd_pos); + } else if constexpr (std::is_same_v) { + return std::make_pair(mHistGraph, &mHistGraph_pos); + } else { + static_assert(sizeof(T) == 0, "unsupported histogram type"); + } } template void GPUQA::createHist(T*& h, const char* name, Args... args) diff --git a/GPU/GPUTracking/utils/qconfig.cxx b/GPU/GPUTracking/utils/qconfig.cxx index 275c254ea9d42..02543dbaebb45 100644 --- a/GPU/GPUTracking/utils/qconfig.cxx +++ b/GPU/GPUTracking/utils/qconfig.cxx @@ -59,31 +59,14 @@ template static int32_t qAddOptionMinMax(qConfigSettings& settings, T& ref, const char* arg); template -struct qConfigTypeSpecialized { - static inline int32_t qAddOptionMain(qConfigSettings& settings, T& ref, int32_t& i, const char** argv, const int argc, T def); +struct qConfigArgType { // First argument of an option of this type can be omitted + static constexpr bool isTuple = false, optional = std::is_same_v; }; -template -struct qConfigTypeSpecialized> { - static inline int32_t qAddOptionMain(qConfigSettings>::settingsType>& settings, std::tuple& ref, int32_t& i, const char** argv, const int argc, std::tuple& def); +template +struct qConfigArgType> { + static constexpr bool isTuple = true, optional = std::is_same_v; }; -// Main processing function for arguments -template -inline int32_t qConfigTypeSpecialized::qAddOptionMain(qConfigSettings& settings, T& ref, int32_t& i, const char** argv, const int argc, T def) -{ - int32_t retVal = 0; - int32_t iOrg = i; - if (settings.doSet) { - ref = settings.set; - } else if ((retVal = qAddOptionType(settings, ref, i, argv, argc, std::move(def)))) { - return (retVal); - } - if ((retVal = qAddOptionMinMax(settings, ref, iOrg < argc ? argv[iOrg] : ""))) { - return (retVal); - } - qAddOptionMessage(settings, ref); - return (0); -} template static inline int32_t qAddOptionMainTupleElem(qConfigSettings::settingsType> settingsTup, T& ref, int32_t& i, const char** argv, const int argc) { @@ -91,10 +74,10 @@ static inline int32_t qAddOptionMainTupleElem(qConfigSettings settings = settingsTup; return (qAddOptionType(settings, ref, i, argv, argc, std::move(def))); } -template > -struct qAddOptionMainTupleStruct { - static inline int32_t qAddOptionMainTuple(qConfigSettings::settingsType> settings, T& tup, int32_t& i, const char** argv, const int argc) - { +template +static inline int32_t qAddOptionMainTuple(qConfigSettings::settingsType> settings, T& tup, int32_t& i, const char** argv, const int argc) +{ + if constexpr (index < std::tuple_size_v) { auto& ref = std::get(tup); int32_t retVal = qAddOptionMainTupleElem(settings, ref, i, argv, argc); if (retVal) { @@ -104,27 +87,33 @@ struct qAddOptionMainTupleStruct { } return (retVal); } - return (qAddOptionMainTupleStruct::qAddOptionMainTuple(settings, tup, i, argv, argc)); + return (qAddOptionMainTuple(settings, tup, i, argv, argc)); + } else { + return 0; } -}; -template -struct qAddOptionMainTupleStruct { - static inline int32_t qAddOptionMainTuple(qConfigSettings::settingsType> /*settings*/, T& /*tup*/, int32_t& /*i*/, const char** /*argv*/, const int32_t /*argc*/) { return 0; } -}; -template -inline int32_t qConfigTypeSpecialized>::qAddOptionMain(qConfigSettings>::settingsType>& settings, std::tuple& ref, int32_t& i, const char** argv, const int argc, std::tuple& /*def*/) -{ - return (qAddOptionMainTupleStruct>::qAddOptionMainTuple(settings, ref, i, argv, argc)); } -template -struct qConfigArgType { // First argument of an option of this type can be omitted - static constexpr bool isTuple = false, optional = std::is_same_v; -}; -template -struct qConfigArgType> { - static constexpr bool isTuple = true, optional = std::is_same_v; -}; +// Main processing function for arguments +template +static inline int32_t qAddOptionMain(qConfigSettings::settingsType>& settings, T& ref, int32_t& i, const char** argv, const int argc, T& def) +{ + if constexpr (qConfigArgType::isTuple) { + return (qAddOptionMainTuple(settings, ref, i, argv, argc)); + } else { + int32_t retVal = 0; + int32_t iOrg = i; + if (settings.doSet) { + ref = settings.set; + } else if ((retVal = qAddOptionType(settings, ref, i, argv, argc, std::move(def)))) { + return (retVal); + } + if ((retVal = qAddOptionMinMax(settings, ref, iOrg < argc ? argv[iOrg] : ""))) { + return (retVal); + } + qAddOptionMessage(settings, ref); + return (0); + } +} template struct qConfigType : public qConfigSettingsParser { @@ -141,7 +130,7 @@ struct qConfigType : public qConfigSettingsParser { static inline int32_t qAddOption(T& ref, int32_t& i, const char** argv, const int argc, T def, const char* /*help*/, Args&&... args) { auto settings = qConfigGetSettings(args...); - return qConfigTypeSpecialized::qAddOptionMain(settings, ref, i, argv, argc, def); + return qAddOptionMain(settings, ref, i, argv, argc, def); } template @@ -153,7 +142,7 @@ struct qConfigType : public qConfigSettingsParser { iLast = i; T tmp = T(), def = T(); settings.allowEmpty = (i != iFirst); - int32_t retVal = qConfigTypeSpecialized::qAddOptionMain(settings, tmp, i, argv, argc, def); + int32_t retVal = qAddOptionMain(settings, tmp, i, argv, argc, def); if (retVal) { return (retVal != qcrArgMissing || i == iFirst ? retVal : 0); } @@ -173,7 +162,7 @@ struct qConfigType : public qConfigSettingsParser { iLast = i; T tmp = T(), def = T(); settings.allowEmpty = (i != iFirst); - int32_t retVal = qConfigTypeSpecialized::qAddOptionMain(settings, tmp, i, argv, argc, def); + int32_t retVal = qAddOptionMain(settings, tmp, i, argv, argc, def); if (retVal) { return (retVal != qcrArgMissing || i == iFirst ? retVal : 0); } @@ -263,142 +252,55 @@ static inline int32_t qAddOptionGeneric(qConfigSettings& settings, T& ref, in } // Handling of all supported types -template <> -inline int32_t qAddOptionType(qConfigSettings& settings, bool& ref, int32_t& i, const char** argv, const int argc, bool /*def*/) -{ - return qAddOptionGeneric( - settings, ref, i, argv, argc, settings.doDefault ? settings.set : true, [](const char* a) -> bool { - return atoi(a); - }, - true); -} -template <> -inline int32_t qAddOptionType(qConfigSettings& settings, int8_t& ref, int32_t& i, const char** argv, const int argc, int8_t /*def*/) -{ - return qAddOptionGeneric( - settings, ref, i, argv, argc, settings.set, [](const char* a) -> int8_t { - return atoi(a); - }, - settings.doDefault); -} -template <> -inline int32_t qAddOptionType(qConfigSettings& settings, uint8_t& ref, int32_t& i, const char** argv, const int argc, uint8_t /*def*/) -{ - return qAddOptionGeneric( - settings, ref, i, argv, argc, settings.set, [](const char* a) -> uint8_t { - return atoi(a); - }, - settings.doDefault); -} -template <> -inline int32_t qAddOptionType(qConfigSettings& settings, int32_t& ref, int32_t& i, const char** argv, const int argc, int32_t /*def*/) -{ - return qAddOptionGeneric( - settings, ref, i, argv, argc, settings.set, [](const char* a) -> int32_t { - return atoi(a); - }, - settings.doDefault); -} -template <> -inline int32_t qAddOptionType(qConfigSettings& settings, uint32_t& ref, int32_t& i, const char** argv, const int argc, uint32_t /*def*/) -{ - return qAddOptionGeneric( - settings, ref, i, argv, argc, settings.set, [](const char* a) -> uint32_t { - return strtoul(a, nullptr, 0); - }, - settings.doDefault); -} -template <> -inline int32_t qAddOptionType(qConfigSettings& settings, int16_t& ref, int32_t& i, const char** argv, const int argc, int16_t /*def*/) -{ - return qAddOptionGeneric( - settings, ref, i, argv, argc, settings.set, [](const char* a) -> int16_t { - return atoi(a); - }, - settings.doDefault); -} -template <> -inline int32_t qAddOptionType(qConfigSettings& settings, uint16_t& ref, int32_t& i, const char** argv, const int argc, uint16_t /*def*/) -{ - return qAddOptionGeneric( - settings, ref, i, argv, argc, settings.set, [](const char* a) -> uint16_t { - return strtoul(a, nullptr, 0); - }, - settings.doDefault); -} -template <> -inline int32_t qAddOptionType(qConfigSettings& settings, int64_t& ref, int32_t& i, const char** argv, const int argc, int64_t /*def*/) -{ - return qAddOptionGeneric( - settings, ref, i, argv, argc, settings.set, [](const char* a) -> int64_t { - return strtoll(a, nullptr, 0); - }, - settings.doDefault); -} -template <> -inline int32_t qAddOptionType(qConfigSettings& settings, uint64_t& ref, int32_t& i, const char** argv, const int argc, uint64_t /*def*/) -{ - return qAddOptionGeneric( - settings, ref, i, argv, argc, settings.set, [](const char* a) -> uint64_t { - return strtoull(a, nullptr, 0); - }, - settings.doDefault); -} -template <> -inline int32_t qAddOptionType(qConfigSettings& settings, float& ref, int32_t& i, const char** argv, const int argc, float /*def*/) -{ - return qAddOptionGeneric( - settings, ref, i, argv, argc, settings.set, [](const char* a) -> float { - return (float)atof(a); - }, - settings.doDefault); -} -template <> -inline int32_t qAddOptionType(qConfigSettings& settings, double& ref, int32_t& i, const char** argv, const int argc, double /*def*/) -{ - return qAddOptionGeneric( - settings, ref, i, argv, argc, settings.set, [](const char* a) -> double { - return atof(a); - }, - settings.doDefault); -} -template <> -inline int32_t qAddOptionType(qConfigSettings& settings, const char*& ref, int32_t& i, const char** argv, const int argc, const char* /*def*/) -{ - return qAddOptionGeneric( - settings, ref, i, argv, argc, settings.set, [](const char* a) -> const char* { - return a; - }, - settings.doDefault); -} -template <> -inline int32_t qAddOptionType(qConfigSettings& settings, std::string& ref, int32_t& i, const char** argv, const int argc, std::string /*def*/) +template +static inline int32_t qAddOptionType(qConfigSettings& settings, T& ref, int32_t& i, const char** argv, const int argc, T def) { - return qAddOptionGeneric( - settings, ref, i, argv, argc, settings.set, [](const char* a) -> std::string { - return a; + constexpr bool isBool = std::is_same_v; + if constexpr (isBool) { + def = settings.doDefault ? settings.set : true; + } else { + def = settings.set; + } + return qAddOptionGeneric( + settings, ref, i, argv, argc, std::move(def), [](const char* a) -> T { + if constexpr (isBool || std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v) { + return atoi(a); + } else if constexpr (std::is_same_v || std::is_same_v) { + return strtoul(a, nullptr, 0); + } else if constexpr (std::is_same_v) { + return strtoll(a, nullptr, 0); + } else if constexpr (std::is_same_v) { + return strtoull(a, nullptr, 0); + } else if constexpr (std::is_same_v) { + return (float)atof(a); + } else if constexpr (std::is_same_v) { + return atof(a); + } else if constexpr (std::is_same_v || std::is_same_v) { + return a; + } else { + static_assert(sizeof(T) == 0, "unsupported qconfig type"); + } }, - settings.doDefault); + isBool || settings.doDefault); } // Checks and messages for additional settings template static inline int32_t qAddOptionMinMax(qConfigSettings& settings, T& ref, const char* arg) { - if (settings.checkMin && ref < settings.min) { - std::cout << "Invalid setting for " << arg << ": minimum threshold exceeded (" << ref << " < " << settings.min << ")!\n"; - return (qcrMinFailure); - } - if (settings.checkMax && ref > settings.max) { - std::cout << "Invalid setting for " << arg << ": maximum threshold exceeded (" << ref << " > " << settings.max << ")!\n"; - return (qcrMaxFailure); + if constexpr (std::is_same_v) { + return 0; + } else { + if (settings.checkMin && ref < settings.min) { + std::cout << "Invalid setting for " << arg << ": minimum threshold exceeded (" << ref << " < " << settings.min << ")!\n"; + return (qcrMinFailure); + } + if (settings.checkMax && ref > settings.max) { + std::cout << "Invalid setting for " << arg << ": maximum threshold exceeded (" << ref << " > " << settings.max << ")!\n"; + return (qcrMaxFailure); + } + return (0); } - return (0); -} -template <> -inline int32_t qAddOptionMinMax(qConfigSettings& /*settings*/, bool& /*ref*/, const char* /*arg*/) -{ - return (0); } template diff --git a/GPU/GPUTracking/utils/qconfig_helpers.h b/GPU/GPUTracking/utils/qconfig_helpers.h index 51c89b759e9cf..c2447a4b99920 100644 --- a/GPU/GPUTracking/utils/qconfig_helpers.h +++ b/GPU/GPUTracking/utils/qconfig_helpers.h @@ -33,34 +33,20 @@ namespace qConfig template inline std::string print_type(T val, bool precise = false) { - std::ostringstream s; - if constexpr (std::is_same_v || std::is_same_v) { - if (precise) { - s << std::hexfloat; + if constexpr (std::is_same_v) { + return val ? "true" : "false"; + } else if constexpr (std::is_same_v || std::is_same_v || std::is_same_v) { + return std::to_string(val); + } else { + std::ostringstream s; + if constexpr (std::is_same_v || std::is_same_v) { + if (precise) { + s << std::hexfloat; + } } + s << val; + return s.str(); } - s << val; - return s.str(); -}; -template <> -inline std::string print_type(char val, bool precise) -{ - return std::to_string(val); -}; -template <> -inline std::string print_type(int8_t val, bool precise) -{ - return std::to_string(val); -}; -template <> -inline std::string print_type(uint8_t val, bool precise) -{ - return std::to_string(val); -}; -template <> -inline std::string print_type(bool val, bool precise) -{ - return val ? "true" : "false"; }; } // namespace qConfig diff --git a/GPU/GPUbenchmark/cuda/Kernels.cu b/GPU/GPUbenchmark/cuda/Kernels.cu index a10fcd357d81b..dc42174f5de76 100644 --- a/GPU/GPUbenchmark/cuda/Kernels.cu +++ b/GPU/GPUbenchmark/cuda/Kernels.cu @@ -16,6 +16,7 @@ #include #include #include +#include // Memory partitioning schema // @@ -80,6 +81,16 @@ namespace gpu //////////// // Kernels +template +__device__ inline chunk_t writeValue() +{ + if constexpr (std::is_same_v) { + return {0, 1, 0, 0}; + } else { + return 0; + } +} + // Read template __global__ void read_k( @@ -100,20 +111,10 @@ __global__ void write_k( size_t chunkSize) { for (size_t i = blockIdx.x * blockDim.x + threadIdx.x; i < chunkSize; i += blockDim.x * gridDim.x) { - chunkPtr[i] = 0; + chunkPtr[i] = writeValue(); } } -template <> -__global__ void write_k( - int4* chunkPtr, - size_t chunkSize) -{ - for (size_t i = blockIdx.x * blockDim.x + threadIdx.x; i < chunkSize; i += blockDim.x * gridDim.x) { - chunkPtr[i] = {0, 1, 0, 0}; - }; -} - // Copy template __global__ void copy_k( @@ -148,21 +149,10 @@ __global__ void rand_write_k( int32_t prime) { for (size_t i = blockIdx.x * blockDim.x + threadIdx.x; i < chunkSize; i += blockDim.x * gridDim.x) { - chunkPtr[(i * prime) % chunkSize] = 0; + chunkPtr[(i * prime) % chunkSize] = writeValue(); } } -template <> -__global__ void rand_write_k( - int4* chunkPtr, - size_t chunkSize, - int32_t prime) -{ - for (size_t i = blockIdx.x * blockDim.x + threadIdx.x; i < chunkSize; i += blockDim.x * gridDim.x) { - chunkPtr[(i * prime) % chunkSize] = {0, 1, 0, 0}; - }; -} - // Random copy template __global__ void rand_copy_k( @@ -200,19 +190,7 @@ __global__ void write_dist_k( chunk_t* ptr = block_ptr[blockIdx.x]; size_t n = block_size[blockIdx.x]; for (size_t i = threadIdx.x; i < n; i += blockDim.x) { - ptr[i] = 0; - } -} - -template <> -__global__ void write_dist_k( - int4** block_ptr, - size_t* block_size) -{ - int4* ptr = block_ptr[blockIdx.x]; - size_t n = block_size[blockIdx.x]; - for (size_t i = threadIdx.x; i < n; i += blockDim.x) { - ptr[i] = {0, 1, 0, 0}; + ptr[i] = writeValue(); } } @@ -256,20 +234,7 @@ __global__ void rand_write_dist_k( chunk_t* ptr = block_ptr[blockIdx.x]; size_t n = block_size[blockIdx.x]; for (size_t i = threadIdx.x; i < n; i += blockDim.x) { - ptr[(i * prime) % n] = 0; - } -} - -template <> -__global__ void rand_write_dist_k( - int4** block_ptr, - size_t* block_size, - int32_t prime) -{ - int4* ptr = block_ptr[blockIdx.x]; - size_t n = block_size[blockIdx.x]; - for (size_t i = threadIdx.x; i < n; i += blockDim.x) { - ptr[(i * prime) % n] = {0, 1, 0, 0}; + ptr[(i * prime) % n] = writeValue(); } } diff --git a/GPU/Utils/MultivariatePolynomialHelper.cxx b/GPU/Utils/MultivariatePolynomialHelper.cxx index 93e341fe4823b..03321a0b7052d 100644 --- a/GPU/Utils/MultivariatePolynomialHelper.cxx +++ b/GPU/Utils/MultivariatePolynomialHelper.cxx @@ -145,13 +145,15 @@ Type MultivariatePolynomialHelper<0, 0, false>::combination_with_repetiton(const term *= x[pos[i]]; } val += term; - } else { + } else if constexpr (std::is_same_v>) { std::string term{}; for (size_t i = 1; i <= degree; ++i) { term += fmt::format("x[{}] * ", pos[i]); } term += fmt::format("par[{}]", indexPar++); val.emplace_back(std::move(term)); + } else { + static_assert(sizeof(Type) == 0, "Invalid template"); } } diff --git a/GPU/Utils/Spline1DSpec.h b/GPU/Utils/Spline1DSpec.h index 66fa7a1ffc4d5..481078ee155ba 100644 --- a/GPU/Utils/Spline1DSpec.h +++ b/GPU/Utils/Spline1DSpec.h @@ -148,7 +148,7 @@ class Spline1DContainer : public Spline1DContainerBase GPUd() const Knot& getKnot(int32_t i) const { - if (SafeT == SafetyLevel::kSafe) { + if constexpr (SafeT == SafetyLevel::kSafe) { i = (i < 0) ? 0 : (i >= this->getNumberOfKnots() ? this->getNumberOfKnots() - 1 : i); } return getKnots()[i]; @@ -229,7 +229,7 @@ class Spline1DContainer : public Spline1DContainerBase (float)this->mUmax ? this->mUmax : (int32_t)u); - if (SafeT == SafetyLevel::kSafe) { + if constexpr (SafeT == SafetyLevel::kSafe) { iu = (iu < 0) ? 0 : (iu > this->mUmax ? this->mUmax : iu); } return getUtoKnotMapFromBuffer(flatBuf)[iu]; @@ -245,7 +245,7 @@ class Spline1DContainer : public Spline1DContainerBase GPUd() const Knot& getKnotFromBuffer(const char* flatBuf, int32_t i) const { - if (SafeT == SafetyLevel::kSafe) { + if constexpr (SafeT == SafetyLevel::kSafe) { i = (i < 0) ? 0 : (i >= this->getNumberOfKnots() ? this->getNumberOfKnots() - 1 : i); } return getKnotsFromBuffer(flatBuf)[i]; @@ -286,7 +286,7 @@ GPUdi() int32_t Spline1DContainer::getLeftKnotIndexForU(DataT /// Get i: u is in [knot_i, knot_{i+1}) segment /// when u is otside of [0, mUmax], return a corresponding edge segment int32_t iu = u < 0 ? 0 : (u > (float)this->mUmax ? this->mUmax : (int32_t)u); - if (SafeT == SafetyLevel::kSafe) { + if constexpr (SafeT == SafetyLevel::kSafe) { iu = (iu < 0) ? 0 : (iu > this->mUmax ? this->mUmax : iu); } return getUtoKnotMap()[iu]; From b0c6e76c96745587d321a6e92fa51c8527c487d9 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Tue, 1 Dec 2026 18:20:56 +0100 Subject: [PATCH 19/41] GPU OpenCL: Modernize C++: Simplify code a bit using more elaborate helper template --- .../Base/opencl/GPUReconstructionOCL.cxx | 133 ++++++++++-------- 1 file changed, 71 insertions(+), 62 deletions(-) diff --git a/GPU/GPUTracking/Base/opencl/GPUReconstructionOCL.cxx b/GPU/GPUTracking/Base/opencl/GPUReconstructionOCL.cxx index 95d6b680a0a8b..dcd3be16599d4 100644 --- a/GPU/GPUTracking/Base/opencl/GPUReconstructionOCL.cxx +++ b/GPU/GPUTracking/Base/opencl/GPUReconstructionOCL.cxx @@ -18,6 +18,9 @@ #include #include +#include +#include +#include static_assert(std::is_convertible_v, "OpenCL event type incompatible to deviceEvent"); @@ -60,6 +63,27 @@ int32_t GPUReconstructionOCL::GPUChkErrInternal(const int64_t retval, const char return retval != CL_SUCCESS; } +namespace o2::gpu::internal +{ +template +T clInfo(F func, Args... args) // Query an OpenCL info value, e.g. clInfo(clGetDeviceInfo, device, CL_DEVICE_MAX_COMPUTE_UNITS), std::string for string values +{ + if constexpr (std::is_same_v) { + size_t size = 0; + func(args..., 0, nullptr, &size); + std::string retVal(size ? size - 1 : 0, '\0'); + if (size) { + func(args..., size, retVal.data(), nullptr); + } + return retVal; + } else { + T retVal{}; + func(args..., sizeof(retVal), &retVal, nullptr); + return retVal; + } +} +} // namespace o2::gpu::internal + int32_t GPUReconstructionOCL::InitDevice_Runtime() { // Propagate processing settings to PoCL runtime. @@ -88,39 +112,34 @@ int32_t GPUReconstructionOCL::InitDevice_Runtime() GPUErrorReturn("Error getting OpenCL Platforms"); } - auto query = [&](auto func, auto obj, auto var) { - size_t size; - func(obj, var, 0, nullptr, &size); - std::string retVal(size - 1, ' '); - func(obj, var, size, retVal.data(), nullptr); - return retVal; - }; - std::string platform_profile, platform_version, platform_name, platform_vendor; float platform_version_f; auto queryPlatform = [&](auto platform) { - platform_profile = query(clGetPlatformInfo, platform, CL_PLATFORM_PROFILE); - platform_version = query(clGetPlatformInfo, platform, CL_PLATFORM_VERSION); - platform_name = query(clGetPlatformInfo, platform, CL_PLATFORM_NAME); - platform_vendor = query(clGetPlatformInfo, platform, CL_PLATFORM_VENDOR); + platform_profile = internal::clInfo(clGetPlatformInfo, platform, CL_PLATFORM_PROFILE); + platform_version = internal::clInfo(clGetPlatformInfo, platform, CL_PLATFORM_VERSION); + platform_name = internal::clInfo(clGetPlatformInfo, platform, CL_PLATFORM_NAME); + platform_vendor = internal::clInfo(clGetPlatformInfo, platform, CL_PLATFORM_VENDOR); sscanf(platform_version.c_str(), "OpenCL %f", &platform_version_f); }; std::vector devices; - std::string device_vendor, device_name, device_il_version; - cl_device_type device_type; - cl_uint device_freq, device_shaders, device_nbits; - cl_bool device_endian; - auto queryDevice = [&](auto device) { - device_name = query(clGetDeviceInfo, device, CL_DEVICE_NAME); - device_vendor = query(clGetDeviceInfo, device, CL_DEVICE_VENDOR); - device_il_version = query(clGetDeviceInfo, device, CL_DEVICE_IL_VERSION); - clGetDeviceInfo(device, CL_DEVICE_TYPE, sizeof(device_type), &device_type, nullptr); - clGetDeviceInfo(device, CL_DEVICE_MAX_CLOCK_FREQUENCY, sizeof(device_freq), &device_freq, nullptr); - clGetDeviceInfo(device, CL_DEVICE_MAX_COMPUTE_UNITS, sizeof(device_shaders), &device_shaders, nullptr); - clGetDeviceInfo(device, CL_DEVICE_ADDRESS_BITS, sizeof(device_nbits), &device_nbits, nullptr); - clGetDeviceInfo(device, CL_DEVICE_ENDIAN_LITTLE, sizeof(device_endian), &device_endian, nullptr); + struct deviceInfo { + std::string name, vendor, ilVersion; + cl_device_type type; + cl_uint freq, shaders, nbits; + cl_bool endian; + }; + auto queryDevice = [](cl_device_id device) { + return deviceInfo{.name = internal::clInfo(clGetDeviceInfo, device, CL_DEVICE_NAME), + .vendor = internal::clInfo(clGetDeviceInfo, device, CL_DEVICE_VENDOR), + .ilVersion = internal::clInfo(clGetDeviceInfo, device, CL_DEVICE_IL_VERSION), + .type = internal::clInfo(clGetDeviceInfo, device, CL_DEVICE_TYPE), + .freq = internal::clInfo(clGetDeviceInfo, device, CL_DEVICE_MAX_CLOCK_FREQUENCY), + .shaders = internal::clInfo(clGetDeviceInfo, device, CL_DEVICE_MAX_COMPUTE_UNITS), + .nbits = internal::clInfo(clGetDeviceInfo, device, CL_DEVICE_ADDRESS_BITS), + .endian = internal::clInfo(clGetDeviceInfo, device, CL_DEVICE_ENDIAN_LITTLE)}; }; + deviceInfo dev; cl_uint deviceCount, bestDevice = (cl_uint)-1, bestPlatform = (cl_uint)-1; double bestDeviceSpeed = -1; @@ -169,25 +188,25 @@ int32_t GPUReconstructionOCL::InitDevice_Runtime() i = GetProcessingSettings().deviceNum; } bool deviceOK = true; - queryDevice(devices[i]); + dev = queryDevice(devices[i]); std::string deviceFailure; - if (GetProcessingSettings().gpuDeviceOnly && ((device_type & CL_DEVICE_TYPE_CPU) || !(device_type & CL_DEVICE_TYPE_GPU))) { + if (GetProcessingSettings().gpuDeviceOnly && ((dev.type & CL_DEVICE_TYPE_CPU) || !(dev.type & CL_DEVICE_TYPE_GPU))) { deviceOK = false; deviceFailure += " - No GPU device"; } - if (device_nbits / 8 != sizeof(void*)) { + if (dev.nbits / 8 != sizeof(void*)) { deviceOK = false; deviceFailure += " - No 64 bit device"; } - if (!device_endian) { + if (!dev.endian) { deviceOK = false; deviceFailure += " - No Little Endian Mode"; } if (!GetProcessingSettings().backend.compileFromSources) { size_t pos = 0; - while ((pos = device_il_version.find("SPIR-V", pos)) != std::string::npos) { + while ((pos = dev.ilVersion.find("SPIR-V", pos)) != std::string::npos) { float spirvVersion; - sscanf(device_il_version.c_str() + pos, "SPIR-V_%f", &spirvVersion); + sscanf(dev.ilVersion.c_str() + pos, "SPIR-V_%f", &spirvVersion); if (spirvVersion >= GPUCA_OCL_SPIRV_VERSION) { break; } @@ -195,13 +214,13 @@ int32_t GPUReconstructionOCL::InitDevice_Runtime() } if (pos == std::string::npos) { deviceOK = false; - deviceFailure += std::format(" - No SPIR-V {} ({})", GPUCA_OCL_SPIRV_VERSION, device_il_version); + deviceFailure += std::format(" - No SPIR-V {} ({})", GPUCA_OCL_SPIRV_VERSION, dev.ilVersion); } } - double deviceSpeed = (double)device_freq * (double)device_shaders; + double deviceSpeed = (double)dev.freq * (double)dev.shaders; if (GetProcessingSettings().debugLevel >= 2 && !GetProcessingSettings().debugSilent) { - GPUInfo(" Device %s%2d: %s %s (Frequency %d, Shaders %d, %d bit) (Speed Value: %ld)%s %s", deviceOK ? " " : "[", i, device_vendor.c_str(), device_name.c_str(), (int32_t)device_freq, (int32_t)device_shaders, (int32_t)device_nbits, (int64_t)deviceSpeed, deviceOK ? " " : " ]", deviceOK ? "" : deviceFailure.c_str()); + GPUInfo(" Device %s%2d: %s %s (Frequency %d, Shaders %d, %d bit) (Speed Value: %ld)%s %s", deviceOK ? " " : "[", i, dev.vendor.c_str(), dev.name.c_str(), (int32_t)dev.freq, (int32_t)dev.shaders, (int32_t)dev.nbits, (int64_t)deviceSpeed, deviceOK ? " " : " ]", deviceOK ? "" : deviceFailure.c_str()); } if (!deviceOK) { if (GetProcessingSettings().deviceNum >= 0) { @@ -233,24 +252,21 @@ int32_t GPUReconstructionOCL::InitDevice_Runtime() mInternals->platform = platforms[bestPlatform]; GPUChkErr(clGetDeviceIDs(mInternals->platform, CL_DEVICE_TYPE_ALL, devices.size(), devices.data(), nullptr)); mInternals->device = devices[bestDevice]; - queryDevice(mInternals->device); - - cl_ulong deviceConstantBuffer, deviceGlobalMem, deviceLocalMem; - std::string deviceVersion; - size_t deviceMaxWorkGroup, deviceMaxWorkItems[3]; - clGetDeviceInfo(mInternals->device, CL_DEVICE_GLOBAL_MEM_SIZE, sizeof(deviceGlobalMem), &deviceGlobalMem, nullptr); - clGetDeviceInfo(mInternals->device, CL_DEVICE_MAX_CONSTANT_BUFFER_SIZE, sizeof(deviceConstantBuffer), &deviceConstantBuffer, nullptr); - clGetDeviceInfo(mInternals->device, CL_DEVICE_LOCAL_MEM_SIZE, sizeof(deviceLocalMem), &deviceLocalMem, nullptr); - clGetDeviceInfo(mInternals->device, CL_DEVICE_MAX_WORK_GROUP_SIZE, sizeof(deviceMaxWorkGroup), &deviceMaxWorkGroup, nullptr); - clGetDeviceInfo(mInternals->device, CL_DEVICE_MAX_WORK_ITEM_SIZES, sizeof(deviceMaxWorkItems), deviceMaxWorkItems, nullptr); - deviceVersion = query(clGetDeviceInfo, mInternals->device, CL_DEVICE_VERSION); + dev = queryDevice(mInternals->device); + + const cl_ulong deviceGlobalMem = internal::clInfo(clGetDeviceInfo, mInternals->device, CL_DEVICE_GLOBAL_MEM_SIZE); + const cl_ulong deviceConstantBuffer = internal::clInfo(clGetDeviceInfo, mInternals->device, CL_DEVICE_MAX_CONSTANT_BUFFER_SIZE); + const cl_ulong deviceLocalMem = internal::clInfo(clGetDeviceInfo, mInternals->device, CL_DEVICE_LOCAL_MEM_SIZE); + const size_t deviceMaxWorkGroup = internal::clInfo(clGetDeviceInfo, mInternals->device, CL_DEVICE_MAX_WORK_GROUP_SIZE); + const auto deviceMaxWorkItems = internal::clInfo>(clGetDeviceInfo, mInternals->device, CL_DEVICE_MAX_WORK_ITEM_SIZES); + const std::string deviceVersion = internal::clInfo(clGetDeviceInfo, mInternals->device, CL_DEVICE_VERSION); int versionMajor, versionMinor; sscanf(deviceVersion.c_str(), "OpenCL %d.%d", &versionMajor, &versionMinor); if (GetProcessingSettings().debugLevel >= 2) { - GPUInfo("Using OpenCL platform %d / device %d: %s %s with properties:", bestPlatform, bestDevice, device_vendor.c_str(), device_name.c_str()); - GPUInfo("\tVersion = %s", deviceVersion); - GPUInfo("\tFrequency = %d", (int32_t)device_freq); - GPUInfo("\tShaders = %d", (int32_t)device_shaders); + GPUInfo("Using OpenCL platform %d / device %d: %s %s with properties:", bestPlatform, bestDevice, dev.vendor.c_str(), dev.name.c_str()); + GPUInfo("\tVersion = %s", deviceVersion.c_str()); + GPUInfo("\tFrequency = %d", (int32_t)dev.freq); + GPUInfo("\tShaders = %d", (int32_t)dev.shaders); GPUInfo("\tGLobalMemory = %ld", (int64_t)deviceGlobalMem); GPUInfo("\tContantMemoryBuffer = %ld", (int64_t)deviceConstantBuffer); GPUInfo("\tLocalMemory = %ld", (int64_t)deviceLocalMem); @@ -264,9 +280,9 @@ int32_t GPUReconstructionOCL::InitDevice_Runtime() } #endif - mDeviceName = device_name.c_str(); + mDeviceName = dev.name.c_str(); mDeviceName += " (OpenCL)"; - mMultiprocessorCount = device_shaders; + mMultiprocessorCount = dev.shaders; mWarpSize = 32; mMaxBackendThreads = std::max(mMaxBackendThreads, deviceMaxWorkGroup * mMultiprocessorCount); @@ -296,7 +312,7 @@ int32_t GPUReconstructionOCL::InitDevice_Runtime() GPUErrorReturn("OPENCL Constant Memory Allocation Error"); } - if (device_type & CL_DEVICE_TYPE_CPU) { + if (dev.type & CL_DEVICE_TYPE_CPU) { if (GetProcessingSettings().deviceTimers && GetProcessingSettings().debugLevel >= 2) { GPUInfo("Disabling device timers for CPU device"); } @@ -341,9 +357,7 @@ int32_t GPUReconstructionOCL::InitDevice_Runtime() } ocl_error = clBuildProgram(program, 1, &mInternals->device, "", nullptr, nullptr); if (GPUChkErrI(ocl_error)) { - char build_log[16384]; - clGetProgramBuildInfo(program, mInternals->device, CL_PROGRAM_BUILD_LOG, 16384, build_log, nullptr); - GPUImportant("Build Log:\n\n%s\n\n", build_log); + GPUImportant("Build Log:\n\n%s\n\n", internal::clInfo(clGetProgramBuildInfo, program, mInternals->device, CL_PROGRAM_BUILD_LOG).c_str()); PrintPoCLHint(); GPUErrorReturn("Error compiling program"); } @@ -376,7 +390,7 @@ int32_t GPUReconstructionOCL::InitDevice_Runtime() memset(mHostMemoryBase, 0xDD, mHostMemorySize); } - GPUInfo("OPENCL Initialisation successfull (%d: %s %s (Frequency %d, Shaders %d), %ld / %ld bytes host / global memory, Stack frame %d, Constant memory %ld)", bestDevice, device_vendor, device_name, (int32_t)device_freq, (int32_t)device_shaders, (int64_t)mDeviceMemorySize, (int64_t)mHostMemorySize, -1, (int64_t)gGPUConstantMemBufferSize); + GPUInfo("OPENCL Initialisation successfull (%d: %s %s (Frequency %d, Shaders %d), %ld / %ld bytes host / global memory, Stack frame %d, Constant memory %ld)", bestDevice, dev.vendor.c_str(), dev.name.c_str(), (int32_t)dev.freq, (int32_t)dev.shaders, (int64_t)mHostMemorySize, (int64_t)mDeviceMemorySize, -1, (int64_t)gGPUConstantMemBufferSize); } else { GPUReconstructionOCL* master = dynamic_cast(mMaster); mMultiprocessorCount = master->mMultiprocessorCount; @@ -551,12 +565,7 @@ int32_t GPUReconstructionOCL::GetOCLPrograms() if (GPUChkErrI(clBuildProgram(mInternals->program, 1, &mInternals->device, oclBuildFlags, nullptr, nullptr))) { cl_build_status status; if (GPUChkErrI(clGetProgramBuildInfo(mInternals->program, mInternals->device, CL_PROGRAM_BUILD_STATUS, sizeof(status), &status, nullptr)) == 0 && status == CL_BUILD_ERROR) { - size_t log_size; - clGetProgramBuildInfo(mInternals->program, mInternals->device, CL_PROGRAM_BUILD_LOG, 0, nullptr, &log_size); - std::unique_ptr build_log(new char[log_size + 1]); - clGetProgramBuildInfo(mInternals->program, mInternals->device, CL_PROGRAM_BUILD_LOG, log_size, build_log.get(), nullptr); - build_log[log_size] = 0; - GPUError("Build Log:\n\n%s\n", build_log.get()); + GPUError("Build Log:\n\n%s\n", internal::clInfo(clGetProgramBuildInfo, mInternals->program, mInternals->device, CL_PROGRAM_BUILD_LOG).c_str()); } PrintPoCLHint(); return 1; From a352fd56e7628c03ef68ff54f6c3924294b334cb Mon Sep 17 00:00:00 2001 From: David Rohr Date: Tue, 1 Dec 2026 18:33:47 +0100 Subject: [PATCH 20/41] TPCFastTransform: Fix typo --- GPU/Utils/SplineSpec.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/GPU/Utils/SplineSpec.h b/GPU/Utils/SplineSpec.h index c306ae4240e03..3b7066e3c983e 100644 --- a/GPU/Utils/SplineSpec.h +++ b/GPU/Utils/SplineSpec.h @@ -286,7 +286,7 @@ class SplineSpec : public SplineContainer const auto maxXdim = maxXdimTmp.get(); const auto nYdimTmp = SplineUtil::getNdim(mYdim); const auto nYdim = nYdimTmp.get(); - const auto maxYdimTmp = SplineUtil::getMaxNdim(mYdim); + const auto maxYdimTmp = SplineUtil::getMaxNdim(mYdim); const auto maxYdim = maxYdimTmp.get(); // const auto nParameters = 1 << (2 * nXdim); //total Nr of Parameters necessary for one interpolation From ef3a6d54732dd2d4e49f4d3a9608eb6e0e47c395 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Tue, 1 Dec 2026 18:34:28 +0100 Subject: [PATCH 21/41] GPU Benchmark: Fix invalid string comparisons based on const char* comparison --- GPU/GPUbenchmark/Shared/Utils.h | 16 +++++++--------- 1 file changed, 7 insertions(+), 9 deletions(-) diff --git a/GPU/GPUbenchmark/Shared/Utils.h b/GPU/GPUbenchmark/Shared/Utils.h index fc3345a704b65..aa1fa4a8dd267 100644 --- a/GPU/GPUbenchmark/Shared/Utils.h +++ b/GPU/GPUbenchmark/Shared/Utils.h @@ -22,7 +22,7 @@ #include #include #include -#include +#include #include #include #include @@ -137,19 +137,17 @@ inline std::ostream& operator<<(std::ostream& os, KernelConfig config) template inline std::string getType() { - if (typeid(T).name() == typeid(int8_t).name()) { + if constexpr (std::is_same_v) { return std::string{"int8_t"}; - } - if (typeid(T).name() == typeid(size_t).name()) { + } else if constexpr (std::is_same_v) { return std::string{"uint64_t"}; - } - if (typeid(T).name() == typeid(int32_t).name()) { + } else if constexpr (std::is_same_v) { return std::string{"int32_t"}; - } - if (typeid(T).name() == typeid(int4).name()) { + } else if constexpr (std::is_same_v) { return std::string{"int4"}; + } else { + return std::string{"unknown"}; } - return std::string{"unknown"}; } inline std::string getTestName(Mode mode, Test test, KernelConfig blocks) From 510ee40f88163cd9df44dd13ad5b495e05a846eb Mon Sep 17 00:00:00 2001 From: David Rohr Date: Tue, 1 Dec 2026 18:34:55 +0100 Subject: [PATCH 22/41] GPU: Fix asserts that never triggered --- GPU/GPUTracking/Refit/GPUTrackingRefit.cxx | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/GPU/GPUTracking/Refit/GPUTrackingRefit.cxx b/GPU/GPUTracking/Refit/GPUTrackingRefit.cxx index 2edc6e155b58e..3f560edf1017e 100644 --- a/GPU/GPUTracking/Refit/GPUTrackingRefit.cxx +++ b/GPU/GPUTracking/Refit/GPUTrackingRefit.cxx @@ -200,7 +200,7 @@ GPUd() int32_t GPUTrackingRefit::RefitTrack(T& trkX, bool outward, bool resetCov tOffset = trkX.time0; eLossSign = trkX.eLossSign; } else { - static_assert("Invalid template"); + static_assert(sizeof(T) == 0, "Invalid template"); } if constexpr (std::is_same_v) { CADEBUG(printf("\t%21sInit Alpha %8.3f , X %8.3f - Y %8.3f, Z %8.3f - QPt %7.2f (%7.2f), SP %5.2f (%5.2f) --- Cov sY %8.3f sZ %8.3f sSP %8.3f sPt %8.3f\n", "", prop.GetAlpha(), trk.GetX(), trk.Par()[0], trk.Par()[1], trk.Par()[4], prop.GetQPt0(), trk.Par()[2], prop.GetSinPhi0(), sqrtf(trk.Cov()[0]), sqrtf(trk.Cov()[2]), sqrtf(trk.Cov()[5]), sqrtf(trk.Cov()[14]))); @@ -245,7 +245,7 @@ GPUd() int32_t GPUTrackingRefit::RefitTrack(T& trkX, bool outward, bool resetCov cl = &TrackTPC::getCluster(mPtrackHitReferences, i, *mPclusterNative, sector, row, trkX.clusRef); nextState = mPclusterState[cl - mPclusterNative->clustersLinear]; } else { - static_assert("Invalid template"); + static_assert(sizeof(T) == 0, "Invalid template"); } } if (clusters == 0 || (row == currentRow && sector == currentSector)) { @@ -356,7 +356,7 @@ GPUd() int32_t GPUTrackingRefit::RefitTrack(T& trkX, bool outward, bool resetCov } CADEBUG(printf("\t%21sFit Alpha %8.3f , X %8.3f - Y %8.3f, Z %8.3f - QPt %7.2f (%7.2f), SP %5.2f (%5.2f), DzDs %5.2f %16s --- Cov sY %8.3f sZ %8.3f sSP %8.3f sPt %8.3f - YPt %8.3f\n", "", trk.getAlpha(), x, trk.getParams()[0], trk.getParams()[1], trk.getParams()[4], trk.getParams()[4], trk.getParams()[2], trk.getParams()[2], trk.getParams()[3], "", sqrtf(trk.getCov()[0]), sqrtf(trk.getCov()[2]), sqrtf(trk.getCov()[5]), sqrtf(trk.getCov()[14]), trk.getCov()[10])); } else { - static_assert("Invalid template"); + static_assert(sizeof(S) == 0, "Invalid template"); } resetCov = false; nFitted++; @@ -378,7 +378,7 @@ GPUd() int32_t GPUTrackingRefit::RefitTrack(T& trkX, bool outward, bool resetCov } } } else { - static_assert("Invalid template"); + static_assert(sizeof(S) == 0, "Invalid template"); } storeTrack>(trkX, trk, prop, TrackParCovChi2); From 2d46a09a3806acb2575ede21dc8a5640f1d9445c Mon Sep 17 00:00:00 2001 From: David Rohr Date: Tue, 1 Dec 2026 18:40:23 +0100 Subject: [PATCH 23/41] GPU TPC: Fix debug code using MC in track merger --- GPU/GPUTracking/Merger/GPUTPCGMMerger.cxx | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/GPU/GPUTracking/Merger/GPUTPCGMMerger.cxx b/GPU/GPUTracking/Merger/GPUTPCGMMerger.cxx index ad100256cd887..7314f2bf55425 100644 --- a/GPU/GPUTracking/Merger/GPUTPCGMMerger.cxx +++ b/GPU/GPUTracking/Merger/GPUTPCGMMerger.cxx @@ -17,13 +17,14 @@ // #define GPUCA_CADEBUG_ENABLED #include "GPUCommonDef.h" -#include "GPUDef.h" #if !defined(GPUCA_GPUCODE) && (defined(GPUCA_MERGER_BY_MC_LABEL) || defined(GPUCA_CADEBUG_ENABLED) || GPUCA_MERGE_LOOPER_MC) -#include "AliHLTTPCClusterMCData.h" #include "GPUROOTDump.h" +#include "AliHLTTPCClusterMCData.h" #endif +#include "GPUDef.h" + #ifndef GPUCA_GPUCODE_DEVICE #include #include @@ -190,7 +191,7 @@ int64_t GPUTPCGMMerger::GetTrackLabelA(const S& trk) const { GPUTPCGMSectorTrack* sectorTrack = nullptr; int32_t nClusters = 0; - if constexpr (std::is_same_v) { + if constexpr (std::is_same_v) { sectorTrack = &mSectorTrackInfos[trk.TrackID()]; nClusters = sectorTrack->OrigTrack(this)->NHits(); } else if constexpr (std::is_same_v) { @@ -201,7 +202,7 @@ int64_t GPUTPCGMMerger::GetTrackLabelA(const S& trk) const auto acc = GPUTPCTrkLbl(resolveMCLabels(GetConstantMem()->ioPtrs.clustersNative ? GetConstantMem()->ioPtrs.clustersNative->clustersMCTruth : nullptr, GetConstantMem()->ioPtrs.mcLabelsTPC), 0.5f); for (int32_t i = 0; i < nClusters; i++) { int32_t id; - if constexpr (std::is_same_v) { + if constexpr (std::is_same_v) { const GPUTPCTracker& tracker = GetConstantMem()->tpcTrackers[sectorTrack->Sector()]; const GPUTPCHitId& ic = tracker.TrackHits()[sectorTrack->OrigTrack(this)->FirstHitID() + i]; id = tracker.Data().ClusterDataIndex(tracker.Data().Row(ic.RowIndex()), ic.HitIndex()) + GetConstantMem()->ioPtrs.clustersNative->clusterOffset[sectorTrack->Sector()][0]; From 96d1df4d3bb1dbcc1057c3836957394b0a1e61e2 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Tue, 1 Dec 2026 18:45:36 +0100 Subject: [PATCH 24/41] GPU OpenCL: Fix 8 / 16 bit work group operations --- GPU/Common/GPUCommonAlgorithm.h | 16 +++------------- 1 file changed, 3 insertions(+), 13 deletions(-) diff --git a/GPU/Common/GPUCommonAlgorithm.h b/GPU/Common/GPUCommonAlgorithm.h index 9c0ef8a31ed6b..797b9cee1e273 100644 --- a/GPU/Common/GPUCommonAlgorithm.h +++ b/GPU/Common/GPUCommonAlgorithm.h @@ -357,24 +357,14 @@ GPUhdi() I GPUCommonAlgorithm::partitionPoint(I first, I count, const P& pred) #pragma OPENCL EXTENSION cl_khr_subgroups : enable template -GPUdi() T warp_scan_inclusive_add_FUNC(T v) +GPUdi() auto warp_scan_inclusive_add_FUNC(T v) -> decltype(+v) // OpenCL has no 8 / 16 bit subgroup operations: widen, and return the sum promoted (callers pass !!pred, a bool would truncate it) { - return sub_group_scan_inclusive_add(v); -} -template <> // FIXME: It seems OpenCL does not support 8 and 16 bit subgroup operations -GPUdi() uint8_t warp_scan_inclusive_add_FUNC(uint8_t v) -{ - return sub_group_scan_inclusive_add((uint32_t)v); + return sub_group_scan_inclusive_add(+v); } template GPUdi() T warp_broadcast_FUNC(T v, int32_t i) { - return sub_group_broadcast(v, i); -} -template <> -GPUdi() uint8_t warp_broadcast_FUNC(uint8_t v, int32_t i) -{ - return sub_group_broadcast((uint32_t)v, i); + return (T)sub_group_broadcast(+v, i); } #define warp_scan_inclusive_add(v) warp_scan_inclusive_add_FUNC(v) From e428b395c5ce8cfe0ac46f0620661b15278f0a72 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Tue, 1 Dec 2026 20:32:08 +0100 Subject: [PATCH 25/41] GPU Refit: Add option to refit O2 tracks instead of GPU tracks --- .../Definitions/GPUSettingsList.template | 1 + .../Definitions/Parameters/GPUParameters.csv | 2 + .../Global/GPUChainTrackingRefit.cxx | 37 +++++++++++--- GPU/GPUTracking/Refit/GPUTrackingRefit.h | 2 + .../Refit/GPUTrackingRefitKernel.cxx | 51 +++++++++++++------ .../Refit/GPUTrackingRefitKernel.h | 2 + GPU/GPUTracking/kernels.cmake | 2 + 7 files changed, 75 insertions(+), 22 deletions(-) diff --git a/GPU/GPUTracking/Definitions/GPUSettingsList.template b/GPU/GPUTracking/Definitions/GPUSettingsList.template index d8575c7a7bea3..82d311f82f18a 100644 --- a/GPU/GPUTracking/Definitions/GPUSettingsList.template +++ b/GPU/GPUTracking/Definitions/GPUSettingsList.template @@ -230,6 +230,7 @@ AddOptionRTC(fitInProjections, int8_t, -1, "", 0, "Fit in projection, -1 fits al AddOptionRTC(fitPropagateBzOnly, int8_t, -1, "", 0, "Propagate using Bz only for n passes") AddOptionRTC(useMatLUT, int8_t, 0, "", 0, "Use material lookup table for TPC refit") AddOptionRTC(trackingRefitGPUModel, int8_t, 1, "", 0, "Use GPU track model for the Global Track Refit") +AddOption(trackingRefitO2Tracks, int8_t, 0, "", 0, "Run the Global Track Refit on the O2 output tracks (TrackTPC) of the merger instead of the merged GPU tracks") AddOptionRTC(enableCyclicGraphWorkarounds, int8_t, 0, "", 0, "Apply workarounds to avoid cyclic merge graphs, should not be needed") AddCustomCPP(void SetMinTrackPtB5(float v) { maxTrackQPtB5 = v > 0.001f ? (1.f / v) : (1.f / 0.001f); }) AddSubConfig(GPUSettingsRecTPC, tpc) diff --git a/GPU/GPUTracking/Definitions/Parameters/GPUParameters.csv b/GPU/GPUTracking/Definitions/Parameters/GPUParameters.csv index 87d7ba961540b..681af7e750025 100644 --- a/GPU/GPUTracking/Definitions/Parameters/GPUParameters.csv +++ b/GPU/GPUTracking/Definitions/Parameters/GPUParameters.csv @@ -80,6 +80,8 @@ GPUTPCCFClusterizer,512,,"[448, 3]","[512, 2]",,,,,,"[608, 3]",,736,"[192, 3]",, GPUTPCNNClusterizerKernels,512,,,,,,,,,,,,,,,,,, GPUTrackingRefitKernel_mode0asGPU,256,,,,,,,,,256,,256,256,,256,,256,256, GPUTrackingRefitKernel_mode1asTrackParCov,256,,,,,,,,,256,,256,256,,256,,256,256, +GPUTrackingRefitKernel_mode2O2asGPU,256,,,,,,,,,256,,256,256,,256,,256,256, +GPUTrackingRefitKernel_mode3O2asTrackParCov,256,,,,,,,,,256,,256,256,,256,,256,256, GPUMemClean16,"[""GPUCA_THREAD_COUNT_DEFAULT"", 1]",,,,,,,,,"[512, 1]",,"[512, 1]","[512, 1]",,"[256, 1]",,,"[256, 1]", GPUitoa,"[""GPUCA_THREAD_COUNT_DEFAULT"", 1]",,,,,,,,,"[512, 1]",,"[512, 1]","[512, 1]",,"[256, 1]",,,"[256, 1]", GPUTPCCFNoiseSuppression_noiseSuppression,"""GPUCA_LB_GPUTPCCFNoiseSuppression""",,,,,,,,,,,,,,,,448,, diff --git a/GPU/GPUTracking/Global/GPUChainTrackingRefit.cxx b/GPU/GPUTracking/Global/GPUChainTrackingRefit.cxx index 62d35df61414c..cf87bd3c7d472 100644 --- a/GPU/GPUTracking/Global/GPUChainTrackingRefit.cxx +++ b/GPU/GPUTracking/Global/GPUChainTrackingRefit.cxx @@ -19,12 +19,21 @@ #include "GPUTrackingRefit.h" #include "GPUConstantMem.h" #include "GPUTrackingRefitKernel.h" +#include "GPUChainTrackingDebug.h" +#include "DetectorsBase/Propagator.h" +#include using namespace o2::gpu; int32_t GPUChainTracking::RunRefit() { bool doGPU = GetRecoStepsGPU() & RecoStep::Refit; + if (!param().rec.trackingRefitGPUModel && (GetO2Propagator() == nullptr || GetO2Propagator()->getMatLUT() == nullptr)) { + throw std::runtime_error("Track refit with the TrackParCov model (trackingRefitGPUModel = 0) needs the material LUT, but none is loaded"); + } + if (GetRecoStepsGPU() & RecoStep::TPCMerging) { + SynchronizeStream(OutputStream()); // TODO: Fix synchronization: merger does not need to copy if we run the refit in the first place + } GPUTrackingRefitProcessor& Refit = processors()->trackingRefit; GPUTrackingRefitProcessor& RefitShadow = doGPU ? processorsShadow()->trackingRefit : Refit; @@ -32,15 +41,31 @@ int32_t GPUChainTracking::RunRefit() SetupGPUProcessor(&Refit, false); RefitShadow.SetPtrsFromGPUConstantMem(processorsShadow(), doGPU ? &processorsDevice()->param : nullptr); RefitShadow.SetPropagator(doGPU ? processorsShadow()->calibObjects.o2Propagator : GetO2Propagator()); - RefitShadow.mPTracks = (doGPU ? processorsShadow() : processors())->tpcMerger.MergedTracks(); + GPUTPCGMMerger& Merger = processors()->tpcMerger; + GPUTPCGMMerger& MergerShadow = doGPU ? processorsShadow()->tpcMerger : Merger; + const bool o2Tracks = param().rec.trackingRefitO2Tracks; + RefitShadow.mPTracks = MergerShadow.MergedTracks(); + if (o2Tracks) { + RefitShadow.mPTracksO2 = MergerShadow.OutputTracksTPCO2(); + RefitShadow.mNTracksO2 = Merger.NOutputTracksTPCO2(); + RefitShadow.SetTrackHitReferences(MergerShadow.OutputClusRefsTPCO2()); + } WriteToConstantMemory(RecoStep::Refit, (char*)&processors()->trackingRefit - (char*)processors(), &RefitShadow, sizeof(RefitShadow), 0); - // TransferMemoryResourcesToGPU(RecoStep::Refit, &Refit, 0); - if (param().rec.trackingRefitGPUModel) { - runKernel(GetGrid(mIOPtrs.nMergedTracks, 0)); + if (o2Tracks) { + if (param().rec.trackingRefitGPUModel) { + runKernel(GetGrid(Merger.NOutputTracksTPCO2(), 0)); + } else { + runKernel(GetGrid(Merger.NOutputTracksTPCO2(), 0)); + } + TransferMemoryResourceLinkToHost(RecoStep::Refit, Merger.MemoryResOutputO2(), 0); } else { - runKernel(GetGrid(mIOPtrs.nMergedTracks, 0)); + if (param().rec.trackingRefitGPUModel) { + runKernel(GetGrid(mIOPtrs.nMergedTracks, 0)); + } else { + runKernel(GetGrid(mIOPtrs.nMergedTracks, 0)); + } + TransferMemoryResourceLinkToHost(RecoStep::Refit, Merger.MemoryResOutput(), 0); } - // TransferMemoryResourcesToHost(RecoStep::Refit, &Refit, 0); SynchronizeStream(0); return 0; } diff --git a/GPU/GPUTracking/Refit/GPUTrackingRefit.h b/GPU/GPUTracking/Refit/GPUTrackingRefit.h index 10b537781370b..d7fdf2f26302e 100644 --- a/GPU/GPUTracking/Refit/GPUTrackingRefit.h +++ b/GPU/GPUTracking/Refit/GPUTrackingRefit.h @@ -114,6 +114,8 @@ class GPUTrackingRefitProcessor : public GPUTrackingRefit, public GPUProcessor void SetMaxData(const GPUTrackingInOutPointers& io); #endif GPUTPCGMMergedTrack* mPTracks = nullptr; + o2::tpc::TrackTPC* mPTracksO2 = nullptr; + uint32_t mNTracksO2 = 0; }; } // namespace o2::gpu diff --git a/GPU/GPUTracking/Refit/GPUTrackingRefitKernel.cxx b/GPU/GPUTracking/Refit/GPUTrackingRefitKernel.cxx index f99544f239bb7..f5256a583cc63 100644 --- a/GPU/GPUTracking/Refit/GPUTrackingRefitKernel.cxx +++ b/GPU/GPUTracking/Refit/GPUTrackingRefitKernel.cxx @@ -15,6 +15,7 @@ #include "GPUROOTDump.h" #include "GPUTrackingRefitKernel.h" #include "GPUTrackingRefit.h" +#include "DataFormatsTPC/TrackTPC.h" using namespace o2::gpu; @@ -22,24 +23,40 @@ template GPUdii() void GPUTrackingRefitKernel::Thread(int32_t nBlocks, int32_t nThreads, int32_t iBlock, int32_t iThread, GPUsharedref() GPUSharedMemory& smem, processorType& GPUrestrict() processors) { auto& refit = processors.trackingRefit; - for (uint32_t i = get_global_id(0); i < processors.ioPtrs.nMergedTracks; i += get_global_size(0)) { - if (refit.mPTracks[i].OK()) { - GPUTPCGMMergedTrack trk = refit.mPTracks[i]; - int32_t retval; - if constexpr (I == mode0asGPU) { - retval = refit.RefitTrackAsGPU(trk, false, true); - } else if constexpr (I == mode1asTrackParCov) { - retval = refit.RefitTrackAsTrackParCov(trk, false, true); - } - /*#pragma omp critical - if (retval > 0) { - static auto cldump = GPUROOTDump::getNew("org", "refit", "debugTree"); - cldump.Fill(refit.mPTracks[i], trk); - }*/ + auto refitTrack = [&refit](auto& trk) { + if constexpr (I == mode0asGPU || I == mode2O2asGPU) { + return refit.RefitTrackAsGPU(trk, false, true); + } else if constexpr (I == mode1asTrackParCov || I == mode3O2asTrackParCov) { + return refit.RefitTrackAsTrackParCov(trk, false, true); + } else { + static_assert(I == mode0asGPU || I == mode1asTrackParCov || I == mode2O2asGPU || I == mode3O2asTrackParCov, "Invalid refit mode"); + } + }; + if constexpr (I == mode2O2asGPU || I == mode3O2asTrackParCov) { + for (uint32_t i = get_global_id(0); i < refit.mNTracksO2; i += get_global_size(0)) { + o2::tpc::TrackTPC trk = refit.mPTracksO2[i]; + const int32_t retval = refitTrack(trk); if (retval > 0) { - refit.mPTracks[i] = trk; + refit.mPTracksO2[i] = trk; } else { - refit.mPTracks[i].SetOK(false); + refit.mPTracksO2[i].setClusterRef(refit.mPTracksO2[i].getClusterRef().getFirstEntry(), 0); // TrackTPC has no OK flag + } + } + } else { + for (uint32_t i = get_global_id(0); i < processors.ioPtrs.nMergedTracks; i += get_global_size(0)) { + if (refit.mPTracks[i].OK()) { + GPUTPCGMMergedTrack trk = refit.mPTracks[i]; + const int32_t retval = refitTrack(trk); + /*#pragma omp critical + if (retval > 0) { + static auto cldump = GPUROOTDump::getNew("org", "refit", "debugTree"); + cldump.Fill(refit.mPTracks[i], trk); + }*/ + if (retval > 0) { + refit.mPTracks[i] = trk; + } else { + refit.mPTracks[i].SetOK(false); + } } } } @@ -47,4 +64,6 @@ GPUdii() void GPUTrackingRefitKernel::Thread(int32_t nBlocks, int32_t nThreads, #if !defined(GPUCA_GPUCODE) || defined(GPUCA_GPUCODE_DEVICE) // FIXME: DR: WORKAROUND to avoid CUDA bug creating host symbols for device code. template GPUdni() void GPUTrackingRefitKernel::Thread<0>(int32_t nBlocks, int32_t nThreads, int32_t iBlock, int32_t iThread, GPUsharedref() GPUSharedMemory& smem, processorType& GPUrestrict() processors); template GPUdni() void GPUTrackingRefitKernel::Thread<1>(int32_t nBlocks, int32_t nThreads, int32_t iBlock, int32_t iThread, GPUsharedref() GPUSharedMemory& smem, processorType& GPUrestrict() processors); +template GPUdni() void GPUTrackingRefitKernel::Thread<2>(int32_t nBlocks, int32_t nThreads, int32_t iBlock, int32_t iThread, GPUsharedref() GPUSharedMemory& smem, processorType& GPUrestrict() processors); +template GPUdni() void GPUTrackingRefitKernel::Thread<3>(int32_t nBlocks, int32_t nThreads, int32_t iBlock, int32_t iThread, GPUsharedref() GPUSharedMemory& smem, processorType& GPUrestrict() processors); #endif diff --git a/GPU/GPUTracking/Refit/GPUTrackingRefitKernel.h b/GPU/GPUTracking/Refit/GPUTrackingRefitKernel.h index a397e349d29fb..f421fc37a3a67 100644 --- a/GPU/GPUTracking/Refit/GPUTrackingRefitKernel.h +++ b/GPU/GPUTracking/Refit/GPUTrackingRefitKernel.h @@ -29,6 +29,8 @@ class GPUTrackingRefitKernel : public GPUKernelTemplate enum K : int32_t { mode0asGPU = 0, mode1asTrackParCov = 1, + mode2O2asGPU = 2, + mode3O2asTrackParCov = 3, }; template diff --git a/GPU/GPUTracking/kernels.cmake b/GPU/GPUTracking/kernels.cmake index 5bdd95cff3bb2..7487373b73731 100644 --- a/GPU/GPUTracking/kernels.cmake +++ b/GPU/GPUTracking/kernels.cmake @@ -134,6 +134,8 @@ o2_gpu_add_kernel("GPUTPCCFDecodeZSDenseLink" "GPUTP o2_gpu_add_kernel("GPUTPCCFGather" "=" LB o2::tpc::ClusterNative* dest) o2_gpu_add_kernel("GPUTrackingRefitKernel, mode0asGPU" "= GLOBALREFIT " LB) o2_gpu_add_kernel("GPUTrackingRefitKernel, mode1asTrackParCov" "= GLOBALREFIT " LB) +o2_gpu_add_kernel("GPUTrackingRefitKernel, mode2O2asGPU" "= GLOBALREFIT " LB) +o2_gpu_add_kernel("GPUTrackingRefitKernel, mode3O2asTrackParCov" "= GLOBALREFIT " LB) if(onnxruntime_FOUND) o2_gpu_add_kernel("GPUTPCNNClusterizerKernels, runCfClusterizer" "= TPCNNCLUSTERFINDER" LB uint8_t sector int8_t dtype int8_t withMC uint32_t batchStart) o2_gpu_add_kernel("GPUTPCNNClusterizerKernels, fillInputNNCPU" "= TPCNNCLUSTERFINDER" LB uint8_t sector int8_t dtype int8_t withMC uint32_t batchStart) From c1d49bd77269a625097be7d35824f1892343ce71 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Tue, 1 Dec 2026 20:34:24 +0100 Subject: [PATCH 26/41] GPU: Add debugDump option for refitted tracks --- GPU/GPUTracking/Definitions/GPUSettingsList.template | 2 +- GPU/GPUTracking/Global/GPUChainTrackingDebug.h | 3 ++- GPU/GPUTracking/Global/GPUChainTrackingMerger.cxx | 4 ++-- GPU/GPUTracking/Global/GPUChainTrackingRefit.cxx | 5 +++++ GPU/GPUTracking/Merger/GPUTPCGMMerger.h | 4 ++-- GPU/GPUTracking/Merger/GPUTPCGMMergerDump.cxx | 8 ++++---- 6 files changed, 16 insertions(+), 10 deletions(-) diff --git a/GPU/GPUTracking/Definitions/GPUSettingsList.template b/GPU/GPUTracking/Definitions/GPUSettingsList.template index 82d311f82f18a..9b2d6e2b87b97 100644 --- a/GPU/GPUTracking/Definitions/GPUSettingsList.template +++ b/GPU/GPUTracking/Definitions/GPUSettingsList.template @@ -377,7 +377,7 @@ AddOption(trdTrackModelO2, bool, false, "", 0, "Use O2 track model instead of GP AddOption(debugLevel, int32_t, -1, "debug", 'd', "Set debug level (-2 = silent, -1 = autoselect (-2 for O2, 0 for standalone))") AddOption(debugSilent, int32_t, 0, "", 0, "Silence many debug messages, but still run the debug path", def(1)) AddOption(allocDebugLevel, int32_t, 0, "allocDebug", 0, "Some debug output for memory allocations (without messing with normal debug level)") -AddOption(debugMask, uint32_t, ((1 << 18) - 1) | (1 << 24), "debugMask", 0, "Mask for debug output dumps to file") +AddOption(debugMask, uint32_t, ((1 << 18) - 1) | (1 << 24) | (1 << 25), "debugMask", 0, "Mask for debug output dumps to file") AddOption(debugLogSuffix, std::string, "", "debugSuffix", 0, "Suffix for debug log files with --debug 6") AddOption(debugDumpFinal, bool, false, "", 0, "When using --debug < 6, dump the final output") AddOption(debugDumpChecksum, bool, false, "", 0, "When using --debug 6 or debugDumpFinal, log only the checksum instead of writing the full dump to a file") diff --git a/GPU/GPUTracking/Global/GPUChainTrackingDebug.h b/GPU/GPUTracking/Global/GPUChainTrackingDebug.h index c9eff9e9347de..0f77556505be9 100644 --- a/GPU/GPUTracking/Global/GPUChainTrackingDebug.h +++ b/GPU/GPUTracking/Global/GPUChainTrackingDebug.h @@ -47,7 +47,8 @@ enum GPUChainTrackingDebugFlags : uint32_t { TPCClustererChargeMap = 1 << 21, TPCClustererChargeMapSplit = 1 << 22, TPCClustererZeroedCharges = 1 << 23, - TPCOccupancyMap = 1 << 24 + TPCOccupancyMap = 1 << 24, + TrackingRefit = 1 << 25 }; template diff --git a/GPU/GPUTracking/Global/GPUChainTrackingMerger.cxx b/GPU/GPUTracking/Global/GPUChainTrackingMerger.cxx index 1686fedb41723..8f0b142c74731 100644 --- a/GPU/GPUTracking/Global/GPUChainTrackingMerger.cxx +++ b/GPU/GPUTracking/Global/GPUChainTrackingMerger.cxx @@ -314,7 +314,7 @@ int32_t GPUChainTracking::RunTPCTrackingMerger(bool synchronizeOutput) runKernel({GetGridAuto(followExtrapolationStream ? 1 : 0), krnlRunRangeNone, {followExtrapolationStream ? &mEvents->init : nullptr, followExtrapolationStream ? &mEvents->single : nullptr}}); } - DoDebugAndDump(RecoStep::TPCMerging, GPUChainTrackingDebugFlags::TPCMergingRefit, Merger, &GPUTPCGMMerger::DumpRefit, *mDebugFile); + DoDebugAndDump(RecoStep::TPCMerging, GPUChainTrackingDebugFlags::TPCMergingRefit, Merger, &GPUTPCGMMerger::DumpRefit, *mDebugFile, "TPC Merger Refit"); runKernel({GetGridAuto(0, deviceType), krnlRunRangeNone, {nullptr, followExtrapolationStream ? &mEvents->init : nullptr}}); if (followExtrapolationStream) { ReleaseEvent(mEvents->single); @@ -411,7 +411,7 @@ int32_t GPUChainTracking::RunTPCTrackingMerger(bool synchronizeOutput) TransferMemoryResourceLinkToHost(RecoStep::TPCMerging, Merger.MemoryResOutputO2Clus(), outputStream); ReleaseEvent(mEvents->single); } - DoDebugAndDump(RecoStep::TPCMerging, GPUChainTrackingDebugFlags::TPCMergingRefit, doGPU, Merger, &GPUTPCGMMerger::DumpFinalO2, *mDebugFile); + DoDebugAndDump(RecoStep::TPCMerging, GPUChainTrackingDebugFlags::TPCMergingRefit, doGPU, Merger, &GPUTPCGMMerger::DumpFinalO2, *mDebugFile, "TPC O2 Tracks"); mRec->PopNonPersistentMemory(RecoStep::TPCMerging, qStr2Tag("TPCMERG2")); } #endif diff --git a/GPU/GPUTracking/Global/GPUChainTrackingRefit.cxx b/GPU/GPUTracking/Global/GPUChainTrackingRefit.cxx index cf87bd3c7d472..7c8de4e7cc1c2 100644 --- a/GPU/GPUTracking/Global/GPUChainTrackingRefit.cxx +++ b/GPU/GPUTracking/Global/GPUChainTrackingRefit.cxx @@ -67,5 +67,10 @@ int32_t GPUChainTracking::RunRefit() TransferMemoryResourceLinkToHost(RecoStep::Refit, Merger.MemoryResOutput(), 0); } SynchronizeStream(0); + if (o2Tracks) { + DoDebugAndDump(RecoStep::Refit, GPUChainTrackingDebugFlags::TrackingRefit, false, Merger, &GPUTPCGMMerger::DumpFinalO2, *mDebugFile, "Tracking Refit O2 Tracks"); + } else { + DoDebugAndDump(RecoStep::Refit, GPUChainTrackingDebugFlags::TrackingRefit, false, Merger, &GPUTPCGMMerger::DumpRefit, *mDebugFile, "Tracking Refit"); + } return 0; } diff --git a/GPU/GPUTracking/Merger/GPUTPCGMMerger.h b/GPU/GPUTracking/Merger/GPUTPCGMMerger.h index 63d4f6b842584..0d32839daf55e 100644 --- a/GPU/GPUTracking/Merger/GPUTPCGMMerger.h +++ b/GPU/GPUTracking/Merger/GPUTPCGMMerger.h @@ -253,9 +253,9 @@ class GPUTPCGMMerger : public GPUProcessor void DumpCollected(std::ostream& out) const; void DumpMergeCE(std::ostream& out) const; void DumpFitPrepare(std::ostream& out) const; - void DumpRefit(std::ostream& out) const; + void DumpRefit(std::ostream& out, const char* title = "TPC Merger Refit") const; void DumpFinal(std::ostream& out) const; - void DumpFinalO2(std::ostream& out) const; + void DumpFinalO2(std::ostream& out, const char* title = "TPC O2 Tracks") const; void DumpLoopers(std::ostream& out) const; void DumpInterpolatedHits(std::ostream& out) const; void DumpRebuiltTracks(std::ostream& out) const; diff --git a/GPU/GPUTracking/Merger/GPUTPCGMMergerDump.cxx b/GPU/GPUTracking/Merger/GPUTPCGMMergerDump.cxx index 34d2256332ecf..e5bed33df695e 100644 --- a/GPU/GPUTracking/Merger/GPUTPCGMMergerDump.cxx +++ b/GPU/GPUTracking/Merger/GPUTPCGMMergerDump.cxx @@ -221,11 +221,11 @@ void GPUTPCGMMerger::DumpFitPrepare(std::ostream& out) const out << "\n"; } -void GPUTPCGMMerger::DumpRefit(std::ostream& out) const +void GPUTPCGMMerger::DumpRefit(std::ostream& out, const char* title) const { std::streamsize ss = out.precision(); out << std::setprecision(6); - out << "\nTPC Merger Refit\n"; + out << "\n" << title << "\n"; for (uint32_t i = 0; i < mMemory->nMergedTracks; i++) { const auto& trk = mMergedTracks[i]; if (trk.NClusters() == 0) { @@ -273,9 +273,9 @@ void GPUTPCGMMerger::DumpFinal(std::ostream& out) const out << "\n"; } -void GPUTPCGMMerger::DumpFinalO2(std::ostream& out) const +void GPUTPCGMMerger::DumpFinalO2(std::ostream& out, const char* title) const { - out << "\nTPC O2 Tracks: " << mMemory->nO2Tracks << "\n"; + out << "\n" << title << ": " << mMemory->nO2Tracks << "\n"; for (uint32_t i = 0; i < mMemory->nO2Tracks; i++) { const auto& trk = mOutputTracksTPCO2[i]; out << "Track " << i << ": X " << trk.getX() << " Alpha " << trk.getAlpha() << " Par"; From 6861cf2df516da9c52f654fbf6a10a2e9fc3a20e Mon Sep 17 00:00:00 2001 From: David Rohr Date: Tue, 1 Dec 2026 20:34:55 +0100 Subject: [PATCH 27/41] GPU: Add sanity check to run refit: Tracks must be present --- GPU/GPUTracking/Global/GPUChainTracking.cxx | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/GPU/GPUTracking/Global/GPUChainTracking.cxx b/GPU/GPUTracking/Global/GPUChainTracking.cxx index f8b54c3f50ba2..e0f7e5e0911bb 100644 --- a/GPU/GPUTracking/Global/GPUChainTracking.cxx +++ b/GPU/GPUTracking/Global/GPUChainTracking.cxx @@ -281,6 +281,10 @@ bool GPUChainTracking::ValidateSettings() GPUError("Clusterizer and merger Sanity checks only supported when not running on GPU"); return false; } + if ((GetRecoSteps() & RecoStep::Refit) && param().rec.trackingRefitO2Tracks && (GetProcessingSettings().createO2Output == 0 || ((GetRecoStepsGPU() & RecoStep::Refit) && GetProcessingSettings().clearO2OutputFromGPU))) { + GPUError("trackingRefitO2Tracks needs the O2 track output (createO2Output > 0), and on the GPU it must not be freed (clearO2OutputFromGPU)"); + return false; + } if (mRec->IsGPU() && GetProcessingSettings().debug.tpcMergerFitOnCPUSingleThread) { GPUError("tpcMergerFitOnCPUSingleThread only supported when not running on GPU"); return false; From 31528236a8d6e2e588774ae8b4918a1963460033 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Tue, 1 Dec 2026 20:35:02 +0100 Subject: [PATCH 28/41] GPU: Fix typo --- GPU/GPUTracking/Refit/GPUTrackingRefitKernel.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/GPU/GPUTracking/Refit/GPUTrackingRefitKernel.h b/GPU/GPUTracking/Refit/GPUTrackingRefitKernel.h index f421fc37a3a67..11623dda42ead 100644 --- a/GPU/GPUTracking/Refit/GPUTrackingRefitKernel.h +++ b/GPU/GPUTracking/Refit/GPUTrackingRefitKernel.h @@ -24,7 +24,7 @@ namespace o2::gpu class GPUTrackingRefitKernel : public GPUKernelTemplate { public: - GPUhdi() constexpr static gpudatatypes::RecoStep GetRecoStep() { return gpudatatypes::RecoStep::TPCCompression; } + GPUhdi() constexpr static gpudatatypes::RecoStep GetRecoStep() { return gpudatatypes::RecoStep::Refit; } enum K : int32_t { mode0asGPU = 0, From d76c490372aa75e729924a49b44e64a54c55effb Mon Sep 17 00:00:00 2001 From: David Rohr Date: Tue, 1 Dec 2026 21:24:10 +0100 Subject: [PATCH 29/41] GPU: Modernize C++: Simplify code and reduce lines of code --- .../Merger/GPUTPCGlobalDebugSortKernels.cxx | 69 +++++++++---------- .../TRDTracking/GPUTRDInterfaces.h | 40 +++++------ 2 files changed, 49 insertions(+), 60 deletions(-) diff --git a/GPU/GPUTracking/Merger/GPUTPCGlobalDebugSortKernels.cxx b/GPU/GPUTracking/Merger/GPUTPCGlobalDebugSortKernels.cxx index 2f9f9b83d7fda..59cb5816ae0b3 100644 --- a/GPU/GPUTracking/Merger/GPUTPCGlobalDebugSortKernels.cxx +++ b/GPU/GPUTracking/Merger/GPUTPCGlobalDebugSortKernels.cxx @@ -20,6 +20,37 @@ using namespace o2::gpu; +template // Reorder items in place so that items[j] = old items[perm[j]] (cycle by cycle, perm entries are set to -1), optionally storing the inverse permutation in inv +GPUdi() static void applyPermutation(T* GPUrestrict() items, int32_t* GPUrestrict() perm, S n, int32_t* GPUrestrict() inv) +{ + for (S j = 0; j < n; j++) { + if (perm[j] == (int32_t)j) { + if constexpr (StoreInverse) { + inv[j] = j; + } + } else if (perm[j] >= 0) { + int32_t firstIdx = j; + auto firstItem = items[firstIdx]; + int32_t currIdx = firstIdx; + int32_t sourceIdx = perm[currIdx]; + if constexpr (StoreInverse) { + inv[sourceIdx] = currIdx; + } + do { + perm[currIdx] = -1; + items[currIdx] = items[sourceIdx]; + currIdx = sourceIdx; + sourceIdx = perm[currIdx]; + if constexpr (StoreInverse) { + inv[sourceIdx] = currIdx; + } + } while (sourceIdx != firstIdx); + perm[currIdx] = -1; + items[currIdx] = firstItem; + } + } +} + template <> GPUdii() void GPUTPCGlobalDebugSortKernels::Thread(int32_t nBlocks, int32_t nThreads, int32_t iBlock, int32_t iThread, GPUsharedref() GPUSharedMemory& smem, processorType& GPUrestrict() merger, int8_t) { @@ -71,22 +102,7 @@ GPUdii() void GPUTPCGlobalDebugSortKernels::Thread= 0 && tmp[j] != (int32_t)j) { - int32_t firstIdx = j; - auto firstItem = tracks[firstIdx]; - int32_t currIdx = firstIdx; - int32_t sourceIdx = tmp[currIdx]; - do { - tmp[currIdx] = -1; - tracks[currIdx] = tracks[sourceIdx]; - currIdx = sourceIdx; - sourceIdx = tmp[currIdx]; - } while (sourceIdx != firstIdx); - tmp[currIdx] = -1; - tracks[currIdx] = firstItem; - } - } + applyPermutation(tracks, tmp, n, nullptr); } if (parameter) { return; @@ -125,26 +141,7 @@ GPUdii() void GPUTPCGlobalDebugSortKernels::Thread= 0) { - int32_t firstIdx = j; - auto firstItem = merger.MergedTracks()[firstIdx]; - int32_t currIdx = firstIdx; - int32_t sourceIdx = tmp[currIdx]; - tmp2[sourceIdx] = currIdx; - do { - tmp[currIdx] = -1; - merger.MergedTracks()[currIdx] = merger.MergedTracks()[sourceIdx]; - currIdx = sourceIdx; - sourceIdx = tmp[currIdx]; - tmp2[sourceIdx] = currIdx; - } while (sourceIdx != firstIdx); - tmp[currIdx] = -1; - merger.MergedTracks()[currIdx] = firstItem; - } - } + applyPermutation(merger.MergedTracks(), tmp, n, tmp2); for (int32_t j = 0; j < n; j++) { if (merger.MergedTracks()[j].PrevSegment() >= 0) { merger.MergedTracks()[j].SetPrevSegment(tmp2[merger.MergedTracks()[j].PrevSegment()]); diff --git a/GPU/GPUTracking/TRDTracking/GPUTRDInterfaces.h b/GPU/GPUTracking/TRDTracking/GPUTRDInterfaces.h index 6ef8643215e6d..72c44419fabfd 100644 --- a/GPU/GPUTracking/TRDTracking/GPUTRDInterfaces.h +++ b/GPU/GPUTracking/TRDTracking/GPUTRDInterfaces.h @@ -112,30 +112,8 @@ class trackInterface : public GPUTPCGMTrackParam }; GPUdDefault() trackInterface(const trackInterface& param) = default; GPUdDefault() trackInterface& operator=(const trackInterface& param) = default; - GPUd() trackInterface(const o2::dataformats::TrackTPCITS& param) : GPUTPCGMTrackParam(), mAlpha(param.getParamOut().getAlpha()) - { - SetX(param.getParamOut().getX()); - SetPar(0, param.getParamOut().getY()); - SetPar(1, param.getParamOut().getZ()); - SetPar(2, param.getParamOut().getSnp()); - SetPar(3, param.getParamOut().getTgl()); - SetPar(4, param.getParamOut().getQ2Pt()); - for (int32_t i = 0; i < 15; i++) { - SetCov(i, param.getParamOut().getCov()[i]); - } - } - GPUd() trackInterface(const o2::tpc::TrackTPC& param) : GPUTPCGMTrackParam(), mAlpha(param.getParamOut().getAlpha()) - { - SetX(param.getParamOut().getX()); - SetPar(0, param.getParamOut().getY()); - SetPar(1, param.getParamOut().getZ()); - SetPar(2, param.getParamOut().getSnp()); - SetPar(3, param.getParamOut().getTgl()); - SetPar(4, param.getParamOut().getQ2Pt()); - for (int32_t i = 0; i < 15; i++) { - SetCov(i, param.getParamOut().getCov()[i]); - } - } + GPUd() trackInterface(const o2::dataformats::TrackTPCITS& param) : GPUTPCGMTrackParam() { setFromParamOut(param.getParamOut()); } + GPUd() trackInterface(const o2::tpc::TrackTPC& param) : GPUTPCGMTrackParam() { setFromParamOut(param.getParamOut()); } GPUd() float getX() const { @@ -175,6 +153,20 @@ class trackInterface : public GPUTPCGMTrackParam typedef GPUTPCGMTrackParam baseClass; private: + GPUd() void setFromParamOut(const o2::track::TrackParCov& p) + { + mAlpha = p.getAlpha(); + SetX(p.getX()); + SetPar(0, p.getY()); + SetPar(1, p.getZ()); + SetPar(2, p.getSnp()); + SetPar(3, p.getTgl()); + SetPar(4, p.getQ2Pt()); + for (int32_t i = 0; i < 15; i++) { + SetCov(i, p.getCov()[i]); + } + } + float mAlpha = 0.f; // rotation along phi wrt global coordinate system ClassDefNV(trackInterface, 1); From acc569c5ed141a39220f8e898862e685a20ed4c1 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Tue, 1 Dec 2026 21:32:56 +0100 Subject: [PATCH 30/41] GPU: Modernize C++: Simplify code / remove dead code --- GPU/GPUTracking/DataTypes/TPCPadGainCalib.h | 17 +-------- GPU/GPUTracking/Debug/GPUROOTDump.h | 19 ---------- GPU/GPUTracking/TPCClusterFinder/CfArray2D.h | 40 +++----------------- GPU/GPUTracking/qa/GPUQAHelper.h | 14 ++----- 4 files changed, 11 insertions(+), 79 deletions(-) diff --git a/GPU/GPUTracking/DataTypes/TPCPadGainCalib.h b/GPU/GPUTracking/DataTypes/TPCPadGainCalib.h index b262060cba70e..d51de6b23bf51 100644 --- a/GPU/GPUTracking/DataTypes/TPCPadGainCalib.h +++ b/GPU/GPUTracking/DataTypes/TPCPadGainCalib.h @@ -30,20 +30,6 @@ class CalDet; namespace o2::gpu { -template -struct TPCPadGainCorrectionStepNum { -}; - -template <> -struct TPCPadGainCorrectionStepNum { - static GPUglobalconstexpr() int32_t value = 254; -}; - -template <> -struct TPCPadGainCorrectionStepNum { - static GPUglobalconstexpr() int32_t value = 65534; -}; - struct TPCPadGainCalib { public: #ifndef GPUCA_GPUCODE @@ -104,7 +90,8 @@ struct TPCPadGainCalib { public: float mMinCorrectionFactor = 0.f; float mMaxCorrectionFactor = 2.f; - GPUglobalconstexpr() static int32_t NumOfSteps = TPCPadGainCorrectionStepNum::value; + static_assert(sizeof(T) == 1 || sizeof(T) == 2, "Pad gain correction needs 8 or 16 bit steps"); + GPUglobalconstexpr() static int32_t NumOfSteps = (1 << (8 * sizeof(T))) - 2; // 254 / 65534 for uint8_t / uint16_t GPUdi() SectorPadGainCorrection() { diff --git a/GPU/GPUTracking/Debug/GPUROOTDump.h b/GPU/GPUTracking/Debug/GPUROOTDump.h index 87cbdc2bfbbe7..58819af5fa0aa 100644 --- a/GPU/GPUTracking/Debug/GPUROOTDump.h +++ b/GPU/GPUTracking/Debug/GPUROOTDump.h @@ -31,25 +31,6 @@ class TNtuple; namespace o2::gpu { #if !defined(GPUCA_NO_ROOT) && !defined(GPUCA_GPUCODE) -namespace -{ -template -struct internal_Branch { - template - static void Branch(S* p, Args... args) - { - } -}; -template <> -struct internal_Branch { - template - static void Branch(TTree* p, Args... args) - { - p->Branch(args...); - } -}; -} // namespace - template class GPUROOTDump; diff --git a/GPU/GPUTracking/TPCClusterFinder/CfArray2D.h b/GPU/GPUTracking/TPCClusterFinder/CfArray2D.h index dd5600a8a8cbf..1d46de19fd775 100644 --- a/GPU/GPUTracking/TPCClusterFinder/CfArray2D.h +++ b/GPU/GPUTracking/TPCClusterFinder/CfArray2D.h @@ -17,6 +17,7 @@ #include "clusterFinderDefs.h" #include "CfChargePos.h" +#include "GPUCommonTypeTraits.h" namespace o2::gpu { @@ -84,45 +85,16 @@ class LinearLayout }; template -struct GridSize; - -template <> -struct GridSize<1> { - enum { - Width = 8, - Height = 8, - }; -}; - -template <> -struct GridSize<2> { - enum { - Width = 8, - Height = 4, - }; -}; - -template <> -struct GridSize<4> { +struct GridSize { + static_assert(S == 1 || S == 2 || S == 4, "Invalid element size for tiling layout"); enum { - Width = 4, - Height = 4, + Width = S == 4 ? 4 : 8, + Height = S == 1 ? 8 : 4, }; }; -template -struct TPCMapMemoryLayoutSelector; -template -struct TPCMapMemoryLayoutSelector<0, T> { - using type = LinearLayout; -}; -template -struct TPCMapMemoryLayoutSelector<1, T> { - using type = TilingLayout>; -}; - template -using TPCMapMemoryLayout = typename TPCMapMemoryLayoutSelector::type; +using TPCMapMemoryLayout = std::conditional_t>, LinearLayout>; template using CfArray2D = AbstractCfArray2D>; diff --git a/GPU/GPUTracking/qa/GPUQAHelper.h b/GPU/GPUTracking/qa/GPUQAHelper.h index 6712fd0a603ed..507b845f01618 100644 --- a/GPU/GPUTracking/qa/GPUQAHelper.h +++ b/GPU/GPUTracking/qa/GPUQAHelper.h @@ -127,7 +127,7 @@ struct GPUTPCTrkLbl_ret { int64_t id = -1; GPUTPCTrkLbl_ret() = default; template - GPUTPCTrkLbl_ret(T){}; + GPUTPCTrkLbl_ret(T) {}; #ifndef GPUCA_RUN2 GPUTPCTrkLbl_ret(const MCCompLabel& a) : id(a.getTrackEventSourceID()) {}; #endif @@ -143,11 +143,7 @@ struct GPUTPCTrkLbl_ret { template class S, typename... Args> static inline auto GPUTPCTrkLbl(const S* x, Args... args) { - if constexpr (std::is_same_v) { - return internal::GPUTPCTrkLbl>(x, args...); - } else { - return internal::GPUTPCTrkLbl, U>(x, args...); - } + return internal::GPUTPCTrkLbl, std::conditional_t, T, U>>(x, args...); } template @@ -155,11 +151,7 @@ static inline auto GPUTPCTrkLbl(const AliHLTTPCClusterMCLabel* x, Args... args) { using S = AliHLTTPCClusterMCLabel; using T = AliHLTTPCClusterMCWeight; - if constexpr (std::is_same_v) { - return internal::GPUTPCTrkLbl(x, args...); - } else { - return internal::GPUTPCTrkLbl(x, args...); - } + return internal::GPUTPCTrkLbl, T, U>>(x, args...); } template From 8777337ef98ba0bc0c3497e165f66e0adbb25725 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Tue, 1 Dec 2026 21:33:10 +0100 Subject: [PATCH 31/41] GPU: Modernize C++: Use requires instead of std::enable_if --- GPU/Utils/MultivariatePolynomial.h | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/GPU/Utils/MultivariatePolynomial.h b/GPU/Utils/MultivariatePolynomial.h index 1454194f9e3b4..3ece5adb14748 100644 --- a/GPU/Utils/MultivariatePolynomial.h +++ b/GPU/Utils/MultivariatePolynomial.h @@ -48,15 +48,17 @@ class MultivariatePolynomial : public FlatObject, public MultivariatePolynomialH /// constructor for runtime evaluation of polynomial formula /// \param nDim number of dimensions /// \param degree degree of the polynomial - template ::type = 0> - MultivariatePolynomial(const uint32_t nDim, const uint32_t degree, const bool interactionOnly = false) : MultivariatePolynomialHelper{nDim, degree, interactionOnly}, mNParams{this->getNParameters(degree, nDim, interactionOnly)} + MultivariatePolynomial(const uint32_t nDim, const uint32_t degree, const bool interactionOnly = false) + requires(Dim == 0 && Degree == 0) + : MultivariatePolynomialHelper{nDim, degree, interactionOnly}, mNParams{this->getNParameters(degree, nDim, interactionOnly)} { construct(); } /// constructor for compile time evaluation of polynomial formula - template ::type = 0> - MultivariatePolynomial() : mNParams{this->template getNParameters()} + MultivariatePolynomial() + requires(Dim != 0 && Degree != 0) + : mNParams{this->template getNParameters()} { construct(); } @@ -126,8 +128,8 @@ class MultivariatePolynomial : public FlatObject, public MultivariatePolynomialH /// \param y values which will be fitted of length 'nPoints' /// \param error error of weigths of the points (if empty no weights are applied) /// \param clearPoints perform the fit on new data points - template ::type = 0> void fit(std::vector& x, std::vector& y, std::vector& error, const bool clearPoints) + requires(Dim == 0 && Degree == 0) { const auto vec = MultivariatePolynomialHelper::fit(x, y, error, clearPoints); if (vec.empty()) { From 1c09a9385db3ddeeb80a62ac0fa7fb6b14d213f0 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Tue, 1 Dec 2026 21:39:31 +0100 Subject: [PATCH 32/41] GPU: Code cleanup: use named structs instead of array / tuples --- GPU/GPUTracking/Base/GPUReconstruction.cxx | 42 ++++++++++++------- GPU/GPUTracking/Base/GPUReconstruction.h | 3 +- .../Base/GPUReconstructionTimeframe.cxx | 6 +-- .../Base/GPUReconstructionTimeframe.h | 8 +++- 4 files changed, 39 insertions(+), 20 deletions(-) diff --git a/GPU/GPUTracking/Base/GPUReconstruction.cxx b/GPU/GPUTracking/Base/GPUReconstruction.cxx index 46cfc3e1cf730..317c4ab842de0 100644 --- a/GPU/GPUTracking/Base/GPUReconstruction.cxx +++ b/GPU/GPUTracking/Base/GPUReconstruction.cxx @@ -72,6 +72,15 @@ struct GPUReconstructionPipelineContext { bool workerRunning = false; bool terminate = false; }; + +struct GPUReconstruction::NonPersistentMemoryState { + void* hostPoolEnd; + void* devicePoolEnd; + size_t nIndividualAllocations; + size_t nIndividualDirectAllocations; + uint64_t tag; +}; + } // namespace o2::gpu using namespace o2::gpu; @@ -920,16 +929,16 @@ void GPUReconstruction::PopNonPersistentMemory(RecoStep step, uint64_t tag, cons if (mNonPersistentMemoryStack.size() == 0) { GPUFatal("Trying to pop memory state from empty stack"); } - if (tag != 0 && std::get<4>(mNonPersistentMemoryStack.back()) != tag) { - GPUFatal("Tag mismatch when popping non persistent memory from stack : pop %s vs on stack %s", qTag2Str(tag).c_str(), qTag2Str(std::get<4>(mNonPersistentMemoryStack.back())).c_str()); + if (tag != 0 && mNonPersistentMemoryStack.back().tag != tag) { + GPUFatal("Tag mismatch when popping non persistent memory from stack : pop %s vs on stack %s", qTag2Str(tag).c_str(), qTag2Str(mNonPersistentMemoryStack.back().tag).c_str()); } if (!proc && (GetProcessingSettings().debugLevel >= 3 || GetProcessingSettings().allocDebugLevel) && !GetProcessingSettings().debugSilent && (IsGPU() || GetProcessingSettings().forceHostMemoryPoolSize)) { - printf("Allocated memory after %30s (%8s) (Stack %zu): ", gpudatatypes::RECO_STEP_NAMES[getRecoStepNum(step, true)], qTag2Str(std::get<4>(mNonPersistentMemoryStack.back())).c_str(), mNonPersistentMemoryStack.size()); + printf("Allocated memory after %30s (%8s) (Stack %zu): ", gpudatatypes::RECO_STEP_NAMES[getRecoStepNum(step, true)], qTag2Str(mNonPersistentMemoryStack.back().tag).c_str(), mNonPersistentMemoryStack.size()); PrintMemoryOverview(); printf("%76s", ""); PrintMemoryMax(); } - for (uint32_t i = std::get<2>(mNonPersistentMemoryStack.back()); i < mNonPersistentIndividualAllocations.size(); i++) { + for (uint32_t i = mNonPersistentMemoryStack.back().nIndividualAllocations; i < mNonPersistentIndividualAllocations.size(); i++) { GPUMemoryResource* res = mNonPersistentIndividualAllocations[i]; if (proc && res->mProcessor != proc) { continue; @@ -945,10 +954,11 @@ void GPUReconstruction::PopNonPersistentMemory(RecoStep step, uint64_t tag, cons } if (!proc) { stdspinlock spinlock(mMemoryMutex); - mHostMemoryPoolEnd = std::get<0>(mNonPersistentMemoryStack.back()); - mDeviceMemoryPoolEnd = std::get<1>(mNonPersistentMemoryStack.back()); - mNonPersistentIndividualAllocations.resize(std::get<2>(mNonPersistentMemoryStack.back())); - mNonPersistentIndividualDirectAllocations.resize(std::get<3>(mNonPersistentMemoryStack.back())); + const auto& state = mNonPersistentMemoryStack.back(); + mHostMemoryPoolEnd = state.hostPoolEnd; + mDeviceMemoryPoolEnd = state.devicePoolEnd; + mNonPersistentIndividualAllocations.resize(state.nIndividualAllocations); + mNonPersistentIndividualDirectAllocations.resize(state.nIndividualDirectAllocations); mNonPersistentMemoryStack.pop_back(); } if (!proc && GetProcessingSettings().queryHostMemoryUSS) { @@ -1060,7 +1070,11 @@ void GPUReconstruction::PrintMemoryOverview() void GPUReconstruction::PrintMemoryStatistics() { - std::map> sizes; + struct AllocationSizes { + size_t host = 0, device = 0; + bool permanent = false; + }; + std::map sizes; for (uint32_t i = 0; i < mMemoryResources.size(); i++) { auto& res = mMemoryResources[i]; if (res.mReuse >= 0) { @@ -1068,18 +1082,18 @@ void GPUReconstruction::PrintMemoryStatistics() } auto& x = sizes[res.mName]; if (res.mPtr) { - x[0] += res.mSize; + x.host += res.mSize; } if (res.mPtrDevice) { - x[1] += res.mSize; + x.device += res.mSize; } if (res.mType & GPUMemoryResource::MemoryType::MEMORY_PERMANENT) { - x[2] = 1; + x.permanent = true; } } printf("%59s CPU / %9s GPU\n", "", ""); - for (auto it = sizes.begin(); it != sizes.end(); it++) { - printf("Allocation %50s %s: Size %'14zu / %'14zu\n", it->first.c_str(), it->second[2] ? "P" : " ", it->second[0], it->second[1]); + for (const auto& [name, s] : sizes) { + printf("Allocation %50s %s: Size %'14zu / %'14zu\n", name.c_str(), s.permanent ? "P" : " ", s.host, s.device); } PrintMemoryOverview(); for (uint32_t i = 0; i < mChains.size(); i++) { diff --git a/GPU/GPUTracking/Base/GPUReconstruction.h b/GPU/GPUTracking/Base/GPUReconstruction.h index 4fbe0cd2a259d..1795484f8922b 100644 --- a/GPU/GPUTracking/Base/GPUReconstruction.h +++ b/GPU/GPUTracking/Base/GPUReconstruction.h @@ -403,7 +403,8 @@ class GPUReconstruction std::vector res; }; std::unordered_map mMemoryReuse1to1; - std::vector> mNonPersistentMemoryStack; // hostPoolAddress, devicePoolAddress, individualAllocationCount, directIndividualAllocationCound, tag + struct NonPersistentMemoryState; + std::vector mNonPersistentMemoryStack; std::vector mNonPersistentIndividualAllocations; std::vector> mNonPersistentIndividualDirectAllocations; std::vector> mDirectMemoryChunks; diff --git a/GPU/GPUTracking/Base/GPUReconstructionTimeframe.cxx b/GPU/GPUTracking/Base/GPUReconstructionTimeframe.cxx index fe1a50327dc10..06c7deca7c720 100644 --- a/GPU/GPUTracking/Base/GPUReconstructionTimeframe.cxx +++ b/GPU/GPUTracking/Base/GPUReconstructionTimeframe.cxx @@ -141,7 +141,7 @@ int32_t GPUReconstructionTimeframe::ReadEventShifted(int32_t iEvent, float shift } } - mShiftedEvents.emplace_back(mChain->mIOPtrs, std::move(mChain->mIOMem), mChain->mIOPtrs.clustersNative ? *mChain->mIOPtrs.clustersNative : o2::tpc::ClusterNativeAccess()); + mShiftedEvents.push_back({mChain->mIOPtrs, std::move(mChain->mIOMem), mChain->mIOPtrs.clustersNative ? *mChain->mIOPtrs.clustersNative : o2::tpc::ClusterNativeAccess()}); return nClusters; } @@ -149,7 +149,7 @@ void GPUReconstructionTimeframe::MergeShiftedEvents() { mChain->ClearIOPointers(); for (uint32_t i = 0; i < mShiftedEvents.size(); i++) { - auto& ptr = std::get<0>(mShiftedEvents[i]); + auto& ptr = mShiftedEvents[i].ptrs; for (uint32_t j = 0; j < NSECTORS; j++) { mChain->mIOPtrs.nClusterData[j] += ptr.nClusterData[j]; if (config.overlayRaw) { @@ -184,7 +184,7 @@ void GPUReconstructionTimeframe::MergeShiftedEvents() uint32_t nColOffset = 0; uint32_t nClustersEventOffset[NSECTORS] = {0}; for (uint32_t i = 0; i < mShiftedEvents.size(); i++) { - auto& ptr = std::get<0>(mShiftedEvents[i]); + auto& ptr = mShiftedEvents[i].ptrs; uint32_t inEventOffset = 0; for (uint32_t j = 0; j < NSECTORS; j++) { memcpy((void*)&mChain->mIOMem.clusterData[j][nClustersEventOffset[j]], (void*)ptr.clusterData[j], ptr.nClusterData[j] * sizeof(ptr.clusterData[j][0])); diff --git a/GPU/GPUTracking/Base/GPUReconstructionTimeframe.h b/GPU/GPUTracking/Base/GPUReconstructionTimeframe.h index 14fc949240a7f..aa1c19a2f7211 100644 --- a/GPU/GPUTracking/Base/GPUReconstructionTimeframe.h +++ b/GPU/GPUTracking/Base/GPUReconstructionTimeframe.h @@ -20,7 +20,6 @@ #include "GPUTPCGeometry.h" #include #include -#include namespace o2::tpc { @@ -69,7 +68,12 @@ class GPUReconstructionTimeframe int64_t mEventStride; int32_t mSimBunchNoRepeatEvent; std::vector mEventUsed; - std::vector> mShiftedEvents; + struct ShiftedEvent { + GPUTrackingInOutPointers ptrs; + GPUChainTracking::InOutMemory mem; // keeps the buffers ptrs points to + o2::tpc::ClusterNativeAccess clustersNative; + }; + std::vector mShiftedEvents; }; } // namespace o2::gpu From 461cf51159f998a0c48d03a3d89bc74982a13c51 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Tue, 1 Dec 2026 21:42:29 +0100 Subject: [PATCH 33/41] GPU: Modernize C++: Use fold expressions / parameter expansion instead of recursive helpers --- .../Base/cuda/GPUReconstructionCUDAInternals.h | 8 -------- .../Base/cuda/GPUReconstructionCUDAKernels.cu | 9 +++------ .../Base/opencl/GPUReconstructionOCL.h | 2 -- .../opencl/GPUReconstructionOCLIncludesHost.h | 18 ++++-------------- 4 files changed, 7 insertions(+), 30 deletions(-) diff --git a/GPU/GPUTracking/Base/cuda/GPUReconstructionCUDAInternals.h b/GPU/GPUTracking/Base/cuda/GPUReconstructionCUDAInternals.h index ed58cfb1e3e40..bc27c4dc61a96 100644 --- a/GPU/GPUTracking/Base/cuda/GPUReconstructionCUDAInternals.h +++ b/GPU/GPUTracking/Base/cuda/GPUReconstructionCUDAInternals.h @@ -32,14 +32,6 @@ struct GPUReconstructionCUDAInternals { std::vector> kernelFunctions; // vector of ptrs to RTC kernels cudaStream_t Streams[constants::GPU_MAX_STREAMS]; // Pointer to array of CUDA Streams size_t stackSizeInit = 0; // Stack size limit after initialization, to detect increases by the driver at runtime - - static void getArgPtrs(const void** pArgs) {} - template - static void getArgPtrs(const void** pArgs, const T& arg, const Args&... args) - { - *pArgs = &arg; - getArgPtrs(pArgs + 1, args...); - } }; class GPUDebugTiming diff --git a/GPU/GPUTracking/Base/cuda/GPUReconstructionCUDAKernels.cu b/GPU/GPUTracking/Base/cuda/GPUReconstructionCUDAKernels.cu index d668bc7da1513..285ee72beefce 100644 --- a/GPU/GPUTracking/Base/cuda/GPUReconstructionCUDAKernels.cu +++ b/GPU/GPUTracking/Base/cuda/GPUReconstructionCUDAKernels.cu @@ -42,14 +42,11 @@ inline void GPUReconstructionCUDA::runKernelBackendTimed(const krnlSetupTime& _x { auto& x = _xyz.x; auto& y = _xyz.y; - const void* pArgs[sizeof...(Args) + 3]; // 3 is max: cons mem + y.index + y.num - int32_t arg_offset = 0; + const void* pArgs[] = { #ifdef GPUCA_NO_CONSTANT_MEMORY - arg_offset = 1; - pArgs[0] = &mDeviceConstantMem; + &mDeviceConstantMem, #endif - pArgs[arg_offset] = &y.index; - GPUReconstructionCUDAInternals::getArgPtrs(&pArgs[arg_offset + 1], args...); + &y.index, &args...}; GPUChkErr(cuLaunchKernel(*mInternals->kernelFunctions[GetKernelNum()], x.nBlocks, 1, 1, x.nThreads, 1, 1, 0, mInternals->Streams[x.stream], (void**)pArgs, nullptr)); } } diff --git a/GPU/GPUTracking/Base/opencl/GPUReconstructionOCL.h b/GPU/GPUTracking/Base/opencl/GPUReconstructionOCL.h index d75dc794f9a05..c9f971c43d7b5 100644 --- a/GPU/GPUTracking/Base/opencl/GPUReconstructionOCL.h +++ b/GPU/GPUTracking/Base/opencl/GPUReconstructionOCL.h @@ -72,8 +72,6 @@ class GPUReconstructionOCL : public GPUReconstructionProcessing::KernelInterface private: static const char* convertErrorToString(int32_t errorCode); - template - static inline int64_t OCLsetKernelParameters_helper(cl_kernel& kernel, int32_t i, const T& firstParameter, const Args&... restOfParameters); template static int64_t OCLsetKernelParameters(cl_kernel& kernel, const Args&... args); static int64_t clExecuteKernelA(cl_command_queue queue, cl_kernel krnl, size_t local_size, size_t global_size, cl_event* pEvent = nullptr, cl_event* wait = nullptr, cl_int nWaitEvents = 1); diff --git a/GPU/GPUTracking/Base/opencl/GPUReconstructionOCLIncludesHost.h b/GPU/GPUTracking/Base/opencl/GPUReconstructionOCLIncludesHost.h index 0dac836f6127d..99fbe4f12e7f2 100644 --- a/GPU/GPUTracking/Base/opencl/GPUReconstructionOCLIncludesHost.h +++ b/GPU/GPUTracking/Base/opencl/GPUReconstructionOCLIncludesHost.h @@ -55,23 +55,13 @@ struct GPUReconstructionOCLInternals { }; } // namespace o2::gpu -template -inline int64_t GPUReconstructionOCL::OCLsetKernelParameters_helper(cl_kernel& kernel, int32_t i, const T& firstParameter, const Args&... restOfParameters) -{ - int64_t retVal = clSetKernelArg(kernel, i, sizeof(T), &firstParameter); - if (retVal) { - return retVal; - } - if constexpr (sizeof...(restOfParameters) > 0) { - return OCLsetKernelParameters_helper(kernel, i + 1, restOfParameters...); - } - return 0; -} - template inline int64_t GPUReconstructionOCL::OCLsetKernelParameters(cl_kernel& kernel, const Args&... args) { - return OCLsetKernelParameters_helper(kernel, 0, args...); + int64_t retVal = 0; + cl_uint i = 0; + ((retVal = clSetKernelArg(kernel, i++, sizeof(Args), &args)) || ...); // stops at the first error + return retVal; } inline int64_t GPUReconstructionOCL::clExecuteKernelA(cl_command_queue queue, cl_kernel krnl, size_t local_size, size_t global_size, cl_event* pEvent, cl_event* wait, cl_int nWaitEvents) From 841077c77f08679daed7fe7a1269264a5e66084a Mon Sep 17 00:00:00 2001 From: David Rohr Date: Tue, 1 Dec 2026 21:46:15 +0100 Subject: [PATCH 34/41] GPU: Modernize C++: Use tuple comparators in sort --- .../Base/GPUReconstructionConvert.cxx | 23 +++---------------- .../Base/GPUReconstructionRTCHelpers.inc | 2 +- 2 files changed, 4 insertions(+), 21 deletions(-) diff --git a/GPU/GPUTracking/Base/GPUReconstructionConvert.cxx b/GPU/GPUTracking/Base/GPUReconstructionConvert.cxx index d4fc30dccef17..95e6208a97fac 100644 --- a/GPU/GPUTracking/Base/GPUReconstructionConvert.cxx +++ b/GPU/GPUTracking/Base/GPUReconstructionConvert.cxx @@ -33,6 +33,7 @@ #include #include #include +#include #include "clusterFinderDefs.h" #include "DataFormatsTPC/ZeroSuppression.h" @@ -245,16 +246,7 @@ inline bool zsEncoderRow::sort(const o2::tpc::Digit a, const o2::tpc::Digit b) int32_t endpointb = GPUTPCGeometry::GetRegion(b.getRow()); endpointa = 2 * endpointa + (a.getRow() >= GPUTPCGeometry::GetRegionStart(endpointa) + GPUTPCGeometry::GetRegionRows(endpointa) / 2); endpointb = 2 * endpointb + (b.getRow() >= GPUTPCGeometry::GetRegionStart(endpointb) + GPUTPCGeometry::GetRegionRows(endpointb) / 2); - if (endpointa != endpointb) { - return endpointa <= endpointb; - } - if (a.getTimeStamp() != b.getTimeStamp()) { - return a.getTimeStamp() < b.getTimeStamp(); - } - if (a.getRow() != b.getRow()) { - return a.getRow() < b.getRow(); - } - return a.getPad() < b.getPad(); + return std::tuple{endpointa, a.getTimeStamp(), a.getRow(), a.getPad()} < std::tuple{endpointb, b.getTimeStamp(), b.getRow(), b.getPad()}; } bool zsEncoderRow::checkInput(std::vector& tmpBuffer, uint32_t k) @@ -517,16 +509,7 @@ bool zsEncoderLinkBased::sort(const o2::tpc::Digit a, const o2::tpc::Digit b) int32_t endpointa = 2 * cruinsectora + (fecInPartitiona >= (mapper.getPartitionInfo(cru.partition()).getNumberOfFECs() + 1) / 2); int32_t endpointb = 2 * cruinsectorb + (fecInPartitionb >= (mapper.getPartitionInfo(cru.partition()).getNumberOfFECs() + 1) / 2); - if (endpointa != endpointb) { - return endpointa < endpointb; - } - if (a.getTimeStamp() != b.getTimeStamp()) { - return a.getTimeStamp() < b.getTimeStamp(); - } - if (fecInPartitiona != fecInPartitionb) { - return fecInPartitiona < fecInPartitionb; - } - return inverseChannelMapping[feca.getSampaChip()][feca.getSampaChannel()] < inverseChannelMapping[fecb.getSampaChip()][fecb.getSampaChannel()]; + return std::tuple{endpointa, a.getTimeStamp(), fecInPartitiona, inverseChannelMapping[feca.getSampaChip()][feca.getSampaChannel()]} < std::tuple{endpointb, b.getTimeStamp(), fecInPartitionb, inverseChannelMapping[fecb.getSampaChip()][fecb.getSampaChannel()]}; } // ------------------------------------------------- TPC Improved Link Based ZS ------------------------------------------------- diff --git a/GPU/GPUTracking/Base/GPUReconstructionRTCHelpers.inc b/GPU/GPUTracking/Base/GPUReconstructionRTCHelpers.inc index a9cbd01a54292..2cc4a68258021 100644 --- a/GPU/GPUTracking/Base/GPUReconstructionRTCHelpers.inc +++ b/GPU/GPUTracking/Base/GPUReconstructionRTCHelpers.inc @@ -322,7 +322,7 @@ class Cache // RTC cache file /rtc..cache. (no id with if (fread(&cachedSettings, sizeof(cachedSettings), 1, fp) != 1) { throw std::runtime_error("Cache file corrupt"); } - if (!mProc.rtctech.ignoreCacheValid && !(cachedSettings == mProc.rtc)) { + if (!mProc.rtctech.ignoreCacheValid && cachedSettings != mProc.rtc) { GPUInfo("Cache file content outdated (rtc parameters)"); return false; } From 261048a936175b72f8c3a6077b22002796732532 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Tue, 1 Dec 2026 21:49:14 +0100 Subject: [PATCH 35/41] GPU: Modernize C++: Use std::clamp / popcount / bit_width --- GPU/GPUTracking/Base/GPUReconstruction.cxx | 5 +++-- GPU/GPUTracking/Base/GPUReconstructionCPU.cxx | 7 ++----- GPU/GPUTracking/Base/GPUReconstructionConvert.cxx | 3 ++- GPU/GPUTracking/Base/GPUReconstructionDebug.cxx | 14 ++++++-------- 4 files changed, 13 insertions(+), 16 deletions(-) diff --git a/GPU/GPUTracking/Base/GPUReconstruction.cxx b/GPU/GPUTracking/Base/GPUReconstruction.cxx index 317c4ab842de0..cb22e42fd09a3 100644 --- a/GPU/GPUTracking/Base/GPUReconstruction.cxx +++ b/GPU/GPUTracking/Base/GPUReconstruction.cxx @@ -22,6 +22,7 @@ #include #include #include +#include #include #include "GPUReconstruction.h" @@ -356,7 +357,7 @@ int32_t GPUReconstruction::InitPhaseBeforeDevice() } if (GetProcessingSettings().nTPCClustererLanes == -1) { - mProcessingSettings->nTPCClustererLanes = (GetRecoStepsGPU() & RecoStep::TPCClusterFinding) ? 3 : std::max(1, std::min(GPUTPCGeometry::NSECTORS, GetProcessingSettings().inKernelParallel ? (mMaxHostThreads >= 4 ? std::min(mMaxHostThreads / 2, mMaxHostThreads >= 32 ? GPUTPCGeometry::NSECTORS : 4) : 1) : mMaxHostThreads)); + mProcessingSettings->nTPCClustererLanes = (GetRecoStepsGPU() & RecoStep::TPCClusterFinding) ? 3 : std::clamp(GetProcessingSettings().inKernelParallel ? (mMaxHostThreads >= 4 ? std::min(mMaxHostThreads / 2, mMaxHostThreads >= 32 ? GPUTPCGeometry::NSECTORS : 4) : 1) : mMaxHostThreads, 1, GPUTPCGeometry::NSECTORS); } if (GetProcessingSettings().overrideClusterizerFragmentLen == -1) { mProcessingSettings->overrideClusterizerFragmentLen = ((GetRecoStepsGPU() & RecoStep::TPCClusterFinding) || (mMaxHostThreads / GetProcessingSettings().nTPCClustererLanes >= 3)) ? tpccf::TPC_MAX_FRAGMENT_LEN_GPU : tpccf::TPC_MAX_FRAGMENT_LEN_HOST; @@ -1134,7 +1135,7 @@ template constexpr static inline int32_t getStepNum(T step, bool validCheck, int32_t N, const char* err = "Invalid step num") { static_assert(sizeof(step) == sizeof(uint32_t), "Invalid step enum size"); - int32_t retVal = 8 * sizeof(uint32_t) - 1 - CAMath::Clz((uint32_t)step); + int32_t retVal = std::bit_width((uint32_t)step) - 1; if ((uint32_t)step == 0 || retVal >= N) { if (!validCheck) { return -1; diff --git a/GPU/GPUTracking/Base/GPUReconstructionCPU.cxx b/GPU/GPUTracking/Base/GPUReconstructionCPU.cxx index a2157347275bb..9adaa674d364a 100644 --- a/GPU/GPUTracking/Base/GPUReconstructionCPU.cxx +++ b/GPU/GPUTracking/Base/GPUReconstructionCPU.cxx @@ -147,13 +147,10 @@ GPUConstantMem* GPUReconstructionCPU::DeviceProcessorOnHostView(const krnlSetupT template <> inline void GPUReconstructionCPU::runKernelBackend(const krnlSetupTime& _xyz, void* const& ptr, uint64_t const& size) { - int32_t nThreads = std::max(1, std::min(size / (16 * 1024 * 1024), getNKernelHostThreads(true))); + int32_t nThreads = std::clamp(size / (16 * 1024 * 1024), 1, getNKernelHostThreads(true)); if (nThreads > 1) { tbb::parallel_for(0, nThreads, [&](int iThread) { - size_t threadSize = size / nThreads; - if (threadSize % 4096) { - threadSize += 4096 - threadSize % 4096; - } + size_t threadSize = CAMath::nextMultipleOf<4096>(size / nThreads); size_t offset = threadSize * iThread; size_t mySize = std::min(threadSize, size - offset); if (mySize) { diff --git a/GPU/GPUTracking/Base/GPUReconstructionConvert.cxx b/GPU/GPUTracking/Base/GPUReconstructionConvert.cxx index 95e6208a97fac..7d7b67dd881de 100644 --- a/GPU/GPUTracking/Base/GPUReconstructionConvert.cxx +++ b/GPU/GPUTracking/Base/GPUReconstructionConvert.cxx @@ -34,6 +34,7 @@ #include #include #include +#include #include "clusterFinderDefs.h" #include "DataFormatsTPC/ZeroSuppression.h" @@ -380,7 +381,7 @@ void zsEncoderRow::decodePage(std::vector& outputBuffer, const z } const int32_t rowOffset = GPUTPCGeometry::GetRegionStart(region) + (upperRows ? (nRowsRegion / 2) : 0); const int32_t nRows = upperRows ? (nRowsRegion - nRowsRegion / 2) : (nRowsRegion / 2); - const int32_t nRowsUsed = __builtin_popcount((uint32_t)(tbHdr->rowMask & 0x7FFF)); + const int32_t nRowsUsed = std::popcount((uint32_t)(tbHdr->rowMask & 0x7FFF)); decPagePtr += nRowsUsed ? (2 * nRowsUsed) : 2; int32_t rowPos = 0; for (int32_t m = 0; m < nRows; m++) { diff --git a/GPU/GPUTracking/Base/GPUReconstructionDebug.cxx b/GPU/GPUTracking/Base/GPUReconstructionDebug.cxx index 7d0bb7ef3a998..9de04bcc2c395 100644 --- a/GPU/GPUTracking/Base/GPUReconstructionDebug.cxx +++ b/GPU/GPUTracking/Base/GPUReconstructionDebug.cxx @@ -26,6 +26,7 @@ #include #include #include +#include using namespace o2::gpu; @@ -61,15 +62,12 @@ void GPUReconstruction::debugInit() sa.sa_sigaction = GPUReconstruction::debugInternal::globalCallback; sa.sa_flags = SA_SIGINFO; uint32_t mask = GetProcessingSettings().debugOnFailureSignalMask == (uint32_t)-1 ? ((1 << SIGINT) | (1 << SIGABRT) | (1 << SIGBUS) | (1 << SIGTERM) | (1 << SIGSEGV)) : GetProcessingSettings().debugOnFailureSignalMask; - if (mask) { - for (uint32_t i = 0; i < sizeof(mask) * 8; i++) { - if (mask & (1 << i)) { - if (sigaction(i, &sa, &oldsa)) { - GPUFatal("Error installing signal handler for error dump on signal %d", i); - } - mDebugData->oldActions.emplace(i, oldsa); - } + for (uint32_t m = mask; m; m &= m - 1) { // loop over the set bits + int32_t i = std::countr_zero(m); + if (sigaction(i, &sa, &oldsa)) { + GPUFatal("Error installing signal handler for error dump on signal %d", i); } + mDebugData->oldActions.emplace(i, oldsa); } mDebugData->signalCallback = [this, &oldActions = mDebugData->oldActions, myAction = std::move(sa)](int32_t signal, siginfo_t* info, void* ucontext) { From 78b518f2ac63bf1bf0719688d78f88574ff1eff7 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Tue, 1 Dec 2026 21:58:29 +0100 Subject: [PATCH 36/41] GPU: More C++ modernization --- GPU/GPUTracking/Base/GPUMemoryResource.h | 14 ++++++-------- GPU/GPUTracking/Base/GPUReconstruction.cxx | 14 +++----------- GPU/GPUTracking/Base/GPUReconstruction.h | 3 +-- GPU/GPUTracking/Base/GPUReconstructionCPU.cxx | 14 +++----------- GPU/GPUTracking/Base/GPUReconstructionConvert.cxx | 9 +++++---- GPU/GPUTracking/Base/GPUReconstructionDebug.cxx | 7 +++---- .../Base/GPUReconstructionDeviceBase.cxx | 4 ++-- GPU/GPUTracking/Base/GPUReconstructionLibrary.cxx | 4 ++-- .../Base/GPUReconstructionProcessing.cxx | 2 -- GPU/GPUTracking/Base/GPUReconstructionProcessing.h | 6 +++--- GPU/GPUTracking/Base/cuda/GPUReconstructionCUDA.cu | 5 ++--- 11 files changed, 30 insertions(+), 52 deletions(-) diff --git a/GPU/GPUTracking/Base/GPUMemoryResource.h b/GPU/GPUTracking/Base/GPUMemoryResource.h index 9f1e824488c4d..8fa429dc6b3dc 100644 --- a/GPU/GPUTracking/Base/GPUMemoryResource.h +++ b/GPU/GPUTracking/Base/GPUMemoryResource.h @@ -79,9 +79,7 @@ class GPUMemoryResource ALLOCATION_INDIVIDUAL = 1, // Individual memory allocations with malloc (host only) ALLOCATION_GLOBAL = 2 }; // Allocate memory blocks from large preallocated memory range with internal allocator (host and GPU) - GPUMemoryResource(GPUProcessor* proc, void* (GPUProcessor::*setPtr)(void*), MemoryType type, const char* name = "") : mProcessor(proc), mPtr(nullptr), mPtrDevice(nullptr), mSetPointers(setPtr), mName(name), mSize(0), mOverrideSize(0), mReuse(-1), mType(type) - { - } + GPUMemoryResource(GPUProcessor* proc, void* (GPUProcessor::*setPtr)(void*), MemoryType type, const char* name = "") : mProcessor(proc), mSetPointers(setPtr), mName(name), mType(type) {} GPUMemoryResource(const GPUMemoryResource&) = default; void* SetPointers(void* ptr) const; @@ -94,13 +92,13 @@ class GPUMemoryResource private: GPUProcessor* mProcessor; - void* mPtr; - void* mPtrDevice; + void* mPtr = nullptr; + void* mPtrDevice = nullptr; void* (GPUProcessor::*mSetPointers)(void*); const char* mName; - size_t mSize; - size_t mOverrideSize; - int32_t mReuse; + size_t mSize = 0; + size_t mOverrideSize = 0; + int32_t mReuse = -1; MemoryType mType; }; } // namespace o2::gpu diff --git a/GPU/GPUTracking/Base/GPUReconstruction.cxx b/GPU/GPUTracking/Base/GPUReconstruction.cxx index cb22e42fd09a3..4830fdf8de173 100644 --- a/GPU/GPUTracking/Base/GPUReconstruction.cxx +++ b/GPU/GPUTracking/Base/GPUReconstruction.cxx @@ -86,10 +86,6 @@ struct GPUReconstruction::NonPersistentMemoryState { using namespace o2::gpu; -constexpr const char* const GPUReconstruction::GEOMETRY_TYPE_NAMES[]; -constexpr const char* const GPUReconstruction::IOTYPENAMES[]; -constexpr GPUReconstruction::GeometryType GPUReconstruction::geometryType; - static ptrdiff_t ptrDiff(void* a, void* b) { return (char*)a - (char*)b; } GPUReconstruction::GPUReconstruction(const GPUSettingsDeviceBackend& cfg) : mHostConstantMem(std::make_unique()), mGRPSettings(std::make_unique()), mDeviceBackendSettings(std::make_unique(cfg)), mProcessingSettings(std::make_unique()), mMemoryScalers(std::make_unique()) @@ -545,10 +541,8 @@ int16_t GPUReconstruction::RegisterMemoryAllocationHelper(GPUProcessor* proc, vo } uint16_t retVal = mMemoryResources.size() - 1; if (re.type != GPUMemoryReuse::NONE && !GetProcessingSettings().disableMemoryReuse) { - const auto& it = mMemoryReuse1to1.find(re.id); - if (it == mMemoryReuse1to1.end()) { - mMemoryReuse1to1[re.id] = {proc, retVal}; - } else { + auto [it, inserted] = mMemoryReuse1to1.try_emplace(re.id, proc, retVal); + if (!inserted) { mMemoryResources[retVal].mReuse = it->second.res[0]; it->second.res.emplace_back(retVal); } @@ -1119,9 +1113,7 @@ int32_t GPUReconstruction::unregisterMemoryForGPU(const void* ptr) if (GetProcessingSettings().noGPUMemoryRegistration) { return 0; } - const auto& pos = mRegisteredMemoryPtrs.find(ptr); - if (pos != mRegisteredMemoryPtrs.end()) { - mRegisteredMemoryPtrs.erase(pos); + if (mRegisteredMemoryPtrs.erase(ptr)) { return unregisterMemoryForGPU_internal(ptr); } return 1; diff --git a/GPU/GPUTracking/Base/GPUReconstruction.h b/GPU/GPUTracking/Base/GPUReconstruction.h index 1795484f8922b..c97351aa66701 100644 --- a/GPU/GPUTracking/Base/GPUReconstruction.h +++ b/GPU/GPUTracking/Base/GPUReconstruction.h @@ -389,7 +389,6 @@ class GPUReconstruction // Management for GPUProcessors struct ProcessorData { - ProcessorData(GPUProcessor* p, void (GPUProcessor::*r)(), void (GPUProcessor::*i)(), void (GPUProcessor::*d)(const GPUTrackingInOutPointers&)) : proc(p), RegisterMemoryAllocation(r), InitializeProcessor(i), SetMaxData(d) {} GPUProcessor* proc; void (GPUProcessor::*RegisterMemoryAllocation)(); void (GPUProcessor::*InitializeProcessor)(); @@ -409,7 +408,7 @@ class GPUReconstruction std::vector> mNonPersistentIndividualDirectAllocations; std::vector> mDirectMemoryChunks; std::vector> mVolatileChunks; - std::atomic_flag mMemoryMutex = ATOMIC_FLAG_INIT; + std::atomic_flag mMemoryMutex; std::unique_ptr mPipelineContext; diff --git a/GPU/GPUTracking/Base/GPUReconstructionCPU.cxx b/GPU/GPUTracking/Base/GPUReconstructionCPU.cxx index 9adaa674d364a..14217357d4b85 100644 --- a/GPU/GPUTracking/Base/GPUReconstructionCPU.cxx +++ b/GPU/GPUTracking/Base/GPUReconstructionCPU.cxx @@ -33,6 +33,7 @@ #include "GPUReconstructionProcessingKernels.inc" #include "GPUTPCClusterOccupancyMap.h" +#include #include #include #include @@ -44,9 +45,6 @@ using namespace o2::gpu; -constexpr GPUReconstructionCPU::krnlRunRange GPUReconstructionCPU::krnlRunRangeNone; -constexpr GPUReconstructionCPU::krnlEvent GPUReconstructionCPU::krnlEventNone; - GPUReconstruction* GPUReconstruction::GPUReconstruction_Create_CPU(const GPUSettingsDeviceBackend& cfg) { return new GPUReconstructionCPU(cfg); } GPUReconstructionCPU::~GPUReconstructionCPU() @@ -318,7 +316,7 @@ int32_t GPUReconstructionCPU::RunChains() nEventReport += std::format(" (average of {} runs)", mStatNEvents); } double kernelTotal = 0; - std::vector kernelStepTimes(gpudatatypes::N_RECO_STEPS, 0.); + std::array kernelStepTimes{}; debugWriter writer(GetProcessingSettings().debugCSV, GetProcessingSettings().debugMarkdown, mStatNEvents, GetProcessingSettings().debugSilent); @@ -363,13 +361,7 @@ int32_t GPUReconstructionCPU::RunChains() writer.row('D', mTimersRecoSteps[i].countToHost, std::string(gpudatatypes::RECO_STEP_NAMES[i]) + " (DMA to Host)", mTimersRecoSteps[i].timerToHost.GetElapsedTime(), -1.0, -1.0, mTimersRecoSteps[i].bytesToHost); } if (GetProcessingSettings().resetTimers) { - mTimersRecoSteps[i].bytesToGPU = mTimersRecoSteps[i].bytesToHost = 0; - mTimersRecoSteps[i].timerToGPU.Reset(); - mTimersRecoSteps[i].timerToHost.Reset(); - mTimersRecoSteps[i].timerTotal.Reset(); - mTimersRecoSteps[i].timerCPU = 0; - mTimersRecoSteps[i].countToGPU = 0; - mTimersRecoSteps[i].countToHost = 0; + mTimersRecoSteps[i] = {}; } } for (int32_t i = 0; i < gpudatatypes::N_GENERAL_STEPS; i++) { diff --git a/GPU/GPUTracking/Base/GPUReconstructionConvert.cxx b/GPU/GPUTracking/Base/GPUReconstructionConvert.cxx index 7d7b67dd881de..a5092018ff493 100644 --- a/GPU/GPUTracking/Base/GPUReconstructionConvert.cxx +++ b/GPU/GPUTracking/Base/GPUReconstructionConvert.cxx @@ -1038,6 +1038,7 @@ struct zsEncoderRun : public T { template inline uint32_t zsEncoderRun::run(std::vector* buffer, std::vector& tmpBuffer, size_t* totalSize) { + static constexpr bool isDense = std::is_same_v; uint32_t totalPages = 0; zsPage singleBuffer; #ifndef GPUCA_STANDALONE @@ -1081,7 +1082,7 @@ inline uint32_t zsEncoderRun::run(std::vector* buffer, std::vector) { + if constexpr (isDense) { if ((pagePtr - (uint8_t*)page) % o2::raw::RDHUtils::GBTWord128) { pagePtr += o2::raw::RDHUtils::GBTWord128 - (pagePtr - (uint8_t*)page) % o2::raw::RDHUtils::GBTWord128; } @@ -1118,9 +1119,9 @@ inline uint32_t zsEncoderRun::run(std::vector* buffer, std::vectorRAWLNK); if (totalSize) { - *totalSize += !std::is_same_v && (lastEndpoint == -1 || hbf == nexthbf) ? TPCZSHDR::TPC_ZS_PAGE_SIZE : (pagePtr - (uint8_t*)page); + *totalSize += !isDense && (lastEndpoint == -1 || hbf == nexthbf) ? TPCZSHDR::TPC_ZS_PAGE_SIZE : (pagePtr - (uint8_t*)page); } - size_t size = !std::is_same_v && (padding || lastEndpoint == -1 || hbf == nexthbf) ? TPCZSHDR::TPC_ZS_PAGE_SIZE : (pagePtr - (uint8_t*)page); + size_t size = !isDense && (padding || lastEndpoint == -1 || hbf == nexthbf) ? TPCZSHDR::TPC_ZS_PAGE_SIZE : (pagePtr - (uint8_t*)page); size = CAMath::nextMultipleOf(size); #ifndef GPUCA_STANDALONE if (raw) { @@ -1174,7 +1175,7 @@ inline uint32_t zsEncoderRun::run(std::vector* buffer, std::vector(page); std::fill(page->begin(), page->end(), 0); pagePtr += sizeof(o2::header::RAWDataHeader); - if constexpr (std::is_same_v) { + if constexpr (isDense) { hdr = &this->hdrBuffer; } else { hdr = reinterpret_cast(pagePtr); diff --git a/GPU/GPUTracking/Base/GPUReconstructionDebug.cxx b/GPU/GPUTracking/Base/GPUReconstructionDebug.cxx index 9de04bcc2c395..34ebb77debdbb 100644 --- a/GPU/GPUTracking/Base/GPUReconstructionDebug.cxx +++ b/GPU/GPUTracking/Base/GPUReconstructionDebug.cxx @@ -57,8 +57,7 @@ void GPUReconstruction::debugInit() } mDebugEnabled = true; if ((GetProcessingSettings().debugOnFailure & 1) || (GetProcessingSettings().debugOnFailure & 2)) { - struct sigaction sa, oldsa; - memset(&sa, 0, sizeof(sa)); + struct sigaction sa{}, oldsa; sa.sa_sigaction = GPUReconstruction::debugInternal::globalCallback; sa.sa_flags = SA_SIGINFO; uint32_t mask = GetProcessingSettings().debugOnFailureSignalMask == (uint32_t)-1 ? ((1 << SIGINT) | (1 << SIGABRT) | (1 << SIGBUS) | (1 << SIGTERM) | (1 << SIGSEGV)) : GetProcessingSettings().debugOnFailureSignalMask; @@ -231,13 +230,13 @@ void GPUReconstructionCPU::debugWriter::row(char type, uint32_t count, const std } std::cout << std::endl; } else if (!mSilent) { - if (name.substr(0, 3) == "GPU") { + if (name.starts_with("GPU")) { char bandwidth[256] = ""; if (memSize && mStatNEvents && gpu_time != 0.0) { snprintf(bandwidth, 256, " (%8.3f GB/s - %'14zu bytes - %'14zu per call)", memSize / gpu_time * 1e-9, memSize / mStatNEvents, memSize / mStatNEvents / count); } printf("Execution Time: Task (%c %8ux): %50s Time: %'10.0f us%s\n", type, count, name.c_str(), gpu_time * scale, bandwidth); - } else if (name.substr(0, 3) == "TPC") { + } else if (name.starts_with("TPC")) { std::size_t n = name.find('('); std::string basename = name.substr(0, n - 1); std::string postfix = name.substr(n + 1, name.size() - n - 2); diff --git a/GPU/GPUTracking/Base/GPUReconstructionDeviceBase.cxx b/GPU/GPUTracking/Base/GPUReconstructionDeviceBase.cxx index 89393bec4987e..4cc6727e6b7f2 100644 --- a/GPU/GPUTracking/Base/GPUReconstructionDeviceBase.cxx +++ b/GPU/GPUTracking/Base/GPUReconstructionDeviceBase.cxx @@ -26,7 +26,7 @@ using namespace o2::gpu; #include #include #endif -#include +#include class GPUTPCRow; @@ -192,7 +192,7 @@ size_t GPUReconstructionDeviceBase::TransferMemoryInternal(GPUMemoryResource* re } return 0; } - if (GetProcessingSettings().debugLevel >= 3 && !GetProcessingSettings().debugSilent && (strcmp(res->Name(), "ErrorCodes") || GetProcessingSettings().debugLevel >= 4)) { + if (GetProcessingSettings().debugLevel >= 3 && !GetProcessingSettings().debugSilent && (std::string_view(res->Name()) != "ErrorCodes" || GetProcessingSettings().debugLevel >= 4)) { GPUInfo("Copying to %s: %s - %ld bytes", toGPU ? "GPU" : "Host", res->Name(), (int64_t)res->Size()); } return GPUMemCpy(dst, src, res->Size(), stream, toGPU, ev, evList, nEvents); diff --git a/GPU/GPUTracking/Base/GPUReconstructionLibrary.cxx b/GPU/GPUTracking/Base/GPUReconstructionLibrary.cxx index 614301cdeecba..05490a5d39924 100644 --- a/GPU/GPUTracking/Base/GPUReconstructionLibrary.cxx +++ b/GPU/GPUTracking/Base/GPUReconstructionLibrary.cxx @@ -181,8 +181,8 @@ GPUReconstruction* GPUReconstruction::LibraryLoader::GetPtr(const GPUSettingsDev if (mGPUEntry == nullptr) { return nullptr; } - GPUReconstruction* (*tmp)(const GPUSettingsDeviceBackend& cfg) = (GPUReconstruction * (*)(const GPUSettingsDeviceBackend& cfg)) mGPUEntry; - return tmp(cfg); + using CreateFn = GPUReconstruction* (*)(const GPUSettingsDeviceBackend&); + return reinterpret_cast(mGPUEntry)(cfg); } int32_t GPUReconstruction::LibraryLoader::CloseLibrary() diff --git a/GPU/GPUTracking/Base/GPUReconstructionProcessing.cxx b/GPU/GPUTracking/Base/GPUReconstructionProcessing.cxx index fbb211f794981..87de6ecee2d3c 100644 --- a/GPU/GPUTracking/Base/GPUReconstructionProcessing.cxx +++ b/GPU/GPUTracking/Base/GPUReconstructionProcessing.cxx @@ -91,8 +91,6 @@ uint32_t GPUReconstructionProcessing::SetAndGetNActiveThreadsOuterLoop(bool cond return mNActiveThreadsOuterLoop; } -std::atomic_flag GPUReconstructionProcessing::mTimerFlag = ATOMIC_FLAG_INIT; - GPUReconstructionProcessing::timerMeta* GPUReconstructionProcessing::insertTimer(uint32_t id, std::string&& name, int32_t J, int32_t num, int32_t type, RecoStep step) { stdspinlock spinlock(mTimerFlag); diff --git a/GPU/GPUTracking/Base/GPUReconstructionProcessing.h b/GPU/GPUTracking/Base/GPUReconstructionProcessing.h index 9c2a437f68a2a..b7058990cfa06 100644 --- a/GPU/GPUTracking/Base/GPUReconstructionProcessing.h +++ b/GPU/GPUTracking/Base/GPUReconstructionProcessing.h @@ -126,7 +126,7 @@ class GPUReconstructionProcessing : public GPUReconstruction template struct krnlSetupArgs : public kernelInterfaceArguments { const krnlSetupTime s; - std::tuple sizeof(void*)), const Args&, const Args>::type...> v; + std::tuple sizeof(void*)), const Args&, const Args>...> v; }; template @@ -209,13 +209,13 @@ class GPUReconstructionProcessing : public GPUReconstruction timerMeta* getTimerById(uint32_t id, bool increment = true); timerMeta* insertTimer(uint32_t id, std::string&& name, int32_t J, int32_t num, int32_t type, RecoStep step); - static std::atomic_flag mTimerFlag; + static inline std::atomic_flag mTimerFlag; }; template inline void GPUReconstructionProcessing::AddGPUEvents(T*& events) { - mEvents.emplace_back(std::vector(sizeof(T) / sizeof(deviceEvent))); + mEvents.emplace_back(sizeof(T) / sizeof(deviceEvent)); events = (T*)mEvents.back().data(); } diff --git a/GPU/GPUTracking/Base/cuda/GPUReconstructionCUDA.cu b/GPU/GPUTracking/Base/cuda/GPUReconstructionCUDA.cu index 0aa72b54e0c28..35399280a6539 100644 --- a/GPU/GPUTracking/Base/cuda/GPUReconstructionCUDA.cu +++ b/GPU/GPUTracking/Base/cuda/GPUReconstructionCUDA.cu @@ -377,8 +377,7 @@ int32_t GPUReconstructionCUDA::InitDevice_Runtime() mMaxBackendThreads = master->mMaxBackendThreads; mDeviceName = master->mDeviceName; mDeviceConstantMem = master->mDeviceConstantMem; - mDeviceConstantMemList.resize(master->mDeviceConstantMemList.size()); - std::copy(master->mDeviceConstantMemList.begin(), master->mDeviceConstantMemList.end(), mDeviceConstantMemList.begin()); + mDeviceConstantMemList = master->mDeviceConstantMemList; mInternals = master->mInternals; GPUChkErr(cudaSetDevice(mDeviceId)); @@ -650,7 +649,7 @@ void GPUReconstructionCUDA::SetONNXGPUStream(Ort::SessionOptions& sessionOptions const char* keys[] = {"device_id", "trt_int8_enable"}; const char* values[] = {device.c_str(), "1"}; - ORTCHK(api->UpdateTensorRTProviderOptions(trtOptions, keys, values, sizeof(keys) / sizeof(keys[0]))); + ORTCHK(api->UpdateTensorRTProviderOptions(trtOptions, keys, values, std::size(keys))); ORTCHK(api->UpdateTensorRTProviderOptionsWithValue(trtOptions, "user_compute_stream", mInternals->Streams[stream])); ORTCHK(api->SessionOptionsAppendExecutionProvider_TensorRT_V2(sessionOptions, trtOptions)); // Register TensorRT first: it consequently has higher priority. api->ReleaseTensorRTProviderOptions(trtOptions); From 68ac0bd6195a6b12550cfce204537276f2e12fa9 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Tue, 1 Dec 2026 22:18:20 +0100 Subject: [PATCH 37/41] GPU: Modernize C++: Use range-based for loop in many places --- GPU/GPUTracking/Base/GPUReconstruction.cxx | 132 +++++++++--------- GPU/GPUTracking/Base/GPUReconstructionCPU.cxx | 35 +++-- .../Base/GPUReconstructionConvert.cxx | 12 +- .../Base/GPUReconstructionDebug.cxx | 6 +- .../Base/GPUReconstructionTimeframe.cxx | 3 +- .../cpudevice/GPUReconstructionCPUDevice.cxx | 19 +-- .../Base/cuda/GPUReconstructionCUDA.cu | 44 +++--- .../Base/cuda/GPUReconstructionCUDAKernels.cu | 4 +- .../Base/metal/GPUReconstructionMetal.mm | 43 +++--- .../Base/opencl/GPUReconstructionOCL.cxx | 9 +- 10 files changed, 146 insertions(+), 161 deletions(-) diff --git a/GPU/GPUTracking/Base/GPUReconstruction.cxx b/GPU/GPUTracking/Base/GPUReconstruction.cxx index 4830fdf8de173..3aa542690854c 100644 --- a/GPU/GPUTracking/Base/GPUReconstruction.cxx +++ b/GPU/GPUTracking/Base/GPUReconstruction.cxx @@ -145,15 +145,15 @@ int32_t GPUReconstruction::Init() if (retVal) { return retVal; } - for (uint32_t i = 0; i < mSlaves.size(); i++) { - retVal = mSlaves[i]->InitPhaseBeforeDevice(); + for (auto* slaveRec : mSlaves) { + retVal = slaveRec->InitPhaseBeforeDevice(); if (retVal) { GPUError("Error initialization slave (before deviceinit)"); return retVal; } - mNStreams = std::max(mNStreams, mSlaves[i]->mNStreams); - mHostMemorySize += mSlaves[i]->mHostMemorySize; - mDeviceMemorySize = std::max(mDeviceMemorySize, mSlaves[i]->mDeviceMemorySize); + mNStreams = std::max(mNStreams, slaveRec->mNStreams); + mHostMemorySize += slaveRec->mHostMemorySize; + mDeviceMemorySize = std::max(mDeviceMemorySize, slaveRec->mDeviceMemorySize); } if (InitDevice()) { return 1; @@ -167,39 +167,39 @@ int32_t GPUReconstruction::Init() if (InitPhasePermanentMemory()) { return 1; } - for (uint32_t i = 0; i < mSlaves.size(); i++) { - mSlaves[i]->mDeviceMemoryBase = mDeviceMemoryPermanent; - mSlaves[i]->mDeviceMemoryHostView = mDeviceMemoryHostView ? (char*)mDeviceMemoryHostView + ptrDiff(mSlaves[i]->mDeviceMemoryBase, mDeviceMemoryBase) : nullptr; - mSlaves[i]->mHostMemoryBase = mHostMemoryPermanent; - mSlaves[i]->mDeviceMemorySize = mDeviceMemorySize - ptrDiff(mSlaves[i]->mDeviceMemoryBase, mDeviceMemoryBase); - mSlaves[i]->mHostMemorySize = mHostMemorySize - ptrDiff(mSlaves[i]->mHostMemoryBase, mHostMemoryBase); - mSlaves[i]->mHostMemoryPoolEnd = mHostMemoryPoolEnd; - mSlaves[i]->mDeviceMemoryPoolEnd = mDeviceMemoryPoolEnd; - if (mSlaves[i]->InitDevice()) { + for (auto* slaveRec : mSlaves) { + slaveRec->mDeviceMemoryBase = mDeviceMemoryPermanent; + slaveRec->mDeviceMemoryHostView = mDeviceMemoryHostView ? (char*)mDeviceMemoryHostView + ptrDiff(slaveRec->mDeviceMemoryBase, mDeviceMemoryBase) : nullptr; + slaveRec->mHostMemoryBase = mHostMemoryPermanent; + slaveRec->mDeviceMemorySize = mDeviceMemorySize - ptrDiff(slaveRec->mDeviceMemoryBase, mDeviceMemoryBase); + slaveRec->mHostMemorySize = mHostMemorySize - ptrDiff(slaveRec->mHostMemoryBase, mHostMemoryBase); + slaveRec->mHostMemoryPoolEnd = mHostMemoryPoolEnd; + slaveRec->mDeviceMemoryPoolEnd = mDeviceMemoryPoolEnd; + if (slaveRec->InitDevice()) { GPUError("Error initialization slave (deviceinit)"); return 1; } - if (mSlaves[i]->InitPhasePermanentMemory()) { + if (slaveRec->InitPhasePermanentMemory()) { GPUError("Error initialization slave (permanent memory)"); return 1; } - mDeviceMemoryPermanent = mSlaves[i]->mDeviceMemoryPermanent; - mHostMemoryPermanent = mSlaves[i]->mHostMemoryPermanent; + mDeviceMemoryPermanent = slaveRec->mDeviceMemoryPermanent; + mHostMemoryPermanent = slaveRec->mHostMemoryPermanent; } retVal = InitPhaseAfterDevice(); if (retVal) { return retVal; } ClearAllocatedMemory(); - for (uint32_t i = 0; i < mSlaves.size(); i++) { - mSlaves[i]->mDeviceMemoryPermanent = mDeviceMemoryPermanent; - mSlaves[i]->mHostMemoryPermanent = mHostMemoryPermanent; - retVal = mSlaves[i]->InitPhaseAfterDevice(); + for (auto* slaveRec : mSlaves) { + slaveRec->mDeviceMemoryPermanent = mDeviceMemoryPermanent; + slaveRec->mHostMemoryPermanent = mHostMemoryPermanent; + retVal = slaveRec->InitPhaseAfterDevice(); if (retVal) { GPUError("Error initialization slave (after device init)"); return retVal; } - mSlaves[i]->ClearAllocatedMemory(); + slaveRec->ClearAllocatedMemory(); } debugInit(); return 0; @@ -230,8 +230,8 @@ int32_t GPUReconstruction::InitPhaseBeforeDevice() printf("\nConfig Dump %s\n", mMaster ? "Slave" : "Master"); } const GPUChainTracking* chTrk = nullptr; - for (uint32_t i = 0; i < mChains.size(); i++) { - if ((chTrk = dynamic_cast(mChains[i].get()))) { + for (auto& chain : mChains) { + if ((chTrk = dynamic_cast(chain.get()))) { break; } } @@ -380,13 +380,13 @@ int32_t GPUReconstruction::InitPhaseBeforeDevice() } mDeviceMemorySize = mHostMemorySize = 0; - for (uint32_t i = 0; i < mChains.size(); i++) { - if (mChains[i]->EarlyConfigure()) { + for (auto& chain : mChains) { + if (chain->EarlyConfigure()) { return 1; } - mChains[i]->RegisterPermanentMemoryAndProcessors(); + chain->RegisterPermanentMemoryAndProcessors(); size_t memPrimary = 0, memPageLocked = 0; - mChains[i]->MemorySize(memPrimary, memPageLocked); + chain->MemorySize(memPrimary, memPageLocked); if (!IsGPU() || mOutputControl.useInternal()) { memPageLocked = memPrimary; } @@ -405,8 +405,8 @@ int32_t GPUReconstruction::InitPhaseBeforeDevice() mHostMemorySize = GetProcessingSettings().forceHostMemoryPoolSize; } - for (uint32_t i = 0; i < mProcessors.size(); i++) { - (mProcessors[i].proc->*(mProcessors[i].RegisterMemoryAllocation))(); + for (const auto& p : mProcessors) { + (p.proc->*(p.RegisterMemoryAllocation))(); } return 0; @@ -415,8 +415,8 @@ int32_t GPUReconstruction::InitPhaseBeforeDevice() int32_t GPUReconstruction::InitPhasePermanentMemory() { if (IsGPU()) { - for (uint32_t i = 0; i < mChains.size(); i++) { - mChains[i]->RegisterGPUProcessors(); + for (auto& chain : mChains) { + chain->RegisterGPUProcessors(); } } AllocateRegisteredPermanentMemory(); @@ -428,13 +428,13 @@ int32_t GPUReconstruction::InitPhaseAfterDevice() if (GetProcessingSettings().forceMaxMemScalers <= 1 && GetProcessingSettings().memoryAllocationStrategy == GPUMemoryResource::ALLOCATION_GLOBAL) { mMemoryScalers->rescaleMaxMem(IsGPU() ? mDeviceMemorySize : mHostMemorySize); } - for (uint32_t i = 0; i < mChains.size(); i++) { - if (mChains[i]->Init()) { + for (auto& chain : mChains) { + if (chain->Init()) { return 1; } } - for (uint32_t i = 0; i < mProcessors.size(); i++) { - (mProcessors[i].proc->*(mProcessors[i].InitializeProcessor))(); + for (const auto& p : mProcessors) { + (p.proc->*(p.InitializeProcessor))(); } WriteConstantParams(); // Initialize with initial values, can optionally be updated later @@ -465,11 +465,11 @@ int32_t GPUReconstruction::GetTPCCompressionGatherMode() const int32_t GPUReconstruction::Finalize() { - for (uint32_t i = 0; i < mChains.size(); i++) { - mChains[i]->Finalize(); + for (auto& chain : mChains) { + chain->Finalize(); } - for (uint32_t i = 0; i < mSlaves.size(); i++) { - mSlaves[i]->Finalize(); + for (auto* slaveRec : mSlaves) { + slaveRec->Finalize(); } return 0; } @@ -479,8 +479,8 @@ int32_t GPUReconstruction::Exit() if (!mInitialized) { return 1; } - for (uint32_t i = 0; i < mSlaves.size(); i++) { - if (mSlaves[i]->Exit()) { + for (auto* slaveRec : mSlaves) { + if (slaveRec->Exit()) { GPUError("Error exiting slave"); } } @@ -488,12 +488,12 @@ int32_t GPUReconstruction::Exit() mChains.clear(); // Make sure we destroy a possible ITS GPU tracker before we call the destructors mHostConstantMem.reset(); // Reset these explicitly before the destruction of other members unloads the library if (GetProcessingSettings().memoryAllocationStrategy == GPUMemoryResource::ALLOCATION_INDIVIDUAL) { - for (uint32_t i = 0; i < mMemoryResources.size(); i++) { - if (mMemoryResources[i].mReuse >= 0) { + for (auto& res : mMemoryResources) { + if (res.mReuse >= 0) { continue; } - alignedDefaultBufferDeleter()(mMemoryResources[i].mPtrDevice); - mMemoryResources[i].mPtr = mMemoryResources[i].mPtrDevice = nullptr; + alignedDefaultBufferDeleter()(res.mPtrDevice); + res.mPtr = res.mPtrDevice = nullptr; } } mMemoryResources.clear(); @@ -510,13 +510,12 @@ void GPUReconstruction::ConstructGPUProcessor(GPUProcessor* proc) { proc->mConst void GPUReconstruction::ComputeReuseMax(GPUProcessor* proc) { - for (auto it = mMemoryReuse1to1.begin(); it != mMemoryReuse1to1.end(); it++) { - auto& re = it->second; + for (auto& [id, re] : mMemoryReuse1to1) { if (proc == nullptr || re.proc == proc) { GPUMemoryResource& resMain = mMemoryResources[re.res[0]]; resMain.mOverrideSize = 0; - for (uint32_t i = 0; i < re.res.size(); i++) { - GPUMemoryResource& res = mMemoryResources[re.res[i]]; + for (uint16_t ires : re.res) { + GPUMemoryResource& res = mMemoryResources[ires]; resMain.mOverrideSize = std::max(resMain.mOverrideSize, ptrDiff(res.SetPointers((void*)1), (char*)1)); } } @@ -1070,8 +1069,7 @@ void GPUReconstruction::PrintMemoryStatistics() bool permanent = false; }; std::map sizes; - for (uint32_t i = 0; i < mMemoryResources.size(); i++) { - auto& res = mMemoryResources[i]; + for (auto& res : mMemoryResources) { if (res.mReuse >= 0) { continue; } @@ -1091,8 +1089,8 @@ void GPUReconstruction::PrintMemoryStatistics() printf("Allocation %50s %s: Size %'14zu / %'14zu\n", name.c_str(), s.permanent ? "P" : " ", s.host, s.device); } PrintMemoryOverview(); - for (uint32_t i = 0; i < mChains.size(); i++) { - mChains[i]->PrintMemoryStatistics(); + for (auto& chain : mChains) { + chain->PrintMemoryStatistics(); } } @@ -1228,16 +1226,16 @@ GPUChain* GPUReconstruction::GetNextChainInQueue() void GPUReconstruction::PrepareEvent() // TODO: Clean this up, this should not be called from chainTracking but before { ClearAllocatedMemory(true); - for (uint32_t i = 0; i < mChains.size(); i++) { - mChains[i]->PrepareEvent(); + for (auto& chain : mChains) { + chain->PrepareEvent(); } - for (uint32_t i = 0; i < mProcessors.size(); i++) { - if (mProcessors[i].proc->mAllocateAndInitializeLate) { + for (const auto& p : mProcessors) { + if (p.proc->mAllocateAndInitializeLate) { continue; } - (mProcessors[i].proc->*(mProcessors[i].SetMaxData))(mHostConstantMem->ioPtrs); - if (mProcessors[i].proc->mGPUProcessorType != GPUProcessor::PROCESSOR_TYPE_DEVICE && mProcessors[i].proc->mLinkedProcessor) { - (mProcessors[i].proc->mLinkedProcessor->*(mProcessors[i].SetMaxData))(mHostConstantMem->ioPtrs); + (p.proc->*(p.SetMaxData))(mHostConstantMem->ioPtrs); + if (p.proc->mGPUProcessorType != GPUProcessor::PROCESSOR_TYPE_DEVICE && p.proc->mLinkedProcessor) { + (p.proc->mLinkedProcessor->*(p.SetMaxData))(mHostConstantMem->ioPtrs); } } ComputeReuseMax(nullptr); @@ -1247,8 +1245,8 @@ void GPUReconstruction::PrepareEvent() // TODO: Clean this up, this should not b int32_t GPUReconstruction::CheckErrorCodes(bool cpuOnly, bool forceShowErrors, std::vector>* fillErrors) { int32_t retVal = 0; - for (uint32_t i = 0; i < mChains.size(); i++) { - if (mChains[i]->CheckErrorCodes(cpuOnly, forceShowErrors, fillErrors)) { + for (auto& chain : mChains) { + if (chain->CheckErrorCodes(cpuOnly, forceShowErrors, fillErrors)) { retVal++; } } @@ -1276,8 +1274,8 @@ void GPUReconstruction::DumpSettings(const char* dir, const GPUSettingsGRP* grp) f = dir; f += "settings.dump"; DumpStructToFile(grp ? grp : mGRPSettings.get(), f.c_str()); - for (uint32_t i = 0; i < mChains.size(); i++) { - mChains[i]->DumpSettings(dir); + for (auto& chain : mChains) { + chain->DumpSettings(dir); } } @@ -1317,8 +1315,8 @@ int32_t GPUReconstruction::ReadSettings(const char* dir) return 1; } param().UpdateSettings(mGRPSettings.get()); - for (uint32_t i = 0; i < mChains.size(); i++) { - mChains[i]->ReadSettings(dir); + for (auto& chain : mChains) { + chain->ReadSettings(dir); } return 0; } diff --git a/GPU/GPUTracking/Base/GPUReconstructionCPU.cxx b/GPU/GPUTracking/Base/GPUReconstructionCPU.cxx index 14217357d4b85..112cab32d1644 100644 --- a/GPU/GPUTracking/Base/GPUReconstructionCPU.cxx +++ b/GPU/GPUTracking/Base/GPUReconstructionCPU.cxx @@ -37,6 +37,7 @@ #include #include #include +#include #include #ifndef _WIN32 @@ -197,8 +198,7 @@ size_t GPUReconstructionCPU::TransferMemoryResourcesHelper(GPUProcessor* proc, i int32_t inc = toGPU ? GPUMemoryResource::MEMORY_INPUT_FLAG : GPUMemoryResource::MEMORY_OUTPUT_FLAG; int32_t exc = toGPU ? GPUMemoryResource::MEMORY_OUTPUT_FLAG : GPUMemoryResource::MEMORY_INPUT_FLAG; size_t n = 0; - for (uint32_t i = 0; i < mMemoryResources.size(); i++) { - GPUMemoryResource& res = mMemoryResources[i]; + for (auto& res : mMemoryResources) { if (res.mPtr == nullptr) { continue; } @@ -212,9 +212,9 @@ size_t GPUReconstructionCPU::TransferMemoryResourcesHelper(GPUProcessor* proc, i continue; } if (toGPU) { - n += TransferMemoryResourceToGPU(&mMemoryResources[i], stream); + n += TransferMemoryResourceToGPU(&res, stream); } else { - n += TransferMemoryResourceToHost(&mMemoryResources[i], stream); + n += TransferMemoryResourceToHost(&res, stream); } } return n; @@ -293,8 +293,8 @@ int32_t GPUReconstructionCPU::RunChains() if (mSlaves.size() || mMaster) { WriteConstantParams(); // Reinitialize // TODO: Get this in sync with GPUChainTracking::DoQueuedUpdates, and consider the doublePipeline } - for (uint32_t i = 0; i < mChains.size(); i++) { - retVal = mChains[i]->RunChain(); + for (auto& chain : mChains) { + retVal = chain->RunChain(); } } if (retVal != GPUReconstruction::retValValue::retOk && retVal != GPUReconstruction::retValValue::retDoExit) { @@ -322,29 +322,28 @@ int32_t GPUReconstructionCPU::RunChains() if (GetProcessingSettings().debugLevel >= 1) { writer.header(); - for (uint32_t i = 0; i < mTimers.size(); i++) { + for (auto& tm : mTimers) { double time = 0; - if (mTimers[i] == nullptr) { + if (tm == nullptr) { continue; } - for (int32_t j = 0; j < mTimers[i]->num; j++) { - HighResTimer& timer = mTimers[i]->timer[j]; + for (auto& timer : std::span(tm->timer.get(), tm->num)) { time += timer.GetElapsedTime(); if (GetProcessingSettings().resetTimers) { timer.Reset(); } } - uint32_t type = mTimers[i]->type; + uint32_t type = tm->type; if (type == 0) { kernelTotal += time; - int32_t stepNum = getRecoStepNum(mTimers[i]->step); + int32_t stepNum = getRecoStepNum(tm->step); kernelStepTimes[stepNum] += time; } - writer.row('K', mTimers[i]->count, mTimers[i]->name.c_str(), time, -1.0, -1.0, mTimers[i]->memSize); + writer.row('K', tm->count, tm->name.c_str(), time, -1.0, -1.0, tm->memSize); if (GetProcessingSettings().resetTimers) { - mTimers[i]->count = 0; - mTimers[i]->memSize = 0; + tm->count = 0; + tm->memSize = 0; } } } @@ -394,9 +393,9 @@ int32_t GPUReconstructionCPU::RunChains() void GPUReconstructionCPU::ResetDeviceProcessorTypes() { - for (uint32_t i = 0; i < mProcessors.size(); i++) { - if (mProcessors[i].proc->mGPUProcessorType != GPUProcessor::PROCESSOR_TYPE_DEVICE && mProcessors[i].proc->mLinkedProcessor) { - mProcessors[i].proc->mLinkedProcessor->InitGPUProcessor(this, GPUProcessor::PROCESSOR_TYPE_DEVICE); + for (const auto& p : mProcessors) { + if (p.proc->mGPUProcessorType != GPUProcessor::PROCESSOR_TYPE_DEVICE && p.proc->mLinkedProcessor) { + p.proc->mLinkedProcessor->InitGPUProcessor(this, GPUProcessor::PROCESSOR_TYPE_DEVICE); } } } diff --git a/GPU/GPUTracking/Base/GPUReconstructionConvert.cxx b/GPU/GPUTracking/Base/GPUReconstructionConvert.cxx index a5092018ff493..a70b546d2d91d 100644 --- a/GPU/GPUTracking/Base/GPUReconstructionConvert.cxx +++ b/GPU/GPUTracking/Base/GPUReconstructionConvert.cxx @@ -87,10 +87,8 @@ int32_t GPUReconstructionConvert::GetMaxTimeBin(const ClusterNativeAccess& nativ float retVal = 0; for (uint32_t i = 0; i < NSECTORS; i++) { for (uint32_t j = 0; j < GPUTPCGeometry::NROWS; j++) { - for (uint32_t k = 0; k < native.nClusters[i][j]; k++) { - if (native.clusters[i][j][k].getTime() > retVal) { - retVal = native.clusters[i][j][k].getTime(); - } + for (const auto& cl : std::span(native.clusters[i][j], native.nClusters[i][j])) { + retVal = std::max(retVal, cl.getTime()); } } } @@ -101,10 +99,8 @@ int32_t GPUReconstructionConvert::GetMaxTimeBin(const GPUTrackingInOutDigits& di { float retVal = 0; for (uint32_t i = 0; i < NSECTORS; i++) { - for (uint32_t k = 0; k < digits.nTPCDigits[i]; k++) { - if (digits.tpcDigits[i][k].getTimeStamp() > retVal) { - retVal = digits.tpcDigits[i][k].getTimeStamp(); - } + for (const auto& digit : std::span(digits.tpcDigits[i], digits.nTPCDigits[i])) { + retVal = std::max(retVal, digit.getTimeStamp()); } } return ceil(retVal); diff --git a/GPU/GPUTracking/Base/GPUReconstructionDebug.cxx b/GPU/GPUTracking/Base/GPUReconstructionDebug.cxx index 34ebb77debdbb..a4afdf0ff0fc9 100644 --- a/GPU/GPUTracking/Base/GPUReconstructionDebug.cxx +++ b/GPU/GPUTracking/Base/GPUReconstructionDebug.cxx @@ -94,9 +94,9 @@ void GPUReconstruction::debugExit() return; } if (mDebugData) { - for (auto& it : mDebugData->oldActions) { - if (sigaction(it.first, &it.second, nullptr)) { - GPUFatal("Error restoring signal handler for signal %d", it.first); + for (auto& [signal, action] : mDebugData->oldActions) { + if (sigaction(signal, &action, nullptr)) { + GPUFatal("Error restoring signal handler for signal %d", signal); } } } diff --git a/GPU/GPUTracking/Base/GPUReconstructionTimeframe.cxx b/GPU/GPUTracking/Base/GPUReconstructionTimeframe.cxx index 06c7deca7c720..d7d9f872db47c 100644 --- a/GPU/GPUTracking/Base/GPUReconstructionTimeframe.cxx +++ b/GPU/GPUTracking/Base/GPUReconstructionTimeframe.cxx @@ -183,8 +183,7 @@ void GPUReconstructionTimeframe::MergeShiftedEvents() uint32_t nTrackOffset = 0; uint32_t nColOffset = 0; uint32_t nClustersEventOffset[NSECTORS] = {0}; - for (uint32_t i = 0; i < mShiftedEvents.size(); i++) { - auto& ptr = mShiftedEvents[i].ptrs; + for (auto& [ptr, mem, clusters] : mShiftedEvents) { uint32_t inEventOffset = 0; for (uint32_t j = 0; j < NSECTORS; j++) { memcpy((void*)&mChain->mIOMem.clusterData[j][nClustersEventOffset[j]], (void*)ptr.clusterData[j], ptr.nClusterData[j] * sizeof(ptr.clusterData[j][0])); diff --git a/GPU/GPUTracking/Base/cpudevice/GPUReconstructionCPUDevice.cxx b/GPU/GPUTracking/Base/cpudevice/GPUReconstructionCPUDevice.cxx index db2cd8eedb656..51cf3fad51c2e 100644 --- a/GPU/GPUTracking/Base/cpudevice/GPUReconstructionCPUDevice.cxx +++ b/GPU/GPUTracking/Base/cpudevice/GPUReconstructionCPUDevice.cxx @@ -24,6 +24,7 @@ #include #include #include +#include #include #include #include @@ -258,8 +259,8 @@ void GPUReconstructionCPUDevice::EnqueueTask(int32_t stream, deviceEvent* evList } GPUReconstructionCPUDeviceTask task; if (evList) { // Capture the event states at enqueue time, such that the queue waits for the markers recorded so far, like cudaStreamWaitEvent - for (int32_t k = 0; k < nEvents; k++) { - auto* e = getEvent(evList[k]); + for (auto& evIn : std::span(evList, nEvents)) { + auto* e = getEvent(evIn); std::lock_guard lock(e->mutex); task.waits.emplace_back(e, e->nRecorded); } @@ -289,8 +290,8 @@ void GPUReconstructionCPUDevice::SynchronizeGPU() void GPUReconstructionCPUDevice::SynchronizeEvents(deviceEvent* evList, int32_t nEvents) { - for (int32_t i = 0; i < nEvents; i++) { - auto* e = getEvent(evList[i]); + for (auto& ev : std::span(evList, nEvents)) { + auto* e = getEvent(ev); std::unique_lock lock(e->mutex); const uint64_t value = e->nRecorded; e->cv.wait(lock, [e, value]() { return e->nCompleted >= value; }); @@ -306,8 +307,8 @@ void GPUReconstructionCPUDevice::StreamWaitForEvents(int32_t stream, deviceEvent bool GPUReconstructionCPUDevice::IsEventDone(deviceEvent* evList, int32_t nEvents) { - for (int32_t i = 0; i < nEvents; i++) { - auto* e = getEvent(evList[i]); + for (auto& ev : std::span(evList, nEvents)) { + auto* e = getEvent(ev); std::lock_guard lock(e->mutex); if (e->nCompleted < e->nRecorded) { return false; @@ -365,7 +366,7 @@ size_t GPUReconstructionCPUDevice::GPUMemCpy(void* dst, const void* src, size_t mInternals->completeEvent(e, value); } } else { - EnqueueTask(stream, evList, evList ? nEvents : 0, ev, [dst, src, size]() { + EnqueueTask(stream, evList, nEvents, ev, [dst, src, size]() { if (size) { memcpy(dst, src, size); } @@ -410,7 +411,7 @@ inline void GPUReconstructionCPUDevice::runKernelBackend(const krnlSetupTime& _x rtcKernel rtc = mInternals->rtcKernels.size() ? reinterpret_cast(mInternals->rtcKernels[GetKernelNum()]) : nullptr; // The kernel arguments are captured by value, since the kernel runs asynchronously in the command queue - EnqueueTask(x.stream, z.evList, z.evList ? z.nEvents : 0, z.ev, [nBlocks, iSector, constantMem, rtc, ... args = args]() { + EnqueueTask(x.stream, z.evList, z.nEvents, z.ev, [nBlocks, iSector, constantMem, rtc, ... args = args]() { tbb::this_task_arena::isolate([&] { // Do not pick up tasks of other command queues while waiting inside parallel_for tbb::parallel_for(tbb::blocked_range(0, nBlocks, 1), [&](const tbb::blocked_range& r) { if (rtc) { @@ -429,7 +430,7 @@ inline void GPUReconstructionCPUDevice::runKernelBackend(const krnlSetupTime& _x template <> inline void GPUReconstructionCPUDevice::runKernelBackend(const krnlSetupTime& _xyz, void* const& ptr, uint64_t const& size) { - EnqueueTask(_xyz.x.stream, _xyz.z.evList, _xyz.z.evList ? _xyz.z.nEvents : 0, _xyz.z.ev, [ptr, size]() { memset(ptr, 0, size); }); + EnqueueTask(_xyz.x.stream, _xyz.z.evList, _xyz.z.nEvents, _xyz.z.ev, [ptr, size]() { memset(ptr, 0, size); }); } #include "GPUReconstructionProcessingKernels.inc" diff --git a/GPU/GPUTracking/Base/cuda/GPUReconstructionCUDA.cu b/GPU/GPUTracking/Base/cuda/GPUReconstructionCUDA.cu index 35399280a6539..c20bfe42128f6 100644 --- a/GPU/GPUTracking/Base/cuda/GPUReconstructionCUDA.cu +++ b/GPU/GPUTracking/Base/cuda/GPUReconstructionCUDA.cu @@ -17,6 +17,7 @@ #include "GPUReconstructionCUDAIncludesSystem.h" #include "GPUReconstructionCUDADef.h" #include +#include #include "GPUReconstructionCUDA.h" #include "GPUReconstructionCUDAInternals.h" @@ -353,14 +354,14 @@ int32_t GPUReconstructionCUDA::InitDevice_Runtime() #ifndef GPUCA_NO_CONSTANT_MEMORY runConstantRegistrators(); devPtrConstantMem = mDeviceConstantMemList[0]; - for (uint32_t i = 0; i < mInternals->kernelModules.size(); i++) { + for (auto& mod : mInternals->kernelModules) { #ifndef __HIPCC__ CUdeviceptr tmp; // CUDA has a custom type, that initializes to zero and cannot be initialized with nullptr #else CUdeviceptr tmp = nullptr; // HIP just uses void* #endif size_t tmpSize = 0; - GPUChkErr(cuModuleGetGlobal(&tmp, &tmpSize, *mInternals->kernelModules[i], "gGPUConstantMemBuffer")); + GPUChkErr(cuModuleGetGlobal(&tmp, &tmpSize, *mod, "gGPUConstantMemBuffer")); mDeviceConstantMemList.emplace_back((void*)tmp); } #else @@ -384,13 +385,12 @@ int32_t GPUReconstructionCUDA::InitDevice_Runtime() GPUInfo("CUDA Initialisation successfull (from master)"); } - for (uint32_t i = 0; i < mEvents.size(); i++) { - cudaEvent_t* events = (cudaEvent_t*)mEvents[i].data(); - for (uint32_t j = 0; j < mEvents[i].size(); j++) { + for (auto& events : mEvents) { + for (auto& ev : events) { #ifndef __HIPCC__ // CUDA - if (GPUChkErrI(cudaEventCreate(&events[j]))) { + if (GPUChkErrI(cudaEventCreate(&ev.get()))) { #else - if (GPUChkErrI(hipEventCreateWithFlags(&events[j], hipEventBlockingSync))) { + if (GPUChkErrI(hipEventCreateWithFlags(&ev.get(), hipEventBlockingSync))) { #endif GPUError("Error creating event"); GPUChkErrI(cudaDeviceReset()); @@ -432,10 +432,9 @@ int32_t GPUReconstructionCUDA::ExitDevice_Runtime() SynchronizeGPU(); unregisterRemainingRegisteredMemory(); - for (uint32_t i = 0; i < mEvents.size(); i++) { - cudaEvent_t* events = (cudaEvent_t*)mEvents[i].data(); - for (uint32_t j = 0; j < mEvents[i].size(); j++) { - GPUChkErrI(cudaEventDestroy(events[j])); + for (auto& events : mEvents) { + for (auto& ev : events) { + GPUChkErrI(cudaEventDestroy(ev.get())); } } @@ -450,8 +449,8 @@ int32_t GPUReconstructionCUDA::ExitDevice_Runtime() } GPUChkErrI(cudaFreeHost(mHostMemoryBase)); - for (uint32_t i = 0; i < mInternals->kernelModules.size(); i++) { - GPUChkErr(cuModuleUnload(*mInternals->kernelModules[i])); + for (auto& mod : mInternals->kernelModules) { + GPUChkErr(cuModuleUnload(*mod)); } size_t stackSize = 0; @@ -476,11 +475,8 @@ size_t GPUReconstructionCUDA::GPUMemCpy(void* dst, const void* src, size_t size, SynchronizeGPU(); GPUChkErr(cudaMemcpy(dst, src, size, toGPU ? cudaMemcpyHostToDevice : cudaMemcpyDeviceToHost)); } else { - if (evList == nullptr) { - nEvents = 0; - } - for (int32_t k = 0; k < nEvents; k++) { - GPUChkErr(cudaStreamWaitEvent(mInternals->Streams[stream], evList[k].get(), 0)); + if (evList) { + StreamWaitForEvents(stream, evList, nEvents); } GPUChkErr(cudaMemcpyAsync(dst, src, size, toGPU == -2 ? cudaMemcpyDeviceToDevice : (toGPU ? cudaMemcpyHostToDevice : cudaMemcpyDeviceToHost), mInternals->Streams[stream])); } @@ -529,22 +525,22 @@ void GPUReconstructionCUDA::SynchronizeStream(int32_t stream) { GPUChkErr(cudaSt void GPUReconstructionCUDA::SynchronizeEvents(deviceEvent* evList, int32_t nEvents) { - for (int32_t i = 0; i < nEvents; i++) { - GPUChkErr(cudaEventSynchronize(evList[i].get())); + for (auto& ev : std::span(evList, nEvents)) { + GPUChkErr(cudaEventSynchronize(ev.get())); } } void GPUReconstructionCUDA::StreamWaitForEvents(int32_t stream, deviceEvent* evList, int32_t nEvents) { - for (int32_t i = 0; i < nEvents; i++) { - GPUChkErr(cudaStreamWaitEvent(mInternals->Streams[stream], evList[i].get(), 0)); + for (auto& ev : std::span(evList, nEvents)) { + GPUChkErr(cudaStreamWaitEvent(mInternals->Streams[stream], ev.get(), 0)); } } bool GPUReconstructionCUDA::IsEventDone(deviceEvent* evList, int32_t nEvents) { - for (int32_t i = 0; i < nEvents; i++) { - cudaError_t retVal = cudaEventSynchronize(evList[i].get()); + for (auto& ev : std::span(evList, nEvents)) { + cudaError_t retVal = cudaEventSynchronize(ev.get()); if (retVal == cudaErrorNotReady) { return false; } diff --git a/GPU/GPUTracking/Base/cuda/GPUReconstructionCUDAKernels.cu b/GPU/GPUTracking/Base/cuda/GPUReconstructionCUDAKernels.cu index 285ee72beefce..f5d039ac73bca 100644 --- a/GPU/GPUTracking/Base/cuda/GPUReconstructionCUDAKernels.cu +++ b/GPU/GPUTracking/Base/cuda/GPUReconstructionCUDAKernels.cu @@ -57,9 +57,7 @@ inline void GPUReconstructionCUDA::runKernelBackend(const krnlSetupTime& _xyz, c auto& x = _xyz.x; auto& z = _xyz.z; if (z.evList) { - for (int32_t k = 0; k < z.nEvents; k++) { - GPUChkErr(cudaStreamWaitEvent(mInternals->Streams[x.stream], ((cudaEvent_t*)z.evList)[k], 0)); - } + StreamWaitForEvents(x.stream, z.evList, z.nEvents); } { GPUDebugTiming timer(GetProcessingSettings().deviceTimers && GetProcessingSettings().debugLevel > 0, (deviceEvent*)mDebugEvents, mInternals->Streams, _xyz, this); diff --git a/GPU/GPUTracking/Base/metal/GPUReconstructionMetal.mm b/GPU/GPUTracking/Base/metal/GPUReconstructionMetal.mm index 217616a71c308..c9949dd80aa4e 100644 --- a/GPU/GPUTracking/Base/metal/GPUReconstructionMetal.mm +++ b/GPU/GPUTracking/Base/metal/GPUReconstructionMetal.mm @@ -18,6 +18,7 @@ #include #include #include +#include #include #include @@ -208,11 +209,11 @@ uint32_t metalGPUCoreCount() mInternals = master->mInternals; } - for (uint32_t i = 0; i < mEvents.size(); i++) { - auto* events = (id*)mEvents[i].data(); - for (uint32_t j = 0; j < mEvents[i].size(); j++) { - events[j] = [mInternals->device newSharedEvent]; - if (events[j] == nil) { + for (auto& events : mEvents) { + for (auto& ev : events) { + auto& mtlEvent = ev.get>(); + mtlEvent = [mInternals->device newSharedEvent]; + if (mtlEvent == nil) { GPUErrorReturn("Error creating Metal event"); } } @@ -227,10 +228,9 @@ uint32_t metalGPUCoreCount() mInternals->exiting = true; SynchronizeGPU(); - for (uint32_t i = 0; i < mEvents.size(); i++) { - auto* events = (id*)mEvents[i].data(); - for (uint32_t j = 0; j < mEvents[i].size(); j++) { - [events[j] release]; + for (auto& events : mEvents) { + for (auto& ev : events) { + [ev.get>() release]; } } @@ -239,12 +239,12 @@ uint32_t metalGPUCoreCount() [mInternals->mem_gpu release]; [mInternals->mem_constant release]; [mInternals->canaryPipeline release]; - for (uint32_t i = 0; i < mInternals->functions.size(); i++) { - [mInternals->functions[i] release]; + for (auto& function : mInternals->functions) { + [function release]; } mInternals->functions.clear(); - for (uint32_t i = 0; i < mInternals->pipelines.size(); i++) { - [mInternals->pipelines[i] release]; + for (auto& pipeline : mInternals->pipelines) { + [pipeline release]; } mInternals->pipelines.clear(); mInternals->maxThreadsPerGroup.clear(); @@ -308,9 +308,6 @@ MetalMemRef metalResolve(const GPUReconstructionMetalInternals* internals, const size_t GPUReconstructionMetal::GPUMemCpy(void* dst, const void* src, size_t sizeBytes, int32_t stream, int32_t toGPU, deviceEvent* ev, deviceEvent* evList, int32_t nEvents) { - if (evList == nullptr) { - nEvents = 0; - } if (GetProcessingSettings().debugLevel >= 3) { stream = -1; } @@ -320,7 +317,7 @@ MetalMemRef metalResolve(const GPUReconstructionMetalInternals* internals, const } auto realStream = stream == -1 ? 0 : stream; - if (nEvents) { + if (evList && nEvents) { StreamWaitForEvents(realStream, evList, nEvents); } const MetalMemRef s = metalResolve(mInternals, src); @@ -528,9 +525,9 @@ MetalMemRef metalResolve(const GPUReconstructionMetalInternals* internals, const } // Encode commands to wait for all the events id cb = mInternals->commandBuffers[stream]; - for (int32_t ei = 0; ei < nEvents; ei++) { - auto mtlEvent = (__bridge id)(evList[ei].get()); - if (const uint64_t value = EventValue(evList[ei], false)) { + for (auto& ev : std::span(evList, nEvents)) { + auto mtlEvent = (__bridge id)(ev.get()); + if (const uint64_t value = EventValue(ev, false)) { [cb encodeWaitForEvent:mtlEvent value:value]; metalTimelineAdd(mInternals, stream, "w", mtlEvent, value); } @@ -541,9 +538,9 @@ MetalMemRef metalResolve(const GPUReconstructionMetalInternals* internals, const bool GPUReconstructionMetal::IsEventDone(deviceEvent* evList, int32_t nEvents) { - for (int32_t i = 0; i < nEvents; i++) { - auto mtlEvent = (__bridge id)(evList[i].get()); - if (mtlEvent.signaledValue < EventValue(evList[i], false)) { + for (auto& ev : std::span(evList, nEvents)) { + auto mtlEvent = (__bridge id)(ev.get()); + if (mtlEvent.signaledValue < EventValue(ev, false)) { return false; } } diff --git a/GPU/GPUTracking/Base/opencl/GPUReconstructionOCL.cxx b/GPU/GPUTracking/Base/opencl/GPUReconstructionOCL.cxx index dcd3be16599d4..d8d921f550dcf 100644 --- a/GPU/GPUTracking/Base/opencl/GPUReconstructionOCL.cxx +++ b/GPU/GPUTracking/Base/opencl/GPUReconstructionOCL.cxx @@ -19,6 +19,7 @@ #include #include #include +#include #include #include @@ -413,8 +414,8 @@ int32_t GPUReconstructionOCL::ExitDevice_Runtime() if (mDeviceMemoryBase) { clReleaseMemObject(mInternals->mem_gpu); clReleaseMemObject(mInternals->mem_constant); - for (uint32_t i = 0; i < mInternals->kernels.size(); i++) { - clReleaseKernel(mInternals->kernels[i]); + for (auto& kernel : mInternals->kernels) { + clReleaseKernel(kernel); } mInternals->kernels.clear(); } @@ -501,8 +502,8 @@ void GPUReconstructionOCL::StreamWaitForEvents(int32_t stream, deviceEvent* evLi bool GPUReconstructionOCL::IsEventDone(deviceEvent* evList, int32_t nEvents) { cl_int eventdone; - for (int32_t i = 0; i < nEvents; i++) { - GPUChkErr(clGetEventInfo(evList[i].get(), CL_EVENT_COMMAND_EXECUTION_STATUS, sizeof(eventdone), &eventdone, nullptr)); + for (auto& ev : std::span(evList, nEvents)) { + GPUChkErr(clGetEventInfo(ev.get(), CL_EVENT_COMMAND_EXECUTION_STATUS, sizeof(eventdone), &eventdone, nullptr)); if (eventdone != CL_COMPLETE) { return false; } From 9740e8a27b368370a59d0355ddfdcb9d2f4e978e Mon Sep 17 00:00:00 2001 From: David Rohr Date: Tue, 1 Dec 2026 22:41:22 +0100 Subject: [PATCH 38/41] GPU Standalone: Add script for benchmarking --- .../Standalone/scripts/benchmarkCommits.py | 92 +++++++++++++++++++ 1 file changed, 92 insertions(+) create mode 100755 GPU/GPUTracking/Standalone/scripts/benchmarkCommits.py diff --git a/GPU/GPUTracking/Standalone/scripts/benchmarkCommits.py b/GPU/GPUTracking/Standalone/scripts/benchmarkCommits.py new file mode 100755 index 0000000000000..3a0ef2d0c6cca --- /dev/null +++ b/GPU/GPUTracking/Standalone/scripts/benchmarkCommits.py @@ -0,0 +1,92 @@ +#!/usr/bin/env python3 +# Copyright 2019-2026 CERN and copyright holders of ALICE O2. +# See https://alice-o2.web.cern.ch/copyright for details of the copyright holders. +# All rights not expressly granted are reserved. +# +# This software is distributed under the terms of the GNU General Public +# License v3 (GPL Version 3), copied verbatim in the file "COPYING". +# +# In applying this license CERN does not waive the privileges and immunities +# granted to it by virtue of its status as an Intergovernmental Organization +# or submit itself to any jurisdiction. + +# Usage: benchmarkCommits.py RESULT_DIR STANDALONE_DIR FIRST_COMMIT LAST_COMMIT [ca options...], to be run in the environment of the standalone build (prepare.sh). +# Builds and benchmarks every commit in the range (any git revision: hash, branch, tag, HEAD~2, ...) that has no folder RESULT_DIR/benchmarkResults/ yet, and stores the ca outputs there. +# The checkouts may change or remove this file: that is safe, since Python has compiled the whole script before it runs, and it must stay a single file without imports after startup. + +import os +import shlex +import shutil +import subprocess +import sys + +RUNS = [("pipelined", ["--PROCdoublePipeline", "--runs", "10", "-e", "reference_50kHz"]), + ("taskTimes", ["--runs", "5", "-e", "reference_50kHz", "--PROCrecoTaskTiming", "1"]), + ("kernelTimes", ["--runs", "5", "-e", "reference_50kHz", "--debug", "1"]), + ("qa", ["-e", "sim-pbpb-50", "--qa"])] + + +def git(src, *args, check=True): + p = subprocess.run(["git", "-C", src] + list(args), stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) + if check and p.returncode: + sys.exit("git " + " ".join(args) + " failed: " + p.stderr.strip()) + return p.stdout.strip() if check else p.returncode + + +if len(sys.argv) < 5: + sys.exit("Usage: " + sys.argv[0] + " RESULT_DIR STANDALONE_DIR FIRST_COMMIT LAST_COMMIT [ca options...]") +resultDir = os.path.join(os.path.abspath(sys.argv[1]), "benchmarkResults") +caDir = os.path.abspath(sys.argv[2]) +userArgs = sys.argv[5:] +src = os.path.join(caDir, "src") +if not os.path.isdir(resultDir): + sys.exit("Folder " + resultDir + " does not exist") +if not (os.path.isfile(os.path.join(caDir, "ca")) and os.access(os.path.join(caDir, "ca"), os.X_OK)): + sys.exit("No ca binary in " + caDir) +if not any(os.path.isfile(os.path.join(caDir, f)) for f in ("makefile", "Makefile")): + sys.exit("No makefile in " + caDir) +if not (os.path.islink(src) and os.path.isdir(src)): + sys.exit(src + " is not a symlink to the sources") + +if git(src, "status", "--porcelain", "--untracked-files=no"): + sys.exit("Source folder " + os.path.realpath(src) + " has uncommitted changes") +origHead = git(src, "rev-parse", "--abbrev-ref", "HEAD") # branch name, or the hash if detached +if origHead == "HEAD": + origHead = git(src, "rev-parse", "HEAD") +first, last = (git(src, "rev-parse", "--verify", c + "^{commit}") for c in sys.argv[3:5]) +if git(src, "merge-base", "--is-ancestor", first, last, check=False): + if git(src, "merge-base", "--is-ancestor", last, first, check=False): + sys.exit("Commit " + sys.argv[3] + " is not an ancestor of " + sys.argv[4]) + first, last = last, first # range given in reverse order +commits = [first] + git(src, "rev-list", "--reverse", first + ".." + last).split() +todo = [c for c in commits if not os.path.exists(os.path.join(resultDir, c))] +print("%d commits in range, %d already benchmarked, source currently at %s" % (len(commits), len(commits) - len(todo), origHead), flush=True) + +try: + for iCommit, commit in enumerate(todo): + commitDir = os.path.join(resultDir, commit) + os.mkdir(commitDir) + shutil.copyfile(os.path.join(caDir, "config.cmake"), os.path.join(commitDir, "config.cmake")) # follows symlinks + git(src, "checkout", "-q", "--detach", commit) + print("Building commit %d/%d (%s)" % (iCommit + 1, len(todo), commit), flush=True) + build = subprocess.run(["make", "-j", str(os.cpu_count())], cwd=caDir, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) + if build.returncode: + with open(os.path.join(commitDir, "compilation.failed"), "wb") as f: + f.write(build.stdout) + print("Compilation failed", flush=True) + continue + with open(os.path.join(commitDir, "command.txt"), "w") as fCmd: + for iRun, (name, args) in enumerate(RUNS): + cmd = ["./ca"] + args + userArgs + print("Benchmarking commit %d/%d (%s), runs %d/%d (%s)" % (iCommit + 1, len(todo), commit, iRun + 1, len(RUNS), shlex.join(cmd)), flush=True) + fCmd.write(name + ": " + shlex.join(cmd) + "\n") + fCmd.flush() + outFile = os.path.join(commitDir, name + ".txt") + with open(outFile, "wb") as f: + ret = subprocess.run(cmd, cwd=caDir, stdin=subprocess.DEVNULL, stdout=f, stderr=subprocess.STDOUT).returncode + if ret: + os.rename(outFile, os.path.join(commitDir, name + ".failed")) + print("Run failed with return value %d" % ret, flush=True) +finally: + git(src, "checkout", "-q", origHead) + print("Restored source to " + origHead + " (the build in " + caDir + " is from the last benchmarked commit)", flush=True) From bdede69d64543ac9951dbeb94264382204147806 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Tue, 1 Dec 2026 22:41:46 +0100 Subject: [PATCH 39/41] GPU: Fix typo --- GPU/GPUTracking/Base/GPUReconstructionTimeframe.cxx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/GPU/GPUTracking/Base/GPUReconstructionTimeframe.cxx b/GPU/GPUTracking/Base/GPUReconstructionTimeframe.cxx index d7d9f872db47c..4efde8793de13 100644 --- a/GPU/GPUTracking/Base/GPUReconstructionTimeframe.cxx +++ b/GPU/GPUTracking/Base/GPUReconstructionTimeframe.cxx @@ -87,7 +87,7 @@ int32_t GPUReconstructionTimeframe::ReadEventShifted(int32_t iEvent, float shift } for (uint32_t i = 0; i < mChain->mIOPtrs.nMCInfosTPC; i++) { auto& tmp = mChain->mIOMem.mcInfosTPC[i]; - tmp.z += i < NSECTORS / 2 ? shiftZ : -shiftZ; + tmp.z += tmp.z >= 0 ? shiftZ : -shiftZ; } } From 4e54e8b78e76ce8f488b1f422fae946ccb08a3e0 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Tue, 1 Dec 2026 23:05:53 +0100 Subject: [PATCH 40/41] GPU: Modernize C++: Use some range-based algorithms --- GPU/GPUTracking/Base/GPUReconstruction.cxx | 9 ++------- .../Base/GPUReconstructionConvert.cxx | 13 ++----------- .../Base/GPUReconstructionRTCHelpers.inc | 19 +++++++++---------- .../cpudevice/GPUReconstructionCPUDevice.cxx | 15 ++++----------- 4 files changed, 17 insertions(+), 39 deletions(-) diff --git a/GPU/GPUTracking/Base/GPUReconstruction.cxx b/GPU/GPUTracking/Base/GPUReconstruction.cxx index 3aa542690854c..b923f348fd500 100644 --- a/GPU/GPUTracking/Base/GPUReconstruction.cxx +++ b/GPU/GPUTracking/Base/GPUReconstruction.cxx @@ -21,6 +21,7 @@ #include #include #include +#include #include #include #include @@ -1244,13 +1245,7 @@ void GPUReconstruction::PrepareEvent() // TODO: Clean this up, this should not b int32_t GPUReconstruction::CheckErrorCodes(bool cpuOnly, bool forceShowErrors, std::vector>* fillErrors) { - int32_t retVal = 0; - for (auto& chain : mChains) { - if (chain->CheckErrorCodes(cpuOnly, forceShowErrors, fillErrors)) { - retVal++; - } - } - return retVal; + return std::ranges::count_if(mChains, [&](auto& chain) { return chain->CheckErrorCodes(cpuOnly, forceShowErrors, fillErrors) != 0; }); } int32_t GPUReconstruction::GPUChkErrA(const int64_t retval, const char* file, int32_t line, bool failOnError) diff --git a/GPU/GPUTracking/Base/GPUReconstructionConvert.cxx b/GPU/GPUTracking/Base/GPUReconstructionConvert.cxx index a70b546d2d91d..8dc72c1736aff 100644 --- a/GPU/GPUTracking/Base/GPUReconstructionConvert.cxx +++ b/GPU/GPUTracking/Base/GPUReconstructionConvert.cxx @@ -744,16 +744,7 @@ bool zsEncoderDenseLinkBased::writeSubPage() { uint32_t offset = sequenceBuffer.size(); if (sequenceBufferADC.size()) { - bool need12bit = zsVersion != ZSVersion::ZSVersionDenseLinkBasedV2; - uint32_t needNow = 0; - if (zsVersion == ZSVersion::ZSVersionDenseLinkBasedV2) { - for (uint32_t i = 0; i < sequenceBufferADC.size(); i++) { - if (sequenceBufferADC[i] >= (1 << v2nbits)) { - need12bit = true; - break; - } - } - } + bool need12bit = zsVersion != ZSVersion::ZSVersionDenseLinkBasedV2 || std::ranges::any_of(sequenceBufferADC, [](auto v) { return v >= (1 << v2nbits); }); uint32_t encodeBitsBlock = encodeBits; if (!need12bit) { encodeBitsBlock = v2nbits; @@ -1047,7 +1038,7 @@ inline uint32_t zsEncoderRun::run(std::vector* buffer, std::vector #include #include +#include #include #include #include @@ -89,13 +90,11 @@ static void loadLaunchBounds(const GPUSettingsProcessing& proc, GPUDefParameters } } std::vector overrides; - const std::string& str = proc.rtctech.overrideRTCParameters; - for (size_t pos = 0; pos < str.size();) { - const size_t end = std::min(str.find(';', pos), str.size()), first = str.find_first_not_of(' ', pos); - if (first < end) { - overrides.emplace_back(str.substr(first, str.find_last_not_of(' ', end - 1) - first + 1)); + for (const auto part : proc.rtctech.overrideRTCParameters | std::views::split(';')) { + const std::string_view s(part.begin(), part.end()); + if (const size_t first = s.find_first_not_of(' '); first != s.npos) { + overrides.emplace_back(s.substr(first, s.find_last_not_of(' ') - first + 1)); } - pos = end + 1; } o2::gpu::internal::GPUDefParametersOverride(par, overrides); } @@ -112,7 +111,7 @@ static std::string launchBoundsCode(const GPUSettingsProcessing& proc, const GPU static bool deterministic(const GPUSettingsProcessing& proc, const std::string& kernelName) { - return proc.rtc.deterministic || (proc.rtc.compilePerKernel && noFastMathKernels.find(kernelName) != noFastMathKernels.end()); + return proc.rtc.deterministic || (proc.rtc.compilePerKernel && noFastMathKernels.contains(kernelName)); } static void writeSource(const std::string& file, bool deterministic, const std::string& param, const std::string& launchBounds, std::string_view source, const std::string& kernel) @@ -288,9 +287,9 @@ class Cache // RTC cache file /rtc..cache. (no id with if (files.size() < mProc.rtctech.cacheSize) { return; } - std::sort(files.begin(), files.end(), std::greater<>()); // Most recent first - for (uint32_t i = mProc.rtctech.cacheSize - 1; i < files.size(); i++) { - std::filesystem::remove(files[i].second, ec); + std::ranges::sort(files, std::greater<>()); // Most recent first + for (const auto& file : files | std::views::drop(mProc.rtctech.cacheSize - 1)) { + std::filesystem::remove(file.second, ec); } } diff --git a/GPU/GPUTracking/Base/cpudevice/GPUReconstructionCPUDevice.cxx b/GPU/GPUTracking/Base/cpudevice/GPUReconstructionCPUDevice.cxx index 51cf3fad51c2e..8442ddd695ccd 100644 --- a/GPU/GPUTracking/Base/cpudevice/GPUReconstructionCPUDevice.cxx +++ b/GPU/GPUTracking/Base/cpudevice/GPUReconstructionCPUDevice.cxx @@ -43,9 +43,7 @@ GPUReconstructionCPUDevice::GPUReconstructionCPUDevice(const GPUSettingsDeviceBa mInternalsOwner = std::make_unique(); mInternals = mInternalsOwner.get(); *mParDevice = *mParCPU; // We run the host-compiled CPU kernels on the "device", so the device parameters must be the CPU kernel parameters. Other values are possible only with RTC (genRTC), checked in InitDevice_Runtime - for (auto& v : mParDevice->par_LB_maxThreads) { - v = 1; - } + std::ranges::fill(mParDevice->par_LB_maxThreads, 1); } mDeviceBackendSettings->deviceType = DeviceType::CPUDEVICE; } @@ -237,14 +235,9 @@ void GPUReconstructionCPUDeviceInternals::completeEvent(GPUReconstructionCPUDevi { std::lock_guard lock(e->mutex); e->nCompleted = std::max(e->nCompleted, value); - for (auto it = e->waiting.begin(); it != e->waiting.end();) { - if (it->value <= e->nCompleted) { - resume.emplace_back(*it); - it = e->waiting.erase(it); - } else { - it++; - } - } + auto done = std::ranges::stable_partition(e->waiting, [e](const auto& w) { return w.value > e->nCompleted; }); + resume.assign(done.begin(), done.end()); + e->waiting.erase(done.begin(), done.end()); e->cv.notify_all(); } for (auto& w : resume) { From de88ea5975a2e950cd565c1e56bc4de65d09f0ca Mon Sep 17 00:00:00 2001 From: David Rohr Date: Tue, 1 Dec 2026 21:24:31 +0100 Subject: [PATCH 41/41] GPU: Modernize C++: Merge 2 functions in Clusterizer Code --- GPU/GPUTracking/TPCClusterFinder/CfUtils.h | 84 ++++++++++------------ 1 file changed, 39 insertions(+), 45 deletions(-) diff --git a/GPU/GPUTracking/TPCClusterFinder/CfUtils.h b/GPU/GPUTracking/TPCClusterFinder/CfUtils.h index 7a3166452315d..469674c8f904c 100644 --- a/GPU/GPUTracking/TPCClusterFinder/CfUtils.h +++ b/GPU/GPUTracking/TPCClusterFinder/CfUtils.h @@ -177,36 +177,7 @@ class CfUtils const CfChargePos* posBcast, GPUgeneric() T* buf) { -#if defined(GPUCA_GPUCODE) && !defined(GPUCA_DEVICE_SINGLE_THREAD) // Cooperative load by the threads of the block - GPUbarrier(); - uint16_t x = ll % N; - uint16_t y = ll / N; - tpccf::Delta2 d = neighbors[x + offset]; - - for (uint32_t i = y; i < wgSize; i += (elems / N)) { - CfChargePos readFrom = posBcast[i]; - uint32_t writeTo = N * i + x; - buf[writeTo] = map[readFrom.delta(d)]; - } - GPUbarrier(); -#else - if (ll >= wgSize) { - return; - } - - CfChargePos readFrom = posBcast[ll]; - - GPUbarrier(); - - for (uint32_t i = 0; i < N; i++) { - tpccf::Delta2 d = neighbors[i + offset]; - - uint32_t writeTo = N * ll + i; - buf[writeTo] = map[readFrom.delta(d)]; - } - - GPUbarrier(); -#endif + blockLoadImpl(map, wgSize, elems, ll, offset, N, neighbors, posBcast, nullptr, buf); } template @@ -222,22 +193,42 @@ class CfUtils const uint8_t* aboveThreshold, GPUgeneric() T* buf) { + blockLoadImpl(map, wgSize, elems, ll, offset, N, neighbors, posBcast, aboveThreshold, buf); + } + + private: + template // CondMode: 0 = load all, 1 = only if innerAboveThreshold, 2 = only if innerAboveThresholdInv + static GPUdi() void blockLoadImpl( + const CfArray2D& map, + S wgSize, + S elems, + uint16_t ll, + S offset, + S N, + GPUconstexprref() const tpccf::Delta2* neighbors, + const CfChargePos* posBcast, + const uint8_t* aboveThreshold, + GPUgeneric() T* buf) + { #if defined(GPUCA_GPUCODE) && !defined(GPUCA_DEVICE_SINGLE_THREAD) // Cooperative load by the threads of the block GPUbarrier(); - uint16_t y = ll / N; uint16_t x = ll % N; + uint16_t y = ll / N; tpccf::Delta2 d = neighbors[x + offset]; + for (uint32_t i = y; i < wgSize; i += (elems / N)) { CfChargePos readFrom = posBcast[i]; - uint8_t above = aboveThreshold[i]; + [[maybe_unused]] uint8_t above = CondMode ? aboveThreshold[i] : 0; uint32_t writeTo = N * i + x; - T v(0); - bool cond = (Inv) ? innerAboveThresholdInv(above, x + offset) - : innerAboveThreshold(above, x + offset); - if (cond) { - v = map[readFrom.delta(d)]; + if constexpr (CondMode == 0) { + buf[writeTo] = map[readFrom.delta(d)]; + } else { + T v(0); + if ((CondMode == 2) ? innerAboveThresholdInv(above, x + offset) : innerAboveThreshold(above, x + offset)) { + v = map[readFrom.delta(d)]; + } + buf[writeTo] = v; } - buf[writeTo] = v; } GPUbarrier(); #else @@ -246,20 +237,23 @@ class CfUtils } CfChargePos readFrom = posBcast[ll]; - uint8_t above = aboveThreshold[ll]; + [[maybe_unused]] uint8_t above = CondMode ? aboveThreshold[ll] : 0; + GPUbarrier(); for (uint32_t i = 0; i < N; i++) { tpccf::Delta2 d = neighbors[i + offset]; uint32_t writeTo = N * ll + i; - T v(0); - bool cond = (Inv) ? innerAboveThresholdInv(above, i + offset) - : innerAboveThreshold(above, i + offset); - if (cond) { - v = map[readFrom.delta(d)]; + if constexpr (CondMode == 0) { + buf[writeTo] = map[readFrom.delta(d)]; + } else { + T v(0); + if ((CondMode == 2) ? innerAboveThresholdInv(above, i + offset) : innerAboveThreshold(above, i + offset)) { + v = map[readFrom.delta(d)]; + } + buf[writeTo] = v; } - buf[writeTo] = v; } GPUbarrier();