Project
Loading...
Searching...
No Matches
GPUChainTrackingClusterizer.cxx
Go to the documentation of this file.
1// Copyright 2019-2020 CERN and copyright holders of ALICE O2.
2// See https://alice-o2.web.cern.ch/copyright for details of the copyright holders.
3// All rights not expressly granted are reserved.
4//
5// This software is distributed under the terms of the GNU General Public
6// License v3 (GPL Version 3), copied verbatim in the file "COPYING".
7//
8// In applying this license CERN does not waive the privileges and immunities
9// granted to it by virtue of its status as an Intergovernmental Organization
10// or submit itself to any jurisdiction.
11
14
15#include "GPUChainTracking.h"
18#include "GPULogging.h"
19#include "GPUO2DataTypes.h"
22#include "GPUNewCalibValues.h"
23#include "GPUConstantMem.h"
24#include "CfChargePos.h"
25#include "CfArray2D.h"
26#include "GPUGeneralKernels.h"
27#include "GPUDefParametersRuntime.h"
30#include "GPUTPCCFDecodeZS.h"
32#include "GPUTPCCFPeakFinder.h"
35#include "GPUTPCCFClusterizer.h"
36#include "GPUTPCCFGather.h"
38#include "GPUTriggerOutputs.h"
39#include "GPUHostDataTypes.h"
45#include "TPCBase/RDHUtils.h"
46
47#ifdef GPUCA_HAS_ONNX
50#include "ORTRootSerializer.h"
51#endif
52
53#ifdef GPUCA_O2_LIB
55#endif
56
57#include "utils/VcShim.h"
58#include "utils/strtag.h"
59#include <fstream>
60#include <numeric>
61#include <vector>
62
63using namespace o2::gpu;
64using namespace o2::tpc;
65using namespace o2::tpc::constants;
66using namespace o2::dataformats;
67
68#ifdef GPUCA_TPC_GEOMETRY_O2
69std::pair<uint32_t, uint32_t> GPUChainTracking::TPCClusterizerDecodeZSCountUpdate(uint32_t iSector, const CfFragment& fragment)
70{
72 GPUTPCClusterFinder& clusterer = processors()->tpcClusterer[iSector];
74 uint32_t digits = 0;
75 uint32_t pages = 0;
76 for (uint16_t j = 0; j < GPUTrackingInOutZS::NENDPOINTS; j++) {
77 clusterer.mMinMaxCN[j] = mCFContext->fragmentData[fragment.index].minMaxCN[iSector][j];
78 if (doGPU) {
79 uint16_t posInEndpoint = 0;
80 uint16_t pagesEndpoint = 0;
81 for (uint32_t k = clusterer.mMinMaxCN[j].zsPtrFirst; k < clusterer.mMinMaxCN[j].zsPtrLast; k++) {
82 const uint32_t pageFirst = (k == clusterer.mMinMaxCN[j].zsPtrFirst) ? clusterer.mMinMaxCN[j].zsPageFirst : 0;
83 const uint32_t pageLast = (k + 1 == clusterer.mMinMaxCN[j].zsPtrLast) ? clusterer.mMinMaxCN[j].zsPageLast : mIOPtrs.tpcZS->sector[iSector].nZSPtr[j][k];
84 for (uint32_t l = pageFirst; l < pageLast; l++) {
85 uint16_t pageDigits = mCFContext->fragmentData[fragment.index].pageDigits[iSector][j][posInEndpoint++];
86 if (pageDigits) {
87 *(o++) = GPUTPCClusterFinder::ZSOffset{digits, j, pagesEndpoint};
88 digits += pageDigits;
89 }
90 pagesEndpoint++;
91 }
92 }
93 if (pagesEndpoint != mCFContext->fragmentData[fragment.index].pageDigits[iSector][j].size()) {
94 if (GetProcessingSettings().ignoreNonFatalGPUErrors) {
95 GPUError("TPC raw page count mismatch in TPCClusterizerDecodeZSCountUpdate: expected %d / buffered %lu", pagesEndpoint, mCFContext->fragmentData[fragment.index].pageDigits[iSector][j].size());
96 return {0, 0};
97 } else {
98 GPUFatal("TPC raw page count mismatch in TPCClusterizerDecodeZSCountUpdate: expected %d / buffered %lu", pagesEndpoint, mCFContext->fragmentData[fragment.index].pageDigits[iSector][j].size());
99 }
100 }
101 } else {
103 digits += mCFContext->fragmentData[fragment.index].nDigits[iSector][j];
104 pages += mCFContext->fragmentData[fragment.index].nPages[iSector][j];
105 }
106 }
107 if (doGPU) {
108 pages = o - processors()->tpcClusterer[iSector].mPzsOffsets;
109 }
110 if (GetProcessingSettings().clusterizerZSSanityCheck && mCFContext->zsVersion >= ZSVersion::ZSVersionDenseLinkBased) {
111 TPCClusterizerEnsureZSOffsets(iSector, fragment);
112 }
113 return {digits, pages};
114}
115
116void GPUChainTracking::TPCClusterizerEnsureZSOffsets(uint32_t iSector, const CfFragment& fragment)
117{
118 GPUTPCClusterFinder& clusterer = processors()->tpcClusterer[iSector];
119 uint32_t nAdcs = 0;
121 const auto& data = mCFContext->fragmentData[fragment.index];
122 uint32_t pagesEndpoint = 0;
123 const uint32_t nAdcsExpected = data.nDigits[iSector][endpoint];
124 const uint32_t nPagesExpected = data.nPages[iSector][endpoint];
125
126 uint32_t nAdcDecoded = 0;
127 const auto& zs = mIOPtrs.tpcZS->sector[iSector];
128 for (uint32_t i = data.minMaxCN[iSector][endpoint].zsPtrFirst; i < data.minMaxCN[iSector][endpoint].zsPtrLast; i++) {
129 const uint32_t pageFirst = (i == data.minMaxCN[iSector][endpoint].zsPtrFirst) ? data.minMaxCN[iSector][endpoint].zsPageFirst : 0;
130 const uint32_t pageLast = (i + 1 == data.minMaxCN[iSector][endpoint].zsPtrLast) ? data.minMaxCN[iSector][endpoint].zsPageLast : zs.nZSPtr[endpoint][i];
131 for (uint32_t j = pageFirst; j < pageLast; j++) {
132 const uint8_t* page = static_cast<const uint8_t*>(zs.zsPtr[endpoint][i]) + j * TPCZSHDR::TPC_ZS_PAGE_SIZE;
133 const header::RAWDataHeader* rawDataHeader = reinterpret_cast<const header::RAWDataHeader*>(page);
134 const TPCZSHDRV2* decHdr = reinterpret_cast<const TPCZSHDRV2*>(page + raw::RDHUtils::getMemorySize(*rawDataHeader) - sizeof(TPCZSHDRV2));
135 const uint16_t nSamplesInPage = decHdr->nADCsamples;
136
137 nAdcDecoded += nSamplesInPage;
138 pagesEndpoint++;
139 }
140 }
141
142 if (pagesEndpoint != nPagesExpected) {
143 GPUFatal("Sector %d, Endpoint %d, Fragment %d: TPC raw page count mismatch: expected %d / buffered %u", iSector, endpoint, fragment.index, pagesEndpoint, nPagesExpected);
144 }
145
146 if (nAdcDecoded != nAdcsExpected) {
147 GPUFatal("Sector %d, Endpoint %d, Fragment %d: TPC ADC count mismatch: expected %u, buffered %u", iSector, endpoint, fragment.index, nAdcsExpected, nAdcDecoded);
148 }
149
150 if (nAdcs != clusterer.mPzsOffsets[endpoint].offset) {
151 GPUFatal("Sector %d, Endpoint %d, Fragment %d: TPC ADC offset mismatch: expected %u, buffered %u", iSector, endpoint, fragment.index, nAdcs, clusterer.mPzsOffsets[endpoint].offset);
152 }
153
154 nAdcs += nAdcsExpected;
155 }
156}
157
158namespace
159{
160struct TPCCFDecodeScanTmp {
161 int32_t zsPtrFirst, zsPageFirst, zsPtrLast, zsPageLast, hasData, pageCounter;
162};
163} // namespace
164
165std::pair<uint32_t, uint32_t> GPUChainTracking::TPCClusterizerDecodeZSCount(uint32_t iSector, const CfFragment& fragment)
166{
167 mRec->getGeneralStepTimer(GeneralStep::Prepare).Start();
168 uint32_t nDigits = 0;
169 uint32_t nPages = 0;
170 uint32_t endpointAdcSamples[GPUTrackingInOutZS::NENDPOINTS];
171 memset(endpointAdcSamples, 0, sizeof(endpointAdcSamples));
173 int32_t firstHBF = (mIOPtrs.settingsTF && mIOPtrs.settingsTF->hasTfStartOrbit) ? mIOPtrs.settingsTF->tfStartOrbit : ((mIOPtrs.tpcZS->sector[iSector].count[0] && mIOPtrs.tpcZS->sector[iSector].nZSPtr[0][0]) ? o2::raw::RDHUtils::getHeartBeatOrbit(*(const o2::header::RAWDataHeader*)mIOPtrs.tpcZS->sector[iSector].zsPtr[0][0]) : 0);
174
175 for (uint16_t j = 0; j < GPUTrackingInOutZS::NENDPOINTS; j++) {
176
177 if (GetProcessingSettings().prefetchTPCpageScan >= 3 && j < GPUTrackingInOutZS::NENDPOINTS - 1) {
178 for (uint32_t k = 0; k < mIOPtrs.tpcZS->sector[iSector].count[j + 1]; k++) {
179 for (uint32_t l = 0; l < mIOPtrs.tpcZS->sector[iSector].nZSPtr[j + 1][k]; l++) {
180 Vc::Common::prefetchMid(((const uint8_t*)mIOPtrs.tpcZS->sector[iSector].zsPtr[j + 1][k]) + l * TPCZSHDR::TPC_ZS_PAGE_SIZE);
181 Vc::Common::prefetchMid(((const uint8_t*)mIOPtrs.tpcZS->sector[iSector].zsPtr[j + 1][k]) + l * TPCZSHDR::TPC_ZS_PAGE_SIZE + sizeof(o2::header::RAWDataHeader));
182 }
183 }
184 }
185
186 std::vector<std::pair<CfFragment, TPCCFDecodeScanTmp>> fragments;
187 fragments.reserve(mCFContext->nFragments);
188 fragments.emplace_back(std::pair<CfFragment, TPCCFDecodeScanTmp>{fragment, {0, 0, 0, 0, 0, -1}});
189 for (uint32_t i = 1; i < mCFContext->nFragments; i++) {
190 fragments.emplace_back(std::pair<CfFragment, TPCCFDecodeScanTmp>{fragments.back().first.next(), {0, 0, 0, 0, 0, -1}});
191 }
192 std::vector<bool> fragmentExtends(mCFContext->nFragments, false);
193
194 uint32_t firstPossibleFragment = 0;
195 uint32_t pageCounter = 0;
196 uint32_t emptyPages = 0;
197 for (uint32_t k = 0; k < mIOPtrs.tpcZS->sector[iSector].count[j]; k++) {
198 if (GetProcessingSettings().tpcSingleSector != -1 && GetProcessingSettings().tpcSingleSector != (int32_t)iSector) {
199 break;
200 }
201 nPages += mIOPtrs.tpcZS->sector[iSector].nZSPtr[j][k];
202 for (uint32_t l = 0; l < mIOPtrs.tpcZS->sector[iSector].nZSPtr[j][k]; l++) {
203
204 if (GetProcessingSettings().prefetchTPCpageScan >= 2 && l + 1 < mIOPtrs.tpcZS->sector[iSector].nZSPtr[j][k]) {
205 Vc::Common::prefetchForOneRead(((const uint8_t*)mIOPtrs.tpcZS->sector[iSector].zsPtr[j][k]) + (l + 1) * TPCZSHDR::TPC_ZS_PAGE_SIZE);
206 Vc::Common::prefetchForOneRead(((const uint8_t*)mIOPtrs.tpcZS->sector[iSector].zsPtr[j][k]) + (l + 1) * TPCZSHDR::TPC_ZS_PAGE_SIZE + sizeof(o2::header::RAWDataHeader));
207 }
208
209 const uint8_t* const page = ((const uint8_t*)mIOPtrs.tpcZS->sector[iSector].zsPtr[j][k]) + l * TPCZSHDR::TPC_ZS_PAGE_SIZE;
211 if (o2::raw::RDHUtils::getMemorySize(*rdh) == sizeof(o2::header::RAWDataHeader)) {
212 emptyPages++;
213 continue;
214 }
215 pageCounter++;
216 const TPCZSHDR* const hdr = (const TPCZSHDR*)(rdh_utils::getLink(o2::raw::RDHUtils::getFEEID(*rdh)) == rdh_utils::DLBZSLinkID ? (page + o2::raw::RDHUtils::getMemorySize(*rdh) - sizeof(TPCZSHDRV2)) : (page + sizeof(o2::header::RAWDataHeader)));
217 if (mCFContext->zsVersion == -1) {
218 mCFContext->zsVersion = hdr->version;
219 if (GetProcessingSettings().param.tpcTriggerHandling && mCFContext->zsVersion < ZSVersion::ZSVersionDenseLinkBased) { // TODO: Move tpcTriggerHandling to recoSteps bitmask
220 static bool errorShown = false;
221 if (errorShown == false) {
222 GPUAlarm("Trigger handling only possible with TPC Dense Link Based data, received version %d, disabling", mCFContext->zsVersion);
223 }
224 errorShown = true;
225 }
226 } else if (mCFContext->zsVersion != (int32_t)hdr->version) {
227 GPUError("Received TPC ZS 8kb page of mixed versions, expected %d, received %d (linkid %d, feeCRU %d, feeEndpoint %d, feelinkid %d)", mCFContext->zsVersion, (int32_t)hdr->version, (int32_t)o2::raw::RDHUtils::getLinkID(*rdh), (int32_t)rdh_utils::getCRU(*rdh), (int32_t)rdh_utils::getEndPoint(*rdh), (int32_t)rdh_utils::getLink(*rdh));
228 constexpr size_t bufferSize = 3 * std::max(sizeof(*rdh), sizeof(*hdr)) + 1;
229 char dumpBuffer[bufferSize];
230 for (size_t i = 0; i < sizeof(*rdh); i++) {
231 // "%02X " guaranteed to be 3 chars + ending 0.
232 snprintf(dumpBuffer + 3 * i, 4, "%02X ", (int32_t)((uint8_t*)rdh)[i]);
233 }
234 GPUAlarm("RDH of page: %s", dumpBuffer);
235 for (size_t i = 0; i < sizeof(*hdr); i++) {
236 // "%02X " guaranteed to be 3 chars + ending 0.
237 snprintf(dumpBuffer + 3 * i, 4, "%02X ", (int32_t)((uint8_t*)hdr)[i]);
238 }
239 GPUAlarm("Metainfo of page: %s", dumpBuffer);
240 if (GetProcessingSettings().ignoreNonFatalGPUErrors) {
241 mCFContext->abandonTimeframe = true;
242 return {0, 0};
243 } else {
244 GPUFatal("Cannot process with invalid TPC ZS data, exiting");
245 }
246 }
247 if (GetProcessingSettings().param.tpcTriggerHandling) {
248 const TPCZSHDRV2* const hdr2 = (const TPCZSHDRV2*)hdr;
249 if (hdr2->flags & TPCZSHDRV2::ZSFlags::TriggerWordPresent) {
250 const char* triggerWord = (const char*)hdr - TPCZSHDRV2::TRIGGER_WORD_SIZE;
252 memcpy((void*)&tmp.triggerWord, triggerWord, TPCZSHDRV2::TRIGGER_WORD_SIZE);
253 tmp.orbit = o2::raw::RDHUtils::getHeartBeatOrbit(*rdh);
254 if (tmp.triggerWord.isValid(0)) {
255 mTriggerBuffer->triggers.emplace(tmp);
256 }
257 }
258 }
259 nDigits += hdr->nADCsamples;
260 endpointAdcSamples[j] += hdr->nADCsamples;
261 uint32_t timeBin = (hdr->timeOffset + (o2::raw::RDHUtils::getHeartBeatOrbit(*rdh) - firstHBF) * o2::constants::lhc::LHCMaxBunches) / LHCBCPERTIMEBIN;
262 uint32_t maxTimeBin = timeBin + hdr->nTimeBinSpan;
263 if (mCFContext->zsVersion >= ZSVersion::ZSVersionDenseLinkBased) {
264 const TPCZSHDRV2* const hdr2 = (const TPCZSHDRV2*)hdr;
265 if (hdr2->flags & TPCZSHDRV2::ZSFlags::nTimeBinSpanBit8) {
266 maxTimeBin += 256;
267 }
268 }
269 if (maxTimeBin > mCFContext->tpcMaxTimeBin) {
270 mCFContext->tpcMaxTimeBin = maxTimeBin;
271 }
272 bool extendsInNextPage = false;
273 if (mCFContext->zsVersion >= ZSVersion::ZSVersionDenseLinkBased) {
274 if (l + 1 < mIOPtrs.tpcZS->sector[iSector].nZSPtr[j][k] && o2::raw::RDHUtils::getMemorySize(*rdh) == TPCZSHDR::TPC_ZS_PAGE_SIZE) {
276 extendsInNextPage = o2::raw::RDHUtils::getHeartBeatOrbit(*nextrdh) == o2::raw::RDHUtils::getHeartBeatOrbit(*rdh) && o2::raw::RDHUtils::getMemorySize(*nextrdh) > sizeof(o2::header::RAWDataHeader);
277 }
278 }
279 while (firstPossibleFragment && (uint32_t)fragments[firstPossibleFragment - 1].first.last() > timeBin) {
280 firstPossibleFragment--;
281 }
282 auto handleExtends = [&](uint32_t ff) {
283 if (fragmentExtends[ff]) {
284 if (doGPU) {
285 // Only add extended page on GPU. On CPU the pages are in consecutive memory anyway.
286 // Not adding the page prevents an issue where a page is decoded twice on CPU, when only the extend should be decoded.
287 fragments[ff].second.zsPageLast++;
288 mCFContext->fragmentData[ff].nPages[iSector][j]++;
289 mCFContext->fragmentData[ff].pageDigits[iSector][j].emplace_back(0);
290 }
291 fragmentExtends[ff] = false;
292 }
293 };
294 if (mCFContext->zsVersion >= ZSVersion::ZSVersionDenseLinkBased) {
295 for (uint32_t ff = 0; ff < firstPossibleFragment; ff++) {
296 handleExtends(ff);
297 }
298 }
299 for (uint32_t f = firstPossibleFragment; f < mCFContext->nFragments; f++) {
300 if (timeBin < (uint32_t)fragments[f].first.last() && (uint32_t)fragments[f].first.first() <= maxTimeBin) {
301 if (!fragments[f].second.hasData) {
302 fragments[f].second.hasData = 1;
303 fragments[f].second.zsPtrFirst = k;
304 fragments[f].second.zsPageFirst = l;
305 } else {
306 if (pageCounter > (uint32_t)fragments[f].second.pageCounter + 1) {
307 mCFContext->fragmentData[f].nPages[iSector][j] += emptyPages + pageCounter - fragments[f].second.pageCounter - 1;
308 for (uint32_t k2 = fragments[f].second.zsPtrLast - 1; k2 <= k; k2++) {
309 for (uint32_t l2 = ((int32_t)k2 == fragments[f].second.zsPtrLast - 1) ? fragments[f].second.zsPageLast : 0; l2 < (k2 < k ? mIOPtrs.tpcZS->sector[iSector].nZSPtr[j][k2] : l); l2++) {
310 if (doGPU) {
311 mCFContext->fragmentData[f].pageDigits[iSector][j].emplace_back(0);
312 } else {
313 // CPU cannot skip unneeded pages, so we must keep space to store the invalid dummy clusters
314 const uint8_t* const pageTmp = ((const uint8_t*)mIOPtrs.tpcZS->sector[iSector].zsPtr[j][k2]) + l2 * TPCZSHDR::TPC_ZS_PAGE_SIZE;
315 const o2::header::RAWDataHeader* rdhTmp = (const o2::header::RAWDataHeader*)pageTmp;
316 if (o2::raw::RDHUtils::getMemorySize(*rdhTmp) != sizeof(o2::header::RAWDataHeader)) {
317 const TPCZSHDR* const hdrTmp = (const TPCZSHDR*)(rdh_utils::getLink(o2::raw::RDHUtils::getFEEID(*rdhTmp)) == rdh_utils::DLBZSLinkID ? (pageTmp + o2::raw::RDHUtils::getMemorySize(*rdhTmp) - sizeof(TPCZSHDRV2)) : (pageTmp + sizeof(o2::header::RAWDataHeader)));
318 mCFContext->fragmentData[f].nDigits[iSector][j] += hdrTmp->nADCsamples;
319 }
320 }
321 }
322 }
323 } else if (emptyPages) {
324 mCFContext->fragmentData[f].nPages[iSector][j] += emptyPages;
325 if (doGPU) {
326 for (uint32_t m = 0; m < emptyPages; m++) {
327 mCFContext->fragmentData[f].pageDigits[iSector][j].emplace_back(0);
328 }
329 }
330 }
331 }
332 fragments[f].second.zsPtrLast = k + 1;
333 fragments[f].second.zsPageLast = l + 1;
334 fragments[f].second.pageCounter = pageCounter;
335 mCFContext->fragmentData[f].nPages[iSector][j]++;
336 mCFContext->fragmentData[f].nDigits[iSector][j] += hdr->nADCsamples;
337 if (doGPU) {
338 mCFContext->fragmentData[f].pageDigits[iSector][j].emplace_back(hdr->nADCsamples);
339 }
340 fragmentExtends[f] = extendsInNextPage;
341 } else {
342 handleExtends(f);
343 if (timeBin < (uint32_t)fragments[f].first.last()) {
344 if (mCFContext->zsVersion >= ZSVersion::ZSVersionDenseLinkBased) {
345 for (uint32_t ff = f + 1; ff < mCFContext->nFragments; ff++) {
346 handleExtends(ff);
347 }
348 }
349 break;
350 } else {
351 firstPossibleFragment = f + 1;
352 }
353 }
354 }
355 emptyPages = 0;
356 }
357 }
358 for (uint32_t f = 0; f < mCFContext->nFragments; f++) {
359 mCFContext->fragmentData[f].minMaxCN[iSector][j].zsPtrLast = fragments[f].second.zsPtrLast;
360 mCFContext->fragmentData[f].minMaxCN[iSector][j].zsPtrFirst = fragments[f].second.zsPtrFirst;
361 mCFContext->fragmentData[f].minMaxCN[iSector][j].zsPageLast = fragments[f].second.zsPageLast;
362 mCFContext->fragmentData[f].minMaxCN[iSector][j].zsPageFirst = fragments[f].second.zsPageFirst;
363 }
364 }
365 mCFContext->nPagesTotal += nPages;
366 mCFContext->nPagesSector[iSector] = nPages;
367
368 mCFContext->nDigitsEndpointMax[iSector] = 0;
369 for (uint32_t i = 0; i < GPUTrackingInOutZS::NENDPOINTS; i++) {
370 if (endpointAdcSamples[i] > mCFContext->nDigitsEndpointMax[iSector]) {
371 mCFContext->nDigitsEndpointMax[iSector] = endpointAdcSamples[i];
372 }
373 }
374 uint32_t nDigitsFragmentMax = 0;
375 for (uint32_t i = 0; i < mCFContext->nFragments; i++) {
376 uint32_t pagesInFragment = 0;
377 uint32_t digitsInFragment = 0;
378 for (uint16_t j = 0; j < GPUTrackingInOutZS::NENDPOINTS; j++) {
379 pagesInFragment += mCFContext->fragmentData[i].nPages[iSector][j];
380 digitsInFragment += mCFContext->fragmentData[i].nDigits[iSector][j];
381 }
382 mCFContext->nPagesFragmentMax = std::max(mCFContext->nPagesFragmentMax, pagesInFragment);
383 nDigitsFragmentMax = std::max(nDigitsFragmentMax, digitsInFragment);
384 }
385 mRec->getGeneralStepTimer(GeneralStep::Prepare).Stop();
386 return {nDigits, nDigitsFragmentMax};
387}
388
389void GPUChainTracking::RunTPCClusterizer_compactPeaks(GPUTPCClusterFinder& clusterer, GPUTPCClusterFinder& clustererShadow, int32_t stage, bool doGPU, int32_t lane)
390{
391 auto& in = stage ? clustererShadow.mPpeakPositions : clustererShadow.mPpositions;
392 auto& out = stage ? clustererShadow.mPfilteredPeakPositions : clustererShadow.mPpeakPositions;
393 if (doGPU) {
394 const uint32_t iSector = clusterer.mISector;
395 auto& count = stage ? clusterer.mPmemory->counters.nPeaks : clusterer.mPmemory->counters.nPositions;
396
397 std::vector<size_t> counts;
398
399 uint32_t nSteps = clusterer.getNSteps(count);
400 if (nSteps > clusterer.mNBufs) {
401 GPUError("Clusterer buffers exceeded (%u > %u)", nSteps, (int32_t)clusterer.mNBufs);
402 exit(1);
403 }
404
405 int32_t scanWorkgroupSize = mRec->getGPUParameters(doGPU).par_CF_SCAN_WORKGROUP_SIZE;
406 size_t tmpCount = count;
407 if (nSteps > 1) {
408 for (uint32_t i = 1; i < nSteps; i++) {
409 counts.push_back(tmpCount);
410 if (i == 1) {
411 runKernel<GPUTPCCFStreamCompaction, GPUTPCCFStreamCompaction::scanStart>({GetGrid(tmpCount, scanWorkgroupSize, lane), {iSector}}, i, stage);
412 } else {
413 runKernel<GPUTPCCFStreamCompaction, GPUTPCCFStreamCompaction::scanUp>({GetGrid(tmpCount, scanWorkgroupSize, lane), {iSector}}, i, tmpCount);
414 }
415 tmpCount = (tmpCount + scanWorkgroupSize - 1) / scanWorkgroupSize;
416 }
417
418 runKernel<GPUTPCCFStreamCompaction, GPUTPCCFStreamCompaction::scanTop>({GetGrid(tmpCount, scanWorkgroupSize, lane), {iSector}}, nSteps, tmpCount);
419
420 for (uint32_t i = nSteps - 1; i > 1; i--) {
421 tmpCount = counts[i - 1];
422 runKernel<GPUTPCCFStreamCompaction, GPUTPCCFStreamCompaction::scanDown>({GetGrid(tmpCount - scanWorkgroupSize, scanWorkgroupSize, lane), {iSector}}, i, scanWorkgroupSize, tmpCount);
423 }
424 }
425
426 runKernel<GPUTPCCFStreamCompaction, GPUTPCCFStreamCompaction::compactDigits>({GetGrid(count, scanWorkgroupSize, lane), {iSector}}, 1, stage, in, out);
427 } else {
428 auto& nOut = stage ? clusterer.mPmemory->counters.nClusters : clusterer.mPmemory->counters.nPeaks;
429 auto& nIn = stage ? clusterer.mPmemory->counters.nPeaks : clusterer.mPmemory->counters.nPositions;
430 size_t count = 0;
431 for (size_t i = 0; i < nIn; i++) {
432 if (clusterer.mPisPeak[i]) {
433 out[count++] = in[i];
434 }
435 }
436 nOut = count;
437 }
438}
439
440std::pair<uint32_t, uint32_t> GPUChainTracking::RunTPCClusterizer_transferZS(int32_t iSector, const CfFragment& fragment, int32_t lane)
441{
442 bool doGPU = GetRecoStepsGPU() & RecoStep::TPCClusterFinding;
443 if (mCFContext->abandonTimeframe) {
444 return {0, 0};
445 }
446 const auto& retVal = TPCClusterizerDecodeZSCountUpdate(iSector, fragment);
447 if (doGPU) {
448 GPUTPCClusterFinder& clusterer = processors()->tpcClusterer[iSector];
449 GPUTPCClusterFinder& clustererShadow = doGPU ? processorsShadow()->tpcClusterer[iSector] : clusterer;
450 uint32_t nPagesSector = 0;
451 for (uint32_t j = 0; j < GPUTrackingInOutZS::NENDPOINTS; j++) {
452 uint32_t nPages = 0;
453 mInputsHost->mPzsMeta->sector[iSector].zsPtr[j] = &mInputsShadow->mPzsPtrs[iSector * GPUTrackingInOutZS::NENDPOINTS + j];
454 mInputsHost->mPzsPtrs[iSector * GPUTrackingInOutZS::NENDPOINTS + j] = clustererShadow.mPzs + (nPagesSector + nPages) * TPCZSHDR::TPC_ZS_PAGE_SIZE;
455 for (uint32_t k = clusterer.mMinMaxCN[j].zsPtrFirst; k < clusterer.mMinMaxCN[j].zsPtrLast; k++) {
456 const uint32_t min = (k == clusterer.mMinMaxCN[j].zsPtrFirst) ? clusterer.mMinMaxCN[j].zsPageFirst : 0;
457 const uint32_t max = (k + 1 == clusterer.mMinMaxCN[j].zsPtrLast) ? clusterer.mMinMaxCN[j].zsPageLast : mIOPtrs.tpcZS->sector[iSector].nZSPtr[j][k];
458 if (max > min) {
459 char* src = (char*)mIOPtrs.tpcZS->sector[iSector].zsPtr[j][k] + min * TPCZSHDR::TPC_ZS_PAGE_SIZE;
460 char* ptrLast = (char*)mIOPtrs.tpcZS->sector[iSector].zsPtr[j][k] + (max - 1) * TPCZSHDR::TPC_ZS_PAGE_SIZE;
461 size_t size = (ptrLast - src) + o2::raw::RDHUtils::getMemorySize(*(const o2::header::RAWDataHeader*)ptrLast);
462 GPUMemCpy(RecoStep::TPCClusterFinding, clustererShadow.mPzs + (nPagesSector + nPages) * TPCZSHDR::TPC_ZS_PAGE_SIZE, src, size, lane, true);
463 }
464 nPages += max - min;
465 }
466 mInputsHost->mPzsMeta->sector[iSector].nZSPtr[j] = &mInputsShadow->mPzsSizes[iSector * GPUTrackingInOutZS::NENDPOINTS + j];
467 mInputsHost->mPzsSizes[iSector * GPUTrackingInOutZS::NENDPOINTS + j] = nPages;
468 mInputsHost->mPzsMeta->sector[iSector].count[j] = 1;
469 nPagesSector += nPages;
470 }
471 GPUMemCpy(RecoStep::TPCClusterFinding, clustererShadow.mPzsOffsets, clusterer.mPzsOffsets, clusterer.mNMaxPages * sizeof(*clusterer.mPzsOffsets), lane, true);
472 }
473 return retVal;
474}
475
476int32_t GPUChainTracking::RunTPCClusterizer_prepare(bool restorePointers)
477{
479 if (restorePointers) {
480 for (uint32_t iSector = 0; iSector < NSECTORS; iSector++) {
481 processors()->tpcClusterer[iSector].mPzsOffsets = mCFContext->ptrSave[iSector].zsOffsetHost;
482 processorsShadow()->tpcClusterer[iSector].mPzsOffsets = mCFContext->ptrSave[iSector].zsOffsetDevice;
483 processorsShadow()->tpcClusterer[iSector].mPzs = mCFContext->ptrSave[iSector].zsDevice;
484 }
485 processorsShadow()->ioPtrs.clustersNative = mCFContext->ptrClusterNativeSave;
486 return 0;
487 }
488 const auto& threadContext = GetThreadContext();
490 if (mCFContext == nullptr) {
492 }
493 const int16_t maxFragmentLen = GetProcessingSettings().overrideClusterizerFragmentLen;
494 const uint32_t maxAllowedTimebin = param().par.continuousTracking ? std::max<int32_t>(param().continuousMaxTimeBin, maxFragmentLen) : TPC_MAX_TIME_BIN_TRIGGERED;
495 mCFContext->tpcMaxTimeBin = maxAllowedTimebin;
496 const CfFragment fragmentMax{(tpccf::TPCTime)mCFContext->tpcMaxTimeBin + 1, maxFragmentLen};
497 mCFContext->prepare(mIOPtrs.tpcZS, fragmentMax);
498 if (GetProcessingSettings().param.tpcTriggerHandling) {
499 mTriggerBuffer->triggers.clear();
500 }
501 if (mIOPtrs.tpcZS) {
502 uint32_t nDigitsFragmentMax[NSECTORS];
503 mCFContext->zsVersion = -1;
504 for (uint32_t iSector = 0; iSector < NSECTORS; iSector++) {
505 if (mIOPtrs.tpcZS->sector[iSector].count[0]) {
506 const void* rdh = mIOPtrs.tpcZS->sector[iSector].zsPtr[0][0];
507 if (rdh && o2::raw::RDHUtils::getVersion<o2::header::RAWDataHeaderV6>() > o2::raw::RDHUtils::getVersion(rdh)) {
508 GPUError("Data has invalid RDH version %d, %d required\n", o2::raw::RDHUtils::getVersion(rdh), o2::raw::RDHUtils::getVersion<o2::header::RAWDataHeader>());
509 return 1;
510 }
511 }
512
513 if (GetProcessingSettings().prefetchTPCpageScan >= 1 && iSector < NSECTORS - 1) {
514 for (uint32_t j = 0; j < GPUTrackingInOutZS::NENDPOINTS; j++) {
515 for (uint32_t k = 0; k < mIOPtrs.tpcZS->sector[iSector].count[j]; k++) {
516 for (uint32_t l = 0; l < mIOPtrs.tpcZS->sector[iSector].nZSPtr[j][k]; l++) {
517 Vc::Common::prefetchFar(((const uint8_t*)mIOPtrs.tpcZS->sector[iSector + 1].zsPtr[j][k]) + l * TPCZSHDR::TPC_ZS_PAGE_SIZE);
518 Vc::Common::prefetchFar(((const uint8_t*)mIOPtrs.tpcZS->sector[iSector + 1].zsPtr[j][k]) + l * TPCZSHDR::TPC_ZS_PAGE_SIZE + sizeof(o2::header::RAWDataHeader));
519 }
520 }
521 }
522 }
523
524 const auto& x = TPCClusterizerDecodeZSCount(iSector, fragmentMax);
525 nDigitsFragmentMax[iSector] = x.first;
526 processors()->tpcClusterer[iSector].mPmemory->counters.nDigits = x.first;
527 mRec->MemoryScalers()->nTPCdigits += x.first;
528 }
529 for (uint32_t iSector = 0; iSector < NSECTORS; iSector++) {
530 uint32_t nDigitsBase = nDigitsFragmentMax[iSector];
531 uint32_t threshold = 40000000;
532 uint32_t nDigitsScaled = nDigitsBase > threshold ? nDigitsBase : std::min((threshold + nDigitsBase) / 2, 2 * nDigitsBase);
533 processors()->tpcClusterer[iSector].SetNMaxDigits(processors()->tpcClusterer[iSector].mPmemory->counters.nDigits, mCFContext->nPagesFragmentMax, nDigitsScaled, mCFContext->nDigitsEndpointMax[iSector]);
534 if (doGPU) {
535 processorsShadow()->tpcClusterer[iSector].SetNMaxDigits(processors()->tpcClusterer[iSector].mPmemory->counters.nDigits, mCFContext->nPagesFragmentMax, nDigitsScaled, mCFContext->nDigitsEndpointMax[iSector]);
536 }
537 if (mPipelineNotifyCtx && GetProcessingSettings().doublePipelineClusterizer) {
538 mPipelineNotifyCtx->rec->AllocateRegisteredForeignMemory(processors()->tpcClusterer[iSector].mZSOffsetId, mRec);
539 mPipelineNotifyCtx->rec->AllocateRegisteredForeignMemory(processors()->tpcClusterer[iSector].mZSId, mRec);
540 } else {
541 AllocateRegisteredMemory(processors()->tpcClusterer[iSector].mZSOffsetId);
542 AllocateRegisteredMemory(processors()->tpcClusterer[iSector].mZSId);
543 }
544 }
545 } else {
546 for (uint32_t iSector = 0; iSector < NSECTORS; iSector++) {
547 uint32_t nDigits = mIOPtrs.tpcPackedDigits->nTPCDigits[iSector];
548 mRec->MemoryScalers()->nTPCdigits += nDigits;
549 processors()->tpcClusterer[iSector].SetNMaxDigits(nDigits, mCFContext->nPagesFragmentMax, nDigits, 0);
550 }
551 }
552
553 if (mIOPtrs.tpcZS) {
554 GPUInfo("Event has %u 8kb TPC ZS pages (version %d), %ld digits", mCFContext->nPagesTotal, mCFContext->zsVersion, (int64_t)mRec->MemoryScalers()->nTPCdigits);
555 } else {
556 GPUInfo("Event has %ld TPC Digits", (int64_t)mRec->MemoryScalers()->nTPCdigits);
557 }
558
559 if (mCFContext->tpcMaxTimeBin > maxAllowedTimebin) {
560 GPUError("Input data has invalid time bin %u > %d", mCFContext->tpcMaxTimeBin, maxAllowedTimebin);
561 if (GetProcessingSettings().ignoreNonFatalGPUErrors) {
562 mCFContext->abandonTimeframe = true;
563 mCFContext->tpcMaxTimeBin = maxAllowedTimebin;
564 } else {
565 return 1;
566 }
567 }
568
569 mCFContext->fragmentFirst = CfFragment{std::max<int32_t>(mCFContext->tpcMaxTimeBin + 1, maxFragmentLen), maxFragmentLen};
570 for (int32_t iSector = 0; iSector < GetProcessingSettings().nTPCClustererLanes && iSector < NSECTORS; iSector++) {
571 if (mIOPtrs.tpcZS && mCFContext->nPagesSector[iSector] && mCFContext->zsVersion != -1) {
572 mCFContext->nextPos[iSector] = RunTPCClusterizer_transferZS(iSector, mCFContext->fragmentFirst, GetProcessingSettings().nTPCClustererLanes + iSector);
573 }
574 }
575
576 if (mPipelineNotifyCtx && GetProcessingSettings().doublePipelineClusterizer) {
577 for (uint32_t iSector = 0; iSector < NSECTORS; iSector++) {
578 mCFContext->ptrSave[iSector].zsOffsetHost = processors()->tpcClusterer[iSector].mPzsOffsets;
579 mCFContext->ptrSave[iSector].zsOffsetDevice = processorsShadow()->tpcClusterer[iSector].mPzsOffsets;
580 mCFContext->ptrSave[iSector].zsDevice = processorsShadow()->tpcClusterer[iSector].mPzs;
581 }
582 }
583 return 0;
584}
585#endif
586
587int32_t GPUChainTracking::RunTPCClusterizer(bool synchronizeOutput)
588{
589 if (param().rec.fwdTPCDigitsAsClusters) {
590 return ForwardTPCDigits();
591 }
592#ifdef GPUCA_TPC_GEOMETRY_O2
593 int32_t tpcTimeBinCut = (mUpdateNewCalibObjects && mNewCalibValues->newTPCTimeBinCut) ? mNewCalibValues->tpcTimeBinCut : param().tpcCutTimeBin;
594
596 const auto& threadContext = GetThreadContext();
597 const bool doGPU = GetRecoStepsGPU() & RecoStep::TPCClusterFinding;
598 if (RunTPCClusterizer_prepare(mPipelineNotifyCtx && GetProcessingSettings().doublePipelineClusterizer)) {
599 return 1;
600 }
601 if (GetProcessingSettings().autoAdjustHostThreads && !doGPU) {
603 }
604
606 float tpcHitLowOccupancyScalingFactor = 1.f;
608 uint32_t nHitsBase = mRec->MemoryScalers()->nTPCHits;
609 uint32_t threshold = 30000000 / 256 * mIOPtrs.settingsTF->nHBFPerTF;
610 if (mIOPtrs.settingsTF->nHBFPerTF < 64) {
611 threshold *= 2;
612 }
613 mRec->MemoryScalers()->nTPCHits = std::max<uint32_t>(nHitsBase, std::min<uint32_t>(threshold, nHitsBase * 3.5f)); // Increase the buffer size for low occupancy data to compensate for noisy pads creating exceiive clusters
614 if (nHitsBase < threshold) {
615 float maxFactor = mRec->MemoryScalers()->nTPCHits < threshold * 2 / 3 ? 3 : (mRec->MemoryScalers()->nTPCHits < threshold ? 2.25f : 1.75f);
616 mRec->MemoryScalers()->temporaryFactor *= std::min(maxFactor, (float)threshold / nHitsBase);
617 tpcHitLowOccupancyScalingFactor = std::min(3.5f, (float)threshold / nHitsBase);
618 }
619 }
620 for (uint32_t iSector = 0; iSector < NSECTORS; iSector++) {
621 processors()->tpcClusterer[iSector].SetMaxData(mIOPtrs); // First iteration to set data sizes
622 }
623 mRec->ComputeReuseMax(nullptr); // Resolve maximums for shared buffers
624 for (uint32_t iSector = 0; iSector < NSECTORS; iSector++) {
625 SetupGPUProcessor(&processors()->tpcClusterer[iSector], true); // Now we allocate
626 }
627 if (mPipelineNotifyCtx && GetProcessingSettings().doublePipelineClusterizer) {
628 RunTPCClusterizer_prepare(true); // Restore some pointers, allocated by the other pipeline, and set to 0 by SetupGPUProcessor (since not allocated in this pipeline)
629 }
630
631 if (doGPU && mIOPtrs.tpcZS) {
633 WriteToConstantMemory(RecoStep::TPCClusterFinding, (char*)&processors()->ioPtrs - (char*)processors(), &processorsShadow()->ioPtrs, sizeof(processorsShadow()->ioPtrs), mRec->NStreams() - 1);
634 }
635 if (doGPU) {
636 WriteToConstantMemory(RecoStep::TPCClusterFinding, (char*)processors()->tpcClusterer - (char*)processors(), processorsShadow()->tpcClusterer, sizeof(GPUTPCClusterFinder) * NSECTORS, mRec->NStreams() - 1, &mEvents->init);
637 }
638
639#ifdef GPUCA_HAS_ONNX
640 const GPUSettingsProcessingNNclusterizer& nn_settings = GetProcessingSettings().nn;
641 GPUTPCNNClusterizerHost nnApplications[GetProcessingSettings().nTPCClustererLanes];
642
643 // Maximum of 4 lanes supported
644 HighResTimer* nnTimers[12];
645
646 if (nn_settings.applyNNclusterizer) {
647 int32_t deviceId = -1;
648 int32_t numLanes = GetProcessingSettings().nTPCClustererLanes;
649 int32_t maxThreads = mRec->getNKernelHostThreads(true);
650 // bool recreateMemoryAllocator = false;
651
652 if (GetProcessingSettings().debugLevel >= 1) {
653 nnTimers[0] = &getTimer<GPUTPCNNClusterizer, 0>("GPUTPCNNClusterizer_ONNXClassification_0_", 0);
654 nnTimers[1] = &getTimer<GPUTPCNNClusterizer, 1>("GPUTPCNNClusterizer_ONNXRegression_1_", 1);
655 nnTimers[2] = &getTimer<GPUTPCNNClusterizer, 2>("GPUTPCNNClusterizer_ONNXRegression2_2_", 2);
656 nnTimers[3] = &getTimer<GPUTPCNNClusterizer, 3>("GPUTPCNNClusterizer_ONNXClassification_0_", 3);
657 nnTimers[4] = &getTimer<GPUTPCNNClusterizer, 4>("GPUTPCNNClusterizer_ONNXRegression_1_", 4);
658 nnTimers[5] = &getTimer<GPUTPCNNClusterizer, 5>("GPUTPCNNClusterizer_ONNXRegression2_2_", 5);
659 nnTimers[6] = &getTimer<GPUTPCNNClusterizer, 6>("GPUTPCNNClusterizer_ONNXClassification_0_", 6);
660 nnTimers[7] = &getTimer<GPUTPCNNClusterizer, 7>("GPUTPCNNClusterizer_ONNXRegression_1_", 7);
661 nnTimers[8] = &getTimer<GPUTPCNNClusterizer, 8>("GPUTPCNNClusterizer_ONNXRegression2_2_", 8);
662 nnTimers[9] = &getTimer<GPUTPCNNClusterizer, 9>("GPUTPCNNClusterizer_ONNXClassification_0_", 9);
663 nnTimers[10] = &getTimer<GPUTPCNNClusterizer, 10>("GPUTPCNNClusterizer_ONNXRegression_1_", 10);
664 nnTimers[11] = &getTimer<GPUTPCNNClusterizer, 11>("GPUTPCNNClusterizer_ONNXRegression2_2_", 11);
665 }
666
667 mRec->runParallelOuterLoop(doGPU, numLanes, [&](uint32_t lane) {
668 nnApplications[lane].init(nn_settings, GetProcessingSettings().deterministicGPUReconstruction);
669 if (nnApplications[lane].mModelsUsed[0]) {
670 SetONNXGPUStream(*(nnApplications[lane].mModelClass).getSessionOptions(), lane, &deviceId);
671 (nnApplications[lane].mModelClass).setDeviceId(deviceId);
672 if (nnApplications[lane].mModelClass.getIntraOpNumThreads() > maxThreads) {
673 nnApplications[lane].mModelClass.setIntraOpNumThreads(maxThreads);
674 }
675 (nnApplications[lane].mModelClass).initEnvironment();
676 // Registering this once seems to be enough, even with different environmnents / models. ONNX apparently uses this per device and stores the OrtAllocator internally. All models will then use the volatile allocation.
677 // But environment must be valid, so we init the model environment first and use it here afterwards.
678 // Either this is done in one environment with lane == 0 or by recreating the allocator using recreateMemoryAllocator.
679 // TODO: Volatile allocation works for reserving, but not yet for allocations when binding the input tensor
680 // if (lane == 0) {
681 // nnApplications[lane].directOrtAllocator((nnApplications[lane].mModelClass).getEnv(), (nnApplications[lane].mModelClass).getMemoryInfo(), mRec, recreateMemoryAllocator);
682 // }
683 // recreateMemoryAllocator = true;
684 if (!nn_settings.nnLoadFromCCDB) {
685 (nnApplications[lane].mModelClass).initSession(); // loads from file
686 } else {
687 (nnApplications[lane].mModelClass).initSessionFromBuffer((processors()->calibObjects.nnClusterizerNetworks[0])->getONNXModel(), (processors()->calibObjects.nnClusterizerNetworks[0])->getONNXModelSize()); // loads from CCDB
688 }
689 }
690 if (nnApplications[lane].mModelsUsed[1]) {
691 SetONNXGPUStream(*(nnApplications[lane].mModelReg1).getSessionOptions(), lane, &deviceId);
692 (nnApplications[lane].mModelReg1).setDeviceId(deviceId);
693 if (nnApplications[lane].mModelReg1.getIntraOpNumThreads() > maxThreads) {
694 nnApplications[lane].mModelReg1.setIntraOpNumThreads(maxThreads);
695 }
696 // (nnApplications[lane].mModelReg1).setEnv((nnApplications[lane].mModelClass).getEnv());
697 (nnApplications[lane].mModelReg1).initEnvironment();
698 // nnApplications[lane].directOrtAllocator((nnApplications[lane].mModelReg1).getEnv(), (nnApplications[lane].mModelReg1).getMemoryInfo(), mRec, recreateMemoryAllocator);
699 if (!nn_settings.nnLoadFromCCDB) {
700 (nnApplications[lane].mModelReg1).initSession(); // loads from file
701 } else {
702 (nnApplications[lane].mModelReg1).initSessionFromBuffer((processors()->calibObjects.nnClusterizerNetworks[1])->getONNXModel(), (processors()->calibObjects.nnClusterizerNetworks[1])->getONNXModelSize()); // loads from CCDB
703 }
704 }
705 if (nnApplications[lane].mModelsUsed[2]) {
706 SetONNXGPUStream(*(nnApplications[lane].mModelReg2).getSessionOptions(), lane, &deviceId);
707 (nnApplications[lane].mModelReg2).setDeviceId(deviceId);
708 if (nnApplications[lane].mModelReg2.getIntraOpNumThreads() > maxThreads) {
709 nnApplications[lane].mModelReg2.setIntraOpNumThreads(maxThreads);
710 }
711 // (nnApplications[lane].mModelReg2).setEnv((nnApplications[lane].mModelClass).getEnv());
712 (nnApplications[lane].mModelReg2).initEnvironment();
713 // nnApplications[lane].directOrtAllocator((nnApplications[lane].mModelClass).getEnv(), (nnApplications[lane].mModelClass).getMemoryInfo(), mRec, recreateMemoryAllocator);
714 if (!nn_settings.nnLoadFromCCDB) {
715 (nnApplications[lane].mModelReg2).initSession(); // loads from file
716 } else {
717 (nnApplications[lane].mModelReg2).initSessionFromBuffer((processors()->calibObjects.nnClusterizerNetworks[2])->getONNXModel(), (processors()->calibObjects.nnClusterizerNetworks[2])->getONNXModelSize()); // loads from CCDB
718 }
719 }
720 if (nn_settings.nnClusterizerVerbosity > 0) {
721 LOG(info) << "(ORT) Allocated ONNX stream for lane " << lane << " and device " << deviceId;
722 }
723 });
724 const int16_t maxFragmentLen = GetProcessingSettings().overrideClusterizerFragmentLen;
725 const uint32_t maxAllowedTimebin = param().par.continuousTracking ? std::max<int32_t>(param().continuousMaxTimeBin, maxFragmentLen) : TPC_MAX_TIME_BIN_TRIGGERED;
726 for (int32_t sector = 0; sector < NSECTORS; sector++) {
727 GPUTPCNNClusterizer& clustererNN = processors()->tpcNNClusterer[sector];
728 GPUTPCNNClusterizer& clustererNNShadow = doGPU ? processorsShadow()->tpcNNClusterer[sector] : clustererNN;
729 int32_t lane = sector % numLanes;
730 clustererNN.mDeviceId = deviceId;
731 clustererNN.mISector = sector;
733 nnApplications[lane].initClusterizer(nn_settings, clustererNN, maxFragmentLen, maxAllowedTimebin);
734 if (doGPU) {
735 clustererNNShadow.mDeviceId = deviceId;
736 clustererNNShadow.mISector = sector;
738 nnApplications[lane].initClusterizer(nn_settings, clustererNNShadow, maxFragmentLen, maxAllowedTimebin);
739 }
740 if (nn_settings.nnClusterizerVerbosity > 2) {
741 LOG(info) << "(NNCLUS, GPUChainTrackingClusterizer, this=" << this << ") Processor initialized. Sector " << sector << ", lane " << lane << ", max clusters " << clustererNN.mNnClusterizerTotalClusters << " (clustererNN=" << &clustererNN << ", clustererNNShadow=" << &clustererNNShadow << ")";
742 }
744 if (nn_settings.nnClusterizerVerbosity > 2) {
745 LOG(info) << "(NNCLUS, GPUChainTrackingClusterizer, this=" << this << ") Memory registered for memoryId " << clustererNN.mMemoryId << " (clustererNN=" << &clustererNN << ", clustererNNShadow=" << &clustererNNShadow << ")";
746 }
747 // nnApplications[lane].createBoundary(clustererNNShadow);
748 // nnApplications[lane].createIndexLookup(clustererNNShadow);
749 }
750 if (doGPU) {
751 if (nn_settings.nnClusterizerVerbosity > 2) {
752 LOG(info) << "(NNCLUS, GPUChainTrackingClusterizer, this=" << this << ") Writing to constant memory...";
753 }
754 WriteToConstantMemory(RecoStep::TPCClusterFinding, (char*)&processors()->tpcNNClusterer - (char*)processors(), &processorsShadow()->tpcNNClusterer, sizeof(GPUTPCNNClusterizer) * NSECTORS, mRec->NStreams() - 1, &mEvents->init);
755 if (nn_settings.nnClusterizerVerbosity > 2) {
756 LOG(info) << "(NNCLUS, GPUChainTrackingClusterizer, this=" << this << ") Writing to constant memory done";
757 }
758 }
759 }
760#endif
761
762 size_t nClsTotal = 0;
763 ClusterNativeAccess* tmpNativeAccess = mClusterNativeAccess.get();
764 ClusterNative* tmpNativeClusters = nullptr;
765 std::unique_ptr<ClusterNative[]> tmpNativeClusterBuffer;
766
767 const bool buildNativeGPU = doGPU && NeedTPCClustersOnGPU();
768 const bool buildNativeHost = (mRec->GetRecoStepsOutputs() & gpudatatypes::InOutType::TPCClusters) || GetProcessingSettings().deterministicGPUReconstruction; // TODO: Should do this also when clusters are needed for later steps on the host but not requested as output
769 const bool propagateMCLabels = buildNativeHost && GetProcessingSettings().runMC && processors()->ioPtrs.tpcPackedDigits && processors()->ioPtrs.tpcPackedDigits->tpcDigitsMC;
770 const bool sortClusters = buildNativeHost && (GetProcessingSettings().deterministicGPUReconstruction || GetProcessingSettings().debugLevel >= 4);
771
772 auto* digitsMC = propagateMCLabels ? processors()->ioPtrs.tpcPackedDigits->tpcDigitsMC : nullptr;
773
774 mInputsHost->mNClusterNative = mInputsShadow->mNClusterNative = mRec->MemoryScalers()->nTPCHits * tpcHitLowOccupancyScalingFactor;
775 if (buildNativeGPU) {
776 AllocateRegisteredMemory(mInputsHost->mResourceClusterNativeBuffer);
777 }
778 if (mWaitForFinalInputs && GetProcessingSettings().nTPCClustererLanes > 6) {
779 GPUFatal("ERROR, mWaitForFinalInputs cannot be called with nTPCClustererLanes > 6");
780 }
781 if (buildNativeHost && !(buildNativeGPU && GetProcessingSettings().delayedOutput)) {
782 if (mWaitForFinalInputs) {
783 GPUFatal("Cannot use waitForFinalInput callback without delayed output");
784 }
785 if (!GetProcessingSettings().tpcApplyClusterFilterOnCPU) {
786 AllocateRegisteredMemory(mInputsHost->mResourceClusterNativeOutput, GetProcessingSettings().tpcWriteClustersAfterRejection ? nullptr : mSubOutputControls[GPUTrackingOutputs::getIndex(&GPUTrackingOutputs::clustersNative)]);
787 tmpNativeClusters = mInputsHost->mPclusterNativeOutput;
788 } else {
789 tmpNativeClusterBuffer = std::make_unique<ClusterNative[]>(mInputsHost->mNClusterNative);
790 tmpNativeClusters = tmpNativeClusterBuffer.get();
791 }
792 }
793
794 GPUTPCLinearLabels mcLinearLabels;
795 if (propagateMCLabels) {
796 // No need to overallocate here, nTPCHits is anyway an upper bound used for the GPU cluster buffer, and we can always enlarge the buffer anyway
797 mcLinearLabels.header.reserve(mRec->MemoryScalers()->nTPCHits / 2);
798 mcLinearLabels.data.reserve(mRec->MemoryScalers()->nTPCHits);
799 }
800
801 int8_t transferRunning[NSECTORS] = {0};
802 uint32_t outputQueueStart = mOutputQueue.size();
803
804 auto notifyForeignChainFinished = [this]() {
805 if (mPipelineNotifyCtx) {
806 SynchronizeStream(OutputStream()); // Must finish before updating ioPtrs in (global) constant memory
807 {
808 std::lock_guard<std::mutex> lock(mPipelineNotifyCtx->mutex);
809 mPipelineNotifyCtx->ready = true;
810 }
811 mPipelineNotifyCtx->cond.notify_one();
812 }
813 };
814 bool synchronizeCalibUpdate = false;
815
816 for (uint32_t iSectorBase = 0; iSectorBase < NSECTORS; iSectorBase += GetProcessingSettings().nTPCClustererLanes) {
817 std::vector<bool> laneHasData(GetProcessingSettings().nTPCClustererLanes, false);
818 static_assert(NSECTORS <= GPUCA_MAX_STREAMS, "Stream events must be able to hold all sectors");
819 const int32_t maxLane = std::min<int32_t>(GetProcessingSettings().nTPCClustererLanes, NSECTORS - iSectorBase);
820 for (CfFragment fragment = mCFContext->fragmentFirst; !fragment.isEnd(); fragment = fragment.next()) {
821 if (GetProcessingSettings().debugLevel >= 3) {
822 GPUInfo("Processing time bins [%d, %d) for sectors %d to %d", fragment.start, fragment.last(), iSectorBase, iSectorBase + GetProcessingSettings().nTPCClustererLanes - 1);
823 }
824 mRec->runParallelOuterLoop(doGPU, maxLane, [&](uint32_t lane) {
825 if (doGPU && fragment.index != 0) {
826 SynchronizeStream(lane); // Don't overwrite charge map from previous iteration until cluster computation is finished
827 }
828
829 uint32_t iSector = iSectorBase + lane;
830 GPUTPCClusterFinder& clusterer = processors()->tpcClusterer[iSector];
831 GPUTPCClusterFinder& clustererShadow = doGPU ? processorsShadow()->tpcClusterer[iSector] : clusterer;
832 clusterer.mPmemory->counters.nPeaks = clusterer.mPmemory->counters.nClusters = 0;
833 clusterer.mPmemory->fragment = fragment;
834
836 bool setDigitsOnGPU = doGPU && not mIOPtrs.tpcZS;
837 bool setDigitsOnHost = (not doGPU && not mIOPtrs.tpcZS) || propagateMCLabels;
838 auto* inDigits = mIOPtrs.tpcPackedDigits;
839 size_t numDigits = inDigits->nTPCDigits[iSector];
840 if (setDigitsOnGPU) {
841 GPUMemCpy(RecoStep::TPCClusterFinding, clustererShadow.mPdigits, inDigits->tpcDigits[iSector], sizeof(clustererShadow.mPdigits[0]) * numDigits, lane, true);
842 }
843 if (setDigitsOnHost) {
844 clusterer.mPdigits = const_cast<o2::tpc::Digit*>(inDigits->tpcDigits[iSector]); // TODO: Needs fixing (invalid const cast)
845 }
846 clusterer.mPmemory->counters.nDigits = numDigits;
847 }
848
849 if (mIOPtrs.tpcZS) {
850 if (mCFContext->nPagesSector[iSector] && mCFContext->zsVersion != -1) {
851 clusterer.mPmemory->counters.nPositions = mCFContext->nextPos[iSector].first;
852 clusterer.mPmemory->counters.nPagesSubsector = mCFContext->nextPos[iSector].second;
853 } else {
854 clusterer.mPmemory->counters.nPositions = clusterer.mPmemory->counters.nPagesSubsector = 0;
855 }
856 }
857 TransferMemoryResourceLinkToGPU(RecoStep::TPCClusterFinding, clusterer.mMemoryId, lane);
858
859 using ChargeMapType = decltype(*clustererShadow.mPchargeMap);
860 using PeakMapType = decltype(*clustererShadow.mPpeakMap);
861 runKernel<GPUMemClean16>({GetGridAutoStep(lane, RecoStep::TPCClusterFinding)}, clustererShadow.mPchargeMap, TPCMapMemoryLayout<ChargeMapType>::items(GetProcessingSettings().overrideClusterizerFragmentLen) * sizeof(ChargeMapType));
862 runKernel<GPUMemClean16>({GetGridAutoStep(lane, RecoStep::TPCClusterFinding)}, clustererShadow.mPpeakMap, TPCMapMemoryLayout<PeakMapType>::items(GetProcessingSettings().overrideClusterizerFragmentLen) * sizeof(PeakMapType));
863 if (fragment.index == 0) {
864 runKernel<GPUMemClean16>({GetGridAutoStep(lane, RecoStep::TPCClusterFinding)}, clustererShadow.mPpadIsNoisy, TPC_PADS_IN_SECTOR * sizeof(*clustererShadow.mPpadIsNoisy));
865 }
867
868 if (doGPU) {
869 if (mIOPtrs.tpcZS && mCFContext->nPagesSector[iSector] && mCFContext->zsVersion != -1) {
870 TransferMemoryResourceLinkToGPU(RecoStep::TPCClusterFinding, mInputsHost->mResourceZS, lane);
871 SynchronizeStream(GetProcessingSettings().nTPCClustererLanes + lane);
872 }
873 SynchronizeStream(mRec->NStreams() - 1); // Wait for copying to constant memory
874 }
875
876 if (mIOPtrs.tpcZS && (mCFContext->abandonTimeframe || !mCFContext->nPagesSector[iSector] || mCFContext->zsVersion == -1)) {
877 clusterer.mPmemory->counters.nPositions = 0;
878 return;
879 }
880 if (!mIOPtrs.tpcZS && mIOPtrs.tpcPackedDigits->nTPCDigits[iSector] == 0) {
881 clusterer.mPmemory->counters.nPositions = 0;
882 return;
883 }
884
885 if (propagateMCLabels && fragment.index == 0) {
886 clusterer.PrepareMC();
887 clusterer.mPinputLabels = digitsMC->v[iSector];
888 if (clusterer.mPinputLabels == nullptr) {
889 GPUFatal("MC label container missing, sector %d", iSector);
890 }
891 if (clusterer.mPinputLabels->getIndexedSize() != mIOPtrs.tpcPackedDigits->nTPCDigits[iSector]) {
892 GPUFatal("MC label container has incorrect number of entries: %d expected, has %d\n", (int32_t)mIOPtrs.tpcPackedDigits->nTPCDigits[iSector], (int32_t)clusterer.mPinputLabels->getIndexedSize());
893 }
894 }
895
896 if (GetProcessingSettings().tpcSingleSector == -1 || GetProcessingSettings().tpcSingleSector == (int32_t)iSector) {
897 if (not mIOPtrs.tpcZS) {
898 runKernel<GPUTPCCFChargeMapFiller, GPUTPCCFChargeMapFiller::findFragmentStart>({GetGrid(1, lane), {iSector}}, mIOPtrs.tpcZS == nullptr);
899 TransferMemoryResourceLinkToHost(RecoStep::TPCClusterFinding, clusterer.mMemoryId, lane);
900 } else if (propagateMCLabels) {
901 runKernel<GPUTPCCFChargeMapFiller, GPUTPCCFChargeMapFiller::findFragmentStart>({GetGrid(1, lane, GPUReconstruction::krnlDeviceType::CPU), {iSector}}, mIOPtrs.tpcZS == nullptr);
902 TransferMemoryResourceLinkToGPU(RecoStep::TPCClusterFinding, clusterer.mMemoryId, lane);
903 }
904 }
905
906 if (mIOPtrs.tpcZS) {
907 int32_t firstHBF = (mIOPtrs.settingsTF && mIOPtrs.settingsTF->hasTfStartOrbit) ? mIOPtrs.settingsTF->tfStartOrbit : ((mIOPtrs.tpcZS->sector[iSector].count[0] && mIOPtrs.tpcZS->sector[iSector].nZSPtr[0][0]) ? o2::raw::RDHUtils::getHeartBeatOrbit(*(const o2::header::RAWDataHeader*)mIOPtrs.tpcZS->sector[iSector].zsPtr[0][0]) : 0);
908 uint32_t nBlocks = doGPU ? clusterer.mPmemory->counters.nPagesSubsector : GPUTrackingInOutZS::NENDPOINTS;
909
910 switch (mCFContext->zsVersion) {
911 default:
912 GPUFatal("Data with invalid TPC ZS mode (%d) received", mCFContext->zsVersion);
913 break;
916 runKernel<GPUTPCCFDecodeZS>({GetGridBlk(nBlocks, lane), {iSector}}, firstHBF, tpcTimeBinCut);
917 break;
919 runKernel<GPUTPCCFDecodeZSLink>({GetGridBlk(nBlocks, lane), {iSector}}, firstHBF, tpcTimeBinCut);
920 break;
922 runKernel<GPUTPCCFDecodeZSDenseLink>({GetGridBlk(nBlocks, lane), {iSector}}, firstHBF, tpcTimeBinCut);
923 break;
924 }
925 TransferMemoryResourceLinkToHost(RecoStep::TPCClusterFinding, clusterer.mMemoryId, lane);
926 } // clang-format off
927 });
928 mRec->runParallelOuterLoop(doGPU, maxLane, [&](uint32_t lane) {
929 uint32_t iSector = iSectorBase + lane;
930 if (doGPU) {
931 SynchronizeStream(lane);
932 }
933 if (mIOPtrs.tpcZS) {
934 CfFragment f = fragment.next();
935 int32_t nextSector = iSector;
936 if (f.isEnd()) {
937 nextSector += GetProcessingSettings().nTPCClustererLanes;
938 f = mCFContext->fragmentFirst;
939 }
940 if (nextSector < NSECTORS && mIOPtrs.tpcZS && mCFContext->nPagesSector[nextSector] && mCFContext->zsVersion != -1 && !mCFContext->abandonTimeframe) {
941 mCFContext->nextPos[nextSector] = RunTPCClusterizer_transferZS(nextSector, f, GetProcessingSettings().nTPCClustererLanes + lane);
942 }
943 }
944 GPUTPCClusterFinder& clusterer = processors()->tpcClusterer[iSector];
945 GPUTPCClusterFinder& clustererShadow = doGPU ? processorsShadow()->tpcClusterer[iSector] : clusterer;
946 if (clusterer.mPmemory->counters.nPositions == 0) {
947 return;
948 }
949 if (!mIOPtrs.tpcZS) {
950 runKernel<GPUTPCCFChargeMapFiller, GPUTPCCFChargeMapFiller::fillFromDigits>({GetGrid(clusterer.mPmemory->counters.nPositions, lane), {iSector}});
951 }
953 clusterer.DumpChargeMap(*mDebugFile, "Charges");
954 }
955
956 if (propagateMCLabels) {
957 runKernel<GPUTPCCFChargeMapFiller, GPUTPCCFChargeMapFiller::fillIndexMap>({GetGrid(clusterer.mPmemory->counters.nDigitsInFragment, lane, GPUReconstruction::krnlDeviceType::CPU), {iSector}});
958 }
959
960 bool checkForNoisyPads = (rec()->GetParam().rec.tpc.maxTimeBinAboveThresholdIn1000Bin > 0) || (rec()->GetParam().rec.tpc.maxConsecTimeBinAboveThreshold > 0);
961 checkForNoisyPads &= (rec()->GetParam().rec.tpc.noisyPadsQuickCheck ? fragment.index == 0 : true);
962 checkForNoisyPads &= !GetProcessingSettings().disableTPCNoisyPadFilter;
963
964 if (checkForNoisyPads) {
966
967 runKernel<GPUTPCCFCheckPadBaseline>({GetGridBlk(nBlocks, lane), {iSector}});
968 getKernelTimer<GPUTPCCFCheckPadBaseline>(RecoStep::TPCClusterFinding, iSector, TPC_PADS_IN_SECTOR * fragment.lengthWithoutOverlap() * sizeof(PackedCharge), false);
969 }
970
971 runKernel<GPUTPCCFPeakFinder>({GetGrid(clusterer.mPmemory->counters.nPositions, lane), {iSector}});
973 clusterer.DumpPeakMap(*mDebugFile, "Peaks");
974 }
975
976 RunTPCClusterizer_compactPeaks(clusterer, clustererShadow, 0, doGPU, lane);
977 TransferMemoryResourceLinkToHost(RecoStep::TPCClusterFinding, clusterer.mMemoryId, lane);
978 DoDebugAndDump(RecoStep::TPCClusterFinding, GPUChainTrackingDebugFlags::TPCClustererPeaks, clusterer, &GPUTPCClusterFinder::DumpPeaksCompacted, *mDebugFile); // clang-format off
979 });
980 mRec->runParallelOuterLoop(doGPU, maxLane, [&](uint32_t lane) {
981 uint32_t iSector = iSectorBase + lane;
982 GPUTPCClusterFinder& clusterer = processors()->tpcClusterer[iSector];
983 GPUTPCClusterFinder& clustererShadow = doGPU ? processorsShadow()->tpcClusterer[iSector] : clusterer;
984 if (doGPU) {
985 SynchronizeStream(lane);
986 }
987 if (clusterer.mPmemory->counters.nPeaks == 0) {
988 return;
989 }
990 runKernel<GPUTPCCFNoiseSuppression, GPUTPCCFNoiseSuppression::noiseSuppression>({GetGrid(clusterer.mPmemory->counters.nPeaks, lane), {iSector}});
991 runKernel<GPUTPCCFNoiseSuppression, GPUTPCCFNoiseSuppression::updatePeaks>({GetGrid(clusterer.mPmemory->counters.nPeaks, lane), {iSector}});
993 clusterer.DumpPeakMap(*mDebugFile, "Suppressed Peaks");
994 }
995
996 RunTPCClusterizer_compactPeaks(clusterer, clustererShadow, 1, doGPU, lane);
997 TransferMemoryResourceLinkToHost(RecoStep::TPCClusterFinding, clusterer.mMemoryId, lane);
999 });
1000 mRec->runParallelOuterLoop(doGPU, maxLane, [&](uint32_t lane) {
1001 uint32_t iSector = iSectorBase + lane;
1002 GPUTPCClusterFinder& clusterer = processors()->tpcClusterer[iSector];
1003 GPUTPCClusterFinder& clustererShadow = doGPU ? processorsShadow()->tpcClusterer[iSector] : clusterer;
1004
1005 if (doGPU) {
1006 SynchronizeStream(lane);
1007 }
1008
1009 if (fragment.index == 0) {
1010 deviceEvent* waitEvent = nullptr;
1011 if (transferRunning[lane] == 1) {
1012 waitEvent = &mEvents->stream[lane];
1013 transferRunning[lane] = 2;
1014 }
1015 runKernel<GPUMemClean16>({GetGridAutoStep(lane, RecoStep::TPCClusterFinding), krnlRunRangeNone, {nullptr, waitEvent}}, clustererShadow.mPclusterInRow, GPUCA_ROW_COUNT * sizeof(*clustererShadow.mPclusterInRow));
1016 }
1017
1018 if (clusterer.mPmemory->counters.nClusters == 0) {
1019 return;
1020 }
1021
1022 if (GetProcessingSettings().nn.applyNNclusterizer) {
1023#ifdef GPUCA_HAS_ONNX
1024 GPUTPCNNClusterizer& clustererNN = processors()->tpcNNClusterer[lane];
1025 GPUTPCNNClusterizer& clustererNNShadow = doGPU ? processorsShadow()->tpcNNClusterer[lane] : clustererNN;
1026 GPUTPCNNClusterizerHost& nnApplication = nnApplications[lane];
1027
1028 // int withMC = (doGPU && propagateMCLabels);
1029
1030 if (nn_settings.nnClusterizerApplyCfDeconvolution) {
1031 runKernel<GPUTPCCFDeconvolution>({GetGrid(clusterer.mPmemory->counters.nPositions, lane), {iSector}}, true);
1032 } else if (clustererNNShadow.mNnClusterizerSetDeconvolutionFlags) {
1033 runKernel<GPUTPCCFDeconvolution>({GetGrid(clusterer.mPmemory->counters.nPositions, lane), {iSector}}, false);
1034 }
1035
1036 // float time_clusterizer = 0, time_fill = 0, time_networks = 0;
1037 if (nn_settings.nnClusterizerVerbosity > 2) {
1038 LOG(info) << "(NNCLUS, GPUChainTrackingClusterizer, this=" << this << ") Starting loop over batched data. clustererNNShadow.mNnClusterizerBatchedMode=" << clustererNNShadow.mNnClusterizerBatchedMode << ", numLoops=" << std::ceil((float)clusterer.mPmemory->counters.nClusters / clustererNNShadow.mNnClusterizerBatchedMode) << ", numClusters=" << clusterer.mPmemory->counters.nClusters << ". (clustererNN=" << &clustererNN << ", clustererNNShadow=" << &clustererNNShadow << ")";
1039 }
1040 for (int batch = 0; batch < std::ceil((float)clusterer.mPmemory->counters.nClusters / clustererNNShadow.mNnClusterizerBatchedMode); batch++) {
1041 if (nn_settings.nnClusterizerVerbosity > 3) {
1042 LOG(info) << "(NNCLUS, GPUChainTrackingClusterizer, this=" << this << ") Start. Loop=" << batch << ". (clustererNN=" << &clustererNN << ", clustererNNShadow=" << &clustererNNShadow << ")";
1043 }
1044 uint batchStart = batch * clustererNNShadow.mNnClusterizerBatchedMode;
1045 size_t iSize = CAMath::Min((uint)clustererNNShadow.mNnClusterizerBatchedMode, (uint)(clusterer.mPmemory->counters.nClusters - batchStart));
1046
1047 // Filling the data
1048 if (mRec->IsGPU() || GetProcessingSettings().nn.nnClusterizerForceGpuInputFill) {
1049 // Fills element by element of each input matrix -> better parallelizability, but worse on CPU due to unnecessary computations
1050 runKernel<GPUTPCNNClusterizerKernels, GPUTPCNNClusterizerKernels::fillInputNNGPU>({GetGrid(iSize * clustererNNShadow.mNnClusterizerRowTimeSizeThreads , lane), krnlRunRangeNone}, iSector, clustererNNShadow.mNnInferenceInputDType, propagateMCLabels, batchStart);
1051 } else {
1052 // Fills the whole input matrix at once -> better performance on CPU, but worse parallelizability
1053 runKernel<GPUTPCNNClusterizerKernels, GPUTPCNNClusterizerKernels::fillInputNNCPU>({GetGrid(iSize, lane), krnlRunRangeNone}, iSector, clustererNNShadow.mNnInferenceInputDType, propagateMCLabels, batchStart);
1054 }
1055 if (nn_settings.nnClusterizerVerbosity > 3) {
1056 LOG(info) << "(NNCLUS, GPUChainTrackingClusterizer, this=" << this << ") Done filling data. Loop=" << batch << ". (clustererNN=" << &clustererNN << ", clustererNNShadow=" << &clustererNNShadow << ")";
1057 }
1058
1059 if (clustererNNShadow.mNnClusterizerSetDeconvolutionFlags) {
1060 runKernel<GPUTPCNNClusterizerKernels, GPUTPCNNClusterizerKernels::publishDeconvolutionFlags>({GetGrid(iSize, lane), krnlRunRangeNone}, iSector, clustererNNShadow.mNnInferenceInputDType, propagateMCLabels, batchStart); // Publishing the deconvolution flags
1061 if (nn_settings.nnClusterizerVerbosity > 3) {
1062 LOG(info) << "(NNCLUS, GPUChainTrackingClusterizer, this=" << this << ") Done setting deconvolution flags. Loop=" << batch << ". (clustererNN=" << &clustererNN << ", clustererNNShadow=" << &clustererNNShadow << ")";
1063 }
1064 }
1065
1066 // NN evaluations
1067 if(clustererNNShadow.mNnClusterizerUseClassification) {
1068 if(GetProcessingSettings().debugLevel >= 1 && (doGPU || lane < 4)) { nnTimers[3*lane]->Start(); }
1069 if (clustererNNShadow.mNnInferenceInputDType == 0) {
1070 if (clustererNNShadow.mNnInferenceOutputDType == 0) {
1071 (nnApplication.mModelClass).inference(clustererNNShadow.mInputData_16, iSize, clustererNNShadow.mModelProbabilities_16);
1072 } else if (clustererNNShadow.mNnInferenceOutputDType == 1) {
1073 (nnApplication.mModelClass).inference(clustererNNShadow.mInputData_16, iSize, clustererNNShadow.mModelProbabilities_32);
1074 }
1075 } else if (clustererNNShadow.mNnInferenceInputDType == 1) {
1076 if (clustererNNShadow.mNnInferenceOutputDType == 0) {
1077 (nnApplication.mModelClass).inference(clustererNNShadow.mInputData_32, iSize, clustererNNShadow.mModelProbabilities_16);
1078 } else if (clustererNNShadow.mNnInferenceOutputDType == 1) {
1079 (nnApplication.mModelClass).inference(clustererNNShadow.mInputData_32, iSize, clustererNNShadow.mModelProbabilities_32);
1080 }
1081 }
1082 if(GetProcessingSettings().debugLevel >= 1 && (doGPU || lane < 4)) { nnTimers[3*lane]->Stop(); } // doGPU || lane<4 -> only for GPU or first 4 CPU lanes (to limit number of concurrent timers). At least gives some statistics for CPU time...
1083 if (nn_settings.nnClusterizerVerbosity > 3) {
1084 LOG(info) << "(NNCLUS, GPUChainTrackingClusterizer, this=" << this << ") Done with NN classification inference. Loop=" << batch << ". (clustererNN=" << &clustererNN << ", clustererNNShadow=" << &clustererNNShadow << ")";
1085 }
1086 }
1087 if (!clustererNNShadow.mNnClusterizerUseCfRegression) {
1088 if(GetProcessingSettings().debugLevel >= 1 && (doGPU || lane < 4)) { nnTimers[3*lane + 1]->Start(); }
1089 if (clustererNNShadow.mNnInferenceInputDType == 0) {
1090 if (clustererNNShadow.mNnInferenceOutputDType == 0) {
1091 (nnApplication.mModelReg1).inference(clustererNNShadow.mInputData_16, iSize, clustererNNShadow.mOutputDataReg1_16);
1092 } else if (clustererNNShadow.mNnInferenceOutputDType == 1) {
1093 (nnApplication.mModelReg1).inference(clustererNNShadow.mInputData_16, iSize, clustererNNShadow.mOutputDataReg1_32);
1094 }
1095 } else if (clustererNNShadow.mNnInferenceInputDType == 1) {
1096 if (clustererNNShadow.mNnInferenceOutputDType == 0) {
1097 (nnApplication.mModelReg1).inference(clustererNNShadow.mInputData_32, iSize, clustererNNShadow.mOutputDataReg1_16);
1098 } else if (clustererNNShadow.mNnInferenceOutputDType == 1) {
1099 (nnApplication.mModelReg1).inference(clustererNNShadow.mInputData_32, iSize, clustererNNShadow.mOutputDataReg1_32);
1100 }
1101 }
1102 if(GetProcessingSettings().debugLevel >= 1 && (doGPU || lane < 4)) { nnTimers[3*lane + 1]->Stop(); }
1103 if (nnApplication.mModelClass.getNumOutputNodes()[0][1] > 1 && nnApplication.mModelReg2.isInitialized()) {
1104 if(GetProcessingSettings().debugLevel >= 1 && (doGPU || lane < 4)) { nnTimers[3*lane + 2]->Start(); }
1105 if (clustererNNShadow.mNnInferenceInputDType == 0) {
1106 if (clustererNNShadow.mNnInferenceOutputDType == 0) {
1107 (nnApplication.mModelReg2).inference(clustererNNShadow.mInputData_16, iSize, clustererNNShadow.mOutputDataReg2_16);
1108 } else if (clustererNNShadow.mNnInferenceOutputDType == 1) {
1109 (nnApplication.mModelReg2).inference(clustererNNShadow.mInputData_16, iSize, clustererNNShadow.mOutputDataReg2_32);
1110 }
1111 } else if (clustererNNShadow.mNnInferenceInputDType == 1) {
1112 if (clustererNNShadow.mNnInferenceOutputDType == 0) {
1113 (nnApplication.mModelReg2).inference(clustererNNShadow.mInputData_32, iSize, clustererNNShadow.mOutputDataReg2_16);
1114 } else if (clustererNNShadow.mNnInferenceOutputDType == 1) {
1115 (nnApplication.mModelReg2).inference(clustererNNShadow.mInputData_32, iSize, clustererNNShadow.mOutputDataReg2_32);
1116 }
1117 }
1118 if(GetProcessingSettings().debugLevel >= 1 && (doGPU || lane < 4)) { nnTimers[3*lane + 2]->Stop(); }
1119 }
1120 if (nn_settings.nnClusterizerVerbosity > 3) {
1121 LOG(info) << "(NNCLUS, GPUChainTrackingClusterizer, this=" << this << ") Done with NN regression inference. Loop=" << batch << ". (clustererNN=" << &clustererNN << ", clustererNNShadow=" << &clustererNNShadow << ")";
1122 }
1123 }
1124
1125 // Publishing kernels for class labels and regression results
1126 // In case classification should not be used, this kernel should still be executed to fill the mOutputDataClass array with default values
1127 if (nnApplication.mModelClass.getNumOutputNodes()[0][1] == 1) {
1128 runKernel<GPUTPCNNClusterizerKernels, GPUTPCNNClusterizerKernels::determineClass1Labels>({GetGrid(iSize, lane), krnlRunRangeNone}, iSector, clustererNNShadow.mNnInferenceOutputDType, propagateMCLabels, batchStart); // Assigning class labels
1129 } else {
1130 runKernel<GPUTPCNNClusterizerKernels, GPUTPCNNClusterizerKernels::determineClass2Labels>({GetGrid(iSize, lane), krnlRunRangeNone}, iSector, clustererNNShadow.mNnInferenceOutputDType, propagateMCLabels, batchStart); // Assigning class labels
1131 }
1132 if (!clustererNNShadow.mNnClusterizerUseCfRegression) {
1133 runKernel<GPUTPCNNClusterizerKernels, GPUTPCNNClusterizerKernels::publishClass1Regression>({GetGrid(iSize, lane), krnlRunRangeNone}, iSector, clustererNNShadow.mNnInferenceOutputDType, propagateMCLabels, batchStart); // Publishing class 1 regression results
1134 if (nnApplication.mModelClass.getNumOutputNodes()[0][1] > 1 && nnApplication.mModelReg2.isInitialized()) {
1135 runKernel<GPUTPCNNClusterizerKernels, GPUTPCNNClusterizerKernels::publishClass2Regression>({GetGrid(iSize, lane), krnlRunRangeNone}, iSector, clustererNNShadow.mNnInferenceOutputDType, propagateMCLabels, batchStart); // Publishing class 2 regression results
1136 }
1137 }
1138 if (nn_settings.nnClusterizerVerbosity > 3) {
1139 LOG(info) << "(NNCLUS, GPUChainTrackingClusterizer, this=" << this << ") Done publishing. Loop=" << batch << ". (clustererNN=" << &clustererNN << ", clustererNNShadow=" << &clustererNNShadow << ")";
1140 }
1141 }
1142
1143 if (clustererNNShadow.mNnClusterizerUseCfRegression) {
1144 if(!nn_settings.nnClusterizerApplyCfDeconvolution) { // If it is already applied don't do it twice, otherwise apply now
1145 runKernel<GPUTPCCFDeconvolution>({GetGrid(clusterer.mPmemory->counters.nPositions, lane), {iSector}}, true);
1146 }
1147 DoDebugAndDump(RecoStep::TPCClusterFinding, GPUChainTrackingDebugFlags::TPCClustererChargeMap, clusterer, &GPUTPCClusterFinder::DumpChargeMap, *mDebugFile, "Split Charges");
1148 runKernel<GPUTPCNNClusterizerKernels, GPUTPCNNClusterizerKernels::runCfClusterizer>({GetGrid(clusterer.mPmemory->counters.nClusters, lane), krnlRunRangeNone}, iSector, clustererNNShadow.mNnInferenceInputDType, propagateMCLabels, 0); // Running the CF regression kernel - no batching needed: batchStart = 0
1149 if (nn_settings.nnClusterizerVerbosity > 3) {
1150 LOG(info) << "(NNCLUS, GPUChainTrackingClusterizer, this=" << this << ") Done with CF regression. (clustererNN=" << &clustererNN << ", clustererNNShadow=" << &clustererNNShadow << ")";
1151 }
1152 }
1153#else
1154 GPUFatal("Project not compiled with neural network clusterization. Aborting.");
1155#endif
1156 } else {
1157 runKernel<GPUTPCCFDeconvolution>({GetGrid(clusterer.mPmemory->counters.nPositions, lane), {iSector}}, true);
1158 DoDebugAndDump(RecoStep::TPCClusterFinding, GPUChainTrackingDebugFlags::TPCClustererChargeMap, clusterer, &GPUTPCClusterFinder::DumpChargeMap, *mDebugFile, "Split Charges");
1159 runKernel<GPUTPCCFClusterizer>({GetGrid(clusterer.mPmemory->counters.nClusters, lane), {iSector}}, 0);
1160 }
1161
1162 if (doGPU && propagateMCLabels) {
1163 TransferMemoryResourceLinkToHost(RecoStep::TPCClusterFinding, clusterer.mScratchId, lane);
1164 if (doGPU) {
1165 SynchronizeStream(lane);
1166 }
1167 runKernel<GPUTPCCFClusterizer>({GetGrid(clusterer.mPmemory->counters.nClusters, lane, GPUReconstruction::krnlDeviceType::CPU), {iSector}}, 1); // Computes MC labels
1168 }
1169
1170 if (GetProcessingSettings().debugLevel >= 3) {
1171 GPUInfo("Sector %02d Fragment %02d Lane %d: Found clusters: digits %u peaks %u clusters %u", iSector, fragment.index, lane, (int32_t)clusterer.mPmemory->counters.nPositions, (int32_t)clusterer.mPmemory->counters.nPeaks, (int32_t)clusterer.mPmemory->counters.nClusters);
1172 }
1173
1174 TransferMemoryResourcesToHost(RecoStep::TPCClusterFinding, &clusterer, lane);
1175 laneHasData[lane] = true;
1176 // Include clusters in default debug mask, exclude other debug output by default
1177 DoDebugAndDump(RecoStep::TPCClusterFinding, GPUChainTrackingDebugFlags::TPCClustererClusters, clusterer, &GPUTPCClusterFinder::DumpClusters, *mDebugFile); // clang-format off
1178 });
1180 }
1181
1182 size_t nClsFirst = nClsTotal;
1183 bool anyLaneHasData = false;
1184 for (int32_t lane = 0; lane < maxLane; lane++) {
1185 uint32_t iSector = iSectorBase + lane;
1186 std::fill(&tmpNativeAccess->nClusters[iSector][0], &tmpNativeAccess->nClusters[iSector][0] + MAXGLOBALPADROW, 0);
1187 if (doGPU) {
1188 SynchronizeStream(lane);
1189 }
1190 GPUTPCClusterFinder& clusterer = processors()->tpcClusterer[iSector];
1191 GPUTPCClusterFinder& clustererShadow = doGPU ? processorsShadow()->tpcClusterer[iSector] : clusterer;
1192
1193 if (laneHasData[lane]) {
1194 anyLaneHasData = true;
1195 if (buildNativeGPU && GetProcessingSettings().tpccfGatherKernel) {
1196 runKernel<GPUTPCCFGather>({GetGridBlk(GPUCA_ROW_COUNT, mRec->NStreams() - 1), {iSector}}, &mInputsShadow->mPclusterNativeBuffer[nClsTotal]);
1197 }
1198 for (uint32_t j = 0; j < GPUCA_ROW_COUNT; j++) {
1199 if (nClsTotal + clusterer.mPclusterInRow[j] > mInputsHost->mNClusterNative) {
1200 clusterer.raiseError(GPUErrors::ERROR_CF_GLOBAL_CLUSTER_OVERFLOW, iSector * 1000 + j, nClsTotal + clusterer.mPclusterInRow[j], mInputsHost->mNClusterNative);
1201 continue;
1202 }
1203 if (buildNativeGPU) {
1204 if (!GetProcessingSettings().tpccfGatherKernel) {
1205 GPUMemCpyAlways(RecoStep::TPCClusterFinding, (void*)&mInputsShadow->mPclusterNativeBuffer[nClsTotal], (const void*)&clustererShadow.mPclusterByRow[j * clusterer.mNMaxClusterPerRow], sizeof(mIOPtrs.clustersNative->clustersLinear[0]) * clusterer.mPclusterInRow[j], mRec->NStreams() - 1, -2);
1206 }
1207 } else if (buildNativeHost) {
1208 GPUMemCpyAlways(RecoStep::TPCClusterFinding, (void*)&tmpNativeClusters[nClsTotal], (const void*)&clustererShadow.mPclusterByRow[j * clusterer.mNMaxClusterPerRow], sizeof(mIOPtrs.clustersNative->clustersLinear[0]) * clusterer.mPclusterInRow[j], mRec->NStreams() - 1, false);
1209 }
1210 tmpNativeAccess->nClusters[iSector][j] += clusterer.mPclusterInRow[j];
1211 nClsTotal += clusterer.mPclusterInRow[j];
1212 }
1213 if (transferRunning[lane]) {
1214 ReleaseEvent(mEvents->stream[lane], doGPU);
1215 }
1216 RecordMarker(&mEvents->stream[lane], mRec->NStreams() - 1);
1217 transferRunning[lane] = 1;
1218 }
1219
1220 if (not propagateMCLabels || not laneHasData[lane]) {
1221 assert(propagateMCLabels ? mcLinearLabels.header.size() == nClsTotal : true);
1222 continue;
1223 }
1224
1225 runKernel<GPUTPCCFMCLabelFlattener, GPUTPCCFMCLabelFlattener::setRowOffsets>({GetGrid(GPUCA_ROW_COUNT, lane, GPUReconstruction::krnlDeviceType::CPU), {iSector}});
1227 runKernel<GPUTPCCFMCLabelFlattener, GPUTPCCFMCLabelFlattener::flatten>({GetGrid(GPUCA_ROW_COUNT, lane, GPUReconstruction::krnlDeviceType::CPU), {iSector}}, &mcLinearLabels);
1228 clusterer.clearMCMemory();
1229 assert(propagateMCLabels ? mcLinearLabels.header.size() == nClsTotal : true);
1230 }
1231 if (propagateMCLabels) {
1232 for (int32_t lane = 0; lane < maxLane; lane++) {
1233 processors()->tpcClusterer[iSectorBase + lane].clearMCMemory();
1234 }
1235 }
1236 if (buildNativeHost && buildNativeGPU && anyLaneHasData) {
1237 if (GetProcessingSettings().delayedOutput) {
1238 mOutputQueue.emplace_back(outputQueueEntry{(void*)((char*)&tmpNativeClusters[nClsFirst] - (char*)&tmpNativeClusters[0]), &mInputsShadow->mPclusterNativeBuffer[nClsFirst], (nClsTotal - nClsFirst) * sizeof(tmpNativeClusters[0]), RecoStep::TPCClusterFinding});
1239 } else {
1240 GPUMemCpy(RecoStep::TPCClusterFinding, (void*)&tmpNativeClusters[nClsFirst], (const void*)&mInputsShadow->mPclusterNativeBuffer[nClsFirst], (nClsTotal - nClsFirst) * sizeof(tmpNativeClusters[0]), mRec->NStreams() - 1, false);
1241 }
1242 }
1243
1244 if (mWaitForFinalInputs && iSectorBase >= 21 && (int32_t)iSectorBase < 21 + GetProcessingSettings().nTPCClustererLanes) {
1245 notifyForeignChainFinished();
1246 }
1247 if (mWaitForFinalInputs && iSectorBase >= 30 && (int32_t)iSectorBase < 30 + GetProcessingSettings().nTPCClustererLanes) {
1248 mWaitForFinalInputs();
1249 synchronizeCalibUpdate = DoQueuedUpdates(0, false);
1250 }
1251 }
1252 for (int32_t i = 0; i < GetProcessingSettings().nTPCClustererLanes; i++) {
1253#ifdef GPUCA_HAS_ONNX
1254 if (GetProcessingSettings().nn.applyNNclusterizer) {
1255 if (GetProcessingSettings().nn.nnClusterizerVerbosity > 0) {
1256 LOG(info) << "(ORT) Environment releasing...";
1257 }
1258 GPUTPCNNClusterizerHost& nnApplication = nnApplications[i];
1259 nnApplication.mModelClass.release(true);
1260 nnApplication.mModelReg1.release(true);
1261 nnApplication.mModelReg2.release(true);
1262 }
1263#endif
1264 if (transferRunning[i]) {
1265 ReleaseEvent(mEvents->stream[i], doGPU);
1266 }
1267 }
1268
1269 if (GetProcessingSettings().param.tpcTriggerHandling) {
1271 if (triggerOutput && triggerOutput->allocator) {
1272 // GPUInfo("Storing %lu trigger words", mTriggerBuffer->triggers.size());
1273 auto* outputBuffer = (decltype(mTriggerBuffer->triggers)::value_type*)triggerOutput->allocator(mTriggerBuffer->triggers.size() * sizeof(decltype(mTriggerBuffer->triggers)::value_type));
1274 std::copy(mTriggerBuffer->triggers.begin(), mTriggerBuffer->triggers.end(), outputBuffer);
1275 }
1276 mTriggerBuffer->triggers.clear();
1277 }
1278
1279 // Number of clusters is logged by tracking. This ensures clusters are still printed if it's not running
1281 GPUInfo("Event has %zu TPC Clusters", nClsTotal);
1282 }
1283
1284 ClusterNativeAccess::ConstMCLabelContainerView* mcLabelsConstView = nullptr;
1285 if (propagateMCLabels) { // TODO: write to buffer directly
1287 std::pair<ConstMCLabelContainer*, ConstMCLabelContainerView*> buffer;
1289 if (!GetProcessingSettings().tpcWriteClustersAfterRejection && !sortClusters && labelOutputControl && labelOutputControl->useExternal()) {
1290 if (!labelOutputControl->allocator) {
1291 throw std::runtime_error("Cluster MC Label buffer missing");
1292 }
1294 buffer = {&container->first, &container->second};
1295 } else {
1296 mIOMem.clusterNativeMCView = std::make_unique<ConstMCLabelContainerView>();
1297 mIOMem.clusterNativeMCBuffer = std::make_unique<ConstMCLabelContainer>();
1299 }
1300
1301 assert(propagateMCLabels ? mcLinearLabels.header.size() == nClsTotal : true);
1302 assert(propagateMCLabels ? mcLinearLabels.data.size() >= nClsTotal : true);
1303
1304 mcLabels.setFrom(mcLinearLabels.header, mcLinearLabels.data);
1305 mcLabels.flatten_to(*buffer.first);
1306 *buffer.second = *buffer.first;
1307 mcLabelsConstView = buffer.second;
1308 }
1309
1310 if (buildNativeHost && buildNativeGPU && GetProcessingSettings().delayedOutput) {
1311 mInputsHost->mNClusterNative = mInputsShadow->mNClusterNative = nClsTotal;
1312 AllocateRegisteredMemory(mInputsHost->mResourceClusterNativeOutput, GetProcessingSettings().tpcWriteClustersAfterRejection ? nullptr : mSubOutputControls[GPUTrackingOutputs::getIndex(&GPUTrackingOutputs::clustersNative)]);
1313 tmpNativeClusters = mInputsHost->mPclusterNativeOutput;
1314 for (uint32_t i = outputQueueStart; i < mOutputQueue.size(); i++) {
1315 mOutputQueue[i].dst = (char*)tmpNativeClusters + (size_t)mOutputQueue[i].dst;
1316 }
1317 }
1318
1319 if (buildNativeHost) {
1320 tmpNativeAccess->clustersLinear = tmpNativeClusters;
1321 tmpNativeAccess->clustersMCTruth = mcLabelsConstView;
1322 tmpNativeAccess->setOffsetPtrs();
1323 mIOPtrs.clustersNative = tmpNativeAccess;
1324 if (GetProcessingSettings().tpcApplyClusterFilterOnCPU) {
1325 auto allocator = [this, &tmpNativeClusters](size_t size) {
1326 this->mInputsHost->mNClusterNative = size;
1327 this->AllocateRegisteredMemory(this->mInputsHost->mResourceClusterNativeOutput, this->GetProcessingSettings().tpcWriteClustersAfterRejection ? nullptr : this->mSubOutputControls[GPUTrackingOutputs::getIndex(&GPUTrackingOutputs::clustersNative)]);
1328 return (tmpNativeClusters = this->mInputsHost->mPclusterNativeOutput);
1329 };
1330 RunTPCClusterFilter(tmpNativeAccess, allocator, false);
1331 nClsTotal = tmpNativeAccess->nClustersTotal;
1332 }
1333 }
1334
1335 if (!mWaitForFinalInputs) {
1336 notifyForeignChainFinished();
1337 }
1338
1339 if (buildNativeGPU) {
1340 processorsShadow()->ioPtrs.clustersNative = mInputsShadow->mPclusterNativeAccess;
1341 WriteToConstantMemory(RecoStep::TPCClusterFinding, (char*)&processors()->ioPtrs - (char*)processors(), &processorsShadow()->ioPtrs, sizeof(processorsShadow()->ioPtrs), 0);
1342 *mInputsHost->mPclusterNativeAccess = *mIOPtrs.clustersNative;
1343 mInputsHost->mPclusterNativeAccess->clustersLinear = mInputsShadow->mPclusterNativeBuffer;
1344 mInputsHost->mPclusterNativeAccess->setOffsetPtrs();
1345 TransferMemoryResourceLinkToGPU(RecoStep::TPCClusterFinding, mInputsHost->mResourceClusterNativeAccess, 0);
1346 }
1347 if (doGPU && synchronizeOutput) {
1349 }
1350 if (doGPU && synchronizeCalibUpdate) {
1352 }
1353 if (sortClusters) {
1354 SortClusters(buildNativeGPU, propagateMCLabels, tmpNativeAccess, tmpNativeClusters);
1355 }
1356 mRec->MemoryScalers()->nTPCHits = nClsTotal;
1357 mRec->PopNonPersistentMemory(RecoStep::TPCClusterFinding, qStr2Tag("TPCCLUST"));
1358 if (mPipelineNotifyCtx) {
1360 mPipelineNotifyCtx = nullptr;
1361 }
1362
1363 if (GetProcessingSettings().autoAdjustHostThreads && !doGPU) {
1365 }
1366
1367#endif
1368 return 0;
1369}
1370
1371void GPUChainTracking::SortClusters(bool buildNativeGPU, bool propagateMCLabels, ClusterNativeAccess* clusterAccess, ClusterNative* clusters)
1372{
1373 if (propagateMCLabels) {
1374 std::vector<uint32_t> clsOrder(clusterAccess->nClustersTotal);
1375 std::iota(clsOrder.begin(), clsOrder.end(), 0);
1376 std::vector<ClusterNative> tmpClusters;
1377 for (uint32_t i = 0; i < NSECTORS; i++) {
1378 for (uint32_t j = 0; j < GPUCA_ROW_COUNT; j++) {
1379 const uint32_t offset = clusterAccess->clusterOffset[i][j];
1380 std::sort(&clsOrder[offset], &clsOrder[offset + clusterAccess->nClusters[i][j]], [&clusters](const uint32_t a, const uint32_t b) {
1381 return clusters[a] < clusters[b];
1382 });
1383 tmpClusters.resize(clusterAccess->nClusters[i][j]);
1384 memcpy(tmpClusters.data(), &clusters[offset], clusterAccess->nClusters[i][j] * sizeof(tmpClusters[0]));
1385 for (uint32_t k = 0; k < tmpClusters.size(); k++) {
1386 clusters[offset + k] = tmpClusters[clsOrder[offset + k] - offset];
1387 }
1388 }
1389 }
1390 tmpClusters.clear();
1391
1392 std::pair<o2::dataformats::ConstMCLabelContainer*, o2::dataformats::ConstMCLabelContainerView*> labelBuffer;
1394 std::unique_ptr<ConstMCLabelContainerView> tmpUniqueContainerView;
1395 std::unique_ptr<ConstMCLabelContainer> tmpUniqueContainerBuffer;
1396 if (labelOutput && labelOutput->allocator) {
1398 labelBuffer = {&labelContainer->first, &labelContainer->second};
1399 } else {
1400 tmpUniqueContainerView = std::move(mIOMem.clusterNativeMCView);
1401 tmpUniqueContainerBuffer = std::move(mIOMem.clusterNativeMCBuffer);
1402 mIOMem.clusterNativeMCView = std::make_unique<ConstMCLabelContainerView>();
1403 mIOMem.clusterNativeMCBuffer = std::make_unique<ConstMCLabelContainer>();
1404 labelBuffer = {mIOMem.clusterNativeMCBuffer.get(), mIOMem.clusterNativeMCView.get()};
1405 }
1406
1408 for (uint32_t i = 0; i < clusterAccess->nClustersTotal; i++) {
1409 for (const auto& element : clusterAccess->clustersMCTruth->getLabels(clsOrder[i])) {
1410 tmpContainer.addElement(i, element);
1411 }
1412 }
1413 tmpContainer.flatten_to(*labelBuffer.first);
1414 *labelBuffer.second = *labelBuffer.first;
1415 clusterAccess->clustersMCTruth = labelBuffer.second;
1416 } else {
1417 for (uint32_t i = 0; i < NSECTORS; i++) {
1418 for (uint32_t j = 0; j < GPUCA_ROW_COUNT; j++) {
1419 std::sort(&clusters[clusterAccess->clusterOffset[i][j]], &clusters[clusterAccess->clusterOffset[i][j] + clusterAccess->nClusters[i][j]]);
1420 }
1421 }
1422 }
1423 if (buildNativeGPU) {
1424 GPUMemCpy(RecoStep::TPCClusterFinding, (void*)mInputsShadow->mPclusterNativeBuffer, (const void*)clusters, clusterAccess->nClustersTotal * sizeof(clusters[0]), -1, true);
1425 }
1426}
Definition of the TPC Digit.
atype::type element
int32_t i
#define TPC_MAX_TIME_BIN_TRIGGERED
#define GPUCA_MAX_STREAMS
int32_t retVal
#define GPUCA_ROW_COUNT
Class to serialize ONNX objects for ROOT snapshots of CCDB objects at runtime.
std::enable_if_t< std::is_signed< T >::value, bool > hasData(const CalArray< T > &cal)
Definition Painter.cxx:599
uint32_t j
Definition RawData.h:0
uint8_t endpoint
Definition RawData.h:0
Provides a basic fallback implementation for Vc.
Definitions of TPC Zero Suppression Data Headers.
void Start()
Definition timer.cxx:64
void Stop()
Definition timer.cxx:76
A container to hold and manage MC truth information/labels.
void addElement(uint32_t dataindex, TruthElement const &element, bool noElement=false)
void setFrom(std::vector< MCTruthHeaderElement > &header, std::vector< TruthElement > &truthArray)
size_t flatten_to(ContainerType &container) const
std::unique_ptr< o2::tpc::ClusterNativeAccess > mClusterNativeAccess
int32_t RunTPCClusterizer(bool synchronizeOutput=true)
std::unique_ptr< GPUTrackingInputProvider > mInputsHost
std::array< GPUOutputControl *, GPUTrackingOutputs::count()> mSubOutputControls
std::unique_ptr< std::ofstream > mDebugFile
std::unique_ptr< GPUTriggerOutputs > mTriggerBuffer
std::vector< outputQueueEntry > mOutputQueue
std::unique_ptr< GPUTPCCFChainContext > mCFContext
int32_t DoQueuedUpdates(int32_t stream, bool updateSlave=true)
std::unique_ptr< GPUNewCalibValues > mNewCalibValues
GPUTrackingInOutPointers & mIOPtrs
struct o2::gpu::GPUChainTracking::InOutMemory mIOMem
std::unique_ptr< GPUTrackingInputProvider > mInputsShadow
void RecordMarker(deviceEvent *ev, int32_t stream)
Definition GPUChain.h:108
void TransferMemoryResourceLinkToGPU(RecoStep step, int16_t res, int32_t stream=-1, deviceEvent *ev=nullptr, deviceEvent *evList=nullptr, int32_t nEvents=1)
Definition GPUChain.h:124
void GPUMemCpyAlways(RecoStep step, void *dst, const void *src, size_t size, int32_t stream, int32_t toGPU, deviceEvent *ev=nullptr, deviceEvent *evList=nullptr, int32_t nEvents=1)
Definition GPUChain.h:129
void GPUMemCpy(RecoStep step, void *dst, const void *src, size_t size, int32_t stream, int32_t toGPU, deviceEvent *ev=nullptr, deviceEvent *evList=nullptr, int32_t nEvents=1)
Definition GPUChain.h:128
bool DoDebugAndDump(RecoStep step, uint32_t mask, T &processor, S T::*func, Args &&... args)
Definition GPUChain.h:228
GPUReconstruction::RecoStepField GetRecoStepsGPU() const
Definition GPUChain.h:72
GPUReconstruction::RecoStepField GetRecoSteps() const
Definition GPUChain.h:71
void WriteToConstantMemory(RecoStep step, size_t offset, const void *src, size_t size, int32_t stream=-1, deviceEvent *ev=nullptr)
Definition GPUChain.h:127
void ReleaseEvent(deviceEvent ev, bool doGPU=true)
Definition GPUChain.h:111
krnlExec GetGrid(uint32_t totalItems, uint32_t nThreads, int32_t stream, GPUReconstruction::krnlDeviceType d=GPUReconstruction::krnlDeviceType::Auto, gpudatatypes::RecoStep st=gpudatatypes::RecoStep::NoRecoStep)
Definition GPUChain.cxx:21
size_t AllocateRegisteredMemory(GPUProcessor *proc)
Definition GPUChain.h:217
virtual std::unique_ptr< GPUReconstructionProcessing::threadContext > GetThreadContext()
Definition GPUChain.h:109
GPUConstantMem * processors()
Definition GPUChain.h:84
static constexpr krnlRunRange krnlRunRangeNone
Definition GPUChain.h:41
void SetONNXGPUStream(Ort::SessionOptions &opt, int32_t stream, int32_t *deviceId)
Definition GPUChain.h:90
krnlExec GetGridAutoStep(int32_t stream, gpudatatypes::RecoStep st=gpudatatypes::RecoStep::NoRecoStep)
Definition GPUChain.cxx:47
GPUParam & param()
Definition GPUChain.h:87
void SetupGPUProcessor(T *proc, bool allocate)
Definition GPUChain.h:220
const GPUSettingsProcessing & GetProcessingSettings() const
Definition GPUChain.h:76
void SynchronizeStream(int32_t stream)
Definition GPUChain.h:89
GPUReconstructionCPU * mRec
Definition GPUChain.h:79
GPUConstantMem * processorsShadow()
Definition GPUChain.h:85
krnlExec GetGridBlk(uint32_t nBlocks, int32_t stream, GPUReconstruction::krnlDeviceType d=GPUReconstruction::krnlDeviceType::Auto, gpudatatypes::RecoStep st=gpudatatypes::RecoStep::NoRecoStep)
Definition GPUChain.cxx:32
static constexpr int32_t NSECTORS
Definition GPUChain.h:58
void TransferMemoryResourceLinkToHost(RecoStep step, int16_t res, int32_t stream=-1, deviceEvent *ev=nullptr, deviceEvent *evList=nullptr, int32_t nEvents=1)
Definition GPUChain.h:125
void TransferMemoryResourcesToHost(RecoStep step, GPUProcessor *proc, int32_t stream=-1, bool all=false)
Definition GPUChain.h:123
GPUReconstruction * rec()
Definition GPUChain.h:66
HighResTimer & getGeneralStepTimer(GeneralStep step)
void runParallelOuterLoop(bool doGPU, uint32_t nThreads, std::function< void(uint32_t)> lambda)
const GPUDefParameters & getGPUParameters(bool doGPU) const override
void AllocateRegisteredForeignMemory(int16_t res, GPUReconstruction *rec, GPUOutputControl *control=nullptr)
void ComputeReuseMax(GPUProcessor *proc)
RecoStepField GetRecoStepsGPU() const
void PopNonPersistentMemory(RecoStep step, uint64_t tag, const GPUProcessor *proc=nullptr)
const GPUParam & GetParam() const
void PushNonPersistentMemory(uint64_t tag)
InOutTypeField GetRecoStepsOutputs() const
GPUMemorySizeScalers * MemoryScalers()
static void setGlobalOffsetsAndAllocate(GPUTPCClusterFinder &, GPUTPCLinearLabels &)
void SetMaxData(const GPUTrackingInOutPointers &io)
void SetNMaxDigits(size_t nDigits, size_t nPages, size_t nDigitsFragment, size_t nDigitsEndpointMax)
void DumpSuppressedPeaks(std::ostream &out)
void DumpPeakMap(std::ostream &out, std::string_view)
o2::dataformats::ConstMCTruthContainerView< o2::MCCompLabel > const * mPinputLabels
void DumpChargeMap(std::ostream &out, std::string_view)
uint32_t getNSteps(size_t items) const
void DumpSuppressedPeaksCompacted(std::ostream &out)
void DumpPeaksCompacted(std::ostream &out)
tpc::ClusterNative * mPclusterByRow
void init(const GPUSettingsProcessingNNclusterizer &, bool=false)
void initClusterizer(const GPUSettingsProcessingNNclusterizer &, GPUTPCNNClusterizer &, int32_t=-1, int32_t=-1)
OrtDataType::Float16_t * mInputData_16
OrtDataType::Float16_t * mOutputDataReg2_16
OrtDataType::Float16_t * mModelProbabilities_16
OrtDataType::Float16_t * mOutputDataReg1_16
void release(bool=false)
void setIntraOpNumThreads(int threads)
std::vector< std::vector< int64_t > > getNumOutputNodes() const
#define TPC_PADS_IN_SECTOR
GLint GLenum GLint x
Definition glcorearb.h:403
const GLfloat * m
Definition glcorearb.h:4066
GLenum src
Definition glcorearb.h:1767
GLint GLsizei count
Definition glcorearb.h:399
GLuint buffer
Definition glcorearb.h:655
GLsizeiptr size
Definition glcorearb.h:659
GLdouble f
Definition glcorearb.h:310
GLboolean GLboolean GLboolean b
Definition glcorearb.h:1233
GLboolean * data
Definition glcorearb.h:298
GLintptr offset
Definition glcorearb.h:660
GLenum GLfloat param
Definition glcorearb.h:271
GLboolean GLboolean GLboolean GLboolean a
Definition glcorearb.h:1233
uint8_t itsSharedClusterMap uint8_t
constexpr int LHCMaxBunches
Definition of a container to keep/associate and arbitrary number of labels associated to an index wit...
RAWDataHeaderV7 RAWDataHeader
const float k2
Definition MathUtils.h:72
void dumpBuffer(gsl::span< const std::byte > buffer, std::ostream &out=std::cout, size_t maxbytes=std::numeric_limits< size_t >::max())
Definition DumpBuffer.h:139
std::unique_ptr< const o2::dataformats::MCTruthContainer< MCLabel > > getLabels(framework::ProcessingContext &pc, std::string_view dataBind)
constexpr int LHCBCPERTIMEBIN
Definition Constants.h:38
constexpr int MAXGLOBALPADROW
Definition Constants.h:34
Global TPC definitions and constants.
Definition SimTraits.h:168
@ ZSVersionDenseLinkBased
@ ZSVersionLinkBasedWithMeta
@ ZSVersionRowBased10BitADC
@ ZSVersionRowBased12BitADC
a couple of static helper functions to create timestamp values for CCDB queries or override obsolete ...
constexpr T qStr2Tag(const char *str)
Definition strtag.h:22
tpccf::TPCTime start
Definition CfFragment.h:31
S< o2::tpc::ORTRootSerializer >::type * nnClusterizerNetworks[3]
std::unique_ptr< o2::dataformats::ConstMCTruthContainerView< o2::MCCompLabel > > clusterNativeMCView
std::unique_ptr< o2::dataformats::ConstMCTruthContainer< o2::MCCompLabel > > clusterNativeMCBuffer
deviceEvent stream[GPUCA_MAX_STREAMS]
GPUTPCClusterFinder tpcClusterer[GPUCA_NSECTORS]
GPUCalibObjectsConst calibObjects
GPUTrackingInOutPointers ioPtrs
size_t NTPCClusters(size_t tpcDigits, bool perSector=false)
std::function< void *(size_t)> allocator
struct o2::gpu::GPUTPCClusterFinder::Memory::counters_t counters
std::vector< o2::MCCompLabel > data
std::vector< o2::dataformats::MCTruthHeaderElement > header
const GPUTPCDigitsMCInput * tpcDigitsMC
const o2::tpc::ClusterNativeAccess * clustersNative
const GPUTrackingInOutZS * tpcZS
const GPUTrackingInOutDigits * tpcPackedDigits
GPUTrackingInOutZSSector sector[NSECTORS]
static constexpr uint32_t NENDPOINTS
size_t getIndex(const GPUOutputControl &v)
static constexpr int getVersion()
get numeric version of the RDH
Definition RDHUtils.h:60
unsigned int nClusters[constants::MAXSECTOR][constants::MAXGLOBALPADROW]
const o2::dataformats::ConstMCTruthContainerView< o2::MCCompLabel > * clustersMCTruth
std::pair< ConstMCLabelContainer, ConstMCLabelContainerView > ConstMCLabelContainerViewWithBuffer
unsigned int clusterOffset[constants::MAXSECTOR][constants::MAXGLOBALPADROW]
const ClusterNative * clustersLinear
static constexpr unsigned int TRIGGER_WORD_SIZE
unsigned char version
static constexpr size_t TPC_ZS_PAGE_SIZE
unsigned short nADCsamples
Trigger info including the orbit.
uint32_t orbit
orbit of the trigger word
TriggerWordDLBZS triggerWord
trigger Word information
bool isValid(int entry=0) const
constexpr size_t min
constexpr size_t max
LOG(info)<< "Compressed in "<< sw.CpuTime()<< " s"
std::vector< Cluster > clusters
std::vector< Digit > digits