forked from AliceO2Group/AliceO2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGPUChainTrackingClusterizer.cxx
More file actions
1360 lines (1262 loc) · 79.1 KB
/
GPUChainTrackingClusterizer.cxx
File metadata and controls
1360 lines (1262 loc) · 79.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2019-2020 CERN and copyright holders of ALICE O2.
// See https://alice-o2.web.cern.ch/copyright for details of the copyright holders.
// All rights not expressly granted are reserved.
//
// This software is distributed under the terms of the GNU General Public
// License v3 (GPL Version 3), copied verbatim in the file "COPYING".
//
// In applying this license CERN does not waive the privileges and immunities
// granted to it by virtue of its status as an Intergovernmental Organization
// or submit itself to any jurisdiction.
/// \file GPUChainTrackingClusterizer.cxx
/// \author David Rohr
#include "GPUChainTracking.h"
#include "GPUChainTrackingDefs.h"
#include "GPUChainTrackingDebug.h"
#include "GPULogging.h"
#include "GPUO2DataTypes.h"
#include "GPUMemorySizeScalers.h"
#include "GPUTrackingInputProvider.h"
#include "GPUNewCalibValues.h"
#include "GPUConstantMem.h"
#include "CfChargePos.h"
#include "CfArray2D.h"
#include "GPUGeneralKernels.h"
#include "GPUDefParametersRuntime.h"
#include "GPUTPCCFStreamCompaction.h"
#include "GPUTPCCFChargeMapFiller.h"
#include "GPUTPCCFDecodeZS.h"
#include "GPUTPCCFCheckPadBaseline.h"
#include "GPUTPCCFPeakFinder.h"
#include "GPUTPCCFNoiseSuppression.h"
#include "GPUTPCCFDeconvolution.h"
#include "GPUTPCCFClusterizer.h"
#include "GPUTPCCFGather.h"
#include "GPUTPCCFMCLabelFlattener.h"
#include "GPUTriggerOutputs.h"
#include "GPUHostDataTypes.h"
#include "GPUTPCCFChainContext.h"
#include "DataFormatsTPC/ZeroSuppression.h"
#include "DetectorsRaw/RDHUtils.h"
#include "DataFormatsTPC/Digit.h"
#include "DataFormatsTPC/Constants.h"
#include "TPCBase/RDHUtils.h"
#ifdef GPUCA_HAS_ONNX
#include "GPUTPCNNClusterizerKernels.h"
#include "GPUTPCNNClusterizerHost.h"
#endif
#ifdef GPUCA_O2_LIB
#include "CommonDataFormat/InteractionRecord.h"
#endif
#include "utils/strtag.h"
#include <fstream>
#ifndef GPUCA_NO_VC
#include <Vc/Vc>
#endif
using namespace o2::gpu;
using namespace o2::tpc;
using namespace o2::tpc::constants;
using namespace o2::dataformats;
#ifdef GPUCA_TPC_GEOMETRY_O2
std::pair<uint32_t, uint32_t> GPUChainTracking::TPCClusterizerDecodeZSCountUpdate(uint32_t iSector, const CfFragment& fragment)
{
bool doGPU = mRec->GetRecoStepsGPU() & GPUDataTypes::RecoStep::TPCClusterFinding;
GPUTPCClusterFinder& clusterer = processors()->tpcClusterer[iSector];
GPUTPCClusterFinder::ZSOffset* o = processors()->tpcClusterer[iSector].mPzsOffsets;
uint32_t digits = 0;
uint32_t pages = 0;
for (uint16_t j = 0; j < GPUTrackingInOutZS::NENDPOINTS; j++) {
clusterer.mMinMaxCN[j] = mCFContext->fragmentData[fragment.index].minMaxCN[iSector][j];
if (doGPU) {
uint16_t posInEndpoint = 0;
uint16_t pagesEndpoint = 0;
for (uint32_t k = clusterer.mMinMaxCN[j].zsPtrFirst; k < clusterer.mMinMaxCN[j].zsPtrLast; k++) {
const uint32_t pageFirst = (k == clusterer.mMinMaxCN[j].zsPtrFirst) ? clusterer.mMinMaxCN[j].zsPageFirst : 0;
const uint32_t pageLast = (k + 1 == clusterer.mMinMaxCN[j].zsPtrLast) ? clusterer.mMinMaxCN[j].zsPageLast : mIOPtrs.tpcZS->sector[iSector].nZSPtr[j][k];
for (uint32_t l = pageFirst; l < pageLast; l++) {
uint16_t pageDigits = mCFContext->fragmentData[fragment.index].pageDigits[iSector][j][posInEndpoint++];
if (pageDigits) {
*(o++) = GPUTPCClusterFinder::ZSOffset{digits, j, pagesEndpoint};
digits += pageDigits;
}
pagesEndpoint++;
}
}
if (pagesEndpoint != mCFContext->fragmentData[fragment.index].pageDigits[iSector][j].size()) {
if (GetProcessingSettings().ignoreNonFatalGPUErrors) {
GPUError("TPC raw page count mismatch in TPCClusterizerDecodeZSCountUpdate: expected %d / buffered %lu", pagesEndpoint, mCFContext->fragmentData[fragment.index].pageDigits[iSector][j].size());
return {0, 0};
} else {
GPUFatal("TPC raw page count mismatch in TPCClusterizerDecodeZSCountUpdate: expected %d / buffered %lu", pagesEndpoint, mCFContext->fragmentData[fragment.index].pageDigits[iSector][j].size());
}
}
} else {
clusterer.mPzsOffsets[j] = GPUTPCClusterFinder::ZSOffset{digits, j, 0};
digits += mCFContext->fragmentData[fragment.index].nDigits[iSector][j];
pages += mCFContext->fragmentData[fragment.index].nPages[iSector][j];
}
}
if (doGPU) {
pages = o - processors()->tpcClusterer[iSector].mPzsOffsets;
}
if (GetProcessingSettings().clusterizerZSSanityCheck && mCFContext->zsVersion >= ZSVersion::ZSVersionDenseLinkBased) {
TPCClusterizerEnsureZSOffsets(iSector, fragment);
}
return {digits, pages};
}
void GPUChainTracking::TPCClusterizerEnsureZSOffsets(uint32_t iSector, const CfFragment& fragment)
{
GPUTPCClusterFinder& clusterer = processors()->tpcClusterer[iSector];
uint32_t nAdcs = 0;
for (uint16_t endpoint = 0; endpoint < GPUTrackingInOutZS::NENDPOINTS; endpoint++) {
const auto& data = mCFContext->fragmentData[fragment.index];
uint32_t pagesEndpoint = 0;
const uint32_t nAdcsExpected = data.nDigits[iSector][endpoint];
const uint32_t nPagesExpected = data.nPages[iSector][endpoint];
uint32_t nAdcDecoded = 0;
const auto& zs = mIOPtrs.tpcZS->sector[iSector];
for (uint32_t i = data.minMaxCN[iSector][endpoint].zsPtrFirst; i < data.minMaxCN[iSector][endpoint].zsPtrLast; i++) {
const uint32_t pageFirst = (i == data.minMaxCN[iSector][endpoint].zsPtrFirst) ? data.minMaxCN[iSector][endpoint].zsPageFirst : 0;
const uint32_t pageLast = (i + 1 == data.minMaxCN[iSector][endpoint].zsPtrLast) ? data.minMaxCN[iSector][endpoint].zsPageLast : zs.nZSPtr[endpoint][i];
for (uint32_t j = pageFirst; j < pageLast; j++) {
const uint8_t* page = static_cast<const uint8_t*>(zs.zsPtr[endpoint][i]) + j * TPCZSHDR::TPC_ZS_PAGE_SIZE;
const header::RAWDataHeader* rawDataHeader = reinterpret_cast<const header::RAWDataHeader*>(page);
const TPCZSHDRV2* decHdr = reinterpret_cast<const TPCZSHDRV2*>(page + raw::RDHUtils::getMemorySize(*rawDataHeader) - sizeof(TPCZSHDRV2));
const uint16_t nSamplesInPage = decHdr->nADCsamples;
nAdcDecoded += nSamplesInPage;
pagesEndpoint++;
}
}
if (pagesEndpoint != nPagesExpected) {
GPUFatal("Sector %d, Endpoint %d, Fragment %d: TPC raw page count mismatch: expected %d / buffered %u", iSector, endpoint, fragment.index, pagesEndpoint, nPagesExpected);
}
if (nAdcDecoded != nAdcsExpected) {
GPUFatal("Sector %d, Endpoint %d, Fragment %d: TPC ADC count mismatch: expected %u, buffered %u", iSector, endpoint, fragment.index, nAdcsExpected, nAdcDecoded);
}
if (nAdcs != clusterer.mPzsOffsets[endpoint].offset) {
GPUFatal("Sector %d, Endpoint %d, Fragment %d: TPC ADC offset mismatch: expected %u, buffered %u", iSector, endpoint, fragment.index, nAdcs, clusterer.mPzsOffsets[endpoint].offset);
}
nAdcs += nAdcsExpected;
}
}
namespace
{
struct TPCCFDecodeScanTmp {
int32_t zsPtrFirst, zsPageFirst, zsPtrLast, zsPageLast, hasData, pageCounter;
};
} // namespace
std::pair<uint32_t, uint32_t> GPUChainTracking::TPCClusterizerDecodeZSCount(uint32_t iSector, const CfFragment& fragment)
{
mRec->getGeneralStepTimer(GeneralStep::Prepare).Start();
uint32_t nDigits = 0;
uint32_t nPages = 0;
uint32_t endpointAdcSamples[GPUTrackingInOutZS::NENDPOINTS];
memset(endpointAdcSamples, 0, sizeof(endpointAdcSamples));
bool doGPU = mRec->GetRecoStepsGPU() & GPUDataTypes::RecoStep::TPCClusterFinding;
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);
for (uint16_t j = 0; j < GPUTrackingInOutZS::NENDPOINTS; j++) {
#ifndef GPUCA_NO_VC
if (GetProcessingSettings().prefetchTPCpageScan >= 3 && j < GPUTrackingInOutZS::NENDPOINTS - 1) {
for (uint32_t k = 0; k < mIOPtrs.tpcZS->sector[iSector].count[j + 1]; k++) {
for (uint32_t l = 0; l < mIOPtrs.tpcZS->sector[iSector].nZSPtr[j + 1][k]; l++) {
Vc::Common::prefetchMid(((const uint8_t*)mIOPtrs.tpcZS->sector[iSector].zsPtr[j + 1][k]) + l * TPCZSHDR::TPC_ZS_PAGE_SIZE);
Vc::Common::prefetchMid(((const uint8_t*)mIOPtrs.tpcZS->sector[iSector].zsPtr[j + 1][k]) + l * TPCZSHDR::TPC_ZS_PAGE_SIZE + sizeof(o2::header::RAWDataHeader));
}
}
}
#endif
std::vector<std::pair<CfFragment, TPCCFDecodeScanTmp>> fragments;
fragments.reserve(mCFContext->nFragments);
fragments.emplace_back(std::pair<CfFragment, TPCCFDecodeScanTmp>{fragment, {0, 0, 0, 0, 0, -1}});
for (uint32_t i = 1; i < mCFContext->nFragments; i++) {
fragments.emplace_back(std::pair<CfFragment, TPCCFDecodeScanTmp>{fragments.back().first.next(), {0, 0, 0, 0, 0, -1}});
}
std::vector<bool> fragmentExtends(mCFContext->nFragments, false);
uint32_t firstPossibleFragment = 0;
uint32_t pageCounter = 0;
uint32_t emptyPages = 0;
for (uint32_t k = 0; k < mIOPtrs.tpcZS->sector[iSector].count[j]; k++) {
if (GetProcessingSettings().tpcSingleSector != -1 && GetProcessingSettings().tpcSingleSector != (int32_t)iSector) {
break;
}
nPages += mIOPtrs.tpcZS->sector[iSector].nZSPtr[j][k];
for (uint32_t l = 0; l < mIOPtrs.tpcZS->sector[iSector].nZSPtr[j][k]; l++) {
#ifndef GPUCA_NO_VC
if (GetProcessingSettings().prefetchTPCpageScan >= 2 && l + 1 < mIOPtrs.tpcZS->sector[iSector].nZSPtr[j][k]) {
Vc::Common::prefetchForOneRead(((const uint8_t*)mIOPtrs.tpcZS->sector[iSector].zsPtr[j][k]) + (l + 1) * TPCZSHDR::TPC_ZS_PAGE_SIZE);
Vc::Common::prefetchForOneRead(((const uint8_t*)mIOPtrs.tpcZS->sector[iSector].zsPtr[j][k]) + (l + 1) * TPCZSHDR::TPC_ZS_PAGE_SIZE + sizeof(o2::header::RAWDataHeader));
}
#endif
const uint8_t* const page = ((const uint8_t*)mIOPtrs.tpcZS->sector[iSector].zsPtr[j][k]) + l * TPCZSHDR::TPC_ZS_PAGE_SIZE;
const o2::header::RAWDataHeader* rdh = (const o2::header::RAWDataHeader*)page;
if (o2::raw::RDHUtils::getMemorySize(*rdh) == sizeof(o2::header::RAWDataHeader)) {
emptyPages++;
continue;
}
pageCounter++;
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)));
if (mCFContext->zsVersion == -1) {
mCFContext->zsVersion = hdr->version;
if (GetProcessingSettings().param.tpcTriggerHandling && mCFContext->zsVersion < ZSVersion::ZSVersionDenseLinkBased) { // TODO: Move tpcTriggerHandling to recoSteps bitmask
static bool errorShown = false;
if (errorShown == false) {
GPUAlarm("Trigger handling only possible with TPC Dense Link Based data, received version %d, disabling", mCFContext->zsVersion);
}
errorShown = true;
}
} else if (mCFContext->zsVersion != (int32_t)hdr->version) {
GPUError("Received TPC ZS 8kb page of mixed versions, expected %d, received %d (linkid %d, feeCRU %d, feeEndpoint %d, feelinkid %d)", mCFContext->zsVersion, (int32_t)hdr->version, (int32_t)o2::raw::RDHUtils::getLinkID(*rdh), (int32_t)rdh_utils::getCRU(*rdh), (int32_t)rdh_utils::getEndPoint(*rdh), (int32_t)rdh_utils::getLink(*rdh));
constexpr size_t bufferSize = 3 * std::max(sizeof(*rdh), sizeof(*hdr)) + 1;
char dumpBuffer[bufferSize];
for (size_t i = 0; i < sizeof(*rdh); i++) {
// "%02X " guaranteed to be 3 chars + ending 0.
snprintf(dumpBuffer + 3 * i, 4, "%02X ", (int32_t)((uint8_t*)rdh)[i]);
}
GPUAlarm("RDH of page: %s", dumpBuffer);
for (size_t i = 0; i < sizeof(*hdr); i++) {
// "%02X " guaranteed to be 3 chars + ending 0.
snprintf(dumpBuffer + 3 * i, 4, "%02X ", (int32_t)((uint8_t*)hdr)[i]);
}
GPUAlarm("Metainfo of page: %s", dumpBuffer);
if (GetProcessingSettings().ignoreNonFatalGPUErrors) {
mCFContext->abandonTimeframe = true;
return {0, 0};
} else {
GPUFatal("Cannot process with invalid TPC ZS data, exiting");
}
}
if (GetProcessingSettings().param.tpcTriggerHandling) {
const TPCZSHDRV2* const hdr2 = (const TPCZSHDRV2*)hdr;
if (hdr2->flags & TPCZSHDRV2::ZSFlags::TriggerWordPresent) {
const char* triggerWord = (const char*)hdr - TPCZSHDRV2::TRIGGER_WORD_SIZE;
o2::tpc::TriggerInfoDLBZS tmp;
memcpy((void*)&tmp.triggerWord, triggerWord, TPCZSHDRV2::TRIGGER_WORD_SIZE);
tmp.orbit = o2::raw::RDHUtils::getHeartBeatOrbit(*rdh);
if (tmp.triggerWord.isValid(0)) {
mTriggerBuffer->triggers.emplace(tmp);
}
}
}
nDigits += hdr->nADCsamples;
endpointAdcSamples[j] += hdr->nADCsamples;
uint32_t timeBin = (hdr->timeOffset + (o2::raw::RDHUtils::getHeartBeatOrbit(*rdh) - firstHBF) * o2::constants::lhc::LHCMaxBunches) / LHCBCPERTIMEBIN;
uint32_t maxTimeBin = timeBin + hdr->nTimeBinSpan;
if (mCFContext->zsVersion >= ZSVersion::ZSVersionDenseLinkBased) {
const TPCZSHDRV2* const hdr2 = (const TPCZSHDRV2*)hdr;
if (hdr2->flags & TPCZSHDRV2::ZSFlags::nTimeBinSpanBit8) {
maxTimeBin += 256;
}
}
if (maxTimeBin > mCFContext->tpcMaxTimeBin) {
mCFContext->tpcMaxTimeBin = maxTimeBin;
}
bool extendsInNextPage = false;
if (mCFContext->zsVersion >= ZSVersion::ZSVersionDenseLinkBased) {
if (l + 1 < mIOPtrs.tpcZS->sector[iSector].nZSPtr[j][k] && o2::raw::RDHUtils::getMemorySize(*rdh) == TPCZSHDR::TPC_ZS_PAGE_SIZE) {
const o2::header::RAWDataHeader* nextrdh = (const o2::header::RAWDataHeader*)(page + TPCZSHDR::TPC_ZS_PAGE_SIZE);
extendsInNextPage = o2::raw::RDHUtils::getHeartBeatOrbit(*nextrdh) == o2::raw::RDHUtils::getHeartBeatOrbit(*rdh) && o2::raw::RDHUtils::getMemorySize(*nextrdh) > sizeof(o2::header::RAWDataHeader);
}
}
while (firstPossibleFragment && (uint32_t)fragments[firstPossibleFragment - 1].first.last() > timeBin) {
firstPossibleFragment--;
}
auto handleExtends = [&](uint32_t ff) {
if (fragmentExtends[ff]) {
if (doGPU) {
// Only add extended page on GPU. On CPU the pages are in consecutive memory anyway.
// Not adding the page prevents an issue where a page is decoded twice on CPU, when only the extend should be decoded.
fragments[ff].second.zsPageLast++;
mCFContext->fragmentData[ff].nPages[iSector][j]++;
mCFContext->fragmentData[ff].pageDigits[iSector][j].emplace_back(0);
}
fragmentExtends[ff] = false;
}
};
if (mCFContext->zsVersion >= ZSVersion::ZSVersionDenseLinkBased) {
for (uint32_t ff = 0; ff < firstPossibleFragment; ff++) {
handleExtends(ff);
}
}
for (uint32_t f = firstPossibleFragment; f < mCFContext->nFragments; f++) {
if (timeBin < (uint32_t)fragments[f].first.last() && (uint32_t)fragments[f].first.first() <= maxTimeBin) {
if (!fragments[f].second.hasData) {
fragments[f].second.hasData = 1;
fragments[f].second.zsPtrFirst = k;
fragments[f].second.zsPageFirst = l;
} else {
if (pageCounter > (uint32_t)fragments[f].second.pageCounter + 1) {
mCFContext->fragmentData[f].nPages[iSector][j] += emptyPages + pageCounter - fragments[f].second.pageCounter - 1;
for (uint32_t k2 = fragments[f].second.zsPtrLast - 1; k2 <= k; k2++) {
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++) {
if (doGPU) {
mCFContext->fragmentData[f].pageDigits[iSector][j].emplace_back(0);
} else {
// CPU cannot skip unneeded pages, so we must keep space to store the invalid dummy clusters
const uint8_t* const pageTmp = ((const uint8_t*)mIOPtrs.tpcZS->sector[iSector].zsPtr[j][k2]) + l2 * TPCZSHDR::TPC_ZS_PAGE_SIZE;
const o2::header::RAWDataHeader* rdhTmp = (const o2::header::RAWDataHeader*)pageTmp;
if (o2::raw::RDHUtils::getMemorySize(*rdhTmp) != sizeof(o2::header::RAWDataHeader)) {
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)));
mCFContext->fragmentData[f].nDigits[iSector][j] += hdrTmp->nADCsamples;
}
}
}
}
} else if (emptyPages) {
mCFContext->fragmentData[f].nPages[iSector][j] += emptyPages;
if (doGPU) {
for (uint32_t m = 0; m < emptyPages; m++) {
mCFContext->fragmentData[f].pageDigits[iSector][j].emplace_back(0);
}
}
}
}
fragments[f].second.zsPtrLast = k + 1;
fragments[f].second.zsPageLast = l + 1;
fragments[f].second.pageCounter = pageCounter;
mCFContext->fragmentData[f].nPages[iSector][j]++;
mCFContext->fragmentData[f].nDigits[iSector][j] += hdr->nADCsamples;
if (doGPU) {
mCFContext->fragmentData[f].pageDigits[iSector][j].emplace_back(hdr->nADCsamples);
}
fragmentExtends[f] = extendsInNextPage;
} else {
handleExtends(f);
if (timeBin < (uint32_t)fragments[f].first.last()) {
if (mCFContext->zsVersion >= ZSVersion::ZSVersionDenseLinkBased) {
for (uint32_t ff = f + 1; ff < mCFContext->nFragments; ff++) {
handleExtends(ff);
}
}
break;
} else {
firstPossibleFragment = f + 1;
}
}
}
emptyPages = 0;
}
}
for (uint32_t f = 0; f < mCFContext->nFragments; f++) {
mCFContext->fragmentData[f].minMaxCN[iSector][j].zsPtrLast = fragments[f].second.zsPtrLast;
mCFContext->fragmentData[f].minMaxCN[iSector][j].zsPtrFirst = fragments[f].second.zsPtrFirst;
mCFContext->fragmentData[f].minMaxCN[iSector][j].zsPageLast = fragments[f].second.zsPageLast;
mCFContext->fragmentData[f].minMaxCN[iSector][j].zsPageFirst = fragments[f].second.zsPageFirst;
}
}
mCFContext->nPagesTotal += nPages;
mCFContext->nPagesSector[iSector] = nPages;
mCFContext->nDigitsEndpointMax[iSector] = 0;
for (uint32_t i = 0; i < GPUTrackingInOutZS::NENDPOINTS; i++) {
if (endpointAdcSamples[i] > mCFContext->nDigitsEndpointMax[iSector]) {
mCFContext->nDigitsEndpointMax[iSector] = endpointAdcSamples[i];
}
}
uint32_t nDigitsFragmentMax = 0;
for (uint32_t i = 0; i < mCFContext->nFragments; i++) {
uint32_t pagesInFragment = 0;
uint32_t digitsInFragment = 0;
for (uint16_t j = 0; j < GPUTrackingInOutZS::NENDPOINTS; j++) {
pagesInFragment += mCFContext->fragmentData[i].nPages[iSector][j];
digitsInFragment += mCFContext->fragmentData[i].nDigits[iSector][j];
}
mCFContext->nPagesFragmentMax = std::max(mCFContext->nPagesFragmentMax, pagesInFragment);
nDigitsFragmentMax = std::max(nDigitsFragmentMax, digitsInFragment);
}
mRec->getGeneralStepTimer(GeneralStep::Prepare).Stop();
return {nDigits, nDigitsFragmentMax};
}
void GPUChainTracking::RunTPCClusterizer_compactPeaks(GPUTPCClusterFinder& clusterer, GPUTPCClusterFinder& clustererShadow, int32_t stage, bool doGPU, int32_t lane)
{
auto& in = stage ? clustererShadow.mPpeakPositions : clustererShadow.mPpositions;
auto& out = stage ? clustererShadow.mPfilteredPeakPositions : clustererShadow.mPpeakPositions;
if (doGPU) {
const uint32_t iSector = clusterer.mISector;
auto& count = stage ? clusterer.mPmemory->counters.nPeaks : clusterer.mPmemory->counters.nPositions;
std::vector<size_t> counts;
uint32_t nSteps = clusterer.getNSteps(count);
if (nSteps > clusterer.mNBufs) {
GPUError("Clusterer buffers exceeded (%u > %u)", nSteps, (int32_t)clusterer.mNBufs);
exit(1);
}
int32_t scanWorkgroupSize = mRec->getGPUParameters(doGPU).par_CF_SCAN_WORKGROUP_SIZE;
size_t tmpCount = count;
if (nSteps > 1) {
for (uint32_t i = 1; i < nSteps; i++) {
counts.push_back(tmpCount);
if (i == 1) {
runKernel<GPUTPCCFStreamCompaction, GPUTPCCFStreamCompaction::scanStart>({GetGrid(tmpCount, scanWorkgroupSize, lane), {iSector}}, i, stage);
} else {
runKernel<GPUTPCCFStreamCompaction, GPUTPCCFStreamCompaction::scanUp>({GetGrid(tmpCount, scanWorkgroupSize, lane), {iSector}}, i, tmpCount);
}
tmpCount = (tmpCount + scanWorkgroupSize - 1) / scanWorkgroupSize;
}
runKernel<GPUTPCCFStreamCompaction, GPUTPCCFStreamCompaction::scanTop>({GetGrid(tmpCount, scanWorkgroupSize, lane), {iSector}}, nSteps, tmpCount);
for (uint32_t i = nSteps - 1; i > 1; i--) {
tmpCount = counts[i - 1];
runKernel<GPUTPCCFStreamCompaction, GPUTPCCFStreamCompaction::scanDown>({GetGrid(tmpCount - scanWorkgroupSize, scanWorkgroupSize, lane), {iSector}}, i, scanWorkgroupSize, tmpCount);
}
}
runKernel<GPUTPCCFStreamCompaction, GPUTPCCFStreamCompaction::compactDigits>({GetGrid(count, scanWorkgroupSize, lane), {iSector}}, 1, stage, in, out);
} else {
auto& nOut = stage ? clusterer.mPmemory->counters.nClusters : clusterer.mPmemory->counters.nPeaks;
auto& nIn = stage ? clusterer.mPmemory->counters.nPeaks : clusterer.mPmemory->counters.nPositions;
size_t count = 0;
for (size_t i = 0; i < nIn; i++) {
if (clusterer.mPisPeak[i]) {
out[count++] = in[i];
}
}
nOut = count;
}
}
std::pair<uint32_t, uint32_t> GPUChainTracking::RunTPCClusterizer_transferZS(int32_t iSector, const CfFragment& fragment, int32_t lane)
{
bool doGPU = GetRecoStepsGPU() & RecoStep::TPCClusterFinding;
if (mCFContext->abandonTimeframe) {
return {0, 0};
}
const auto& retVal = TPCClusterizerDecodeZSCountUpdate(iSector, fragment);
if (doGPU) {
GPUTPCClusterFinder& clusterer = processors()->tpcClusterer[iSector];
GPUTPCClusterFinder& clustererShadow = doGPU ? processorsShadow()->tpcClusterer[iSector] : clusterer;
uint32_t nPagesSector = 0;
for (uint32_t j = 0; j < GPUTrackingInOutZS::NENDPOINTS; j++) {
uint32_t nPages = 0;
mInputsHost->mPzsMeta->sector[iSector].zsPtr[j] = &mInputsShadow->mPzsPtrs[iSector * GPUTrackingInOutZS::NENDPOINTS + j];
mInputsHost->mPzsPtrs[iSector * GPUTrackingInOutZS::NENDPOINTS + j] = clustererShadow.mPzs + (nPagesSector + nPages) * TPCZSHDR::TPC_ZS_PAGE_SIZE;
for (uint32_t k = clusterer.mMinMaxCN[j].zsPtrFirst; k < clusterer.mMinMaxCN[j].zsPtrLast; k++) {
const uint32_t min = (k == clusterer.mMinMaxCN[j].zsPtrFirst) ? clusterer.mMinMaxCN[j].zsPageFirst : 0;
const uint32_t max = (k + 1 == clusterer.mMinMaxCN[j].zsPtrLast) ? clusterer.mMinMaxCN[j].zsPageLast : mIOPtrs.tpcZS->sector[iSector].nZSPtr[j][k];
if (max > min) {
char* src = (char*)mIOPtrs.tpcZS->sector[iSector].zsPtr[j][k] + min * TPCZSHDR::TPC_ZS_PAGE_SIZE;
char* ptrLast = (char*)mIOPtrs.tpcZS->sector[iSector].zsPtr[j][k] + (max - 1) * TPCZSHDR::TPC_ZS_PAGE_SIZE;
size_t size = (ptrLast - src) + o2::raw::RDHUtils::getMemorySize(*(const o2::header::RAWDataHeader*)ptrLast);
GPUMemCpy(RecoStep::TPCClusterFinding, clustererShadow.mPzs + (nPagesSector + nPages) * TPCZSHDR::TPC_ZS_PAGE_SIZE, src, size, lane, true);
}
nPages += max - min;
}
mInputsHost->mPzsMeta->sector[iSector].nZSPtr[j] = &mInputsShadow->mPzsSizes[iSector * GPUTrackingInOutZS::NENDPOINTS + j];
mInputsHost->mPzsSizes[iSector * GPUTrackingInOutZS::NENDPOINTS + j] = nPages;
mInputsHost->mPzsMeta->sector[iSector].count[j] = 1;
nPagesSector += nPages;
}
GPUMemCpy(RecoStep::TPCClusterFinding, clustererShadow.mPzsOffsets, clusterer.mPzsOffsets, clusterer.mNMaxPages * sizeof(*clusterer.mPzsOffsets), lane, true);
}
return retVal;
}
int32_t GPUChainTracking::RunTPCClusterizer_prepare(bool restorePointers)
{
bool doGPU = mRec->GetRecoStepsGPU() & GPUDataTypes::RecoStep::TPCClusterFinding;
if (restorePointers) {
for (uint32_t iSector = 0; iSector < NSECTORS; iSector++) {
processors()->tpcClusterer[iSector].mPzsOffsets = mCFContext->ptrSave[iSector].zsOffsetHost;
processorsShadow()->tpcClusterer[iSector].mPzsOffsets = mCFContext->ptrSave[iSector].zsOffsetDevice;
processorsShadow()->tpcClusterer[iSector].mPzs = mCFContext->ptrSave[iSector].zsDevice;
}
processorsShadow()->ioPtrs.clustersNative = mCFContext->ptrClusterNativeSave;
return 0;
}
const auto& threadContext = GetThreadContext();
mRec->MemoryScalers()->nTPCdigits = 0;
if (mCFContext == nullptr) {
mCFContext.reset(new GPUTPCCFChainContext);
}
const int16_t maxFragmentLen = GetProcessingSettings().overrideClusterizerFragmentLen;
const uint32_t maxAllowedTimebin = param().par.continuousTracking ? std::max<int32_t>(param().continuousMaxTimeBin, maxFragmentLen) : TPC_MAX_TIME_BIN_TRIGGERED;
mCFContext->tpcMaxTimeBin = maxAllowedTimebin;
const CfFragment fragmentMax{(tpccf::TPCTime)mCFContext->tpcMaxTimeBin + 1, maxFragmentLen};
mCFContext->prepare(mIOPtrs.tpcZS, fragmentMax);
if (GetProcessingSettings().param.tpcTriggerHandling) {
mTriggerBuffer->triggers.clear();
}
if (mIOPtrs.tpcZS) {
uint32_t nDigitsFragmentMax[NSECTORS];
mCFContext->zsVersion = -1;
for (uint32_t iSector = 0; iSector < NSECTORS; iSector++) {
if (mIOPtrs.tpcZS->sector[iSector].count[0]) {
const void* rdh = mIOPtrs.tpcZS->sector[iSector].zsPtr[0][0];
if (rdh && o2::raw::RDHUtils::getVersion<o2::header::RAWDataHeaderV6>() > o2::raw::RDHUtils::getVersion(rdh)) {
GPUError("Data has invalid RDH version %d, %d required\n", o2::raw::RDHUtils::getVersion(rdh), o2::raw::RDHUtils::getVersion<o2::header::RAWDataHeader>());
return 1;
}
}
#ifndef GPUCA_NO_VC
if (GetProcessingSettings().prefetchTPCpageScan >= 1 && iSector < NSECTORS - 1) {
for (uint32_t j = 0; j < GPUTrackingInOutZS::NENDPOINTS; j++) {
for (uint32_t k = 0; k < mIOPtrs.tpcZS->sector[iSector].count[j]; k++) {
for (uint32_t l = 0; l < mIOPtrs.tpcZS->sector[iSector].nZSPtr[j][k]; l++) {
Vc::Common::prefetchFar(((const uint8_t*)mIOPtrs.tpcZS->sector[iSector + 1].zsPtr[j][k]) + l * TPCZSHDR::TPC_ZS_PAGE_SIZE);
Vc::Common::prefetchFar(((const uint8_t*)mIOPtrs.tpcZS->sector[iSector + 1].zsPtr[j][k]) + l * TPCZSHDR::TPC_ZS_PAGE_SIZE + sizeof(o2::header::RAWDataHeader));
}
}
}
}
#endif
const auto& x = TPCClusterizerDecodeZSCount(iSector, fragmentMax);
nDigitsFragmentMax[iSector] = x.first;
processors()->tpcClusterer[iSector].mPmemory->counters.nDigits = x.first;
mRec->MemoryScalers()->nTPCdigits += x.first;
}
for (uint32_t iSector = 0; iSector < NSECTORS; iSector++) {
uint32_t nDigitsBase = nDigitsFragmentMax[iSector];
uint32_t threshold = 40000000;
uint32_t nDigitsScaled = nDigitsBase > threshold ? nDigitsBase : std::min((threshold + nDigitsBase) / 2, 2 * nDigitsBase);
processors()->tpcClusterer[iSector].SetNMaxDigits(processors()->tpcClusterer[iSector].mPmemory->counters.nDigits, mCFContext->nPagesFragmentMax, nDigitsScaled, mCFContext->nDigitsEndpointMax[iSector]);
if (doGPU) {
processorsShadow()->tpcClusterer[iSector].SetNMaxDigits(processors()->tpcClusterer[iSector].mPmemory->counters.nDigits, mCFContext->nPagesFragmentMax, nDigitsScaled, mCFContext->nDigitsEndpointMax[iSector]);
}
if (mPipelineNotifyCtx && GetProcessingSettings().doublePipelineClusterizer) {
mPipelineNotifyCtx->rec->AllocateRegisteredForeignMemory(processors()->tpcClusterer[iSector].mZSOffsetId, mRec);
mPipelineNotifyCtx->rec->AllocateRegisteredForeignMemory(processors()->tpcClusterer[iSector].mZSId, mRec);
} else {
AllocateRegisteredMemory(processors()->tpcClusterer[iSector].mZSOffsetId);
AllocateRegisteredMemory(processors()->tpcClusterer[iSector].mZSId);
}
}
} else {
for (uint32_t iSector = 0; iSector < NSECTORS; iSector++) {
uint32_t nDigits = mIOPtrs.tpcPackedDigits->nTPCDigits[iSector];
mRec->MemoryScalers()->nTPCdigits += nDigits;
processors()->tpcClusterer[iSector].SetNMaxDigits(nDigits, mCFContext->nPagesFragmentMax, nDigits, 0);
}
}
if (mIOPtrs.tpcZS) {
GPUInfo("Event has %u 8kb TPC ZS pages (version %d), %ld digits", mCFContext->nPagesTotal, mCFContext->zsVersion, (int64_t)mRec->MemoryScalers()->nTPCdigits);
} else {
GPUInfo("Event has %ld TPC Digits", (int64_t)mRec->MemoryScalers()->nTPCdigits);
}
if (mCFContext->tpcMaxTimeBin > maxAllowedTimebin) {
GPUError("Input data has invalid time bin %u > %d", mCFContext->tpcMaxTimeBin, maxAllowedTimebin);
if (GetProcessingSettings().ignoreNonFatalGPUErrors) {
mCFContext->abandonTimeframe = true;
mCFContext->tpcMaxTimeBin = maxAllowedTimebin;
} else {
return 1;
}
}
mCFContext->fragmentFirst = CfFragment{std::max<int32_t>(mCFContext->tpcMaxTimeBin + 1, maxFragmentLen), maxFragmentLen};
for (int32_t iSector = 0; iSector < GetProcessingSettings().nTPCClustererLanes && iSector < NSECTORS; iSector++) {
if (mIOPtrs.tpcZS && mCFContext->nPagesSector[iSector] && mCFContext->zsVersion != -1) {
mCFContext->nextPos[iSector] = RunTPCClusterizer_transferZS(iSector, mCFContext->fragmentFirst, GetProcessingSettings().nTPCClustererLanes + iSector);
}
}
if (mPipelineNotifyCtx && GetProcessingSettings().doublePipelineClusterizer) {
for (uint32_t iSector = 0; iSector < NSECTORS; iSector++) {
mCFContext->ptrSave[iSector].zsOffsetHost = processors()->tpcClusterer[iSector].mPzsOffsets;
mCFContext->ptrSave[iSector].zsOffsetDevice = processorsShadow()->tpcClusterer[iSector].mPzsOffsets;
mCFContext->ptrSave[iSector].zsDevice = processorsShadow()->tpcClusterer[iSector].mPzs;
}
}
return 0;
}
#endif
int32_t GPUChainTracking::RunTPCClusterizer(bool synchronizeOutput)
{
if (param().rec.fwdTPCDigitsAsClusters) {
return ForwardTPCDigits();
}
#ifdef GPUCA_TPC_GEOMETRY_O2
[[maybe_unused]] int32_t tpcTimeBinCut = mUpdateNewCalibObjects && mNewCalibValues->newTPCTimeBinCut ? mNewCalibValues->tpcTimeBinCut : param().tpcCutTimeBin;
mRec->PushNonPersistentMemory(qStr2Tag("TPCCLUST"));
const auto& threadContext = GetThreadContext();
const bool doGPU = GetRecoStepsGPU() & RecoStep::TPCClusterFinding;
if (RunTPCClusterizer_prepare(mPipelineNotifyCtx && GetProcessingSettings().doublePipelineClusterizer)) {
return 1;
}
if (GetProcessingSettings().autoAdjustHostThreads && !doGPU) {
mRec->SetNActiveThreads(mRec->MemoryScalers()->nTPCdigits / 6000);
}
mRec->MemoryScalers()->nTPCHits = mRec->MemoryScalers()->NTPCClusters(mRec->MemoryScalers()->nTPCdigits);
float tpcHitLowOccupancyScalingFactor = 1.f;
if (mIOPtrs.settingsTF && mIOPtrs.settingsTF->hasNHBFPerTF) {
uint32_t nHitsBase = mRec->MemoryScalers()->nTPCHits;
uint32_t threshold = 30000000 / 256 * mIOPtrs.settingsTF->nHBFPerTF;
if (mIOPtrs.settingsTF->nHBFPerTF < 64) {
threshold *= 2;
}
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
if (nHitsBase < threshold) {
float maxFactor = mRec->MemoryScalers()->nTPCHits < threshold * 2 / 3 ? 3 : (mRec->MemoryScalers()->nTPCHits < threshold ? 2.25f : 1.75f);
mRec->MemoryScalers()->temporaryFactor *= std::min(maxFactor, (float)threshold / nHitsBase);
tpcHitLowOccupancyScalingFactor = std::min(3.5f, (float)threshold / nHitsBase);
}
}
for (uint32_t iSector = 0; iSector < NSECTORS; iSector++) {
processors()->tpcClusterer[iSector].SetMaxData(mIOPtrs); // First iteration to set data sizes
}
mRec->ComputeReuseMax(nullptr); // Resolve maximums for shared buffers
for (uint32_t iSector = 0; iSector < NSECTORS; iSector++) {
SetupGPUProcessor(&processors()->tpcClusterer[iSector], true); // Now we allocate
}
if (mPipelineNotifyCtx && GetProcessingSettings().doublePipelineClusterizer) {
RunTPCClusterizer_prepare(true); // Restore some pointers, allocated by the other pipeline, and set to 0 by SetupGPUProcessor (since not allocated in this pipeline)
}
if (doGPU && mIOPtrs.tpcZS) {
processorsShadow()->ioPtrs.tpcZS = mInputsShadow->mPzsMeta;
WriteToConstantMemory(RecoStep::TPCClusterFinding, (char*)&processors()->ioPtrs - (char*)processors(), &processorsShadow()->ioPtrs, sizeof(processorsShadow()->ioPtrs), mRec->NStreams() - 1);
}
if (doGPU) {
WriteToConstantMemory(RecoStep::TPCClusterFinding, (char*)processors()->tpcClusterer - (char*)processors(), processorsShadow()->tpcClusterer, sizeof(GPUTPCClusterFinder) * NSECTORS, mRec->NStreams() - 1, &mEvents->init);
}
#ifdef GPUCA_HAS_ONNX
const GPUSettingsProcessingNNclusterizer& nn_settings = GetProcessingSettings().nn;
GPUTPCNNClusterizerHost nnApplications[GetProcessingSettings().nTPCClustererLanes];
// Maximum of 4 lanes supported
HighResTimer* nnTimers[12];
if (GetProcessingSettings().nn.applyNNclusterizer) {
int32_t deviceId = -1;
int32_t numLanes = GetProcessingSettings().nTPCClustererLanes;
int32_t maxThreads = mRec->getNKernelHostThreads(true);
// bool recreateMemoryAllocator = false;
if (GetProcessingSettings().debugLevel >= 1) {
nnTimers[0] = &getTimer<GPUTPCNNClusterizer, 0>("GPUTPCNNClusterizer_ONNXClassification_0_", 0);
nnTimers[1] = &getTimer<GPUTPCNNClusterizer, 1>("GPUTPCNNClusterizer_ONNXRegression_1_", 1);
nnTimers[2] = &getTimer<GPUTPCNNClusterizer, 2>("GPUTPCNNClusterizer_ONNXRegression2_2_", 2);
nnTimers[3] = &getTimer<GPUTPCNNClusterizer, 3>("GPUTPCNNClusterizer_ONNXClassification_0_", 3);
nnTimers[4] = &getTimer<GPUTPCNNClusterizer, 4>("GPUTPCNNClusterizer_ONNXRegression_1_", 4);
nnTimers[5] = &getTimer<GPUTPCNNClusterizer, 5>("GPUTPCNNClusterizer_ONNXRegression2_2_", 5);
nnTimers[6] = &getTimer<GPUTPCNNClusterizer, 6>("GPUTPCNNClusterizer_ONNXClassification_0_", 6);
nnTimers[7] = &getTimer<GPUTPCNNClusterizer, 7>("GPUTPCNNClusterizer_ONNXRegression_1_", 7);
nnTimers[8] = &getTimer<GPUTPCNNClusterizer, 8>("GPUTPCNNClusterizer_ONNXRegression2_2_", 8);
nnTimers[9] = &getTimer<GPUTPCNNClusterizer, 9>("GPUTPCNNClusterizer_ONNXClassification_0_", 9);
nnTimers[10] = &getTimer<GPUTPCNNClusterizer, 10>("GPUTPCNNClusterizer_ONNXRegression_1_", 10);
nnTimers[11] = &getTimer<GPUTPCNNClusterizer, 11>("GPUTPCNNClusterizer_ONNXRegression2_2_", 11);
}
mRec->runParallelOuterLoop(doGPU, numLanes, [&](uint32_t lane) {
nnApplications[lane].init(nn_settings, GetProcessingSettings().deterministicGPUReconstruction);
if (nnApplications[lane].mModelsUsed[0]) {
SetONNXGPUStream(*(nnApplications[lane].mModelClass).getSessionOptions(), lane, &deviceId);
(nnApplications[lane].mModelClass).setDeviceId(deviceId);
if (nnApplications[lane].mModelClass.getIntraOpNumThreads() > maxThreads) {
nnApplications[lane].mModelClass.setIntraOpNumThreads(maxThreads);
}
(nnApplications[lane].mModelClass).initEnvironment();
// 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.
// But environment must be valid, so we init the model environment first and use it here afterwards.
// Either this is done in one environment with lane == 0 or by recreating the allocator using recreateMemoryAllocator.
// TODO: Volatile allocation works for reserving, but not yet for allocations when binding the input tensor
// if (lane == 0) {
// nnApplications[lane].directOrtAllocator((nnApplications[lane].mModelClass).getEnv(), (nnApplications[lane].mModelClass).getMemoryInfo(), mRec, recreateMemoryAllocator);
// }
// recreateMemoryAllocator = true;
(nnApplications[lane].mModelClass).initSession();
}
if (nnApplications[lane].mModelsUsed[1]) {
SetONNXGPUStream(*(nnApplications[lane].mModelReg1).getSessionOptions(), lane, &deviceId);
(nnApplications[lane].mModelReg1).setDeviceId(deviceId);
if (nnApplications[lane].mModelReg1.getIntraOpNumThreads() > maxThreads) {
nnApplications[lane].mModelReg1.setIntraOpNumThreads(maxThreads);
}
// (nnApplications[lane].mModelReg1).setEnv((nnApplications[lane].mModelClass).getEnv());
(nnApplications[lane].mModelReg1).initEnvironment();
// nnApplications[lane].directOrtAllocator((nnApplications[lane].mModelReg1).getEnv(), (nnApplications[lane].mModelReg1).getMemoryInfo(), mRec, recreateMemoryAllocator);
(nnApplications[lane].mModelReg1).initSession();
}
if (nnApplications[lane].mModelsUsed[2]) {
SetONNXGPUStream(*(nnApplications[lane].mModelReg2).getSessionOptions(), lane, &deviceId);
(nnApplications[lane].mModelReg2).setDeviceId(deviceId);
if (nnApplications[lane].mModelReg2.getIntraOpNumThreads() > maxThreads) {
nnApplications[lane].mModelReg2.setIntraOpNumThreads(maxThreads);
}
// (nnApplications[lane].mModelReg2).setEnv((nnApplications[lane].mModelClass).getEnv());
(nnApplications[lane].mModelReg2).initEnvironment();
// nnApplications[lane].directOrtAllocator((nnApplications[lane].mModelClass).getEnv(), (nnApplications[lane].mModelClass).getMemoryInfo(), mRec, recreateMemoryAllocator);
(nnApplications[lane].mModelReg2).initSession();
}
if (nn_settings.nnClusterizerVerbosity > 0) {
LOG(info) << "(ORT) Allocated ONNX stream for lane " << lane << " and device " << deviceId;
}
});
const int16_t maxFragmentLen = GetProcessingSettings().overrideClusterizerFragmentLen;
const uint32_t maxAllowedTimebin = param().par.continuousTracking ? std::max<int32_t>(param().continuousMaxTimeBin, maxFragmentLen) : TPC_MAX_TIME_BIN_TRIGGERED;
for (int32_t sector = 0; sector < NSECTORS; sector++) {
GPUTPCNNClusterizer& clustererNN = processors()->tpcNNClusterer[sector];
GPUTPCNNClusterizer& clustererNNShadow = doGPU ? processorsShadow()->tpcNNClusterer[sector] : clustererNN;
int32_t lane = sector % numLanes;
clustererNN.mDeviceId = deviceId;
clustererNN.mISector = sector;
clustererNN.mNnClusterizerTotalClusters = processors()->tpcClusterer[lane].mNMaxClusters;
nnApplications[lane].initClusterizer(nn_settings, clustererNN, maxFragmentLen, maxAllowedTimebin);
if (doGPU) {
clustererNNShadow.mDeviceId = deviceId;
clustererNNShadow.mISector = sector;
clustererNNShadow.mNnClusterizerTotalClusters = processors()->tpcClusterer[lane].mNMaxClusters;
nnApplications[lane].initClusterizer(nn_settings, clustererNNShadow, maxFragmentLen, maxAllowedTimebin);
}
if (nn_settings.nnClusterizerVerbosity > 2) {
LOG(info) << "(NNCLUS, GPUChainTrackingClusterizer, this=" << this << ") Processor initialized. Sector " << sector << ", lane " << lane << ", max clusters " << clustererNN.mNnClusterizerTotalClusters << " (clustererNN=" << &clustererNN << ", clustererNNShadow=" << &clustererNNShadow << ")";
}
AllocateRegisteredMemory(clustererNN.mMemoryId);
if (nn_settings.nnClusterizerVerbosity > 2) {
LOG(info) << "(NNCLUS, GPUChainTrackingClusterizer, this=" << this << ") Memory registered for memoryId " << clustererNN.mMemoryId << " (clustererNN=" << &clustererNN << ", clustererNNShadow=" << &clustererNNShadow << ")";
}
// nnApplications[lane].createBoundary(clustererNNShadow);
// nnApplications[lane].createIndexLookup(clustererNNShadow);
}
if (doGPU) {
if (nn_settings.nnClusterizerVerbosity > 2) {
LOG(info) << "(NNCLUS, GPUChainTrackingClusterizer, this=" << this << ") Writing to constant memory...";
}
WriteToConstantMemory(RecoStep::TPCClusterFinding, (char*)&processors()->tpcNNClusterer - (char*)processors(), &processorsShadow()->tpcNNClusterer, sizeof(GPUTPCNNClusterizer) * NSECTORS, mRec->NStreams() - 1, &mEvents->init);
if (nn_settings.nnClusterizerVerbosity > 2) {
LOG(info) << "(NNCLUS, GPUChainTrackingClusterizer, this=" << this << ") Writing to constant memory done";
}
}
}
#endif
size_t nClsTotal = 0;
ClusterNativeAccess* tmpNativeAccess = mClusterNativeAccess.get();
ClusterNative* tmpNativeClusters = nullptr;
std::unique_ptr<ClusterNative[]> tmpNativeClusterBuffer;
// setup MC Labels
bool propagateMCLabels = GetProcessingSettings().runMC && processors()->ioPtrs.tpcPackedDigits && processors()->ioPtrs.tpcPackedDigits->tpcDigitsMC;
auto* digitsMC = propagateMCLabels ? processors()->ioPtrs.tpcPackedDigits->tpcDigitsMC : nullptr;
bool buildNativeGPU = doGPU && NeedTPCClustersOnGPU();
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
mInputsHost->mNClusterNative = mInputsShadow->mNClusterNative = mRec->MemoryScalers()->nTPCHits * tpcHitLowOccupancyScalingFactor;
if (buildNativeGPU) {
AllocateRegisteredMemory(mInputsHost->mResourceClusterNativeBuffer);
}
if (mWaitForFinalInputs && GetProcessingSettings().nTPCClustererLanes > 6) {
GPUFatal("ERROR, mWaitForFinalInputs cannot be called with nTPCClustererLanes > 6");
}
if (buildNativeHost && !(buildNativeGPU && GetProcessingSettings().delayedOutput)) {
if (mWaitForFinalInputs) {
GPUFatal("Cannot use waitForFinalInput callback without delayed output");
}
if (!GetProcessingSettings().tpcApplyClusterFilterOnCPU) {
AllocateRegisteredMemory(mInputsHost->mResourceClusterNativeOutput, mSubOutputControls[GPUTrackingOutputs::getIndex(&GPUTrackingOutputs::clustersNative)]);
tmpNativeClusters = mInputsHost->mPclusterNativeOutput;
} else {
tmpNativeClusterBuffer = std::make_unique<ClusterNative[]>(mInputsHost->mNClusterNative);
tmpNativeClusters = tmpNativeClusterBuffer.get();
}
}
GPUTPCLinearLabels mcLinearLabels;
if (propagateMCLabels) {
// 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
mcLinearLabels.header.reserve(mRec->MemoryScalers()->nTPCHits / 2);
mcLinearLabels.data.reserve(mRec->MemoryScalers()->nTPCHits);
}
int8_t transferRunning[NSECTORS] = {0};
uint32_t outputQueueStart = mOutputQueue.size();
auto notifyForeignChainFinished = [this]() {
if (mPipelineNotifyCtx) {
SynchronizeStream(OutputStream()); // Must finish before updating ioPtrs in (global) constant memory
{
std::lock_guard<std::mutex> lock(mPipelineNotifyCtx->mutex);
mPipelineNotifyCtx->ready = true;
}
mPipelineNotifyCtx->cond.notify_one();
}
};
bool synchronizeCalibUpdate = false;
for (uint32_t iSectorBase = 0; iSectorBase < NSECTORS; iSectorBase += GetProcessingSettings().nTPCClustererLanes) {
std::vector<bool> laneHasData(GetProcessingSettings().nTPCClustererLanes, false);
static_assert(NSECTORS <= GPUCA_MAX_STREAMS, "Stream events must be able to hold all sectors");
const int32_t maxLane = std::min<int32_t>(GetProcessingSettings().nTPCClustererLanes, NSECTORS - iSectorBase);
for (CfFragment fragment = mCFContext->fragmentFirst; !fragment.isEnd(); fragment = fragment.next()) {
if (GetProcessingSettings().debugLevel >= 3) {
GPUInfo("Processing time bins [%d, %d) for sectors %d to %d", fragment.start, fragment.last(), iSectorBase, iSectorBase + GetProcessingSettings().nTPCClustererLanes - 1);
}
mRec->runParallelOuterLoop(doGPU, maxLane, [&](uint32_t lane) {
if (doGPU && fragment.index != 0) {
SynchronizeStream(lane); // Don't overwrite charge map from previous iteration until cluster computation is finished
}
uint32_t iSector = iSectorBase + lane;
GPUTPCClusterFinder& clusterer = processors()->tpcClusterer[iSector];
GPUTPCClusterFinder& clustererShadow = doGPU ? processorsShadow()->tpcClusterer[iSector] : clusterer;
clusterer.mPmemory->counters.nPeaks = clusterer.mPmemory->counters.nClusters = 0;
clusterer.mPmemory->fragment = fragment;
if (mIOPtrs.tpcPackedDigits) {
bool setDigitsOnGPU = doGPU && not mIOPtrs.tpcZS;
bool setDigitsOnHost = (not doGPU && not mIOPtrs.tpcZS) || propagateMCLabels;
auto* inDigits = mIOPtrs.tpcPackedDigits;
size_t numDigits = inDigits->nTPCDigits[iSector];
if (setDigitsOnGPU) {
GPUMemCpy(RecoStep::TPCClusterFinding, clustererShadow.mPdigits, inDigits->tpcDigits[iSector], sizeof(clustererShadow.mPdigits[0]) * numDigits, lane, true);
}
if (setDigitsOnHost) {
clusterer.mPdigits = const_cast<o2::tpc::Digit*>(inDigits->tpcDigits[iSector]); // TODO: Needs fixing (invalid const cast)
}
clusterer.mPmemory->counters.nDigits = numDigits;
}
if (mIOPtrs.tpcZS) {
if (mCFContext->nPagesSector[iSector] && mCFContext->zsVersion != -1) {
clusterer.mPmemory->counters.nPositions = mCFContext->nextPos[iSector].first;
clusterer.mPmemory->counters.nPagesSubsector = mCFContext->nextPos[iSector].second;
} else {
clusterer.mPmemory->counters.nPositions = clusterer.mPmemory->counters.nPagesSubsector = 0;
}
}
TransferMemoryResourceLinkToGPU(RecoStep::TPCClusterFinding, clusterer.mMemoryId, lane);
using ChargeMapType = decltype(*clustererShadow.mPchargeMap);
using PeakMapType = decltype(*clustererShadow.mPpeakMap);
runKernel<GPUMemClean16>({GetGridAutoStep(lane, RecoStep::TPCClusterFinding)}, clustererShadow.mPchargeMap, TPCMapMemoryLayout<ChargeMapType>::items(GetProcessingSettings().overrideClusterizerFragmentLen) * sizeof(ChargeMapType));
runKernel<GPUMemClean16>({GetGridAutoStep(lane, RecoStep::TPCClusterFinding)}, clustererShadow.mPpeakMap, TPCMapMemoryLayout<PeakMapType>::items(GetProcessingSettings().overrideClusterizerFragmentLen) * sizeof(PeakMapType));
if (fragment.index == 0) {
runKernel<GPUMemClean16>({GetGridAutoStep(lane, RecoStep::TPCClusterFinding)}, clustererShadow.mPpadIsNoisy, TPC_PADS_IN_SECTOR * sizeof(*clustererShadow.mPpadIsNoisy));
}
DoDebugAndDump(RecoStep::TPCClusterFinding, GPUChainTrackingDebugFlags::TPCClustererZeroedCharges, clusterer, &GPUTPCClusterFinder::DumpChargeMap, *mDebugFile, "Zeroed Charges");
if (doGPU) {
if (mIOPtrs.tpcZS && mCFContext->nPagesSector[iSector] && mCFContext->zsVersion != -1) {
TransferMemoryResourceLinkToGPU(RecoStep::TPCClusterFinding, mInputsHost->mResourceZS, lane);
SynchronizeStream(GetProcessingSettings().nTPCClustererLanes + lane);
}
SynchronizeStream(mRec->NStreams() - 1); // Wait for copying to constant memory
}
if (mIOPtrs.tpcZS && (mCFContext->abandonTimeframe || !mCFContext->nPagesSector[iSector] || mCFContext->zsVersion == -1)) {
clusterer.mPmemory->counters.nPositions = 0;
return;
}
if (!mIOPtrs.tpcZS && mIOPtrs.tpcPackedDigits->nTPCDigits[iSector] == 0) {
clusterer.mPmemory->counters.nPositions = 0;
return;
}
if (propagateMCLabels && fragment.index == 0) {
clusterer.PrepareMC();
clusterer.mPinputLabels = digitsMC->v[iSector];
if (clusterer.mPinputLabels == nullptr) {
GPUFatal("MC label container missing, sector %d", iSector);
}
if (clusterer.mPinputLabels->getIndexedSize() != mIOPtrs.tpcPackedDigits->nTPCDigits[iSector]) {
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());
}
}
if (GetProcessingSettings().tpcSingleSector == -1 || GetProcessingSettings().tpcSingleSector == (int32_t)iSector) {
if (not mIOPtrs.tpcZS) {
runKernel<GPUTPCCFChargeMapFiller, GPUTPCCFChargeMapFiller::findFragmentStart>({GetGrid(1, lane), {iSector}}, mIOPtrs.tpcZS == nullptr);
TransferMemoryResourceLinkToHost(RecoStep::TPCClusterFinding, clusterer.mMemoryId, lane);
} else if (propagateMCLabels) {
runKernel<GPUTPCCFChargeMapFiller, GPUTPCCFChargeMapFiller::findFragmentStart>({GetGrid(1, lane, GPUReconstruction::krnlDeviceType::CPU), {iSector}}, mIOPtrs.tpcZS == nullptr);
TransferMemoryResourceLinkToGPU(RecoStep::TPCClusterFinding, clusterer.mMemoryId, lane);
}
}
if (mIOPtrs.tpcZS) {
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);
uint32_t nBlocks = doGPU ? clusterer.mPmemory->counters.nPagesSubsector : GPUTrackingInOutZS::NENDPOINTS;
switch (mCFContext->zsVersion) {
default:
GPUFatal("Data with invalid TPC ZS mode (%d) received", mCFContext->zsVersion);
break;
case ZSVersionRowBased10BitADC:
case ZSVersionRowBased12BitADC:
runKernel<GPUTPCCFDecodeZS>({GetGridBlk(nBlocks, lane), {iSector}}, firstHBF);
break;
case ZSVersionLinkBasedWithMeta:
runKernel<GPUTPCCFDecodeZSLink>({GetGridBlk(nBlocks, lane), {iSector}}, firstHBF);
break;
case ZSVersionDenseLinkBased:
runKernel<GPUTPCCFDecodeZSDenseLink>({GetGridBlk(nBlocks, lane), {iSector}}, firstHBF);
break;
}
TransferMemoryResourceLinkToHost(RecoStep::TPCClusterFinding, clusterer.mMemoryId, lane);
} // clang-format off
});
mRec->runParallelOuterLoop(doGPU, maxLane, [&](uint32_t lane) {
uint32_t iSector = iSectorBase + lane;
if (doGPU) {
SynchronizeStream(lane);
}
if (mIOPtrs.tpcZS) {
CfFragment f = fragment.next();
int32_t nextSector = iSector;
if (f.isEnd()) {
nextSector += GetProcessingSettings().nTPCClustererLanes;
f = mCFContext->fragmentFirst;
}
if (nextSector < NSECTORS && mIOPtrs.tpcZS && mCFContext->nPagesSector[nextSector] && mCFContext->zsVersion != -1 && !mCFContext->abandonTimeframe) {
mCFContext->nextPos[nextSector] = RunTPCClusterizer_transferZS(nextSector, f, GetProcessingSettings().nTPCClustererLanes + lane);
}
}
GPUTPCClusterFinder& clusterer = processors()->tpcClusterer[iSector];
GPUTPCClusterFinder& clustererShadow = doGPU ? processorsShadow()->tpcClusterer[iSector] : clusterer;
if (clusterer.mPmemory->counters.nPositions == 0) {
return;
}
if (!mIOPtrs.tpcZS) {
runKernel<GPUTPCCFChargeMapFiller, GPUTPCCFChargeMapFiller::fillFromDigits>({GetGrid(clusterer.mPmemory->counters.nPositions, lane), {iSector}});
}
if (DoDebugAndDump(RecoStep::TPCClusterFinding, GPUChainTrackingDebugFlags::TPCClustererDigits, clusterer, &GPUTPCClusterFinder::DumpDigits, *mDebugFile)) {
clusterer.DumpChargeMap(*mDebugFile, "Charges");
}
if (propagateMCLabels) {
runKernel<GPUTPCCFChargeMapFiller, GPUTPCCFChargeMapFiller::fillIndexMap>({GetGrid(clusterer.mPmemory->counters.nDigitsInFragment, lane, GPUReconstruction::krnlDeviceType::CPU), {iSector}});
}
bool checkForNoisyPads = (rec()->GetParam().rec.tpc.maxTimeBinAboveThresholdIn1000Bin > 0) || (rec()->GetParam().rec.tpc.maxConsecTimeBinAboveThreshold > 0);
checkForNoisyPads &= (rec()->GetParam().rec.tpc.noisyPadsQuickCheck ? fragment.index == 0 : true);
checkForNoisyPads &= !GetProcessingSettings().disableTPCNoisyPadFilter;
if (checkForNoisyPads) {
int32_t nBlocks = TPC_PADS_IN_SECTOR / GPUTPCCFCheckPadBaseline::PadsPerCacheline;
runKernel<GPUTPCCFCheckPadBaseline>({GetGridBlk(nBlocks, lane), {iSector}});
}
runKernel<GPUTPCCFPeakFinder>({GetGrid(clusterer.mPmemory->counters.nPositions, lane), {iSector}});
if (DoDebugAndDump(RecoStep::TPCClusterFinding, GPUChainTrackingDebugFlags::TPCClustererPeaks, clusterer, &GPUTPCClusterFinder::DumpPeaks, *mDebugFile)) {
clusterer.DumpPeakMap(*mDebugFile, "Peaks");
}
RunTPCClusterizer_compactPeaks(clusterer, clustererShadow, 0, doGPU, lane);
TransferMemoryResourceLinkToHost(RecoStep::TPCClusterFinding, clusterer.mMemoryId, lane);
DoDebugAndDump(RecoStep::TPCClusterFinding, GPUChainTrackingDebugFlags::TPCClustererPeaks, clusterer, &GPUTPCClusterFinder::DumpPeaksCompacted, *mDebugFile); // clang-format off
});
mRec->runParallelOuterLoop(doGPU, maxLane, [&](uint32_t lane) {
uint32_t iSector = iSectorBase + lane;
GPUTPCClusterFinder& clusterer = processors()->tpcClusterer[iSector];
GPUTPCClusterFinder& clustererShadow = doGPU ? processorsShadow()->tpcClusterer[iSector] : clusterer;
if (doGPU) {
SynchronizeStream(lane);
}
if (clusterer.mPmemory->counters.nPeaks == 0) {
return;
}
runKernel<GPUTPCCFNoiseSuppression, GPUTPCCFNoiseSuppression::noiseSuppression>({GetGrid(clusterer.mPmemory->counters.nPeaks, lane), {iSector}});
runKernel<GPUTPCCFNoiseSuppression, GPUTPCCFNoiseSuppression::updatePeaks>({GetGrid(clusterer.mPmemory->counters.nPeaks, lane), {iSector}});
if (DoDebugAndDump(RecoStep::TPCClusterFinding, GPUChainTrackingDebugFlags::TPCClustererSuppressedPeaks, clusterer, &GPUTPCClusterFinder::DumpSuppressedPeaks, *mDebugFile)) {
clusterer.DumpPeakMap(*mDebugFile, "Suppressed Peaks");
}
RunTPCClusterizer_compactPeaks(clusterer, clustererShadow, 1, doGPU, lane);
TransferMemoryResourceLinkToHost(RecoStep::TPCClusterFinding, clusterer.mMemoryId, lane);
DoDebugAndDump(RecoStep::TPCClusterFinding, GPUChainTrackingDebugFlags::TPCClustererSuppressedPeaks, clusterer, &GPUTPCClusterFinder::DumpSuppressedPeaksCompacted, *mDebugFile); // clang-format off
});
mRec->runParallelOuterLoop(doGPU, maxLane, [&](uint32_t lane) {
uint32_t iSector = iSectorBase + lane;
GPUTPCClusterFinder& clusterer = processors()->tpcClusterer[iSector];
GPUTPCClusterFinder& clustererShadow = doGPU ? processorsShadow()->tpcClusterer[iSector] : clusterer;
if (doGPU) {
SynchronizeStream(lane);
}
if (fragment.index == 0) {
deviceEvent* waitEvent = nullptr;
if (transferRunning[lane] == 1) {
waitEvent = &mEvents->stream[lane];