-
Notifications
You must be signed in to change notification settings - Fork 494
Expand file tree
/
Copy pathGPUWorkflowSpec.cxx
More file actions
1325 lines (1220 loc) · 63.3 KB
/
GPUWorkflowSpec.cxx
File metadata and controls
1325 lines (1220 loc) · 63.3 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 GPUWorkflowSpec.cxx
/// @author Matthias Richter, David Rohr
/// @since 2018-04-18
/// @brief Processor spec for running TPC CA tracking
#include "GPUWorkflow/GPUWorkflowSpec.h"
#include "Headers/DataHeader.h"
#include "Framework/WorkflowSpec.h" // o2::framework::mergeInputs
#include "Framework/DataRefUtils.h"
#include "Framework/DataSpecUtils.h"
#include "Framework/DeviceSpec.h"
#include "Framework/ControlService.h"
#include "Framework/ConfigParamRegistry.h"
#include "Framework/InputRecordWalker.h"
#include "Framework/SerializationMethods.h"
#include "Framework/Logger.h"
#include "Framework/CallbackService.h"
#include "Framework/CCDBParamSpec.h"
#include "Framework/RawDeviceService.h"
#include "DataFormatsTPC/TPCSectorHeader.h"
#include "DataFormatsTPC/ClusterNative.h"
#include "DataFormatsTPC/CompressedClusters.h"
#include "DataFormatsTPC/Helpers.h"
#include "DataFormatsTPC/ZeroSuppression.h"
#include "DataFormatsTPC/RawDataTypes.h"
#include "DataFormatsTPC/WorkflowHelper.h"
#include "DataFormatsGlobalTracking/TrackTuneParams.h"
#include "TPCReconstruction/TPCTrackingDigitsPreCheck.h"
#include "TPCReconstruction/TPCFastTransformHelperO2.h"
#include "DataFormatsTPC/Digit.h"
#include "TPCFastTransform.h"
#include "DPLUtils/DPLRawParser.h"
#include "DPLUtils/DPLRawPageSequencer.h"
#include "DetectorsBase/MatLayerCylSet.h"
#include "DetectorsBase/Propagator.h"
#include "DetectorsBase/GeometryManager.h"
#include "DetectorsRaw/HBFUtils.h"
#include "DetectorsBase/GRPGeomHelper.h"
#include "CommonUtils/NameConf.h"
#include "TPCBase/RDHUtils.h"
#include "GPUO2InterfaceConfiguration.h"
#include "GPUO2InterfaceQA.h"
#include "GPUO2Interface.h"
#include "GPUO2InterfaceUtils.h"
#include "CalibdEdxContainer.h"
#include "GPUNewCalibValues.h"
#include "TPCPadGainCalib.h"
#include "TPCZSLinkMapping.h"
#include "display/GPUDisplayInterface.h"
#include "TPCBase/Sector.h"
#include "TPCBase/Utils.h"
#include "TPCBase/CDBInterface.h"
#include "TPCCalibration/VDriftHelper.h"
#include "CorrectionMapsHelper.h"
#include "TPCCalibration/CorrectionMapsLoader.h"
#include "TPCBase/DeadChannelMapCreator.h"
#include "SimulationDataFormat/ConstMCTruthContainer.h"
#include "SimulationDataFormat/MCCompLabel.h"
#include "Algorithm/Parser.h"
#include "DataFormatsGlobalTracking/RecoContainer.h"
#include "DataFormatsTRD/RecoInputContainer.h"
#include "TRDBase/Geometry.h"
#include "TRDBase/GeometryFlat.h"
#include "ITSBase/GeometryTGeo.h"
#include "CommonUtils/DebugStreamer.h"
#include "GPUReconstructionConvert.h"
#include "DetectorsRaw/RDHUtils.h"
#include "ITStracking/TrackingInterface.h"
#include "GPUWorkflowInternal.h"
#include "TPCCalibration/NeuralNetworkClusterizer.h"
// #include "Framework/ThreadPool.h"
#include <TStopwatch.h>
#include <TObjArray.h>
#include <TH1F.h>
#include <TH2F.h>
#include <TH1D.h>
#include <TGraphAsymmErrors.h>
#include <filesystem>
#include <memory>
#include <vector>
#include <iomanip>
#include <stdexcept>
#include <regex>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <chrono>
#include <unordered_set>
using namespace o2::framework;
using namespace o2::header;
using namespace o2::gpu;
using namespace o2::base;
using namespace o2::dataformats;
using namespace o2::gpu::gpurecoworkflow_internals;
namespace o2::gpu
{
GPURecoWorkflowSpec::GPURecoWorkflowSpec(GPURecoWorkflowSpec::CompletionPolicyData* policyData, Config const& specconfig, std::vector<int32_t> const& tpcsectors, uint64_t tpcSectorMask, std::shared_ptr<o2::base::GRPGeomRequest>& ggr, std::function<bool(o2::framework::DataProcessingHeader::StartTime)>** gPolicyOrder) : o2::framework::Task(), mPolicyData(policyData), mTPCSectorMask(tpcSectorMask), mTPCSectors(tpcsectors), mSpecConfig(specconfig), mGGR(ggr)
{
if (mSpecConfig.outputCAClusters && !mSpecConfig.caClusterer && !mSpecConfig.decompressTPC) {
throw std::runtime_error("inconsistent configuration: cluster output is only possible if CA clusterer is activated");
}
mConfig.reset(new GPUO2InterfaceConfiguration);
mConfParam.reset(new GPUSettingsO2);
mTFSettings.reset(new GPUSettingsTF);
mTimer.reset(new TStopwatch);
mPipeline.reset(new GPURecoWorkflowSpec_PipelineInternals);
if (mSpecConfig.enableDoublePipeline == 1 && gPolicyOrder) {
*gPolicyOrder = &mPolicyOrder;
}
}
GPURecoWorkflowSpec::~GPURecoWorkflowSpec() = default;
void GPURecoWorkflowSpec::init(InitContext& ic)
{
GRPGeomHelper::instance().setRequest(mGGR);
GPUO2InterfaceConfiguration& config = *mConfig.get();
GPUSettingsProcessingNNclusterizer& mNNClusterizerSettings = mConfig->configProcessing.nn;
if (mNNClusterizerSettings.nnLoadFromCCDB) {
LOG(info) << "Loading neural networks from CCDB";
o2::tpc::NeuralNetworkClusterizer nnClusterizerFetcher;
nnClusterizerFetcher.initCcdbApi(mNNClusterizerSettings.nnCCDBURL);
std::map<std::string, std::string> ccdbSettings = {
{"nnCCDBURL", mNNClusterizerSettings.nnCCDBURL},
{"nnCCDBPath", mNNClusterizerSettings.nnCCDBPath},
{"inputDType", mNNClusterizerSettings.nnInferenceInputDType},
{"outputDType", mNNClusterizerSettings.nnInferenceOutputDType},
{"outputFolder", mNNClusterizerSettings.nnLocalFolder},
{"nnCCDBPath", mNNClusterizerSettings.nnCCDBPath},
{"nnCCDBWithMomentum", std::to_string(mNNClusterizerSettings.nnCCDBWithMomentum)},
{"nnCCDBBeamType", mNNClusterizerSettings.nnCCDBBeamType},
{"nnCCDBInteractionRate", std::to_string(mNNClusterizerSettings.nnCCDBInteractionRate)}};
std::string nnFetchFolder = mNNClusterizerSettings.nnLocalFolder;
std::vector<std::string> evalMode = o2::utils::Str::tokenize(mNNClusterizerSettings.nnEvalMode, ':');
if (evalMode[0] == "c1") {
ccdbSettings["nnCCDBLayerType"] = mNNClusterizerSettings.nnCCDBClassificationLayerType;
ccdbSettings["nnCCDBEvalType"] = "classification_c1";
ccdbSettings["outputFile"] = "net_classification_c1.onnx";
nnClusterizerFetcher.loadIndividualFromCCDB(ccdbSettings);
} else if (evalMode[0] == "c2") {
ccdbSettings["nnCCDBLayerType"] = mNNClusterizerSettings.nnCCDBClassificationLayerType;
ccdbSettings["nnCCDBEvalType"] = "classification_c2";
ccdbSettings["outputFile"] = "net_classification_c2.onnx";
nnClusterizerFetcher.loadIndividualFromCCDB(ccdbSettings);
}
ccdbSettings["nnCCDBLayerType"] = mNNClusterizerSettings.nnCCDBRegressionLayerType;
ccdbSettings["nnCCDBEvalType"] = "regression_c1";
ccdbSettings["outputFile"] = "net_regression_c1.onnx";
nnClusterizerFetcher.loadIndividualFromCCDB(ccdbSettings);
if (evalMode[1] == "r2") {
ccdbSettings["nnCCDBLayerType"] = mNNClusterizerSettings.nnCCDBRegressionLayerType;
ccdbSettings["nnCCDBEvalType"] = "regression_c2";
ccdbSettings["outputFile"] = "net_regression_c2.onnx";
nnClusterizerFetcher.loadIndividualFromCCDB(ccdbSettings);
}
LOG(info) << "Neural network loading done!";
}
// Create configuration object and fill settings
mConfig->configGRP.solenoidBzNominalGPU = 0;
mTFSettings->hasSimStartOrbit = 1;
auto& hbfu = o2::raw::HBFUtils::Instance();
mTFSettings->simStartOrbit = hbfu.getFirstIRofTF(o2::InteractionRecord(0, hbfu.orbitFirstSampled)).orbit;
*mConfParam = mConfig->ReadConfigurableParam();
if (mConfParam->display) {
mDisplayFrontend.reset(GPUDisplayFrontendInterface::getFrontend(mConfig->configDisplay.displayFrontend.c_str()));
mConfig->configProcessing.eventDisplay = mDisplayFrontend.get();
if (mConfig->configProcessing.eventDisplay != nullptr) {
LOG(info) << "Event display enabled";
} else {
throw std::runtime_error("GPU Event Display frontend could not be created!");
}
}
if (mSpecConfig.enableDoublePipeline) {
mConfig->configProcessing.doublePipeline = 1;
}
mAutoSolenoidBz = mConfParam->solenoidBzNominalGPU == -1e6f;
mAutoContinuousMaxTimeBin = mConfig->configGRP.grpContinuousMaxTimeBin < 0;
if (mAutoContinuousMaxTimeBin) {
mConfig->configGRP.grpContinuousMaxTimeBin = GPUO2InterfaceUtils::getTpcMaxTimeBinFromNHbf(mConfParam->overrideNHbfPerTF ? mConfParam->overrideNHbfPerTF : 256);
}
if (mConfig->configProcessing.deviceNum == -2) {
int32_t myId = ic.services().get<const o2::framework::DeviceSpec>().inputTimesliceId;
int32_t idMax = ic.services().get<const o2::framework::DeviceSpec>().maxInputTimeslices;
mConfig->configProcessing.deviceNum = myId;
LOG(info) << "GPU device number selected from pipeline id: " << myId << " / " << idMax;
}
if (mConfig->configProcessing.debugLevel >= 3 && mVerbosity == 0) {
mVerbosity = 1;
}
mConfig->configProcessing.runMC = mSpecConfig.processMC;
if (mSpecConfig.outputQA) {
if (!mSpecConfig.processMC && !mConfig->configQA.clusterRejectionHistograms) {
throw std::runtime_error("Need MC information to create QA plots");
}
if (!mSpecConfig.processMC) {
mConfig->configQA.noMC = true;
}
mConfig->configQA.shipToQC = true;
if (!mConfig->configProcessing.runQA) {
mConfig->configQA.enableLocalOutput = false;
mQATaskMask = (mSpecConfig.processMC ? 15 : 0) | (mConfig->configQA.clusterRejectionHistograms ? 32 : 0);
mConfig->configProcessing.runQA = -mQATaskMask;
}
}
mConfig->configReconstruction.tpc.nWaysOuter = true;
mConfig->configInterface.outputToExternalBuffers = true;
if (mConfParam->synchronousProcessing) {
mConfig->configReconstruction.useMatLUT = false;
}
if (mConfig->configProcessing.rtc.optSpecialCode == -1) {
mConfig->configProcessing.rtc.optSpecialCode = mConfParam->synchronousProcessing;
}
// Configure the "GPU workflow" i.e. which steps we run on the GPU (or CPU)
if (mSpecConfig.outputTracks || mSpecConfig.outputCompClusters || mSpecConfig.outputCompClustersFlat) {
mConfig->configWorkflow.steps.set(GPUDataTypes::RecoStep::TPCConversion,
GPUDataTypes::RecoStep::TPCSectorTracking,
GPUDataTypes::RecoStep::TPCMerging);
mConfig->configWorkflow.outputs.set(GPUDataTypes::InOutType::TPCMergedTracks);
mConfig->configWorkflow.steps.setBits(GPUDataTypes::RecoStep::TPCdEdx, mConfParam->rundEdx == -1 ? !mConfParam->synchronousProcessing : mConfParam->rundEdx);
}
if (mSpecConfig.outputCompClusters || mSpecConfig.outputCompClustersFlat) {
mConfig->configWorkflow.steps.setBits(GPUDataTypes::RecoStep::TPCCompression, true);
mConfig->configWorkflow.outputs.setBits(GPUDataTypes::InOutType::TPCCompressedClusters, true);
}
mConfig->configWorkflow.inputs.set(GPUDataTypes::InOutType::TPCClusters);
if (mSpecConfig.caClusterer) { // Override some settings if we have raw data as input
mConfig->configWorkflow.inputs.set(GPUDataTypes::InOutType::TPCRaw);
mConfig->configWorkflow.steps.setBits(GPUDataTypes::RecoStep::TPCClusterFinding, true);
mConfig->configWorkflow.outputs.setBits(GPUDataTypes::InOutType::TPCClusters, true);
}
if (mSpecConfig.decompressTPC) {
mConfig->configWorkflow.steps.setBits(GPUDataTypes::RecoStep::TPCCompression, false);
mConfig->configWorkflow.steps.setBits(GPUDataTypes::RecoStep::TPCDecompression, true);
mConfig->configWorkflow.inputs.set(GPUDataTypes::InOutType::TPCCompressedClusters);
mConfig->configWorkflow.outputs.setBits(GPUDataTypes::InOutType::TPCClusters, true);
mConfig->configWorkflow.outputs.setBits(GPUDataTypes::InOutType::TPCCompressedClusters, false);
if (mTPCSectorMask != 0xFFFFFFFFF) {
throw std::invalid_argument("Cannot run TPC decompression with a sector mask");
}
}
if (mSpecConfig.runTRDTracking) {
mConfig->configWorkflow.inputs.setBits(GPUDataTypes::InOutType::TRDTracklets, true);
mConfig->configWorkflow.steps.setBits(GPUDataTypes::RecoStep::TRDTracking, true);
}
if (mSpecConfig.runITSTracking) {
mConfig->configWorkflow.inputs.setBits(GPUDataTypes::InOutType::ITSClusters, true);
mConfig->configWorkflow.outputs.setBits(GPUDataTypes::InOutType::ITSTracks, true);
mConfig->configWorkflow.steps.setBits(GPUDataTypes::RecoStep::ITSTracking, true);
}
if (mSpecConfig.outputSharedClusterMap) {
mConfig->configProcessing.outputSharedClusterMap = true;
}
if (!mSpecConfig.outputTracks) {
mConfig->configProcessing.createO2Output = 0; // Disable O2 TPC track format output if no track output requested
}
mConfig->configProcessing.param.tpcTriggerHandling = mSpecConfig.tpcTriggerHandling;
if (mConfParam->transformationFile.size() || mConfParam->transformationSCFile.size()) {
LOG(fatal) << "Deprecated configurable param options GPU_global.transformationFile or transformationSCFile used\n"
<< "Instead, link the corresponding file as <somedir>/TPC/Calib/CorrectionMap/snapshot.root and use it via\n"
<< "--condition-remap file://<somdir>=TPC/Calib/CorrectionMap option";
}
/* if (config.configProcessing.doublePipeline && ic.services().get<ThreadPool>().poolSize != 2) {
throw std::runtime_error("double pipeline requires exactly 2 threads");
} */
if (config.configProcessing.doublePipeline && (mSpecConfig.readTRDtracklets || mSpecConfig.runITSTracking || !(mSpecConfig.zsOnTheFly || mSpecConfig.zsDecoder))) {
LOG(fatal) << "GPU two-threaded pipeline works only with TPC-only processing, and with ZS input";
}
if (mSpecConfig.enableDoublePipeline != 2) {
mGPUReco = std::make_unique<GPUO2Interface>();
// initialize TPC calib objects
initFunctionTPCCalib(ic);
mConfig->configCalib.fastTransform = mCalibObjects.mFastTransformHelper->getCorrMap();
mConfig->configCalib.fastTransformRef = mCalibObjects.mFastTransformHelper->getCorrMapRef();
mConfig->configCalib.fastTransformMShape = mCalibObjects.mFastTransformHelper->getCorrMapMShape();
mConfig->configCalib.fastTransformHelper = mCalibObjects.mFastTransformHelper.get();
if (mConfig->configCalib.fastTransform == nullptr) {
throw std::invalid_argument("GPU workflow: initialization of the TPC transformation failed");
}
if (mConfParam->matLUTFile.size()) {
LOGP(info, "Loading matlut file {}", mConfParam->matLUTFile.c_str());
mConfig->configCalib.matLUT = o2::base::MatLayerCylSet::loadFromFile(mConfParam->matLUTFile.c_str());
if (mConfig->configCalib.matLUT == nullptr) {
LOGF(fatal, "Error loading matlut file");
}
} else {
mConfig->configProcessing.lateO2MatLutProvisioningSize = 50 * 1024 * 1024;
}
if (mSpecConfig.readTRDtracklets) {
mTRDGeometry = std::make_unique<o2::trd::GeometryFlat>();
mConfig->configCalib.trdGeometry = mTRDGeometry.get();
}
mConfig->configProcessing.willProvideO2PropagatorLate = true;
mConfig->configProcessing.o2PropagatorUseGPUField = true;
if (mConfParam->printSettings && (mConfParam->printSettings > 1 || ic.services().get<const o2::framework::DeviceSpec>().inputTimesliceId == 0)) {
mConfig->configProcessing.printSettings = true;
if (mConfParam->printSettings > 1) {
mConfig->PrintParam();
}
}
// Configuration is prepared, initialize the tracker.
if (mGPUReco->Initialize(config) != 0) {
throw std::invalid_argument("GPU Reconstruction initialization failed");
}
if (mSpecConfig.outputQA) {
mQA = std::make_unique<GPUO2InterfaceQA>(mConfig.get());
}
if (mSpecConfig.outputErrorQA) {
mGPUReco->setErrorCodeOutput(&mErrorQA);
}
// initialize ITS
if (mSpecConfig.runITSTracking) {
initFunctionITS(ic);
}
}
if (mSpecConfig.enableDoublePipeline) {
initPipeline(ic);
if (mConfParam->dump >= 2) {
LOG(fatal) << "Cannot use dump-only mode with multi-threaded pipeline";
}
}
auto& callbacks = ic.services().get<CallbackService>();
callbacks.set<CallbackService::Id::RegionInfoCallback>([this](fair::mq::RegionInfo const& info) {
if (info.size == 0) {
return;
}
if (mSpecConfig.enableDoublePipeline) {
mRegionInfos.emplace_back(info);
}
if (mSpecConfig.enableDoublePipeline == 2) {
return;
}
if (mConfParam->registerSelectedSegmentIds != -1 && info.managed && info.id != (uint32_t)mConfParam->registerSelectedSegmentIds) {
return;
}
int32_t fd = 0;
if (mConfParam->mutexMemReg) {
mode_t mask = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH;
fd = open("/tmp/o2_gpu_memlock_mutex.lock", O_RDWR | O_CREAT | O_CLOEXEC, mask);
if (fd == -1) {
throw std::runtime_error("Error opening memlock mutex lock file");
}
fchmod(fd, mask);
if (lockf(fd, F_LOCK, 0)) {
throw std::runtime_error("Error locking memlock mutex file");
}
}
std::chrono::time_point<std::chrono::high_resolution_clock> start, end;
if (mConfParam->benchmarkMemoryRegistration) {
start = std::chrono::high_resolution_clock::now();
}
if (mGPUReco->registerMemoryForGPU(info.ptr, info.size)) {
throw std::runtime_error("Error registering memory for GPU");
}
if (mConfParam->benchmarkMemoryRegistration) {
end = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> elapsed_seconds = end - start;
LOG(info) << "Memory registration time (0x" << info.ptr << ", " << info.size << " bytes): " << elapsed_seconds.count() << " s";
}
if (mConfParam->mutexMemReg) {
if (lockf(fd, F_ULOCK, 0)) {
throw std::runtime_error("Error unlocking memlock mutex file");
}
close(fd);
}
});
mTimer->Stop();
mTimer->Reset();
}
void GPURecoWorkflowSpec::stop()
{
LOGF(info, "GPU Reconstruction total timing: Cpu: %.3e Real: %.3e s in %d slots", mTimer->CpuTime(), mTimer->RealTime(), mTimer->Counter() - 1);
handlePipelineStop();
}
void GPURecoWorkflowSpec::endOfStream(EndOfStreamContext& ec)
{
handlePipelineEndOfStream(ec);
}
void GPURecoWorkflowSpec::finaliseCCDB(o2::framework::ConcreteDataMatcher& matcher, void* obj)
{
if (mSpecConfig.enableDoublePipeline != 2) {
finaliseCCDBTPC(matcher, obj);
if (mSpecConfig.runITSTracking) {
finaliseCCDBITS(matcher, obj);
}
}
if (GRPGeomHelper::instance().finaliseCCDB(matcher, obj)) {
mGRPGeomUpdated = true;
return;
}
}
template <class D, class E, class F, class G, class H, class I, class J, class K>
void GPURecoWorkflowSpec::processInputs(ProcessingContext& pc, D& tpcZSmeta, E& inputZS, F& tpcZS, G& tpcZSonTheFlySizes, bool& debugTFDump, H& compClustersDummy, I& compClustersFlatDummy, J& pCompClustersFlat, K& tmpEmptyCompClusters)
{
if (mSpecConfig.enableDoublePipeline == 1) {
return;
}
constexpr static size_t NSectors = o2::tpc::Sector::MAXSECTOR;
constexpr static size_t NEndpoints = o2::gpu::GPUTrackingInOutZS::NENDPOINTS;
if (mSpecConfig.zsOnTheFly || mSpecConfig.zsDecoder) {
for (uint32_t i = 0; i < GPUTrackingInOutZS::NSECTORS; i++) {
for (uint32_t j = 0; j < GPUTrackingInOutZS::NENDPOINTS; j++) {
tpcZSmeta.Pointers[i][j].clear();
tpcZSmeta.Sizes[i][j].clear();
}
}
}
if (mSpecConfig.zsOnTheFly) {
tpcZSonTheFlySizes = {0};
// tpcZSonTheFlySizes: #zs pages per endpoint:
std::vector<InputSpec> filter = {{"check", ConcreteDataTypeMatcher{gDataOriginTPC, "ZSSIZES"}, Lifetime::Timeframe}};
bool recv = false, recvsizes = false;
for (auto const& ref : InputRecordWalker(pc.inputs(), filter)) {
if (recvsizes) {
throw std::runtime_error("Received multiple ZSSIZES data");
}
tpcZSonTheFlySizes = pc.inputs().get<std::array<uint32_t, NEndpoints * NSectors>>(ref);
recvsizes = true;
}
// zs pages
std::vector<InputSpec> filter2 = {{"check", ConcreteDataTypeMatcher{gDataOriginTPC, "TPCZS"}, Lifetime::Timeframe}};
for (auto const& ref : InputRecordWalker(pc.inputs(), filter2)) {
if (recv) {
throw std::runtime_error("Received multiple TPCZS data");
}
inputZS = pc.inputs().get<gsl::span<o2::tpc::ZeroSuppressedContainer8kb>>(ref);
recv = true;
}
if (!recv || !recvsizes) {
throw std::runtime_error("TPC ZS on the fly data not received");
}
uint32_t offset = 0;
for (uint32_t i = 0; i < NSectors; i++) {
uint32_t pageSector = 0;
for (uint32_t j = 0; j < NEndpoints; j++) {
pageSector += tpcZSonTheFlySizes[i * NEndpoints + j];
offset += tpcZSonTheFlySizes[i * NEndpoints + j];
}
if (mVerbosity >= 1) {
LOG(info) << "GOT ZS on the fly pages FOR SECTOR " << i << " -> pages: " << pageSector;
}
}
}
if (mSpecConfig.zsDecoder) {
std::vector<InputSpec> filter = {{"check", ConcreteDataTypeMatcher{gDataOriginTPC, "RAWDATA"}, Lifetime::Timeframe}};
auto isSameRdh = [](const char* left, const char* right) -> bool {
return o2::raw::RDHUtils::getFEEID(left) == o2::raw::RDHUtils::getFEEID(right) && o2::raw::RDHUtils::getDetectorField(left) == o2::raw::RDHUtils::getDetectorField(right);
};
auto checkForZSData = [](const char* ptr, uint32_t subSpec) -> bool {
const auto rdhLink = o2::raw::RDHUtils::getLinkID(ptr);
const auto detField = o2::raw::RDHUtils::getDetectorField(ptr);
const auto feeID = o2::raw::RDHUtils::getFEEID(ptr);
const auto feeLinkID = o2::tpc::rdh_utils::getLink(feeID);
// This check is not what it is supposed to be, but some MC SYNTHETIC data was generated with rdhLinkId set to feeLinkId, so we add some extra logic so we can still decode it
return detField == o2::tpc::raw_data_types::ZS && ((feeLinkID == o2::tpc::rdh_utils::UserLogicLinkID && (rdhLink == o2::tpc::rdh_utils::UserLogicLinkID || rdhLink == 0)) ||
(feeLinkID == o2::tpc::rdh_utils::ILBZSLinkID && (rdhLink == o2::tpc::rdh_utils::UserLogicLinkID || rdhLink == o2::tpc::rdh_utils::ILBZSLinkID || rdhLink == 0)) ||
(feeLinkID == o2::tpc::rdh_utils::DLBZSLinkID && (rdhLink == o2::tpc::rdh_utils::UserLogicLinkID || rdhLink == o2::tpc::rdh_utils::DLBZSLinkID || rdhLink == 0)));
};
auto insertPages = [&tpcZSmeta, checkForZSData](const char* ptr, size_t count, uint32_t subSpec) -> void {
if (checkForZSData(ptr, subSpec)) {
int32_t rawcru = o2::tpc::rdh_utils::getCRU(ptr);
int32_t rawendpoint = o2::tpc::rdh_utils::getEndPoint(ptr);
tpcZSmeta.Pointers[rawcru / 10][(rawcru % 10) * 2 + rawendpoint].emplace_back(ptr);
tpcZSmeta.Sizes[rawcru / 10][(rawcru % 10) * 2 + rawendpoint].emplace_back(count);
}
};
if (DPLRawPageSequencer(pc.inputs(), filter)(isSameRdh, insertPages, checkForZSData)) {
debugTFDump = true;
static uint32_t nErrors = 0;
nErrors++;
if (nErrors == 1 || (nErrors < 100 && nErrors % 10 == 0) || nErrors % 1000 == 0 || mNTFs % 1000 == 0) {
LOG(error) << "DPLRawPageSequencer failed to process TPC raw data - data most likely not padded correctly - Using slow page scan instead (this alarm is downscaled from now on, so far " << nErrors << " of " << mNTFs << " TFs affected)";
}
}
int32_t totalCount = 0;
for (uint32_t i = 0; i < GPUTrackingInOutZS::NSECTORS; i++) {
for (uint32_t j = 0; j < GPUTrackingInOutZS::NENDPOINTS; j++) {
tpcZSmeta.Pointers2[i][j] = tpcZSmeta.Pointers[i][j].data();
tpcZSmeta.Sizes2[i][j] = tpcZSmeta.Sizes[i][j].data();
tpcZS.sector[i].zsPtr[j] = tpcZSmeta.Pointers2[i][j];
tpcZS.sector[i].nZSPtr[j] = tpcZSmeta.Sizes2[i][j];
tpcZS.sector[i].count[j] = tpcZSmeta.Pointers[i][j].size();
totalCount += tpcZSmeta.Pointers[i][j].size();
}
}
} else if (mSpecConfig.decompressTPC) {
if (mSpecConfig.decompressTPCFromROOT) {
compClustersDummy = *pc.inputs().get<o2::tpc::CompressedClustersROOT*>("input");
compClustersFlatDummy.setForward(&compClustersDummy);
pCompClustersFlat = &compClustersFlatDummy;
} else {
pCompClustersFlat = pc.inputs().get<o2::tpc::CompressedClustersFlat*>("input").get();
}
if (pCompClustersFlat == nullptr) {
tmpEmptyCompClusters.reset(new char[sizeof(o2::tpc::CompressedClustersFlat)]);
memset(tmpEmptyCompClusters.get(), 0, sizeof(o2::tpc::CompressedClustersFlat));
pCompClustersFlat = (o2::tpc::CompressedClustersFlat*)tmpEmptyCompClusters.get();
}
} else if (!mSpecConfig.zsOnTheFly) {
if (mVerbosity) {
LOGF(info, "running tracking for sector(s) 0x%09x", mTPCSectorMask);
}
}
}
int32_t GPURecoWorkflowSpec::runMain(o2::framework::ProcessingContext* pc, GPUTrackingInOutPointers* ptrs, GPUInterfaceOutputs* outputRegions, int32_t threadIndex, GPUInterfaceInputUpdate* inputUpdateCallback)
{
int32_t retVal = 0;
if (mConfParam->dump < 2) {
retVal = mGPUReco->RunTracking(ptrs, outputRegions, threadIndex, inputUpdateCallback);
if (retVal == 0 && mSpecConfig.runITSTracking) {
retVal = runITSTracking(*pc);
}
}
if (!mSpecConfig.enableDoublePipeline) { // TODO: Why is this needed for double-pipeline?
mGPUReco->Clear(false, threadIndex); // clean non-output memory used by GPU Reconstruction
}
return retVal;
}
void GPURecoWorkflowSpec::cleanOldCalibsTPCPtrs(calibObjectStruct& oldCalibObjects)
{
if (mOldCalibObjects.size() > 0) {
mOldCalibObjects.pop();
}
mOldCalibObjects.emplace(std::move(oldCalibObjects));
}
void GPURecoWorkflowSpec::run(ProcessingContext& pc)
{
constexpr static size_t NSectors = o2::tpc::Sector::MAXSECTOR;
constexpr static size_t NEndpoints = o2::gpu::GPUTrackingInOutZS::NENDPOINTS;
auto cput = mTimer->CpuTime();
auto realt = mTimer->RealTime();
mTimer->Start(false);
mNTFs++;
std::vector<gsl::span<const char>> inputs;
const o2::tpc::CompressedClustersFlat* pCompClustersFlat = nullptr;
size_t compClustersFlatDummyMemory[(sizeof(o2::tpc::CompressedClustersFlat) + sizeof(size_t) - 1) / sizeof(size_t)];
o2::tpc::CompressedClustersFlat& compClustersFlatDummy = reinterpret_cast<o2::tpc::CompressedClustersFlat&>(compClustersFlatDummyMemory);
o2::tpc::CompressedClusters compClustersDummy;
o2::gpu::GPUTrackingInOutZS tpcZS;
GPURecoWorkflowSpec_TPCZSBuffers tpcZSmeta;
std::array<uint32_t, NEndpoints * NSectors> tpcZSonTheFlySizes;
gsl::span<const o2::tpc::ZeroSuppressedContainer8kb> inputZS;
std::unique_ptr<char[]> tmpEmptyCompClusters;
bool getWorkflowTPCInput_clusters = false, getWorkflowTPCInput_mc = false, getWorkflowTPCInput_digits = false;
bool debugTFDump = false;
if (mSpecConfig.processMC) {
getWorkflowTPCInput_mc = true;
}
if (!mSpecConfig.decompressTPC && !mSpecConfig.caClusterer) {
getWorkflowTPCInput_clusters = true;
}
if (!mSpecConfig.decompressTPC && mSpecConfig.caClusterer && ((!mSpecConfig.zsOnTheFly || mSpecConfig.processMC) && !mSpecConfig.zsDecoder)) {
getWorkflowTPCInput_digits = true;
}
// ------------------------------ Handle inputs ------------------------------
auto lockDecodeInput = std::make_unique<std::lock_guard<std::mutex>>(mPipeline->mutexDecodeInput);
GRPGeomHelper::instance().checkUpdates(pc);
if (pc.inputs().getPos("itsTGeo") >= 0) {
pc.inputs().get<o2::its::GeometryTGeo*>("itsTGeo");
}
if (GRPGeomHelper::instance().getGRPECS()->isDetReadOut(o2::detectors::DetID::TPC) && mConfParam->tpcTriggeredMode ^ !GRPGeomHelper::instance().getGRPECS()->isDetContinuousReadOut(o2::detectors::DetID::TPC)) {
LOG(fatal) << "configKeyValue tpcTriggeredMode does not match GRP isDetContinuousReadOut(TPC) setting";
}
GPUTrackingInOutPointers ptrs;
processInputs(pc, tpcZSmeta, inputZS, tpcZS, tpcZSonTheFlySizes, debugTFDump, compClustersDummy, compClustersFlatDummy, pCompClustersFlat, tmpEmptyCompClusters); // Process non-digit / non-cluster inputs
const auto& inputsClustersDigits = o2::tpc::getWorkflowTPCInput(pc, mVerbosity, getWorkflowTPCInput_mc, getWorkflowTPCInput_clusters, mTPCSectorMask, getWorkflowTPCInput_digits); // Process digit and cluster inputs
const auto& tinfo = pc.services().get<o2::framework::TimingInfo>();
mTFSettings->tfStartOrbit = tinfo.firstTForbit;
mTFSettings->hasTfStartOrbit = 1;
mTFSettings->hasNHBFPerTF = 1;
mTFSettings->nHBFPerTF = mConfParam->overrideNHbfPerTF ? mConfParam->overrideNHbfPerTF : GRPGeomHelper::instance().getGRPECS()->getNHBFPerTF();
mTFSettings->hasRunStartOrbit = 0;
if (mVerbosity) {
LOG(info) << "TF firstTForbit " << mTFSettings->tfStartOrbit << " nHBF " << mTFSettings->nHBFPerTF << " runStartOrbit " << mTFSettings->runStartOrbit << " simStartOrbit " << mTFSettings->simStartOrbit;
}
ptrs.settingsTF = mTFSettings.get();
if (mConfParam->checkFirstTfOrbit) {
static uint32_t lastFirstTFOrbit = -1;
static uint32_t lastTFCounter = -1;
if (lastFirstTFOrbit != -1 && lastTFCounter != -1) {
int32_t diffOrbit = tinfo.firstTForbit - lastFirstTFOrbit;
int32_t diffCounter = tinfo.tfCounter - lastTFCounter;
if (diffOrbit != diffCounter * mTFSettings->nHBFPerTF) {
LOG(error) << "Time frame has mismatching firstTfOrbit - Last orbit/counter: " << lastFirstTFOrbit << " " << lastTFCounter << " - Current: " << tinfo.firstTForbit << " " << tinfo.tfCounter;
}
}
lastFirstTFOrbit = tinfo.firstTForbit;
lastTFCounter = tinfo.tfCounter;
}
o2::globaltracking::RecoContainer inputTracksTRD;
decltype(o2::trd::getRecoInputContainer(pc, &ptrs, &inputTracksTRD)) trdInputContainer;
if (mSpecConfig.readTRDtracklets) {
o2::globaltracking::DataRequest dataRequestTRD;
dataRequestTRD.requestTracks(o2::dataformats::GlobalTrackID::getSourcesMask(o2::dataformats::GlobalTrackID::NONE), false);
inputTracksTRD.collectData(pc, dataRequestTRD);
trdInputContainer = std::move(o2::trd::getRecoInputContainer(pc, &ptrs, &inputTracksTRD));
}
void* ptrEp[NSectors * NEndpoints] = {};
bool doInputDigits = false, doInputDigitsMC = false;
if (mSpecConfig.decompressTPC) {
ptrs.tpcCompressedClusters = pCompClustersFlat;
} else if (mSpecConfig.zsOnTheFly) {
const uint64_t* buffer = reinterpret_cast<const uint64_t*>(&inputZS[0]);
o2::gpu::GPUReconstructionConvert::RunZSEncoderCreateMeta(buffer, tpcZSonTheFlySizes.data(), *&ptrEp, &tpcZS);
ptrs.tpcZS = &tpcZS;
doInputDigits = doInputDigitsMC = mSpecConfig.processMC;
} else if (mSpecConfig.zsDecoder) {
ptrs.tpcZS = &tpcZS;
if (mSpecConfig.processMC) {
throw std::runtime_error("Cannot process MC information, none available");
}
} else if (mSpecConfig.caClusterer) {
doInputDigits = true;
doInputDigitsMC = mSpecConfig.processMC;
} else {
ptrs.clustersNative = &inputsClustersDigits->clusterIndex;
}
if (mTPCSectorMask != 0xFFFFFFFFF) {
// Clean out the unused sectors, such that if they were present by chance, they are not processed, and if the values are uninitialized, we should not crash
for (uint32_t i = 0; i < NSectors; i++) {
if (!(mTPCSectorMask & (1ul << i))) {
if (ptrs.tpcZS) {
for (uint32_t j = 0; j < GPUTrackingInOutZS::NENDPOINTS; j++) {
tpcZS.sector[i].zsPtr[j] = nullptr;
tpcZS.sector[i].nZSPtr[j] = nullptr;
tpcZS.sector[i].count[j] = 0;
}
}
}
}
}
GPUTrackingInOutDigits tpcDigitsMap;
GPUTPCDigitsMCInput tpcDigitsMapMC;
if (doInputDigits) {
ptrs.tpcPackedDigits = &tpcDigitsMap;
if (doInputDigitsMC) {
tpcDigitsMap.tpcDigitsMC = &tpcDigitsMapMC;
}
for (uint32_t i = 0; i < NSectors; i++) {
tpcDigitsMap.tpcDigits[i] = inputsClustersDigits->inputDigits[i].data();
tpcDigitsMap.nTPCDigits[i] = inputsClustersDigits->inputDigits[i].size();
if (doInputDigitsMC) {
tpcDigitsMapMC.v[i] = inputsClustersDigits->inputDigitsMCPtrs[i];
}
}
}
o2::tpc::TPCSectorHeader clusterOutputSectorHeader{0};
if (mClusterOutputIds.size() > 0) {
clusterOutputSectorHeader.sectorBits = mTPCSectorMask;
// subspecs [0, NSectors - 1] are used to identify sector data, we use NSectors to indicate the full TPC
clusterOutputSectorHeader.activeSectors = mTPCSectorMask;
}
// ------------------------------ Prepare stage for double-pipeline before normal output preparation ------------------------------
std::unique_ptr<GPURecoWorkflow_QueueObject> pipelineContext;
if (mSpecConfig.enableDoublePipeline) {
if (handlePipeline(pc, ptrs, tpcZSmeta, tpcZS, pipelineContext)) {
return;
}
}
// ------------------------------ Prepare outputs ------------------------------
GPUInterfaceOutputs outputRegions;
using outputDataType = char;
using outputBufferUninitializedVector = std::decay_t<decltype(pc.outputs().make<DataAllocator::UninitializedVector<outputDataType>>(Output{"", "", 0}))>;
using outputBufferType = std::pair<std::optional<std::reference_wrapper<outputBufferUninitializedVector>>, outputDataType*>;
std::vector<outputBufferType> outputBuffers(GPUInterfaceOutputs::count(), {std::nullopt, nullptr});
std::unordered_set<std::string> outputsCreated;
auto setOutputAllocator = [this, &outputBuffers, &outputRegions, &pc, &outputsCreated](const char* name, bool condition, GPUOutputControl& region, auto&& outputSpec, size_t offset = 0) {
if (condition) {
auto& buffer = outputBuffers[outputRegions.getIndex(region)];
if (mConfParam->allocateOutputOnTheFly) {
region.allocator = [this, name, &buffer, &pc, outputSpec = std::move(outputSpec), offset, &outputsCreated](size_t size) -> void* {
size += offset;
if (mVerbosity) {
LOG(info) << "ALLOCATING " << size << " bytes for " << name << ": " << std::get<DataOrigin>(outputSpec).template as<std::string>() << "/" << std::get<DataDescription>(outputSpec).template as<std::string>() << "/" << std::get<2>(outputSpec);
}
std::chrono::time_point<std::chrono::high_resolution_clock> start, end;
if (mVerbosity) {
start = std::chrono::high_resolution_clock::now();
}
buffer.first.emplace(pc.outputs().make<DataAllocator::UninitializedVector<outputDataType>>(std::make_from_tuple<Output>(outputSpec), size));
outputsCreated.insert(name);
if (mVerbosity) {
end = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> elapsed_seconds = end - start;
LOG(info) << "Allocation time for " << name << " (" << size << " bytes)"
<< ": " << elapsed_seconds.count() << "s";
}
return (buffer.second = buffer.first->get().data()) + offset;
};
} else {
buffer.first.emplace(pc.outputs().make<DataAllocator::UninitializedVector<outputDataType>>(std::make_from_tuple<Output>(outputSpec), mConfParam->outputBufferSize));
region.ptrBase = (buffer.second = buffer.first->get().data()) + offset;
region.size = buffer.first->get().size() - offset;
outputsCreated.insert(name);
}
}
};
auto downSizeBuffer = [](outputBufferType& buffer, size_t size) {
if (!buffer.first) {
return;
}
if (buffer.first->get().size() < size) {
throw std::runtime_error("Invalid buffer size requested");
}
buffer.first->get().resize(size);
if (size && buffer.first->get().data() != buffer.second) {
throw std::runtime_error("Inconsistent buffer address after downsize");
}
};
/*auto downSizeBufferByName = [&outputBuffers, &outputRegions, &downSizeBuffer](GPUOutputControl& region, size_t size) {
auto& buffer = outputBuffers[outputRegions.getIndex(region)];
downSizeBuffer(buffer, size);
};*/
auto downSizeBufferToSpan = [&outputBuffers, &outputRegions, &downSizeBuffer](GPUOutputControl& region, auto span) {
auto& buffer = outputBuffers[outputRegions.getIndex(region)];
if (!buffer.first) {
return;
}
if (span.size() && buffer.second != (char*)span.data()) {
throw std::runtime_error("Buffer does not match span");
}
downSizeBuffer(buffer, span.size() * sizeof(*span.data()));
};
setOutputAllocator("COMPCLUSTERSFLAT", mSpecConfig.outputCompClustersFlat, outputRegions.compressedClusters, std::make_tuple(gDataOriginTPC, (DataDescription) "COMPCLUSTERSFLAT", 0));
setOutputAllocator("CLUSTERNATIVE", mClusterOutputIds.size() > 0, outputRegions.clustersNative, std::make_tuple(gDataOriginTPC, mSpecConfig.sendClustersPerSector ? (DataDescription) "CLUSTERNATIVETMP" : (DataDescription) "CLUSTERNATIVE", NSectors, clusterOutputSectorHeader), sizeof(o2::tpc::ClusterCountIndex));
setOutputAllocator("CLSHAREDMAP", mSpecConfig.outputSharedClusterMap, outputRegions.sharedClusterMap, std::make_tuple(gDataOriginTPC, (DataDescription) "CLSHAREDMAP", 0));
setOutputAllocator("TPCOCCUPANCYMAP", mSpecConfig.outputSharedClusterMap, outputRegions.tpcOccupancyMap, std::make_tuple(gDataOriginTPC, (DataDescription) "TPCOCCUPANCYMAP", 0));
setOutputAllocator("TRACKS", mSpecConfig.outputTracks, outputRegions.tpcTracksO2, std::make_tuple(gDataOriginTPC, (DataDescription) "TRACKS", 0));
setOutputAllocator("CLUSREFS", mSpecConfig.outputTracks, outputRegions.tpcTracksO2ClusRefs, std::make_tuple(gDataOriginTPC, (DataDescription) "CLUSREFS", 0));
setOutputAllocator("TRACKSMCLBL", mSpecConfig.outputTracks && mSpecConfig.processMC, outputRegions.tpcTracksO2Labels, std::make_tuple(gDataOriginTPC, (DataDescription) "TRACKSMCLBL", 0));
setOutputAllocator("TRIGGERWORDS", mSpecConfig.caClusterer && mConfig->configProcessing.param.tpcTriggerHandling, outputRegions.tpcTriggerWords, std::make_tuple(gDataOriginTPC, (DataDescription) "TRIGGERWORDS", 0));
o2::tpc::ClusterNativeHelper::ConstMCLabelContainerViewWithBuffer clustersMCBuffer;
if (mSpecConfig.processMC && mSpecConfig.caClusterer) {
outputRegions.clusterLabels.allocator = [&clustersMCBuffer](size_t size) -> void* { return &clustersMCBuffer; };
}
// ------------------------------ Actual processing ------------------------------
if ((int32_t)(ptrs.tpcZS != nullptr) + (int32_t)(ptrs.tpcPackedDigits != nullptr && (ptrs.tpcZS == nullptr || ptrs.tpcPackedDigits->tpcDigitsMC == nullptr)) + (int32_t)(ptrs.clustersNative != nullptr) + (int32_t)(ptrs.tpcCompressedClusters != nullptr) != 1) {
throw std::runtime_error("Invalid input for gpu tracking");
}
const auto& holdData = o2::tpc::TPCTrackingDigitsPreCheck::runPrecheck(&ptrs, mConfig.get());
calibObjectStruct oldCalibObjects;
doCalibUpdates(pc, oldCalibObjects);
lockDecodeInput.reset();
if (mConfParam->dump) {
if (mNTFs == 1) {
mGPUReco->DumpSettings();
}
mGPUReco->DumpEvent(mNTFs - 1, &ptrs);
}
std::unique_ptr<GPUTrackingInOutPointers> ptrsDump;
if (mConfParam->dumpBadTFMode == 2) {
ptrsDump.reset(new GPUTrackingInOutPointers);
memcpy((void*)ptrsDump.get(), (const void*)&ptrs, sizeof(ptrs));
}
int32_t retVal = 0;
if (mSpecConfig.enableDoublePipeline) {
if (!pipelineContext->jobSubmitted) {
enqueuePipelinedJob(&ptrs, &outputRegions, pipelineContext.get(), true);
} else {
finalizeInputPipelinedJob(&ptrs, &outputRegions, pipelineContext.get());
}
std::unique_lock lk(pipelineContext->jobFinishedMutex);
pipelineContext->jobFinishedNotify.wait(lk, [context = pipelineContext.get()]() { return context->jobFinished; });
retVal = pipelineContext->jobReturnValue;
} else {
// uint32_t threadIndex = pc.services().get<ThreadPool>().threadIndex;
uint32_t threadIndex = mNextThreadIndex;
if (mConfig->configProcessing.doublePipeline) {
mNextThreadIndex = (mNextThreadIndex + 1) % 2;
}
retVal = runMain(&pc, &ptrs, &outputRegions, threadIndex);
}
if (retVal != 0) {
debugTFDump = true;
}
cleanOldCalibsTPCPtrs(oldCalibObjects);
o2::utils::DebugStreamer::instance()->flush(); // flushing debug output to file
if (debugTFDump && mNDebugDumps < mConfParam->dumpBadTFs) {
mNDebugDumps++;
if (mConfParam->dumpBadTFMode <= 1) {
std::string filename = std::string("tpc_dump_") + std::to_string(pc.services().get<const o2::framework::DeviceSpec>().inputTimesliceId) + "_" + std::to_string(mNDebugDumps) + ".dump";
FILE* fp = fopen(filename.c_str(), "w+b");
std::vector<InputSpec> filter = {{"check", ConcreteDataTypeMatcher{gDataOriginTPC, "RAWDATA"}, Lifetime::Timeframe}};
for (auto const& ref : InputRecordWalker(pc.inputs(), filter)) {
auto data = pc.inputs().get<gsl::span<char>>(ref);
if (mConfParam->dumpBadTFMode == 1) {
uint64_t size = data.size();
fwrite(&size, 1, sizeof(size), fp);
}
fwrite(data.data(), 1, data.size(), fp);
}
fclose(fp);
} else if (mConfParam->dumpBadTFMode == 2) {
mGPUReco->DumpEvent(mNDebugDumps - 1, ptrsDump.get());
}
}
if (mConfParam->dump == 2) {
return;
}
// ------------------------------ Varios postprocessing steps ------------------------------
bool createEmptyOutput = false;
if (retVal != 0) {
if (retVal == 3 && mConfig->configProcessing.ignoreNonFatalGPUErrors) {
if (mConfig->configProcessing.throttleAlarms) {
LOG(warning) << "GPU Reconstruction aborted with non fatal error code, ignoring";
} else {
LOG(alarm) << "GPU Reconstruction aborted with non fatal error code, ignoring";
}
createEmptyOutput = !mConfParam->partialOutputForNonFatalErrors;
} else {
throw std::runtime_error("GPU Reconstruction error: error code " + std::to_string(retVal));
}
}
std::unique_ptr<o2::tpc::ClusterNativeAccess> tmpEmptyClNative;
if (createEmptyOutput) {
memset(&ptrs, 0, sizeof(ptrs));
for (uint32_t i = 0; i < outputRegions.count(); i++) {
if (outputBuffers[i].first) {
size_t toSize = 0;
if (i == outputRegions.getIndex(outputRegions.compressedClusters)) {
toSize = sizeof(*ptrs.tpcCompressedClusters);
} else if (i == outputRegions.getIndex(outputRegions.clustersNative)) {
toSize = sizeof(o2::tpc::ClusterCountIndex);
}
outputBuffers[i].first->get().resize(toSize);
outputBuffers[i].second = outputBuffers[i].first->get().data();
if (toSize) {
memset(outputBuffers[i].second, 0, toSize);
}
}
}
tmpEmptyClNative = std::make_unique<o2::tpc::ClusterNativeAccess>();
memset(tmpEmptyClNative.get(), 0, sizeof(*tmpEmptyClNative));
ptrs.clustersNative = tmpEmptyClNative.get();
if (mSpecConfig.processMC) {
MCLabelContainer cont;
cont.flatten_to(clustersMCBuffer.first);
clustersMCBuffer.second = clustersMCBuffer.first;
tmpEmptyClNative->clustersMCTruth = &clustersMCBuffer.second;
}
} else {
gsl::span<const o2::tpc::TrackTPC> spanOutputTracks = {ptrs.outputTracksTPCO2, ptrs.nOutputTracksTPCO2};
gsl::span<const uint32_t> spanOutputClusRefs = {ptrs.outputClusRefsTPCO2, ptrs.nOutputClusRefsTPCO2};
gsl::span<const o2::MCCompLabel> spanOutputTracksMCTruth = {ptrs.outputTracksTPCO2MC, ptrs.outputTracksTPCO2MC ? ptrs.nOutputTracksTPCO2 : 0};
if (!mConfParam->allocateOutputOnTheFly) {
for (uint32_t i = 0; i < outputRegions.count(); i++) {
if (outputRegions.asArray()[i].ptrBase) {
if (outputRegions.asArray()[i].size == 1) {
throw std::runtime_error("Preallocated buffer size exceeded");
}
outputRegions.asArray()[i].checkCurrent();
downSizeBuffer(outputBuffers[i], (char*)outputRegions.asArray()[i].ptrCurrent - (char*)outputBuffers[i].second);
}
}
}
downSizeBufferToSpan(outputRegions.tpcTracksO2, spanOutputTracks);
downSizeBufferToSpan(outputRegions.tpcTracksO2ClusRefs, spanOutputClusRefs);
downSizeBufferToSpan(outputRegions.tpcTracksO2Labels, spanOutputTracksMCTruth);
// if requested, tune TPC tracks
if (ptrs.nOutputTracksTPCO2) {
doTrackTuneTPC(ptrs, outputBuffers[outputRegions.getIndex(outputRegions.tpcTracksO2)].first->get().data());
}
if (mClusterOutputIds.size() > 0 && (void*)ptrs.clustersNative->clustersLinear != (void*)(outputBuffers[outputRegions.getIndex(outputRegions.clustersNative)].second + sizeof(o2::tpc::ClusterCountIndex))) {
throw std::runtime_error("cluster native output ptrs out of sync"); // sanity check
}
}
if (mConfig->configWorkflow.outputs.isSet(GPUDataTypes::InOutType::TPCMergedTracks)) {
LOG(info) << "found " << ptrs.nOutputTracksTPCO2 << " track(s)";
}
if (mSpecConfig.outputCompClusters) {
o2::tpc::CompressedClustersROOT compressedClusters = *ptrs.tpcCompressedClusters;
pc.outputs().snapshot(Output{gDataOriginTPC, "COMPCLUSTERS", 0}, ROOTSerialized<o2::tpc::CompressedClustersROOT const>(compressedClusters));
}
if (mClusterOutputIds.size() > 0) {
o2::tpc::ClusterNativeAccess const& accessIndex = *ptrs.clustersNative;
if (mSpecConfig.sendClustersPerSector) {
// Clusters are shipped by sector, we are copying into per-sector buffers (anyway only for ROOT output)
for (uint32_t i = 0; i < NSectors; i++) {
if (mTPCSectorMask & (1ul << i)) {
DataHeader::SubSpecificationType subspec = i;
clusterOutputSectorHeader.sectorBits = (1ul << i);
char* buffer = pc.outputs().make<char>({gDataOriginTPC, "CLUSTERNATIVE", subspec, {clusterOutputSectorHeader}}, accessIndex.nClustersSector[i] * sizeof(*accessIndex.clustersLinear) + sizeof(o2::tpc::ClusterCountIndex)).data();
o2::tpc::ClusterCountIndex* outIndex = reinterpret_cast<o2::tpc::ClusterCountIndex*>(buffer);
memset(outIndex, 0, sizeof(*outIndex));
for (int32_t j = 0; j < o2::tpc::constants::MAXGLOBALPADROW; j++) {
outIndex->nClusters[i][j] = accessIndex.nClusters[i][j];
}
memcpy(buffer + sizeof(*outIndex), accessIndex.clusters[i][0], accessIndex.nClustersSector[i] * sizeof(*accessIndex.clustersLinear));
if (mSpecConfig.processMC && accessIndex.clustersMCTruth) {
MCLabelContainer cont;
for (uint32_t j = 0; j < accessIndex.nClustersSector[i]; j++) {
const auto& labels = accessIndex.clustersMCTruth->getLabels(accessIndex.clusterOffset[i][0] + j);
for (const auto& label : labels) {
cont.addElement(j, label);
}
}
ConstMCLabelContainer contflat;
cont.flatten_to(contflat);
pc.outputs().snapshot({gDataOriginTPC, "CLNATIVEMCLBL", subspec, {clusterOutputSectorHeader}}, contflat);
}
}
}
} else {
// Clusters are shipped as single message, fill ClusterCountIndex
DataHeader::SubSpecificationType subspec = NSectors;
o2::tpc::ClusterCountIndex* outIndex = reinterpret_cast<o2::tpc::ClusterCountIndex*>(outputBuffers[outputRegions.getIndex(outputRegions.clustersNative)].second);