From 3ce42a19ef35b53b6f42c70b3e4766787bcb6afe Mon Sep 17 00:00:00 2001 From: David Rohr Date: Fri, 27 Nov 2026 10:33:13 +0100 Subject: [PATCH 01/12] GPU RTC: Print which cache files are used --- GPU/GPUTracking/Base/GPUReconstructionRTCHelpers.inc | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/GPU/GPUTracking/Base/GPUReconstructionRTCHelpers.inc b/GPU/GPUTracking/Base/GPUReconstructionRTCHelpers.inc index 08a6ca5df25b8..f768b9382e739 100644 --- a/GPU/GPUTracking/Base/GPUReconstructionRTCHelpers.inc +++ b/GPU/GPUTracking/Base/GPUReconstructionRTCHelpers.inc @@ -232,7 +232,7 @@ class Cache // RTC cache file /rtc..cache. (no id with bool retVal = read(fp, filename, binExtension, nCompile); fclose(fp); if (retVal) { - GPUInfo("Using RTC cache file"); + 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() } @@ -248,7 +248,7 @@ class Cache // RTC cache file /rtc..cache. (no id with if (fp == nullptr) { throw std::runtime_error("Cannot open cache file for writing"); } - GPUInfo("Storing RTC compilation result in cache file"); + GPUInfo("Storing RTC compilation result in cache file %s", mFileName.c_str()); for (uint32_t i = 0; i < N_SHA; i++) { if (fwrite(mSHA[i], 1, 20, fp) != 20) { throw std::runtime_error("Error writing cache file"); From 720be741144017fadcd49418a6b08db286d10684 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Fri, 27 Nov 2026 11:08:00 +0100 Subject: [PATCH 02/12] GPU CUDA: Increase stack size, and print a warning if stack size was exceeded --- GPU/GPUTracking/Base/cuda/GPUReconstructionCUDA.cu | 5 +++++ GPU/GPUTracking/Base/cuda/GPUReconstructionCUDAInternals.h | 1 + GPU/GPUTracking/Definitions/GPUDefParametersConstants.h | 2 +- 3 files changed, 7 insertions(+), 1 deletion(-) diff --git a/GPU/GPUTracking/Base/cuda/GPUReconstructionCUDA.cu b/GPU/GPUTracking/Base/cuda/GPUReconstructionCUDA.cu index ed4e8bbf042e0..1f9949e8ffde2 100644 --- a/GPU/GPUTracking/Base/cuda/GPUReconstructionCUDA.cu +++ b/GPU/GPUTracking/Base/cuda/GPUReconstructionCUDA.cu @@ -285,6 +285,7 @@ int32_t GPUReconstructionCUDA::InitDevice_Runtime() return (1); } #endif + GPUChkErr(cudaDeviceGetLimit(&mInternals->stackSizeInit, cudaLimitStackSize)); if (mDeviceMemorySize == 1 || mDeviceMemorySize == 2) { mDeviceMemorySize = std::max(0, devMemory[mDeviceId] - REQUIRE_FREE_MEMORY_RESERVED_PER_SM * deviceProp.multiProcessorCount); // Take all GPU memory but some reserve @@ -456,6 +457,10 @@ int32_t GPUReconstructionCUDA::ExitDevice_Runtime() GPUChkErr(cuModuleUnload(*mInternals->kernelModules[i])); } + size_t stackSize = 0; + if (GPUChkErrI(cudaDeviceGetLimit(&stackSize, cudaLimitStackSize)) == 0 && stackSize > mInternals->stackSizeInit) { + GPUError("CUDA stack size was increased at runtime from %zu to %zu, please increase GPU_STACK_SIZE", mInternals->stackSizeInit, stackSize); + } GPUChkErrI(cudaDeviceReset()); GPUInfo("CUDA Uninitialized"); } diff --git a/GPU/GPUTracking/Base/cuda/GPUReconstructionCUDAInternals.h b/GPU/GPUTracking/Base/cuda/GPUReconstructionCUDAInternals.h index acc3ee06e3f9a..ed58cfb1e3e40 100644 --- a/GPU/GPUTracking/Base/cuda/GPUReconstructionCUDAInternals.h +++ b/GPU/GPUTracking/Base/cuda/GPUReconstructionCUDAInternals.h @@ -31,6 +31,7 @@ struct GPUReconstructionCUDAInternals { std::vector> kernelModules; // module for RTC compilation std::vector> kernelFunctions; // vector of ptrs to RTC kernels cudaStream_t Streams[constants::GPU_MAX_STREAMS]; // Pointer to array of CUDA Streams + size_t stackSizeInit = 0; // Stack size limit after initialization, to detect increases by the driver at runtime static void getArgPtrs(const void** pArgs) {} template diff --git a/GPU/GPUTracking/Definitions/GPUDefParametersConstants.h b/GPU/GPUTracking/Definitions/GPUDefParametersConstants.h index d62d69a87a920..f66c250d213e1 100644 --- a/GPU/GPUTracking/Definitions/GPUDefParametersConstants.h +++ b/GPU/GPUTracking/Definitions/GPUDefParametersConstants.h @@ -43,7 +43,7 @@ static GPUglobalconstexpr() size_t GPU_MEM_MAX_TPC_CLUSTERS = 1024 * 102 static GPUglobalconstexpr() size_t GPU_MEM_MAX_TRD_TRACKLETS = 128 * 1024ull; // Maximum number of TRD tracklets static GPUglobalconstexpr() size_t GPU_DEFAULT_MEMORY_SIZE = 6 * 1024 * 1024 * 1024ull; // Size of memory allocated on Device static GPUglobalconstexpr() size_t GPU_DEFAULT_HOST_MEMORY_SIZE = 1 * 1024 * 1024 * 1024ull; // Size of memory allocated on Host -static GPUglobalconstexpr() size_t GPU_STACK_SIZE = 8 * 1024ull; // Stack size per GPU thread +static GPUglobalconstexpr() size_t GPU_STACK_SIZE = 24 * 1024ull; // Stack size per GPU thread static GPUglobalconstexpr() size_t GPU_HEAP_SIZE = 16 * 1025 * 1024ull; // Stack size per GPU thread } // namespace o2::gpu::constants From f887fb804f243e3cfdaf8b574054c8e6c74c3ece Mon Sep 17 00:00:00 2001 From: David Rohr Date: Fri, 27 Nov 2026 10:12:51 +0100 Subject: [PATCH 03/12] GPU TPC: Use some smaller data types for local variables to reduce register count / stack size --- GPU/GPUTracking/Merger/GPUTPCGMMerger.cxx | 76 +++++++-------- GPU/GPUTracking/Merger/GPUTPCGMTrackParam.cxx | 95 ++++++++++--------- GPU/GPUTracking/Merger/GPUTPCGMTrackParam.h | 14 +-- 3 files changed, 93 insertions(+), 92 deletions(-) diff --git a/GPU/GPUTracking/Merger/GPUTPCGMMerger.cxx b/GPU/GPUTracking/Merger/GPUTPCGMMerger.cxx index 2f0a5eecae5cb..94daa1bffe3a5 100644 --- a/GPU/GPUTracking/Merger/GPUTPCGMMerger.cxx +++ b/GPU/GPUTracking/Merger/GPUTPCGMMerger.cxx @@ -648,7 +648,7 @@ GPUd() int32_t GPUTPCGMMerger::RefitSectorTrack(GPUTPCGMSectorTrack& sectorTrack const auto tmp = sectorTrack.ClusterTN() > sectorTrack.ClusterT0() ? std::array{sectorTrack.ClusterTN(), sectorTrack.ClusterT0()} : std::array{sectorTrack.ClusterT0(), sectorTrack.ClusterTN()}; trk.ShiftZ(*this, sector, tmp[0], tmp[1], inTrack->Param().GetX()); // We do not store the inner / outer cluster X, so we just use the track X instead sectorTrack.SetX2(0.f); - for (int32_t way = 0; way < 2; way++) { + for (int8_t way = 0; way < 2; way++) { if (way) { prop.SetFitInProjections(true); prop.SetPropagateBzOnly(true); @@ -657,10 +657,10 @@ GPUd() int32_t GPUTPCGMMerger::RefitSectorTrack(GPUTPCGMSectorTrack& sectorTrack prop.SetTrack(&trk, alpha); int32_t start = way ? inTrack->NHits() - 1 : 0; int32_t end = way ? 0 : (inTrack->NHits() - 1); - int32_t incr = way ? -1 : 1; + const int32_t incr = way ? -1 : 1; for (int32_t i = start; i != end; i += incr) { float x, y, z; - int32_t row, flags; + uint8_t row, flags; const GPUTPCTracker& tracker = GetConstantMem()->tpcTrackers[sector]; const GPUTPCHitId& ic = tracker.TrackHits()[inTrack->FirstHitID() + i]; int32_t clusterIndex = tracker.Data().ClusterDataIndex(tracker.Data().Row(ic.RowIndex()), ic.HitIndex()); @@ -770,7 +770,7 @@ GPUd() void GPUTPCGMMerger::LinkExtrapolatedTracks(int32_t nBlocks, int32_t nThr for (uint32_t itr = mMemory->nUnpackedTracks + iBlock * nThreads + iThread; itr < mMemory->nUnpackedTracks + mMemory->nUnpackedTracksGlobal; itr += nThreads * nBlocks) { GPUTPCGMSectorTrack& extrapolatedTrack = mSectorTrackInfos[itr]; GPUTPCGMSectorTrack& localTrack = mSectorTrackInfos[extrapolatedTrack.LocalTrackId() & 0xFFFFFF]; - int up = (extrapolatedTrack.LocalTrackId() & 0x40000000) ? 1 : 0; + const bool up = (extrapolatedTrack.LocalTrackId() & 0x40000000) ? 1 : 0; localTrack.SetExtrapolatedTrackId(up, itr); } } @@ -803,7 +803,7 @@ GPUd() void GPUTPCGMMerger::MergeSectorsPrepareStep2(int32_t nBlocks, int32_t nT GPUTPCGMSectorTrack trackTmp; for (uint32_t itr = iBlock * nThreads + iThread; itr < mMemory->nUnpackedTracks; itr += nThreads * nBlocks) { const GPUTPCGMSectorTrack* track = &mSectorTrackInfos[itr]; - int32_t iSector = track->Sector(); + const int8_t iSector = track->Sector(); if (track->PrevSegmentNeighbour() >= 0 && track->Sector() == mSectorTrackInfos[track->PrevSegmentNeighbour()].Sector()) { continue; @@ -841,7 +841,7 @@ GPUd() void GPUTPCGMMerger::MergeSectorsPrepareStep2(int32_t nBlocks, int32_t nT if (track->TransportToXAlpha(this, x0, sinAlpha, cosAlpha, fieldBz, b, maxSin)) { b.SetTrackID(itr); b.SetNClusters(track->NClusters()); - for (int32_t i = 0; i < 4; i++) { + for (int8_t i = 0; i < 4; i++) { if (CAMath::Abs(b.Cov()[i]) >= 5.0f) { b.SetCov(i, 5.0f); } @@ -937,8 +937,8 @@ GPUd() void GPUTPCGMMerger::MergeBorderTracks<2>(int32_t nBlocks, int32_t nThrea factor2ys = factor2General * factor2ys; factor2zt = factor2General * factor2zt; - int32_t minNPartHits = Param().rec.tpc.trackMergerMinPartHits; - int32_t minNTotalHits = Param().rec.tpc.trackMergerMinTotalHits; + const int16_t minNPartHits = Param().rec.tpc.trackMergerMinPartHits; + const int16_t minNTotalHits = Param().rec.tpc.trackMergerMinTotalHits; bool sameSector = (iSector1 == iSector2); @@ -983,7 +983,7 @@ GPUd() void GPUTPCGMMerger::MergeBorderTracks<2>(int32_t nBlocks, int32_t nThrea } if (mergeMode & mergeModes::mergeAcrossCE) { // Merging CE tracks - int32_t maxRowDiff = (mergeMode & mergeModes::mergeAtCluster) ? 1 : 3; // TODO: check cut + const int8_t maxRowDiff = (mergeMode & mergeModes::mergeAtCluster) ? 1 : 3; // TODO: check cut if (CAMath::Abs(b1.Row() - b2.Row()) > maxRowDiff) { CADEBUG2(continue, printf("!ROW\n")); } @@ -1085,7 +1085,7 @@ GPUd() void GPUTPCGMMerger::MergeWithinSectorsPrepare(int32_t nBlocks, int32_t n for (uint32_t itr = iBlock * nThreads + iThread; itr < mMemory->nUnpackedTracks; itr += nThreads * nBlocks) { const GPUTPCGMSectorTrack& track = mSectorTrackInfos[itr]; - int32_t iSector = track.Sector(); + const int8_t iSector = track.Sector(); GPUTPCGMBorderTrack b; if (track.TransportToX(this, x0, Param().bzCLight, b, maxSin)) { b.SetTrackID(itr); @@ -1100,7 +1100,7 @@ GPUd() void GPUTPCGMMerger::MergeWithinSectorsPrepare(int32_t nBlocks, int32_t n GPUd() void GPUTPCGMMerger::MergeSectorsPrepare(int32_t nBlocks, int32_t nThreads, int32_t iBlock, int32_t iThread, int32_t border0, int32_t border1, int8_t useOrigTrackParam) { bool part2 = iBlock & 1; - int32_t border = part2 ? border1 : border0; + const int8_t border = part2 ? border1 : border0; GPUAtomic(uint32_t)* n = mMemory->tmpCounter; GPUTPCGMBorderTrack** b = mBorder; if (part2) { @@ -1172,7 +1172,7 @@ GPUd() void GPUTPCGMMerger::ResolveFindConnectedComponentsHookNeighbors(int32_t int32_t start, end; setBlockRange(mMemory->nUnpackedTracks, nBlocks / 4, iBlock / 4, start, end); - int32_t myNeighbor = iBlock % 4; + const int8_t myNeighbor = iBlock % 4; for (int32_t itr = start + iThread; itr < end; itr += nThreads) { int32_t v = mSectorTrackInfos[itr].AnyNeighbour(myNeighbor); @@ -1247,7 +1247,7 @@ GPUd() void GPUTPCGMMerger::ResolveMergeSectors(GPUResolveSharedMemory& smem, in }; // Report whether target sits on either neighbour chain starting at from. auto neighbourChainReaches = [tracks = mSectorTrackInfos](const GPUTPCGMSectorTrack* from, const GPUTPCGMSectorTrack* target) { - for (int32_t k = 0; k < 2; k++) { + for (int8_t k = 0; k < 2; k++) { const GPUTPCGMSectorTrack* tmp = from; while (tmp->Neighbour(k) >= 0) { tmp = &tracks[tmp->Neighbour(k)]; @@ -1367,7 +1367,7 @@ GPUd() void GPUTPCGMMerger::ResolveMergeSectors(GPUResolveSharedMemory& smem, in track2->SetPrevSegmentNeighbour(track1 - mSectorTrackInfos); // k = 0: Merge right side // k = 1: Merge left side - for (int32_t k = 0; k < 2; k++) { + for (int8_t k = 0; k < 2; k++) { track1 = track1Base; track2 = track2Base; while (track2->Neighbour(k) >= 0) { @@ -1412,8 +1412,8 @@ GPUd() void GPUTPCGMMerger::MergeCEFill(const GPUTPCGMSectorTrack* track, const if (!Param().par.continuousTracking && CAMath::Abs(z) > 10) { return; } - int32_t sector = track->Sector(); - for (int32_t attempt = 0; attempt < 2; attempt++) { + const int8_t sector = track->Sector(); + for (int8_t attempt = 0; attempt < 2; attempt++) { GPUTPCGMBorderTrack b; const float x0 = GPUTPCGeometry::Row2X(attempt == 0 ? 63 : cls.row); // TODO: Fix 63 if (track->TransportToX(this, x0, Param().bzCLight, b, constants::MAX_SIN_PHI_LOW)) { @@ -1510,7 +1510,7 @@ GPUd() void GPUTPCGMMerger::MergeCE(int32_t nBlocks, int32_t nThreads, int32_t i int32_t pos = newRef; #pragma unroll - for (int32_t k = 1; k >= 0; k--) { + for (int8_t k = 1; k >= 0; k--) { for (uint32_t j = 0; j != trk[k]->NClusters(); j++) { mClusters[pos++] = mClusters[trk[k]->FirstClusterRef() + j]; } @@ -1560,7 +1560,7 @@ GPUd() void GPUTPCGMMerger::CollectMergedTracks(int32_t nBlocks, int32_t nThread int32_t itr = iBlock * nThreads + iThread; GPUTPCGMSectorTrack* trbase = nullptr; - int32_t leg = 0; + int16_t leg = 0; int32_t lastMergedSegment = -1; bool revertSegments = false; bool revertInSegment = false; @@ -1614,7 +1614,7 @@ GPUd() void GPUTPCGMMerger::CollectMergedTracks(int32_t nBlocks, int32_t nThread float mainT = 1e9; revertSegments = true; - for (uint32_t k = 0; k < 2; k++) { // --------------- check if first or last segment is primary --------------- + for (uint8_t k = 0; k < 2; k++) { // --------------- check if first or last segment is primary --------------- int32_t ichk = k ? lasttr : itr; const GPUTPCGMSectorTrack* trchk = &mSectorTrackInfos[ichk]; while (true) { @@ -1638,7 +1638,7 @@ GPUd() void GPUTPCGMMerger::CollectMergedTracks(int32_t nBlocks, int32_t nThread } { // --------------- find longest sector track of main segment --------------- - int32_t length = 0; + int16_t length = 0; int32_t ichk = revertSegments ? itr : lasttr; const GPUTPCGMSectorTrack* trchk = &mSectorTrackInfos[ichk]; const GPUTPCGMSectorTrack* longest = trchk; @@ -1661,8 +1661,8 @@ GPUd() void GPUTPCGMMerger::CollectMergedTracks(int32_t nBlocks, int32_t nThread } do { - int32_t nParts = 0; - uint32_t nHits = 0; + int8_t nParts = 0; + uint16_t nHits = 0; GPUTPCGMSectorTrack* tr = trbase; while (true) { @@ -1675,7 +1675,7 @@ GPUd() void GPUTPCGMMerger::CollectMergedTracks(int32_t nBlocks, int32_t nThread nHits += tr->NClusters(); trackParts[nParts++] = tr; - for (int32_t i = 0; i < 2; i++) { + for (int8_t i = 0; i < 2; i++) { if (tr->ExtrapolatedTrackId(i) != -1) { if (nParts >= kMaxParts) { break; @@ -1723,7 +1723,7 @@ GPUd() void GPUTPCGMMerger::CollectMergedTracks(int32_t nBlocks, int32_t nThread trackCluster trackClusters[kMaxClusters]; nHits = 0; - for (int32_t ipart = 0; ipart < nParts; ipart++) { + for (int8_t ipart = 0; ipart < nParts; ipart++) { const GPUTPCGMSectorTrack* t = trackParts[ipart]; CADEBUG(printf("Collect Track %d Part %d QPt %f DzDs %f\n", mMemory->nMergedTracks, ipart, t->QPt(), t->DzDs())); int32_t nTrackHits = t->NClusters(); @@ -1750,10 +1750,10 @@ GPUd() void GPUTPCGMMerger::CollectMergedTracks(int32_t nBlocks, int32_t nThread } } } - int32_t firstTrackIndex = 0; - int32_t lastTrackIndex = nParts - 1; + int8_t firstTrackIndex = 0; + int8_t lastTrackIndex = nParts - 1; if (ordered == 0) { - int32_t nTmpHits = 0; + int16_t nTmpHits = 0; trackCluster trackClustersUnsorted[kMaxClusters]; int16_t clusterIndices[kMaxClusters]; for (uint32_t i = 0; i < nHits; i++) { @@ -1775,10 +1775,10 @@ GPUd() void GPUTPCGMMerger::CollectMergedTracks(int32_t nBlocks, int32_t nThread } } - int32_t nFilteredHits = 0; - int32_t indPrev = -1; + int16_t nFilteredHits = 0; + int16_t indPrev = -1; for (uint32_t i = 0; i < nHits; i++) { - int32_t ind = clusterIndices[i]; + const int16_t ind = clusterIndices[i]; if (indPrev >= 0 && trackClustersUnsorted[ind].id == trackClustersUnsorted[indPrev].id) { continue; } @@ -1929,7 +1929,7 @@ GPUd() void GPUTPCGMMerger::PrepareForFit1(int32_t nBlocks, int32_t nThreads, in if (Param().rec.tpc.rebuildTrackInFit) { // Row range the rebuild can use: cluster rows and the radii the helix can reach, plus margin const auto& GPUrestrict() p = trk.GetParam(); const float k = -p.GetQPt() * Param().bzCLight; - int32_t rowFirst = 0, rowLast = GPUTPCGeometry::NROWS - 1; + uint8_t rowFirst = 0, rowLast = GPUTPCGeometry::NROWS - 1; if (CAMath::Abs(k) > 1e-4f && p.GetX() > 50.f && p.GetX() < 300.f && CAMath::Abs(p.GetY()) < p.GetX()) { // Otherwise (almost straight tracks, implausible seed) full range const float cosPhi = CAMath::Sqrt(CAMath::Max(0.f, 1.f - p.GetSinPhi() * p.GetSinPhi())); const float r1 = 1.f / k, r2 = 2.f / k; // Signed radius for nominal pt, and for twice the pt as upper limit of the circle @@ -2045,7 +2045,7 @@ GPUd() void GPUTPCGMMerger::MergeLoopersInit(int32_t nBlocks, int32_t nThreads, const auto& p = trk.GetParam(); const float qptabs = CAMath::Abs(p.GetQPt()); if (trk.OK() && trk.NClusters() && trk.Leg() == 0 && qptabs * Param().qptB5Scaler > 5.f && qptabs * Param().qptB5Scaler <= lowPtThresh) { - const int32_t sector = mClusters[trk.FirstClusterRef() + trk.NClusters() - 1].sector; + const int8_t sector = mClusters[trk.FirstClusterRef() + trk.NClusters() - 1].sector; const float refz = p.GetZ() + (Param().par.continuousTracking ? GetConstantMem()->calibObjects.fastTransform->convVertexTimeToZOffset(sector, p.GetTOffset(), Param().continuousMaxTimeBin) : 0) + (trk.CSide() ? -100 : 100); float sinA, cosA; CAMath::SinCos(trk.GetAlpha(), sinA, cosA); @@ -2149,10 +2149,10 @@ GPUd() void GPUTPCGMMerger::MergeLoopersMain(int32_t nBlocks, int32_t nThreads, const float dzcorr = dznormalized + phasecorr * phasecorrdirection; const bool sameside = !(trk1.CSide() ^ trk2.CSide()); const float dzcorrlimit[4] = {sameside ? 0.018f : 0.012f, sameside ? 0.12f : 0.025f, 0.14f, 0.15f}; - const int32_t dzcorrcount = sameside ? 4 : 2; + const int8_t dzcorrcount = sameside ? 4 : 2; bool dzcorrok = false; float dznorm = 0.f; - for (int32_t k = 0; k < dzcorrcount; k++) { + for (int8_t k = 0; k < dzcorrcount; k++) { const float d = CAMath::Abs(dzcorr - 0.5f * k); if (d <= dzcorrlimit[k]) { dzcorrok = true; @@ -2256,8 +2256,8 @@ GPUd() void GPUTPCGMMerger::PrepareHitWeights(int32_t nBlocks, int32_t nThreads, } mTrackRebuildHelper[i].reverse = mClusters[trk.FirstClusterRef()].row < mClusters[trk.FirstClusterRef() + trk.NClusters() - 1].row; if (!(Param().rec.tpc.disableRebuildAttachment & 8)) { - const uint32_t nMaxCandidates = Param().rec.tpc.rebuildTrackInFitClusterCandidates; - int lastRow = -1; + const uint8_t nMaxCandidates = Param().rec.tpc.rebuildTrackInFitClusterCandidates; + int16_t lastRow = -1; for (uint32_t j = 0; j < trk.NClusters(); j++) { const auto& cl = mClusters[trk.FirstClusterRef() + j]; if (!RebuildRowInRange(i, cl.row)) { @@ -2265,7 +2265,7 @@ GPUd() void GPUTPCGMMerger::PrepareHitWeights(int32_t nBlocks, int32_t nThreads, } auto* candidates = ClusterCandidates(i, cl.row); if ((!(cl.state & GPUTPCGMMergedTrackHit::flagReject) || trk.GetParam().GetNDF() <= 0) && (candidates[0].isEmpty() || cl.row == lastRow)) { // Row not searched: the original clusters of the row compete as normal candidates with fixed error - for (uint32_t k = 0; k < nMaxCandidates; k++) { + for (uint8_t k = 0; k < nMaxCandidates; k++) { if (candidates[k].isEmpty()) { candidates[k].set(CandidateId(cl.num, cl.sector, cl.row), cl.sector, (CAMath::half_t)Param().rec.tpc.rebuildTrackFallbackErr); break; @@ -2322,7 +2322,7 @@ GPUd() void GPUTPCGMMerger::ResolveHitWeights1(int32_t nBlocks, int32_t nThreads GPUd() void GPUTPCGMMerger::ResolveHitWeights2(int32_t nBlocks, int32_t nThreads, int32_t iBlock, int32_t iThread) { - int32_t nIter = Param().rec.tpc.rebuildTrackInFitClusterCandidates; + const int8_t nIter = Param().rec.tpc.rebuildTrackInFitClusterCandidates; for (int32_t i = get_global_id(0); i < NMergedTracks(); i += get_global_size(0)) { auto& trk = mMergedTracks[i]; if (!trk.OK()) { diff --git a/GPU/GPUTracking/Merger/GPUTPCGMTrackParam.cxx b/GPU/GPUTracking/Merger/GPUTPCGMTrackParam.cxx index 04b9b3570175a..8e31191d36ba2 100644 --- a/GPU/GPUTracking/Merger/GPUTPCGMTrackParam.cxx +++ b/GPU/GPUTracking/Merger/GPUTPCGMTrackParam.cxx @@ -91,7 +91,7 @@ GPUd() bool GPUTPCGMTrackParam::Fit(GPUTPCGMMerger& GPUrestrict() merger, GPUTPC merger.TrackRebuildHelper()[iTrk].highInclRowLow = merger.TrackRebuildHelper()[iTrk].highInclRowHigh = 255; } - const int32_t nWays = param.rec.tpc.nWays; + const int8_t nWays = param.rec.tpc.nWays; const int32_t maxN = N; if (rebuilt && maxN > 0 && param.par.continuousTracking && !track.CCE() && !track.Looper()) { // The rebuilt track can have other first / last clusters than the track the Z shift was computed for const float t0 = merger.GetConstantMem()->ioPtrs.clustersNative->clustersLinear[clusters[0].num].getTime(), tN = merger.GetConstantMem()->ioPtrs.clustersNative->clustersLinear[clusters[maxN - 1].num].getTime(); @@ -102,17 +102,17 @@ GPUd() bool GPUTPCGMTrackParam::Fit(GPUTPCGMMerger& GPUrestrict() merger, GPUTPC int32_t interpolatedStart = 0; float covYYUpd = 0.f; float deltaZ = 0.f; - const int32_t wayRebuildStart = param.rec.tpc.mergerInitial3wayFit ? 2 : 0; + const int8_t wayRebuildStart = param.rec.tpc.mergerInitial3wayFit ? 2 : 0; const bool adjacentInRebuild = param.rec.tpc.rebuildTrackInFit && !param.rec.tpc.mergerInterpolateErrors; const int8_t adjacentLeg = 1 + (track.Leg() == 0); - for (int32_t iWay = rebuilt ? (wayRebuildStart + 2) : 0; iWay < nWays; iWay++) { // TODO DR: Unrolling has no performance improvement on GPU, why? - GPUbarrierWarp(); // TODO: Validate on different GPUs, check if we should do similar things in other places - int32_t nMissed = 0, nMissedHard = 0; // nMissed: cluster rejected, fit failure. nMissedHard: also propagation failure / high incl. - float sumInvSqrtCharge = 0.f; // TODO: Compute in first iteration and store! - int32_t nAvgCharge = 0; + for (int8_t iWay = rebuilt ? (wayRebuildStart + 2) : 0; iWay < nWays; iWay++) { // TODO DR: Unrolling has no performance improvement on GPU, why? + GPUbarrierWarp(); // TODO: Validate on different GPUs, check if we should do similar things in other places + int16_t nMissed = 0, nMissedHard = 0; // nMissed: cluster rejected, fit failure. nMissedHard: also propagation failure / high incl. + float sumInvSqrtCharge = 0.f; // TODO: Compute in first iteration and store! + int16_t nAvgCharge = 0; - int32_t resetT0 = CAMath::Max(10, CAMath::Min(40, 150.f / CAMath::Abs(mP[4]))); + int16_t resetT0 = CAMath::Max(10, CAMath::Min(40, 150.f / CAMath::Abs(mP[4]))); const bool refit = (nWays == 1 || iWay >= 1); const bool finalOutInFit = iWay >= nWays - 2; const bool finalFit = iWay == nWays - 1; @@ -135,7 +135,7 @@ GPUd() bool GPUTPCGMTrackParam::Fit(GPUTPCGMMerger& GPUrestrict() merger, GPUTPC bool fitBroken = false; float lastUpdateX = -1; const bool inFlyDirection = iWay & 1; - const int32_t wayDirection = (iWay & 1) ? -1 : 1; + const int8_t wayDirection = (iWay & 1) ? -1 : 1; if (param.rec.tpc.mergerInterpolateErrors && iWay == nWays - 2) { ihitStartInterpolateReject = ihitStart; @@ -169,14 +169,14 @@ GPUd() bool GPUTPCGMTrackParam::Fit(GPUTPCGMMerger& GPUrestrict() merger, GPUTPC uint8_t clusterState = clusters[ihit].state; const float clAlpha = param.Alpha(clusters[ihit].sector); float xx, yy, zz; - const int32_t currentClusterStatus = MergeDoubleRowClusters(ihit, wayDirection, clusters, merger, prop, xx, yy, zz, maxN, clAlpha, clusterState, (param.rec.tpc.rebuildTrackInFit && !param.rec.tpc.mergerInterpolateErrors) ? rebuilt : allowChangeClusters); + const int8_t currentClusterStatus = MergeDoubleRowClusters(ihit, wayDirection, clusters, merger, prop, xx, yy, zz, maxN, clAlpha, clusterState, (param.rec.tpc.rebuildTrackInFit && !param.rec.tpc.mergerInterpolateErrors) ? rebuilt : allowChangeClusters); // TODO: Check about tracks who have clusters in the same row multiple times in different sectors const auto& cluster = clusters[ihit]; CADEBUG(printf("\tSector %2d %11sTrack Alpha %8.3f %s, X %8.3f - Y %8.3f, Z %8.3f - QPt %7.2f (%7.2f), SP %5.2f (%5.2f) %28s --- Cov sY %8.3f sZ %8.3f sSP %8.3f sPt %8.3f - YPt %8.3f\n", (int32_t)cluster.sector, "", prop.GetAlpha(), (CAMath::Abs(prop.GetAlpha() - clAlpha) < 0.01 ? " " : " R!"), mX, mP[0], mP[1], mP[4], prop.GetQPt0(), mP[2], prop.GetSinPhi0(), "", sqrtf(CAMath::Max(0.f, mC[0])), sqrtf(CAMath::Max(0.f, mC[2])), sqrtf(CAMath::Max(0.f, mC[5])), sqrtf(CAMath::Max(0.f, mC[14])), mC[10])); CADEBUG(printf("\tHit %3d/%3d Row %3d: Cluster Alpha %8.3f %3d, X %8.3f - Y %8.3f, Z %8.3f (Missed %d, %d)\n", ihit, maxN, (int32_t)clusters[ihit].row, clAlpha, (int32_t)clusters[ihit].sector, xx, yy, zz, nMissed, nMissedHard)); - const int32_t rowGap = lastPropagateRow == 255 ? 0 : CAMath::Max(0, CAMath::Abs(cluster.row - lastPropagateRow) - 1); + const uint8_t rowGap = lastPropagateRow == 255 ? 0 : CAMath::Max(0, CAMath::Abs(cluster.row - lastPropagateRow) - 1); if (rebuilt) { interpolationIndex = ihit; } else if ((uint32_t)interpolationIndex >= interpolation.size) { // covers all indices of the row gap, since they are monotonic @@ -193,7 +193,7 @@ GPUd() bool GPUTPCGMTrackParam::Fit(GPUTPCGMMerger& GPUrestrict() merger, GPUTPC const bool doAttach = (adjacentInRebuild ? (iWay == wayRebuildStart + 1 && !ceOverlap) : (allowChangeClusters && !param.rec.tpc.rebuildTrackInFit)) && !(param.rec.tpc.disableMarkAdjacent & 2); const uint8_t doInterpolate = (!param.rec.tpc.rebuildTrackInFit || (param.rec.tpc.disableRebuildAttachment & 2) || ceOverlap) ? 0 : (iWay == wayRebuildStart ? 1 : (iWay == wayRebuildStart + 1 ? 2 : 0)); if (lastUpdateRow != 255 && (dodEdx || doAttach || doInterpolate)) { - int32_t step = cluster.row > lastPropagateRow ? 1 : -1; + const int8_t step = cluster.row > lastPropagateRow ? 1 : -1; uint8_t sector = lastSector; for (int32_t iRow = lastPropagateRow + step, index = rebuilt ? interpolationIndex : (interpolationIndex - rowGap * wayDirection); iRow != cluster.row; iRow += step, index += wayDirection) { @@ -215,7 +215,7 @@ GPUd() bool GPUTPCGMTrackParam::Fit(GPUTPCGMMerger& GPUrestrict() merger, GPUTPC lastPropagateRow = cluster.row; auto& inter = interpolation.hit[interpolationIndex]; - int32_t retValProp = prop.PropagateToXAlpha(xx, clAlpha, inFlyDirection); + int8_t retValProp = prop.PropagateToXAlpha(xx, clAlpha, inFlyDirection); if ((retValProp == -2 && // Rotation failed, try to bring to new x with old alpha first, rotate, and then propagate to x, alpha (prop.PropagateToXAlpha(xx, prop.GetAlpha(), inFlyDirection) != 0 || // Cannot rotate to new alpha at all prop.PropagateToXAlpha(xx, clAlpha, inFlyDirection))) || // propagation fails nonetheless @@ -307,7 +307,7 @@ GPUd() bool GPUTPCGMTrackParam::Fit(GPUTPCGMMerger& GPUrestrict() merger, GPUTPC } } - int32_t retValHit = FitHit(merger, tmpRows, iTrk, track, xx, yy, zz, clusterState, clAlpha, iWay, inFlyDirection, deltaZ, lastUpdateX, clusters, prop, inter, dEdx, dEdxAlt, sumInvSqrtCharge, nAvgCharge, ihit, ihitMergeFirst, allowChangeClusters, refit, finalFit, nMissed, nMissedHard, uncorrectedY, retryAttempt); + int8_t retValHit = FitHit(merger, tmpRows, iTrk, track, xx, yy, zz, clusterState, clAlpha, iWay, inFlyDirection, deltaZ, lastUpdateX, clusters, prop, inter, dEdx, dEdxAlt, sumInvSqrtCharge, nAvgCharge, ihit, ihitMergeFirst, allowChangeClusters, refit, finalFit, nMissed, nMissedHard, uncorrectedY, retryAttempt); if (retValHit == 0) { DodEdx(dEdx, dEdxAlt, merger, finalFit, ihit, ihitMergeFirst, wayDirection, clusters, clusterState, zz, dEdxSubThresholdRow GPUCA_DEBUG_STREAMER_CHECK(, iTrk)); if (CAMath::Abs(mP[4]) * param.qptB5Scaler > 10 && --resetT0 <= 0 && CAMath::Abs(mP[2]) < 0.15f && CAMath::Square(mP[0] - prop.Model().Y()) + CAMath::Square(mP[1] - prop.Model().Z()) > 1) { // TODO: Could be investigated to reinit the linearization also when sinPhi drifts away from it (a reinit when QPt differs makes things worse, early in the way the QPt of the linearization is usually the better one) @@ -344,8 +344,8 @@ GPUd() bool GPUTPCGMTrackParam::Fit(GPUTPCGMMerger& GPUrestrict() merger, GPUTPC } if (param.rec.tpc.rebuildTrackInFit && !rebuilt && !(param.rec.tpc.disableRebuildAttachment & 16) && param.rec.tpc.rebuildTrackMaxNonIntCov > 0 && iWay >= wayRebuildStart && !(fitBroken && iWay == wayRebuildStart + 1) && CAMath::Abs(mP[2]) < maxSinForUpdate && lastUpdateRow != 255 && mNDF > (int32_t)param.rec.tpc.rebuildTrackNonIntMinNDF) { - const int32_t up = ((clusters[0].row < clusters[maxN - 1].row) ^ (iWay & 1)) ? 1 : -1; - int32_t sector = lastSector; + const int8_t up = ((clusters[0].row < clusters[maxN - 1].row) ^ (iWay & 1)) ? 1 : -1; + int8_t sector = lastSector; CADEBUG(if (merger.MergedTrackMC()) printf("Extrapolate Start Track %d - sector %2d row %3d %s - fake %d\n", iTrk, sector, (int32_t)lastPropagateRow, up == 1 ? "upwards" : "downwards", (int)merger.MergedTrackMC()[iTrk].isFake())); ExtrapolationState es; es.lastGoodRow = es.lastExtrapolateRow = es.lastFoundRow = lastPropagateRow; @@ -357,7 +357,7 @@ GPUd() bool GPUTPCGMTrackParam::Fit(GPUTPCGMMerger& GPUrestrict() merger, GPUTPC const float qPtStart = mP[4], alphaStart = prop.GetAlpha(); const GPUTPCGMTrackParam paramStart = *this; // To revert to if the extrapolation fails prop.SetTrack(this, prop.GetAlpha()); - const uint32_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 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; const float lastFoundX = es.lastFoundX, lastFoundAlpha = es.lastFoundAlpha; const bool revert = es.revert; @@ -365,13 +365,13 @@ GPUd() bool GPUTPCGMTrackParam::Fit(GPUTPCGMMerger& GPUrestrict() merger, GPUTPC StoreLoopPropagation(merger, sector, iExtrapolatedRow, iTrk, up == 1, prop.GetAlpha()); CADEBUG(printf("\t\tSTORING %d extrapolated row %d sector %d out %d\n", iTrk, (int)iExtrapolatedRow, sector, up == 1)); } - const int32_t rowsMoved = CAMath::Abs((int32_t)(iExtrapolatedRow < GPUTPCGeometry::NROWS ? iExtrapolatedRow : iExtrapolatedRow - up) - (int32_t)lastGoodRow); + const int16_t rowsMoved = CAMath::Abs((int32_t)(iExtrapolatedRow < GPUTPCGeometry::NROWS ? iExtrapolatedRow : (uint8_t)(iExtrapolatedRow - up)) - (int32_t)lastGoodRow); // 255 after row 0 with up = -1 if (revert || lastGoodRow == lastPropagateRow || lastFoundRow != lastGoodRow || (iWay == wayRebuildStart && sector != lastSector) || rowsMoved > param.rec.tpc.rebuildTrackExtrMaxRowsBack || (rowsMoved && prop.PropagateToXAlpha(lastFoundX, lastFoundAlpha, !inFlyDirection))) { *this = paramStart; // Failure, nothing accepted, rejected clusters in the fit, sector changed before the next way goes back, or too far from the last accepted cluster to go back to it prop.SetTrack(this, alphaStart); } } else if (finalOutInFit && lastUpdateRow != 255 && !retryAttempt) { - int32_t loopStored = -1; // Not attempted: handle like no looper + int8_t loopStored = -1; // Not attempted: handle like no looper if (!(param.rec.tpc.disableMarkAdjacent & 8)) { loopStored = StoreLoopPropagation(merger, lastSector, lastUpdateRow, iTrk, lastUpdateRow > clusters[(iWay & 1) ? (maxN - 1) : 0].row, prop.GetAlpha()); CADEBUG(printf("\t\tSTORING %d lastUpdateRow %d row %d out %d\n", iTrk, (int)lastUpdateRow, (int)clusters[(iWay & 1) ? (maxN - 1) : 0].row, lastUpdateRow > clusters[(iWay & 1) ? (maxN - 1) : 0].row)); @@ -423,14 +423,14 @@ GPUd() bool GPUTPCGMTrackParam::Fit(GPUTPCGMMerger& GPUrestrict() merger, GPUTPC return true; } -GPUdi() void GPUTPCGMTrackParam::MarkAdjacentSearch(const GPUParam& GPUrestrict() param, int32_t iWay, gputpcgmmergertypes::InterpolationErrorHit& GPUrestrict() inter) +GPUdi() void GPUTPCGMTrackParam::MarkAdjacentSearch(const GPUParam& GPUrestrict() param, int8_t iWay, gputpcgmmergertypes::InterpolationErrorHit& GPUrestrict() inter) { if (param.rec.tpc.mergerInterpolateErrors && iWay == param.rec.tpc.nWays - 2) { // Hit not passed to InterpolateReject, search adjacent clusters in the last way inter.markAdjacentSearch(); } } -GPUdii() void GPUTPCGMTrackParam::FitAddRow(const int32_t iRow, const uint8_t sector, const int32_t iTrk, const GPUTPCGMMergedTrack& GPUrestrict() track, GPUTPCGMPropagator& GPUrestrict() prop, const bool inFlyDirection, GPUTPCGMMerger& GPUrestrict() merger, GPUTPCGMMergerRebuildTmp* tmpRows, uint8_t* GPUrestrict() dEdxSubThresholdRow, const bool dodEdx, const bool doAttach, const uint8_t doInterpolate, gputpcgmmergertypes::InterpolationErrorHit& GPUrestrict() inter, const float deltaZ, const float sumInvSqrtCharge, const int32_t nAvgCharge) +GPUdii() void GPUTPCGMTrackParam::FitAddRow(const int32_t iRow, const uint8_t sector, const int32_t iTrk, const GPUTPCGMMergedTrack& GPUrestrict() track, GPUTPCGMPropagator& GPUrestrict() prop, const bool inFlyDirection, GPUTPCGMMerger& GPUrestrict() merger, GPUTPCGMMergerRebuildTmp* tmpRows, uint8_t* GPUrestrict() dEdxSubThresholdRow, const bool dodEdx, const bool doAttach, const uint8_t doInterpolate, gputpcgmmergertypes::InterpolationErrorHit& GPUrestrict() inter, const float deltaZ, const float sumInvSqrtCharge, const int16_t nAvgCharge) { if (CAMath::Abs(mP[2]) > constants::MAX_SIN_PHI || CAMath::Abs(mP[0]) > CAMath::Abs(mX) * CAMath::Tan(GPUTPCGeometry::kSectAngle() / 2.f)) { return; @@ -477,16 +477,16 @@ GPUdii() void GPUTPCGMTrackParam::HandleCrossCE(const GPUParam& GPUrestrict() pa } } -GPUdii() int32_t GPUTPCGMTrackParam::FitHit(GPUTPCGMMerger& GPUrestrict() merger, GPUTPCGMMergerRebuildTmp* tmpRows, const int32_t iTrk, const GPUTPCGMMergedTrack& GPUrestrict() track, const float xx, const float yy, const float zz, const uint8_t clusterState, const float clAlpha, const int32_t iWay, const bool inFlyDirection, float& GPUrestrict() deltaZ, float& GPUrestrict() lastUpdateX, GPUTPCGMMergedTrackHit* GPUrestrict() clusters, GPUTPCGMPropagator& GPUrestrict() prop, gputpcgmmergertypes::InterpolationErrorHit& GPUrestrict() inter, GPUdEdx& GPUrestrict() dEdx, GPUdEdx& GPUrestrict() dEdxAlt, float& GPUrestrict() sumInvSqrtCharge, int32_t& GPUrestrict() nAvgCharge, const int32_t ihit, const int32_t ihitMergeFirst, const bool allowChangeClusters, const bool refit, const bool finalFit, int32_t& GPUrestrict() nMissed, int32_t& GPUrestrict() nMissedHard, float uncorrectedY, bool retryAttempt) +GPUdii() int32_t GPUTPCGMTrackParam::FitHit(GPUTPCGMMerger& GPUrestrict() merger, GPUTPCGMMergerRebuildTmp* tmpRows, const int32_t iTrk, const GPUTPCGMMergedTrack& GPUrestrict() track, const float xx, const float yy, const float zz, const uint8_t clusterState, const float clAlpha, const int8_t iWay, const bool inFlyDirection, float& GPUrestrict() deltaZ, float& GPUrestrict() lastUpdateX, GPUTPCGMMergedTrackHit* GPUrestrict() clusters, GPUTPCGMPropagator& GPUrestrict() prop, gputpcgmmergertypes::InterpolationErrorHit& GPUrestrict() inter, GPUdEdx& GPUrestrict() dEdx, GPUdEdx& GPUrestrict() dEdxAlt, float& GPUrestrict() sumInvSqrtCharge, int16_t& GPUrestrict() nAvgCharge, const int32_t ihit, const int32_t ihitMergeFirst, const bool allowChangeClusters, const bool refit, const bool finalFit, int16_t& GPUrestrict() nMissed, int16_t& GPUrestrict() nMissedHard, float uncorrectedY, bool retryAttempt) { const GPUParam& GPUrestrict() param = merger.Param(); - const int32_t nWays = param.rec.tpc.nWays; - const int32_t wayRebuildStart = param.rec.tpc.mergerInitial3wayFit ? 2 : 0; - const int32_t wayDirection = (iWay & 1) ? -1 : 1; + const int8_t nWays = param.rec.tpc.nWays; + const int8_t wayRebuildStart = param.rec.tpc.mergerInitial3wayFit ? 2 : 0; + const int8_t wayDirection = (iWay & 1) ? -1 : 1; const bool finalOutInFit = iWay >= nWays - 2; const auto& cluster = clusters[ihit]; - int32_t retValUpd = 0, retValInt = 0; + int8_t retValUpd = 0, retValInt = 0; float threshold = 3.f + (lastUpdateX >= 0 ? (CAMath::Abs(mX - lastUpdateX) / 2) : 0.f); if (mNDF > (int32_t)param.rec.tpc.mergerNonInterpolateRejectMinNDF && (CAMath::Abs(yy - mP[0]) > threshold || CAMath::Abs(zz - mP[1]) > threshold)) { retValUpd = GPUTPCGMPropagator::updateErrorClusterRejectedDistance; @@ -641,7 +641,7 @@ GPUd() int32_t GPUTPCGMTrackParam::InterpolateReject(const GPUTPCGMMerger& GPUre } template -GPUdi() uint32_t GPUTPCGMTrackParam::ExtrapolateRows(GPUTPCGMMerger& GPUrestrict() merger, GPUTPCGMMergerRebuildTmp* tmpRows, GPUTPCGMPropagator& GPUrestrict() prop, ExtrapolationState& GPUrestrict() s, int32_t& GPUrestrict() sector, const uint8_t startRow, const int32_t up, const bool inFlyDirection, const bool refit, float& GPUrestrict() sumInvSqrtCharge, int32_t& GPUrestrict() nAvgCharge, const float deltaZ, const int32_t iTrk, const int8_t doAttach, const float maxCov, const float qPtStart) +GPUdi() uint8_t GPUTPCGMTrackParam::ExtrapolateRows(GPUTPCGMMerger& GPUrestrict() merger, GPUTPCGMMergerRebuildTmp* tmpRows, GPUTPCGMPropagator& GPUrestrict() prop, ExtrapolationState& GPUrestrict() s, int8_t& GPUrestrict() sector, const uint8_t startRow, const int8_t up, const bool inFlyDirection, const bool refit, float& GPUrestrict() sumInvSqrtCharge, int16_t& GPUrestrict() nAvgCharge, const float deltaZ, const int32_t iTrk, const int8_t doAttach, const float maxCov, const float qPtStart) { const GPUParam& GPUrestrict() param = merger.Param(); const float maxSinForUpdate = param.rec.tpc.maxSinPhiForFitUpdate; @@ -649,10 +649,10 @@ GPUdi() uint32_t GPUTPCGMTrackParam::ExtrapolateRows(GPUTPCGMMerger& GPUrestrict float &segmentStartChi2 = s.segmentStartChi2, &lastFoundX = s.lastFoundX, &lastFoundAlpha = s.lastFoundAlpha; bool& revert = s.revert; uint8_t rowGapActive = 0, rowGapTotal = 0, missingRowsTotal = 0, consecGoodRowsMissing = 0; - uint32_t iExtrapolatedRow = startRow + up; // uint8_t implies > 0! // TODO: Try to reduce some variables to int8/uint8 to save registers + uint8_t iExtrapolatedRow = startRow + up; // Wraps to 255 >= NROWS below row 0 for (; iExtrapolatedRow < GPUTPCGeometry::NROWS && (followOnly || merger.RebuildRowInRange(iTrk, iExtrapolatedRow, tmpRows)); iExtrapolatedRow += up) { bool fail = false; - for (int32_t iAttempt = 0; iAttempt < 2; iAttempt++) { + for (int8_t iAttempt = 0; iAttempt < 2; iAttempt++) { float tmpX, tmpY, tmpZ; if (prop.GetPropagatedYZ(GPUTPCGeometry::Row2X(iExtrapolatedRow), tmpY, tmpZ)) { fail = revert = true; @@ -672,7 +672,7 @@ GPUdi() uint32_t GPUTPCGMTrackParam::ExtrapolateRows(GPUTPCGMMerger& GPUrestrict fail = true; break; } - const int32_t sectorSide = sector >= (int8_t)(GPUTPCGeometry::NSECTORS / 2) ? (GPUTPCGeometry::NSECTORS / 2) : 0; + const int8_t sectorSide = sector >= (int8_t)(GPUTPCGeometry::NSECTORS / 2) ? (GPUTPCGeometry::NSECTORS / 2) : 0; if (mP[0] > 0) { if (++sector >= sectorSide + 18) { sector -= 18; @@ -739,7 +739,7 @@ GPUdi() uint32_t GPUTPCGMTrackParam::ExtrapolateRows(GPUTPCGMMerger& GPUrestrict segmentStartChi2 = mChi2; segmentRows = 0; } - int32_t retValUpd = prop.Update(yy, zz, iExtrapolatedRow, param, clusterState, true, refit, err2Y, err2Z); + int8_t retValUpd = prop.Update(yy, zz, iExtrapolatedRow, param, clusterState, true, refit, err2Y, err2Z); CADEBUG(printf("\tExtrapol. Sec %2d Row %3d Fit Alpha %8.3f , X %8.3f - Y %8.3f, Z %8.3f - QPt %7.2f (%7.2f), SP %5.2f (%5.2f), DzDs %5.2f %16s --- Cov sY %8.3f sZ %8.3f sSP %8.3f sPt %8.3f - YPt %8.3f - FErr %d\n", sector, iExtrapolatedRow, prop.GetAlpha(), mX, mP[0], mP[1], mP[4], prop.GetQPt0(), mP[2], prop.GetSinPhi0(), mP[3], "", sqrtf(CAMath::Max(0.f, mC[0])), sqrtf(CAMath::Max(0.f, mC[2])), sqrtf(CAMath::Max(0.f, mC[5])), sqrtf(CAMath::Max(0.f, mC[14])), mC[10], retValUpd)); if (retValUpd == 0 && param.rec.tpc.rebuildTrackMaxQPtDrift > 0 && CAMath::Abs(mP[4] - qPtStart) > param.rec.tpc.rebuildTrackMaxQPtDrift * CAMath::Max(1.f, CAMath::Abs(qPtStart))) { // Track changed too much, probably following something else if constexpr (!followOnly) { @@ -804,7 +804,7 @@ GPUdi() uint32_t GPUTPCGMTrackParam::ExtrapolateRows(GPUTPCGMMerger& GPUrestrict } template -GPUdii() float GPUTPCGMTrackParam::FindBestInterpolatedHit(GPUTPCGMMerger& GPUrestrict() merger, GPUTPCGMMergerRebuildTmp* tmpRows, gputpcgmmergertypes::InterpolationErrorHit& GPUrestrict() inter, const uint8_t sector, const uint8_t row, const float deltaZ, const float sumInvSqrtCharge, const int nAvgCharge, const GPUTPCGMPropagator& GPUrestrict() prop, const int32_t iTrk, bool interOnly, int8_t doAttach, bool extrapolation, C*... followCandidate) +GPUdii() float GPUTPCGMTrackParam::FindBestInterpolatedHit(GPUTPCGMMerger& GPUrestrict() merger, GPUTPCGMMergerRebuildTmp* tmpRows, gputpcgmmergertypes::InterpolationErrorHit& GPUrestrict() inter, const uint8_t sector, const uint8_t row, const float deltaZ, const float sumInvSqrtCharge, const int16_t nAvgCharge, const GPUTPCGMPropagator& GPUrestrict() prop, const int32_t iTrk, bool interOnly, int8_t doAttach, bool extrapolation, C*... followCandidate) { const GPUParam& GPUrestrict() param = merger.Param(); const GPUTPCTracker& GPUrestrict() tracker = *(merger.GetConstantMem()->tpcTrackers + sector); @@ -825,7 +825,7 @@ GPUdii() float GPUTPCGMTrackParam::FindBestInterpolatedHit(GPUTPCGMMerger& GPUre } else { candidates = merger.ClusterCandidates(iTrk, row, tmpRows); } - const int32_t nMaxCandidates = follow ? 1 : param.rec.tpc.rebuildTrackInFitClusterCandidates; + const int8_t nMaxCandidates = follow ? 1 : param.rec.tpc.rebuildTrackInFitClusterCandidates; const float zOffset = param.par.continuousTracking ? merger.GetConstantMem()->calibObjects.fastTransform->convVertexTimeToZOffset(sector, mTOffset, param.continuousMaxTimeBin) : 0; const float y0 = rowData.Grid().YMin(); const float stepY = rowData.HstepY(); @@ -873,7 +873,7 @@ GPUdii() float GPUTPCGMTrackParam::FindBestInterpolatedHit(GPUTPCGMMerger& GPUre sinPhiMoved = CAMath::Clamp(sinPhiMoved, -constants::MAX_SIN_PHI, constants::MAX_SIN_PHI); } - int32_t nCandidates = 0; + int8_t nCandidates = 0; while (nCandidates < nMaxCandidates && candidates[nCandidates].hasCluster()) { nCandidates++; } @@ -932,8 +932,8 @@ GPUdii() float GPUTPCGMTrackParam::FindBestInterpolatedHit(GPUTPCGMMerger& GPUre bool ok = !prop.RejectCluster(chi2Y * param.rec.tpc.clusterRejectChi2TolleranceY * chi2Factor, chi2Z * param.rec.tpc.clusterRejectChi2TolleranceZ * chi2Factor, clflags); const float err = (param.rec.tpc.rebuildTrackCandidateErrChi2 ? (chi2Y + chi2Z) : (dy * dy + dz * dz)) * errFactor; if (ok) { - int32_t insert = nCandidates; - for (int32_t c = 0; c < nCandidates; c++) { + int8_t insert = nCandidates; + for (int8_t c = 0; c < nCandidates; c++) { if (err < (float)candidates[c].error) { insert = c; break; @@ -941,7 +941,7 @@ GPUdii() float GPUTPCGMTrackParam::FindBestInterpolatedHit(GPUTPCGMMerger& GPUre } if (insert < nMaxCandidates) { if constexpr (!follow) { // Only one candidate in follow mode, nothing to shift - for (int32_t c = CAMath::Min(nCandidates, nMaxCandidates - 1); c > insert; c--) { + for (int8_t c = CAMath::Min(nCandidates, nMaxCandidates - 1); c > insert; c--) { candidates[c] = candidates[c - 1]; } } @@ -969,7 +969,7 @@ GPUdii() float GPUTPCGMTrackParam::FindBestInterpolatedHit(GPUTPCGMMerger& GPUre return uncorrectedY; } -GPUdni() void GPUTPCGMTrackParam::InterpolateMissingRows(GPUTPCGMMerger& GPUrestrict() merger, GPUTPCGMMergerRebuildTmp* tmpRows, gputpcgmmergertypes::InterpolationErrors& GPUrestrict() interpolation, GPUTPCGMMergedTrackHit* GPUrestrict() clusters, int32_t ihit, int32_t interpolationIndex, int32_t lastRow, const float deltaZ, const float sumInvSqrtCharge, const int32_t nAvgCharge, const GPUTPCGMPropagator& GPUrestrict() prop, const int32_t iTrk, const int8_t doAttach) +GPUdni() void GPUTPCGMTrackParam::InterpolateMissingRows(GPUTPCGMMerger& GPUrestrict() merger, GPUTPCGMMergerRebuildTmp* tmpRows, gputpcgmmergertypes::InterpolationErrors& GPUrestrict() interpolation, GPUTPCGMMergedTrackHit* GPUrestrict() clusters, int32_t ihit, int32_t interpolationIndex, int32_t lastRow, const float deltaZ, const float sumInvSqrtCharge, const int16_t nAvgCharge, const GPUTPCGMPropagator& GPUrestrict() prop, const int32_t iTrk, const int8_t doAttach) { for (; ihit >= 0; ihit--, interpolationIndex--) { while (ihit > 0 && clusters[ihit].row == clusters[ihit - 1].row && clusters[ihit].sector == clusters[ihit - 1].sector) { @@ -1035,7 +1035,7 @@ GPUdni() void GPUTPCGMTrackParam::MoveToReference(GPUTPCGMPropagator& GPUrestric if (param.rec.tpc.trackReferenceX <= 500) { GPUTPCGMTrackParam save = *this; float saveAlpha = Alpha; - for (int32_t attempt = 0; attempt < 3; attempt++) { + for (int8_t attempt = 0; attempt < 3; attempt++) { float dAngle = CAMath::Round(CAMath::ATan2(mP[0], mX) / CAMath::Deg2Rad() / 20.f) * GPUTPCGeometry::kSectAngle(); Alpha += dAngle; if (prop.PropagateToXAlpha(param.rec.tpc.trackReferenceX, Alpha, 0)) { @@ -1361,7 +1361,8 @@ GPUdii() void GPUTPCGMTrackParam::FollowExtrapolation(GPUTPCGMMerger& GPUrestric es.segmentStartChi2 = t.mChi2; es.lastFoundX = es.lastFoundAlpha = 0.f; es.revert = false; - int32_t sector = data.sector, nAvgCharge = 0; + int8_t sector = data.sector; + int16_t nAvgCharge = 0; float sumInvSqrtCharge = 0.f; // Not used by ExtrapolateRows t.ExtrapolateRows(merger, nullptr, prop, es, sector, data.row, data.outwards ? 1 : -1, (track.Leg() & 1) ^ data.outwards, true, sumInvSqrtCharge, nAvgCharge, 0.f, data.track, 1 + (track.Leg() == 0), param.rec.tpc.followExtrapolationMaxCov, t.mP[4]); } @@ -1390,14 +1391,14 @@ GPUdii() void GPUTPCGMTrackParam::PropagateLooper(const GPUTPCGMMerger& GPUrestr } } -GPUdi() void GPUTPCGMTrackParam::FindAdjacentClustersLooperFollow(const GPUTPCGMMerger& GPUrestrict() merger, GPUTPCGMPropagator& GPUrestrict() prop, int32_t sector, const int32_t iTrack, const bool up) +GPUdi() void GPUTPCGMTrackParam::FindAdjacentClustersLooperFollow(const GPUTPCGMMerger& GPUrestrict() merger, GPUTPCGMPropagator& GPUrestrict() prop, int8_t sector, const int32_t iTrack, const bool up) { float toX = mX; bool inFlyDirection = (merger.MergedTracks()[iTrack].Leg() & 1) ^ up; const GPUParam& GPUrestrict() param = merger.Param(); bool right = (mP[2] < 0) ^ up; - const int32_t sectorSide = sector >= (int32_t)(GPUTPCGeometry::NSECTORS / 2) ? (GPUTPCGeometry::NSECTORS / 2) : 0; + const int8_t sectorSide = sector >= (int8_t)(GPUTPCGeometry::NSECTORS / 2) ? (GPUTPCGeometry::NSECTORS / 2) : 0; float lrFactor = right ^ !up ? 1.f : -1.f; // clang-format off CADEBUG(printf("\nCIRCLE Track %d: Sector %d Alpha %f X %f Y %f Z %f SinPhi %f DzDs %f QPt %f - Right %d Up %d lrFactor %f\n", iTrack, sector, prop.GetAlpha(), mX, mP[0], mP[1], mP[2], mP[3], mP[4], (int32_t)right, (int32_t)up, lrFactor)); @@ -1423,7 +1424,7 @@ GPUdi() void GPUTPCGMTrackParam::FindAdjacentClustersLooperFollow(const GPUTPCGM if (!((up ? (localX >= toX) : (localX <= toX)) || (right ^ (mP[2] > 0)))) { return; } - int32_t err = prop.PropagateToXAlpha(mX + (up ? 1.f : -1.f), prop.GetAlpha(), inFlyDirection); + int8_t err = prop.PropagateToXAlpha(mX + (up ? 1.f : -1.f), prop.GetAlpha(), inFlyDirection); if (err) { CADEBUG(printf("\t\tpropagation error (%d)\n", err)); return; @@ -1452,7 +1453,7 @@ GPUdi() void GPUTPCGMTrackParam::FindAdjacentClustersLooperFollow(const GPUTPCGM } } CADEBUG(printf("\tRotating to sector %d: %f --> %f\n", sector, prop.GetAlpha(), param.Alpha(sector) + (CAMath::Pi() / 2.f) * lrFactor)); - int32_t err = prop.RotateToAlpha(param.Alpha(sector) + (CAMath::Pi() / 2.f) * lrFactor); + int8_t err = prop.RotateToAlpha(param.Alpha(sector) + (CAMath::Pi() / 2.f) * lrFactor); if (err) { CADEBUG(printf("Rotation Error %d\n", err)); return; @@ -1504,9 +1505,9 @@ GPUdi() void GPUTPCGMTrackParam::FindAdjacentClustersLooperMirror(const GPUTPCGM // printf("count %d: At X %f Y %f Z %f SinPhi %f\n", maxTries, mP[2] > 0 ? -Y : Y, mP[2] > 0 ? X : -X, Z, SinPhi); float paramX = mP[2] > 0 ? -Y : Y; - int32_t step = up ? 1 : -1; - int32_t found = 0; - for (int32_t j = iRow; j >= 0 && j < (int32_t)GPUTPCGeometry::NROWS && found < 3; j += step) { + const int8_t step = up ? 1 : -1; + int8_t found = 0; + for (int16_t j = iRow; j >= 0 && j < (int16_t)GPUTPCGeometry::NROWS && found < 3; j += step) { float rowX = mX + GPUTPCGeometry::Row2X(j) - myRowX; if (CAMath::Abs(rowX - paramX) < 1.5f) { // printf("Attempt row %d at y %f\n", j, X); diff --git a/GPU/GPUTracking/Merger/GPUTPCGMTrackParam.h b/GPU/GPUTracking/Merger/GPUTPCGMTrackParam.h index 591d2facf440a..b7f4daca98305 100644 --- a/GPU/GPUTracking/Merger/GPUTPCGMTrackParam.h +++ b/GPU/GPUTracking/Merger/GPUTPCGMTrackParam.h @@ -157,10 +157,10 @@ class GPUTPCGMTrackParam template GPUd() bool Fit(GPUTPCGMMerger& merger, GPUTPCGMMergerRebuildTmp* tmpRows, int32_t iTrk, int32_t& N, int32_t& NTolerated, float& Alpha, GPUTPCGMMergedTrack& track); GPUd() void DodEdx(GPUdEdx& dEdx, GPUdEdx& dEdxAlt, GPUTPCGMMerger& merger, bool finalFit, int ihit, int ihitMergeFirst, int wayDirection, const GPUTPCGMMergedTrackHit* clusters, uint8_t clusterState, float zz, uint8_t dEdxSubThresholdRow GPUCA_DEBUG_STREAMER_CHECK(, int32_t iTrk)); - GPUd() int32_t FitHit(GPUTPCGMMerger& merger, GPUTPCGMMergerRebuildTmp* tmpRows, const int32_t iTrk, const GPUTPCGMMergedTrack& track, const float xx, const float yy, const float zz, const uint8_t clusterState, const float clAlpha, const int32_t iWay, const bool inFlyDirection, float& deltaZ, float& lastUpdateX, GPUTPCGMMergedTrackHit* clusters, GPUTPCGMPropagator& prop, gputpcgmmergertypes::InterpolationErrorHit& inter, GPUdEdx& dEdx, GPUdEdx& dEdxAlt, float& sumInvSqrtCharge, int32_t& nAvgCharge, const int32_t ihit, const int32_t ihitMergeFirst, const bool allowChangeClusters, const bool refit, const bool finalFit, int32_t& nMissed, int32_t& nMissedHard, float uncorrectedY, bool retryAttempt); - GPUd() void FitAddRow(const int32_t iRow, const uint8_t sector, const int32_t iTrk, const GPUTPCGMMergedTrack& track, GPUTPCGMPropagator& prop, const bool inFlyDirection, GPUTPCGMMerger& merger, GPUTPCGMMergerRebuildTmp* tmpRows, uint8_t* dEdxSubThresholdRow, const bool dodEdx, const bool doAttach, const uint8_t doInterpolate, gputpcgmmergertypes::InterpolationErrorHit& inter, const float deltaZ, const float sumInvSqrtCharge, const int32_t nAvgCharge); + GPUd() int32_t FitHit(GPUTPCGMMerger& merger, GPUTPCGMMergerRebuildTmp* tmpRows, const int32_t iTrk, const GPUTPCGMMergedTrack& track, const float xx, const float yy, const float zz, const uint8_t clusterState, const float clAlpha, const int8_t iWay, const bool inFlyDirection, float& deltaZ, float& lastUpdateX, GPUTPCGMMergedTrackHit* clusters, GPUTPCGMPropagator& prop, gputpcgmmergertypes::InterpolationErrorHit& inter, GPUdEdx& dEdx, GPUdEdx& dEdxAlt, float& sumInvSqrtCharge, int16_t& nAvgCharge, const int32_t ihit, const int32_t ihitMergeFirst, const bool allowChangeClusters, const bool refit, const bool finalFit, int16_t& nMissed, int16_t& nMissedHard, float uncorrectedY, bool retryAttempt); + GPUd() void FitAddRow(const int32_t iRow, const uint8_t sector, const int32_t iTrk, const GPUTPCGMMergedTrack& track, GPUTPCGMPropagator& prop, const bool inFlyDirection, GPUTPCGMMerger& merger, GPUTPCGMMergerRebuildTmp* tmpRows, uint8_t* dEdxSubThresholdRow, const bool dodEdx, const bool doAttach, const uint8_t doInterpolate, gputpcgmmergertypes::InterpolationErrorHit& inter, const float deltaZ, const float sumInvSqrtCharge, const int16_t nAvgCharge); GPUd() void HandleCrossCE(const GPUParam& param, const uint8_t sector, const uint8_t& lastSector); - GPUd() static void MarkAdjacentSearch(const GPUParam& param, int32_t iWay, gputpcgmmergertypes::InterpolationErrorHit& inter); + GPUd() static void MarkAdjacentSearch(const GPUParam& param, int8_t iWay, gputpcgmmergertypes::InterpolationErrorHit& inter); template GPUd() static void RefitTrack(GPUTPCGMMergedTrack& track, int32_t iTrk, GPUTPCGMMerger& merger); GPUd() void MoveToReference(GPUTPCGMPropagator& prop, const GPUParam& param, float& alpha); @@ -168,17 +168,17 @@ class GPUTPCGMTrackParam GPUd() int32_t MergeDoubleRowClusters(int32_t& ihit, int32_t wayDirection, GPUTPCGMMergedTrackHit* clusters, const GPUTPCGMMerger& merger, GPUTPCGMPropagator& prop, float& xx, float& yy, float& zz, int32_t maxN, float clAlpha, uint8_t& clusterState, const bool markReject); GPUd() int32_t InterpolateReject(const GPUTPCGMMerger& merger, const GPUTPCGMPropagator& prop, float posY, float posZ, int16_t clusterState, gputpcgmmergertypes::InterpolationErrorHit* inter, float err2Y, float err2Z, float deltaZ, uint8_t sector, uint8_t row, int32_t iTrk, int8_t doAttach); template - GPUd() float FindBestInterpolatedHit(GPUTPCGMMerger& merger, GPUTPCGMMergerRebuildTmp* tmpRows, gputpcgmmergertypes::InterpolationErrorHit& inter, const uint8_t sector, const uint8_t row, const float deltaZ, const float sumInvSqrtCharge, const int nAvgCharge, const GPUTPCGMPropagator& prop, const int32_t iTrk, bool interOnly, int8_t doAttach, bool extrapolation = false, C*... followCandidate); + GPUd() float FindBestInterpolatedHit(GPUTPCGMMerger& merger, GPUTPCGMMergerRebuildTmp* tmpRows, gputpcgmmergertypes::InterpolationErrorHit& inter, const uint8_t sector, const uint8_t row, const float deltaZ, const float sumInvSqrtCharge, const int16_t nAvgCharge, const GPUTPCGMPropagator& prop, const int32_t iTrk, bool interOnly, int8_t doAttach, bool extrapolation = false, C*... followCandidate); struct ExtrapolationState; template - GPUd() uint32_t ExtrapolateRows(GPUTPCGMMerger& merger, GPUTPCGMMergerRebuildTmp* tmpRows, GPUTPCGMPropagator& prop, ExtrapolationState& s, int32_t& sector, const uint8_t startRow, const int32_t up, const bool inFlyDirection, const bool refit, float& sumInvSqrtCharge, int32_t& nAvgCharge, const float deltaZ, const int32_t iTrk, const int8_t doAttach, const float maxCov, const float qPtStart); - GPUd() void InterpolateMissingRows(GPUTPCGMMerger& merger, GPUTPCGMMergerRebuildTmp* tmpRows, gputpcgmmergertypes::InterpolationErrors& interpolation, GPUTPCGMMergedTrackHit* clusters, int32_t ihit, int32_t interpolationIndex, int32_t lastRow, const float deltaZ, const float sumInvSqrtCharge, const int32_t nAvgCharge, const GPUTPCGMPropagator& prop, const int32_t iTrk, const int8_t doAttach); + GPUd() uint8_t ExtrapolateRows(GPUTPCGMMerger& merger, GPUTPCGMMergerRebuildTmp* tmpRows, GPUTPCGMPropagator& prop, ExtrapolationState& s, int8_t& sector, const uint8_t startRow, const int8_t up, const bool inFlyDirection, const bool refit, float& sumInvSqrtCharge, int16_t& nAvgCharge, const float deltaZ, const int32_t iTrk, const int8_t doAttach, const float maxCov, const float qPtStart); + GPUd() void InterpolateMissingRows(GPUTPCGMMerger& merger, GPUTPCGMMergerRebuildTmp* tmpRows, gputpcgmmergertypes::InterpolationErrors& interpolation, GPUTPCGMMergedTrackHit* clusters, int32_t ihit, int32_t interpolationIndex, int32_t lastRow, const float deltaZ, const float sumInvSqrtCharge, const int16_t nAvgCharge, const GPUTPCGMPropagator& prop, const int32_t iTrk, const int8_t doAttach); GPUd() float FindAdjacentClusters(const GPUTPCGMMerger& GPUrestrict() merger, int32_t sector, int32_t iRow, int32_t iTrack, bool goodLeg, GPUTPCGMPropagator& prop); // Returns uncorrectedY for later use GPUd() float FindAdjacentClusters(const GPUTPCGMMerger& GPUrestrict() merger, int32_t sector, int32_t iRow, int32_t iTrack, bool goodLeg, float Y, float Z); GPUd() void FindAdjacentClustersUncorrectedPos(const GPUTPCGMMerger& GPUrestrict() merger, int32_t sector, int32_t iRow, int32_t iTrack, bool goodLeg, float uncorrectedY, float uncorrectedZ, float Z, float err2Y, float err2Z); GPUd() void FindAdjacentClustersLooperMirror(const GPUTPCGMMerger& GPUrestrict() merger, int32_t sector, int32_t iRow, const int32_t iTrack, const bool up, const GPUTPCGMPropagator& prop); - GPUd() void FindAdjacentClustersLooperFollow(const GPUTPCGMMerger& GPUrestrict() merger, GPUTPCGMPropagator& prop, int32_t sector, const int32_t iTrack, const bool up); + GPUd() void FindAdjacentClustersLooperFollow(const GPUTPCGMMerger& GPUrestrict() merger, GPUTPCGMPropagator& prop, int8_t sector, const int32_t iTrack, const bool up); GPUd() int32_t StoreLoopPropagation(const GPUTPCGMMerger& GPUrestrict() merger, int32_t sector, int32_t iRow, int32_t iTrack, bool outwards, float alpha); GPUd() void StoreFollowExtrapolation(const GPUTPCGMMerger& GPUrestrict() merger, int32_t sector, int32_t iRow, int32_t iTrack, bool outwards, float alpha); GPUd() static void FollowExtrapolation(GPUTPCGMMerger& merger, int32_t idx); From 57d1828ec3b309e06c34fdff74711d2656b32aad Mon Sep 17 00:00:00 2001 From: David Rohr Date: Fri, 27 Nov 2026 12:02:07 +0100 Subject: [PATCH 04/12] GPU: Several minor fixes and improvements by Claude --- GPU/GPUTracking/Base/GPUReconstruction.cxx | 2 +- .../Definitions/GPUSettingsList.template | 6 +++--- .../GPUSettingsListStandalone.template | 2 +- .../Definitions/clusterFinderDefs.h | 1 + GPU/GPUTracking/Merger/GPUTPCGMMerger.cxx | 2 +- GPU/GPUTracking/Merger/GPUTPCGMTrackParam.cxx | 21 ++++++++++--------- GPU/GPUTracking/Merger/GPUTPCGMTrackParam.h | 4 ++-- .../TPCClusterFinder/CfChargePos.h | 4 +--- 8 files changed, 21 insertions(+), 21 deletions(-) diff --git a/GPU/GPUTracking/Base/GPUReconstruction.cxx b/GPU/GPUTracking/Base/GPUReconstruction.cxx index 4a37b7fde54d5..51233a29f6fbe 100644 --- a/GPU/GPUTracking/Base/GPUReconstruction.cxx +++ b/GPU/GPUTracking/Base/GPUReconstruction.cxx @@ -269,7 +269,7 @@ int32_t GPUReconstruction::InitPhaseBeforeDevice() detMode = true; #endif if (GetProcessingSettings().deterministicGPUReconstruction == -1) { - mProcessingSettings->deterministicGPUReconstruction = detMode ? 1 : (GetProcessingSettings().debugLevel >= 6); + mProcessingSettings->deterministicGPUReconstruction = detMode ? 1 : (GetProcessingSettings().debugLevel >= 6 || GetProcessingSettings().debugDumpFinal); } if (GetProcessingSettings().deterministicGPUReconstruction) { if (!detMode) { diff --git a/GPU/GPUTracking/Definitions/GPUSettingsList.template b/GPU/GPUTracking/Definitions/GPUSettingsList.template index 6e0927c017b9f..fe2538701a121 100644 --- a/GPU/GPUTracking/Definitions/GPUSettingsList.template +++ b/GPU/GPUTracking/Definitions/GPUSettingsList.template @@ -104,7 +104,7 @@ AddOptionRTC(trackFitMinHitsMaxQPtIncrease, float, 0.2f, "", 0, "For the QPt-dep AddOptionRTC(rebuildTrackMaxSharedFraction, float, 0.1f, "", 0, "Max fraction of shared clusters for rebuilt tracks") AddOptionRTC(rebuildTrackMaxNonIntCov, float, 4.f, "", 0, "Max Err2 allowed for non-interpolated cluster attachment during rebuild") AddOptionRTC(followExtrapolationMaxCov, float, 4.f, "", 0, "Max Err2 for following (not during rebuild) the track beyond its ends for adjacent clusters") -AddOptionRTC(followExtrapolationChi2Factor, float, 0.f, "", 0, "> 1: follow track once more after rebuild, sets factor by which chi2 window is reduced for marking adjcacent clusters") +AddOptionRTC(followExtrapolationChi2Factor, float, 0.f, "", 0, "> 0: follow track once more after extrapolated rebuild to mark adjacent clusters, the chi2 of the cluster candidates is scaled by this factor (> 1 reduces the chi2 window)") AddOptionRTC(rebuildErrorWeightFactor, float, 5.f, "", 0, "Factor for the error (distance^2) of a cluster candidate in its hit weight 1 / (1 + factor * error) during rebuild") AddOptionRTC(maxSinPhiForFitUpdate, float, 0.9396926f, "", 0, "Max abs(sinPhi) of the track to update it with a cluster in the track fit)") // default sin(70 deg = 0.9396926 AddOptionRTC(rebuildTrackMaxQPtDrift, float, 0.5f, "", 0, "Stop the track extrapolation during rebuild when QPt changed by more than this fraction of max(1, abs(QPt)) compared to before the extrapolation (0 = disabled)") @@ -357,7 +357,7 @@ BeginSubConfig(GPUSettingsProcessingDebug, debug, configStandalone.proc, "DEBUG" AddOption(memoryScalingFuzz, uint64_t, 0, "", 0, "Fuzz the memoryScalingFactor (0 disable, 1 enable, >1 set seed", def(1)) AddOption(mergerMCLabels, bool, false, "", 0, "Create MC labels for merged tracks before refit for debugging") AddOption(mergerDumpTrackNCl, bool, false, "", 0, "Dump file with nCl per merged track fit") -AddOption(tpcMergerFitOnCPUSingleThread, bool, false, "", 0, "Run the TPC merger kernels from the track fit on with 1 CPU thread, for ordered GPUCA_CADEBUG output (CPU only)") +AddOption(tpcMergerFitOnCPUSingleThread, bool, false, "", 0, "Run the TPC merger kernels starting from the track fit with 1 CPU thread, for ordered GPUCA_CADEBUG output (CPU only)") AddHelp("help", 0) EndConfig() @@ -388,7 +388,7 @@ AddOption(debugCSV, std::string, "", "", 0, "CSV filename to append the benchmar AddOption(debugMarkdown, bool, false, "", 0, "Print the results of standalone benchmarks in markdown format") AddOption(serializeGPU, int8_t, 0, "", 0, "Synchronize after each kernel call (bit 1) and DMA transfer (bit 2) and identify failures") AddOption(recoTaskTiming, bool, 0, "", 0, "Perform summary timing after whole reconstruction tasks") -AddOption(deterministicGPUReconstruction, int32_t, -1, "", 0, "Make CPU and GPU debug output comparable (sort / skip concurrent parts), -1 = automatic if debugLevel >= 6 or deterministic compile flag set", def(1)) +AddOption(deterministicGPUReconstruction, int32_t, -1, "", 0, "Make CPU and GPU debug output comparable (sort / skip concurrent parts), -1 = automatic if debugLevel >= 6, debugDumpFinal, or deterministic compile flag set", def(1)) AddOption(showOutputStat, bool, false, "", 0, "Print some track output statistics") AddOption(runCompressionStatistics, int8_t, 0, "compressionStat", 0, "Run statistics and verification for cluster compression, 2 to dump clusters and entropy-reduced clusters to CSV", def(1)) AddOption(resetTimers, int8_t, 1, "", 0, "Reset timers every event") diff --git a/GPU/GPUTracking/Definitions/GPUSettingsListStandalone.template b/GPU/GPUTracking/Definitions/GPUSettingsListStandalone.template index e8d5056bf38be..30317b3a2a251 100644 --- a/GPU/GPUTracking/Definitions/GPUSettingsListStandalone.template +++ b/GPU/GPUTracking/Definitions/GPUSettingsListStandalone.template @@ -76,7 +76,7 @@ AddOption(overrideMaxTimebin, bool, false, "", 0, "Override max time bin setting AddOption(encodeZS, int32_t, -1, "", 0, "Zero-Suppress TPC data", def(1)) AddOption(zsFilter, int32_t, -1, "", 0, "Apply Zero-Suppression when loading digits and remove those below threshold", def(1)) AddOption(zsVersion, int32_t, 2, "", 0, "ZS Version: 1 = 10-bit ADC row based, 2 = 12-bit ADC row based, 3 = improved link based, 4 = dense link based") -AddOption(dumpEvents, uint8_t, 0, "", 0, "Dump events (1 = input after transformation such as encodeZS, 2 = input of the asynchronous phase with --syncAsync)") +AddOption(dumpEvents, uint8_t, 0, "", 0, "Dump events (1 = input after transformation such as encodeZS, 2 = input of the asynchronous phase with --syncAsync)", def(1)) AddOption(stripDumpedEvents, bool, false, "", 0, "Remove redundant inputs (e.g. digits and ZS) before dumping") AddOption(printSettings, int32_t, 0, "", 0, "Print all settings", def(1)) AddOption(testSyncAsync, bool, false, "syncAsync", 0, "Test first synchronous and then asynchronous processing") diff --git a/GPU/GPUTracking/Definitions/clusterFinderDefs.h b/GPU/GPUTracking/Definitions/clusterFinderDefs.h index 0b0028b0cc77b..e43eedc96f552 100644 --- a/GPU/GPUTracking/Definitions/clusterFinderDefs.h +++ b/GPU/GPUTracking/Definitions/clusterFinderDefs.h @@ -54,6 +54,7 @@ static GPUglobalconstexpr() uint32_t SCRATCH_PAD_NOISE_N = 16; // rows are always aligned along cache lines. Likewise for TPC_CLUSTERER_ROW_PAD_CAPACITY. static GPUglobalconstexpr() int32_t GPUCF_PADDING_PAD = 8; static GPUglobalconstexpr() int32_t GPUCF_PADDING_TIME = 4; +static GPUglobalconstexpr() int32_t INVALID_TIME_BIN = -GPUCF_PADDING_TIME - 1; // Largest possible number of pads in a TPC row static GPUglobalconstexpr() int32_t TPC_CLUSTERER_ROW_PAD_CAPACITY = 144; diff --git a/GPU/GPUTracking/Merger/GPUTPCGMMerger.cxx b/GPU/GPUTracking/Merger/GPUTPCGMMerger.cxx index 94daa1bffe3a5..e09ea1a30b87b 100644 --- a/GPU/GPUTracking/Merger/GPUTPCGMMerger.cxx +++ b/GPU/GPUTracking/Merger/GPUTPCGMMerger.cxx @@ -552,7 +552,7 @@ void GPUTPCGMMerger::SetMaxData(const GPUTrackingInOutPointers& io) } else { mNMaxTracks = mRec->MemoryScalers()->NTPCMergedTracks(mNTotalSectorTracks); } - mNMaxLoopExtrData = !(Param().rec.tpc.disableMarkAdjacent & 4) && !(Param().rec.tpc.disableMarkAdjacent & 8) + mNMaxLoopExtrData = !(Param().rec.tpc.disableMarkAdjacent & 8) || FollowExtrapolationEnabled(Param()) ? mRec->MemoryScalers()->NTPCLoopExtrData(mNMaxTracks, FollowExtrapolationEnabled(Param())) : 0; if (io.clustersNative) { diff --git a/GPU/GPUTracking/Merger/GPUTPCGMTrackParam.cxx b/GPU/GPUTracking/Merger/GPUTPCGMTrackParam.cxx index 8e31191d36ba2..2c8d89bcd9750 100644 --- a/GPU/GPUTracking/Merger/GPUTPCGMTrackParam.cxx +++ b/GPU/GPUTracking/Merger/GPUTPCGMTrackParam.cxx @@ -136,6 +136,7 @@ GPUd() bool GPUTPCGMTrackParam::Fit(GPUTPCGMMerger& GPUrestrict() merger, GPUTPC float lastUpdateX = -1; const bool inFlyDirection = iWay & 1; const int8_t wayDirection = (iWay & 1) ? -1 : 1; + const bool searchSkippedHits = param.rec.tpc.rebuildTrackInFit && iWay == wayRebuildStart + 1 && (param.rec.tpc.rebuildTrackMaxNonIntCov > 0 ? !(param.rec.tpc.disableRebuildAttachment & 4) : adjacentInRebuild); // Search at the interpolated position for hits the fit skips or stops at. With maxNonIntCov 0 no one-sided candidates, only the adjacent search if (param.rec.tpc.mergerInterpolateErrors && iWay == nWays - 2) { ihitStartInterpolateReject = ihitStart; @@ -225,7 +226,7 @@ GPUd() bool GPUTPCGMTrackParam::Fit(GPUTPCGMMerger& GPUrestrict() merger, GPUTPC nMissedHard++; NTolerated++; MarkAdjacentSearch(param, iWay, inter); - if (param.rec.tpc.rebuildTrackInFit && iWay == wayRebuildStart + 1 && (param.rec.tpc.rebuildTrackMaxNonIntCov > 0 ? !(param.rec.tpc.disableRebuildAttachment & 4) : adjacentInRebuild)) { // With maxNonIntCov 0 no one-sided candidates, only the adjacent search at the interpolated position + if (searchSkippedHits) { FindBestInterpolatedHit(merger, tmpRows, inter, cluster.sector, cluster.row, deltaZ, sumInvSqrtCharge, nAvgCharge, prop, iTrk, true, adjacentInRebuild && !(param.rec.tpc.disableMarkAdjacent & 1) ? adjacentLeg : 0); } continue; @@ -235,7 +236,7 @@ GPUd() bool GPUTPCGMTrackParam::Fit(GPUTPCGMMerger& GPUrestrict() merger, GPUTPC CADEBUG(printf("\t%21sPropaga Alpha %8.3f , X %8.3f - Y %8.3f, Z %8.3f - QPt %7.2f (%7.2f), SP %5.2f (%5.2f) --- Res %8.3f %8.3f --- Cov sY %8.3f sZ %8.3f sSP %8.3f sPt %8.3f - YPt %8.3f - PErr %d\n", "", prop.GetAlpha(), mX, mP[0], mP[1], mP[4], prop.GetQPt0(), mP[2], prop.GetSinPhi0(), mP[0] - yy, mP[1] - zz, sqrtf(CAMath::Max(0.f, mC[0])), sqrtf(CAMath::Max(0.f, mC[2])), sqrtf(CAMath::Max(0.f, mC[5])), sqrtf(CAMath::Max(0.f, mC[14])), mC[10], retValProp)); // clang-format on if (mNDF >= 0 && (mC[0] > param.rec.tpc.trackFitCovLimit || mC[2] > param.rec.tpc.trackFitCovLimit)) { - if (param.rec.tpc.rebuildTrackInFit && iWay == wayRebuildStart + 1 && (param.rec.tpc.rebuildTrackMaxNonIntCov > 0 ? !(param.rec.tpc.disableRebuildAttachment & 4) : adjacentInRebuild)) { // With maxNonIntCov 0 no one-sided candidates, only the adjacent search at the interpolated position + if (searchSkippedHits) { InterpolateMissingRows(merger, tmpRows, interpolation, clusters, ihit, interpolationIndex, cluster.row, deltaZ, sumInvSqrtCharge, nAvgCharge, prop, iTrk, adjacentInRebuild && !(param.rec.tpc.disableMarkAdjacent & 1) ? adjacentLeg : 0); } MarkAdjacentSearch(param, iWay, inter); @@ -327,7 +328,7 @@ GPUd() bool GPUTPCGMTrackParam::Fit(GPUTPCGMMerger& GPUrestrict() merger, GPUTPC } } } else if (retValHit == 1) { - if (param.rec.tpc.rebuildTrackInFit && iWay == wayRebuildStart + 1 && (param.rec.tpc.rebuildTrackMaxNonIntCov > 0 ? !(param.rec.tpc.disableRebuildAttachment & 4) : adjacentInRebuild)) { // With maxNonIntCov 0 no one-sided candidates, only the adjacent search at the interpolated position + if (searchSkippedHits) { InterpolateMissingRows(merger, tmpRows, interpolation, clusters, ihit + wayDirection, interpolationIndex + wayDirection, cluster.row, deltaZ, sumInvSqrtCharge, nAvgCharge, prop, iTrk, adjacentInRebuild && !(param.rec.tpc.disableMarkAdjacent & 1) ? adjacentLeg : 0); } fitBroken = true; @@ -377,7 +378,7 @@ GPUd() bool GPUTPCGMTrackParam::Fit(GPUTPCGMMerger& GPUrestrict() merger, GPUTPC CADEBUG(printf("\t\tSTORING %d lastUpdateRow %d row %d out %d\n", iTrk, (int)lastUpdateRow, (int)clusters[(iWay & 1) ? (maxN - 1) : 0].row, lastUpdateRow > clusters[(iWay & 1) ? (maxN - 1) : 0].row)); } if (loopStored == -1 && GPUTPCGMMerger::FollowExtrapolationEnabled(param) && !fitBroken && CAMath::Abs(mP[2]) < maxSinForUpdate && mNDF > (int32_t)param.rec.tpc.rebuildTrackNonIntMinNDF && (!GPUTPCGMMerger::FollowExtrapolationAfterRebuild(param) || (track.Leg() == 0 && CAMath::Abs(GetQPt() * param.qptB5Scaler) <= param.rec.tpc.rejectQPtB5))) { - StoreFollowExtrapolation(merger, lastSector, lastPropagateRow, iTrk, (clusters[0].row < clusters[maxN - 1].row) ^ (iWay & 1), prop.GetAlpha()); // Follow the track beyond its end for adjacent clusters (same conditions as for the extrapolation), in the 5-way fit only to protect clusters, i.e. for good legs of tracks not rejected by rejectQPtB5 + StoreFollowExtrapolation(merger, lastSector, lastPropagateRow, iTrk, (clusters[0].row < clusters[maxN - 1].row) ^ (iWay & 1), inFlyDirection, prop.GetAlpha()); // Follow the track beyond its end for adjacent clusters (same conditions as for the extrapolation), in the 5-way fit only to protect clusters, i.e. for good legs of tracks not rejected by rejectQPtB5 } } @@ -793,9 +794,9 @@ GPUdi() uint8_t GPUTPCGMTrackParam::ExtrapolateRows(GPUTPCGMMerger& GPUrestrict( if (iExtrapolatedRow >= GPUTPCGeometry::NROWS && consecGoodRows >= param.rec.tpc.rebuildTrackExtrMinConsecGoodRowsEdge && (param.rec.tpc.rebuildTrackExtrMaxAvgChi2 <= 0 || mChi2 - segmentStartChi2 <= param.rec.tpc.rebuildTrackExtrMaxAvgChi2 * segmentRows)) { // Reached the inner / outer end of the TPC, a shorter last segment is sufficient lastGoodRow = lastFoundRow; } - if (lastGoodRow != lastExtrapolateRow) { - for (int32_t iRow = lastGoodRow + up; iRow != lastExtrapolateRow + up; iRow += up) { - if constexpr (!followOnly) { + if constexpr (!followOnly) { + if (lastGoodRow != lastExtrapolateRow) { + for (int32_t iRow = lastGoodRow + up; iRow != lastExtrapolateRow + up; iRow += up) { merger.TrackRebuildHelperRow(iTrk, iRow, tmpRows).setBest(GPUTPCGMMerger::trackRebuildHelperRow::bestRowRemoved); } } @@ -1319,7 +1320,7 @@ GPUdic(0, 1) int32_t GPUTPCGMTrackParam::StoreLoopPropagation(const GPUTPCGMMerg return 1; } -GPUd() void GPUTPCGMTrackParam::StoreFollowExtrapolation(const GPUTPCGMMerger& GPUrestrict() merger, int32_t sector, int32_t iRow, int32_t iTrack, bool outwards, float alpha) +GPUd() void GPUTPCGMTrackParam::StoreFollowExtrapolation(const GPUTPCGMMerger& GPUrestrict() merger, int32_t sector, int32_t iRow, int32_t iTrack, bool outwards, bool inFlyDirection, float alpha) { const uint32_t n = CAMath::AtomicAdd(&merger.Memory()->nFollowExtrapolationData, 1u); if (n >= merger.NMaxLoopExtrData()) { @@ -1333,7 +1334,7 @@ GPUd() void GPUTPCGMTrackParam::StoreFollowExtrapolation(const GPUTPCGMMerger& G data.alpha = alpha; data.sector = sector; data.row = iRow; - data.outwards = outwards; + data.outwards = (uint8_t)outwards | ((uint8_t)inFlyDirection << 1); } GPUdii() void GPUTPCGMTrackParam::FollowExtrapolation(GPUTPCGMMerger& GPUrestrict() merger, int32_t idx) @@ -1364,7 +1365,7 @@ GPUdii() void GPUTPCGMTrackParam::FollowExtrapolation(GPUTPCGMMerger& GPUrestric int8_t sector = data.sector; int16_t nAvgCharge = 0; float sumInvSqrtCharge = 0.f; // Not used by ExtrapolateRows - t.ExtrapolateRows(merger, nullptr, prop, es, sector, data.row, data.outwards ? 1 : -1, (track.Leg() & 1) ^ data.outwards, true, sumInvSqrtCharge, nAvgCharge, 0.f, data.track, 1 + (track.Leg() == 0), param.rec.tpc.followExtrapolationMaxCov, t.mP[4]); + t.ExtrapolateRows(merger, nullptr, prop, es, sector, data.row, (data.outwards & 1) ? 1 : -1, data.outwards & 2, true, sumInvSqrtCharge, nAvgCharge, 0.f, data.track, 1 + (track.Leg() == 0), param.rec.tpc.followExtrapolationMaxCov, t.mP[4]); } GPUdii() void GPUTPCGMTrackParam::PropagateLooper(const GPUTPCGMMerger& GPUrestrict() merger, int32_t loopIdx) diff --git a/GPU/GPUTracking/Merger/GPUTPCGMTrackParam.h b/GPU/GPUTracking/Merger/GPUTPCGMTrackParam.h index b7f4daca98305..8deee9dea94db 100644 --- a/GPU/GPUTracking/Merger/GPUTPCGMTrackParam.h +++ b/GPU/GPUTracking/Merger/GPUTPCGMTrackParam.h @@ -180,7 +180,7 @@ class GPUTPCGMTrackParam GPUd() void FindAdjacentClustersLooperMirror(const GPUTPCGMMerger& GPUrestrict() merger, int32_t sector, int32_t iRow, const int32_t iTrack, const bool up, const GPUTPCGMPropagator& prop); GPUd() void FindAdjacentClustersLooperFollow(const GPUTPCGMMerger& GPUrestrict() merger, GPUTPCGMPropagator& prop, int8_t sector, const int32_t iTrack, const bool up); GPUd() int32_t StoreLoopPropagation(const GPUTPCGMMerger& GPUrestrict() merger, int32_t sector, int32_t iRow, int32_t iTrack, bool outwards, float alpha); - GPUd() void StoreFollowExtrapolation(const GPUTPCGMMerger& GPUrestrict() merger, int32_t sector, int32_t iRow, int32_t iTrack, bool outwards, float alpha); + GPUd() void StoreFollowExtrapolation(const GPUTPCGMMerger& GPUrestrict() merger, int32_t sector, int32_t iRow, int32_t iTrack, bool outwards, bool inFlyDirection, float alpha); GPUd() static void FollowExtrapolation(GPUTPCGMMerger& merger, int32_t idx); GPUd() void StoreOuter(gputpcgmmergertypes::GPUTPCOuterParam* outerParam, float alpha); GPUd() static void PropagateLooper(const GPUTPCGMMerger& merger, int32_t loopIdx); @@ -255,7 +255,7 @@ struct GPUTPCGMLoopAndExtData { // Track end for FollowLoopers (stored from the float alpha; uint8_t sector; uint8_t row; - uint8_t outwards; + uint8_t outwards; // FollowExtrapolation entries: bit 1 = inFlyDirection }; GPUdi() void GPUTPCGMTrackParam::ResetCovariance() diff --git a/GPU/GPUTracking/TPCClusterFinder/CfChargePos.h b/GPU/GPUTracking/TPCClusterFinder/CfChargePos.h index f7b02d3e421ca..57e32e246cbf0 100644 --- a/GPU/GPUTracking/TPCClusterFinder/CfChargePos.h +++ b/GPU/GPUTracking/TPCClusterFinder/CfChargePos.h @@ -22,8 +22,6 @@ namespace o2::gpu { -#define INVALID_TIME_BIN (-o2::gpu::tpccf::GPUCF_PADDING_TIME - 1) - struct CfChargePos { tpccf::GlobalPad gpad; tpccf::TPCFragmentTime timePadded; @@ -61,7 +59,7 @@ struct CfChargePos { } }; -inline GPUglobalconstexpr() CfChargePos INVALID_CHARGE_POS{255, 255, INVALID_TIME_BIN}; +inline GPUglobalconstexpr() CfChargePos INVALID_CHARGE_POS{255, 255, tpccf::INVALID_TIME_BIN}; } // namespace o2::gpu From 0e43c743aceb74f52e38e7cd6e642509274d9895 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Fri, 27 Nov 2026 12:43:21 +0100 Subject: [PATCH 05/12] GPU TPC: Reduce Collect kernel stack size --- .../Definitions/GPUDefParametersConstants.h | 2 +- GPU/GPUTracking/Merger/GPUTPCGMMerger.cxx | 37 ++++++------------- GPU/GPUTracking/Merger/GPUTPCGMMerger.h | 1 + 3 files changed, 13 insertions(+), 27 deletions(-) diff --git a/GPU/GPUTracking/Definitions/GPUDefParametersConstants.h b/GPU/GPUTracking/Definitions/GPUDefParametersConstants.h index f66c250d213e1..55cfdd28a35fe 100644 --- a/GPU/GPUTracking/Definitions/GPUDefParametersConstants.h +++ b/GPU/GPUTracking/Definitions/GPUDefParametersConstants.h @@ -43,7 +43,7 @@ static GPUglobalconstexpr() size_t GPU_MEM_MAX_TPC_CLUSTERS = 1024 * 102 static GPUglobalconstexpr() size_t GPU_MEM_MAX_TRD_TRACKLETS = 128 * 1024ull; // Maximum number of TRD tracklets static GPUglobalconstexpr() size_t GPU_DEFAULT_MEMORY_SIZE = 6 * 1024 * 1024 * 1024ull; // Size of memory allocated on Device static GPUglobalconstexpr() size_t GPU_DEFAULT_HOST_MEMORY_SIZE = 1 * 1024 * 1024 * 1024ull; // Size of memory allocated on Host -static GPUglobalconstexpr() size_t GPU_STACK_SIZE = 24 * 1024ull; // Stack size per GPU thread +static GPUglobalconstexpr() size_t GPU_STACK_SIZE = 14 * 1024ull; // Stack size per GPU thread static GPUglobalconstexpr() size_t GPU_HEAP_SIZE = 16 * 1025 * 1024ull; // Stack size per GPU thread } // namespace o2::gpu::constants diff --git a/GPU/GPUTracking/Merger/GPUTPCGMMerger.cxx b/GPU/GPUTracking/Merger/GPUTPCGMMerger.cxx index e09ea1a30b87b..329f91b0880d1 100644 --- a/GPU/GPUTracking/Merger/GPUTPCGMMerger.cxx +++ b/GPU/GPUTracking/Merger/GPUTPCGMMerger.cxx @@ -1535,17 +1535,14 @@ namespace o2::gpu::internal namespace // anonymous { struct GPUTPCGMMerger_CompareClusterIds { - const GPUTPCGMMerger::trackCluster* const mCmp; const bool revert; - GPUd() GPUTPCGMMerger_CompareClusterIds(const GPUTPCGMMerger::trackCluster* cmp, bool r) : mCmp(cmp), revert(r) {} - GPUd() bool operator()(const int16_t aa, const int16_t bb) + GPUd() GPUTPCGMMerger_CompareClusterIds(bool r) : revert(r) {} + GPUd() bool operator()(const GPUTPCGMMerger::trackCluster& a, const GPUTPCGMMerger::trackCluster& b) const { - const GPUTPCGMMerger::trackCluster& a = mCmp[aa]; - const GPUTPCGMMerger::trackCluster& b = mCmp[bb]; if (a.row != b.row) { return (a.row > b.row) ^ revert; } - return GPUCA_DETERMINISTIC_CODE((a.id != b.id) ? (a.id > b.id) : (aa > bb), a.id > b.id); + return GPUCA_DETERMINISTIC_CODE((a.id != b.id) ? (a.id > b.id) : (a.idx > b.idx), a.id > b.id); } }; } // anonymous namespace @@ -1732,7 +1729,7 @@ GPUd() void GPUTPCGMMerger::CollectMergedTracks(int32_t nBlocks, int32_t nThread const GPUTPCTracker& trk = GetConstantMem()->tpcTrackers[t->Sector()]; const GPUTPCHitId& ic = trk.TrackHits()[t->OrigTrack(this)->FirstHitID() + i]; uint32_t id = trk.Data().ClusterDataIndex(trk.Data().Row(ic.RowIndex()), ic.HitIndex()) + GetConstantMem()->ioPtrs.clustersNative->clusterOffset[t->Sector()][0]; - *c2 = trackCluster{id, (uint8_t)ic.RowIndex(), t->Sector()}; + *c2 = trackCluster{id, (uint8_t)ic.RowIndex(), t->Sector(), (uint16_t)(c2 - trackClusters)}; } nHits += nTrackHits; } @@ -1753,38 +1750,26 @@ GPUd() void GPUTPCGMMerger::CollectMergedTracks(int32_t nBlocks, int32_t nThread int8_t firstTrackIndex = 0; int8_t lastTrackIndex = nParts - 1; if (ordered == 0) { - int16_t nTmpHits = 0; - trackCluster trackClustersUnsorted[kMaxClusters]; - int16_t clusterIndices[kMaxClusters]; - for (uint32_t i = 0; i < nHits; i++) { - trackClustersUnsorted[i] = trackClusters[i]; - clusterIndices[i] = i; - } + GPUCommonAlgorithm::sort(trackClusters, trackClusters + nHits, GPUTPCGMMerger_CompareClusterIds(mustReverse)); - GPUCommonAlgorithm::sort(clusterIndices, clusterIndices + nHits, GPUTPCGMMerger_CompareClusterIds(trackClusters, mustReverse)); - - nTmpHits = 0; + int16_t nTmpHits = 0; firstTrackIndex = lastTrackIndex = -1; for (int32_t i = 0; i < nParts; i++) { nTmpHits += trackParts[i]->NClusters(); - if (nTmpHits > clusterIndices[0] && firstTrackIndex == -1) { + if (nTmpHits > trackClusters[0].idx && firstTrackIndex == -1) { firstTrackIndex = i; } - if (nTmpHits > clusterIndices[nHits - 1] && lastTrackIndex == -1) { + if (nTmpHits > trackClusters[nHits - 1].idx && lastTrackIndex == -1) { lastTrackIndex = i; } } int16_t nFilteredHits = 0; - int16_t indPrev = -1; - for (uint32_t i = 0; i < nHits; i++) { - const int16_t ind = clusterIndices[i]; - if (indPrev >= 0 && trackClustersUnsorted[ind].id == trackClustersUnsorted[indPrev].id) { + for (uint32_t i = 0; i < nHits; i++) { // Remove duplicates in place, they are adjacent after sorting + if (nFilteredHits > 0 && trackClusters[i].id == trackClusters[nFilteredHits - 1].id) { continue; } - indPrev = ind; - trackClusters[nFilteredHits] = trackClustersUnsorted[ind]; - nFilteredHits++; + trackClusters[nFilteredHits++] = trackClusters[i]; } nHits = nFilteredHits; } diff --git a/GPU/GPUTracking/Merger/GPUTPCGMMerger.h b/GPU/GPUTracking/Merger/GPUTPCGMMerger.h index 0d3bf669b6cee..c3289960d660d 100644 --- a/GPU/GPUTracking/Merger/GPUTPCGMMerger.h +++ b/GPU/GPUTracking/Merger/GPUTPCGMMerger.h @@ -87,6 +87,7 @@ class GPUTPCGMMerger : public GPUProcessor uint32_t id; uint8_t row; uint8_t sector; + uint16_t idx; // Position in the track before sorting }; struct trackRebuildHelperCandidate; From b6db255aae0b42e6ab5b68e33bb0718e68533aa0 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Fri, 27 Nov 2026 15:07:15 +0100 Subject: [PATCH 06/12] GPU TPC: Use correct inFlyDirection for FollowLooper kernel and simplify code --- GPU/GPUTracking/Merger/GPUTPCGMTrackParam.cxx | 22 +++++++++---------- GPU/GPUTracking/Merger/GPUTPCGMTrackParam.h | 6 ++--- 2 files changed, 14 insertions(+), 14 deletions(-) diff --git a/GPU/GPUTracking/Merger/GPUTPCGMTrackParam.cxx b/GPU/GPUTracking/Merger/GPUTPCGMTrackParam.cxx index 2c8d89bcd9750..5060860037c0e 100644 --- a/GPU/GPUTracking/Merger/GPUTPCGMTrackParam.cxx +++ b/GPU/GPUTracking/Merger/GPUTPCGMTrackParam.cxx @@ -344,10 +344,11 @@ GPUd() bool GPUTPCGMTrackParam::Fit(GPUTPCGMMerger& GPUrestrict() merger, GPUTPC deltaZ = 0.f; } + const bool upwards = (clusters[0].row < clusters[maxN - 1].row) ^ (iWay & 1); if (param.rec.tpc.rebuildTrackInFit && !rebuilt && !(param.rec.tpc.disableRebuildAttachment & 16) && param.rec.tpc.rebuildTrackMaxNonIntCov > 0 && iWay >= wayRebuildStart && !(fitBroken && iWay == wayRebuildStart + 1) && CAMath::Abs(mP[2]) < maxSinForUpdate && lastUpdateRow != 255 && mNDF > (int32_t)param.rec.tpc.rebuildTrackNonIntMinNDF) { - const int8_t up = ((clusters[0].row < clusters[maxN - 1].row) ^ (iWay & 1)) ? 1 : -1; + const int8_t up = upwards ? 1 : -1; int8_t sector = lastSector; - CADEBUG(if (merger.MergedTrackMC()) printf("Extrapolate Start Track %d - sector %2d row %3d %s - fake %d\n", iTrk, sector, (int32_t)lastPropagateRow, up == 1 ? "upwards" : "downwards", (int)merger.MergedTrackMC()[iTrk].isFake())); + CADEBUG(if (merger.MergedTrackMC()) printf("Extrapolate Start Track %d - sector %2d row %3d %s - fake %d\n", iTrk, sector, (int32_t)lastPropagateRow, upwards ? "upwards" : "downwards", (int)merger.MergedTrackMC()[iTrk].isFake())); ExtrapolationState es; es.lastGoodRow = es.lastExtrapolateRow = es.lastFoundRow = lastPropagateRow; es.consecGoodRows = ihitStart == ((iWay & 1) ? 0 : maxN - 1) ? param.rec.tpc.rebuildTrackExtrMinConsecGoodRows : 0; // Continue the track directly only if its last hit was accepted in the fit @@ -363,7 +364,7 @@ GPUd() bool GPUTPCGMTrackParam::Fit(GPUTPCGMMerger& GPUrestrict() merger, GPUTPC const float lastFoundX = es.lastFoundX, lastFoundAlpha = es.lastFoundAlpha; const bool revert = es.revert; if (finalOutInFit && !(param.rec.tpc.disableMarkAdjacent & 8) && iExtrapolatedRow < GPUTPCGeometry::NROWS) { // Continue the looper following from where the extrapolation stopped - StoreLoopPropagation(merger, sector, iExtrapolatedRow, iTrk, up == 1, prop.GetAlpha()); + StoreLoopPropagation(merger, sector, iExtrapolatedRow, iTrk, up == 1, inFlyDirection, prop.GetAlpha()); CADEBUG(printf("\t\tSTORING %d extrapolated row %d sector %d out %d\n", iTrk, (int)iExtrapolatedRow, sector, up == 1)); } const int16_t rowsMoved = CAMath::Abs((int32_t)(iExtrapolatedRow < GPUTPCGeometry::NROWS ? iExtrapolatedRow : (uint8_t)(iExtrapolatedRow - up)) - (int32_t)lastGoodRow); // 255 after row 0 with up = -1 @@ -374,11 +375,11 @@ GPUd() bool GPUTPCGMTrackParam::Fit(GPUTPCGMMerger& GPUrestrict() merger, GPUTPC } else if (finalOutInFit && lastUpdateRow != 255 && !retryAttempt) { int8_t loopStored = -1; // Not attempted: handle like no looper if (!(param.rec.tpc.disableMarkAdjacent & 8)) { - loopStored = StoreLoopPropagation(merger, lastSector, lastUpdateRow, iTrk, lastUpdateRow > clusters[(iWay & 1) ? (maxN - 1) : 0].row, prop.GetAlpha()); + loopStored = StoreLoopPropagation(merger, lastSector, lastUpdateRow, iTrk, lastUpdateRow > clusters[(iWay & 1) ? (maxN - 1) : 0].row, inFlyDirection, prop.GetAlpha()); CADEBUG(printf("\t\tSTORING %d lastUpdateRow %d row %d out %d\n", iTrk, (int)lastUpdateRow, (int)clusters[(iWay & 1) ? (maxN - 1) : 0].row, lastUpdateRow > clusters[(iWay & 1) ? (maxN - 1) : 0].row)); } if (loopStored == -1 && GPUTPCGMMerger::FollowExtrapolationEnabled(param) && !fitBroken && CAMath::Abs(mP[2]) < maxSinForUpdate && mNDF > (int32_t)param.rec.tpc.rebuildTrackNonIntMinNDF && (!GPUTPCGMMerger::FollowExtrapolationAfterRebuild(param) || (track.Leg() == 0 && CAMath::Abs(GetQPt() * param.qptB5Scaler) <= param.rec.tpc.rejectQPtB5))) { - StoreFollowExtrapolation(merger, lastSector, lastPropagateRow, iTrk, (clusters[0].row < clusters[maxN - 1].row) ^ (iWay & 1), inFlyDirection, prop.GetAlpha()); // Follow the track beyond its end for adjacent clusters (same conditions as for the extrapolation), in the 5-way fit only to protect clusters, i.e. for good legs of tracks not rejected by rejectQPtB5 + StoreFollowExtrapolation(merger, lastSector, lastPropagateRow, iTrk, upwards, inFlyDirection, prop.GetAlpha()); // Follow the track beyond its end for adjacent clusters (same conditions as for the extrapolation), in the 5-way fit only to protect clusters, i.e. for good legs of tracks not rejected by rejectQPtB5 } } @@ -1288,7 +1289,7 @@ GPUdii() void GPUTPCGMTrackParam::StoreOuter(gputpcgmmergertypes::GPUTPCOuterPar outerParam->alpha = alpha; } -GPUdic(0, 1) int32_t GPUTPCGMTrackParam::StoreLoopPropagation(const GPUTPCGMMerger& GPUrestrict() merger, int32_t sector, int32_t iRow, int32_t iTrack, bool outwards, float alpha) +GPUdic(0, 1) int32_t GPUTPCGMTrackParam::StoreLoopPropagation(const GPUTPCGMMerger& GPUrestrict() merger, int32_t sector, int32_t iRow, int32_t iTrack, bool outwards, bool inFlyDirection, float alpha) { if (iRow == 0 || iRow == GPUTPCGeometry::NROWS - 1) { return 0; @@ -1315,7 +1316,7 @@ GPUdic(0, 1) int32_t GPUTPCGMTrackParam::StoreLoopPropagation(const GPUTPCGMMerg data.alpha = alpha; data.sector = sector; data.row = iRow; - data.outwards = outwards; + data.outwards = (uint8_t)outwards | ((uint8_t)inFlyDirection << 1); merger.LoopAndExtData()[n] = data; return 1; } @@ -1386,16 +1387,15 @@ GPUdii() void GPUTPCGMTrackParam::PropagateLooper(const GPUTPCGMMerger& GPUrestr GPUTPCGMTrackParam t = data.param; // Work on a local copy, not in global memory prop.SetTrack(&t, data.alpha); if (merger.Param().rec.tpc.looperFollowMode == 1) { - t.FindAdjacentClustersLooperFollow(merger, prop, data.sector, data.track, data.outwards); + t.FindAdjacentClustersLooperFollow(merger, prop, data.sector, data.track, data.outwards & 1, data.outwards & 2); } else { - t.FindAdjacentClustersLooperMirror(merger, data.sector, data.row, data.track, data.outwards, prop); + t.FindAdjacentClustersLooperMirror(merger, data.sector, data.row, data.track, data.outwards & 1, prop); } } -GPUdi() void GPUTPCGMTrackParam::FindAdjacentClustersLooperFollow(const GPUTPCGMMerger& GPUrestrict() merger, GPUTPCGMPropagator& GPUrestrict() prop, int8_t sector, const int32_t iTrack, const bool up) +GPUdi() void GPUTPCGMTrackParam::FindAdjacentClustersLooperFollow(const GPUTPCGMMerger& GPUrestrict() merger, GPUTPCGMPropagator& GPUrestrict() prop, int8_t sector, const int32_t iTrack, const bool up, const bool inFlyDirection) { float toX = mX; - bool inFlyDirection = (merger.MergedTracks()[iTrack].Leg() & 1) ^ up; const GPUParam& GPUrestrict() param = merger.Param(); bool right = (mP[2] < 0) ^ up; diff --git a/GPU/GPUTracking/Merger/GPUTPCGMTrackParam.h b/GPU/GPUTracking/Merger/GPUTPCGMTrackParam.h index 8deee9dea94db..bc4a4706765ea 100644 --- a/GPU/GPUTracking/Merger/GPUTPCGMTrackParam.h +++ b/GPU/GPUTracking/Merger/GPUTPCGMTrackParam.h @@ -178,8 +178,8 @@ class GPUTPCGMTrackParam GPUd() float FindAdjacentClusters(const GPUTPCGMMerger& GPUrestrict() merger, int32_t sector, int32_t iRow, int32_t iTrack, bool goodLeg, float Y, float Z); GPUd() void FindAdjacentClustersUncorrectedPos(const GPUTPCGMMerger& GPUrestrict() merger, int32_t sector, int32_t iRow, int32_t iTrack, bool goodLeg, float uncorrectedY, float uncorrectedZ, float Z, float err2Y, float err2Z); GPUd() void FindAdjacentClustersLooperMirror(const GPUTPCGMMerger& GPUrestrict() merger, int32_t sector, int32_t iRow, const int32_t iTrack, const bool up, const GPUTPCGMPropagator& prop); - GPUd() void FindAdjacentClustersLooperFollow(const GPUTPCGMMerger& GPUrestrict() merger, GPUTPCGMPropagator& prop, int8_t sector, const int32_t iTrack, const bool up); - GPUd() int32_t StoreLoopPropagation(const GPUTPCGMMerger& GPUrestrict() merger, int32_t sector, int32_t iRow, int32_t iTrack, bool outwards, float alpha); + GPUd() void FindAdjacentClustersLooperFollow(const GPUTPCGMMerger& GPUrestrict() merger, GPUTPCGMPropagator& prop, int8_t sector, const int32_t iTrack, const bool up, const bool inFlyDirection); + GPUd() int32_t StoreLoopPropagation(const GPUTPCGMMerger& GPUrestrict() merger, int32_t sector, int32_t iRow, int32_t iTrack, bool outwards, bool inFlyDirection, float alpha); GPUd() void StoreFollowExtrapolation(const GPUTPCGMMerger& GPUrestrict() merger, int32_t sector, int32_t iRow, int32_t iTrack, bool outwards, bool inFlyDirection, float alpha); GPUd() static void FollowExtrapolation(GPUTPCGMMerger& merger, int32_t idx); GPUd() void StoreOuter(gputpcgmmergertypes::GPUTPCOuterParam* outerParam, float alpha); @@ -255,7 +255,7 @@ struct GPUTPCGMLoopAndExtData { // Track end for FollowLoopers (stored from the float alpha; uint8_t sector; uint8_t row; - uint8_t outwards; // FollowExtrapolation entries: bit 1 = inFlyDirection + uint8_t outwards; // Bit 0 = outwards, bit 1 = inFlyDirection of the fit way }; GPUdi() void GPUTPCGMTrackParam::ResetCovariance() From a98d43a43177705f19a5518ad4e6cede0d85e2ec Mon Sep 17 00:00:00 2001 From: David Rohr Date: Fri, 27 Nov 2026 16:05:05 +0100 Subject: [PATCH 07/12] GPU TPC: Implement handling for CE crossing tracks with cluster in the same row on both sides during rebuild --- GPU/GPUTracking/Base/GPUReconstruction.cxx | 2 +- GPU/GPUTracking/Merger/GPUTPCGMMerger.cxx | 38 +++++++++++++++++++++- 2 files changed, 38 insertions(+), 2 deletions(-) diff --git a/GPU/GPUTracking/Base/GPUReconstruction.cxx b/GPU/GPUTracking/Base/GPUReconstruction.cxx index 51233a29f6fbe..6104a369b6a81 100644 --- a/GPU/GPUTracking/Base/GPUReconstruction.cxx +++ b/GPU/GPUTracking/Base/GPUReconstruction.cxx @@ -269,7 +269,7 @@ int32_t GPUReconstruction::InitPhaseBeforeDevice() detMode = true; #endif if (GetProcessingSettings().deterministicGPUReconstruction == -1) { - mProcessingSettings->deterministicGPUReconstruction = detMode ? 1 : (GetProcessingSettings().debugLevel >= 6 || GetProcessingSettings().debugDumpFinal); + mProcessingSettings->deterministicGPUReconstruction = detMode ? 1 : GetProcessingSettings().debugLevel >= 6; } if (GetProcessingSettings().deterministicGPUReconstruction) { if (!detMode) { diff --git a/GPU/GPUTracking/Merger/GPUTPCGMMerger.cxx b/GPU/GPUTracking/Merger/GPUTPCGMMerger.cxx index 329f91b0880d1..f2608312d3e3a 100644 --- a/GPU/GPUTracking/Merger/GPUTPCGMMerger.cxx +++ b/GPU/GPUTracking/Merger/GPUTPCGMMerger.cxx @@ -2260,6 +2260,42 @@ GPUd() void GPUTPCGMMerger::PrepareHitWeights(int32_t nBlocks, int32_t nThreads, } } } + if (trk.CCE() && !trk.Looper()) { // Ensure tracks cross the CE only once + const uint8_t nMaxCandidates = Param().rec.tpc.rebuildTrackInFitClusterCandidates; + const uint32_t jFirst = RebuildFirstRow(i), jLast = RebuildLastRow(i); + auto side = [&](uint32_t j) -> int8_t { + const auto& c = ClusterCandidates(i, j)[0]; + 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 + 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 + startSide = s >= 0 && s == lastSide ? s : -1; + lastSide = s >= 0 ? s : lastSide; + } else if (s >= 0 && s != startSide && (j == jLast || side(j + 1) != startSide)) { // Switch sides, unless the next row continues on the current side + border = j; + break; + } + } + for (uint32_t j = jFirst; startSide >= 0 && j <= jLast; j++) { + auto* c = ClusterCandidates(i, j); + const int8_t allowedSide = startSide ^ (j >= border); + uint8_t n = 0, k = 0; + for (; k < nMaxCandidates && c[k].hasCluster(); k++) { + if ((int8_t)(c[k].getSector() >= GPUTPCGeometry::NSECTORS / 2) == allowedSide) { + c[n++] = c[k]; + } + } + for (uint8_t l = n; l < k; l++) { + c[l].setValue(0); + } + if (n == 0 && k) { + c[0].setNoCandidate(); + } + } + } } } @@ -2364,7 +2400,7 @@ GPUd() void GPUTPCGMMerger::ResolveHitWeights2(int32_t nBlocks, int32_t nThreads trk.SetNClusters(nHits); trk.SetFirstClusterRef(iOut); uint32_t written = 0; - const bool reverse = mTrackRebuildHelper[i].reverse; // TODO: CE tracks may have clusters on both sides in the rows around the crossing: make sure the track crosses the CE only once, by cutting at the best row and removing the clusters on the wrong side of the cut + const bool reverse = mTrackRebuildHelper[i].reverse; for (uint32_t j = RebuildFirstRow(i), jLast = RebuildLastRow(i); j <= jLast; j++) { const auto& candidates = ClusterCandidates(i, j); if (TrackRebuildHelperRow(i, j).getBest() > 0 && TrackRebuildHelperRow(i, j).getBest() < trackRebuildHelperRow::bestRowRemoved) { From c4df650840171ed2ef7ad0cc9e518658ce4a7421 Mon Sep 17 00:00:00 2001 From: David Rohr Date: Fri, 27 Nov 2026 16:47:24 +0100 Subject: [PATCH 08/12] GPU TPC: Fix some bugs in CE merging logic of looping tracks --- GPU/GPUTracking/Merger/GPUTPCGMMerger.cxx | 9 ++++++--- GPU/GPUTracking/Merger/GPUTPCGMO2Output.cxx | 2 +- GPU/GPUTracking/Merger/GPUTPCGMTrackParam.cxx | 4 ++-- 3 files changed, 9 insertions(+), 6 deletions(-) diff --git a/GPU/GPUTracking/Merger/GPUTPCGMMerger.cxx b/GPU/GPUTracking/Merger/GPUTPCGMMerger.cxx index f2608312d3e3a..a71c0649b5333 100644 --- a/GPU/GPUTracking/Merger/GPUTPCGMMerger.cxx +++ b/GPU/GPUTracking/Merger/GPUTPCGMMerger.cxx @@ -1448,15 +1448,17 @@ GPUd() void GPUTPCGMMerger::MergeCE(int32_t nBlocks, int32_t nThreads, int32_t i if (!trk[1]->OK() || trk[1]->CCE()) { continue; } - bool celooper = (trk[0]->GetParam().GetQPt() * Param().qptB5Scaler > 1 && trk[0]->GetParam().GetQPt() * trk[1]->GetParam().GetQPt() < 0); + bool celooper = (CAMath::Abs(trk[0]->GetParam().GetQPt() * Param().qptB5Scaler) > 1 && trk[0]->GetParam().GetQPt() * trk[1]->GetParam().GetQPt() < 0); celooper |= trk[0]->PrevSegment() != -1 && trk[1]->PrevSegment() != -1; if (!celooper && trk[0]->GetParam().GetPar(3) * trk[1]->GetParam().GetPar(3) < 0) { continue; } bool needswap = false; - if (trk[0]->PrevSegment() == -1 && trk[1]->PrevSegment() >= 0) { + if (trk[0]->PrevSegment() >= 0 && trk[1]->PrevSegment() == -1) { needswap = true; + } else if (trk[0]->PrevSegment() == -1 && trk[1]->PrevSegment() >= 0) { + needswap = false; } else if (celooper) { const float z0max = -CAMath::Min(cls[mClusters[trk[0]->FirstClusterRef()].num].getTime(), cls[mClusters[trk[0]->FirstClusterRef() + trk[0]->NClusters() - 1].num].getTime()); const float z1max = -CAMath::Min(cls[mClusters[trk[1]->FirstClusterRef()].num].getTime(), cls[mClusters[trk[1]->FirstClusterRef() + trk[1]->NClusters() - 1].num].getTime()); @@ -1508,11 +1510,12 @@ GPUd() void GPUTPCGMMerger::MergeCE(int32_t nBlocks, int32_t nThreads, int32_t i return; } + const bool revertSingle = trk[1]->PrevSegment() >= 0 && mClusters[trk[1]->FirstClusterRef()].row < mClusters[trk[1]->FirstClusterRef() + trk[1]->NClusters() - 1].row; // Ensure correct order when CE-merging looping track + single segment, single segments are always sorted descending int32_t pos = newRef; #pragma unroll for (int8_t k = 1; k >= 0; k--) { for (uint32_t j = 0; j != trk[k]->NClusters(); j++) { - mClusters[pos++] = mClusters[trk[k]->FirstClusterRef() + j]; + mClusters[pos++] = mClusters[trk[k]->FirstClusterRef() + (k == 0 && revertSingle ? trk[k]->NClusters() - 1 - j : j)]; } } trk[1]->SetFirstClusterRef(newRef); diff --git a/GPU/GPUTracking/Merger/GPUTPCGMO2Output.cxx b/GPU/GPUTracking/Merger/GPUTPCGMO2Output.cxx index b2009aba09d41..1248a18ab3e86 100644 --- a/GPU/GPUTracking/Merger/GPUTPCGMO2Output.cxx +++ b/GPU/GPUTracking/Merger/GPUTPCGMO2Output.cxx @@ -226,7 +226,7 @@ GPUdii() void GPUTPCGMO2Output::Thread(int32_t nBlocks float time0 = 0.f, tFwd = 0.f, tBwd = 0.f; if (merger.Param().par.continuousTracking) { time0 = track.GetParam().GetTOffset(); - if (cce) { + if (cce || (track.CCE() && track.Looper())) { bool lastSide = trackClusters[track.FirstClusterRef()].sector < MAXSECTOR / 2; float delta = 0.f; for (uint32_t iCl = 1; iCl < track.NClusters(); iCl++) { diff --git a/GPU/GPUTracking/Merger/GPUTPCGMTrackParam.cxx b/GPU/GPUTracking/Merger/GPUTPCGMTrackParam.cxx index 5060860037c0e..37b041c6e62bd 100644 --- a/GPU/GPUTracking/Merger/GPUTPCGMTrackParam.cxx +++ b/GPU/GPUTracking/Merger/GPUTPCGMTrackParam.cxx @@ -93,7 +93,7 @@ GPUd() bool GPUTPCGMTrackParam::Fit(GPUTPCGMMerger& GPUrestrict() merger, GPUTPC const int8_t nWays = param.rec.tpc.nWays; const int32_t maxN = N; - if (rebuilt && maxN > 0 && param.par.continuousTracking && !track.CCE() && !track.Looper()) { // The rebuilt track can have other first / last clusters than the track the Z shift was computed for + if (rebuilt && param.par.continuousTracking && !track.CCE() && !track.Looper()) { // The rebuilt track can have other first / last clusters than the track the Z shift was computed for const float t0 = merger.GetConstantMem()->ioPtrs.clustersNative->clustersLinear[clusters[0].num].getTime(), tN = merger.GetConstantMem()->ioPtrs.clustersNative->clustersLinear[clusters[maxN - 1].num].getTime(); ConstrainZ(merger, clusters[0].sector, CAMath::Max(t0, tN), CAMath::Min(t0, tN)); } @@ -1629,7 +1629,7 @@ GPUd() bool GPUTPCGMTrackParam::CheckNumericalQuality(float overrideCovYY) const template GPUdii() void GPUTPCGMTrackParam::RefitTrack(GPUTPCGMMergedTrack& GPUrestrict() track, int32_t iTrk, GPUTPCGMMerger& GPUrestrict() merger) { - if (!track.OK()) { + if (!track.OK() || track.NClusters() == 0) { return; } const bool rebuilt = retryAttempt ? merger.Param().rec.tpc.rebuildTrackInFit : rebuiltKernel; From 543824685d2bca1abcdca14dc47b54f1dba30e1b Mon Sep 17 00:00:00 2001 From: David Rohr Date: Fri, 27 Nov 2026 18:00:53 +0100 Subject: [PATCH 09/12] GPU TPC: Implement handling of looping + ce-crossing tracks in first version, can be improved later --- GPU/GPUTracking/Merger/GPUTPCGMBorderTrack.h | 8 +++ GPU/GPUTracking/Merger/GPUTPCGMMerger.cxx | 55 ++++++++++++++------ 2 files changed, 47 insertions(+), 16 deletions(-) diff --git a/GPU/GPUTracking/Merger/GPUTPCGMBorderTrack.h b/GPU/GPUTracking/Merger/GPUTPCGMBorderTrack.h index d59b8fea28f08..9c291b2a55953 100644 --- a/GPU/GPUTracking/Merger/GPUTPCGMBorderTrack.h +++ b/GPU/GPUTracking/Merger/GPUTPCGMBorderTrack.h @@ -45,6 +45,14 @@ class GPUTPCGMBorderTrack GPUd() void SetZOffsetLinear(float v) { mZOffsetLinear = v; } GPUd() void SetCov(int32_t i, float x) { mC[i] = x; } GPUd() void SetCovD(int32_t i, float x) { mD[i] = x; } + GPUd() void SetFlipped() + { + mP[2] = -mP[2]; + mP[3] = -mP[3]; + mP[4] = -mP[4]; + mD[0] = -mD[0]; + mD[1] = -mD[1]; + } GPUd() static bool CheckChi2(float x1, float y1, float cx1, float cxy1, float cy1, float x2, float y2, float cx2, float cxy2, float cy2, float chi2cut) { diff --git a/GPU/GPUTracking/Merger/GPUTPCGMMerger.cxx b/GPU/GPUTracking/Merger/GPUTPCGMMerger.cxx index a71c0649b5333..7eca7c3c3efce 100644 --- a/GPU/GPUTracking/Merger/GPUTPCGMMerger.cxx +++ b/GPU/GPUTracking/Merger/GPUTPCGMMerger.cxx @@ -969,7 +969,14 @@ GPUd() void GPUTPCGMMerger::MergeBorderTracks<2>(int32_t nBlocks, int32_t nThrea } // do check - const GPUTPCGMBorderTrack& b2 = B2[r2.fId]; + const GPUTPCGMBorderTrack& b2orig = B2[r2.fId]; + GPUTPCGMBorderTrack b2flip; + const bool flip = (mergeMode & mergeModes::mergeAcrossCE) && CAMath::Abs(b1.Par()[4]) * Param().qptB5Scaler > 1.f && b1.Par()[4] * b2orig.Par()[4] < 0 && b1.Par()[2] * b2orig.Par()[2] < 0 && b1.Par()[3] * b2orig.Par()[3] < 0; + if (flip) { + b2flip = b2orig; + b2flip.SetFlipped(); + } + const GPUTPCGMBorderTrack& b2 = flip ? b2flip : b2orig; #if defined(GPUCA_MERGER_BY_MC_LABEL) && !defined(GPUCA_GPUCODE) int64_t label1 = GetTrackLabel(b1); int64_t label2 = GetTrackLabel(b2); @@ -1455,16 +1462,17 @@ GPUd() void GPUTPCGMMerger::MergeCE(int32_t nBlocks, int32_t nThreads, int32_t i } bool needswap = false; - if (trk[0]->PrevSegment() >= 0 && trk[1]->PrevSegment() == -1) { + if (celooper) { + // TODO: Could inverse the order of the clusters of the secondary track and merge them in the future, and set trk[0]->SetMergedLooper(true);, for now both stay in output + /* auto lastSegmentMinT = [&](const GPUTPCGMMergedTrack* t) { + t = t->GetFirstSegment(mMergedTracks, Param().rec.enableCyclicGraphWorkarounds); + return CAMath::Min(cls[mClusters[t->FirstClusterRef()].num].getTime(), cls[mClusters[t->FirstClusterRef() + t->NClusters() - 1].num].getTime()); + }; + needswap = lastSegmentMinT(trk[1]) > lastSegmentMinT(trk[0]); */ + } else if (trk[0]->PrevSegment() >= 0 && trk[1]->PrevSegment() == -1) { needswap = true; } else if (trk[0]->PrevSegment() == -1 && trk[1]->PrevSegment() >= 0) { needswap = false; - } else if (celooper) { - const float z0max = -CAMath::Min(cls[mClusters[trk[0]->FirstClusterRef()].num].getTime(), cls[mClusters[trk[0]->FirstClusterRef() + trk[0]->NClusters() - 1].num].getTime()); - const float z1max = -CAMath::Min(cls[mClusters[trk[1]->FirstClusterRef()].num].getTime(), cls[mClusters[trk[1]->FirstClusterRef() + trk[1]->NClusters() - 1].num].getTime()); - if (z1max < z0max) { - needswap = true; - } } else { if (mClusters[trk[0]->FirstClusterRef()].row > mClusters[trk[1]->FirstClusterRef()].row) { needswap = true; @@ -1473,6 +1481,13 @@ GPUd() void GPUTPCGMMerger::MergeCE(int32_t nBlocks, int32_t nThreads, int32_t i if (needswap) { GPUCommonAlgorithm::swap(trk[0], trk[1]); } + bool revertSingle = false; + if (!celooper && trk[1]->PrevSegment() >= 0) { + revertSingle = mClusters[trk[1]->FirstClusterRef()].row < mClusters[trk[1]->FirstClusterRef() + trk[1]->NClusters() - 1].row; // Ensure correct order, single segments are always sorted descending + if (CAMath::Abs((int32_t)mClusters[trk[1]->FirstClusterRef() + trk[1]->NClusters() - 1].row - (int32_t)mClusters[trk[0]->FirstClusterRef() + (revertSingle ? trk[0]->NClusters() - 1 : 0)].row) > 5) { + celooper = true; // Rows do not continue at the junction, i.e. the assumed direction of the looping track is wrong + } + } if (Param().par.continuousTracking) { GPUTPCGMMergedTrackHit* clsmax; @@ -1481,19 +1496,28 @@ GPUd() void GPUTPCGMMerger::MergeCE(int32_t nBlocks, int32_t nThreads, int32_t i &mClusters[trk[0]->FirstClusterRef()], &mClusters[trk[0]->FirstClusterRef() + trk[0]->NClusters() - 1], &mClusters[trk[1]->FirstClusterRef()], &mClusters[trk[1]->FirstClusterRef() + trk[1]->NClusters() - 1], clsmax); const float offset = CAMath::Max(tmax - mConstantMem->calibObjects.fastTransform->getMaxDriftTime(clsmax->sector, clsmax->row, cls[clsmax->num].getPad()), 0.f); - trk[1]->Param().Z() += mConstantMem->calibObjects.fastTransform->convDeltaTimeToDeltaZinTimeFrame(trk[1]->CSide() * NSECTORS / 2, trk[1]->Param().TOffset() - offset); - trk[1]->Param().TOffset() = offset; + auto shiftZ = [&](GPUTPCGMMergedTrack* t) { // Shift the track and its following segments, PrepareForFit1 does not propagate the time offset of CE tracks + for (GPUTPCGMMergedTrack* seg = t;;) { + seg->Param().Z() += mConstantMem->calibObjects.fastTransform->convDeltaTimeToDeltaZinTimeFrame(seg->CSide() * NSECTORS / 2, seg->Param().TOffset() - offset); + seg->Param().TOffset() = offset; + if (seg->PrevSegment() < 0) { + break; + } + seg = &mMergedTracks[seg->PrevSegment()]; + if (Param().rec.enableCyclicGraphWorkarounds && seg == t) { + break; + } + } + }; + shiftZ(trk[1]); if (celooper) { - trk[0]->Param().Z() += mConstantMem->calibObjects.fastTransform->convDeltaTimeToDeltaZinTimeFrame(trk[0]->CSide() * NSECTORS / 2, trk[0]->Param().TOffset() - offset); - trk[0]->Param().TOffset() = offset; + shiftZ(trk[0]); } } - if (celooper) { // TODO: Need propper handling, avoid falsely flagging the primary leg as looper - trk[0]->SetMergedLooperConnected(true); + if (celooper) { trk[0]->SetCCE(true); trk[0]->SetLooper(true); - trk[1]->SetMergedLooperConnected(true); trk[1]->SetCCE(true); trk[1]->SetLooper(true); continue; @@ -1510,7 +1534,6 @@ GPUd() void GPUTPCGMMerger::MergeCE(int32_t nBlocks, int32_t nThreads, int32_t i return; } - const bool revertSingle = trk[1]->PrevSegment() >= 0 && mClusters[trk[1]->FirstClusterRef()].row < mClusters[trk[1]->FirstClusterRef() + trk[1]->NClusters() - 1].row; // Ensure correct order when CE-merging looping track + single segment, single segments are always sorted descending int32_t pos = newRef; #pragma unroll for (int8_t k = 1; k >= 0; k--) { From 00638ebac5994182c7b282640af074cca3cbc44d Mon Sep 17 00:00:00 2001 From: David Rohr Date: Sat, 28 Nov 2026 12:41:26 +0100 Subject: [PATCH 10/12] GPU: Add debugSilent mode --- GPU/GPUTracking/Base/GPUReconstruction.cxx | 31 ++++++++++++------- GPU/GPUTracking/Base/GPUReconstruction.h | 4 +-- GPU/GPUTracking/Base/GPUReconstructionCPU.cxx | 10 +++--- GPU/GPUTracking/Base/GPUReconstructionCPU.h | 3 +- .../Base/GPUReconstructionCPUKernels.h | 2 +- .../Base/GPUReconstructionDebug.cxx | 4 +-- .../Base/GPUReconstructionDeviceBase.cxx | 2 +- GPU/GPUTracking/Base/GPUReconstructionIO.h | 10 +++--- .../Base/GPUReconstructionProcessing.cxx | 2 +- .../Base/GPUReconstructionRTCHelpers.inc | 4 +-- .../cpudevice/GPUReconstructionCPUDevice.cxx | 2 +- .../GPUReconstructionCPUDeviceGenRTC.cxx | 2 +- .../Base/cuda/GPUReconstructionCUDA.cu | 12 +++---- .../Base/cuda/GPUReconstructionCUDAGenRTC.cxx | 2 +- .../Base/metal/GPUReconstructionMetal.mm | 4 +-- .../Base/opencl/GPUReconstructionOCL.cxx | 6 ++-- .../Definitions/GPUSettingsList.template | 1 + GPU/GPUTracking/Global/GPUChainTracking.cxx | 2 +- .../Global/GPUChainTrackingClusterizer.cxx | 6 ++-- .../Global/GPUChainTrackingMerger.cxx | 4 +-- .../Global/GPUChainTrackingSectorTracker.cxx | 12 +++---- .../Global/GPUChainTrackingTRD.cxx | 2 +- .../Global/GPUChainTrackingTransformation.cxx | 2 +- GPU/GPUTracking/qa/GPUQA.cxx | 2 +- 24 files changed, 71 insertions(+), 60 deletions(-) diff --git a/GPU/GPUTracking/Base/GPUReconstruction.cxx b/GPU/GPUTracking/Base/GPUReconstruction.cxx index 6104a369b6a81..14a4c9496cfda 100644 --- a/GPU/GPUTracking/Base/GPUReconstruction.cxx +++ b/GPU/GPUTracking/Base/GPUReconstruction.cxx @@ -584,7 +584,7 @@ size_t GPUReconstruction::AllocateRegisteredMemoryHelper(GPUMemoryResource* res, GPUError("Insufficient reuse memory %lu < %lu (%s) (%s)", mMemoryResources[res->mReuse].mSize, retVal, res->mName, device); throw std::bad_alloc(); } - if (GetProcessingSettings().allocDebugLevel >= 2) { + if (GetProcessingSettings().allocDebugLevel >= 2 && !GetProcessingSettings().debugSilent) { std::cout << "Reused (" << device << ") " << res->mName << ": " << retVal << "\n"; } return retVal; @@ -619,7 +619,7 @@ size_t GPUReconstruction::AllocateRegisteredMemoryHelper(GPUMemoryResource* res, std::cerr << "Memory pool size exceeded (" << device << ") (" << res->mName << ": " << (memorypoolend ? (memorysize + ptrDiff(memorypool, memorypoolend)) : ptrDiff(memorypool, memorybase)) << " > " << memorysize << "\n"; throw std::bad_alloc(); } - if (GetProcessingSettings().allocDebugLevel >= 2) { + if (GetProcessingSettings().allocDebugLevel >= 2 && !GetProcessingSettings().debugSilent) { std::cout << "Allocated (" << device << ") " << res->mName << ": " << retVal << " - available: " << (memorypoolend ? ptrDiff(memorypoolend, memorypool) : (memorysize - ptrDiff(memorypool, memorybase))) << "\n"; } return retVal; @@ -644,7 +644,7 @@ void GPUReconstruction::AllocateRegisteredMemoryInternal(GPUMemoryResource* res, } res->mPtr = GPUProcessor::alignPointer(res->mPtrDevice); res->SetPointers(res->mPtr); - if (GetProcessingSettings().allocDebugLevel >= 2) { + if (GetProcessingSettings().allocDebugLevel >= 2 && !GetProcessingSettings().debugSilent) { std::cout << (res->mReuse >= 0 ? "Reused " : "Allocated ") << res->mName << ": " << res->mSize << " (individual" << ((res->mType & GPUMemoryResource::MEMORY_STACK) ? " stack" : "") << ")\n"; } if (res->mType & GPUMemoryResource::MEMORY_STACK) { @@ -670,7 +670,7 @@ void GPUReconstruction::AllocateRegisteredMemoryInternal(GPUMemoryResource* res, res->mSize = std::max((size_t)res->SetPointers((void*)1) - 1, res->mOverrideSize); res->mPtr = control->allocator(CAMath::nextMultipleOf(res->mSize)); res->mSize = std::max(ptrDiff(res->SetPointers(res->mPtr), res->mPtr), res->mOverrideSize); - if (GetProcessingSettings().allocDebugLevel >= 2) { + if (GetProcessingSettings().allocDebugLevel >= 2 && !GetProcessingSettings().debugSilent) { std::cout << "Allocated (from callback) " << res->mName << ": " << res->mSize << "\n"; } } else { @@ -766,7 +766,7 @@ void* GPUReconstruction::AllocateDirectMemory(size_t size, int32_t type) throw std::bad_alloc(); } UpdateMaxMemoryUsed(); - if (GetProcessingSettings().allocDebugLevel >= 2) { + if (GetProcessingSettings().allocDebugLevel >= 2 && !GetProcessingSettings().debugSilent) { std::cout << "Allocated (direct " << ((type & GPUMemoryResource::MEMORY_GPU) ? "gpu" : "host") << "): " << size << " - available: " << ptrDiff(poolend, pool) << "\n"; } return retVal; @@ -788,7 +788,7 @@ void* GPUReconstruction::AllocateVolatileDeviceMemory(size_t size) throw std::bad_alloc(); } UpdateMaxMemoryUsed(); - if (GetProcessingSettings().allocDebugLevel >= 2) { + if (GetProcessingSettings().allocDebugLevel >= 2 && !GetProcessingSettings().debugSilent) { std::cout << "Allocated (volatile GPU): " << size << " - available: " << ptrDiff(mDeviceMemoryPoolEnd, mDeviceMemoryPool) << "\n"; } return retVal; @@ -818,7 +818,7 @@ void GPUReconstruction::ReturnVolatileDeviceMemory() mDeviceMemoryPool = mVolatileMemoryStart; mVolatileMemoryStart = nullptr; } - if (GetProcessingSettings().allocDebugLevel >= 2) { + if (GetProcessingSettings().allocDebugLevel >= 2 && !GetProcessingSettings().debugSilent) { std::cout << "Freed (volatile GPU) - available: " << ptrDiff(mDeviceMemoryPoolEnd, mDeviceMemoryPool) << "\n"; } } @@ -875,7 +875,7 @@ void GPUReconstruction::FreeRegisteredMemory(int16_t ires) void GPUReconstruction::FreeRegisteredMemory(GPUMemoryResource* res) { - if (GetProcessingSettings().allocDebugLevel >= 2 && (res->mPtr || res->mPtrDevice)) { + if (GetProcessingSettings().allocDebugLevel >= 2 && !GetProcessingSettings().debugSilent && (res->mPtr || res->mPtrDevice)) { std::cout << "Freeing " << res->mName << ": size " << res->mSize << " (reused " << res->mReuse << ")\n"; } if (GetProcessingSettings().memoryAllocationStrategy == GPUMemoryResource::ALLOCATION_INDIVIDUAL && res->mReuse < 0) { @@ -904,7 +904,7 @@ void GPUReconstruction::PopNonPersistentMemory(RecoStep step, uint64_t tag, cons if (tag != 0 && std::get<4>(mNonPersistentMemoryStack.back()) != tag) { GPUFatal("Tag mismatch when popping non persistent memory from stack : pop %s vs on stack %s", qTag2Str(tag).c_str(), qTag2Str(std::get<4>(mNonPersistentMemoryStack.back())).c_str()); } - if (!proc && (GetProcessingSettings().debugLevel >= 3 || GetProcessingSettings().allocDebugLevel) && (IsGPU() || GetProcessingSettings().forceHostMemoryPoolSize)) { + if (!proc && (GetProcessingSettings().debugLevel >= 3 || GetProcessingSettings().allocDebugLevel) && !GetProcessingSettings().debugSilent && (IsGPU() || GetProcessingSettings().forceHostMemoryPoolSize)) { printf("Allocated memory after %30s (%8s) (Stack %zu): ", gpudatatypes::RECO_STEP_NAMES[getRecoStepNum(step, true)], qTag2Str(std::get<4>(mNonPersistentMemoryStack.back())).c_str(), mNonPersistentMemoryStack.size()); PrintMemoryOverview(); printf("%76s", ""); @@ -915,7 +915,7 @@ void GPUReconstruction::PopNonPersistentMemory(RecoStep step, uint64_t tag, cons if (proc && res->mProcessor != proc) { continue; } - if (GetProcessingSettings().allocDebugLevel >= 2 && (res->mPtr || res->mPtrDevice)) { + if (GetProcessingSettings().allocDebugLevel >= 2 && !GetProcessingSettings().debugSilent && (res->mPtr || res->mPtrDevice)) { std::cout << "Freeing NonPersistent " << res->mName << ": size " << res->mSize << " (reused " << res->mReuse << ")\n"; } if (res->mReuse < 0) { @@ -1345,11 +1345,20 @@ void GPUReconstruction::SetInputControl(void* ptr, size_t size) { mInputControl. GPUReconstruction::DeviceType GPUReconstruction::GetDeviceType() const { return (DeviceType)GetDeviceBackendSettings().deviceType; } const GPUParam& GPUReconstruction::GetParam() const { return mHostConstantMem->param; } void GPUReconstruction::SetResetTimers(bool reset) { mProcessingSettings->resetTimers = reset; } -void GPUReconstruction::SetDebugLevelTmp(int32_t level) { mProcessingSettings->debugLevel = level; } GPUParam& GPUReconstruction::param() { return mHostConstantMem->param; } const GPUTrackingInOutPointers GPUReconstruction::GetIOPtrs() const { return mHostConstantMem->ioPtrs; } const GPUCalibObjectsConst& GPUReconstruction::GetCalib() const { return processors()->calibObjects; } +void GPUReconstruction::SetDebugLevelTmp(int32_t level, int32_t silent) +{ + if (level > -100) { + mProcessingSettings->debugLevel = level; + } + if (silent > -100) { + mProcessingSettings->debugSilent = silent; + } +} + ThrustVolatileAllocator::ThrustVolatileAllocator(GPUReconstruction* r) { mAlloc = [&r](size_t n) { return (char*)r->AllocateVolatileDeviceMemory(n); }; diff --git a/GPU/GPUTracking/Base/GPUReconstruction.h b/GPU/GPUTracking/Base/GPUReconstruction.h index ce341b7cf50a5..f83eeaf3f31f6 100644 --- a/GPU/GPUTracking/Base/GPUReconstruction.h +++ b/GPU/GPUTracking/Base/GPUReconstruction.h @@ -216,8 +216,8 @@ class GPUReconstruction bool IsInitialized() const { return mInitialized; } void SetSettings(float solenoidBzNominalGPU, const GPURecoStepConfiguration* workflow = nullptr); void SetSettings(const GPUSettingsGRP* grp, const GPUSettingsRec* rec = nullptr, const GPUSettingsProcessing* proc = nullptr, const GPURecoStepConfiguration* workflow = nullptr); - void SetResetTimers(bool reset); // May update also after Init() - void SetDebugLevelTmp(int32_t level); // Temporarily, before calling SetSettings() + void SetResetTimers(bool reset); // May update also after Init() + void SetDebugLevelTmp(int32_t level = -100, int32_t silent = -100); // Temporarily, before calling SetSettings() void UpdateSettings(const GPUSettingsGRP* g, const GPUSettingsProcessing* p = nullptr, const GPUSettingsRecDynamic* d = nullptr); void UpdateDynamicSettings(const GPUSettingsRecDynamic* d); void SetOutputControl(const GPUOutputControl& v) { mOutputControl = v; } diff --git a/GPU/GPUTracking/Base/GPUReconstructionCPU.cxx b/GPU/GPUTracking/Base/GPUReconstructionCPU.cxx index 1a4be02e66b5a..72f148df01f60 100644 --- a/GPU/GPUTracking/Base/GPUReconstructionCPU.cxx +++ b/GPU/GPUTracking/Base/GPUReconstructionCPU.cxx @@ -288,7 +288,7 @@ int32_t GPUReconstructionCPU::RunChains() mStatNEvents++; mNEventsProcessed++; - if (GetProcessingSettings().debugLevel >= 3 || GetProcessingSettings().allocDebugLevel) { + if ((GetProcessingSettings().debugLevel >= 3 || GetProcessingSettings().allocDebugLevel) && !GetProcessingSettings().debugSilent) { GPUInfo("Allocated memory when starting processing %34s", ""); PrintMemoryOverview(); } @@ -314,7 +314,7 @@ int32_t GPUReconstructionCPU::RunChains() ClearAllocatedMemory(); } mStatCPUTime += (double)(std::clock() - cpuTimerStart) / CLOCKS_PER_SEC; - if (GetProcessingSettings().debugLevel >= 3 || GetProcessingSettings().allocDebugLevel) { + if ((GetProcessingSettings().debugLevel >= 3 || GetProcessingSettings().allocDebugLevel) && !GetProcessingSettings().debugSilent) { GPUInfo("Allocated memory when ending processing %36s", ""); PrintMemoryOverview(); } @@ -327,7 +327,7 @@ int32_t GPUReconstructionCPU::RunChains() double kernelTotal = 0; std::vector kernelStepTimes(gpudatatypes::N_RECO_STEPS, 0.); - debugWriter writer(GetProcessingSettings().debugCSV, GetProcessingSettings().debugMarkdown, mStatNEvents); + debugWriter writer(GetProcessingSettings().debugCSV, GetProcessingSettings().debugMarkdown, mStatNEvents, GetProcessingSettings().debugSilent); if (GetProcessingSettings().debugLevel >= 1) { writer.header(); @@ -385,7 +385,7 @@ int32_t GPUReconstructionCPU::RunChains() } double gpu_time = GetProcessingSettings().debugLevel >= 1 ? kernelTotal : -1.0; writer.row(' ', 0, "Wall", gpu_time, mStatCPUTime, mTimerTotal.GetElapsedTime(), 0, nEventReport); - } else if (GetProcessingSettings().debugLevel >= 0) { + } else if (GetProcessingSettings().debugLevel >= 0 && !GetProcessingSettings().debugSilent) { GPUInfo("Total Wall Time: %10.0f us%s", mStatWallTime, nEventReport.c_str()); } if (GetProcessingSettings().resetTimers) { @@ -399,7 +399,7 @@ int32_t GPUReconstructionCPU::RunChains() } if (GetProcessingSettings().memoryStat) { PrintMemoryStatistics(); - } else if (GetProcessingSettings().debugLevel >= 2) { + } else if (GetProcessingSettings().debugLevel >= 2 && !GetProcessingSettings().debugSilent) { PrintMemoryOverview(); } diff --git a/GPU/GPUTracking/Base/GPUReconstructionCPU.h b/GPU/GPUTracking/Base/GPUReconstructionCPU.h index 0873ce6c30542..6b3e04b0a8c41 100644 --- a/GPU/GPUTracking/Base/GPUReconstructionCPU.h +++ b/GPU/GPUTracking/Base/GPUReconstructionCPU.h @@ -107,13 +107,14 @@ class GPUReconstructionCPU : public GPUReconstructionProcessing::KernelInterface void runKernelInterface(krnlSetup&& setup, Args const&... args); struct debugWriter { - debugWriter(std::string filenameCSV, bool markdown, uint32_t statNEvents); + debugWriter(std::string filenameCSV, bool markdown, uint32_t statNEvents, bool silent); void header(); void row(char type, uint32_t count, std::string name, double gpu_time, double cpu_time, double total_time, std::size_t memSize, std::string nEventReport = ""); private: std::ofstream streamCSV; bool mMarkdown; + bool mSilent; uint32_t mStatNEvents; }; }; diff --git a/GPU/GPUTracking/Base/GPUReconstructionCPUKernels.h b/GPU/GPUTracking/Base/GPUReconstructionCPUKernels.h index 9fbb4d2e6040d..99ef81043c73e 100644 --- a/GPU/GPUTracking/Base/GPUReconstructionCPUKernels.h +++ b/GPU/GPUTracking/Base/GPUReconstructionCPUKernels.h @@ -52,7 +52,7 @@ inline void GPUReconstructionCPU::runKernelInterface(krnlSetup&& setup, Args con if (nThreads > constants::GPU_MAX_THREADS) { throw std::runtime_error("GPU_MAX_THREADS exceeded"); } - if (GetProcessingSettings().debugLevel >= 3) { + if (GetProcessingSettings().debugLevel >= 3 && !GetProcessingSettings().debugSilent) { GPUInfo("Running kernel %s (Stream %d, Index %d, Grid %d/%d) on %s", GetKernelName(), stream, setup.y.index, nBlocks, nThreads, cpuFallback == 2 ? "CPU (forced)" : (cpuFallback ? "CPU (fallback)" : mDeviceName.c_str())); } if (nThreads == 0 || nBlocks == 0) { diff --git a/GPU/GPUTracking/Base/GPUReconstructionDebug.cxx b/GPU/GPUTracking/Base/GPUReconstructionDebug.cxx index 559d1537464ab..e69030c4c96b8 100644 --- a/GPU/GPUTracking/Base/GPUReconstructionDebug.cxx +++ b/GPU/GPUTracking/Base/GPUReconstructionDebug.cxx @@ -190,7 +190,7 @@ bool GPUReconstruction::triggerDebugDump() return false; } -GPUReconstructionCPU::debugWriter::debugWriter(std::string filenameCSV, bool markdown, uint32_t statNEvents) : mMarkdown{markdown}, mStatNEvents{statNEvents} +GPUReconstructionCPU::debugWriter::debugWriter(std::string filenameCSV, bool markdown, uint32_t statNEvents, bool silent) : mMarkdown{markdown}, mSilent{silent}, mStatNEvents{statNEvents} { if (!filenameCSV.empty()) { streamCSV.open(filenameCSV, std::ios::out | std::ios::app); @@ -277,7 +277,7 @@ void GPUReconstructionCPU::debugWriter::row(char type, uint32_t count, std::stri std::cout << " | | |"; } std::cout << std::endl; - } else { + } else if (!mSilent) { if (name.substr(0, 3) == "GPU") { char bandwidth[256] = ""; if (memSize && mStatNEvents && gpu_time != 0.0) { diff --git a/GPU/GPUTracking/Base/GPUReconstructionDeviceBase.cxx b/GPU/GPUTracking/Base/GPUReconstructionDeviceBase.cxx index c43bea334f1e6..89393bec4987e 100644 --- a/GPU/GPUTracking/Base/GPUReconstructionDeviceBase.cxx +++ b/GPU/GPUTracking/Base/GPUReconstructionDeviceBase.cxx @@ -192,7 +192,7 @@ size_t GPUReconstructionDeviceBase::TransferMemoryInternal(GPUMemoryResource* re } return 0; } - if (GetProcessingSettings().debugLevel >= 3 && (strcmp(res->Name(), "ErrorCodes") || GetProcessingSettings().debugLevel >= 4)) { + if (GetProcessingSettings().debugLevel >= 3 && !GetProcessingSettings().debugSilent && (strcmp(res->Name(), "ErrorCodes") || GetProcessingSettings().debugLevel >= 4)) { GPUInfo("Copying to %s: %s - %ld bytes", toGPU ? "GPU" : "Host", res->Name(), (int64_t)res->Size()); } return GPUMemCpy(dst, src, res->Size(), stream, toGPU, ev, evList, nEvents); diff --git a/GPU/GPUTracking/Base/GPUReconstructionIO.h b/GPU/GPUTracking/Base/GPUReconstructionIO.h index d2214fa6b79b2..7d8a87b310d96 100644 --- a/GPU/GPUTracking/Base/GPUReconstructionIO.h +++ b/GPU/GPUTracking/Base/GPUReconstructionIO.h @@ -73,7 +73,7 @@ inline uint32_t GPUReconstruction::DumpData(FILE* fp, const T* const* entries, c fwrite(entries[i], sizeof(*entries[i]), num[i], fp); } } - if (GetProcessingSettings().debugLevel >= 2) { + if (GetProcessingSettings().debugLevel >= 2 && !GetProcessingSettings().debugSilent) { GPUInfo("Dumped %u %s", numTotal, IOTYPENAMES[type]); } return numTotal; @@ -107,7 +107,7 @@ inline size_t GPUReconstruction::ReadData(FILE* fp, const T** entries, S* num, s } numTotal += num[i]; } - if (GetProcessingSettings().debugLevel >= 2) { + if (GetProcessingSettings().debugLevel >= 2 && !GetProcessingSettings().debugSilent) { GPUInfo("Read %zu %s", numTotal, IOTYPENAMES[type]); } return numTotal; @@ -147,7 +147,7 @@ inline std::unique_ptr GPUReconstruction::ReadFlatObjectFromFile(const char* r = fread((void*)retVal.get(), 1, size[0], fp); r = fread(buf, 1, size[1], fp); fclose(fp); - if (GetProcessingSettings().debugLevel >= 2) { + if (GetProcessingSettings().debugLevel >= 2 && !GetProcessingSettings().debugSilent) { GPUInfo("Read %zu bytes from %s", r, file); } retVal->clearInternalBufferPtr(); @@ -197,7 +197,7 @@ inline std::unique_ptr GPUReconstruction::ReadStructFromFile(const char* file GPUError("ERROR reading %s, read %zu (%zu expected)", file, r, size); throw std::runtime_error("invalid size"); } - if (GetProcessingSettings().debugLevel >= 2) { + if (GetProcessingSettings().debugLevel >= 2 && !GetProcessingSettings().debugSilent) { GPUInfo("Read %zu bytes from %s", r, file); } if (errorOnMissing) { @@ -255,7 +255,7 @@ inline aligned_unique_buffer_ptr GPUReconstruction::ReadDynamicStructFromFile GPUError("ERROR in %s: File Read error: %zu (%zu expected)", file, r, dynsize - sizeof(T)); throw std::runtime_error("invalid size"); } - if (GetProcessingSettings().debugLevel >= 2) { + if (GetProcessingSettings().debugLevel >= 2 && !GetProcessingSettings().debugSilent) { GPUInfo("Read %zu bytes from %s", r + dynsize, file); } return newObj; diff --git a/GPU/GPUTracking/Base/GPUReconstructionProcessing.cxx b/GPU/GPUTracking/Base/GPUReconstructionProcessing.cxx index 935db0e640857..08695b80ccef7 100644 --- a/GPU/GPUTracking/Base/GPUReconstructionProcessing.cxx +++ b/GPU/GPUTracking/Base/GPUReconstructionProcessing.cxx @@ -62,7 +62,7 @@ void GPUReconstructionProcessing::SetNActiveThreads(int32_t n) { mActiveHostKernelThreads = std::max(1, n < 0 ? mMaxHostThreads : std::min(n, mMaxHostThreads)); mThreading->activeThreads = std::make_unique(mActiveHostKernelThreads); - if (GetProcessingSettings().debugLevel >= 3) { + if (GetProcessingSettings().debugLevel >= 3 && !GetProcessingSettings().debugSilent) { GPUInfo("Set number of active parallel kernels threads on host to %d (%d requested)", mActiveHostKernelThreads, n); } } diff --git a/GPU/GPUTracking/Base/GPUReconstructionRTCHelpers.inc b/GPU/GPUTracking/Base/GPUReconstructionRTCHelpers.inc index f768b9382e739..90b7bf8c9df52 100644 --- a/GPU/GPUTracking/Base/GPUReconstructionRTCHelpers.inc +++ b/GPU/GPUTracking/Base/GPUReconstructionRTCHelpers.inc @@ -104,7 +104,7 @@ static void loadLaunchBounds(const GPUSettingsProcessing& proc, GPUDefParameters static std::string launchBoundsCode(const GPUSettingsProcessing& proc, const GPUDefParameters& par, int32_t minBlockFactor, uint32_t warpSize) // Prints the launch bounds if requested { std::string retVal = GPUDefParametersExport(par, true, minBlockFactor) + "#define GPUCA_WARP_SIZE " + std::to_string(warpSize) + "\n"; - if (proc.rtctech.printLaunchBounds || proc.debugLevel >= 3) { + 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 } @@ -138,7 +138,7 @@ static void runCommand(const GPUSettingsProcessing& proc, std::string command, c } else if (proc.debugLevel < 2) { command += " > /dev/null"; } - if (proc.debugLevel >= 3) { + if (proc.debugLevel >= 3 && !proc.debugSilent) { printf("Running command %s\n", command.c_str()); } if (system(command.c_str())) { diff --git a/GPU/GPUTracking/Base/cpudevice/GPUReconstructionCPUDevice.cxx b/GPU/GPUTracking/Base/cpudevice/GPUReconstructionCPUDevice.cxx index d91964f36fb5f..475c372c4eeee 100644 --- a/GPU/GPUTracking/Base/cpudevice/GPUReconstructionCPUDevice.cxx +++ b/GPU/GPUTracking/Base/cpudevice/GPUReconstructionCPUDevice.cxx @@ -339,7 +339,7 @@ int32_t GPUReconstructionCPUDevice::GPUDebug(const char* state, int32_t stream, GPUError("CPUDevice Error while synchronizing (%s) (Stream %d)", state, stream); return 1; } - if (GetProcessingSettings().debugLevel >= 3) { + if (GetProcessingSettings().debugLevel >= 3 && !GetProcessingSettings().debugSilent) { GPUInfo("GPU Sync Done"); } return 0; diff --git a/GPU/GPUTracking/Base/cpudevice/GPUReconstructionCPUDeviceGenRTC.cxx b/GPU/GPUTracking/Base/cpudevice/GPUReconstructionCPUDeviceGenRTC.cxx index 311315b92db05..d944562faca0b 100644 --- a/GPU/GPUTracking/Base/cpudevice/GPUReconstructionCPUDeviceGenRTC.cxx +++ b/GPU/GPUTracking/Base/cpudevice/GPUReconstructionCPUDeviceGenRTC.cxx @@ -73,7 +73,7 @@ int32_t GPUReconstructionCPUDevice::genRTC(std::string& filename, uint32_t& nCom if (!cache.load(filename, RTC_BIN_EXTENSION, nCompile)) { rtchelpers::compile(proc, nCompile, "CPUDevice", [&](uint32_t i) { const std::string fileBase = filename + "_" + std::to_string(i); - if (proc.debugLevel >= 3) { + if (proc.debugLevel >= 3 && !proc.debugSilent) { printf("Compiling %s\n", (fileBase + RTC_SRC_EXTENSION).c_str()); } const bool deterministic = rtchelpers::deterministic(proc, GetKernelName(i)); diff --git a/GPU/GPUTracking/Base/cuda/GPUReconstructionCUDA.cu b/GPU/GPUTracking/Base/cuda/GPUReconstructionCUDA.cu index 1f9949e8ffde2..13ca28bac7a7e 100644 --- a/GPU/GPUTracking/Base/cuda/GPUReconstructionCUDA.cu +++ b/GPU/GPUTracking/Base/cuda/GPUReconstructionCUDA.cu @@ -126,7 +126,7 @@ int32_t GPUReconstructionCUDA::InitDevice_Runtime() GPUError("Error getting CUDA Device Count"); return (1); } - if (GetProcessingSettings().debugLevel >= 2) { + if (GetProcessingSettings().debugLevel >= 2 && !GetProcessingSettings().debugSilent) { GPUInfo("Available CUDA devices:"); } std::vector devicesOK(count, false); @@ -175,7 +175,7 @@ int32_t GPUReconstructionCUDA::InitDevice_Runtime() } deviceSpeed = (double)deviceProp.multiProcessorCount * (double)deviceClockRate * (double)deviceProp.warpSize * (double)free * (double)deviceProp.major * (double)deviceProp.major; - if (GetProcessingSettings().debugLevel >= 2) { + if (GetProcessingSettings().debugLevel >= 2 && !GetProcessingSettings().debugSilent) { GPUImportant("Device %s%2d: %s (Rev: %d.%d - Mem Avail %lu / %lu)%s %s", deviceOK ? " " : "[", i, deviceProp.name, deviceProp.major, deviceProp.minor, free, (size_t)deviceProp.totalGlobalMem, deviceOK ? " " : " ]", deviceOK ? "" : deviceFailure); } if (!deviceOK) { @@ -187,7 +187,7 @@ int32_t GPUReconstructionCUDA::InitDevice_Runtime() bestDevice = i; bestDeviceSpeed = deviceSpeed; } else { - if (GetProcessingSettings().debugLevel >= 2 && GetProcessingSettings().deviceNum < 0) { + if (GetProcessingSettings().debugLevel >= 2 && !GetProcessingSettings().debugSilent && GetProcessingSettings().deviceNum < 0) { GPUInfo("Skipping: Speed %f <= %f\n", deviceSpeed, bestDeviceSpeed); } } @@ -228,7 +228,7 @@ int32_t GPUReconstructionCUDA::InitDevice_Runtime() GPUChkErrI(cudaGetDeviceProperties(&deviceProp, mDeviceId)); - if (GetProcessingSettings().debugLevel >= 2) { + if (GetProcessingSettings().debugLevel >= 2 && !GetProcessingSettings().debugSilent) { GPUInfo("Using CUDA Device %d: %s with Properties:", bestDevice, deviceProp.name); GPUInfo("\ttotalGlobalMem = %ld", (uint64_t)deviceProp.totalGlobalMem); GPUInfo("\tsharedMemPerBlock = %ld", (uint64_t)deviceProp.sharedMemPerBlock); @@ -572,7 +572,7 @@ int32_t GPUReconstructionCUDA::GPUDebug(const char* state, int32_t stream, bool GPUError("CUDA Error while synchronizing (%s) (Stream %d)", state, stream); return (1); } - if (GetProcessingSettings().debugLevel >= 3) { + if (GetProcessingSettings().debugLevel >= 3 && !GetProcessingSettings().debugSilent) { GPUInfo("GPU Sync Done"); } return (0); @@ -616,7 +616,7 @@ void GPUReconstructionCUDA::loadKernelModules(bool perKernel) GPUFatal("kernel numbers out of sync"); \ } \ mInternals->kernelFunctions.emplace_back(new CUfunction); \ - if (GetProcessingSettings().debugLevel >= 3) { \ + if (GetProcessingSettings().debugLevel >= 3 && !GetProcessingSettings().debugSilent) { \ GPUInfo("Loading kernel %s (j = %u)", GPUCA_M_STR(GPUCA_M_CAT(krnl_, GPUCA_M_KRNL_NAME(x_class))), j); \ } \ GPUChkErr(cuModuleGetFunction(mInternals->kernelFunctions.back().get(), *mInternals->kernelModules[perKernel ? j : 0], GPUCA_M_STR(GPUCA_M_CAT(krnl_, GPUCA_M_KRNL_NAME(x_class))))); \ diff --git a/GPU/GPUTracking/Base/cuda/GPUReconstructionCUDAGenRTC.cxx b/GPU/GPUTracking/Base/cuda/GPUReconstructionCUDAGenRTC.cxx index 0ac63608f0c84..5e366f15f6c1b 100644 --- a/GPU/GPUTracking/Base/cuda/GPUReconstructionCUDAGenRTC.cxx +++ b/GPU/GPUTracking/Base/cuda/GPUReconstructionCUDAGenRTC.cxx @@ -67,7 +67,7 @@ int32_t GPUReconstructionCUDA::genRTC(std::string& filename, uint32_t& nCompile) if (!cache.load(filename, mRtcBinExtension, nCompile)) { rtchelpers::compile(proc, nCompile, "CUDA", [&](uint32_t i) { const std::string fileBase = filename + "_" + std::to_string(i); - if (proc.debugLevel >= 3) { + if (proc.debugLevel >= 3 && !proc.debugSilent) { printf("Compiling %s\n", (fileBase + mRtcSrcExtension).c_str()); } const bool deterministic = rtchelpers::deterministic(proc, GetKernelName(i)); diff --git a/GPU/GPUTracking/Base/metal/GPUReconstructionMetal.mm b/GPU/GPUTracking/Base/metal/GPUReconstructionMetal.mm index 6f1d8ee9d95cf..1e6d164e267be 100644 --- a/GPU/GPUTracking/Base/metal/GPUReconstructionMetal.mm +++ b/GPU/GPUTracking/Base/metal/GPUReconstructionMetal.mm @@ -112,7 +112,7 @@ uint32_t metalGPUCoreCount() // On Apple Silicon, treat recommended working set as an upper bound deviceGlobalMem = mInternals->device.recommendedMaxWorkingSetSize; deviceLocalMem = mInternals->device.maxThreadgroupMemoryLength; - if (GetProcessingSettings().debugLevel >= 2) { + if (GetProcessingSettings().debugLevel >= 2 && !GetProcessingSettings().debugSilent) { GPUInfo("Using Metal device %s with properties:", device_name.c_str()); GPUInfo("\tUnified Memory Architecture = %ld ", mInternals->device.hasUnifiedMemory); GPUInfo("\tRecommended Max Working Set = %ld bytes", deviceGlobalMem); @@ -556,7 +556,7 @@ MetalMemRef metalResolve(const GPUReconstructionMetalInternals* internals, const for (int32_t si = 0; si < mNStreams; si++) { DrainStream(si); } - if (GetProcessingSettings().debugLevel >= 3) { + if (GetProcessingSettings().debugLevel >= 3 && !GetProcessingSettings().debugSilent) { GPUInfo("GPU Sync Done"); } return (0); diff --git a/GPU/GPUTracking/Base/opencl/GPUReconstructionOCL.cxx b/GPU/GPUTracking/Base/opencl/GPUReconstructionOCL.cxx index a093f10bf3d2e..1be120db35bd8 100644 --- a/GPU/GPUTracking/Base/opencl/GPUReconstructionOCL.cxx +++ b/GPU/GPUTracking/Base/opencl/GPUReconstructionOCL.cxx @@ -147,7 +147,7 @@ int32_t GPUReconstructionOCL::InitDevice_Runtime() } } - if (GetProcessingSettings().backend.platformNum >= 0 || GetProcessingSettings().debugLevel >= 2) { + if (GetProcessingSettings().backend.platformNum >= 0 || (GetProcessingSettings().debugLevel >= 2 && !GetProcessingSettings().debugSilent)) { GPUInfo("%s Platform %d: (%s %s) %s %s (Compatible: %s)%s", GetProcessingSettings().backend.platformNum >= 0 ? "Enforced" : "Available", iPlatform, platform_profile.c_str(), platform_version.c_str(), platform_vendor.c_str(), platform_name.c_str(), platformCompatible ? "yes" : "no", GetProcessingSettings().debugLevel >= 2 ? platformUsageInfo.c_str() : ""); } @@ -201,7 +201,7 @@ int32_t GPUReconstructionOCL::InitDevice_Runtime() } double bestDeviceSpeed = -1, deviceSpeed = (double)device_freq * (double)device_shaders; - if (GetProcessingSettings().debugLevel >= 2) { + if (GetProcessingSettings().debugLevel >= 2 && !GetProcessingSettings().debugSilent) { GPUInfo(" Device %s%2d: %s %s (Frequency %d, Shaders %d, %d bit) (Speed Value: %ld)%s %s", deviceOK ? " " : "[", i, device_vendor.c_str(), device_name.c_str(), (int32_t)device_freq, (int32_t)device_shaders, (int32_t)device_nbits, (int64_t)deviceSpeed, deviceOK ? " " : " ]", deviceOK ? "" : deviceFailure.c_str()); } if (!deviceOK) { @@ -511,7 +511,7 @@ int32_t GPUReconstructionOCL::GPUDebug(const char* state, int32_t stream, bool f GPUError("OpenCL Error while synchronizing (%s) (Stream %d/%d)", state, stream, i); } } - if (GetProcessingSettings().debugLevel >= 3) { + if (GetProcessingSettings().debugLevel >= 3 && !GetProcessingSettings().debugSilent) { GPUInfo("GPU Sync Done"); } return (0); diff --git a/GPU/GPUTracking/Definitions/GPUSettingsList.template b/GPU/GPUTracking/Definitions/GPUSettingsList.template index fe2538701a121..95437aade1cf4 100644 --- a/GPU/GPUTracking/Definitions/GPUSettingsList.template +++ b/GPU/GPUTracking/Definitions/GPUSettingsList.template @@ -378,6 +378,7 @@ AddOption(globalInitMutex, bool, false, "", 0, "Use global mutex to synchronize AddOption(trdNCandidates, int32_t, 3, "", 0, "Number of branching track candidates for single input track during propagation") AddOption(trdTrackModelO2, bool, false, "", 0, "Use O2 track model instead of GPU track model for TRD tracking") 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(debugLogSuffix, std::string, "", "debugSuffix", 0, "Suffix for debug log files with --debug 6") diff --git a/GPU/GPUTracking/Global/GPUChainTracking.cxx b/GPU/GPUTracking/Global/GPUChainTracking.cxx index 16db9a04f9fab..3e30702c83cbf 100644 --- a/GPU/GPUTracking/Global/GPUChainTracking.cxx +++ b/GPU/GPUTracking/Global/GPUChainTracking.cxx @@ -760,7 +760,7 @@ int32_t GPUChainTracking::RunChain() if (GetProcessingSettings().doublePipeline) { GPUChainTracking* foreignChain = (GPUChainTracking*)GetNextChainInQueue(); if (foreignChain && foreignChain->mIOPtrs.tpcZS) { - if (GetProcessingSettings().debugLevel >= 3) { + if (GetProcessingSettings().debugLevel >= 3 && !GetProcessingSettings().debugSilent) { GPUInfo("Preempting tpcZS input of foreign chain"); } mPipelineFinalizationCtx.reset(new GPUChainTrackingFinalContext); diff --git a/GPU/GPUTracking/Global/GPUChainTrackingClusterizer.cxx b/GPU/GPUTracking/Global/GPUChainTrackingClusterizer.cxx index 5de5d1dae642b..718d22b30f61c 100644 --- a/GPU/GPUTracking/Global/GPUChainTrackingClusterizer.cxx +++ b/GPU/GPUTracking/Global/GPUChainTrackingClusterizer.cxx @@ -998,7 +998,7 @@ int32_t GPUChainTracking::RunTPCClusterizer(bool synchronizeOutput) static_assert(NSECTORS <= constants::GPU_MAX_STREAMS, "Stream events must be able to hold all sectors"); const int32_t maxLane = std::min(GetProcessingSettings().nTPCClustererLanes, NSECTORS - iSectorBase); for (CfFragment frag = mCFContext->fragmentFirst; !frag.isEnd(); frag = frag.next()) { - if (GetProcessingSettings().debugLevel >= 3) { + if (GetProcessingSettings().debugLevel >= 3 && !GetProcessingSettings().debugSilent) { GPUInfo("Processing time bins [%d, %d) for sectors %d to %d", frag.start, frag.last(), iSectorBase, iSectorBase + GetProcessingSettings().nTPCClustererLanes - 1); } mRec->runParallelOuterLoop(doGPU, maxLane, [&](uint32_t lane) { @@ -1406,7 +1406,7 @@ int32_t GPUChainTracking::RunTPCClusterizer(bool synchronizeOutput) return; } - if (GetProcessingSettings().debugLevel >= 3) { + if (GetProcessingSettings().debugLevel >= 3 && !GetProcessingSettings().debugSilent) { GPUInfo("Sector %02d Fragment %02d Lane %d: Found clusters: digits %u peaks %u clusters %u", iSector, frag.index, lane, (int32_t)clusterer.mPmemory->counters.nPositions, (int32_t)clusterer.mPmemory->counters.nPeaks, (int32_t)clusterer.mPmemory->counters.nClusters); } @@ -1507,7 +1507,7 @@ int32_t GPUChainTracking::RunTPCClusterizer(bool synchronizeOutput) if (GetRecoSteps() & RecoStep::TPCTriggerHandling) { GPUOutputControl* triggerOutput = mSubOutputControls[GPUTrackingOutputs::getIndex(&GPUTrackingOutputs::tpcTriggerWords)]; const bool storeTriggers = triggerOutput && triggerOutput->allocator; - if (GetProcessingSettings().debugLevel >= 3) { + if (GetProcessingSettings().debugLevel >= 3 && !GetProcessingSettings().debugSilent) { GPUInfo("%zu trigger words found%s", mTriggerBuffer->triggers.size(), storeTriggers ? ", storing" : ""); } if (GetProcessingSettings().debugLevel >= 6 || (GetProcessingSettings().debugDumpFinal && storeTriggers)) { diff --git a/GPU/GPUTracking/Global/GPUChainTrackingMerger.cxx b/GPU/GPUTracking/Global/GPUChainTrackingMerger.cxx index 966b284ef31b5..45d64b50b5632 100644 --- a/GPU/GPUTracking/Global/GPUChainTrackingMerger.cxx +++ b/GPU/GPUTracking/Global/GPUChainTrackingMerger.cxx @@ -101,7 +101,7 @@ int32_t GPUChainTracking::RunTPCTrackingMerger(bool synchronizeOutput) GPUTPCGMMerger& Merger = processors()->tpcMerger; GPUTPCGMMerger& MergerShadow = doGPU ? processorsShadow()->tpcMerger : Merger; const int32_t outputStream = OutputStream(); - if (GetProcessingSettings().debugLevel >= 2) { + if (GetProcessingSettings().debugLevel >= 2 && !GetProcessingSettings().debugSilent) { GPUInfo("Running TPC Merger"); } const auto& holdContext = GetThreadContext(); @@ -448,7 +448,7 @@ int32_t GPUChainTracking::RunTPCTrackingMerger(bool synchronizeOutput) WriteToConstantMemory(RecoStep::TPCMerging, (char*)&processors()->ioPtrs - (char*)processors(), &processorsShadow()->ioPtrs, sizeof(processorsShadow()->ioPtrs), 0); } - if (GetProcessingSettings().debugLevel >= 2) { + if (GetProcessingSettings().debugLevel >= 2 && !GetProcessingSettings().debugSilent) { GPUInfo("TPC Merger Finished (output clusters %d / input clusters %d)", Merger.NMergedTrackClusters(), Merger.NSectorHits()); } return 0; diff --git a/GPU/GPUTracking/Global/GPUChainTrackingSectorTracker.cxx b/GPU/GPUTracking/Global/GPUChainTrackingSectorTracker.cxx index 1f472b380346a..a4941a4489a5e 100644 --- a/GPU/GPUTracking/Global/GPUChainTrackingSectorTracker.cxx +++ b/GPU/GPUTracking/Global/GPUChainTrackingSectorTracker.cxx @@ -69,7 +69,7 @@ int32_t GPUChainTracking::RunTPCTrackingSectors() int32_t GPUChainTracking::RunTPCTrackingSectors_internal() { - if (GetProcessingSettings().debugLevel >= 2) { + if (GetProcessingSettings().debugLevel >= 2 && !GetProcessingSettings().debugSilent) { GPUInfo("Running TPC Sector Tracker"); } bool doGPU = GetRecoStepsGPU() & RecoStep::TPCSectorTracking; @@ -100,7 +100,7 @@ int32_t GPUChainTracking::RunTPCTrackingSectors_internal() bool initializeOccMap = param().rec.tpc.occupancyMapTimeBins || param().rec.tpc.sysClusErrorC12Norm; if (doGPU) { // Copy Tracker Object to GPU Memory - if (GetProcessingSettings().debugLevel >= 3) { + if (GetProcessingSettings().debugLevel >= 3 && !GetProcessingSettings().debugSilent) { GPUInfo("Copying Tracker objects to GPU"); } if (PrepareProfile()) { @@ -147,7 +147,7 @@ int32_t GPUChainTracking::RunTPCTrackingSectors_internal() GPUTPCTracker& trkShadow = doGPU ? processorsShadow()->tpcTrackers[iSector] : trk; int32_t useStream = StreamForSector(iSector); - if (GetProcessingSettings().debugLevel >= 3) { + if (GetProcessingSettings().debugLevel >= 3 && !GetProcessingSettings().debugSilent) { GPUInfo("Creating Sector Data (Sector %d)", iSector); } TransferMemoryResourcesToGPU(RecoStep::TPCSectorTracking, &trk, useStream); @@ -215,7 +215,7 @@ int32_t GPUChainTracking::RunTPCTrackingSectors_internal() } TransferMemoryResourceLinkToHost(RecoStep::TPCSectorTracking, trk.MemoryResCommon(), useStream, &mEvents->sector[iSector]); streamMap[iSector] = useStream; - if (GetProcessingSettings().debugLevel >= 3) { + if (GetProcessingSettings().debugLevel >= 3 && !GetProcessingSettings().debugSilent) { GPUInfo("Sector %u, Number of tracks: %d", iSector, *trk.NTracks()); } DoDebugAndDump(RecoStep::TPCSectorTracking, GPUChainTrackingDebugFlags::TPCSectorTracks, trk, &GPUTPCTracker::DumpTrackHits, *mDebugFile); @@ -266,7 +266,7 @@ int32_t GPUChainTracking::RunTPCTrackingSectors_internal() mRec->SetNActiveThreadsOuterLoop(1); } - if (param().rec.tpc.extrapolationTracking && GetProcessingSettings().debugLevel >= 3) { + if (param().rec.tpc.extrapolationTracking && GetProcessingSettings().debugLevel >= 3 && !GetProcessingSettings().debugSilent) { for (uint32_t iSector = 0; iSector < NSECTORS; iSector++) { GPUInfo("Sector %d - Tracks: Local %d Extrapolated %d - Hits: Local %d Extrapolated %d", iSector, processors()->tpcTrackers[iSector].CommonMemory()->nLocalTracks, processors()->tpcTrackers[iSector].CommonMemory()->nTracks, processors()->tpcTrackers[iSector].CommonMemory()->nLocalTrackHits, processors()->tpcTrackers[iSector].CommonMemory()->nTrackHits); @@ -285,7 +285,7 @@ int32_t GPUChainTracking::RunTPCTrackingSectors_internal() TransferMemoryResourcesToHost(RecoStep::TPCSectorTracking, &processors()->tpcTrackers[i], -1, true); } } - if (GetProcessingSettings().debugLevel >= 2) { + if (GetProcessingSettings().debugLevel >= 2 && !GetProcessingSettings().debugSilent) { GPUInfo("TPC Sector Tracker finished"); } mRec->PopNonPersistentMemory(RecoStep::TPCSectorTracking, qStr2Tag("TPCSLTRK")); diff --git a/GPU/GPUTracking/Global/GPUChainTrackingTRD.cxx b/GPU/GPUTracking/Global/GPUChainTrackingTRD.cxx index 7489f9eb87c09..038b98066a848 100644 --- a/GPU/GPUTracking/Global/GPUChainTrackingTRD.cxx +++ b/GPU/GPUTracking/Global/GPUChainTrackingTRD.cxx @@ -189,7 +189,7 @@ int32_t GPUChainTracking::DoTRDGPUTracking(T* externalInstance) TransferMemoryResourcesToHost(RecoStep::TRDTracking, Tracker, useStream); SynchronizeStream(useStream); - if (GetProcessingSettings().debugLevel >= 2) { + if (GetProcessingSettings().debugLevel >= 2 && !GetProcessingSettings().debugSilent) { GPUInfo("GPU TRD tracker Finished"); } return (0); diff --git a/GPU/GPUTracking/Global/GPUChainTrackingTransformation.cxx b/GPU/GPUTracking/Global/GPUChainTrackingTransformation.cxx index be73dfab87faa..e5ca0f600d5d8 100644 --- a/GPU/GPUTracking/Global/GPUChainTrackingTransformation.cxx +++ b/GPU/GPUTracking/Global/GPUChainTrackingTransformation.cxx @@ -53,7 +53,7 @@ int32_t GPUChainTracking::ConvertNativeToClusterData() TransferMemoryResourceLinkToGPU(RecoStep::TPCConversion, mInputsHost->mResourceClusterNativeAccess, 0); transferClusters = true; } - if (GetProcessingSettings().debugLevel >= 3) { + if (GetProcessingSettings().debugLevel >= 3 && !GetProcessingSettings().debugSilent) { GPUInfo("Early transform inactive, skipping TPC Early transformation kernel, transformed on the fly during sector data creation / refit"); } if (transferClusters) { diff --git a/GPU/GPUTracking/qa/GPUQA.cxx b/GPU/GPUTracking/qa/GPUQA.cxx index bd0deed3f0fd3..de8a174f0063a 100644 --- a/GPU/GPUTracking/qa/GPUQA.cxx +++ b/GPU/GPUTracking/qa/GPUQA.cxx @@ -895,7 +895,7 @@ void GPUQA::RunQA(bool matchOnly, const std::vector* tracksEx if (!mQAInitialized) { throw std::runtime_error("QA not initialized"); } - if (mTracking && mTracking->GetProcessingSettings().debugLevel >= 2) { + if (mTracking && mTracking->GetProcessingSettings().debugLevel >= 2 && !mTracking->GetProcessingSettings().debugSilent) { GPUInfo("Running QA - Mask %d, Efficiency %d, Resolution %d, Pulls %d, Cluster Attachment %d, Track Statistics %d, Cluster Counts %d", mQATasks, (int32_t)(mQATasks & taskTrackingEff), (int32_t)(mQATasks & taskTrackingRes), (int32_t)(mQATasks & taskTrackingResPull), (int32_t)(mQATasks & taskClusterAttach), (int32_t)(mQATasks & taskTrackStatistics), (int32_t)(mQATasks & taskClusterCounts)); } if (!clNative && mTracking) { From 0a2416034b5581757240582b7a5cf2010e1f572a Mon Sep 17 00:00:00 2001 From: David Rohr Date: Sat, 28 Nov 2026 13:53:50 +0100 Subject: [PATCH 11/12] GPU Standalone: Add --benchmark mode --- GPU/GPUTracking/Base/GPUReconstruction.h | 1 + GPU/GPUTracking/Base/GPUReconstructionCPU.cxx | 1 + .../cpudevice/GPUReconstructionCPUDevice.h | 1 + .../Base/cuda/GPUReconstructionCUDA.h | 1 + .../GPUSettingsListStandalone.template | 1 + .../Standalone/Benchmark/standalone.cxx | 80 ++++- GPU/documentation/README.md | 3 + GPU/documentation/benchmark.md | 304 ++++++++++++++++++ 8 files changed, 384 insertions(+), 8 deletions(-) create mode 100644 GPU/documentation/benchmark.md diff --git a/GPU/GPUTracking/Base/GPUReconstruction.h b/GPU/GPUTracking/Base/GPUReconstruction.h index f83eeaf3f31f6..b9ad0d96904f3 100644 --- a/GPU/GPUTracking/Base/GPUReconstruction.h +++ b/GPU/GPUTracking/Base/GPUReconstruction.h @@ -206,6 +206,7 @@ class GPUReconstruction // Getters / setters for parameters DeviceType GetDeviceType() const; bool IsGPU() const { return GetDeviceType() != DeviceType::INVALID_DEVICE && GetDeviceType() != DeviceType::CPU; } + virtual bool backendSupportsRTC() const { return false; } const GPUParam& GetParam() const; const GPUConstantMem& GetConstantMem() const { return *mHostConstantMem; } const GPUTrackingInOutPointers GetIOPtrs() const; diff --git a/GPU/GPUTracking/Base/GPUReconstructionCPU.cxx b/GPU/GPUTracking/Base/GPUReconstructionCPU.cxx index 72f148df01f60..6b7a11f246c23 100644 --- a/GPU/GPUTracking/Base/GPUReconstructionCPU.cxx +++ b/GPU/GPUTracking/Base/GPUReconstructionCPU.cxx @@ -357,6 +357,7 @@ int32_t GPUReconstructionCPU::RunChains() } } } + mStatKernelTime = kernelTotal * 1000000. / mStatNEvents; // Average kernel time per run in us, like mStatWallTime, only with debugLevel >= 1 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/cpudevice/GPUReconstructionCPUDevice.h b/GPU/GPUTracking/Base/cpudevice/GPUReconstructionCPUDevice.h index 8ef4973c9cad4..745a01d7e377f 100644 --- a/GPU/GPUTracking/Base/cpudevice/GPUReconstructionCPUDevice.h +++ b/GPU/GPUTracking/Base/cpudevice/GPUReconstructionCPUDevice.h @@ -39,6 +39,7 @@ class GPUReconstructionCPUDevice : public GPUReconstructionProcessing::KernelInt public: GPUReconstructionCPUDevice(const GPUSettingsDeviceBackend& cfg); ~GPUReconstructionCPUDevice() override; + bool backendSupportsRTC() const override { return true; } template void runKernelBackend(const krnlSetupTime& _xyz, const Args&... args); diff --git a/GPU/GPUTracking/Base/cuda/GPUReconstructionCUDA.h b/GPU/GPUTracking/Base/cuda/GPUReconstructionCUDA.h index 225a381defee6..3acf2d9c58af5 100644 --- a/GPU/GPUTracking/Base/cuda/GPUReconstructionCUDA.h +++ b/GPU/GPUTracking/Base/cuda/GPUReconstructionCUDA.h @@ -42,6 +42,7 @@ class GPUReconstructionCUDA : public GPUReconstructionProcessing::KernelInterfac ~GPUReconstructionCUDA() override; void PrintKernelOccupancies() override; + bool backendSupportsRTC() const override { return true; } virtual int32_t GPUChkErrInternal(const int64_t retval, const char* file, int32_t line) const override; template diff --git a/GPU/GPUTracking/Definitions/GPUSettingsListStandalone.template b/GPU/GPUTracking/Definitions/GPUSettingsListStandalone.template index 30317b3a2a251..5c8f67db81548 100644 --- a/GPU/GPUTracking/Definitions/GPUSettingsListStandalone.template +++ b/GPU/GPUTracking/Definitions/GPUSettingsListStandalone.template @@ -57,6 +57,7 @@ AddOption(nEvents, int32_t, -1, "", 'n', "Number of events to process (-1; all)" AddOption(runs, int32_t, 1, "runs", 'r', "Number of iterations to perform (repeat each event)", min(0)) AddOption(runs2, int32_t, 1, "runsExternal", 0, "Number of iterations to perform (repeat full processing)", min(1)) AddOption(runsInit, int32_t, 1, "", 0, "Number of initial iterations excluded from average", min(0)) +AddOption(benchmark, const char*, "", "", 0, "Benchmark mode [sync|async|combined|alldetectors]-[gpu|cpu]-[wall|kernel]: sets and checks the options for it, needs -n (iterate over events) or --runs (repeat one event)") AddOption(eventsDir, const char*, "pp", "events", 'e', "Directory with events to process", message("Reading events from Directory %s")) AddOption(absoluteEventsDir, bool, false, "", 0, "Events directory is absolute, and not inside './events/'") AddOption(noEvents, bool, false, "", 0, "Run without data (e.g. for field visualization)") diff --git a/GPU/GPUTracking/Standalone/Benchmark/standalone.cxx b/GPU/GPUTracking/Standalone/Benchmark/standalone.cxx index e12c948b3d6b3..818c6ea5646f4 100644 --- a/GPU/GPUTracking/Standalone/Benchmark/standalone.cxx +++ b/GPU/GPUTracking/Standalone/Benchmark/standalone.cxx @@ -60,6 +60,7 @@ #include #include #include +#include #ifndef _WIN32 #include @@ -95,6 +96,7 @@ std::unique_ptr eventDisplay; std::unique_ptr tf; int32_t nEventsInDirectory = 0; std::atomic nIteration, nIterationEnd; +bool benchmark = false, benchmarkGPU = false; // From configStandalone.benchmark std::vector ioPtrEvents; std::vector ioMemEvents; @@ -118,6 +120,47 @@ int32_t ReadConfiguration(int argc, char** argv) printf("Config Dump before ReadConfiguration\n"); qConfig::qConfigPrint(); } + benchmark = configStandalone.benchmark && configStandalone.benchmark[0]; + if (benchmark) { // comes first, affects below options + std::istringstream benchmarkStream(configStandalone.benchmark); + std::string mode, dev, timing; + std::getline(std::getline(std::getline(benchmarkStream, mode, '-'), dev, '-'), timing); + const bool gpu = benchmarkGPU = dev == "gpu", kernel = timing == "kernel"; + const bool nSet = configStandalone.nEvents != -1 && configStandalone.nEvents != configStandalone.StartEvent + 1; + const bool pipeline = gpu && (mode == "sync" || mode == "combined") && !kernel; + const int32_t iterations = nSet ? configStandalone.nEvents - configStandalone.StartEvent : configStandalone.runs; + const std::pair checks[] = { + {(mode != "sync" && mode != "async" && mode != "combined" && mode != "alldetectors") || (!gpu && dev != "cpu") || (!kernel && timing != "wall"), "format must be [sync|async|combined|alldetectors]-[gpu|cpu]-[wall|kernel]"}, + {(configStandalone.testSync && mode != "sync") || (configStandalone.testAsync && mode != "async") || configStandalone.testSyncAsync, "--sync / --async / --syncAsync contradict the mode"}, + {configStandalone.recoSteps != -1, "--recoSteps must not be set"}, + {configStandalone.proc.debugLevel != -1 && configStandalone.proc.debugLevel != kernel, "--debug contradicts the timing mode"}, + {!nSet && configStandalone.runs == 1, "-n or --runs required"}, + {nSet && configStandalone.runs != 1 && configStandalone.runs != iterations, "-n (minus -s) and --runs differ"}, + {iterations < (pipeline ? 10 : 5), "at least 5 iterations needed, 10 with double pipeline"}}; + for (const auto& [failed, msg] : checks) { + if (failed) { + printf("Invalid --benchmark %s: %s\n", configStandalone.benchmark, msg); + return 1; + } + } + configStandalone.testSync = mode == "sync"; + configStandalone.testAsync = mode == "async"; + configStandalone.runGPU = gpu ? 2 : 0; + configStandalone.runGPUforce = true; + configStandalone.runTRD = mode == "alldetectors" ? 1 : (mode == "async" ? configStandalone.runTRD : 0); + configStandalone.timeFrameTime = !kernel; + configStandalone.proc.debugLevel = kernel; + configStandalone.proc.debugSilent = 1; + configStandalone.proc.doublePipeline = pipeline; + if (gpu) { + configStandalone.proc.forceMemoryPoolSize = configStandalone.proc.forceMemoryPoolSize == 1 ? 12000000000 : configStandalone.proc.forceMemoryPoolSize; + configStandalone.inputcontrolmem = configStandalone.inputcontrolmem ? configStandalone.inputcontrolmem : 6000000000; + configStandalone.outputcontrolmem = configStandalone.outputcontrolmem ? configStandalone.outputcontrolmem : 10000000000; + } + configStandalone.runs = nSet && !pipeline ? 1 : iterations; + configStandalone.nEvents = nSet ? configStandalone.nEvents : configStandalone.StartEvent + 1; + configStandalone.preloadEvents |= nSet && pipeline; + } if (configStandalone.proc.debugLevel == -1) { configStandalone.proc.debugLevel = 0; } @@ -670,6 +713,10 @@ int32_t LoadEvent(int32_t iEvent, int32_t x) return 1; } } + if (benchmark && ((configStandalone.testAsync ? !chainTracking->mIOPtrs.tpcCompressedClusters : !chainTracking->mIOPtrs.tpcZS) || (configStandalone.runTRD > 0 && !chainTracking->mIOPtrs.nTRDTracklets))) { + printf("Benchmark needs ZS raw input for sync / combined / alldetectors, compressed clusters for async, and TRD tracklets for alldetectors\n"); + return 1; + } bool encodeZS = configStandalone.encodeZS == -1 ? (chainTracking->mIOPtrs.tpcPackedDigits && !chainTracking->mIOPtrs.tpcZS) : (bool)configStandalone.encodeZS; bool zsFilter = configStandalone.zsFilter == -1 ? (!encodeZS && chainTracking->mIOPtrs.tpcPackedDigits && !chainTracking->mIOPtrs.tpcZS) : (bool)configStandalone.zsFilter; if (encodeZS || zsFilter) { @@ -741,7 +788,10 @@ int32_t RunBenchmark(GPUReconstruction* recUse, GPUChainTracking* chainTrackingU printf("Run %d (thread %d)\n", iteration + 1, threadId); } if (configStandalone.runsInit > 0 && configStandalone.proc.debugCSV.empty()) { - recUse->SetResetTimers(iRun < configStandalone.runsInit); + recUse->SetResetTimers(iRun + (benchmark ? iEvent - configStandalone.StartEvent : 0) < configStandalone.runsInit); + } + if (benchmark && !configStandalone.proc.doublePipeline) { + recUse->SetDebugLevelTmp(-100, iteration != runs - 1 || iEvent != configStandalone.nEvents - 1); } if (configStandalone.outputcontrolmem) { recUse->SetOutputControl(threadId ? outputmemoryPipeline.get() : outputmemory.get(), configStandalone.outputcontrolmem); @@ -874,6 +924,13 @@ int32_t main(int argc, char** argv) printf("Error initializing GPUReconstruction\n"); return 1; } + if (benchmark && rec->IsGPU() != benchmarkGPU) { + printf("Invalid --benchmark %s: device type contradicts the benchmark\n", configStandalone.benchmark); + return 1; + } + if (benchmark && benchmarkGPU && rec->backendSupportsRTC()) { + configStandalone.proc.rtc.enable = configStandalone.proc.rtc.cacheOutput = true; + } rec->SetDebugLevelTmp(configStandalone.proc.debugLevel); chainTracking = rec->AddChain(); if (configStandalone.testSyncAsync) { @@ -905,11 +962,6 @@ int32_t main(int argc, char** argv) return 1; } - std::unique_ptr pipelineThread; - if (configStandalone.proc.doublePipeline) { - pipelineThread.reset(new std::thread([]() { rec->RunPipelineWorker(); })); - } - if (configStandalone.seed == -1) { std::random_device rd; configStandalone.seed = (int32_t)rd(); @@ -947,6 +999,9 @@ int32_t main(int argc, char** argv) if (nEvents == -1 || nEvents > nEventsInDirectory) { if (nEvents >= 0) { printf("Only %d events available in directory %s (%d events requested)\n", nEventsInDirectory, eventsDir.c_str(), nEvents); + if (benchmark) { + return 1; + } } nEvents = nEventsInDirectory; } @@ -964,13 +1019,21 @@ int32_t main(int argc, char** argv) printf("Preloading events%s", configStandalone.proc.debugLevel >= 2 ? "\n" : ""); fflush(stdout); for (int32_t i = 0; i < nEvents - configStandalone.StartEvent; i++) { - LoadEvent(configStandalone.StartEvent + i, i); + if (LoadEvent(configStandalone.StartEvent + i, i)) { + return 1; + } printf(configStandalone.proc.debugLevel >= 2 ? "Loading event %d\n" : " %d", i + configStandalone.StartEvent); fflush(stdout); } printf("\n"); } + std::unique_ptr pipelineThread; + if (configStandalone.proc.doublePipeline) { + pipelineThread.reset(new std::thread([]() { rec->RunPipelineWorker(); })); + } + + int32_t retVal = 1; for (int32_t iRunOuter = 0; iRunOuter < configStandalone.runs2; iRunOuter++) { if (configStandalone.QA.inputHistogramsOnly) { chainTracking->ForceInitQA(); @@ -1085,6 +1148,7 @@ int32_t main(int argc, char** argv) printf("Total: %zu clusters, %zu tracks\n", nClustersTotal, nTracksTotal); } } + retVal = 0; breakrun: if (rec->GetProcessingSettings().memoryAllocationStrategy == GPUMemoryResource::ALLOCATION_GLOBAL) { @@ -1119,5 +1183,5 @@ int32_t main(int argc, char** argv) printf("Press a key to exit!\n"); getchar(); } - return (0); + return retVal; } diff --git a/GPU/documentation/README.md b/GPU/documentation/README.md index 59dc9bf6ad82d..84e3a9398ff1b 100644 --- a/GPU/documentation/README.md +++ b/GPU/documentation/README.md @@ -6,6 +6,9 @@ - Instructions how to build and run the standalone benchmark. - Instructions how to extract data sets for the standalone benchmark from real data or using simulation. +[benchmark.md](https://github.com/AliceO2Group/AliceO2/blob/dev/GPU/documentation/benchmark.md) : +- How to benchmark the GPU reconstruction with the benchmark mode of the standalone benchmark (`--benchmark`), how to read the results, and what is measured. + [deterministic-mode.md](https://github.com/AliceO2Group/AliceO2/blob/dev/GPU/documentation/deterministic-mode.md) : - Instructions how to use the deterministic mode for both the standalone benchmark and O2. diff --git a/GPU/documentation/benchmark.md b/GPU/documentation/benchmark.md new file mode 100644 index 0000000000000..88285b60f1183 --- /dev/null +++ b/GPU/documentation/benchmark.md @@ -0,0 +1,304 @@ +# Benchmark mode of the standalone benchmark + +The standalone benchmark (`./ca`, or `o2-gpu-standalone-benchmark` in O2) has a benchmark mode `--benchmark `, which sets and checks all options needed for a reproducible performance measurement of the GPU reconstruction, and prints the timing only once at the end. How to build the standalone benchmark and how to obtain datasets is described in [build-standalone.md](https://github.com/AliceO2Group/AliceO2/blob/dev/GPU/documentation/build-standalone.md). + +# 1. Syntax + +``` +./ca -e --benchmark [sync|async|combined|alldetectors]-[gpu|cpu]-[wall|kernel] (--runs N | -n N) [--gpuType CUDA|HIP|OCL|CPUDEVICE|...] [-s S] +``` + +The benchmark string has 3 parts, separated by `-`: + +| Part | Value | Meaning | +|------|-------|---------| +| Processing mode | `sync` | Synchronous reconstruction as online (`--sync`): ZS raw data in, cluster finding, TPC tracking, compression. | +| | `async` | Asynchronous reconstruction (`--async`): compressed clusters (CTF) in, decoding, TPC tracking with the full settings. | +| | `combined` | Same input and steps as `sync`, but neither the sync nor the async settings are applied (default settings). | +| | `alldetectors` | Like `combined`, but with TRD tracking. Requires TPC ZS raw data and TRD tracklets in the dataset. | +| Device | `gpu` | Run on a GPU backend (`-g`). CPUDevice counts as GPU. | +| | `cpu` | Run on the CPU backend (`-c`). | +| Timing | `wall` | Measure the wall time of the processing of a time frame (TF) (`--debug 0`). | +| | `kernel` | Measure the time of the individual GPU kernels / CPU tasks (`--debug 1`). | + +Options that must or may be given in addition: + +- `--runs N` or `-n N` (one of them is required): + - `--runs N`: process the same TF `N` times (TF number `-s`, default 0). + - `-n N`: process the TFs `s` to `N - 1` (`-n` is the end index, not the count, the number of iterations is `N - s`), each one once. With double pipeline (see below) they are preloaded and processed round-robin in the pipeline. + - Both may be given if they agree (`--runs` = `N - s`); `-n s+1` (a single TF) may be combined with any `--runs`. + - At least 5 iterations are required, at least 10 with double pipeline. The first iteration is excluded from the average (`--runsInit`, default 1), with double pipeline the first 2 iterations. + - The dataset must contain at least `N` TFs with `-n`. +- `--gpuType`: the GPU backend for `gpu` (`CUDA`, `HIP`, `OCL`, `METAL`, `CPUDEVICE`); default `AUTO` takes the first available one of CUDA, HIP, OpenCL, Metal. With `cpu`, `--gpuType` must be `AUTO` or `CPU`. +- `-s S`: first TF (default 0). +- `-e `: the input must match the processing mode: TPC ZS raw data (`tpcZS`) for `sync`, `combined` and `alldetectors`, compressed clusters for `async` (e.g. the `*-ctf` datasets). Otherwise the benchmark fails at loading the TF. +- `--runsExternal N`: repeat the whole benchmark `N` times (each repetition reports its own result). + +The following are checked and give an error: +- an unknown benchmark string, +- `--sync` / `--async` not matching the processing mode, `--syncAsync`, +- `--recoSteps` (the steps must not be changed, `--recoStepsGPU` is allowed), +- `--debug` other than the value of the timing mode (0 for `wall`, 1 for `kernel`), +- neither `-n` nor `--runs`, `-n` and `--runs` disagreeing, too few iterations, not enough TFs in the dataset, +- a device that does not match the benchmark (checked after the backend is created, e.g. `--gpuType CPU` with `gpu`), +- input data not matching the processing mode. + +`ca` returns exit code 1 for all errors. + +## Pinning CPU cores, memory, and GPUs to one NUMA domain + +On multi-socket servers and on CPUs with several NUMA domains, it is important to pin the CPU cores and the host memory of the process, and to select a GPU attached to the same NUMA domain. Otherwise host memory accesses and DMA transfers cross the socket interconnect, and the results fluctuate and are too slow. E.g. for an AMD GPU: + +``` +ROCR_VISIBLE_DEVICES=0 numactl --membind 0 --cpunodebind 0 ./ca -e 50kHz --benchmark sync-gpu-wall --runs 10 +``` + +and for an NVIDIA GPU: + +``` +CUDA_VISIBLE_DEVICES=0 numactl --membind 0 --cpunodebind 0 ./ca -e 50kHz --benchmark sync-gpu-wall --runs 10 +``` + +The NUMA domain of a GPU can be found with `nvidia-smi topo -m`, `rocm-smi --showtoponuma`, `lstopo`, or `cat /sys/bus/pci/devices//numa_node`. + +Selecting the GPU with `ROCR_VISIBLE_DEVICES` / `HIP_VISIBLE_DEVICES` / `CUDA_VISIBLE_DEVICES` is preferable to the `--gpuDevice` option of the standalone benchmark: with `--gpuDevice`, the runtime still sees all GPUs and maps their memory into the process address space (and the backend creates a context on each GPU while selecting the device), while with the environment variable the runtime sees only the selected GPU, so less memory is mapped and less is initialized. + +The CPU benchmark should be pinned in the same way; the number of CPU threads can be set with `--PROCnThreads` (default: `TBB_NUM_THREADS` or `OMP_NUM_THREADS` if set, otherwise all cores of the affinity mask, i.e. respecting `numactl`). + +# 2. Output examples and how to read them + +The examples below were made on the `50kHz` dataset (one 32-orbit TF of Pb-Pb collisions at 50 kHz, ZS raw data) on a 32-core CPU, with the `CPUDEVICE` backend standing in for a GPU (it runs the GPU code path with the CPU kernels on the host). The output of a real GPU backend has the same format, only the times differ. `[...]` marks removed lines. + +## sync-cpu-wall + +``` +$ ./ca -e 50kHz --benchmark sync-cpu-wall --runs 5 +Reading events from Directory 50kHz +Created GPUReconstruction instance for device type CPU (1) +Read event settings from dir events/50kHz/ (solenoidBz: 5.006668, constBz 0, maxTimeBin 14257) +Standalone Test Framework for CA Tracker - Using CPU +Using random seed -1497483323 +Loading time: 263,363 us +Processing Event 0 +Run 1 (thread 0) +Event has 253799 8kb TPC ZS pages (version 4), 888107032 digits +Event has 92348578 TPC Clusters, 0 TRD Tracklets +Output Tracks (O2): 757312 - Clusters: 46097261 / 92348578 / 86121328 / 0 / 0 (attached / total / compressed / fitted / adjacent) +[... Run 2 to 4 ...] +Run 5 (thread 0) +Event has 253799 8kb TPC ZS pages (version 4), 888107032 digits +Event has 92348578 TPC Clusters, 0 TRD Tracklets +Output Tracks (O2): 757502 - Clusters: 46104404 / 92348578 / 86121895 / 0 / 0 (attached / total / compressed / fitted / adjacent) +Total Wall Time: 27172700 us (avergage of 4 runs) +Sync phase: 31.64 sec per 32 orbit TF, 11120.1 GPUs required (Measured wall time - Extrapolated from 92348578 clusters to 107546607) +``` + +- Each run prints the input (`Event has ...`: ZS pages, digits, clusters found by the cluster finder) and the output (`Output Tracks`: tracks and attached / total / compressed clusters). The track and cluster counts vary slightly between runs, since the reconstruction is not deterministic (see [deterministic-mode.md](https://github.com/AliceO2Group/AliceO2/blob/dev/GPU/documentation/deterministic-mode.md)). They are a sanity check, e.g. when comparing backends or versions. +- `Total Wall Time` is the result: 27.2 s per TF, averaged over runs 2 to 5 (`average of 4 runs`, the first run is excluded). +- The `Sync phase` line extrapolates it from the 92.3 M clusters of this TF to the 107.5 M clusters of an average 50 kHz Pb-Pb TF: 31.6 s, i.e. 11120 such CPUs (with 32 cores each) would be needed to process 50 kHz Pb-Pb in real time. For a CPU benchmark, read "GPUs" as "CPUs". + +## sync-gpu-wall (with double pipeline) + +``` +$ ./ca -e 50kHz --benchmark sync-gpu-wall --gpuType CPUDEVICE --runs 10 +Reading events from Directory 50kHz +GPU Tracker library loaded and GPU tracker object created sucessfully +Created GPUReconstruction instance for device type CPUDEVICE (6) +Created GPUReconstruction instance for device type CPUDEVICE (6) (slave) +Read event settings from dir events/50kHz/ (solenoidBz: 5.006668, constBz 0, maxTimeBin 14257) +Standalone Test Framework for CA Tracker - Using GPU +Using RTC cache file rtc.cpudevice.cache.0854D04A70 +CPUDevice Initialisation successfull (32 blocks, 8 streams, 4294967296 / 12000000000 bytes host / device memory, Constant memory 26920) +GPU Tracker initialization successfull +CPUDevice Initialisation successfull (from master) +Rescaling buffer size limits from 20500000000 to 12000000000 bytes of memory (factor 0.585366) +Rescaling buffer size limits from 20500000000 to 11499264064 bytes of memory (factor 0.560940) +Using random seed 95342693 +Loading time: 261,887 us +Processing Event 0 in Pipeline 10 times +Run 1 (thread 0) +Event has 253799 8kb TPC ZS pages (version 4), 888107032 digits +Event has 92327129 TPC Clusters, 0 TRD Tracklets +Output Tracks (O2): 757383 - Clusters: 46087384 / 92327129 / 86100255 / 0 / 0 (attached / total / compressed / fitted / adjacent) +Run 2 (thread 0) +Event has 253799 8kb TPC ZS pages (version 4), 888107032 digits +Event has 92327129 TPC Clusters, 0 TRD Tracklets +Output Tracks (O2): 757330 - Clusters: 46084191 / 92327129 / 86102928 / 0 / 0 (attached / total / compressed / fitted / adjacent) +Run 3 (thread 0) +Run 4 (thread 1) +Event has 253799 8kb TPC ZS pages (version 4), 888107032 digits +Event has 92327129 TPC Clusters, 0 TRD Tracklets +Event has 253799 8kb TPC ZS pages (version 4), 888107032 digits +Event has 92327129 TPC Clusters, 0 TRD Tracklets +Output Tracks (O2): 757356 - Clusters: 46084848 / 92327129 / 86100156 / 0 / 0 (attached / total / compressed / fitted / adjacent) +Run 5 (thread 0) +[... until Run 10 ...] +Pipeline wall time: 211.651554, 8 iterations, 26.456444 per event +Sync phase: 30.82 sec per 32 orbit TF, 10829.5 GPUs required (Measured wall time - Extrapolated from 92327129 clusters to 107546607) +Maximum Memory Allocation: Host 1,193,148,416 / Device 10,904,500,224 +``` + +- Two instances are created (the second one is the `slave`), both with RTC: here the compiled code was found in the cache (`Using RTC cache file`), otherwise the compilation runs first (`Starting ... RTC Compilation`, `RTC Compilation finished (... seconds)`, `Storing RTC compilation result in cache file ...`). +- `Rescaling buffer size limits`: the buffer size estimates are scaled to the memory pool given by `--memSize`. This is normal. +- Runs 1 and 2 are the warm-up, one per instance, one after the other. From run 3 on, the two instances (`thread 0` / `thread 1`) run concurrently, so their output lines interleave. +- `Pipeline wall time` is the result: 211.7 s for the 8 pipelined iterations (runs 3 to 10), 26.5 s per TF. This is the throughput, it includes the overlap of the input / output of one TF with the processing of the other. No `Total Wall Time` is printed in this mode. +- The `Sync phase` line extrapolates the pipeline time per TF as above. +- `Maximum Memory Allocation`: peak use of the host and device memory pools, to check how much margin `--memSize` has (10.9 GB of 12 GB here). + +## sync-gpu-kernel + +``` +$ ./ca -e 50kHz --benchmark sync-gpu-kernel --gpuType CPUDEVICE --runs 5 +[...] +Memory ptrs: Device (12000000000 bytes): 0x7f6703f4f040 - Host (2147483648 bytes): 0x7f6683f4e040 +Using RTC cache file rtc.cpudevice.cache.0854D04A70 +Loaded 104 CPUDevice RTC kernels from 104 libraries +CPUDevice Initialisation successfull (32 blocks, 8 streams, 2147483648 / 12000000000 bytes host / device memory, Constant memory 26920) +GPU Tracker initialization successfull +Rescaling buffer size limits from 20500000000 to 12000000000 bytes of memory (factor 0.585366) +Enabled Reconstruction Steps: 0x7ffffcef (on GPU: 0x7ffffcef) - TPC Transformation (G) - TPC Sector Tracking (G) - TPC Track Merging and Fit (G) - TPC Compression (G) - [...] +Using random seed -473613791 +Loading time: 265,060 us +Processing Event 0 +Run 1 (thread 0) +[... Run 1 to 5 as above ...] +Execution Time: Task (K 1632x): GPUMemClean16 Time: 1,207,979 us +Execution Time: Task (K 576x): GPUTPCCFDecodeZSDenseLink Time: 1,154,337 us +Execution Time: Task (K 144x): GPUTPCCFCheckPadBaseline Time: 211,133 us ( 19.821 GB/s - 4,184,893,440 bytes - 29,061,760 per call) +Execution Time: Task (K 576x): GPUTPCCFPeakFinder Time: 2,028,258 us +[...] +Execution Time: Task (K 144x): GPUTPCTrackletConstructor Time: 5,525,946 us +[...] +Execution Time: Task (K 4x): GPUTPCGMMergerTrackFit_def Time: 2,511,689 us +[...] +Execution Time: Task (K 4x): GPUTPCCompressionKernels_step1unattached Time: 226,217 us +Execution Time: Step : Tasks TPC Transformation Time: 0 us ( Total Time : 2 us, CPU Time : 9 us, 5.47x ) +Execution Time: Step : Tasks TPC Sector Tracking Time: 7,192,605 us ( Total Time : 7,231,439 us, CPU Time : 153,442,086 us, 21.22x ) +Execution Time: Step (D 148x): DMA to GPU TPC Sector Tracking Time: 1,620 us ( 0.279 GB/s - 451,584 bytes - 3,051 per call) +Execution Time: Step (D 292x): DMA to Host TPC Sector Tracking Time: 3,179 us ( 0.003 GB/s - 8,176 bytes - 28 per call) +Execution Time: Step : Tasks TPC Track Merging and Fit Time: 8,146,231 us ( Total Time : 8,348,434 us, CPU Time : 199,641,803 us, 23.91x ) +[...] +Execution Time: Step : Tasks TPC Cluster Finding Time: 9,385,483 us ( Total Time : 11,180,328 us, CPU Time : 254,368,064 us, 22.75x ) +Execution Time: Step (D 13264x): DMA to GPU TPC Cluster Finding Time: 525,526 us ( 4.003 GB/s - 2,103,499,528 bytes - 158,587 per call) +Execution Time: Step (D 2352x): DMA to Host TPC Cluster Finding Time: 129,677 us ( 8.545 GB/s - 1,108,059,180 bytes - 471,113 per call) +Execution Time: General Step : Prepare Time: 17,015 us +Execution Time: Total : Total Kernel Time: 25,403,766 us (avergage of 4 runs) +Execution Time: Total : Total Wall Time: 49,756,826 us ( CPU Time : 1,283,795,429 us, 25.80x ) (avergage of 4 runs) +Maximum Memory Allocation: Host 687,669,248 / Device 10,403,805,184 +``` + +- The timing table is printed once, after the last run, as average per TF over runs 2 to 5. The counts (`K 576x`) are summed over these 4 runs, i.e. per TF the kernel `GPUTPCCFPeakFinder` runs 144 times (once per sector and cluster-finder fragment). +- `Task (K ...)` lines: time per TF of each kernel, summed over all its calls; for some kernels also the memory bandwidth. Use them to find the expensive kernels, and to compare kernels between versions or GPUs. +- `Step ... Tasks` lines: per reconstruction step the summed kernel time, the total time of the step (incl. gaps, transfers and host work, `Total Time`), and the CPU time used by the process during the step with the ratio CPU time / total time (here the CPUDevice kernels use the CPU cores, on a real GPU the ratio is small). +- `Step (D ...)` lines: DMA transfers per step and direction, with number of transfers, time, bandwidth and bytes. Low bandwidth with many small transfers points to inefficient transfers. +- `Total Kernel Time` is the result: 25.4 s per TF of pure kernel time. There is no `Sync phase` extrapolation in `kernel` mode, since the kernel time is not the time needed per TF. +- `Total Wall Time` (49.8 s) is much larger than in the wall benchmark, due to the synchronization after every kernel; it is not a meaningful wall time. +- With the `CPUDEVICE` backend, the `TPC Compression` step shows millions of small DMA transfers to the host: CPUDevice uses the CPU parameters, which gather the compressed clusters to the host element-wise. Real GPUs gather them on the GPU (`COMP_GATHER_MODE` 3) and transfer one block. + +# 3. Settings applied by the benchmark mode, and how to run the benchmarks manually + +The benchmark mode applies these settings (before all other option processing, since they enable further settings): + +| Setting | Value | Condition | +|---------|-------|-----------| +| `--sync` | 1 | `sync` | +| `--async` | 1 | `async` | +| `-g` / `-c`, `--runGPUforce 1` | GPU / CPU, no fall back to the CPU | always | +| `--runTRD` | 0 | `sync`, `combined` | +| `--runTRD` | 1 | `alldetectors` | +| `--tfTime` | 1 | `wall` | +| `--debug` | 0 / 1 | `wall` / `kernel` | +| `--PROCdebugSilent` | 1, cleared for the last iteration without double pipeline | always | +| `--PROCdoublePipeline` | 1 | `gpu` with `sync` or `combined`, and `wall` | +| `--memSize` | 12000000000 | `gpu`, if not set | +| `--inputMemory` | 6000000000 | `gpu`, if not set | +| `--outputMemory` | 10000000000 | `gpu`, if not set | +| `--RTCenable 1 --RTCcacheOutput 1` | | `gpu`, if the backend supports RTC (CUDA, HIP, CPUDevice) | +| `--runs` | 1 with `-n`, `N - s` with `-n` and double pipeline, else as given | always | +| `-n` | `s + 1` with `--runs` | always | +| `--preloadEvents` | 1 | `-n` with double pipeline | + +In addition, the benchmark mode averages the timers over all TFs with `-n` (normally they are reset for each TF), and it checks the input type of each TF. + +The equivalent manual command lines with the CUDA backend (`50kHz` is a dataset with ZS raw data, `50kHz-ctf` the corresponding compressed clusters): + +``` +# sync-gpu-wall +./ca -e 50kHz -g --gpuType CUDA --runGPUforce 1 --sync --runTRD 0 --tfTime --debug 0 --PROCdoublePipeline 1 --memSize 12000000000 --inputMemory 6000000000 --outputMemory 10000000000 --RTCenable 1 --RTCcacheOutput 1 --runs 10 +# sync-gpu-wall with -n 10: iterate over 10 different TFs in the pipeline +./ca -e 50kHz -g --gpuType CUDA --runGPUforce 1 --sync --runTRD 0 --tfTime --debug 0 --PROCdoublePipeline 1 --memSize 12000000000 --inputMemory 6000000000 --outputMemory 10000000000 --RTCenable 1 --RTCcacheOutput 1 -n 10 --runs 10 --preloadEvents +# sync-gpu-kernel +./ca -e 50kHz -g --gpuType CUDA --runGPUforce 1 --sync --runTRD 0 --debug 1 --memSize 12000000000 --inputMemory 6000000000 --outputMemory 10000000000 --RTCenable 1 --RTCcacheOutput 1 --runs 5 +# combined-gpu-wall +./ca -e 50kHz -g --gpuType CUDA --runGPUforce 1 --runTRD 0 --tfTime --debug 0 --PROCdoublePipeline 1 --memSize 12000000000 --inputMemory 6000000000 --outputMemory 10000000000 --RTCenable 1 --RTCcacheOutput 1 --runs 10 +# combined-gpu-kernel +./ca -e 50kHz -g --gpuType CUDA --runGPUforce 1 --runTRD 0 --debug 1 --memSize 12000000000 --inputMemory 6000000000 --outputMemory 10000000000 --RTCenable 1 --RTCcacheOutput 1 --runs 5 +# async-gpu-wall / async-gpu-kernel (no double pipeline, --runTRD unchanged) +./ca -e 50kHz-ctf -g --gpuType CUDA --runGPUforce 1 --async --tfTime --debug 0 --memSize 12000000000 --inputMemory 6000000000 --outputMemory 10000000000 --RTCenable 1 --RTCcacheOutput 1 --runs 5 +./ca -e 50kHz-ctf -g --gpuType CUDA --runGPUforce 1 --async --debug 1 --memSize 12000000000 --inputMemory 6000000000 --outputMemory 10000000000 --RTCenable 1 --RTCcacheOutput 1 --runs 5 +# alldetectors-gpu-wall / alldetectors-gpu-kernel (no double pipeline) +./ca -e -g --gpuType CUDA --runGPUforce 1 --runTRD 1 --tfTime --debug 0 --memSize 12000000000 --inputMemory 6000000000 --outputMemory 10000000000 --RTCenable 1 --RTCcacheOutput 1 --runs 5 +./ca -e -g --gpuType CUDA --runGPUforce 1 --runTRD 1 --debug 1 --memSize 12000000000 --inputMemory 6000000000 --outputMemory 10000000000 --RTCenable 1 --RTCcacheOutput 1 --runs 5 +# The cpu variants: -c instead of the GPU, memory, RTC, and double pipeline options, e.g. sync-cpu-wall / sync-cpu-kernel +./ca -e 50kHz -c --sync --runTRD 0 --tfTime --debug 0 --runs 5 +./ca -e 50kHz -c --sync --runTRD 0 --debug 1 --runs 5 +# combined-cpu-*, async-cpu-*, alldetectors-cpu-*: the same with the mode options of the gpu variants above +``` + +Differences of the manual commands to the benchmark mode: +- `--PROCdebugSilent 1` is left out, since the manual command cannot clear it for the last iteration. The manual commands therefore print the timing of every iteration (each one is the running average of the iterations so far, without the first). The last one is the result. +- With `-n` and without double pipeline, the manual command resets the timers for each TF, so the printed result is that of the last TF only, not the average over the TFs. +- The input type of the TFs is not checked. + +# 4. Meaning of the settings, and what is measured + +- `--sync` / `--async`: apply the settings of the synchronous / asynchronous reconstruction (`GPUChainTracking::ApplySyncSettings`), e.g. without material lookup table and with reduced dEdx and rebuild settings in sync mode, with material lookup table and full dEdx in async mode. Neither for `combined` and `alldetectors`. +- `-g` / `-c` with `--runGPUforce 1`: select the GPU / CPU backend; with `--runGPUforce` the benchmark fails instead of falling back to the CPU if the GPU backend is not available. +- `--runTRD 0` / `1`: disable / enable TRD tracking. The TPC benchmarks (`sync`, `combined`) disable it, since it is not part of the TPC processing and the double pipeline does not support it; `alldetectors` enables it. +- `--debug 0` / `--debug 1`: the timing mode, see below. +- `--PROCdebugSilent 1`: suppress the per-TF output of the debug levels (timing tables, wall time, debug messages), but still run the debug code paths. The benchmark clears it for the last iteration, so the timing is printed once, as average over all iterations except the first. +- `--tfTime`: print the time extrapolated to a 50 kHz Pb-Pb TF (see below), only in `wall` mode. +- `--memSize`: size of the GPU memory pool. The reconstruction allocates all its GPU memory once at initialization and manages it itself, the pool must be large enough for the largest TF. 12 GB are sufficient for 32-orbit 50 kHz Pb-Pb TFs. +- `--inputMemory` / `--outputMemory`: size of the external input / output buffers in host memory, allocated once and registered (page-locked) for the GPU, as O2 does with its shared memory. The input buffer holds the raw input of the TF (not used with `--preloadEvents`), the output buffer the output (tracks, clusters, compressed clusters). With double pipeline, there is one output buffer per pipeline instance. +- `--RTCenable 1 --RTCcacheOutput 1`: run-time compilation (RTC) of the GPU code, as used in O2 production. At initialization, the GPU code is compiled again with the actual configuration, in which all settings marked as RTC options become compile-time constants (`--RTCoptConstexpr`, default on), and code that is not needed in the current mode (e.g. sync) is removed (`--RTCoptSpecialCode`, default: on in sync mode). This gives faster kernels with fewer registers. The compilation takes from tens of seconds to minutes and is not part of the measured time. With `--RTCcacheOutput`, the result is stored in a cache file `rtc..cache.` in `--RTCTECHcacheFolder` (default `./rtccache/`) and reused by the next run with the same configuration (the id is a hash of the source code, the parameters, the compiler commands and versions, and the RTC settings). The log says `Using RTC cache file ...` or `Storing RTC compilation result in cache file ...`. Backends without RTC (OpenCL, Metal) run the precompiled code. Details: [run-time-compilation.md](https://github.com/AliceO2Group/AliceO2/blob/dev/GPU/documentation/run-time-compilation.md). +- `--PROCdoublePipeline 1`: two reconstruction instances (master and slave) share the GPU and its memory pool and process consecutive TFs alternately, as the GPU reconstruction in O2 does in synchronous processing. While one instance finishes its TF (output transfer to the host and host-side finalization), the other one already transfers and processes the input of the next TF, so the GPU does not idle between TFs. A pipeline worker thread of the master coordinates the two instances. This measures the throughput of the GPU in production-like conditions, which is better than the inverse of the wall time of a single TF. Not used for `async` (no such overlap in async processing), `alldetectors`, and `kernel` timing (`--debug 1` synchronizes the GPU after each kernel, so there is no overlap, and the per-kernel times would be split between the instances). Details of the mechanism: the double-pipeline code in `GPUReconstruction` (`EnqueuePipeline`, `RunPipelineWorker`). +- `--preloadEvents`: load all TFs into host memory before the processing, needed for the double pipeline to cycle through different TFs. + +What is measured: +- `wall` without double pipeline: `Total Wall Time` is the wall time of `GPUReconstruction::RunChains()`, i.e. of the complete processing of one TF: transfer of the input to the GPU, all reconstruction steps, transfer of the output to the host. Not included: loading the TF from disk (`Loading time`), the initialization (incl. RTC compilation and memory allocation), and the QA. It is averaged over all iterations except the first (`--runsInit`), which includes one-time overheads (e.g. first kernel launches, page faults). +- `wall` with double pipeline: `Pipeline wall time` is the elapsed time from the start of the 3rd iteration until the end of the last one, divided by the number of these iterations (`runs - 2`). The first 2 iterations (one per instance) run one after the other as warm-up. This is the average time per TF at full pipeline throughput. The `Total Wall Time` of the single TFs is not printed (they overlap). +- `kernel`: `--debug 1` synchronizes after every GPU kernel and measures each kernel with GPU timers (`deviceTimers`) (on the CPU: each task with a host timer), and the time of the DMA transfers per reconstruction step. The output lists per kernel the number of calls and the time per TF, per step the summed kernel time (`Tasks`), the total time and the CPU time, and the DMA transfers with their bandwidth. `Total Kernel Time` is the sum of all kernel times per TF, i.e. the pure GPU compute time without the gaps between kernels, the transfers and the host work. The `Total Wall Time` in `kernel` mode is larger than in `wall` mode due to the synchronization and the timer overhead and should not be used as wall time. +- `--tfTime` line: `: X sec per 32 orbit TF, Y GPUs required (Measured wall time - Extrapolated from N clusters to M)`. The measured time (pipeline time per TF with double pipeline, otherwise `Total Wall Time`) is scaled linearly with the number of TPC clusters from the `N` clusters of the TF to the `M` = 107,546,607 clusters of a 32-orbit TF of Pb-Pb collisions at 50 kHz (755,851 clusters per collision, 11245 Hz orbit frequency). `Y` = time per TF / duration of the TF (32 / 11245 s) is the number of GPUs (or CPUs) needed to process 50 kHz Pb-Pb in real time. + +# 5. Further information + +## Datasets + +- For meaningful numbers, use large Pb-Pb datasets with real TF size, e.g. 32-orbit TFs at 50 kHz. Small datasets (pp, few collisions) are dominated by fixed overheads (kernel launches, synchronization), and their extrapolation with `--tfTime` is not meaningful. +- `sync`, `combined`, `alldetectors` need TPC ZS raw data; datasets with digits or clusters are rejected. `async` needs compressed clusters, e.g. created from a sync dataset with `--syncAsync --dumpEvents 2` (see [build-standalone.md](https://github.com/AliceO2Group/AliceO2/blob/dev/GPU/documentation/build-standalone.md)). +- `--runs N` repeats the same TF, so caches and memory are warm; `-n N` processes different TFs, which also covers the variation between TFs. With double pipeline, `--runs` processes the same TF in both instances. + +## Build + +- Use an optimized build without debug settings (`GPUCA_BUILD_DEBUG 0` in `config.cmake`) and without deterministic mode (`GPUCA_DETERMINISTIC_MODE OFF`), the deterministic mode is much slower. +- Build only for the GPU architecture of the benchmark (`CUDA_COMPUTETARGET` / `HIP_AMDGPUTARGET`); with RTC, the code is compiled again for the actual GPU anyway. + +## Further output options + +- `--PROCdebugCSV ` appends the timing table of `kernel` mode to a CSV file, `--PROCdebugMarkdown 1` prints it as markdown table. +- `--PROCrecoTaskTiming 1` prints the time per reconstruction step also in `wall` mode (enabled automatically with `--debug 1`). +- `--memoryStat` prints memory statistics; `Maximum Memory Allocation: Host ... / Device ...` at the end shows the peak use of the memory pools, which helps to choose `--memSize`. + +## Memory + +- The GPU must have at least `--memSize` of free memory, plus the memory of the runtime and, with RTC, of the loaded kernels. +- Host memory: the input and output buffers (6 + 10 GB, 10 GB more for the second output buffer with double pipeline), the page-locked host memory pool of the reconstruction (1 GB per instance, 2 GB if the compression output is gathered on the host), and the loaded TFs (all of them with `--preloadEvents`; a 50 kHz TF with ZS raw data has about 2 GB). +- CPUDevice (the CPU kernels run as if on a GPU device, for testing without a GPU) needs the same memory in host memory, and the CPU kernel parameters. + +## Notes + +- The `--tfTime` line is labeled `Sync phase` also for the other processing modes. +- For `async`, the cluster count `N` is the number of clusters after the cluster rejection of the sync phase, so the extrapolation refers to a TF with 107,546,607 clusters after rejection, i.e. more data than a real 50 kHz TF. +- With `-n` and double pipeline, the extrapolation uses the cluster count of the last TF, while the time is the average over all TFs. +- The double pipeline does not support TRD tracking (initialization fails), therefore `sync` and `combined` disable TRD. +- Without a GPU, the `gpu` benchmarks can be tested with `--gpuType CPUDEVICE` (functionally, the timing is not representative of a GPU). From 9b595b7d0d51f92bb4e2552ae7b84c2d8a1be94e Mon Sep 17 00:00:00 2001 From: David Rohr Date: Sat, 28 Nov 2026 14:29:32 +0100 Subject: [PATCH 12/12] GPU: Improve host memory size estimation --- GPU/GPUTracking/Base/GPUReconstruction.cxx | 4 ++-- GPU/GPUTracking/Global/GPUChainTracking.cxx | 3 ++- GPU/GPUTracking/Standalone/Benchmark/standalone.cxx | 4 +++- 3 files changed, 7 insertions(+), 4 deletions(-) diff --git a/GPU/GPUTracking/Base/GPUReconstruction.cxx b/GPU/GPUTracking/Base/GPUReconstruction.cxx index 14a4c9496cfda..93acca09f4119 100644 --- a/GPU/GPUTracking/Base/GPUReconstruction.cxx +++ b/GPU/GPUTracking/Base/GPUReconstruction.cxx @@ -142,7 +142,7 @@ int32_t GPUReconstruction::Init() return retVal; } mNStreams = std::max(mNStreams, mSlaves[i]->mNStreams); - mHostMemorySize = std::max(mHostMemorySize, mSlaves[i]->mHostMemorySize); + mHostMemorySize += mSlaves[i]->mHostMemorySize; mDeviceMemorySize = std::max(mDeviceMemorySize, mSlaves[i]->mDeviceMemorySize); } if (InitDevice()) { @@ -375,7 +375,7 @@ int32_t GPUReconstruction::InitPhaseBeforeDevice() return 1; } mChains[i]->RegisterPermanentMemoryAndProcessors(); - size_t memPrimary, memPageLocked; + size_t memPrimary = 0, memPageLocked = 0; mChains[i]->MemorySize(memPrimary, memPageLocked); if (!IsGPU() || mOutputControl.useInternal()) { memPageLocked = memPrimary; diff --git a/GPU/GPUTracking/Global/GPUChainTracking.cxx b/GPU/GPUTracking/Global/GPUChainTracking.cxx index 3e30702c83cbf..fec4914219a7b 100644 --- a/GPU/GPUTracking/Global/GPUChainTracking.cxx +++ b/GPU/GPUTracking/Global/GPUChainTracking.cxx @@ -168,8 +168,9 @@ void GPUChainTracking::RegisterGPUProcessors() 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; + pageLockedHostMem = constants::GPU_DEFAULT_HOST_MEMORY_SIZE * (gatherMode < 2 ? 2 : 1); } bool GPUChainTracking::ValidateSteps() diff --git a/GPU/GPUTracking/Standalone/Benchmark/standalone.cxx b/GPU/GPUTracking/Standalone/Benchmark/standalone.cxx index 818c6ea5646f4..ed6a3dbf434d2 100644 --- a/GPU/GPUTracking/Standalone/Benchmark/standalone.cxx +++ b/GPU/GPUTracking/Standalone/Benchmark/standalone.cxx @@ -318,7 +318,9 @@ int32_t ReadConfiguration(int argc, char** argv) printf("setO2Settings requires the usage of --inputMemory and --outputMemory as in O2\n"); return 1; } - configStandalone.proc.forceHostMemoryPoolSize = 1024 * 1024 * 1024; + if (configStandalone.proc.forceHostMemoryPoolSize < 1024) { + configStandalone.proc.forceHostMemoryPoolSize = 1024 * 1024 * 1024; + } } configStandalone.rec.tpc.trackReferenceX = 83; configStandalone.proc.outputSharedClusterMap = 1;