From d8ffc8407c4f585fbd5ee183c1b7a8971affd15f Mon Sep 17 00:00:00 2001 From: David Rohr Date: Mon, 30 Nov 2026 16:25:30 +0100 Subject: [PATCH 01/18] GPU: Drop obvious comments --- GPU/Common/GPUCommonAlgorithm.h | 18 ++--------- GPU/Common/GPUCommonDef.h | 12 ++----- GPU/Common/GPUCommonDefAPI.h | 32 +++---------------- GPU/Common/GPUCommonMath.h | 18 +++-------- GPU/Common/GPUCommonTypeTraits.h | 8 +---- GPU/GPUTracking/Base/GPUGeneralKernels.h | 3 +- GPU/GPUTracking/Base/GPUReconstruction.cxx | 2 +- GPU/GPUTracking/Base/GPUReconstruction.h | 6 ++-- GPU/GPUTracking/Base/GPUReconstructionCPU.cxx | 9 ++---- .../Base/GPUReconstructionKernelMacros.h | 5 +-- .../Base/GPUReconstructionRTCHelpers.inc | 18 +++++------ .../opencl/GPUReconstructionOCLIncludesHost.h | 2 +- GPU/GPUTracking/Definitions/GPUDef.h | 12 ++----- .../Definitions/GPUSettingsList.template | 6 +--- .../GPUSettingsListDisplay.template | 6 +--- GPU/GPUTracking/Global/GPUChainTracking.cxx | 2 +- .../Global/GPUChainTrackingMerger.cxx | 8 ++--- GPU/GPUTracking/Merger/GPUTPCGMMerger.cxx | 7 ++-- GPU/GPUTracking/Merger/GPUTPCGMMerger.h | 14 ++++---- .../Merger/GPUTPCGMMergerRebuildInternal.h | 10 +++--- GPU/GPUTracking/Merger/GPUTPCGMO2Output.cxx | 2 +- GPU/GPUTracking/Merger/GPUTPCGMTrackParam.cxx | 10 +++--- .../Merger/GPUTPCGlobalDebugSortKernels.cxx | 4 +-- .../Standalone/Benchmark/standalone.cxx | 2 +- GPU/GPUTracking/display/GPUDisplay.cxx | 10 +++--- .../display/backend/GPUDisplayBackendOpenGL.h | 4 +-- .../backend/GPUDisplayBackendVulkan.cxx | 22 ++++++------- .../display/backend/GPUDisplayBackendVulkan.h | 2 +- .../display/frontend/GPUDisplayFrontend.cxx | 2 +- .../display/frontend/GPUDisplayFrontendX11.h | 2 +- .../display/frontend/GPUDisplayGUIWrapper.cxx | 8 ++--- .../display/frontend/GPUDisplayHelp.cxx | 4 +-- .../display/helpers/GPUDisplayAnimation.cxx | 8 ++--- .../display/helpers/GPUDisplayHelpers.cxx | 2 +- .../display/render/GPUDisplayImportEvent.cxx | 2 +- GPU/GPUTracking/qa/genEvents.cxx | 5 +-- GPU/GPUTracking/utils/vecpod.h | 2 +- GPU/Utils/GPUCommonBitSet.h | 5 +-- 38 files changed, 102 insertions(+), 192 deletions(-) diff --git a/GPU/Common/GPUCommonAlgorithm.h b/GPU/Common/GPUCommonAlgorithm.h index 477bc3c34591b..9c0ef8a31ed6b 100644 --- a/GPU/Common/GPUCommonAlgorithm.h +++ b/GPU/Common/GPUCommonAlgorithm.h @@ -332,9 +332,7 @@ GPUdi() void GPUCommonAlgorithm::swap(T& a, T& b) } #endif -// std::partition_point over the indices [first, first + count): the first index for which pred is false, pred being true on a prefix. -// A lower bound of value in a sorted key(i) is pred(i) = key(i) < value, an upper bound pred(i) = !(value < key(i)). -template +template // std::partition_point over the indices [first, first + count): the first index for which pred is false, pred being true on a prefix. A lower bound of value in a sorted key(i) is pred(i) = key(i) < value, an upper bound pred(i) = !(value < key(i)). GPUhdi() I GPUCommonAlgorithm::partitionPoint(I first, I count, const P& pred) { while (count > 0) { @@ -459,8 +457,6 @@ GPUdi() T warp_shuffle_xor(T v, int32_t laneMask) #endif } -// Butterfly all-reduce over groups of Width lanes: every lane gets the result. -// Width is a power of two and must not exceed the hardware warp size. template GPUdi() T warp_reduce_add(T v) { @@ -501,16 +497,8 @@ GPUdi() T warp_reduce_max(T v) } #elif defined(__METAL__) -// MSL has SIMD-group collectives only, so the work-group ones scan within each -// SIMD group and then across the group totals, which go through smem as with -// cub. The thread index is a kernel parameter in MSL, so like smem it is taken -// from the caller's scope. A 1D threadgroup is split into SIMD groups of -// consecutive threads, of GPUCA_WARP_SIZE each. The SIMD scans take 32-bit -// lanes; the narrower types are counts and are widened. Sums are returned -// promoted, as v + 0 would be, since the callers pass !!pred: a bool would -// truncate them to 0 / 1. They only exchange data through smem, so their -// barriers fence threadgroup memory only: a device-memory fence, as -// GPUbarrier() has, costs the stream compaction ~10%. +// MSL has only SIMD-group collectives: work-group scans run per SIMD group (GPUCA_WARP_SIZE consecutive threads, 32-bit lanes, narrower counts widened), then across the group totals via smem; the thread index comes from the caller like smem. +// Sums are returned promoted (callers pass !!pred, a bool would truncate them); barriers fence threadgroup memory only, a device-memory fence as in GPUbarrier() costs the stream compaction ~10%. template GPUdi() auto warp_scan_inclusive_add(T v) -> decltype(+v) diff --git a/GPU/Common/GPUCommonDef.h b/GPU/Common/GPUCommonDef.h index 0e7c54f296300..85f65617412ff 100644 --- a/GPU/Common/GPUCommonDef.h +++ b/GPU/Common/GPUCommonDef.h @@ -60,10 +60,7 @@ #define GPUCA_ALIGPUCODE // Part of GPUTracking library but not of interface #endif -// __METAL__ unconditionally: the MSL generic address space does not span -// `constant`, so a generic member function cannot be called on an object living -// there, and the shared code is generic throughout. -#if (defined(__CUDACC__) && defined(GPUCA_CUDA_NO_CONSTANT_MEMORY)) || (defined(__HIPCC__) && defined(GPUCA_HIP_NO_CONSTANT_MEMORY)) || (defined(__OPENCL__) && defined(GPUCA_OPENCL_NO_CONSTANT_MEMORY)) || defined(__METAL__) +#if (defined(__CUDACC__) && defined(GPUCA_CUDA_NO_CONSTANT_MEMORY)) || (defined(__HIPCC__) && defined(GPUCA_HIP_NO_CONSTANT_MEMORY)) || (defined(__OPENCL__) && defined(GPUCA_OPENCL_NO_CONSTANT_MEMORY)) || defined(__METAL__) // __METAL__ unconditionally: the MSL generic address space does not span `constant` #define GPUCA_NO_CONSTANT_MEMORY #elif (defined(__CUDACC__) || defined(__HIPCC__)) && !defined(GPUCA_GPUCODE_HOSTONLY) #define GPUCA_HAS_GLOBAL_SYMBOL_CONSTANT_MEM @@ -84,10 +81,7 @@ #endif #if defined(GPUCA_DETERMINISTIC_MODE) && defined(__METAL__) - // The deterministic paths compute the transcendentals in double (see - // GPUCommonMath::SinCos). The emulated double is bit-exact for + - * / but - // its sin and cos are within 2 ulp of libm, not identical to it, so the - // results could not match the other backends. + // The emulated double on metal is bit-exact for + - * / but its sin and cos are within 2 ulp of libm #error "GPUCA_DETERMINISTIC_MODE is not supported on Metal" #endif @@ -99,7 +93,7 @@ #endif #endif -#ifdef GPUCA_GPUCODE // Macros, not functions: the arguments contain code that exists only on the CPU +#ifdef GPUCA_GPUCODE #define GPUCA_IGNORE_ON_GPU(...) #else #define GPUCA_IGNORE_ON_GPU(...) __VA_ARGS__ diff --git a/GPU/Common/GPUCommonDefAPI.h b/GPU/Common/GPUCommonDefAPI.h index 07543797f55b9..8af0a4ff58802 100644 --- a/GPU/Common/GPUCommonDefAPI.h +++ b/GPU/Common/GPUCommonDefAPI.h @@ -126,25 +126,7 @@ #if (!defined(__OPENCL__) || !defined(GPUCA_NO_CONSTANT_MEMORY)) #define GPUconstantref() GPUconstant() #endif -#elif defined(__METAL__) //Defines for Metal Shading Language - // ADDRESS SPACES. This backend targets MSL 4.1 (macOS 27) and later only -- - // see -std=metal4.1 in the CMakeLists, which fails the build on anything - // older rather than miscompiling quietly. - // - // That version is what makes the port tractable: up to MSL 4.0 a member - // function's implicit `this` is `thread`, which is wrong for us, since most - // objects the kernels touch live in `device` memory. Pinning defaulted - // constructors and operators to `device` was the 4.0 workaround, and it made - // the same type unusable in `thread` or `threadgroup`. In 4.1 an unannotated - // `this` is GENERIC and resolves to whichever address space the object is in - // -- the C++ semantics this codebase already assumes -- so GPUdDefault() - // needs nothing at all. The compiler resolves it statically in almost every - // case; it only falls back to a runtime branch where it cannot see through, - // such as argument buffers or dynamic libraries. - // - // The *ref() macros below stay explicit even so. They are already correct - // from the OpenCL port, an explicit annotation is never slower than a generic - // one, and `constant` is not covered by generic pointers at all. +#elif defined(__METAL__) //Defines for Metal Shading Language: ADDRESS SPACES. This backend targets MSL 4.1 (macOS 27) and later only #define GPUdDefault() // generic `this` (MSL 4.1+) #define GPUd() #define GPUhdDefault() @@ -271,10 +253,7 @@ #define get_group_id(dim) (blockIdx.x) #elif defined(__OPENCL__) // Using OpenCL defaults -#elif defined(__METAL__) - // MSL has no work-item builtins. They arrive as attributes on the entry point, - // named there after the nBlocks / nThreads / iBlock / iThread that Thread() - // already takes, so these resolve both there and in every function below it. +#elif defined(__METAL__) // MSL has no work-item builtins. They arrive as attributes on the entry point, named there after the nBlocks / nThreads / iBlock / iThread that Thread() already takes, so these resolve both there and in every function below it. #define get_global_id(dim) (iBlock * nThreads + iThread) #define get_global_size(dim) (nBlocks * nThreads) #define get_num_groups(dim) (nBlocks) @@ -290,9 +269,7 @@ #define get_group_id(dim) iBlock #endif -// A device function that uses the helpers above but has none of the indices in -// scope needs them passed in on Metal, where they are ordinary parameters. -// Both expand to nothing everywhere else, and go last in the parameter list. +// A device function that uses the helpers above but has none of the indices in scope needs them passed in on Metal, where they are ordinary parameters. Both expand to nothing everywhere else, and go last in the parameter list. #ifdef __METAL__ #define GPUCA_THREAD_INFO_DECL , int32_t nBlocks, int32_t nThreads, int32_t iBlock, int32_t iThread #define GPUCA_THREAD_INFO_PROVIDE , nBlocks, nThreads, iBlock, iThread @@ -301,5 +278,4 @@ #define GPUCA_THREAD_INFO_PROVIDE #endif -// clang-format on -#endif +#endif // clang-format on diff --git a/GPU/Common/GPUCommonMath.h b/GPU/Common/GPUCommonMath.h index eb0fd6f11dee1..8c25f376d9e3a 100644 --- a/GPU/Common/GPUCommonMath.h +++ b/GPU/Common/GPUCommonMath.h @@ -363,8 +363,7 @@ GPUhdi() void GPUCommonMath::SinCos(float x, float& s, float& c) __sincosf(x, &s, &c); #elif !defined(GPUCA_GPUCODE_DEVICE) && (defined(__GNU_SOURCE__) || defined(_GNU_SOURCE) || defined(GPUCA_GPUCODE)) sincosf(x, &s, &c); -#elif defined(__METAL__) // MSL's sincos returns sin and takes cos by thread - // reference, so it cannot write through a generic one +#elif defined(__METAL__) // MSL's sincos returns sin and takes cos by thread reference, so it cannot write through a generic one float metalCos; s = sincos(x, metalCos); c = metalCos; @@ -568,10 +567,8 @@ GPUhdi() constexpr double GPUCommonMath::Abs(double x) { return GPUdoubleBinary64::fromBits(x.bits() & ~GPUCA_B64_SIGN); } -// metal::fabs is not constant-evaluable, so this also fails to compile if the -// specialisation above is ever dropped and the call falls back to it in float -static_assert(GPUCommonMath::Abs(GPUdoubleBinary64::fromBits(0xBFF0000000000001ULL)).bits() == 0x3FF0000000000001ULL, - "Abs on the emulated double must clear the sign bit and keep every other one"); +// metal::fabs is not constant-evaluable, so this also fails to compile if the specialisation above is ever dropped and the call falls back to it in float +static_assert(GPUCommonMath::Abs(GPUdoubleBinary64::fromBits(0xBFF0000000000001ULL)).bits() == 0x3FF0000000000001ULL, "Abs on the emulated double must clear the sign bit and keep every other one"); #else template <> GPUhdi() constexpr double GPUCommonMath::Abs(double x) @@ -586,13 +583,7 @@ GPUhdi() constexpr int32_t GPUCommonMath::Abs(int32_t x) return GPUCA_CHOICE(abs(x), abs(x), abs(x)); } -#ifdef __METAL__ -// The counters these operate on are plain integers in the transferred structures, -// as they are for CUDA and HIP. MSL's atomic operations want metal::atomic, which -// has the same size and alignment. The overload is picked by address space, and a -// threadgroup pointer has to keep its own: casting one to a device atomic is an -// error while the qualifier is visible, but a generic pointer resolves here to -// device and the cast then goes through silently. +#ifdef __METAL__ // All atomics must have the same size as plain int / float types. Use metal::atomic template GPUdi() threadgroup metal::atomic* GPUCommonMathMetalAtomic(threadgroup T* p) { @@ -697,7 +688,6 @@ GPUdi() void GPUCommonMath::AtomicMinInternal(S* addr, T val) #endif // GPUCA_GPUCODE } -// Relaxed, as the device atomics above template GPUdi() T GPUCommonMath::AtomicLoadInternal(S* addr) { diff --git a/GPU/Common/GPUCommonTypeTraits.h b/GPU/Common/GPUCommonTypeTraits.h index ff73f8601d8ad..867f5b09d911e 100644 --- a/GPU/Common/GPUCommonTypeTraits.h +++ b/GPU/Common/GPUCommonTypeTraits.h @@ -22,10 +22,6 @@ #include #endif #else // OpenCL C++ and Metal, neither of which provides -// Spelled for MSL, which OpenCL C++ also accepts, so both backends share one implementation: -// enum values because program scope variables must be constant (MSL 4.1 spec, sec. 4.2), and -// is_pointer / is_member_pointer forward rather than inherit because MSL has no derived classes -// (sec. 1.5.4). Bare T* / T& need no address space: a partial specialization matches them all. #ifdef __METAL__ #define GPUCA_TT_PROGRAMSCOPE constant #else @@ -118,9 +114,7 @@ struct is_pointer_t { }; template struct is_pointer { -#ifdef __METAL__ - // A bare T* partial specialization does not match a pointer type deduced from - // an argument, which carries its address space; metal::is_pointer does. +#ifdef __METAL__ // A bare T* partial specialization does not match a pointer type deduced from an argument, which carries its address space; metal::is_pointer does. enum { value = metal::is_pointer::value }; #else enum { value = is_pointer_t::type>::value }; diff --git a/GPU/GPUTracking/Base/GPUGeneralKernels.h b/GPU/GPUTracking/Base/GPUGeneralKernels.h index 904d66a79d6ee..e4e172d583795 100644 --- a/GPU/GPUTracking/Base/GPUGeneralKernels.h +++ b/GPU/GPUTracking/Base/GPUGeneralKernels.h @@ -76,8 +76,7 @@ class GPUKernelTemplate int32_t tmpBroadcast; int32_t warpPredicateSum[I / GPUCA_WARP_SIZE]; }; -#elif defined(__METAL__) && defined(GPUCA_GPUCODE) - // What the Metal work-group collectives in GPUCommonAlgorithm.h go through +#elif defined(__METAL__) && defined(GPUCA_GPUCODE) // For Metal work-group collectives in GPUCommonAlgorithm.h union { int32_t tmpBroadcast; int32_t warpPredicateSum[I / GPUCA_WARP_SIZE]; diff --git a/GPU/GPUTracking/Base/GPUReconstruction.cxx b/GPU/GPUTracking/Base/GPUReconstruction.cxx index 93acca09f4119..103bfe75f0b27 100644 --- a/GPU/GPUTracking/Base/GPUReconstruction.cxx +++ b/GPU/GPUTracking/Base/GPUReconstruction.cxx @@ -932,7 +932,7 @@ void GPUReconstruction::PopNonPersistentMemory(RecoStep step, uint64_t tag, cons mNonPersistentIndividualDirectAllocations.resize(std::get<3>(mNonPersistentMemoryStack.back())); mNonPersistentMemoryStack.pop_back(); } - if (!proc && GetProcessingSettings().queryHostMemoryUSS) { // Outside of the lock above + if (!proc && GetProcessingSettings().queryHostMemoryUSS) { QueryHostMemoryUSS(("pop " + qTag2Str(tag)).c_str()); } } diff --git a/GPU/GPUTracking/Base/GPUReconstruction.h b/GPU/GPUTracking/Base/GPUReconstruction.h index b9ad0d96904f3..68e2359434bc7 100644 --- a/GPU/GPUTracking/Base/GPUReconstruction.h +++ b/GPU/GPUTracking/Base/GPUReconstruction.h @@ -133,7 +133,7 @@ class GPUReconstruction enum class krnlDeviceType : int32_t { CPU = 0, Device = 1, Auto = -1, - HostOnDeviceMemory = 2 }; // CPU code on the host, on the device memory (UNIFIED_MEM_SORT_ON_HOST) + HostOnDeviceMemory = 2 }; struct deviceEvent; struct threadContext; @@ -146,7 +146,7 @@ class GPUReconstruction int32_t Finalize(); int32_t Exit(); - void DumpSettings(const char* dir = "", const GPUSettingsGRP* grp = nullptr); // grp: write these GRP settings instead of the current ones + void DumpSettings(const char* dir = "", const GPUSettingsGRP* grp = nullptr); int32_t ReadSettings(const char* dir = ""); void PrepareEvent(); @@ -193,7 +193,7 @@ class GPUReconstruction void PrintMemoryStatistics(); void PrintMemoryOverview(); void PrintMemoryMax(); - void QueryHostMemoryUSS(const char* where); // With queryHostMemoryUSS: query the USS of the process and keep track of the maximum + void QueryHostMemoryUSS(const char* where); void PrintHostMemoryUSSMax(); void SetMemoryExternalInput(int16_t res, void* ptr); GPUMemorySizeScalers* MemoryScalers() { return mMemoryScalers.get(); } diff --git a/GPU/GPUTracking/Base/GPUReconstructionCPU.cxx b/GPU/GPUTracking/Base/GPUReconstructionCPU.cxx index 6b7a11f246c23..1fac85cf3706c 100644 --- a/GPU/GPUTracking/Base/GPUReconstructionCPU.cxx +++ b/GPU/GPUTracking/Base/GPUReconstructionCPU.cxx @@ -106,12 +106,7 @@ const void* GPUReconstructionCPU::HostPointer(const void* ptr) const return mDeviceMemoryHostView && offset < mDeviceMemorySize ? (const char*)mDeviceMemoryHostView + offset : ptr; } -// A kernel run with krnlDeviceType::HostOnDeviceMemory, on a GPU sharing its memory with the host -// (UNIFIED_MEM_SORT_ON_HOST), runs the CPU code on the device processors, once the work before it in -// the stream is done. If the whole device address space is valid on the host (see mDeviceMemoryHostView), -// directly on the constant memory of the device. Otherwise on a copy of the device processors pointing -// at the host view of the device memory, with the host's parameters and calibration objects. The copy -// is their constant memory. +// Copy of device processor, with host-accessible device memory pointers, and pointers to Params and ConstantMem on host GPUConstantMem* GPUReconstructionCPU::DeviceProcessorOnHostView(const krnlSetupTime& _xyz, std::unique_ptr& copy) { if (mDeviceMemoryHostView == nullptr) { @@ -357,7 +352,7 @@ int32_t GPUReconstructionCPU::RunChains() } } } - mStatKernelTime = kernelTotal * 1000000. / mStatNEvents; // Average kernel time per run in us, like mStatWallTime, only with debugLevel >= 1 + mStatKernelTime = kernelTotal * 1000000. / mStatNEvents; if (GetProcessingSettings().recoTaskTiming) { for (int32_t i = 0; i < gpudatatypes::N_RECO_STEPS; i++) { if (kernelStepTimes[i] != 0. || mTimersRecoSteps[i].timerTotal.GetElapsedTime() != 0.) { diff --git a/GPU/GPUTracking/Base/GPUReconstructionKernelMacros.h b/GPU/GPUTracking/Base/GPUReconstructionKernelMacros.h index 0887cadd7338d..05fbcd85f209e 100644 --- a/GPU/GPUTracking/Base/GPUReconstructionKernelMacros.h +++ b/GPU/GPUTracking/Base/GPUReconstructionKernelMacros.h @@ -63,10 +63,7 @@ #define GPUCA_ATTRRES(...) GPUCA_M_EXPAND(GPUCA_M_CAT(GPUCA_ATTRRES_, GPUCA_M_FIRST(__VA_ARGS__)))(__VA_ARGS__) // GPU Kernel entry point -// MSL requires every kernel parameter to carry an attribute, and supplies the -// grid dimensions the same way, so the backend gets to shape both ends of the -// parameter list. -#ifndef GPUCA_KRNL_SECTOR_ARG +#ifndef GPUCA_KRNL_SECTOR_ARG // Defaults for macros used by Metal #define GPUCA_KRNL_SECTOR_ARG int32_t _iSector_internal #endif #ifndef GPUCA_KRNL_GRID_ARGS diff --git a/GPU/GPUTracking/Base/GPUReconstructionRTCHelpers.inc b/GPU/GPUTracking/Base/GPUReconstructionRTCHelpers.inc index 90b7bf8c9df52..d7de633b82818 100644 --- a/GPU/GPUTracking/Base/GPUReconstructionRTCHelpers.inc +++ b/GPU/GPUTracking/Base/GPUReconstructionRTCHelpers.inc @@ -89,7 +89,7 @@ static void loadLaunchBounds(const GPUSettingsProcessing& proc, GPUDefParameters } fclose(fp); } - std::vector overrides; // Split at ;, trim spaces, skip empty entries + 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); @@ -101,17 +101,17 @@ static void loadLaunchBounds(const GPUSettingsProcessing& proc, GPUDefParameters o2::gpu::internal::GPUDefParametersOverride(par, overrides); } -static std::string launchBoundsCode(const GPUSettingsProcessing& proc, const GPUDefParameters& par, int32_t minBlockFactor, uint32_t warpSize) // Prints the launch bounds if requested +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"; if (proc.rtctech.printLaunchBounds || (proc.debugLevel >= 3 && !proc.debugSilent)) { GPUInfo("RTC Launch Bounds:\n%s", retVal.c_str()); - fflush(stdout); // printLaunchBounds == 2 ends the process via an exception, which would lose buffered output + fflush(stdout); } return retVal; } -static bool deterministic(const GPUSettingsProcessing& proc, const std::string& kernelName) // Whether compilation of kernel (or of all kernels with !compilePerKernel) uses deterministic code and no fast math +static bool deterministic(const GPUSettingsProcessing& proc, const std::string& kernelName) { return proc.rtc.deterministic || (proc.rtc.compilePerKernel && noFastMathKernels.find(kernelName) != noFastMathKernels.end()); } @@ -131,7 +131,7 @@ static void writeSource(const std::string& file, bool deterministic, const std:: fclose(fp); } -static void runCommand(const GPUSettingsProcessing& proc, std::string command, const std::string& sourceFile, const char* errorMessage) // Runs the compiler command, output suppressed depending on the debug level +static void runCommand(const GPUSettingsProcessing& proc, std::string command, const std::string& sourceFile, const char* errorMessage) { if (proc.debugLevel < 0) { command += " &> /dev/null"; @@ -150,7 +150,7 @@ static void runCommand(const GPUSettingsProcessing& proc, std::string command, c } template -static void compile(const GPUSettingsProcessing& proc, uint32_t nCompile, const char* backend, T&& compileOne) // Runs compileOne(i) for all compilations in parallel +static void compile(const GPUSettingsProcessing& proc, uint32_t nCompile, const char* backend, T&& compileOne) { if (proc.debugLevel >= 0) { GPUInfo("Starting %s RTC Compilation", backend); @@ -181,7 +181,7 @@ class Cache // RTC cache file /rtc..cache. (no id with o2::framework::internal::SHA1(shaSettings, (const char*)&mProc.rtc, sizeof(mProc.rtc)); uint64_t id = 0; for (uint32_t i = 0; i <= N_SHA; i++) { - for (uint32_t j = 0; j < 20; j += 5) { // XOR of all SHAs in 5-byte blocks + for (uint32_t j = 0; j < 20; j += 5) { uint64_t block = 0; memcpy(&block, (i < N_SHA ? mSHA[i] : shaSettings) + j, 5); id ^= block; @@ -220,7 +220,7 @@ class Cache // RTC cache file /rtc..cache. (no id with Cache(const Cache&) = delete; Cache& operator=(const Cache&) = delete; - bool load(const std::string& filename, const char* binExtension, uint32_t nCompile) // Writes the cached binaries to filename_, false if no valid cache + bool load(const std::string& filename, const char* binExtension, uint32_t nCompile) { if (!mProc.rtc.cacheOutput) { return false; @@ -234,7 +234,7 @@ class Cache // RTC cache file /rtc..cache. (no id with if (retVal) { GPUInfo("Using RTC cache file %s", mFileName.c_str()); std::error_code ec; - std::filesystem::last_write_time(mFile, std::filesystem::file_time_type::clock::now(), ec); // Mark as recently used for removeOldFiles() + std::filesystem::last_write_time(mFile, std::filesystem::file_time_type::clock::now(), ec); } return retVal; } diff --git a/GPU/GPUTracking/Base/opencl/GPUReconstructionOCLIncludesHost.h b/GPU/GPUTracking/Base/opencl/GPUReconstructionOCLIncludesHost.h index b6f71f9c451b1..0dac836f6127d 100644 --- a/GPU/GPUTracking/Base/opencl/GPUReconstructionOCLIncludesHost.h +++ b/GPU/GPUTracking/Base/opencl/GPUReconstructionOCLIncludesHost.h @@ -46,7 +46,7 @@ struct GPUReconstructionOCLInternals { cl_context context; cl_command_queue command_queue[constants::GPU_MAX_STREAMS]; cl_mem mem_gpu; - void* mem_gpu_ptr; // Device address of mem_gpu, base of the offsets into it (a slave's mDeviceMemoryBase is offset into it) + void* mem_gpu_ptr; cl_mem mem_constant; cl_mem mem_host; cl_program program; diff --git a/GPU/GPUTracking/Definitions/GPUDef.h b/GPU/GPUTracking/Definitions/GPUDef.h index d3aa2acfa51d5..8c898a6393e76 100644 --- a/GPU/GPUTracking/Definitions/GPUDef.h +++ b/GPU/GPUTracking/Definitions/GPUDef.h @@ -21,21 +21,13 @@ #include "GPUDefParametersWrapper.h" #include "GPUCommonRtypes.h" -// Macros for kernel arguments. OpenCL can only pass buffer objects, so pointers -// are masked as uint64_t and cast back inside the kernel. MSL needs an explicit -// buffer index on every parameter, but can bind a pointer directly. The index is -// emitted per argument by o2_gpu_add_kernel; 0, 1 and 2 are taken by gpu_mem, -// the constant memory and the sector index. +// Macros for kernel arguments. OpenCL passes uint64_t instead of pointers. MSL needs an explicit buffer index on every parameter idx #ifdef __OPENCL__ #define GPUPtr1(idx, a, b) uint64_t b #define GPUPtr2(a, b) ((__generic a) (a) b) #define GPUArg1(idx, a, b) a b -#elif defined(__METAL__) - // As for OpenCL, pointers travel as a 64-bit address: a pointer to a derived - // class is not a valid kernel argument type in MSL either. +#elif defined(__METAL__) // As for OpenCL, pointers travel as a 64-bit address #define GPUPtr1(idx, a, b) constant uint64_t& b [[buffer(idx)]] - // through device and then to generic: the kernel's own buffers are device - // memory, but the Thread() entry points take the pointer unannotated #define GPUPtr2(a, b) ((a)((device a)(b))) #define GPUArg1(idx, a, b) constant a& b [[buffer(idx)]] #else diff --git a/GPU/GPUTracking/Definitions/GPUSettingsList.template b/GPU/GPUTracking/Definitions/GPUSettingsList.template index 95437aade1cf4..a03f9a1d22c75 100644 --- a/GPU/GPUTracking/Definitions/GPUSettingsList.template +++ b/GPU/GPUTracking/Definitions/GPUSettingsList.template @@ -13,11 +13,7 @@ /// \author David Rohr // This file contains macros to generate all settings for the GPU Reconstruction. -// Macros are used in the following places: -// Create ConfigurableParam object for workflow. -// Configure standalone benchmark. -// Create plain-C struct for GPU code. -// Create static constexpr with default values for GPU run time compilation +// Macros are used in the following places: Create ConfigurableParam object for workflow, Configure standalone benchmark, Create plain-C struct for GPU code, Create static constexpr with default values for GPU run time compilation #include "GPUSettingsTypes.h" diff --git a/GPU/GPUTracking/Definitions/GPUSettingsListDisplay.template b/GPU/GPUTracking/Definitions/GPUSettingsListDisplay.template index b398559d1ab3f..faba76845720e 100644 --- a/GPU/GPUTracking/Definitions/GPUSettingsListDisplay.template +++ b/GPU/GPUTracking/Definitions/GPUSettingsListDisplay.template @@ -13,11 +13,7 @@ /// \author David Rohr // This file contains macros to generate all settings for the GPU Reconstruction. -// Macros are used in the following places: -// Create ConfigurableParam object for workflow. -// Configure standalone benchmark. -// Create plain-C struct for GPU code. -// Create static constexpr with default values for GPU run time compilation +// Macros are used in the following places: Create ConfigurableParam object for workflow, Configure standalone benchmark, Create plain-C struct for GPU code, Create static constexpr with default values for GPU run time compilation #include "GPUSettingsTypes.h" diff --git a/GPU/GPUTracking/Global/GPUChainTracking.cxx b/GPU/GPUTracking/Global/GPUChainTracking.cxx index 444d020f5075d..9b7331e4ff8a3 100644 --- a/GPU/GPUTracking/Global/GPUChainTracking.cxx +++ b/GPU/GPUTracking/Global/GPUChainTracking.cxx @@ -812,7 +812,7 @@ int32_t GPUChainTracking::RunChainFinalize() mCompressionStatistics->RunStatistics(mIOPtrs.clustersNative, &c, param(), GetProcessingSettings().runCompressionStatistics >= 2); } - if (GetProcessingSettings().debugDumpFinal && GetProcessingSettings().debugLevel < 6) { // With debugLevel >= 6, the full dump contains the outputs already + if (GetProcessingSettings().debugDumpFinal && GetProcessingSettings().debugLevel < 6) { DumpFinalOutput(); } diff --git a/GPU/GPUTracking/Global/GPUChainTrackingMerger.cxx b/GPU/GPUTracking/Global/GPUChainTrackingMerger.cxx index 45d64b50b5632..1686fedb41723 100644 --- a/GPU/GPUTracking/Global/GPUChainTrackingMerger.cxx +++ b/GPU/GPUTracking/Global/GPUChainTrackingMerger.cxx @@ -245,7 +245,7 @@ int32_t GPUChainTracking::RunTPCTrackingMerger(bool synchronizeOutput) runKernel(GetGridAuto(0, sortDeviceType)); runKernel(GetGridAuto(0, deviceType)); runKernel(GetGridAuto(0, deviceType)); - if (doGPU && rebuildConstrainedRows == 1) { // PrepareForFit1 computed nRebuildTrackRow, needed on the host to allocate the rebuild memory, waited for below + if (doGPU && rebuildConstrainedRows == 1) { ReleaseEvent(mEvents->single); TransferMemoryResourceLinkToHost(RecoStep::TPCMerging, Merger.MemoryResMemory(), 0, &mEvents->single); waitForTransfer = 1; @@ -270,9 +270,9 @@ int32_t GPUChainTracking::RunTPCTrackingMerger(bool synchronizeOutput) } if (param().rec.tpc.rebuildTrackInFit) { - AllocateRegisteredMemory(Merger.MemoryResRebuild()); // With constrained rows sized by nRebuildTrackRow, which was transferred to the host above + AllocateRegisteredMemory(Merger.MemoryResRebuild()); WriteToConstantMemory(RecoStep::TPCMerging, (char*)&processors()->tpcMerger - (char*)processors(), &MergerShadow, sizeof(MergerShadow), 0); - if (rebuildConstrainedRows != 2) { // 2: no cleaning, the fit stores complete rows and untouched memory shall not become physical + if (rebuildConstrainedRows != 2) { const size_t nRebuildRows = rebuildConstrainedRows == 1 ? (size_t)Merger.Memory()->nRebuildTrackRow : (size_t)Merger.NMergedTracks() * GPUTPCGeometry::NROWS; runKernel({{numBlocks, -ThreadCount(), 0, deviceType, RecoStep::TPCMerging}}, MergerShadow.ClusterCandidates(), nRebuildRows * param().rec.tpc.rebuildTrackInFitClusterCandidates * sizeof(*MergerShadow.ClusterCandidates())); runKernel({{numBlocks, -ThreadCount(), 0, deviceType, RecoStep::TPCMerging}}, MergerShadow.TrackRebuildHelperRow(), nRebuildRows * sizeof(*MergerShadow.TrackRebuildHelperRow())); @@ -389,7 +389,7 @@ int32_t GPUChainTracking::RunTPCTrackingMerger(bool synchronizeOutput) runKernel(GetGridAuto(0, deviceType)); } TransferMemoryResourceLinkToHost(RecoStep::TPCMerging, Merger.MemoryResMemory(), 0, &mEvents->single); - SynchronizeEventAndRelease(mEvents->single, doGPU); // The CUDA / HIP specialization of the sort reads nO2Tracks on the host + SynchronizeEventAndRelease(mEvents->single, doGPU); runKernel(GetGridAuto(0, sortDeviceType)); mRec->ReturnVolatileDeviceMemory(); diff --git a/GPU/GPUTracking/Merger/GPUTPCGMMerger.cxx b/GPU/GPUTracking/Merger/GPUTPCGMMerger.cxx index 7eca7c3c3efce..009ee6c529811 100644 --- a/GPU/GPUTracking/Merger/GPUTPCGMMerger.cxx +++ b/GPU/GPUTracking/Merger/GPUTPCGMMerger.cxx @@ -447,7 +447,7 @@ void* GPUTPCGMMerger::SetPointersRebuild(void* mem) void* GPUTPCGMMerger::SetPointersRebuild2(void* mem) { if (mRec->getGPUParameters(mRec->GetRecoStepsGPU() & gpudatatypes::RecoStep::TPCMerging).par_TPC_MERGER_REBUILD_CONSTRAINED_ROW_MEMORY == 1) { - computePointerWithAlignment(mem, mTrackRebuildHelperRowInfo, mNMaxTracks); // Needed before the row ranges are known + computePointerWithAlignment(mem, mTrackRebuildHelperRowInfo, mNMaxTracks); } return mem; } @@ -1241,8 +1241,7 @@ GPUd() void GPUTPCGMMerger::ResolveMergeSectors(GPUResolveSharedMemory& smem, in int32_t start, end; setBlockRange(mMemory->nUnpackedTracks, nBlocks, iBlock, start, end); - // Walk a segment chain to its end, dir 0 towards the head and 1 towards the - // tail, reporting whether target was met on the way. + // Walk a segment chain to its end, dir 0 towards the head and 1 towards the tail, reporting whether target was met on the way. auto walkSegmentChain = [tracks = mSectorTrackInfos](GPUTPCGMSectorTrack*& track, const GPUTPCGMSectorTrack* target, int32_t dir) { while (track->SegmentNeighbour(dir) >= 0) { track = &tracks[track->SegmentNeighbour(dir)]; @@ -2294,7 +2293,7 @@ GPUd() void GPUTPCGMMerger::PrepareHitWeights(int32_t nBlocks, int32_t nThreads, return c.hasCluster() ? (c.getSector() >= GPUTPCGeometry::NSECTORS / 2) : -1; }; int8_t startSide = -1, lastSide = -1; - uint32_t border = jLast + 1; // First row on the other side + uint32_t border = jLast + 1; for (uint32_t j = jFirst; j <= jLast; j++) { const int8_t s = side(j); if (startSide < 0) { // Start side: of the first two hits on the same side, hits before are dropped diff --git a/GPU/GPUTracking/Merger/GPUTPCGMMerger.h b/GPU/GPUTracking/Merger/GPUTPCGMMerger.h index c3289960d660d..0510698597f43 100644 --- a/GPU/GPUTracking/Merger/GPUTPCGMMerger.h +++ b/GPU/GPUTracking/Merger/GPUTPCGMMerger.h @@ -148,15 +148,15 @@ class GPUTPCGMMerger : public GPUProcessor GPUdi() trackRebuildHelperRow& TrackRebuildHelperRow(int32_t iTrk, uint32_t row) const; GPUdi() bool RebuildRowInRange(int32_t iTrk, uint32_t row) const; // Variants for the fit: use the temporary rows of the track if tmpRows is set (only with GPUCA_PAR_TPC_MERGER_REBUILD_CONSTRAINED_ROW_MEMORY == 2) - template // T = GPUTPCGMMergerRebuildTmp, template only to discard the code if it is empty + template GPUdi() trackRebuildHelperCandidate* ClusterCandidates(int32_t iTrk, uint32_t row, T* tmpRows) const; - template // T = GPUTPCGMMergerRebuildTmp, template only to discard the code if it is empty + template GPUdi() trackRebuildHelperRow& TrackRebuildHelperRow(int32_t iTrk, uint32_t row, T* tmpRows) const; - template // T = GPUTPCGMMergerRebuildTmp, template only to discard the code if it is empty + template GPUdi() bool RebuildRowInRange(int32_t iTrk, uint32_t row, T* tmpRows) const; - template // T = GPUTPCGMMergerRebuildTmp, template only to discard the code if it is empty + template GPUdi() void ClearRebuildTmpRows(int32_t iTrk, T* tmpRows) const; - template // T = GPUTPCGMMergerRebuildTmp, template only to discard the code if it is empty + template GPUdi() bool StoreRebuildTmpRows(int32_t iTrk, const T* tmpRows); GPUdi() uint32_t RebuildFirstRow(int32_t iTrk) const; // Row range of the track for the rebuild, all rows without GPUCA_PAR_TPC_MERGER_REBUILD_CONSTRAINED_ROW_MEMORY GPUdi() uint32_t RebuildLastRow(int32_t iTrk) const; @@ -234,8 +234,8 @@ class GPUTPCGMMerger : public GPUProcessor GPUd() void MergeLoopersInit(int32_t nBlocks, int32_t nThreads, int32_t iBlock, int32_t iThread); GPUd() void MergeLoopersSort(int32_t nBlocks, int32_t nThreads, int32_t iBlock, int32_t iThread); GPUd() void MergeLoopersMain(int32_t nBlocks, int32_t nThreads, int32_t iBlock, int32_t iThread); - GPUd() uint32_t CandidateId(uint32_t clusterId, uint8_t sector, uint8_t row) const; // Id for trackRebuildHelperCandidate (index in the sector row) of a global cluster id - GPUd() uint32_t CandidateClusterId(trackRebuildHelperCandidate candidate, uint8_t row) const; // Global cluster id of a candidate with cluster + GPUd() uint32_t CandidateId(uint32_t clusterId, uint8_t sector, uint8_t row) const; + GPUd() uint32_t CandidateClusterId(trackRebuildHelperCandidate candidate, uint8_t row) const; GPUd() void PrepareHitWeights(int32_t nBlocks, int32_t nThreads, int32_t iBlock, int32_t iThread); GPUd() void ComputeHitWeights(int32_t nBlocks, int32_t nThreads, int32_t iBlock, int32_t iThread, int32_t iteration); GPUd() void ResolveHitWeights1(int32_t nBlocks, int32_t nThreads, int32_t iBlock, int32_t iThread, int32_t iteration); diff --git a/GPU/GPUTracking/Merger/GPUTPCGMMergerRebuildInternal.h b/GPU/GPUTracking/Merger/GPUTPCGMMergerRebuildInternal.h index f6b8efe46b9c9..1a335bcc80a0d 100644 --- a/GPU/GPUTracking/Merger/GPUTPCGMMergerRebuildInternal.h +++ b/GPU/GPUTracking/Merger/GPUTPCGMMergerRebuildInternal.h @@ -118,7 +118,7 @@ GPUdi() GPUTPCGMMerger::trackRebuildHelperRow& GPUTPCGMMerger::TrackRebuildHelpe } } -template // T = GPUTPCGMMergerRebuildTmp, template only to discard the code if it is empty +template GPUdi() bool GPUTPCGMMerger::RebuildRowInRange(int32_t iTrk, uint32_t row, T* tmpRows) const { if constexpr (GPUCA_PAR_TPC_MERGER_REBUILD_CONSTRAINED_ROW_MEMORY == 2) { @@ -129,7 +129,7 @@ GPUdi() bool GPUTPCGMMerger::RebuildRowInRange(int32_t iTrk, uint32_t row, T* tm return RebuildRowInRange(iTrk, row); } -template // T = GPUTPCGMMergerRebuildTmp, template only to discard the code if it is empty +template GPUdi() GPUTPCGMMerger::trackRebuildHelperCandidate* GPUTPCGMMerger::ClusterCandidates(int32_t iTrk, uint32_t row, T* tmpRows) const { if constexpr (GPUCA_PAR_TPC_MERGER_REBUILD_CONSTRAINED_ROW_MEMORY == 2) { @@ -140,7 +140,7 @@ GPUdi() GPUTPCGMMerger::trackRebuildHelperCandidate* GPUTPCGMMerger::ClusterCand return ClusterCandidates(iTrk, row); } -template // T = GPUTPCGMMergerRebuildTmp, template only to discard the code if it is empty +template GPUdi() GPUTPCGMMerger::trackRebuildHelperRow& GPUTPCGMMerger::TrackRebuildHelperRow(int32_t iTrk, uint32_t row, T* tmpRows) const { if constexpr (GPUCA_PAR_TPC_MERGER_REBUILD_CONSTRAINED_ROW_MEMORY == 2) { @@ -151,7 +151,7 @@ GPUdi() GPUTPCGMMerger::trackRebuildHelperRow& GPUTPCGMMerger::TrackRebuildHelpe return TrackRebuildHelperRow(iTrk, row); } -template // T = GPUTPCGMMergerRebuildTmp, template only to discard the code if it is empty +template GPUdi() void GPUTPCGMMerger::ClearRebuildTmpRows(int32_t iTrk, T* tmpRows) const { if constexpr (GPUCA_PAR_TPC_MERGER_REBUILD_CONSTRAINED_ROW_MEMORY == 2) { @@ -165,7 +165,7 @@ GPUdi() void GPUTPCGMMerger::ClearRebuildTmpRows(int32_t iTrk, T* tmpRows) const } } -template // T = GPUTPCGMMergerRebuildTmp, template only to discard the code if it is empty +template GPUdi() bool GPUTPCGMMerger::StoreRebuildTmpRows(int32_t iTrk, const T* tmpRows) // Returns false if the rebuild memory is full. Stores the row range of the track: the rows filled by the fit and the rows of its clusters (PrepareHitWeights adds those as candidates) { if constexpr (GPUCA_PAR_TPC_MERGER_REBUILD_CONSTRAINED_ROW_MEMORY == 2) { diff --git a/GPU/GPUTracking/Merger/GPUTPCGMO2Output.cxx b/GPU/GPUTracking/Merger/GPUTPCGMO2Output.cxx index 1248a18ab3e86..f59e864d806a7 100644 --- a/GPU/GPUTracking/Merger/GPUTPCGMO2Output.cxx +++ b/GPU/GPUTracking/Merger/GPUTPCGMO2Output.cxx @@ -215,7 +215,7 @@ GPUdii() void GPUTPCGMO2Output::Thread(int32_t nBlocks if (track.PrevSegment() >= 0) { const GPUTPCGMMergedTrack* chkTrk = track.GetFirstSegment(tracks, merger.Param().rec.enableCyclicGraphWorkarounds); - if (chkTrk->NClusters()) { // First segment can have lost all its clusters in the rebuild, then its cluster reference is invalid + if (chkTrk->OK()) { // First segment can have lost all its clusters in the rebuild, then its cluster reference is invalid const auto& firstPrevCluster = trackClusters[chkTrk->FirstClusterRef()]; t1 = clusters->clustersLinear[firstPrevCluster.num].getTime(); sector1 = firstPrevCluster.sector; diff --git a/GPU/GPUTracking/Merger/GPUTPCGMTrackParam.cxx b/GPU/GPUTracking/Merger/GPUTPCGMTrackParam.cxx index bf1130707227a..ba2062fadb639 100644 --- a/GPU/GPUTracking/Merger/GPUTPCGMTrackParam.cxx +++ b/GPU/GPUTracking/Merger/GPUTPCGMTrackParam.cxx @@ -98,7 +98,7 @@ GPUd() bool GPUTPCGMTrackParam::Fit(GPUTPCGMMerger& GPUrestrict() merger, GPUTPC ConstrainZ(merger, clusters[0].sector, CAMath::Max(t0, tN), CAMath::Min(t0, tN)); } int32_t ihitStart = 0; - int32_t ihitStartInterpolateReject = 0; // First hit of the interpolation rejection way, the hits beyond are not covered by its search for adjacent clusters + int32_t ihitStartInterpolateReject = 0; int32_t interpolatedStart = 0; float covYYUpd = 0.f; float deltaZ = 0.f; @@ -118,7 +118,7 @@ GPUd() bool GPUTPCGMTrackParam::Fit(GPUTPCGMMerger& GPUrestrict() merger, GPUTPC const bool finalFit = iWay == nWays - 1; if (iWay && finalFit) { - StoreOuter(&track.OuterParam(), rebuilt && iWay == wayRebuildStart + 2 ? Alpha : prop.GetAlpha()); // In the first way of the rebuilt pass, prop is not yet initialized + StoreOuter(&track.OuterParam(), rebuilt && iWay == wayRebuildStart + 2 ? Alpha : prop.GetAlpha()); } ResetCovariance(); @@ -357,7 +357,7 @@ GPUd() bool GPUTPCGMTrackParam::Fit(GPUTPCGMMerger& GPUrestrict() merger, GPUTPC es.lastFoundX = es.lastFoundAlpha = 0.f; es.revert = false; const float qPtStart = mP[4], alphaStart = prop.GetAlpha(); - const GPUTPCGMTrackParam paramStart = *this; // To revert to if the extrapolation fails + const GPUTPCGMTrackParam paramStart = *this; prop.SetTrack(this, prop.GetAlpha()); const uint8_t iExtrapolatedRow = ExtrapolateRows(merger, tmpRows, prop, es, sector, lastPropagateRow, up, inFlyDirection, refit, sumInvSqrtCharge, nAvgCharge, deltaZ, iTrk, adjacentInRebuild && !(param.rec.tpc.disableMarkAdjacent & 4) ? adjacentLeg : 0, param.rec.tpc.rebuildTrackMaxNonIntCov, qPtStart); const uint8_t lastGoodRow = es.lastGoodRow, lastFoundRow = es.lastFoundRow; @@ -1346,7 +1346,7 @@ GPUdii() void GPUTPCGMTrackParam::FollowExtrapolation(GPUTPCGMMerger& GPUrestric return; } const GPUParam& GPUrestrict() param = merger.Param(); - GPUTPCGMPropagator prop; // Settings as in the extrapolation of the fit, which runs in the ways before the final one + GPUTPCGMPropagator prop; prop.SetMaterialTPC(); prop.SetPolynomialField(¶m.polynomialField); prop.SetMaxSinPhi(constants::MAX_SIN_PHI); @@ -1384,7 +1384,7 @@ GPUdii() void GPUTPCGMTrackParam::PropagateLooper(const GPUTPCGMMerger& GPUrestr prop.SetFitInProjections(true); prop.SetPropagateBzOnly(false); - GPUTPCGMTrackParam t = data.param; // Work on a local copy, not in global memory + GPUTPCGMTrackParam t = data.param; prop.SetTrack(&t, data.alpha); if (merger.Param().rec.tpc.looperFollowMode == 1) { t.FindAdjacentClustersLooperFollow(merger, prop, data.sector, data.track, data.outwards & 1, data.outwards & 2); diff --git a/GPU/GPUTracking/Merger/GPUTPCGlobalDebugSortKernels.cxx b/GPU/GPUTracking/Merger/GPUTPCGlobalDebugSortKernels.cxx index 9a8367fefe40e..2f9f9b83d7fda 100644 --- a/GPU/GPUTracking/Merger/GPUTPCGlobalDebugSortKernels.cxx +++ b/GPU/GPUTracking/Merger/GPUTPCGlobalDebugSortKernels.cxx @@ -42,7 +42,7 @@ GPUdii() void GPUTPCGlobalDebugSortKernels::ThreadDumpData(fname); if (iEvent == configStandalone.StartEvent) { - GPUSettingsGRP grpAsync = recAsync->GetGRPSettings(); // Input are the compressed clusters + GPUSettingsGRP grpAsync = recAsync->GetGRPSettings(); grpAsync.needsClusterer = 0; grpAsync.doCompClusterDecode = 1; recAsync->DumpSettings("", &grpAsync); diff --git a/GPU/GPUTracking/display/GPUDisplay.cxx b/GPU/GPUTracking/display/GPUDisplay.cxx index 487ffa8b3c9db..d8455b44cf74b 100644 --- a/GPU/GPUTracking/display/GPUDisplay.cxx +++ b/GPU/GPUTracking/display/GPUDisplay.cxx @@ -649,8 +649,8 @@ void GPUDisplay::DrawGLScene_internal(bool suspended, float animateTime, bool re mCfgO.animateScreenshot = 0; } } - const bool animateScreenshot = mCfgO.animateScreenshot && mAnimate; // Copy, the animation resets animateScreenshot in its last frame - const bool screenshotFrame = mCfgC.requestScreenshot || animateScreenshot; // Also for the mix pass (animateTime >= 0), which must use the same render size + const bool animateScreenshot = mCfgO.animateScreenshot && mAnimate; + const bool screenshotFrame = mCfgC.requestScreenshot || animateScreenshot; const bool doScreenshot = screenshotFrame && animateTime < 0; updateOptions(); @@ -691,7 +691,7 @@ void GPUDisplay::DrawGLScene_internal(bool suspended, float animateTime, bool re // Draw Event nextViewMatrix = nextViewMatrix * *mModelMatrix; const float zFar = ((mParam->par.continuousTracking ? (mMaxClusterZ * GL_SCALE_FACTOR) : 8.f) + 50.f) * 2.f; - const float aspect = mBackend->mRenderHeight ? (float)mBackend->mRenderWidth / (float)mBackend->mRenderHeight : 1.f; // No render size with the None backend + const float aspect = mBackend->mRenderHeight ? (float)mBackend->mRenderWidth / (float)mBackend->mRenderHeight : 1.f; const hmm_mat4 proj = HMM_Perspective(mCfgR.fov, aspect, 0.1f, zFar); if (!mBackend->prepareDraw(proj, nextViewMatrix, screenshotFrame, renderToMixBuffer, mixSlaveImage)) { return; // No image available (e.g. hidden window), retry with the next frame @@ -744,10 +744,10 @@ void GPUDisplay::DrawGLScene_internal(bool suspended, float animateTime, bool re showInfo(info); } if (consoleFraction > 0.f) { - const bool open = mCfgC.showConsole && mConsoleTimer.GetCurrentElapsedTime() >= mConfig.internal.consoleDelay; // Cursor only when fully open + const bool open = mCfgC.showConsole && mConsoleTimer.GetCurrentElapsedTime() >= mConfig.internal.consoleDelay; if (!open) { mConsoleCursorTimer.Reset(); - } else if (!mConsoleCursorTimer.IsRunning() || mConsoleCursorPos != mFrontend->mConsole->mConsoleTextPos) { // Blinking restarts visible when the cursor moves + } else if (!mConsoleCursorTimer.IsRunning() || mConsoleCursorPos != mFrontend->mConsole->mConsoleTextPos) { mConsoleCursorTimer.ResetStart(); mConsoleCursorPos = mFrontend->mConsole->mConsoleTextPos; } diff --git a/GPU/GPUTracking/display/backend/GPUDisplayBackendOpenGL.h b/GPU/GPUTracking/display/backend/GPUDisplayBackendOpenGL.h index e7bc6480878f5..15447240d36c1 100644 --- a/GPU/GPUTracking/display/backend/GPUDisplayBackendOpenGL.h +++ b/GPU/GPUTracking/display/backend/GPUDisplayBackendOpenGL.h @@ -101,8 +101,8 @@ class GPUDisplayBackendOpenGL : public GPUDisplayBackend uint32_t mFragmentShaderDownsample; uint32_t mGeometryShader; uint32_t mShaderProgram; - uint32_t mShaderProgramSmoothPoint; // Points with fragmentSmoothPoint.frag, for smoothPoints - uint32_t mShaderProgramSmoothLine; // Lines with vertexSmoothLine.vert / fragmentSmoothLine.frag, for smoothLines + uint32_t mShaderProgramSmoothPoint; + uint32_t mShaderProgramSmoothLine; uint32_t mShaderProgramText; uint32_t mShaderProgramTexture; uint32_t mShaderProgramDownsample; diff --git a/GPU/GPUTracking/display/backend/GPUDisplayBackendVulkan.cxx b/GPU/GPUTracking/display/backend/GPUDisplayBackendVulkan.cxx index cc73b350e7bc0..0a4dc72f0beaa 100644 --- a/GPU/GPUTracking/display/backend/GPUDisplayBackendVulkan.cxx +++ b/GPU/GPUTracking/display/backend/GPUDisplayBackendVulkan.cxx @@ -822,7 +822,7 @@ void GPUDisplayBackendVulkan::createSwapChain(vk::SwapchainKHR oldSwapChain) } } mSwapChain = mDevice.createSwapchainKHR(swapCreateInfo, nullptr); - mLastPresentId = 0; // Present IDs are per swapchain + mLastPresentId = 0; if (oldSwapChain) { waitPresentFences(); // Presentation engine done with the old swapchain mDevice.destroySwapchainKHR(oldSwapChain, nullptr); @@ -1027,17 +1027,17 @@ void GPUDisplayBackendVulkan::createPipeline() rasterizer.cullMode = vk::CullModeFlagBits::eBack; rasterizer.frontFace = vk::FrontFace::eClockwise; rasterizer.depthBiasEnable = false; - rasterizer.depthBiasConstantFactor = 0.0f; // Optional - rasterizer.depthBiasClamp = 0.0f; // Optional - rasterizer.depthBiasSlopeFactor = 0.0f; // Optional + rasterizer.depthBiasConstantFactor = 0.0f; + rasterizer.depthBiasClamp = 0.0f; + rasterizer.depthBiasSlopeFactor = 0.0f; vk::PipelineMultisampleStateCreateInfo multisampling{}; multisampling.sampleShadingEnable = false; // multisampling.rasterizationSamples // below - multisampling.minSampleShading = 1.0f; // Optional - multisampling.pSampleMask = nullptr; // Optional - multisampling.alphaToCoverageEnable = false; // Optional - multisampling.alphaToOneEnable = false; // Optional + multisampling.minSampleShading = 1.0f; + multisampling.pSampleMask = nullptr; + multisampling.alphaToCoverageEnable = false; + multisampling.alphaToOneEnable = false; vk::PipelineColorBlendAttachmentState colorBlendAttachment{}; colorBlendAttachment.colorWriteMask = vk::ColorComponentFlagBits::eR | vk::ColorComponentFlagBits::eG | vk::ColorComponentFlagBits::eB | vk::ColorComponentFlagBits::eA; @@ -1103,8 +1103,8 @@ void GPUDisplayBackendVulkan::createPipeline() vk::PipelineRenderingCreateInfo renderingInfo{0, 1, &mSurfaceFormat.format}; pipelineInfo.pNext = &renderingInfo; pipelineInfo.pStages = shaderStages; - pipelineInfo.basePipelineHandle = VkPipeline(VK_NULL_HANDLE); // Optional - pipelineInfo.basePipelineIndex = -1; // Optional + pipelineInfo.basePipelineHandle = VkPipeline(VK_NULL_HANDLE); + pipelineInfo.basePipelineIndex = -1; mPipelines.resize(9); // 0 points, 1 lines, 2 line strip (drawType index), 3 text, 4 texture, 5-7 smooth (shader-based) points, lines, line strip, 8 FSAA downsampling static constexpr vk::PrimitiveTopology types[3] = {vk::PrimitiveTopology::ePointList, vk::PrimitiveTopology::eLineList, vk::PrimitiveTopology::eLineStrip}; @@ -1497,7 +1497,7 @@ bool GPUDisplayBackendVulkan::prepareDraw(const hmm_mat4& proj, const hmm_mat4& }; vk::Result retVal = vk::Result::eSuccess; - if (mPresentModeForVSyncLimit != (fpsLimitMode() == FPS_LIMIT_VSYNC)) { // Present mode depends on the FPS limit mode + if (mPresentModeForVSyncLimit != (fpsLimitMode() == FPS_LIMIT_VSYNC)) { mMustUpdateSwapChain = true; } bool mustUpdateSwapChain = mMustUpdateSwapChain || mDisplay->updateRenderPipeline() || (toMixBuffer && !mMixingSupported) || mDownsampleFactor != getDownsampleFactor(requestScreenshot); diff --git a/GPU/GPUTracking/display/backend/GPUDisplayBackendVulkan.h b/GPU/GPUTracking/display/backend/GPUDisplayBackendVulkan.h index 1b24f2199e3a6..7a58a8bfa9917 100644 --- a/GPU/GPUTracking/display/backend/GPUDisplayBackendVulkan.h +++ b/GPU/GPUTracking/display/backend/GPUDisplayBackendVulkan.h @@ -155,7 +155,7 @@ class GPUDisplayBackendVulkan : public GPUDisplayBackend vk::SwapchainKHR mSwapChain; bool mMustUpdateSwapChain = false; uint8_t mSwapChainSuboptimal = 0; // Bitmask if last acquire / present / ... returned SUBOPTIMAL: recreate only on the first one - bool mFrameSkipped = false; // No image acquired in this frame (timeout) + bool mFrameSkipped = false; void handleSwapChainResult(vk::Result retVal, uint8_t suboptimalBit); std::vector mSwapChainImages; std::vector mSwapChainImageViews; diff --git a/GPU/GPUTracking/display/frontend/GPUDisplayFrontend.cxx b/GPU/GPUTracking/display/frontend/GPUDisplayFrontend.cxx index 316bc42af5d98..00e1081ec722c 100644 --- a/GPU/GPUTracking/display/frontend/GPUDisplayFrontend.cxx +++ b/GPU/GPUTracking/display/frontend/GPUDisplayFrontend.cxx @@ -63,7 +63,7 @@ using namespace o2::gpu; GPUDisplayFrontend::GPUDisplayFrontend() : mConsole(std::make_unique(std::string(DISPLAY_WINDOW_NAME) + " Console")) {} GPUDisplayFrontend::~GPUDisplayFrontend() { - if (mFrontendThread.joinable()) { // Started but not stopped, as the detached thread before + if (mFrontendThread.joinable()) { mFrontendThread.detach(); } } diff --git a/GPU/GPUTracking/display/frontend/GPUDisplayFrontendX11.h b/GPU/GPUTracking/display/frontend/GPUDisplayFrontendX11.h index abceeaaa670f0..0693a14493395 100644 --- a/GPU/GPUTracking/display/frontend/GPUDisplayFrontendX11.h +++ b/GPU/GPUTracking/display/frontend/GPUDisplayFrontendX11.h @@ -45,7 +45,7 @@ class GPUDisplayFrontendX11 : public GPUDisplayFrontend Display* mXDisplay = nullptr; Window mWindow; void updateWindowState(); - float mScale = 1.f; // From the Xft.dpi X resource (desktop scaling, e.g. KDE with "Apply scaling themselves" for X11 apps) + float mScale = 1.f; PFNGLXSWAPINTERVALEXTPROC mGlXSwapIntervalEXT = nullptr; bool vsync_supported = false; diff --git a/GPU/GPUTracking/display/frontend/GPUDisplayGUIWrapper.cxx b/GPU/GPUTracking/display/frontend/GPUDisplayGUIWrapper.cxx index 183c243a3d1fb..50fd72b3d516a 100644 --- a/GPU/GPUTracking/display/frontend/GPUDisplayGUIWrapper.cxx +++ b/GPU/GPUTracking/display/frontend/GPUDisplayGUIWrapper.cxx @@ -33,12 +33,12 @@ struct GPUDisplayGUIWrapperObjects { char appName[64] = "GPU CA Standalone Event Display GUI"; char* argv[2] = {appName, nullptr}; // Must outlive the QApplication std::unique_ptr app; - std::unique_ptr gui; // Protected by mutex + std::unique_ptr gui; std::thread thread; std::mutex mutex; std::condition_variable signal; - bool start = false, terminate = false; // Protected by mutex - std::atomic started = false; // Written under mutex + bool start = false, terminate = false; + std::atomic started = false; }; } // namespace o2::gpu::internal @@ -83,7 +83,7 @@ void GPUDisplayGUIWrapper::guiThread() mO->started = true; mO->signal.notify_all(); lock.unlock(); - mO->app->exec(); // Returns when the GUI window is closed, by the user or by stop() + mO->app->exec(); lock.lock(); mO->gui.reset(); mO->started = false; diff --git a/GPU/GPUTracking/display/frontend/GPUDisplayHelp.cxx b/GPU/GPUTracking/display/frontend/GPUDisplayHelp.cxx index 73b11a253c0d4..8f2bdc2cd2dd9 100644 --- a/GPU/GPUTracking/display/frontend/GPUDisplayHelp.cxx +++ b/GPU/GPUTracking/display/frontend/GPUDisplayHelp.cxx @@ -40,8 +40,8 @@ void GPUDisplay::PrintGLHelpText(float colorValue) } const size_t textStart = line.find(": "); const size_t indent = textStart != std::string::npos && textStart + 2 < (size_t)maxChars / 2 ? textStart + 2 : 0; // Continuation lines aligned with the text after the keys, if that leaves enough space - size_t pos = 0; // Start of the part not yet printed - for (bool first = true;; first = false) { // Wrap at the last space that fits, or hard if there is none (also if it is only in the keys) + size_t pos = 0; + for (bool first = true;; first = false) { // Wrap at the last space that fits, or hard if there is none (also if it is only in the keys) const size_t lineIndent = first ? 0 : indent, available = maxChars - lineIndent; if (line.size() - pos <= available) { print(line.c_str() + pos, line.size() - pos, lineIndent); diff --git a/GPU/GPUTracking/display/helpers/GPUDisplayAnimation.cxx b/GPU/GPUTracking/display/helpers/GPUDisplayAnimation.cxx index 866988aae669e..458fefdcac05a 100644 --- a/GPU/GPUTracking/display/helpers/GPUDisplayAnimation.cxx +++ b/GPU/GPUTracking/display/helpers/GPUDisplayAnimation.cxx @@ -150,7 +150,7 @@ void GPUDisplay::removeAnimationPoint(int32_t i) auto& times = mCfgC.animationPoints.values; mAnimationVectors.erase(mAnimationVectors.begin() + i); times.erase(times.begin() + i); - if (i == 0 && times.size()) { // The first point stays at time 0 + if (i == 0 && times.size()) { const float t0 = times[0]; for (float& t : times) { t -= t0; @@ -178,7 +178,7 @@ void GPUDisplay::StopAnimation() return; } mAnimate = mCfgO.animateScreenshot = 0; - mAnimationMixBase = -1; // Camera and settings stay as they are + mAnimationMixBase = -1; mUpdateDrawCommands = true; SetInfo("Animation stopped", 1); } @@ -217,8 +217,8 @@ void GPUDisplay::setAnimationPointsFromGUI(const GPUDisplayMultiSliderValue& poi void GPUDisplay::updateAnimationPointsGUI() { auto& gui = mCfgC.animationPoints; - gui.progress = mAnimate ? gui.progress : 0; // Set by animateCamera while the animation runs - gui.max = (gui.values.size() ? gui.values.back() : 0.) + ((int32_t)(mCfgO.animationDelay * 20)) / 20.f; // Room for the next point + gui.progress = mAnimate ? gui.progress : 0; + gui.max = (gui.values.size() ? gui.values.back() : 0.) + ((int32_t)(mCfgO.animationDelay * 20)) / 20.f; } void GPUDisplay::runAnimation() diff --git a/GPU/GPUTracking/display/helpers/GPUDisplayHelpers.cxx b/GPU/GPUTracking/display/helpers/GPUDisplayHelpers.cxx index 9920ee0289be6..217a11bdbc54f 100644 --- a/GPU/GPUTracking/display/helpers/GPUDisplayHelpers.cxx +++ b/GPU/GPUTracking/display/helpers/GPUDisplayHelpers.cxx @@ -121,7 +121,7 @@ void GPUDisplay::LoadGLAnimation() GPUSettingsDisplayLight cfg; int32_t size = 0; bool ok = fread(&cfg, sizeof(cfg), 1, ftmp) == 1 && fread(&size, sizeof(size), 1, ftmp) == 1 && size >= 0; - if (ok) { // Check the file size before allocating memory or changing anything + 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)); diff --git a/GPU/GPUTracking/display/render/GPUDisplayImportEvent.cxx b/GPU/GPUTracking/display/render/GPUDisplayImportEvent.cxx index 5209dc9262819..fda160afaa666 100644 --- a/GPU/GPUTracking/display/render/GPUDisplayImportEvent.cxx +++ b/GPU/GPUTracking/display/render/GPUDisplayImportEvent.cxx @@ -40,7 +40,7 @@ using namespace o2::gpu; void GPUDisplay::DrawGLScene_updateEventData() { - mUpdateGUIOptions = true; // E.g. number of collisions + mUpdateGUIOptions = true; HighResTimer timer(mChain->GetProcessingSettings().debugLevel >= 2); if (mIOPtrs->clustersNative) { mCurrentClusters = mIOPtrs->clustersNative->nClustersTotal; diff --git a/GPU/GPUTracking/qa/genEvents.cxx b/GPU/GPUTracking/qa/genEvents.cxx index c1f33a1e0bbc9..2e7fb10706476 100644 --- a/GPU/GPUTracking/qa/genEvents.cxx +++ b/GPU/GPUTracking/qa/genEvents.cxx @@ -115,7 +115,7 @@ void genEvents::InitEventGenerator(const std::string& dir) mClusterError[i][j]->GetXaxis()->SetTitle("Cluster Error [cm]"); } } - mRec->rec()->DumpSettings(dir.c_str()); // the chain's own override does not write settings.dump + mRec->rec()->DumpSettings(dir.c_str()); } void genEvents::FinishEventGenerator() @@ -203,14 +203,12 @@ int32_t genEvents::GenerateEvent(const GPUParam& param, const char* filename) double theta = 2 * std::atan(1. / exp(eta)); double lambda = theta - CAMath::Pi() / 2; - // double theta = gRandom->Uniform(-60,60)*CAMath::Pi()/180.; double pt = .08 * std::pow(10, gRandom->Uniform(0, 2.2)); double q = 1.; int32_t iSector = GetSector(phi); phi = phi - GetSectorAngle(iSector); - // std::cout<<"phi = "<().allocate(n); } void deallocate(T* p, std::size_t n) { std::allocator().deallocate(p, n); } static void construct(T*) {} - bool operator==(const vecpod_allocator&) const { return true; } // Stateless (no member, so std::vector does not store it), needed e.g. for the move assignment of std::vector + bool operator==(const vecpod_allocator&) const { return true; } }; template diff --git a/GPU/Utils/GPUCommonBitSet.h b/GPU/Utils/GPUCommonBitSet.h index 8e2331a1155b9..53e76d5f9d91b 100644 --- a/GPU/Utils/GPUCommonBitSet.h +++ b/GPU/Utils/GPUCommonBitSet.h @@ -38,10 +38,7 @@ class bitset public: GPUdDefault() constexpr bitset() = default; #ifndef __METAL__ - // MSL will not use a user-declared copy constructor to build an object in the - // constant address space, where GPUconstexpr() arrays of bitset live. Leaving - // it implicit is what makes those arrays constructible. - GPUdDefault() constexpr bitset(const bitset&) = default; + GPUdDefault() constexpr bitset(const bitset&) = default; // Use implicit constructor for metal to create objects in constant address space #endif #ifdef __OPENCL__ GPUdDefault() constexpr bitset(const __constant bitset&) = default; From 01f1a8ed6407235fb1f099aa5f468d248bb2e8e8 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Mon, 30 Nov 2026 23:31:26 +0100 Subject: [PATCH 02/18] Propagator: Workaround for OpenCL with Clang --- Detectors/Base/src/Propagator.cxx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Detectors/Base/src/Propagator.cxx b/Detectors/Base/src/Propagator.cxx index cdb3a0ee9db32..caf443a5864f2 100644 --- a/Detectors/Base/src/Propagator.cxx +++ b/Detectors/Base/src/Propagator.cxx @@ -585,7 +585,7 @@ GPUd() bool PropagatorImpl::propagateToR(track_T& track, value_type r, bool clockwise = curv < 0; // q+ in B+ or q- in B- goes clockwise auto phiLoc = math_utils::detail::asin(track.getSnp()); auto phi0 = phiLoc + track.getAlpha(); - o2::math_utils::detail::bringTo02Pi(phi0); + o2::math_utils::bringTo02Pid(phi0); // not detail::bringTo02Pi(): Clang OpenCL C++ mangles the deduced private-reference instantiation like the explicit one, giving invalid IR for (int i = 0; i < cross.nDCA; i++) { // track pT direction angle at crossing points: // == angle of the tangential to track circle at the crossing point X,Y @@ -597,7 +597,7 @@ GPUd() bool PropagatorImpl::propagateToR(track_T& track, value_type r, normY = -normY; } phiCross[i] = math_utils::detail::atan2(normY, normX); - o2::math_utils::detail::bringTo02Pi(phiCross[i]); + o2::math_utils::bringTo02Pid(phiCross[i]); dphi[i] = phiCross[i] - phi0; if (dphi[i] > o2::constants::math::PI) { dphi[i] -= o2::constants::math::TwoPI; From aa6577cc5adbe3d5dcf9eb4c250841c37aaf335d Mon Sep 17 00:00:00 2001 From: David Rohr Date: Mon, 30 Nov 2026 23:32:29 +0100 Subject: [PATCH 03/18] GPU: Use double in DETERMINISTIC_MODE on OpenCL --- GPU/Common/GPUCommonMath.h | 26 ++++++++++++++++---------- 1 file changed, 16 insertions(+), 10 deletions(-) diff --git a/GPU/Common/GPUCommonMath.h b/GPU/Common/GPUCommonMath.h index 8c25f376d9e3a..c7d55ff43fef4 100644 --- a/GPU/Common/GPUCommonMath.h +++ b/GPU/Common/GPUCommonMath.h @@ -48,7 +48,12 @@ #define GPUCA_CHOICE(c1, c2, c3) (c3) // Select third option for OpenCL and Metal #else #define GPUCA_CHOICE(c1, c2, c3) (c1) // Select first option for Host -#endif // clang-format on +#endif // clang-format on +#if defined(__METAL__) // TODO: Support double also in Metal, for deterministic results +#define GPUCA_DETERMINISTIC_DOUBLE(dbl, flt) (flt) // Deterministic math functions computed in double where possible, MSL has no double +#else +#define GPUCA_DETERMINISTIC_DOUBLE(dbl, flt) (dbl) +#endif namespace o2::gpu { @@ -323,16 +328,16 @@ GPUCA_DETERMINISTIC_CODE( // clang-format off GPUdi() constexpr float GPUCommonMath::Round(float x) { return GPUCA_CHOICE(roundf(x), roundf(x), round(x)); } GPUdi() constexpr int32_t GPUCommonMath::Float2IntRn(float x) { return (int32_t)Round(x); } GPUhdi() constexpr float GPUCommonMath::Sqrt(float x) { return GPUCA_CHOICE(sqrtf(x), (float)sqrt((double)x), sqrt(x)); } -GPUdi() constexpr float GPUCommonMath::ATan(float x) { return GPUCA_CHOICE((float)atan((double)x), (float)atan((double)x), atan(x)); } -GPUhdi() constexpr float GPUCommonMath::ATan2(float y, float x) { return GPUCA_CHOICE((float)atan2((double)y, (double)x), (float)atan2((double)y, (double)x), atan2(y, x)); } -GPUdi() constexpr float GPUCommonMath::Sin(float x) { return GPUCA_CHOICE((float)sin((double)x), (float)sin((double)x), sin(x)); } -GPUdi() constexpr float GPUCommonMath::Cos(float x) { return GPUCA_CHOICE((float)cos((double)x), (float)cos((double)x), cos(x)); } +GPUdi() constexpr float GPUCommonMath::ATan(float x) { return GPUCA_CHOICE((float)atan((double)x), (float)atan((double)x), GPUCA_DETERMINISTIC_DOUBLE((float)atan((double)x), atan(x))); } +GPUhdi() constexpr float GPUCommonMath::ATan2(float y, float x) { return GPUCA_CHOICE((float)atan2((double)y, (double)x), (float)atan2((double)y, (double)x), GPUCA_DETERMINISTIC_DOUBLE((float)atan2((double)y, (double)x), atan2(y, x))); } +GPUdi() constexpr float GPUCommonMath::Sin(float x) { return GPUCA_CHOICE((float)sin((double)x), (float)sin((double)x), GPUCA_DETERMINISTIC_DOUBLE((float)sin((double)x), sin(x))); } +GPUdi() constexpr float GPUCommonMath::Cos(float x) { return GPUCA_CHOICE((float)cos((double)x), (float)cos((double)x), GPUCA_DETERMINISTIC_DOUBLE((float)cos((double)x), cos(x))); } GPUdi() constexpr float GPUCommonMath::Tan(float x) { return GPUCA_CHOICE((float)tanf((double)x), (float)tanf((double)x), tan(x)); } -GPUdi() constexpr float GPUCommonMath::Pow(float x, float y) { return GPUCA_CHOICE((float)pow((double)x, (double)y), pow((double)x, (double)y), pow(x, y)); } -GPUdi() constexpr float GPUCommonMath::ASin(float x) { return GPUCA_CHOICE((float)asin((double)x), (float)asin((double)x), asin(x)); } -GPUdi() constexpr float GPUCommonMath::ACos(float x) { return GPUCA_CHOICE((float)acos((double)x), (float)acos((double)x), acos(x)); } -GPUdi() constexpr float GPUCommonMath::Log(float x) { return GPUCA_CHOICE((float)log((double)x), (float)log((double)x), log(x)); } -GPUdi() constexpr float GPUCommonMath::Exp(float x) { return GPUCA_CHOICE((float)exp((double)x), (float)exp((double)x), exp(x)); } +GPUdi() constexpr float GPUCommonMath::Pow(float x, float y) { return GPUCA_CHOICE((float)pow((double)x, (double)y), pow((double)x, (double)y), GPUCA_DETERMINISTIC_DOUBLE((float)pow((double)x, (double)y), pow(x, y))); } +GPUdi() constexpr float GPUCommonMath::ASin(float x) { return GPUCA_CHOICE((float)asin((double)x), (float)asin((double)x), GPUCA_DETERMINISTIC_DOUBLE((float)asin((double)x), asin(x))); } +GPUdi() constexpr float GPUCommonMath::ACos(float x) { return GPUCA_CHOICE((float)acos((double)x), (float)acos((double)x), GPUCA_DETERMINISTIC_DOUBLE((float)acos((double)x), acos(x))); } +GPUdi() constexpr float GPUCommonMath::Log(float x) { return GPUCA_CHOICE((float)log((double)x), (float)log((double)x), GPUCA_DETERMINISTIC_DOUBLE((float)log((double)x), log(x))); } +GPUdi() constexpr float GPUCommonMath::Exp(float x) { return GPUCA_CHOICE((float)exp((double)x), (float)exp((double)x), GPUCA_DETERMINISTIC_DOUBLE((float)exp((double)x), exp(x))); } GPUdi() constexpr bool GPUCommonMath::Finite(float x) { return GPUCA_CHOICE(std::isfinite(x), isfinite(x), isfinite(x)); } GPUdi() constexpr bool GPUCommonMath::IsNaN(float x) { return GPUCA_CHOICE(std::isnan(x), isnan(x), isnan(x)); } , // !GPUCA_DETERMINISTIC_CODE @@ -352,6 +357,7 @@ GPUdi() constexpr float GPUCommonMath::Exp(float x) { return GPUCA_CHOICE(expf(x GPUdi() constexpr bool GPUCommonMath::Finite(float x) { return true; } GPUdi() constexpr bool GPUCommonMath::IsNaN(float x) { return false; } ) // clang-format on +#undef GPUCA_DETERMINISTIC_DOUBLE GPUhdi() void GPUCommonMath::SinCos(float x, float& s, float& c) { From 008dcc0f555e0a419d39f8c9c08bb9339e786de4 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Mon, 30 Nov 2026 23:33:07 +0100 Subject: [PATCH 04/18] GPU: Fix segfault in case of unclean OpenCL exit --- GPU/GPUTracking/Base/GPUReconstruction.cxx | 2 ++ 1 file changed, 2 insertions(+) diff --git a/GPU/GPUTracking/Base/GPUReconstruction.cxx b/GPU/GPUTracking/Base/GPUReconstruction.cxx index 103bfe75f0b27..167e8a9932358 100644 --- a/GPU/GPUTracking/Base/GPUReconstruction.cxx +++ b/GPU/GPUTracking/Base/GPUReconstruction.cxx @@ -101,6 +101,8 @@ GPUReconstruction::~GPUReconstruction() if (mInitialized) { GPUError("GPU Reconstruction not properly deinitialized!"); } + mChains.clear(); + mHostConstantMem.reset(); } void GPUReconstruction::GetITSTraits(std::unique_ptr>* trackerTraits, std::unique_ptr>* vertexerTraits, std::unique_ptr>* timeFrame) From b445ab96973b1075476b328b55e8a44098055aae Mon Sep 17 00:00:00 2001 From: David Rohr Date: Mon, 30 Nov 2026 23:34:46 +0100 Subject: [PATCH 05/18] GPU OpenCL: forward math flags to SPIR-V to binary compilation at runtime --- GPU/GPUTracking/Base/opencl/CMakeLists.txt | 9 +++++---- GPU/GPUTracking/Base/opencl/GPUReconstructionOCL.cxx | 2 +- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/GPU/GPUTracking/Base/opencl/CMakeLists.txt b/GPU/GPUTracking/Base/opencl/CMakeLists.txt index b9093e083266a..ee6d46942b35c 100644 --- a/GPU/GPUTracking/Base/opencl/CMakeLists.txt +++ b/GPU/GPUTracking/Base/opencl/CMakeLists.txt @@ -23,12 +23,13 @@ endif() set(CL_SRC ${GPUDIR}/Base/opencl/GPUReconstructionOCL.cl) set(CL_BIN ${CMAKE_CURRENT_BINARY_DIR}/GPUReconstructionOCLCode) -set(OCL_FLAGS -Dcl_clang_storage_class_specifiers -x cl -cl-std=CLC++2021 ${GPUCA_OCL_DENORMALS_FLAGS}) +set(OCL_MATH_FLAGS ${GPUCA_OCL_DENORMALS_FLAGS}) # Also passed to clBuildProgram for SPIR-V, for the code generation of the runtime if(NOT GPUCA_DETERMINISTIC_MODE GREATER_EQUAL ${GPUCA_DETERMINISTIC_MODE_MAP_NO_FAST_MATH}) - set(OCL_FLAGS ${OCL_FLAGS} -cl-mad-enable -cl-no-signed-zeros -cl-fast-relaxed-math) + set(OCL_MATH_FLAGS ${OCL_MATH_FLAGS} -cl-mad-enable -cl-no-signed-zeros -cl-fast-relaxed-math) else() - set(OCL_FLAGS ${OCL_FLAGS} ${GPUCA_OCL_NO_FAST_MATH_FLAGS}) + set(OCL_MATH_FLAGS ${OCL_MATH_FLAGS} ${GPUCA_OCL_NO_FAST_MATH_FLAGS}) endif() +set(OCL_FLAGS -Dcl_clang_storage_class_specifiers -x cl -cl-std=CLC++2021 ${OCL_MATH_FLAGS}) set(OCL_DEFINECL "-D$,$-D>" "-I$,EXCLUDE,^/usr/include/?>,$-I>" -I${CMAKE_SOURCE_DIR}/Detectors/TRD/base/src @@ -122,4 +123,4 @@ install(FILES ${HDRS} DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/GPU) if(OPENCL_ENABLED_SPIRV) target_compile_definitions(${targetName} PRIVATE OPENCL_ENABLED_SPIRV) endif() -target_compile_definitions(${targetName} PRIVATE GPUCA_OCL_BUILD_FLAGS=$ GPUCA_OCL_SPIRV_VERSION=${GPUCA_OCL_SPIRV_VERSION}) +target_compile_definitions(${targetName} PRIVATE GPUCA_OCL_BUILD_FLAGS=$ GPUCA_OCL_SPIRV_BUILD_FLAGS=$ GPUCA_OCL_SPIRV_VERSION=${GPUCA_OCL_SPIRV_VERSION}) diff --git a/GPU/GPUTracking/Base/opencl/GPUReconstructionOCL.cxx b/GPU/GPUTracking/Base/opencl/GPUReconstructionOCL.cxx index ea14c2d1577c4..40a8ee092ce23 100644 --- a/GPU/GPUTracking/Base/opencl/GPUReconstructionOCL.cxx +++ b/GPU/GPUTracking/Base/opencl/GPUReconstructionOCL.cxx @@ -527,7 +527,7 @@ int32_t GPUReconstructionOCL::GetOCLPrograms() if (mOclVersion >= 2.1f && !GetProcessingSettings().backend.compileFromSources) { GPUInfo("Reading OpenCL program from SPIR-V IL (Platform version %4.2f)", mOclVersion); mInternals->program = clCreateProgramWithIL(mInternals->context, _binary_GPUReconstructionOCLCode_spirv_start, _binary_GPUReconstructionOCLCode_spirv_len, &ocl_error); - oclBuildFlags = ""; + oclBuildFlags = GPUCA_M_STR(GPUCA_OCL_SPIRV_BUILD_FLAGS); } else #endif // clang-format on { From e827047732fc4915de5b3ec63a6e4a7bca34dc15 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Mon, 30 Nov 2026 23:35:05 +0100 Subject: [PATCH 06/18] GPU OpenCL: Disable FMA in DETERMINISTIC_MODE --- GPU/GPUTracking/Base/opencl/GPUReconstructionOCL.cl | 3 +++ 1 file changed, 3 insertions(+) diff --git a/GPU/GPUTracking/Base/opencl/GPUReconstructionOCL.cl b/GPU/GPUTracking/Base/opencl/GPUReconstructionOCL.cl index ea74c43703597..e888797c99baa 100644 --- a/GPU/GPUTracking/Base/opencl/GPUReconstructionOCL.cl +++ b/GPU/GPUTracking/Base/opencl/GPUReconstructionOCL.cl @@ -22,6 +22,9 @@ #endif #pragma OPENCL EXTENSION cl_khr_fp64 : enable // Allow double precision variables #pragma OPENCL EXTENSION cl_khr_fp16 : enable // Allow half precision + #ifdef GPUCA_DETERMINISTIC_MODE + #pragma OPENCL FP_CONTRACT OFF // OpenCL contracts a * b + c to FMA by default, which changes the rounding + #endif #ifdef __clang__ #pragma OPENCL EXTENSION cl_clang_storage_class_specifiers : enable // #pragma OPENCL EXTENSION __cl_clang_function_pointers : enable // Allow function pointers From 5a3d4d0bad98274b46ac1228589305eee455058e Mon Sep 17 00:00:00 2001 From: David Rohr Date: Mon, 30 Nov 2026 23:43:47 +0100 Subject: [PATCH 07/18] GPU OpenCL: Print hit to use POCL debug flag if compilation fails --- .../Base/opencl/GPUReconstructionOCL.cxx | 13 +++++++++++++ GPU/GPUTracking/Base/opencl/GPUReconstructionOCL.h | 2 ++ 2 files changed, 15 insertions(+) diff --git a/GPU/GPUTracking/Base/opencl/GPUReconstructionOCL.cxx b/GPU/GPUTracking/Base/opencl/GPUReconstructionOCL.cxx index 40a8ee092ce23..d4169f5d5dbb2 100644 --- a/GPU/GPUTracking/Base/opencl/GPUReconstructionOCL.cxx +++ b/GPU/GPUTracking/Base/opencl/GPUReconstructionOCL.cxx @@ -216,6 +216,7 @@ int32_t GPUReconstructionOCL::InitDevice_Runtime() bestPlatform = iPlatform; bestDeviceSpeed = deviceSpeed; mOclVersion = platform_version_f; + mOclPoCL = platform_version.find("PoCL") != std::string::npos; } if (GetProcessingSettings().deviceNum >= 0) { break; @@ -344,6 +345,7 @@ int32_t GPUReconstructionOCL::InitDevice_Runtime() 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); + PrintPoCLHint(); GPUErrorReturn("Error compiling program"); } cl_kernel kernel = clCreateKernel(program, "krnlGetPtr", &ocl_error); @@ -517,6 +519,15 @@ int32_t GPUReconstructionOCL::GPUDebug(const char* state, int32_t stream, bool f return (0); } +void GPUReconstructionOCL::PrintPoCLHint() +{ + static bool printed = false; + if (mOclPoCL && !printed) { + printed = true; + GPUError("OpenCL runtime is PoCL: run with POCL_DEBUG=error to get the details of the failure"); + } +} + int32_t GPUReconstructionOCL::GetOCLPrograms() { cl_int ocl_error; @@ -539,6 +550,7 @@ int32_t GPUReconstructionOCL::GetOCLPrograms() if (GPUChkErrI(ocl_error)) { GPUError("Error creating OpenCL program from binary"); + PrintPoCLHint(); return 1; } @@ -552,6 +564,7 @@ int32_t GPUReconstructionOCL::GetOCLPrograms() build_log[log_size] = 0; GPUError("Build Log:\n\n%s\n", build_log.get()); } + PrintPoCLHint(); return 1; } diff --git a/GPU/GPUTracking/Base/opencl/GPUReconstructionOCL.h b/GPU/GPUTracking/Base/opencl/GPUReconstructionOCL.h index b8b35ce7d5c6b..f322c17cb81cd 100644 --- a/GPU/GPUTracking/Base/opencl/GPUReconstructionOCL.h +++ b/GPU/GPUTracking/Base/opencl/GPUReconstructionOCL.h @@ -59,11 +59,13 @@ class GPUReconstructionOCL : public GPUReconstructionProcessing::KernelInterface GPUReconstructionOCLInternals* mInternals; float mOclVersion; + bool mOclPoCL = false; template S& getKernelObject(); int32_t GetOCLPrograms(); + void PrintPoCLHint(); private: static const char* convertErrorToString(int32_t errorCode); From 3f04996a9dd3be8d61af064bea8d1d3e9982ea51 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Mon, 30 Nov 2026 23:50:49 +0100 Subject: [PATCH 08/18] GPU: Fix race while updating occupancy map, must not use temporary variable --- GPU/GPUTracking/Base/GPUReconstructionCPU.cxx | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/GPU/GPUTracking/Base/GPUReconstructionCPU.cxx b/GPU/GPUTracking/Base/GPUReconstructionCPU.cxx index 1fac85cf3706c..d394a65d4f50e 100644 --- a/GPU/GPUTracking/Base/GPUReconstructionCPU.cxx +++ b/GPU/GPUTracking/Base/GPUReconstructionCPU.cxx @@ -420,7 +420,8 @@ void GPUReconstructionCPU::UpdateParamOccupancyMap(const uint32_t* mapHost, cons param().occupancy.total = occupancyTotal; param().occupancy.mapSize = mapSize; if (IsGPU()) { - GPUParam::occupancyStruct tmp = {mapGPU, occupancyTotal, mapSize}; + GPUParam::occupancyStruct& tmp = mProcessorsShadow->param.occupancy; + tmp = {mapGPU, occupancyTotal, mapSize}; const auto holdContext = GetThreadContext(); WriteToConstantMemory((char*)&processors()->param.occupancy - (char*)processors(), &tmp, sizeof(tmp), stream, ev); } From bb4720e3fb23f626c9310909bfb42dc3f6a85ed8 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Mon, 30 Nov 2026 23:51:39 +0100 Subject: [PATCH 09/18] GPU: Fix allignment of Merger tmpCounters --- GPU/GPUTracking/Merger/GPUTPCGMMerger.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/GPU/GPUTracking/Merger/GPUTPCGMMerger.h b/GPU/GPUTracking/Merger/GPUTPCGMMerger.h index 0510698597f43..63d4f6b842584 100644 --- a/GPU/GPUTracking/Merger/GPUTPCGMMerger.h +++ b/GPU/GPUTracking/Merger/GPUTPCGMMerger.h @@ -79,7 +79,7 @@ class GPUTPCGMMerger : public GPUProcessor GPUAtomic(uint32_t) nO2Tracks; GPUAtomic(uint32_t) nO2ClusRefs; const GPUTPCTrack* firstExtrapolatedTracks[NSECTORS]; - GPUAtomic(uint32_t) tmpCounter[2 * NSECTORS]; + alignas(16) GPUAtomic(uint32_t) tmpCounter[2 * NSECTORS]; // cleared with GPUMemClean16, which needs 16-byte alignment GPUAtomic(uint32_t) nLooperMatchCandidates; }; From 76768622fa3b4fb168a4f554241150fe8c7a907f Mon Sep 17 00:00:00 2001 From: David Rohr Date: Mon, 30 Nov 2026 23:52:49 +0100 Subject: [PATCH 10/18] GPU Debug: Add dump for TPC occupancy map --- .../Definitions/GPUSettingsList.template | 2 +- GPU/GPUTracking/Global/GPUChainTracking.h | 1 + GPU/GPUTracking/Global/GPUChainTrackingDebug.h | 3 ++- .../Global/GPUChainTrackingDebugAndProfiling.cxx | 13 +++++++++++++ .../Global/GPUChainTrackingSectorTracker.cxx | 4 ++++ 5 files changed, 21 insertions(+), 2 deletions(-) diff --git a/GPU/GPUTracking/Definitions/GPUSettingsList.template b/GPU/GPUTracking/Definitions/GPUSettingsList.template index a03f9a1d22c75..d8575c7a7bea3 100644 --- a/GPU/GPUTracking/Definitions/GPUSettingsList.template +++ b/GPU/GPUTracking/Definitions/GPUSettingsList.template @@ -376,7 +376,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, "debugMask", 0, "Mask for debug output dumps to file") +AddOption(debugMask, uint32_t, ((1 << 18) - 1) | (1 << 24), "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/GPUChainTracking.h b/GPU/GPUTracking/Global/GPUChainTracking.h index 883ac3818b730..21e3494295c5f 100644 --- a/GPU/GPUTracking/Global/GPUChainTracking.h +++ b/GPU/GPUTracking/Global/GPUChainTracking.h @@ -245,6 +245,7 @@ class GPUChainTracking : public GPUChain void PrintOutputStat(); void DumpFinalOutput(); static void DumpClusters(std::ostream& out, const o2::tpc::ClusterNativeAccess* clusters); + void DumpOccupancyMap(std::ostream& out); static void DebugSortCompressedClusters(o2::tpc::CompressedClustersFlat* cls); void DoDebugRawDump(); diff --git a/GPU/GPUTracking/Global/GPUChainTrackingDebug.h b/GPU/GPUTracking/Global/GPUChainTrackingDebug.h index c347069347e59..466fcf1312f76 100644 --- a/GPU/GPUTracking/Global/GPUChainTrackingDebug.h +++ b/GPU/GPUTracking/Global/GPUChainTrackingDebug.h @@ -46,7 +46,8 @@ enum GPUChainTrackingDebugFlags : uint32_t { TPCClustererSuppressedPeaks = 1 << 20, TPCClustererChargeMap = 1 << 21, TPCClustererChargeMapSplit = 1 << 22, - TPCClustererZeroedCharges = 1 << 23 + TPCClustererZeroedCharges = 1 << 23, + TPCOccupancyMap = 1 << 24 }; template diff --git a/GPU/GPUTracking/Global/GPUChainTrackingDebugAndProfiling.cxx b/GPU/GPUTracking/Global/GPUChainTrackingDebugAndProfiling.cxx index aaf83055abac8..d3ac2acb035d1 100644 --- a/GPU/GPUTracking/Global/GPUChainTrackingDebugAndProfiling.cxx +++ b/GPU/GPUTracking/Global/GPUChainTrackingDebugAndProfiling.cxx @@ -266,10 +266,23 @@ void GPUChainTracking::PrintOutputStat() 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); } +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"; + for (uint32_t i = 0; i < mInputsHost->mTPCClusterOccupancyMapSize; i++) { + out << map[2 + i] << (i % 100 == 99 ? "\n" : " "); + } + out << "\n"; +} + void GPUChainTracking::DumpFinalOutput() { std::ostream& out = *mDebugFile; out << "\n\nFinal Output\n"; + if (mSubOutputControls[GPUTrackingOutputs::getIndex(&GPUTrackingOutputs::tpcOccupancyMap)] && mInputsHost->mTPCClusterOccupancyMap) { + DumpOccupancyMap(out); + } if (mIOPtrs.clustersNative) { DumpClusters(out, mIOPtrs.clustersNative); } diff --git a/GPU/GPUTracking/Global/GPUChainTrackingSectorTracker.cxx b/GPU/GPUTracking/Global/GPUChainTrackingSectorTracker.cxx index a4941a4489a5e..20ef60957c4a9 100644 --- a/GPU/GPUTracking/Global/GPUChainTrackingSectorTracker.cxx +++ b/GPU/GPUTracking/Global/GPUChainTrackingSectorTracker.cxx @@ -137,6 +137,10 @@ int32_t GPUChainTracking::RunTPCTrackingSectors_internal() uint32_t& occupancyTotal = *mInputsHost->mTPCClusterOccupancyMap; occupancyTotal = CAMath::Float2UIntRn(mRec->MemoryScalers()->nTPCHits / (mIOPtrs.settingsTF && mIOPtrs.settingsTF->hasNHBFPerTF ? mIOPtrs.settingsTF->nHBFPerTF : 128)); mRec->UpdateParamOccupancyMap(param().rec.tpc.occupancyMapTimeBins ? mInputsHost->mTPCClusterOccupancyMap + 2 : nullptr, doGPU && param().rec.tpc.occupancyMapTimeBins ? mInputsShadow->mTPCClusterOccupancyMap + 2 : nullptr, occupancyTotal, mInputsHost->mTPCClusterOccupancyMapSize, streamInitAndOccMap, &mEvents->init); + if (GetProcessingSettings().debugLevel >= 6 && (GetProcessingSettings().debugMask & GPUChainTrackingDebugFlags::TPCOccupancyMap)) { + SynchronizeStream(streamInitAndOccMap); + DumpOccupancyMap(*mDebugFile); + } } int32_t streamMap[NSECTORS]; From 48011ff6444746044148fe69bff5a4c5d2eabded Mon Sep 17 00:00:00 2001 From: David Rohr Date: Mon, 30 Nov 2026 23:53:43 +0100 Subject: [PATCH 11/18] GPU: Kill tracks with 0 (or < 10) clusters after rebuld --- GPU/GPUTracking/Merger/GPUTPCGMMerger.cxx | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/GPU/GPUTracking/Merger/GPUTPCGMMerger.cxx b/GPU/GPUTracking/Merger/GPUTPCGMMerger.cxx index 009ee6c529811..d8f321657320d 100644 --- a/GPU/GPUTracking/Merger/GPUTPCGMMerger.cxx +++ b/GPU/GPUTracking/Merger/GPUTPCGMMerger.cxx @@ -2413,6 +2413,11 @@ GPUd() void GPUTPCGMMerger::ResolveHitWeights2(int32_t nBlocks, int32_t nThreads } } + if (nHits < 10) { // 10 is the minimum number of clusters allowed for any Pt + trk.SetNClusters(0); + trk.SetOK(false); + continue; + } const uint32_t iOut = CAMath::AtomicAdd(&mMemory->nMergedTrackClusters, nHits); if (iOut + nHits > mNMaxMergedTrackClusters) { raiseError(GPUErrors::ERROR_MERGER_REBUILD_HIT_OVERFLOW, iOut, mNMaxMergedTrackClusters); From de44408c66361e5be6ba70122f20a38e1504efec Mon Sep 17 00:00:00 2001 From: David Rohr Date: Mon, 30 Nov 2026 23:54:05 +0100 Subject: [PATCH 12/18] GPU OpenCL: Use gather mode 1, the default takes ages to compile --- GPU/GPUTracking/Definitions/Parameters/GPUParameters.csv | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/GPU/GPUTracking/Definitions/Parameters/GPUParameters.csv b/GPU/GPUTracking/Definitions/Parameters/GPUParameters.csv index ca6336fa87eb4..87d7ba961540b 100644 --- a/GPU/GPUTracking/Definitions/Parameters/GPUParameters.csv +++ b/GPU/GPUTracking/Definitions/Parameters/GPUParameters.csv @@ -123,5 +123,5 @@ NO_ATOMIC_PRECHECK,0,0,1,1,,,,,,1,1,1,1,,1,,1,1, DEDX_STORAGE_TYPE,"""CAMath::half_t""","""float""",,,,,,,,,,,,,,,,, MERGER_INTERPOLATION_ERROR_TYPE,"""CAMath::half_t""","""float""",,,,,,,,,,,,,,,,, COMP_GATHER_KERNEL,4,0,4,4,,,,,,4,4,4,4,,4,,4,4, -COMP_GATHER_MODE,3,0,3,3,,,,,,3,3,3,3,,3,,3,3, +COMP_GATHER_MODE,3,0,3,3,,,,,,3,3,3,3,1,3,,3,3, CF_SCAN_WORKGROUP_SIZE,512,0,,,,,,,,224,,992,448,,1024,,,448, From a930d9436f26668ceb66fcdd5287be7f1bc4a9a8 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Mon, 30 Nov 2026 23:54:36 +0100 Subject: [PATCH 13/18] GPU: Improve host memory estimation with gather mode 1 --- GPU/GPUTracking/Global/GPUChainTracking.cxx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/GPU/GPUTracking/Global/GPUChainTracking.cxx b/GPU/GPUTracking/Global/GPUChainTracking.cxx index 9b7331e4ff8a3..bc0cb5dcbbbad 100644 --- a/GPU/GPUTracking/Global/GPUChainTracking.cxx +++ b/GPU/GPUTracking/Global/GPUChainTracking.cxx @@ -170,7 +170,7 @@ void GPUChainTracking::MemorySize(size_t& gpuMem, size_t& pageLockedHostMem) { const int32_t gatherMode = mRec->GetProcessingSettings().tpcCompressionGatherMode == -1 ? mRec->getGPUParameters(mRec->GetRecoStepsGPU() & gpudatatypes::RecoStep::TPCCompression).par_COMP_GATHER_MODE : mRec->GetProcessingSettings().tpcCompressionGatherMode; gpuMem = constants::GPU_DEFAULT_MEMORY_SIZE; - pageLockedHostMem = constants::GPU_DEFAULT_HOST_MEMORY_SIZE * (gatherMode < 2 ? 2 : 1); + pageLockedHostMem = constants::GPU_DEFAULT_HOST_MEMORY_SIZE * (gatherMode < 2 ? 2 : 1) + (gatherMode == 1 ? 2 * 1024 * 1024 * 1024ull : 0); // Gather mode 1 gathers the compressed clusters in host memory } bool GPUChainTracking::ValidateSteps() From eb8bba434535e37d7fdb2bd6ca7e3f037170d0c3 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Mon, 30 Nov 2026 23:54:49 +0100 Subject: [PATCH 14/18] GPU: Fix typo: Invalid gather mode was selected --- GPU/GPUTracking/Global/GPUChainTrackingCompression.cxx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/GPU/GPUTracking/Global/GPUChainTrackingCompression.cxx b/GPU/GPUTracking/Global/GPUChainTrackingCompression.cxx index 2caf7b3df4e54..609ae5e9d14c8 100644 --- a/GPU/GPUTracking/Global/GPUChainTrackingCompression.cxx +++ b/GPU/GPUTracking/Global/GPUChainTrackingCompression.cxx @@ -107,7 +107,7 @@ int32_t GPUChainTracking::RunTPCCompression() TransferMemoryResourcesToGPU(myStep, &Compressor, outputStream); constexpr uint32_t nBlocksDefault = 2; constexpr uint32_t nBlocksMulti = 1 + 2 * 200; - int32_t gatherModeKernel = mRec->GetProcessingSettings().tpcCompressionGatherModeKernel == -1 ? mRec->getGPUParameters(doGPU).par_COMP_GATHER_KERNEL : mRec->GetProcessingSettings().tpcCompressionGatherMode; + int32_t gatherModeKernel = mRec->GetProcessingSettings().tpcCompressionGatherModeKernel == -1 ? mRec->getGPUParameters(doGPU).par_COMP_GATHER_KERNEL : mRec->GetProcessingSettings().tpcCompressionGatherModeKernel; switch (gatherModeKernel) { case 0: runKernel(GetGridBlkStep(nBlocksDefault, outputStream, RecoStep::TPCCompression)); From 24d52c72bfc647c628ac47e118467f4ad33d6574 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Mon, 30 Nov 2026 23:56:03 +0100 Subject: [PATCH 15/18] GPU: Add GPUbarrierWarpAlive(), for cases where only performance matters and threads are allowed to have exited --- GPU/Common/GPUCommonDefAPI.h | 6 ++++++ .../DataCompression/GPUTPCCompressionKernels.cxx | 2 +- GPU/GPUTracking/Merger/GPUTPCGMTrackParam.cxx | 2 +- GPU/GPUTracking/SectorTracker/GPUTPCTrackletSelector.cxx | 2 +- 4 files changed, 9 insertions(+), 3 deletions(-) diff --git a/GPU/Common/GPUCommonDefAPI.h b/GPU/Common/GPUCommonDefAPI.h index 8af0a4ff58802..fdd752404e582 100644 --- a/GPU/Common/GPUCommonDefAPI.h +++ b/GPU/Common/GPUCommonDefAPI.h @@ -54,6 +54,7 @@ #define GPUgeneric() // reference / ptr to generic address space #define GPUbarrier() // synchronize all GPU threads in block #define GPUbarrierWarp() // synchronize threads inside warp + #define GPUbarrierWarpAlive() // GPUbarrierWarp() where threads may skip it or have exited (e.g. warp reconvergence in loops), empty where the backend requires all threads #define GPUAtomic(type) type // atomic variable type #define GPUsharedref() // reference / ptr to shared memory #define GPUglobalref() // reference / ptr to global memory @@ -100,11 +101,13 @@ #if defined(__OPENCL__) && !defined(__clang__) #define GPUbarrier() work_group_barrier(mem_fence::global | mem_fence::local) #define GPUbarrierWarp() sub_group_barrier(mem_fence::global | mem_fence::local) + #define GPUbarrierWarpAlive() #define GPUAtomic(type) atomic static_assert(sizeof(atomic) == sizeof(uint32_t), "Invalid size of atomic type"); #else #define GPUbarrier() barrier(CLK_LOCAL_MEM_FENCE | CLK_GLOBAL_MEM_FENCE) #define GPUbarrierWarp() sub_group_barrier(CLK_LOCAL_MEM_FENCE | CLK_GLOBAL_MEM_FENCE) + #define GPUbarrierWarpAlive() #if defined(__OPENCL__) && defined(GPUCA_OPENCL_CLANG_C11_ATOMICS) namespace o2 { namespace gpu { template struct oclAtomic; @@ -155,6 +158,7 @@ #define GPUdouble() float #define GPUbarrier() threadgroup_barrier(mem_flags::mem_device | mem_flags::mem_threadgroup) #define GPUbarrierWarp() simdgroup_barrier(mem_flags::mem_device | mem_flags::mem_threadgroup) + #define GPUbarrierWarpAlive() #define GPUAtomic(type) type // atomic variable type #elif defined(__HIPCC__) //Defines for HIP #define GPUd() __device__ @@ -178,6 +182,7 @@ #define GPUgeneric() #define GPUbarrier() __syncthreads() #define GPUbarrierWarp() + #define GPUbarrierWarpAlive() #define GPUAtomic(type) type #elif defined(__CUDACC__) //Defines for CUDA #ifndef GPUCA_GPUCODE_DEVICE @@ -205,6 +210,7 @@ #define GPUgeneric() #define GPUbarrier() __syncthreads() #define GPUbarrierWarp() __syncwarp() + #define GPUbarrierWarpAlive() GPUbarrierWarp() #define GPUAtomic(type) type #endif diff --git a/GPU/GPUTracking/DataCompression/GPUTPCCompressionKernels.cxx b/GPU/GPUTracking/DataCompression/GPUTPCCompressionKernels.cxx index 211e45264ca51..31ae458424583 100644 --- a/GPU/GPUTracking/DataCompression/GPUTPCCompressionKernels.cxx +++ b/GPU/GPUTracking/DataCompression/GPUTPCCompressionKernels.cxx @@ -39,7 +39,7 @@ GPUdii() void GPUTPCCompressionKernels::Thread(int32_t nBlocks, int32_t nThread const float maxSharedFrac = tracker.Param().rec.tpc.trackletMaxSharedFraction; for (int32_t itr = s.mItr0 + iThread; itr < s.mNTracklets; itr += s.mNThreadsTotal) { - GPUbarrierWarp(); + GPUbarrierWarpAlive(); GPUglobalref() GPUTPCTracklet& GPUrestrict() tracklet = tracker.Tracklets()[itr]; From 74f74ddea1d55b45360fe83def242e402ec1f753 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Tue, 1 Dec 2026 00:38:22 +0100 Subject: [PATCH 16/18] GPU: Add missing warp synchronization to gather kernel --- .../DataCompression/GPUTPCCompressionKernels.cxx | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/GPU/GPUTracking/DataCompression/GPUTPCCompressionKernels.cxx b/GPU/GPUTracking/DataCompression/GPUTPCCompressionKernels.cxx index 31ae458424583..b51825edc5a0e 100644 --- a/GPU/GPUTracking/DataCompression/GPUTPCCompressionKernels.cxx +++ b/GPU/GPUTracking/DataCompression/GPUTPCCompressionKernels.cxx @@ -610,7 +610,8 @@ GPUdii() void GPUTPCCompressionGatherKernels::Thread(nLanes, trackEnd - i) : 0; for (uint32_t j = 0; j < elems; j++) { nTrackClusters = smem.unbuffered.sizes[iWarp][j]; @@ -641,6 +643,7 @@ GPUdii() void GPUTPCCompressionGatherKernels::Thread Date: Tue, 1 Dec 2026 00:57:58 +0100 Subject: [PATCH 17/18] GPU: Finalize slave chains (e.g. write debug output) --- GPU/GPUTracking/Base/GPUReconstruction.cxx | 3 +++ GPU/GPUTracking/Interface/GPUO2Interface.cxx | 4 +--- GPU/GPUTracking/Standalone/Benchmark/standalone.cxx | 3 --- 3 files changed, 4 insertions(+), 6 deletions(-) diff --git a/GPU/GPUTracking/Base/GPUReconstruction.cxx b/GPU/GPUTracking/Base/GPUReconstruction.cxx index 167e8a9932358..843030d532559 100644 --- a/GPU/GPUTracking/Base/GPUReconstruction.cxx +++ b/GPU/GPUTracking/Base/GPUReconstruction.cxx @@ -448,6 +448,9 @@ int32_t GPUReconstruction::Finalize() for (uint32_t i = 0; i < mChains.size(); i++) { mChains[i]->Finalize(); } + for (uint32_t i = 0; i < mSlaves.size(); i++) { + mSlaves[i]->Finalize(); + } return 0; } diff --git a/GPU/GPUTracking/Interface/GPUO2Interface.cxx b/GPU/GPUTracking/Interface/GPUO2Interface.cxx index a82a1919aabde..8b4eec4c3fae6 100644 --- a/GPU/GPUTracking/Interface/GPUO2Interface.cxx +++ b/GPU/GPUTracking/Interface/GPUO2Interface.cxx @@ -126,9 +126,7 @@ void GPUO2Interface::Deinitialize() mCtx[0].mRec->TerminatePipelineWorker(); mInternals->pipelineThread->join(); } - for (uint32_t i = 0; i < mNContexts; i++) { - mCtx[i].mRec->Finalize(); - } + mCtx[0].mRec->Finalize(); mCtx[0].mRec->Exit(); for (int32_t i = mNContexts - 1; i >= 0; i--) { mCtx[i].mRec.reset(); diff --git a/GPU/GPUTracking/Standalone/Benchmark/standalone.cxx b/GPU/GPUTracking/Standalone/Benchmark/standalone.cxx index 910a8ea46dcff..7b850e174f32d 100644 --- a/GPU/GPUTracking/Standalone/Benchmark/standalone.cxx +++ b/GPU/GPUTracking/Standalone/Benchmark/standalone.cxx @@ -1171,9 +1171,6 @@ int32_t main(int argc, char** argv) } rec->Finalize(); - if (configStandalone.testSyncAsync) { - recAsync->Finalize(); - } if (configStandalone.outputcontrolmem && rec->IsGPU()) { if (rec->unregisterMemoryForGPU(outputmemory.get()) || (configStandalone.proc.doublePipeline && recPipeline->unregisterMemoryForGPU(outputmemoryPipeline.get()))) { printf("Error unregistering memory\n"); From 336e57788c6494a6f5e4a11172b5e5680a23e9b5 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Tue, 1 Dec 2026 00:58:16 +0100 Subject: [PATCH 18/18] GPU OpenCL: Implement missing dummy functions for memory registration --- GPU/GPUTracking/Base/opencl/GPUReconstructionOCL.h | 2 ++ 1 file changed, 2 insertions(+) diff --git a/GPU/GPUTracking/Base/opencl/GPUReconstructionOCL.h b/GPU/GPUTracking/Base/opencl/GPUReconstructionOCL.h index f322c17cb81cd..919526e357e81 100644 --- a/GPU/GPUTracking/Base/opencl/GPUReconstructionOCL.h +++ b/GPU/GPUTracking/Base/opencl/GPUReconstructionOCL.h @@ -50,6 +50,8 @@ class GPUReconstructionOCL : public GPUReconstructionProcessing::KernelInterface bool IsEventDone(deviceEvent* evList, int32_t nEvents = 1) override; size_t WriteToConstantMemory(size_t offset, const void* src, size_t size, int32_t stream = -1, deviceEvent* ev = nullptr) override; + int32_t registerMemoryForGPU_internal(const void* ptr, size_t size) override { return 0; } + int32_t unregisterMemoryForGPU_internal(const void* ptr) override { return 0; } size_t GPUMemCpy(void* dst, const void* src, size_t size, int32_t stream, int32_t toGPU, deviceEvent* ev = nullptr, deviceEvent* evList = nullptr, int32_t nEvents = 1) override; void ReleaseEvent(deviceEvent ev) override; void RecordMarker(deviceEvent* ev, int32_t stream) override;