diff --git a/DataFormats/Reconstruction/include/ReconstructionDataFormats/TrackParametrization.h b/DataFormats/Reconstruction/include/ReconstructionDataFormats/TrackParametrization.h index 83680bbe0332e..0f7b7e55ec76f 100644 --- a/DataFormats/Reconstruction/include/ReconstructionDataFormats/TrackParametrization.h +++ b/DataFormats/Reconstruction/include/ReconstructionDataFormats/TrackParametrization.h @@ -159,9 +159,9 @@ class TrackParametrization GPUd() void set(value_t x, value_t alpha, const params_t& par, int charge = 1, const PID pid = PID::Pion); GPUd() void set(value_t x, value_t alpha, const value_t* par, int charge = 1, const PID pid = PID::Pion); GPUd() const value_t* getParams() const; - GPUd() value_t getParam(int i) const; - GPUd() value_t getX() const; - GPUd() value_t getAlpha() const; + GPUhd() value_t getParam(int i) const; + GPUhd() value_t getX() const; + GPUhd() value_t getAlpha() const; GPUd() value_t getY() const; GPUd() value_t getZ() const; GPUd() value_t getSnp() const; @@ -330,21 +330,21 @@ GPUdi() auto TrackParametrization::getParams() const -> const value_t* //____________________________________________________________ template -GPUdi() auto TrackParametrization::getParam(int i) const -> value_t +GPUhdi() auto TrackParametrization::getParam(int i) const -> value_t { return mP[i]; } //____________________________________________________________ template -GPUdi() auto TrackParametrization::getX() const -> value_t +GPUhdi() auto TrackParametrization::getX() const -> value_t { return mX; } //____________________________________________________________ template -GPUdi() auto TrackParametrization::getAlpha() const -> value_t +GPUhdi() auto TrackParametrization::getAlpha() const -> value_t { return mAlpha; } diff --git a/Detectors/ITSMFT/ITS/tracking/GPU/ITStrackingGPU/TimeFrameGPU.h b/Detectors/ITSMFT/ITS/tracking/GPU/ITStrackingGPU/TimeFrameGPU.h index f067098cec991..0cc4d248fca78 100644 --- a/Detectors/ITSMFT/ITS/tracking/GPU/ITStrackingGPU/TimeFrameGPU.h +++ b/Detectors/ITSMFT/ITS/tracking/GPU/ITStrackingGPU/TimeFrameGPU.h @@ -166,9 +166,9 @@ class TimeFrameGPU : public TimeFrame int* getDeviceLineDensity() { return mLineDensityDevice; } gpu::LineWindow* getDeviceLineWin() { return mLineWinDevice; } uint8_t* getDeviceLineIsPeak() { return mLineIsPeakDevice; } - int* getDeviceLineDensityFine() { return mLineDensityFineDevice; } - gpu::LineWindow* getDeviceLineWinFine() { return mLineWinFineDevice; } - uint8_t* getDeviceLineIsPeakFine() { return mLineIsPeakFineDevice; } + gpu::LineWindow* getDeviceLineWinPeak() { return mLineWinPeakDevice; } + float* getDeviceLineHalfWidth() { return mLineHalfWidthDevice; } + gpu::LineWindow* getDeviceLineWinSeed() { return mLineWinSeedDevice; } int* getDevicePeakScan() { return mPeakScanDevice; } int* getDevicePeakLineIdx() { return mPeakLineIdxDevice; } int* getDevicePeakOffsets() { return mPeakOffsetsDevice; } @@ -197,7 +197,6 @@ class TimeFrameGPU : public TimeFrame int** getDeviceArrayNeighboursCellLUT() const { return mNeighboursCellLUTDeviceArray; } CellSeed** getDeviceArrayCells() { return mCellsDeviceArray; } TrackSeedN* getDeviceTrackSeeds() { return mTrackSeedsDevice; } - int* getDeviceTrackSeedIndices() { return mTrackSeedIndicesDevice; } int* getDeviceTrackCounter() { return mTrackCounterDevice; } auto getNTrackSeeds() const { return mNTracks; } @@ -300,7 +299,6 @@ class TimeFrameGPU : public TimeFrame std::array mCellsDevice{}; CellSeed** mCellsDeviceArray{nullptr}; TrackSeedN* mTrackSeedsDevice{nullptr}; - int* mTrackSeedIndicesDevice{nullptr}; ///< which seed each emitted track was fitted from int* mTrackCounterDevice{nullptr}; unsigned int mNTracks{0}; @@ -325,17 +323,17 @@ class TimeFrameGPU : public TimeFrame float* mLineZsSortedDevice{nullptr}; o2::its::TimeEstBC* mLineTimesSortedDevice{nullptr}; int* mLinesSortedIdx{nullptr}; - int* mLineRofSortedDevice{nullptr}; // per (sorted) line's ROF - int* mRofLineOffsetsDevice{nullptr}; // CSR offsets into the (rof,z)-sorted lines, size nRofs+1 - int* mLineDensityDevice{nullptr}; // per (sorted) line: count of time-compatible neighbours in its z-window - gpu::LineWindow* mLineWinDevice{nullptr}; // per (sorted) line: [lo,hi) bounds of its z-window (sorted coords) - uint8_t* mLineIsPeakDevice{nullptr}; // per (sorted) line: 1 if it is a local density peak (vertex candidate) - int* mLineDensityFineDevice{nullptr}; - gpu::LineWindow* mLineWinFineDevice{nullptr}; - uint8_t* mLineIsPeakFineDevice{nullptr}; - int* mPeakScanDevice{nullptr}; // per (sorted) line: number of peaks strictly before it - int* mPeakLineIdxDevice{nullptr}; // per peak slot: the sorted line index it came from - int* mPeakOffsetsDevice{nullptr}; // CSR offsets into the compacted peaks + int* mLineRofSortedDevice{nullptr}; // per (sorted) line's ROF + int* mRofLineOffsetsDevice{nullptr}; // CSR offsets into the (rof,z)-sorted lines, size nRofs+1 + int* mLineDensityDevice{nullptr}; // per (sorted) line: count of time-compatible neighbours in its own z window (+-h) + gpu::LineWindow* mLineWinDevice{nullptr}; // per (sorted) line: [lo,hi) bounds of +-zWindow, where members are collected (sorted coords) + uint8_t* mLineIsPeakDevice{nullptr}; // per (sorted) line: 1 if it is a local density peak (vertex candidate) + gpu::LineWindow* mLineWinPeakDevice{nullptr}; // per (sorted) line: [lo,hi) bounds of its own z window +-h (peak search) + float* mLineHalfWidthDevice{nullptr}; // per (sorted) line: h + gpu::LineWindow* mLineWinSeedDevice{nullptr}; // per (sorted) line: [lo,hi) bounds of the seed-fit window +-2h + int* mPeakScanDevice{nullptr}; // per (sorted) line: number of peaks strictly before it + int* mPeakLineIdxDevice{nullptr}; // per peak slot: the sorted line index it came from + int* mPeakOffsetsDevice{nullptr}; // CSR offsets into the compacted peaks VertexCand* mVertexCandsDevice{nullptr}; int mNLinesCapacity{0}; // = nCells the line buffers were sized for bounded_vector mLinesHost; diff --git a/Detectors/ITSMFT/ITS/tracking/GPU/ITStrackingGPU/TrackingKernels.h b/Detectors/ITSMFT/ITS/tracking/GPU/ITStrackingGPU/TrackingKernels.h index f2c98509fd580..b4781fe8afe35 100644 --- a/Detectors/ITSMFT/ITS/tracking/GPU/ITStrackingGPU/TrackingKernels.h +++ b/Detectors/ITSMFT/ITS/tracking/GPU/ITStrackingGPU/TrackingKernels.h @@ -154,7 +154,6 @@ struct TrackingKernels { const int** ROFClusters, o2::its::TrackITSExt* tracks, int* trackIndices, - int* trackSeedIndices, int* outputCounter, const int trackCapacity, TrackExtensionHypothesis* activeHypotheses, @@ -234,9 +233,14 @@ struct TrackingKernels { static void scanDensityHandler(const int nLines, const gpu::LineProjSoA sortedSoa, const int* rofOffsets, - int* density, gpu::LineWindow* win, + gpu::LineWindow* winPeak, + int* density, + float* halfWidth, + gpu::LineWindow* winSeed, const float zWindow, + const float alpha, + const float hMin, gpu::Stream& stream); static void findPeaksHandler(const int nLines, @@ -245,11 +249,8 @@ struct TrackingKernels { const int* rofOffsets, const int* density, const gpu::LineWindow* win, + const float* halfWidth, uint8_t* isPeak, - const int* densityFine, - const gpu::LineWindow* winFine, - const int fineMinDensity, - uint8_t* isPeakFine, int* peakScan, int* peakLineIdx, int* peakOffsets, @@ -259,6 +260,7 @@ struct TrackingKernels { static void fitPeaksHandler(const int* nPeaksDevice, const int* peakLineIdx, const gpu::LineWindow* win, + const gpu::LineWindow* seedWin, const gpu::LineProjSoA sortedSoa, const o2::its::Line* lines, const float* lineChi2, @@ -270,8 +272,6 @@ struct TrackingKernels { const int minContributors, const float beamX, const float beamY, - const uint8_t* isPeakFine, - const float fineMaxDrift, gpu::VertexCand* cands, gpu::Stream& stream); diff --git a/Detectors/ITSMFT/ITS/tracking/GPU/cuda/TimeFrameGPU.cu b/Detectors/ITSMFT/ITS/tracking/GPU/cuda/TimeFrameGPU.cu index 3f74f71ed3adf..e69fce88b5040 100644 --- a/Detectors/ITSMFT/ITS/tracking/GPU/cuda/TimeFrameGPU.cu +++ b/Detectors/ITSMFT/ITS/tracking/GPU/cuda/TimeFrameGPU.cu @@ -581,9 +581,9 @@ void TimeFrameGPU::createLinesDevice(const int nCells) mLineDensityDevice = allocDeviceAsync(nCells, mGpuStreams[0], kStack); mLineWinDevice = allocDeviceAsync(nCells, mGpuStreams[0], kStack); mLineIsPeakDevice = allocDeviceAsync(nCells, mGpuStreams[0], kStack); - mLineDensityFineDevice = allocDeviceAsync(nCells, mGpuStreams[0], kStack); - mLineWinFineDevice = allocDeviceAsync(nCells, mGpuStreams[0], kStack); - mLineIsPeakFineDevice = allocDeviceAsync(nCells, mGpuStreams[0], kStack); + mLineWinPeakDevice = allocDeviceAsync(nCells, mGpuStreams[0], kStack); + mLineHalfWidthDevice = allocDeviceAsync(nCells, mGpuStreams[0], kStack); + mLineWinSeedDevice = allocDeviceAsync(nCells, mGpuStreams[0], kStack); mPeakScanDevice = allocDeviceAsync((nCells + 1), mGpuStreams[0], kStack); mPeakLineIdxDevice = allocDeviceAsync(nCells, mGpuStreams[0], kStack); mPeakOffsetsDevice = allocDeviceAsync((this->getNrof(1) + 1), mGpuStreams[0], kStack); @@ -706,7 +706,6 @@ void TimeFrameGPU::createTrackITSExtDevice(const size_t capacity) } GPULog("gpu-allocation: reserving {} track indices, for {:.2f} MB.", capacity, capacity * sizeof(int) / constants::MB); mTrackIndicesDevice = allocDevice(capacity, o2::gpu::GPUMemoryResource::MEMORY_GPU | o2::gpu::GPUMemoryResource::MEMORY_STACK); - mTrackSeedIndicesDevice = allocDevice(capacity, o2::gpu::GPUMemoryResource::MEMORY_GPU | o2::gpu::GPUMemoryResource::MEMORY_STACK); mTrackCounterDevice = allocDevice(1, o2::gpu::GPUMemoryResource::MEMORY_GPU | o2::gpu::GPUMemoryResource::MEMORY_STACK); } diff --git a/Detectors/ITSMFT/ITS/tracking/GPU/cuda/TrackerTraitsGPU.cxx b/Detectors/ITSMFT/ITS/tracking/GPU/cuda/TrackerTraitsGPU.cxx index 8bbd310beae48..365e1e1809389 100644 --- a/Detectors/ITSMFT/ITS/tracking/GPU/cuda/TrackerTraitsGPU.cxx +++ b/Detectors/ITSMFT/ITS/tracking/GPU/cuda/TrackerTraitsGPU.cxx @@ -289,37 +289,28 @@ void TrackerTraitsGPU::computeVertexCandidates(const int iteration) const auto& tp = this->mTrkParams[iteration]; const float zWindow = 0.5f * tp.VtxClusterCut; + // every line gets its own z window, sized by the density of time-compatible lines around it TrackingKernels::scanDensityHandler(static_cast(nLines), mTimeFrameGPU->getLineProjSortedSoA(), mTimeFrameGPU->getDeviceRofLineOffsets(), - mTimeFrameGPU->getDeviceLineDensity(), mTimeFrameGPU->getDeviceLineWin(), + mTimeFrameGPU->getDeviceLineWinPeak(), + mTimeFrameGPU->getDeviceLineDensity(), + mTimeFrameGPU->getDeviceLineHalfWidth(), + mTimeFrameGPU->getDeviceLineWinSeed(), zWindow, + tp.VtxAdaptiveZWindowAlpha, + std::min(tp.VtxAdaptiveZWindowMin, zWindow), mTimeFrameGPU->getStream(0)); - const float fineZWindow = tp.VtxFineZWindow; - const bool doFine = fineZWindow > 0.f && fineZWindow < zWindow; - if (doFine) { - TrackingKernels::scanDensityHandler(static_cast(nLines), - mTimeFrameGPU->getLineProjSortedSoA(), - mTimeFrameGPU->getDeviceRofLineOffsets(), - mTimeFrameGPU->getDeviceLineDensityFine(), - mTimeFrameGPU->getDeviceLineWinFine(), - fineZWindow, - mTimeFrameGPU->getStream(0)); - } - TrackingKernels::findPeaksHandler(nLines, mTimeFrameGPU->getNrof(1), mTimeFrameGPU->getLineProjSortedSoA(), mTimeFrameGPU->getDeviceRofLineOffsets(), mTimeFrameGPU->getDeviceLineDensity(), - mTimeFrameGPU->getDeviceLineWin(), + mTimeFrameGPU->getDeviceLineWinPeak(), + mTimeFrameGPU->getDeviceLineHalfWidth(), mTimeFrameGPU->getDeviceLineIsPeak(), - doFine ? mTimeFrameGPU->getDeviceLineDensityFine() : nullptr, - doFine ? mTimeFrameGPU->getDeviceLineWinFine() : nullptr, - tp.VtxFineMinDensity, - doFine ? mTimeFrameGPU->getDeviceLineIsPeakFine() : nullptr, mTimeFrameGPU->getDevicePeakScan(), mTimeFrameGPU->getDevicePeakLineIdx(), mTimeFrameGPU->getDevicePeakOffsets(), @@ -329,7 +320,8 @@ void TrackerTraitsGPU::computeVertexCandidates(const int iteration) const float goodLinePtCut = std::abs(mTimeFrameGPU->getBz()) > 0.01f ? tp.VtxGoodLinePtCut : -1.f; TrackingKernels::fitPeaksHandler(mTimeFrameGPU->getDeviceNPeaks(), mTimeFrameGPU->getDevicePeakLineIdx(), - mTimeFrameGPU->getDeviceLineWin(), + mTimeFrameGPU->getDeviceLineWin(), // members from +-zWindow + mTimeFrameGPU->getDeviceLineWinSeed(), mTimeFrameGPU->getLineProjSortedSoA(), mTimeFrameGPU->getDeviceLines(), mTimeFrameGPU->getDeviceLineChi2(), @@ -341,8 +333,6 @@ void TrackerTraitsGPU::computeVertexCandidates(const int iteration) tp.VtxClusterContributorsCut, mTimeFrameGPU->getBeamX(), mTimeFrameGPU->getBeamY(), - doFine ? mTimeFrameGPU->getDeviceLineIsPeakFine() : nullptr, - tp.VtxFineMaxDrift, mTimeFrameGPU->getDeviceVertexCands(), mTimeFrameGPU->getStream(0)); @@ -448,7 +438,7 @@ void TrackerTraitsGPU::computeVertices(const int iteration) double rofLoad = 0.; if (goodSig > 0.f) { // compute the number of contributors in this ROF for (int p = peakOffsets[rofId]; p < peakOffsets[rofId + 1]; ++p) { - if (cands[p].ok && !cands[p].fine) { + if (cands[p].ok) { rofLoad += cands[p].size; } } @@ -703,7 +693,6 @@ void TrackerTraitsGPU::findRoads(const int iteration) mTimeFrameGPU->getDeviceROFrameClusters(), mTimeFrameGPU->getDeviceTrackITSExt(), mTimeFrameGPU->getDeviceTrackIndices(), - mTimeFrameGPU->getDeviceTrackSeedIndices(), mTimeFrameGPU->getDeviceTrackCounter(), capacity, extendTracks ? mTimeFrameGPU->getDeviceActiveTrackExtensionHypotheses() : nullptr, diff --git a/Detectors/ITSMFT/ITS/tracking/GPU/cuda/TrackingKernels.cu b/Detectors/ITSMFT/ITS/tracking/GPU/cuda/TrackingKernels.cu index bdb702d3b4427..434fc29352d5a 100644 --- a/Detectors/ITSMFT/ITS/tracking/GPU/cuda/TrackingKernels.cu +++ b/Detectors/ITSMFT/ITS/tracking/GPU/cuda/TrackingKernels.cu @@ -72,17 +72,10 @@ namespace gpu struct compare_track_index_chi2 { const TrackITSExt* tracks; - const int* seedIndices; GPUhd() bool operator()(const int a, const int b) const { - if (o2::its::track::isBetter(tracks[a], tracks[b])) { - return true; - } - if (o2::its::track::isBetter(tracks[b], tracks[a])) { - return false; - } - return seedIndices[a] < seedIndices[b]; + return o2::its::track::isBetterOrdered(tracks[a], tracks[b]); } }; @@ -119,7 +112,6 @@ GPUg() void __launch_bounds__(GPUThreads, (ExtendTracks ? MinBlocks.fitTrackSeed const int** clustersIndexTables, const int** ROFClusters, o2::its::TrackITSExt* tracks, - int* trackSeedIndices, int* outputCounter, const int trackCapacity, TrackExtensionHypothesis* activeHypothesesScratch, @@ -187,7 +179,6 @@ GPUg() void __launch_bounds__(GPUThreads, (ExtendTracks ? MinBlocks.fitTrackSeed if (bestDiff) { tracks[slot].setExtendedLayerPattern(bestDiff); } - trackSeedIndices[slot] = iCurrentTrackSeedIndex; } } @@ -721,7 +712,7 @@ GPUg() void __launch_bounds__(GPUThreads, (std::is_same_v TrackSeed* updatedCellSeeds, int* updatedCellsIds, int* updatedCellTopologyIds, - int* updatedSourceSeeds, + uint64_t* updatedSortKeys, // (source seed, neighbour entry): a total order of the outputs, deterministic mode only int* outputCounter, const int outputCapacity, const TrackingFrameInfo** foundTrackingFrameInfo, @@ -782,8 +773,8 @@ GPUg() void __launch_bounds__(GPUThreads, (std::is_same_v updatedCellsIds[outputIndex] = neighbourCellId; updatedCellTopologyIds[outputIndex] = neighbourCellTopologyId; updatedCellSeeds[outputIndex] = seed; - if (updatedSourceSeeds != nullptr) { - updatedSourceSeeds[outputIndex] = static_cast(iCurrentCell); + if (updatedSortKeys != nullptr) { + updatedSortKeys[outputIndex] = (static_cast(iCurrentCell) << 32) | static_cast(candidate.neighbourEntry); } } } @@ -955,8 +946,22 @@ GPUg() void gatherSortedLinesKernel(const int nLines, LineProjSoA lineProj, Line } } +// Time-compatible lines of one ROF slice with z in [zk - h, zk + h]; w receives the [lo, hi) slot bounds +GPUdi() int countCompatibleInZWindow(const float* z, const o2::its::TimeEstBC* t, const int rofOffset, const int nextRofOffset, const float zk, const o2::its::TimeEstBC ti, const float h, LineWindow& w) +{ + w.lo = deviceLowerBound(z, rofOffset, nextRofOffset, zk - h); // first line with z >= zk - h + w.hi = deviceUpperBound(z, rofOffset, nextRofOffset, zk + h); // first line with z > zk + h + int count = 0; + for (int j = w.lo; j < w.hi; ++j) { + count += ti.isCompatible(t[j]); // includes self + } + return count; +} + template -GPUg() void scanDensityKernel(int* zDensity, LineWindow* win, const int nLines, const int* offsets, const LineProjSoA lineProjSorted, const float zWindow) +GPUg() void scanDensityKernel(LineWindow* win, LineWindow* winPeak, int* density, float* halfWidth, LineWindow* winSeed, + const int nLines, const int* offsets, const LineProjSoA lineProjSorted, + const float zWindow, const float alpha, const float hMin) { const float* z = lineProjSorted.z; const o2::its::TimeEstBC* t = lineProjSorted.t; @@ -966,18 +971,17 @@ GPUg() void scanDensityKernel(int* zDensity, LineWindow* win, const int nLines, const int rofOffset = offsets[rofId]; const int nextRofOffset = offsets[rofId + 1]; const float zk = z[iLine]; - const int lo = deviceLowerBound(z, rofOffset, nextRofOffset, zk - zWindow); // first line with z >= zk - zWindow - const int hi = deviceUpperBound(z, rofOffset, nextRofOffset, zk + zWindow); // first line with z > zk + zWindow - win[iLine] = LineWindow{lo, hi}; const auto ti = t[iLine]; - int count = 0; - for (int j = lo; j < hi; ++j) { - const auto tj = t[j]; - if (ti.isCompatible(tj)) { // count only if time compatible (includes self) - ++count; - } - } - zDensity[iLine] = count; + LineWindow w; + const int n = countCompatibleInZWindow(z, t, rofOffset, nextRofOffset, zk, ti, zWindow, w); + win[iLine] = w; + const float h = o2::its::computeAdaptiveZWindow(n, alpha, hMin, zWindow); + density[iLine] = countCompatibleInZWindow(z, t, rofOffset, nextRofOffset, zk, ti, h, w); + winPeak[iLine] = w; + halfWidth[iLine] = h; + const float hSeed = o2::gpu::CAMath::Min(o2::its::AdaptiveSeedWindowScale * h, zWindow); + winSeed[iLine] = LineWindow{deviceLowerBound(z, rofOffset, nextRofOffset, zk - hSeed), + deviceUpperBound(z, rofOffset, nextRofOffset, zk + hSeed)}; } } @@ -985,6 +989,7 @@ template GPUg() void fitPeaksKernel(const int* nPeaksDevice, const int* peakLineIdx, const gpu::LineWindow* win, + const gpu::LineWindow* seedWin, // per line: the narrower window the seed is fitted on const LineProjSoA lineProjSorted, const o2::its::Line* lines, const float* lineChi2, // global-indexed, same indexing as lines[] @@ -996,8 +1001,6 @@ GPUg() void fitPeaksKernel(const int* nPeaksDevice, const int minContributors, const float beamX, const float beamY, - const uint8_t* isZPeakFine, // null when the fine pass is off - const float fineMaxDrift, // <= 0 disables; see VertexerParamConfig::fineMaxDrift VertexCand* cands) { const int nPeaks = *nPeaksDevice; @@ -1011,13 +1014,13 @@ GPUg() void fitPeaksKernel(const int* nPeaksDevice, if (lane == 0) { cands[iPeak].ok = 0; cands[iPeak].nGood = 0; - cands[iPeak].fine = isZPeakFine != nullptr ? isZPeakFine[k] : 0; } const auto tk = t[k]; const LineWindow wk = win[k]; + const LineWindow ws = seedWin[k]; int nMembers = 0; WarpFit seed; - for (int iLine = wk.lo + lane; iLine < wk.hi; iLine += gpu::WarpSize) { + for (int iLine = ws.lo + lane; iLine < ws.hi; iLine += gpu::WarpSize) { const auto tj = t[iLine]; if (!tk.isCompatible(tj)) { continue; @@ -1072,10 +1075,6 @@ GPUg() void fitPeaksKernel(const int* nPeaksDevice, if (fit.getNContributors() < minContributors || !(bd2 < nSigmaCut)) { continue; } - if (fineMaxDrift > 0.f && (isZPeakFine != nullptr ? isZPeakFine[k] : 0) && - o2::gpu::GPUCommonMath::Abs(vertex[2] - seedVertex[2]) > fineMaxDrift) { - continue; - } for (int iLine = wk.lo + lane; iLine < wk.hi; iLine += gpu::WarpSize) { const auto tj = t[iLine]; @@ -1106,14 +1105,13 @@ GPUg() void fitPeaksKernel(const int* nPeaksDevice, } } -// Strict local maximum of the density over a line's own z-window, ties broken by smaller z -GPUdi() bool isDensityPeak(const int* density, const float* z, const LineWindow w, const int iLine) +GPUdi() bool isDensityPeak(const int* density, const float* halfWidth, const float* z, const LineWindow w, const int iLine) { const int di = density[iLine]; + const float hi = halfWidth[iLine]; const float zi = z[iLine]; for (int j = w.lo; j < w.hi; ++j) { - const int dj = density[j]; - if (dj > di || (dj == di && z[j] < zi)) { + if (o2::its::isDenser(density[j], halfWidth[j], z[j], di, hi, zi)) { return false; } } @@ -1121,24 +1119,12 @@ GPUdi() bool isDensityPeak(const int* density, const float* z, const LineWindow } template -GPUg() void findPeaksKernel(const int* zDensity, const LineWindow* win, const int nLines, const LineProjSoA lineProjSorted, uint8_t* isZPeak, - const int* zDensityFine, const LineWindow* winFine, - const int fineMinDensity, uint8_t* isZPeakFine) +GPUg() void findPeaksKernel(const int* density, const LineWindow* win, const float* halfWidth, const int nLines, + const LineProjSoA lineProjSorted, uint8_t* isPeak) { const float* z = lineProjSorted.z; for (int iLine = blockIdx.x * blockDim.x + threadIdx.x; iLine < nLines; iLine += blockDim.x * gridDim.x) { - uint8_t peak = zDensity[iLine] >= 2 && isDensityPeak(zDensity, z, win[iLine], iLine); - - // fine pass: if the coarse pass did not find a peak, check if the fine density is above threshold and is a peak - uint8_t fine = 0; - if (!peak && zDensityFine != nullptr) { - fine = zDensityFine[iLine] >= fineMinDensity && isDensityPeak(zDensityFine, z, winFine[iLine], iLine); - peak = fine; - } - isZPeak[iLine] = peak; - if (isZPeakFine != nullptr) { - isZPeakFine[iLine] = fine; - } + isPeak[iLine] = density[iLine] >= 2 && isDensityPeak(density, halfWidth, z, win[iLine], iLine); } } @@ -1647,13 +1633,16 @@ void TrackingKernels::linearizeCellsToLinesHandler(const int nCells, linePt); } -// Orders lines by (ROF, z): primary key the ROF, secondary the projected z within the ROF. +// Orders lines by (ROF, z, line index): a total order, so equal z keep the line order as on the CPU struct RofZLess { const int* rof; const float* z; GPUhdi() bool operator()(const int a, const int b) const { - return rof[a] != rof[b] ? rof[a] < rof[b] : z[a] < z[b]; + if (rof[a] != rof[b]) { + return rof[a] < rof[b]; + } + return z[a] != z[b] ? z[a] < z[b] : a < b; } }; @@ -1684,15 +1673,21 @@ template void TrackingKernels::scanDensityHandler(const int nLines, const gpu::LineProjSoA sortedSoa, const int* rofOffsets, - int* density, gpu::LineWindow* win, + gpu::LineWindow* winPeak, + int* density, + float* halfWidth, + gpu::LineWindow* winSeed, const float zWindow, + const float alpha, + const float hMin, gpu::Stream& stream) { if (nLines < 2) { return; } - gpu::scanDensityKernel<<>>(density, win, nLines, rofOffsets, sortedSoa, zWindow); + gpu::scanDensityKernel<<>>( + win, winPeak, density, halfWidth, winSeed, nLines, rofOffsets, sortedSoa, zWindow, alpha, hMin); } template @@ -1702,11 +1697,8 @@ void TrackingKernels::findPeaksHandler(const int nLines, const int* rofOffsets, const int* density, const gpu::LineWindow* win, + const float* halfWidth, uint8_t* isPeak, - const int* densityFine, - const gpu::LineWindow* winFine, - const int fineMinDensity, - uint8_t* isPeakFine, int* peakScan, int* peakLineIdx, int* peakOffsets, @@ -1716,8 +1708,7 @@ void TrackingKernels::findPeaksHandler(const int nLines, if (nLines < 2) { return; } - gpu::findPeaksKernel<<>>(density, win, nLines, sortedSoa, isPeak, - densityFine, winFine, fineMinDensity, isPeakFine); + gpu::findPeaksKernel<<>>(density, win, halfWidth, nLines, sortedSoa, isPeak); auto nosync_policy = THRUST_NAMESPACE::par_nosync(gpu::TypedAllocator(alloc)).on(stream.get()); thrust::exclusive_scan(nosync_policy, isPeak, isPeak + nLines + 1, peakScan, 0, thrust::plus()); thrust::scatter_if(nosync_policy, thrust::make_counting_iterator(0), thrust::make_counting_iterator(nLines), @@ -1729,6 +1720,7 @@ template void TrackingKernels::fitPeaksHandler(const int* nPeaksDevice, const int* peakLineIdx, const gpu::LineWindow* win, + const gpu::LineWindow* seedWin, const gpu::LineProjSoA sortedSoa, const o2::its::Line* lines, const float* lineChi2, @@ -1740,8 +1732,6 @@ void TrackingKernels::fitPeaksHandler(const int* nPeaksDevice, const int minContributors, const float beamX, const float beamY, - const uint8_t* isPeakFine, - const float fineMaxDrift, gpu::VertexCand* cands, gpu::Stream& stream) { @@ -1753,7 +1743,7 @@ void TrackingKernels::fitPeaksHandler(const int* nPeaksDevice, LOGP(fatal, "fitPeaksKernel compiled for warp size {} but the device runs {}", gpu::WarpSize, warpSize); } gpu::fitPeaksKernel<<>>( - nPeaksDevice, peakLineIdx, win, sortedSoa, lines, lineChi2, linePt, goodLineChi2Cut, goodLinePtCut, pairCut2, nSigmaCut, minContributors, beamX, beamY, isPeakFine, fineMaxDrift, cands); + nPeaksDevice, peakLineIdx, win, seedWin, sortedSoa, lines, lineChi2, linePt, goodLineChi2Cut, goodLinePtCut, pairCut2, nSigmaCut, minContributors, beamX, beamY, cands); } template @@ -1844,6 +1834,7 @@ void TrackingKernels::processNeighboursHandler(const int startLevel, alloc->pushTagOnStack(Tag); auto allocInt = gpu::TypedAllocator(alloc); auto allocTrackSeed = gpu::TypedAllocator>(alloc); + auto allocKey = gpu::TypedAllocator(alloc); auto nosync_policy = THRUST_NAMESPACE::par_nosync(gpu::TypedAllocator(alloc)).on(gpu::Stream::DefaultStream); auto outputCounter = allocInt.allocate(1); @@ -1894,7 +1885,8 @@ void TrackingKernels::processNeighboursHandler(const int startLevel, const int outIdx = filled == 0 ? 1 : 0; Slab& out = slabs[outIdx]; thrust::device_ptr> staged{}; - thrust::device_ptr stagedCellIds{}, stagedCellTopologyIds{}, sourceSeeds{}; + thrust::device_ptr stagedCellIds{}, stagedCellTopologyIds{}; + thrust::device_ptr sortKeys{}; const int emitted = runOnSlab( estimator, roadKey(level), static_cast(nLevelSeeds), [&](const int capacity) { ensureCapacity(out, capacity); @@ -1902,7 +1894,7 @@ void TrackingKernels::processNeighboursHandler(const int startLevel, staged = allocTrackSeed.allocate(out.capacity); stagedCellIds = allocInt.allocate(out.capacity); stagedCellTopologyIds = allocInt.allocate(out.capacity); - sourceSeeds = allocInt.allocate(out.capacity); + sortKeys = allocKey.allocate(out.capacity); #else staged = out.seeds; stagedCellIds = out.cellIds; @@ -1947,7 +1939,7 @@ void TrackingKernels::processNeighboursHandler(const int startLevel, thrust::raw_pointer_cast(staged), thrust::raw_pointer_cast(stagedCellIds), thrust::raw_pointer_cast(stagedCellTopologyIds), - thrust::raw_pointer_cast(sourceSeeds), + thrust::raw_pointer_cast(sortKeys), thrust::raw_pointer_cast(outputCounter), out.capacity, foundTrackingFrameInfo, layerxX0, bz, maxChi2ClusterAttachment, propagator, matCorrType); @@ -1966,7 +1958,7 @@ void TrackingKernels::processNeighboursHandler(const int startLevel, if (emitted > 0) { auto permutation = allocInt.allocate(emitted); thrust::sequence(nosync_policy, permutation, permutation + emitted); - thrust::stable_sort_by_key(nosync_policy, sourceSeeds, sourceSeeds + emitted, permutation); + thrust::sort_by_key(nosync_policy, sortKeys, sortKeys + emitted, permutation); thrust::gather(nosync_policy, permutation, permutation + emitted, staged, out.seeds); thrust::gather(nosync_policy, permutation, permutation + emitted, stagedCellIds, out.cellIds); thrust::gather(nosync_policy, permutation, permutation + emitted, stagedCellTopologyIds, out.cellTopologyIds); @@ -2016,7 +2008,6 @@ int TrackingKernels::computeTrackSeedHandler(TrackSeed* trackS const int** ROFClusters, o2::its::TrackITSExt* tracks, int* trackIndices, - int* trackSeedIndices, int* outputCounter, const int trackCapacity, TrackExtensionHypothesis* activeHypotheses, @@ -2079,7 +2070,6 @@ int TrackingKernels::computeTrackSeedHandler(TrackSeed* trackS clustersIndexTables, // int** ROFClusters, // int** tracks, // TrackITSExt* - trackSeedIndices, // int* outputCounter, // int* trackCapacity, // const int activeHypotheses, // TrackExtensionHypothesis* @@ -2120,7 +2110,7 @@ int TrackingKernels::computeTrackSeedHandler(TrackSeed* trackS auto sync_policy = THRUST_NAMESPACE::par(gpu::TypedAllocator(alloc)); thrust::device_ptr trackIndicesPtr(trackIndices); thrust::sequence(sync_policy, trackIndicesPtr, trackIndicesPtr + emitted); - thrust::sort(sync_policy, trackIndicesPtr, trackIndicesPtr + emitted, gpu::compare_track_index_chi2{tracks, trackSeedIndices}); + thrust::sort(sync_policy, trackIndicesPtr, trackIndicesPtr + emitted, gpu::compare_track_index_chi2{tracks}); if (emitted > 0) { auto allocTrack = gpu::TypedAllocator(alloc); diff --git a/Detectors/ITSMFT/ITS/tracking/include/ITStracking/ClusterLines.h b/Detectors/ITSMFT/ITS/tracking/include/ITStracking/ClusterLines.h index 5be9ab093cc91..f20b09a8bdc3e 100644 --- a/Detectors/ITSMFT/ITS/tracking/include/ITStracking/ClusterLines.h +++ b/Detectors/ITSMFT/ITS/tracking/include/ITStracking/ClusterLines.h @@ -16,6 +16,7 @@ #include #include #ifndef GPUCA_GPUCODE +#include #include #else #include "GPUCommonAlgorithm.h" // warp reductions of WarpFit @@ -64,7 +65,20 @@ struct Line final { return d2; } + /// std::hypot on the host keeps the old vertexer bit-exact; DeviceHypot makes the host round like the device + template + GPUhdi() static float dcaHypot(float a, float b) + { +#ifndef GPUCA_GPUCODE + if constexpr (!DeviceHypot) { + return std::hypot(a, b); + } +#endif + return o2::gpu::GPUCommonMath::Hypot(a, b); + } + /// Packed symmetric DCA components in {XX, XY, YY, XZ, YZ, ZZ} order + template GPUhdi() static void getDCAComponents(const Line& line, const float point[3], float out[6]) { float delta[3], proj = 0.f; @@ -79,15 +93,9 @@ struct Line final { out[0] = r[0]; out[2] = r[1]; out[5] = r[2]; -#ifndef GPUCA_GPUCODE - out[1] = std::hypot(r[0], r[1]); - out[3] = std::hypot(r[0], r[2]); - out[4] = std::hypot(r[1], r[2]); -#else - out[1] = o2::gpu::GPUCommonMath::Hypot(r[0], r[1]); - out[3] = o2::gpu::GPUCommonMath::Hypot(r[0], r[2]); - out[4] = o2::gpu::GPUCommonMath::Hypot(r[1], r[2]); -#endif + out[1] = dcaHypot(r[0], r[1]); + out[3] = dcaHypot(r[0], r[2]); + out[4] = dcaHypot(r[1], r[2]); } GPUhdi() static bool getZAtBeam(const Line& line, const float beamX, const float beamY, float& z) @@ -149,7 +157,10 @@ class LineFit { public: /// Accumulate one line - GPUhdi() bool add(const Line& line) + GPUhdi() bool add(const Line& line) { return accumulate(line, mA, mB); } + + /// Accumulate one line into the given normal equations + GPUhdi() static bool accumulate(const Line& line, double A[6], double B[3]) { const double d0 = line.cosinesDirector[0], d1 = line.cosinesDirector[1], d2 = line.cosinesDirector[2]; const double o0 = line.originPoint[0], o1 = line.originPoint[1], o2 = line.originPoint[2]; @@ -157,16 +168,16 @@ class LineFit if (det <= 0.) { return false; } - mA[0] += (det - d0 * d0) / det; - mA[1] += (-d0 * d1) / det; - mA[2] += (-d0 * d2) / det; - mA[3] += (det - d1 * d1) / det; - mA[4] += (-d1 * d2) / det; - mA[5] += (det - d2 * d2) / det; + A[0] += (det - d0 * d0) / det; + A[1] += (-d0 * d1) / det; + A[2] += (-d0 * d2) / det; + A[3] += (det - d1 * d1) / det; + A[4] += (-d1 * d2) / det; + A[5] += (det - d2 * d2) / det; const double dDotO = d0 * o0 + d1 * o1 + d2 * o2; - mB[0] += (d0 * dDotO - det * o0) / det; - mB[1] += (d1 * dDotO - det * o1) / det; - mB[2] += (d2 * dDotO - det * o2) / det; + B[0] += (d0 * dDotO - det * o0) / det; + B[1] += (d1 * dDotO - det * o1) / det; + B[2] += (d2 * dDotO - det * o2) / det; return true; } @@ -315,6 +326,80 @@ struct WarpFit : public LineFit { double rms2Sum[6] = {0., 0., 0., 0., 0., 0.}; double dist2Sum = 0.; }; +#else +/// Lanes of the device warp fit that LaneFit replicates: wave64 of the EPN AMD GPUs (an NVIDIA warp of 32 will not match) +constexpr int HostWarpFitLanes = 64; + +/// Host replica of WarpFit: the line at offset `slot` of its window accumulates into lane slot % Width, and the lanes +/// are combined in the butterfly order of warp_reduce_add, so the sums round exactly like on the device +template +class LaneFit : public LineFit +{ + public: + void add(const Line& line, const int slot) + { + const int lane = slot % Width; + if (accumulate(line, mLaneA[lane], mLaneB[lane])) { + mTLo = std::max(mTLo, line.mTime.lower()); + mTHi = std::min(mTHi, line.mTime.upper()); + ++mNContributors; + } + } + + void reduce() + { + for (int i = 0; i < 6; ++i) { + mA[i] = butterfly([&](const int lane) { return mLaneA[lane][i]; }); + } + for (int i = 0; i < 3; ++i) { + mB[i] = butterfly([&](const int lane) { return mLaneB[lane][i]; }); + } + mTime = TimeEstBC{mTLo, mTHi - mTLo}; + } + + void addResidual(const Line& line, const float vertex[3], const int slot) + { + const int lane = slot % Width; + float dca[6]; + Line::getDCAComponents(line, vertex, dca); + for (int i = 0; i < 6; ++i) { + mLaneRMS2[lane][i] += dca[i]; + } + mLaneDist2[lane] += Line::getDistance2FromPoint(line, vertex); + } + + void reduceResiduals(const int n) + { + for (int i = 0; i < 6; ++i) { + mRMS2[i] = butterfly([&](const int lane) { return mLaneRMS2[lane][i]; }) / n; + } + mAvgDistance2 = butterfly([&](const int lane) { return mLaneDist2[lane]; }) / n; + } + + private: + /// warp_reduce_add: at each step lane l adds lane l ^ m, which leaves the same sum in every lane + template + static double butterfly(Get get) + { + double v[Width], next[Width]; + for (int lane = 0; lane < Width; ++lane) { + v[lane] = get(lane); + } + for (int m = Width / 2; m > 0; m >>= 1) { + for (int lane = 0; lane < Width; ++lane) { + next[lane] = v[lane] + v[lane ^ m]; + } + std::copy(next, next + Width, v); + } + return v[0]; + } + + double mLaneA[Width][6] = {}; + double mLaneB[Width][3] = {}; + double mLaneRMS2[Width][6] = {}; + double mLaneDist2[Width] = {}; + uint32_t mTLo = 0, mTHi = 0xffffffffu; +}; #endif } // namespace o2::its diff --git a/Detectors/ITSMFT/ITS/tracking/include/ITStracking/Configuration.h b/Detectors/ITSMFT/ITS/tracking/include/ITStracking/Configuration.h index 61a681bc30cfe..77fa52f38277e 100644 --- a/Detectors/ITSMFT/ITS/tracking/include/ITStracking/Configuration.h +++ b/Detectors/ITSMFT/ITS/tracking/include/ITStracking/Configuration.h @@ -158,9 +158,8 @@ struct TrackingParameters { float VtxNSigmaCut = -1.f; float VtxDuplicateZCut = -1.f; float VtxDuplicateZScale = -1.f; - float VtxFineZWindow = -1.f; - int VtxFineMinDensity = -1; - float VtxFineMaxDrift = -1.f; + float VtxAdaptiveZWindowAlpha = 0.3f; // per-line z window, see VertexerParamConfig::adaptiveZWindowAlpha + float VtxAdaptiveZWindowMin = 0.0075f; float VtxGoodLineChi2Cut = -1.f; float VtxGoodLinePtCut = -1.f; float VtxGoodContributorsSignificance = -1.f; diff --git a/Detectors/ITSMFT/ITS/tracking/include/ITStracking/LineProjection.h b/Detectors/ITSMFT/ITS/tracking/include/ITStracking/LineProjection.h index c029a6dca27d3..89d87c8b58ab0 100644 --- a/Detectors/ITSMFT/ITS/tracking/include/ITStracking/LineProjection.h +++ b/Detectors/ITSMFT/ITS/tracking/include/ITStracking/LineProjection.h @@ -17,6 +17,7 @@ #define O2_ITS_TRACKING_LINE_PROJECTION_H_ #include "GPUCommonDef.h" +#include "GPUCommonMath.h" #include "DataFormatsITS/TimeEstBC.h" #include #include @@ -30,6 +31,28 @@ struct LineWindow { int hi{0}; }; +// Every line gets its own z window: from the number n of time-compatible lines within +-hMax, +// h = hMax (n/4)^-alpha, clamped to [hMin, hMax]. Peaks compare count/h. +constexpr int AdaptiveZWindowNRef = 4; // up to this many lines the window keeps its full width hMax +constexpr float AdaptiveSeedWindowScale = 2.f; // the seed fit uses the lines within +-2h (at most +-hMax) + +GPUhdi() float computeAdaptiveZWindow(const int n, const float alpha, const float hMin, const float hMax) +{ + if (n <= AdaptiveZWindowNRef) { + return hMax; + } + const float h = hMax * o2::gpu::CAMath::Pow(static_cast(n) / AdaptiveZWindowNRef, -alpha); + return o2::gpu::CAMath::Min(o2::gpu::CAMath::Max(h, hMin), hMax); +} + +// True if line j (density dj over half-width hj, at zj) beats line i: higher dj/hj, ties to the smaller z +GPUhdi() bool isDenser(const int dj, const float hj, const float zj, const int di, const float hi, const float zi) +{ + const float a = dj * hi; + const float b = di * hj; + return a > b || (a == b && zj < zi); +} + // Per-line quality estimators carried alongside the projected line. struct LineQuality { float chi2{-1.f}; @@ -79,7 +102,6 @@ struct VertexCand { int size; uint8_t ok; // 1 if the candidate passed the fit cuts uint8_t keep; // 1 if it survived duplicate suppression (subset of ok) - uint8_t fine; }; } // namespace gpu diff --git a/Detectors/ITSMFT/ITS/tracking/include/ITStracking/TrackHelpers.h b/Detectors/ITSMFT/ITS/tracking/include/ITStracking/TrackHelpers.h index 1ed68342fc160..a9dd0670afb19 100644 --- a/Detectors/ITSMFT/ITS/tracking/include/ITStracking/TrackHelpers.h +++ b/Detectors/ITSMFT/ITS/tracking/include/ITStracking/TrackHelpers.h @@ -40,6 +40,29 @@ GPUhdi() bool isBetter(const auto& a, const auto& b) return isBetter(a.getNumberOfClusters(), a.getChi2(), b.getNumberOfClusters(), b.getChi2()); } +/// isBetter made a total order: exact ties (same clusters count and chi2) are broken by the cluster indices, then the +/// parameters, so the order and the cluster sharing do not depend on threads or on the device +GPUhdi() bool isBetterOrdered(const TrackITSExt& a, const TrackITSExt& b) +{ + if (isBetter(a, b)) { + return true; + } + if (isBetter(b, a)) { + return false; + } + for (int i = 0; i < TrackITSExt::MaxClusters; ++i) { + if (a.getClusterIndex(i) != b.getClusterIndex(i)) { + return a.getClusterIndex(i) < b.getClusterIndex(i); + } + } + for (int i = 0; i < 5; ++i) { + if (a.getParam(i) != b.getParam(i)) { + return a.getParam(i) < b.getParam(i); + } + } + return a.getX() != b.getX() ? a.getX() < b.getX() : a.getAlpha() < b.getAlpha(); +} + template struct TrackSeedSelector { float maxQ2Pt; diff --git a/Detectors/ITSMFT/ITS/tracking/src/Configuration.cxx b/Detectors/ITSMFT/ITS/tracking/src/Configuration.cxx index 302969b4c31f2..7a3edf2dc2ec8 100644 --- a/Detectors/ITSMFT/ITS/tracking/src/Configuration.cxx +++ b/Detectors/ITSMFT/ITS/tracking/src/Configuration.cxx @@ -315,9 +315,8 @@ std::vector TrackingMode::getTrackingParameters(TrackingMode seedingPass.VtxNSigmaCut = vc.nSigmaCut; seedingPass.VtxDuplicateZCut = vc.duplicateZCut; seedingPass.VtxDuplicateZScale = vc.duplicateZScale; - seedingPass.VtxFineZWindow = vc.fineZWindow; - seedingPass.VtxFineMinDensity = vc.fineMinDensity; - seedingPass.VtxFineMaxDrift = vc.fineMaxDrift; + seedingPass.VtxAdaptiveZWindowAlpha = vc.adaptiveZWindowAlpha; + seedingPass.VtxAdaptiveZWindowMin = vc.adaptiveZWindowMin; seedingPass.VtxGoodLineChi2Cut = vc.goodLineChi2Cut; seedingPass.VtxGoodLinePtCut = vc.goodLinePtCut; seedingPass.VtxGoodContributorsSignificance = vc.goodContributorsSignificance; diff --git a/Detectors/ITSMFT/ITS/tracking/src/Tracker.cxx b/Detectors/ITSMFT/ITS/tracking/src/Tracker.cxx index ebd9162a00ad2..cdff164cedf13 100644 --- a/Detectors/ITSMFT/ITS/tracking/src/Tracker.cxx +++ b/Detectors/ITSMFT/ITS/tracking/src/Tracker.cxx @@ -17,6 +17,7 @@ #include "GenericTracking/BoundedAllocator.h" #include "ITSMFTTracking/Constants.h" #include "ITStracking/TrackerTraits.h" +#include "ITStracking/TrackHelpers.h" #include "ITSMFTTracking/ITSTrackingConfigParam.h" #include @@ -291,7 +292,7 @@ void Tracker::sortTracks() if (aLower != bLower) { return aLower < bLower; } - return a.isBetter(b, 1e9); // then sort tracks in quality + return track::isBetterOrdered(a, b); // then in quality, ties broken by content }); bounded_vector sortedTrks(mMemoryPool.get()); sortedTrks.reserve(trks.size()); diff --git a/Detectors/ITSMFT/ITS/tracking/src/TrackerTraits.cxx b/Detectors/ITSMFT/ITS/tracking/src/TrackerTraits.cxx index b29da0e7d22d3..60e76162d7b82 100644 --- a/Detectors/ITSMFT/ITS/tracking/src/TrackerTraits.cxx +++ b/Detectors/ITSMFT/ITS/tracking/src/TrackerTraits.cxx @@ -245,6 +245,9 @@ void TrackerTraits::computeLayerTracklets(const int iteration, int iVer const bool trackletsAlreadyGrouped = seedingPass && mTaskArena->max_concurrency() > 1; tbb::parallel_for(0, static_cast(topology.nLinks), [&](const int linkId) { if (trackletsAlreadyGrouped) { +#ifdef GPUCA_DETERMINISTIC_MODE // the grouped emit keeps the search order within a cluster: sort it as with one thread + tbb::parallel_sort(mTimeFrame->getTracklets()[linkId].begin(), mTimeFrame->getTracklets()[linkId].end()); +#endif return; } /// Sort tracklets & remove duplicates @@ -425,34 +428,18 @@ namespace void computeDensities(const bounded_vector& Z, const bounded_vector& T, const float zWindow, - const float fineZWindow, + const float alpha, + const float hMin, std::pmr::memory_resource* pool, bounded_vector& win, + bounded_vector& winPeak, bounded_vector& density, - bounded_vector& winFine, - bounded_vector& densityFine) + bounded_vector& halfWidth, + bounded_vector& winSeed) { const int m = static_cast(Z.size()); - // Z is sorted, so the window bounds advance monotonically with k - int lo{0}, hi{0}, loF{0}, hiF{0}; - for (int k = 0; k < m; ++k) { - const float zk = Z[k]; - while (lo < m && Z[lo] < zk - zWindow) { - ++lo; - } - while (hi < m && Z[hi] <= zk + zWindow) { - ++hi; - } - while (loF < m && Z[loF] < zk - fineZWindow) { - ++loF; - } - while (hiF < m && Z[hiF] <= zk + fineZWindow) { - ++hiF; - } - win[k] = LineWindow{lo, hi}; - winFine[k] = LineWindow{loF, hiF}; - } - + // Lines with the same time interval form a bucket, z-sorted, so counting the compatible lines in a z range + // takes one binary search per compatible bucket instead of a scan of the window. bounded_vector byTime(m, pool); std::iota(byTime.begin(), byTime.end(), 0); std::sort(byTime.begin(), byTime.end(), [&](const int a, const int b) { @@ -469,46 +456,68 @@ void computeDensities(const bounded_vector& Z, } } bucketStart.push_back(m); - - // How many values of the sorted range [first, last) lie in [lo, hi] - const auto countBetween = [](auto first, auto last, auto lo, auto hi) { return static_cast(std::upper_bound(first, last, hi) - std::lower_bound(first, last, lo)); }; - - for (int k = 0; k < m; ++k) { - const float zk = Z[k]; - int count{0}, countFine{0}; + const auto count = [&](const int k, const float h) { + int n{0}; for (size_t b = 0; b + 1 < bucketStart.size(); ++b) { - if (!T[k].isCompatible(T[byTime[bucketStart[b]]])) { - continue; + if (T[k].isCompatible(T[byTime[bucketStart[b]]])) { + const auto first = zByTime.cbegin() + bucketStart[b], last = zByTime.cbegin() + bucketStart[b + 1]; + n += static_cast(std::upper_bound(first, last, Z[k] + h) - std::lower_bound(first, last, Z[k] - h)); } - const auto first = zByTime.cbegin() + bucketStart[b], last = zByTime.cbegin() + bucketStart[b + 1]; - count += countBetween(first, last, zk - zWindow, zk + zWindow); - countFine += countBetween(first, last, zk - fineZWindow, zk + fineZWindow); } - density[k] = count; - densityFine[k] = countFine; + return n; + }; + const auto bounds = [&](const int k, const float h) { + return LineWindow{static_cast(std::lower_bound(Z.begin(), Z.end(), Z[k] - h) - Z.begin()), + static_cast(std::upper_bound(Z.begin(), Z.end(), Z[k] + h) - Z.begin())}; + }; + + for (int k = 0; k < m; ++k) { + const float h = computeAdaptiveZWindow(count(k, zWindow), alpha, hMin, zWindow); + halfWidth[k] = h; + density[k] = count(k, h); + win[k] = bounds(k, zWindow); + winPeak[k] = bounds(k, h); + winSeed[k] = bounds(k, std::min(AdaptiveSeedWindowScale * h, zWindow)); } } -void markLeftmostMaxima(const bounded_vector& density, - const bounded_vector& win, - std::pmr::memory_resource* pool, - bounded_vector& isMax) +// Line k is a peak if density[k] >= 2 and no line in its own window has a higher density/halfWidth +void markPeaks(const bounded_vector& density, + const bounded_vector& halfWidth, + const bounded_vector& Z, + const bounded_vector& winPeak, + std::pmr::memory_resource* pool, + bounded_vector& isPeak) { - const int m = static_cast(density.size()); - // Monotonic deque over the (monotonically advancing) windowsDetectors/ITSMFT/ITS/tracking/src/TrackingInterface.cxx - bounded_vector maxDeque(m, pool); - int front{0}, back{0}, next{0}; + const int m = static_cast(Z.size()); + const auto best = [&](const int a, const int b) { + return isDenser(density[b], halfWidth[b], Z[b], density[a], halfWidth[a], Z[a]) ? b : a; + }; + int nLevels = 1; + while ((1 << nLevels) <= m) { + ++nLevels; + } + // sparse[j * m + i] = best line in [i, i + 2^j) + bounded_vector sparse(static_cast(nLevels) * m, pool); + std::iota(sparse.begin(), sparse.begin() + m, 0); + for (int j = 1; j < nLevels; ++j) { + const int half = 1 << (j - 1); + for (int i = 0; i + (1 << j) <= m; ++i) { + sparse[j * m + i] = best(sparse[(j - 1) * m + i], sparse[(j - 1) * m + i + half]); + } + } for (int k = 0; k < m; ++k) { - while (next < win[k].hi) { - while (back > front && density[maxDeque[back - 1]] < density[next]) { - --back; - } - maxDeque[back++] = next++; + isPeak[k] = 0; + if (density[k] < 2) { + continue; } - while (front < back && maxDeque[front] < win[k].lo) { - ++front; + const int lo = winPeak[k].lo, hi = winPeak[k].hi; // always contains k + int j = 0; + while ((2 << j) <= hi - lo) { + ++j; } - isMax[k] = maxDeque[front] == k; // the window always contains k itself, so the deque is non-empty + const int top = best(sparse[j * m + lo], sparse[j * m + hi - (1 << j)]); + isPeak[k] = !isDenser(density[top], halfWidth[top], Z[top], density[k], halfWidth[k], Z[k]); } } } // namespace @@ -551,7 +560,6 @@ void TrackerTraits::computeVertices(const int iteration) const float beamX = mTimeFrame->getBeamX(); const float beamY = mTimeFrame->getBeamY(); const auto& tp = mTrkParams[iteration]; - const float maxZ = tp.VtxMaxZPositionAllowed; const float clusterCut = tp.VtxClusterCut; const float pairCut2 = tp.VtxPairCut * tp.VtxPairCut; const float zWindow = 0.5f * clusterCut; @@ -561,10 +569,8 @@ void TrackerTraits::computeVertices(const int iteration) : std::max(4.f * tp.VtxPairCut, 0.5f * clusterCut); const int minContributors = tp.VtxClusterContributorsCut; const int suppressLowMultDebris = tp.VtxSuppressLowMultDebris; - const bool doFine = tp.VtxFineZWindow > 0.f && tp.VtxFineZWindow < zWindow; - const float fineZWindow = doFine ? tp.VtxFineZWindow : zWindow; - const int fineMinDensity = tp.VtxFineMinDensity; - const float fineMaxDrift = tp.VtxFineMaxDrift; + const float zWindowAlpha = tp.VtxAdaptiveZWindowAlpha; + const float zWindowMin = std::min(tp.VtxAdaptiveZWindowMin, zWindow); const float goodSig = tp.VtxGoodContributorsSignificance; const float duplicateZScale = tp.VtxDuplicateZScale; const float goodLineChi2Cut = tp.VtxGoodLineChi2Cut; @@ -579,69 +585,40 @@ void TrackerTraits::computeVertices(const int iteration) if (n < 2) { return; } - const auto lineSpan = gsl::span(lines.data(), lines.size()); - - // project every line onto the beam line - bounded_vector zc(mMemoryPool.get()); - bounded_vector tc(mMemoryPool.get()); - bounded_vector lic(mMemoryPool.get()); - zc.reserve(n); - tc.reserve(n); - lic.reserve(n); + + // project every line onto the beam line, as linearizeCellsKernel (the |z| < maxZ cut was applied per cell) + bounded_vector zc(n, mMemoryPool.get()); for (int i = 0; i < n; ++i) { - const auto& line = lines[i]; - float z; - if (!Line::getZAtBeam(line, beamX, beamY, z)) { - continue; + if (!Line::getZAtBeam(lines[i], beamX, beamY, zc[i])) { + zc[i] = lines[i].originPoint[2]; } - if (!(o2::gpu::CAMath::Abs(z) < maxZ)) { - continue; - } - zc.push_back(z); - tc.push_back(line.mTime); - lic.push_back(i); - } - const int m = static_cast(zc.size()); - if (m < 2) { - return; } - // sort by z - bounded_vector order(m, mMemoryPool.get()); - std::iota(order.begin(), order.end(), 0); - std::sort(order.begin(), order.end(), [&](const int a, const int b) { return zc[a] < zc[b]; }); - bounded_vector Z(m, mMemoryPool.get()); - bounded_vector T(m, mMemoryPool.get()); - bounded_vector LI(m, mMemoryPool.get()); - for (int i = 0; i < m; ++i) { - Z[i] = zc[order[i]]; - T[i] = tc[order[i]]; - LI[i] = lic[order[i]]; + // sort by z, ties by line index as RofZLess + bounded_vector LI(n, mMemoryPool.get()); + std::iota(LI.begin(), LI.end(), 0); + std::sort(LI.begin(), LI.end(), [&](const int a, const int b) { return zc[a] != zc[b] ? zc[a] < zc[b] : a < b; }); + bounded_vector Z(n, mMemoryPool.get()); + bounded_vector T(n, mMemoryPool.get()); + for (int i = 0; i < n; ++i) { + Z[i] = zc[LI[i]]; + T[i] = lines[LI[i]].mTime; } - // density of time-compatible neighbours in a z window - bounded_vector density(m, mMemoryPool.get()); - bounded_vector win(m, mMemoryPool.get()); - bounded_vector densityFine(m, mMemoryPool.get()); - bounded_vector winFine(m, mMemoryPool.get()); - computeDensities(Z, T, zWindow, fineZWindow, mMemoryPool.get(), win, density, winFine, densityFine); - - // peaks: leftmost density maxima - bounded_vector isMax(m, mMemoryPool.get()); - markLeftmostMaxima(density, win, mMemoryPool.get(), isMax); - bounded_vector isMaxFine(doFine ? m : 0, mMemoryPool.get()); - if (doFine) { - markLeftmostMaxima(densityFine, winFine, mMemoryPool.get(), isMaxFine); - } + // every line gets its own z window, sized by the density of time-compatible lines around it + bounded_vector win(n, mMemoryPool.get()); // +-zWindow: where the members are collected + bounded_vector winPeak(n, mMemoryPool.get()); // +-h: the peak search + bounded_vector winSeed(n, mMemoryPool.get()); // +-2h: the seed fit + bounded_vector density(n, mMemoryPool.get()); // time-compatible lines in +-h + bounded_vector halfWidth(n, mMemoryPool.get()); // h + computeDensities(Z, T, zWindow, zWindowAlpha, zWindowMin, mMemoryPool.get(), win, winPeak, density, halfWidth, winSeed); + + // peaks: lines with the highest density per unit length in their own window + bounded_vector isPeak(n, mMemoryPool.get()); + markPeaks(density, halfWidth, Z, winPeak, mMemoryPool.get(), isPeak); bounded_vector peaks(mMemoryPool.get()); - bounded_vector isPeakFine(m, 0, mMemoryPool.get()); - for (int k = 0; k < m; ++k) { - bool peak = density[k] >= 2 && isMax[k]; - if (!peak && doFine && densityFine[k] >= fineMinDensity && isMaxFine[k]) { - peak = true; - isPeakFine[k] = 1; - } - if (peak) { + for (int k = 0; k < n; ++k) { + if (isPeak[k]) { peaks.push_back(k); } } @@ -650,38 +627,35 @@ void TrackerTraits::computeVertices(const int iteration) return; } - // one candidate per peak: seed fit over the window, prune outliers, refit, apply the cuts - bounded_vector cand(np, mMemoryPool.get()); + // one candidate per peak: seed fit over the window, prune outliers, refit, apply the cuts. LaneFit sums the lines + // like fitPeaksKernel (lane = offset in the window), so CPU and GPU candidates are bit-identical + bounded_vector cand(np, mMemoryPool.get()); bounded_vector ok(np, mMemoryPool.get()); bounded_vector nGoodCand(np, 0, mMemoryPool.get()); - bounded_vector fineCand(np, 0, mMemoryPool.get()); bounded_vector> candMembers(withMC ? np : 0, bounded_vector(mMemoryPool.get()), mMemoryPool.get()); const auto& linesQuality = mTimeFrame->getLinesQuality(rofId); const int nQual = static_cast(linesQuality.size()); for (int p = 0; p < np; p++) { const int k = peaks[p]; - fineCand[p] = isPeakFine[k]; - bounded_vector members(mMemoryPool.get()); - members.reserve(density[k]); - for (int j = win[k].lo; j < win[k].hi; ++j) { + // the seed is fitted on the narrower seed window (inside +-zWindow, so 2 seed lines imply 2 members) + LaneFit<> seed; + int nSeedLines = 0; + for (int j = winSeed[k].lo; j < winSeed[k].hi; ++j) { if (T[k].isCompatible(T[j])) { - members.push_back(LI[j]); + seed.add(lines[LI[j]], j - winSeed[k].lo); + ++nSeedLines; } } - if (members.size() < 2) { + seed.reduce(); + seed.computeClusterCentroid(); + if (nSeedLines < 2 || !seed.isValid()) { ok[p] = 0; continue; } - ClusterLines seed{gsl::span{members.data(), members.size()}, lineSpan}; - if (!seed.isValid()) { - ok[p] = 0; - continue; - } - bounded_vector kept(mMemoryPool.get()); - kept.reserve(members.size()); - for (const int idx : members) { - if (Line::getDistance2FromPoint(lines[idx], seed.getVertex()) < pairCut2) { - kept.push_back(idx); + bounded_vector kept(mMemoryPool.get()); // z-sorted positions; the line is LI[j], its lane slot j - win[k].lo + for (int j = win[k].lo; j < win[k].hi; ++j) { + if (T[k].isCompatible(T[j]) && Line::getDistance2FromPoint(lines[LI[j]], seed.getVertex()) < pairCut2) { + kept.push_back(j); } } if (kept.size() < 2) { @@ -692,7 +666,8 @@ void TrackerTraits::computeVertices(const int iteration) if (nQual == 0) { nGood = static_cast(kept.size()); } else { - for (const int idx : kept) { + for (const int j : kept) { + const int idx = LI[j]; const float chi2 = idx < nQual ? linesQuality[idx].chi2 : -1.f; const float pt = idx < nQual ? linesQuality[idx].pt : -1.f; const bool okChi2 = goodLineChi2Cut <= 0.f || chi2 <= goodLineChi2Cut; @@ -701,20 +676,31 @@ void TrackerTraits::computeVertices(const int iteration) } } nGoodCand[p] = nGood; - ClusterLines fit{gsl::span{kept.data(), kept.size()}, lineSpan}; - const float bd2 = (beamX - fit.getVertex()[0]) * (beamX - fit.getVertex()[0]) + - (beamY - fit.getVertex()[1]) * (beamY - fit.getVertex()[1]); - if (!fit.isValid() || static_cast(fit.getSize()) < minContributors || !(bd2 < nSigmaCut)) { + LaneFit<> fit; + for (const int j : kept) { + fit.add(lines[LI[j]], j - win[k].lo); + } + fit.reduce(); + fit.computeClusterCentroid(); + if (!fit.isValid()) { ok[p] = 0; continue; } - if (fineMaxDrift > 0.f && fineCand[p] && std::abs(fit.getVertex()[2] - seed.getVertex()[2]) > fineMaxDrift) { + const float bd2 = (beamX - fit.getVertex()[0]) * (beamX - fit.getVertex()[0]) + + (beamY - fit.getVertex()[1]) * (beamY - fit.getVertex()[1]); + if (static_cast(fit.getSize()) < minContributors || !(bd2 < nSigmaCut)) { ok[p] = 0; continue; } - cand[p] = std::move(fit); + for (const int j : kept) { + fit.addResidual(lines[LI[j]], fit.getVertex(), j - win[k].lo); + } + fit.reduceResiduals(static_cast(kept.size())); + cand[p] = fit; if (withMC) { - candMembers[p] = std::move(kept); + for (const int j : kept) { + candMembers[p].push_back(LI[j]); + } } ok[p] = 1; } @@ -761,7 +747,7 @@ void TrackerTraits::computeVertices(const int iteration) double rofLoad = 0.; if (goodSig > 0.f) { for (int p = 0; p < np; ++p) { - if (ok[p] && !fineCand[p]) { + if (ok[p]) { rofLoad += cand[p].getSize(); } } @@ -1547,7 +1533,7 @@ void TrackerTraits::findRoads(const int iteration) bounded_vector trackIndices(tracks.size(), mMemoryPool.get()); std::iota(trackIndices.begin(), trackIndices.end(), 0); std::sort(trackIndices.begin(), trackIndices.end(), [&tracks](int a, int b) { - return track::isBetter(tracks[a], tracks[b]); + return track::isBetterOrdered(tracks[a], tracks[b]); }); acceptTracks(iteration, tracks, trackIndices, firstClusters); diff --git a/Detectors/ITSMFT/common/tracking/include/ITSMFTTracking/ITSTrackingConfigParam.h b/Detectors/ITSMFT/common/tracking/include/ITSMFTTracking/ITSTrackingConfigParam.h index ae27d432039d7..fde153d979db1 100644 --- a/Detectors/ITSMFT/common/tracking/include/ITSMFTTracking/ITSTrackingConfigParam.h +++ b/Detectors/ITSMFT/common/tracking/include/ITSMFTTracking/ITSTrackingConfigParam.h @@ -42,13 +42,12 @@ struct VertexerParamConfig : public o2::conf::ConfigurableParamHelper