diff --git a/GPU/Common/GPUCommonDef.h b/GPU/Common/GPUCommonDef.h index 5c68366702f93..0e7c54f296300 100644 --- a/GPU/Common/GPUCommonDef.h +++ b/GPU/Common/GPUCommonDef.h @@ -99,6 +99,12 @@ #endif #endif +#ifdef GPUCA_GPUCODE // Macros, not functions: the arguments contain code that exists only on the CPU +#define GPUCA_IGNORE_ON_GPU(...) +#else +#define GPUCA_IGNORE_ON_GPU(...) __VA_ARGS__ +#endif + // API Definitions for GPU Compilation #include "GPUCommonDefAPI.h" diff --git a/GPU/GPUTracking/Base/GPUReconstruction.cxx b/GPU/GPUTracking/Base/GPUReconstruction.cxx index 31ff906a19490..b8dc1a3a4c7ae 100644 --- a/GPU/GPUTracking/Base/GPUReconstruction.cxx +++ b/GPU/GPUTracking/Base/GPUReconstruction.cxx @@ -279,7 +279,7 @@ int32_t GPUReconstruction::InitPhaseBeforeDevice() if (mProcessingSettings->debugLevel >= 6 && ((mProcessingSettings->debugMask + 1) & mProcessingSettings->debugMask)) { GPUError("WARNING: debugMask %d - debug output might not be deterministic with intermediate steps missing", mProcessingSettings->debugMask); } - mProcessingSettings->overrideClusterizerFragmentLen = TPC_MAX_FRAGMENT_LEN_GPU; + mProcessingSettings->overrideClusterizerFragmentLen = tpccf::TPC_MAX_FRAGMENT_LEN_GPU; if (GetProcessingSettings().createO2Output > 1) { mProcessingSettings->createO2Output = 1; } @@ -345,7 +345,7 @@ int32_t GPUReconstruction::InitPhaseBeforeDevice() mProcessingSettings->nTPCClustererLanes = (GetRecoStepsGPU() & RecoStep::TPCClusterFinding) ? 3 : std::max(1, std::min(GPUTPCGeometry::NSECTORS, GetProcessingSettings().inKernelParallel ? (mMaxHostThreads >= 4 ? std::min(mMaxHostThreads / 2, mMaxHostThreads >= 32 ? GPUTPCGeometry::NSECTORS : 4) : 1) : mMaxHostThreads)); } if (GetProcessingSettings().overrideClusterizerFragmentLen == -1) { - mProcessingSettings->overrideClusterizerFragmentLen = ((GetRecoStepsGPU() & RecoStep::TPCClusterFinding) || (mMaxHostThreads / GetProcessingSettings().nTPCClustererLanes >= 3)) ? TPC_MAX_FRAGMENT_LEN_GPU : TPC_MAX_FRAGMENT_LEN_HOST; + mProcessingSettings->overrideClusterizerFragmentLen = ((GetRecoStepsGPU() & RecoStep::TPCClusterFinding) || (mMaxHostThreads / GetProcessingSettings().nTPCClustererLanes >= 3)) ? tpccf::TPC_MAX_FRAGMENT_LEN_GPU : tpccf::TPC_MAX_FRAGMENT_LEN_HOST; } if ((uint32_t)GetProcessingSettings().nTPCClustererLanes > GPUTPCGeometry::NSECTORS) { GPUError("Invalid value for nTPCClustererLanes: %d", GetProcessingSettings().nTPCClustererLanes); @@ -1247,12 +1247,12 @@ int32_t GPUReconstruction::GPUChkErrA(const int64_t retval, const char* file, in return 1; } -void GPUReconstruction::DumpSettings(const char* dir) +void GPUReconstruction::DumpSettings(const char* dir, const GPUSettingsGRP* grp) { std::string f; f = dir; f += "settings.dump"; - DumpStructToFile(mGRPSettings.get(), f.c_str()); + DumpStructToFile(grp ? grp : mGRPSettings.get(), f.c_str()); for (uint32_t i = 0; i < mChains.size(); i++) { mChains[i]->DumpSettings(dir); } diff --git a/GPU/GPUTracking/Base/GPUReconstruction.h b/GPU/GPUTracking/Base/GPUReconstruction.h index c94b66a9a5cc5..bb16fbf80a1ef 100644 --- a/GPU/GPUTracking/Base/GPUReconstruction.h +++ b/GPU/GPUTracking/Base/GPUReconstruction.h @@ -145,7 +145,7 @@ class GPUReconstruction int32_t Finalize(); int32_t Exit(); - void DumpSettings(const char* dir = ""); + void DumpSettings(const char* dir = "", const GPUSettingsGRP* grp = nullptr); // grp: write these GRP settings instead of the current ones int32_t ReadSettings(const char* dir = ""); void PrepareEvent(); diff --git a/GPU/GPUTracking/CMakeLists.txt b/GPU/GPUTracking/CMakeLists.txt index a21608ba8c247..4dbb9b576a7ef 100644 --- a/GPU/GPUTracking/CMakeLists.txt +++ b/GPU/GPUTracking/CMakeLists.txt @@ -326,6 +326,7 @@ if(GPU_STALE_GENERATED_HEADERS) file(REMOVE ${GPU_STALE_GENERATED_HEADERS}) endif() include(kernels.cmake) +check_gpu_param_json("${GPU_PARAM_JSON_FILES}") # Needs the kernel and parameter lists from kernels.cmake # Optional sources depending on optional dependencies if(GPUCA_EVENT_DISPLAY) diff --git a/GPU/GPUTracking/DataTypes/CalibdEdxContainer.cxx b/GPU/GPUTracking/DataTypes/CalibdEdxContainer.cxx index 3f6a7b3257d26..d6eb506d7e652 100644 --- a/GPU/GPUTracking/DataTypes/CalibdEdxContainer.cxx +++ b/GPU/GPUTracking/DataTypes/CalibdEdxContainer.cxx @@ -167,7 +167,7 @@ void CalibdEdxContainer::setDefaultZeroSupresssionThreshold() mThresholdMap.setMinCorrectionFactor(defaultVal - 0.1f); mThresholdMap.setMaxCorrectionFactor(defaultVal + 0.1f); for (int32_t sector = 0; sector < o2::tpc::constants::MAXSECTOR; ++sector) { - for (uint16_t globPad = 0; globPad < TPC_REAL_PADS_IN_SECTOR; ++globPad) { + for (uint16_t globPad = 0; globPad < tpccf::TPC_REAL_PADS_IN_SECTOR; ++globPad) { mThresholdMap.setGainCorrection(sector, globPad, defaultVal); } } diff --git a/GPU/GPUTracking/DataTypes/GPUMemorySizeScalers.cxx b/GPU/GPUTracking/DataTypes/GPUMemorySizeScalers.cxx index 0b97c84218d8c..637ac741b55e5 100644 --- a/GPU/GPUTracking/DataTypes/GPUMemorySizeScalers.cxx +++ b/GPU/GPUTracking/DataTypes/GPUMemorySizeScalers.cxx @@ -79,5 +79,6 @@ size_t GPUMemorySizeScalers::NTPCSectorTracks(size_t tpcHits) { return getValue( size_t GPUMemorySizeScalers::NTPCSectorTrackHits(size_t tpcHits, uint8_t withRejection) { return getValue(tpcMaxSectorTrackHits, tpcHits * (withRejection ? tpcSectorTrackHitsPerHitWithRejection : tpcSectorTrackHitsPerHit)); } size_t GPUMemorySizeScalers::NTPCMergedTracks(size_t tpcSectorTracks) { return getValue(tpcMaxMergedTracks, tpcSectorTracks * (conservativeMemoryEstimate ? 1.0 : tpcMergedTrackPerSectorTrack)); } size_t GPUMemorySizeScalers::NTPCMergedTrackHits(size_t tpcSectorTrackHitss) { return getValue(tpcMaxMergedTrackHits, tpcSectorTrackHitss * tpcMergedTrackHitPerSectorHit); } +size_t GPUMemorySizeScalers::NTPCLoopExtrData(size_t tpcMergedTracks, bool followExtrapolation) { return tpcMergedTracks * (conservativeMemoryEstimate ? 1.0 : tpcLoopExtrDataPerMergedTrack) * (followExtrapolation ? 2 : 1); } // FollowExtrapolation can store both ends of each track size_t GPUMemorySizeScalers::NTPCUnattachedHitsBase1024(int32_t type) { return (returnMaxVal || conservativeMemoryEstimate) ? 1024 : std::min(1024, tpcCompressedUnattachedHitsBase1024[type] * (doFuzzing == 0 ? scalingFactor : getScalingFactor()) * temporaryFactor); } size_t GPUMemorySizeScalers::NTPCRebuildRows() { return (returnMaxVal || conservativeMemoryEstimate) ? GPUTPCGeometry::NROWS : std::min(GPUTPCGeometry::NROWS, GPUTPCGeometry::NROWS * tpcTrackRebuildRowFraction * (doFuzzing == 0 ? scalingFactor : getScalingFactor()) * temporaryFactor); } diff --git a/GPU/GPUTracking/DataTypes/GPUMemorySizeScalers.h b/GPU/GPUTracking/DataTypes/GPUMemorySizeScalers.h index 2cfc6cb924ac0..93af6ddc1488b 100644 --- a/GPU/GPUTracking/DataTypes/GPUMemorySizeScalers.h +++ b/GPU/GPUTracking/DataTypes/GPUMemorySizeScalers.h @@ -65,6 +65,7 @@ struct GPUMemorySizeScalers : public GPUSettingsProcessingScaling { size_t NTPCSectorTrackHits(size_t tpcHits, uint8_t withRejection = 0); size_t NTPCMergedTracks(size_t tpcSectorTracks); size_t NTPCMergedTrackHits(size_t tpcSectorTrackHitss); + size_t NTPCLoopExtrData(size_t tpcMergedTracks, bool followExtrapolation); // tpcMergedTracks: already scaled value from NTPCMergedTracks size_t NTPCUnattachedHitsBase1024(int32_t type); size_t NTPCRebuildRows(); }; diff --git a/GPU/GPUTracking/DataTypes/TPCPadBitMap.cxx b/GPU/GPUTracking/DataTypes/TPCPadBitMap.cxx index 6ebc5db8e7e06..660d5771acae3 100644 --- a/GPU/GPUTracking/DataTypes/TPCPadBitMap.cxx +++ b/GPU/GPUTracking/DataTypes/TPCPadBitMap.cxx @@ -40,7 +40,7 @@ TPCPadBitMap::TPCPadBitMap(const o2::tpc::CalDet& map) : TPCPadBitMap() void TPCPadBitMap::setFromMap(const o2::tpc::CalDet& map) { for (int32_t sector = 0; sector < o2::tpc::constants::MAXSECTOR; sector++) { - for (int32_t p = 0; p < TPC_REAL_PADS_IN_SECTOR; p++) { + for (int32_t p = 0; p < tpccf::TPC_REAL_PADS_IN_SECTOR; p++) { const auto val = map.getValue(sector, p); mBitMap[sector].set(p, val); } diff --git a/GPU/GPUTracking/DataTypes/TPCPadBitMap.h b/GPU/GPUTracking/DataTypes/TPCPadBitMap.h index 70ff0886ec8da..9c9fe56336945 100644 --- a/GPU/GPUTracking/DataTypes/TPCPadBitMap.h +++ b/GPU/GPUTracking/DataTypes/TPCPadBitMap.h @@ -71,7 +71,7 @@ struct TPCPadBitMap { { public: using T = uint32_t; - static GPUglobalconstexpr() int32_t NWORDS = (TPC_REAL_PADS_IN_SECTOR + sizeof(T) * 8 - 1) / sizeof(T); + static GPUglobalconstexpr() int32_t NWORDS = (tpccf::TPC_REAL_PADS_IN_SECTOR + sizeof(T) * 8 - 1) / sizeof(T); GPUdi() SectorBitMap() { reset(); diff --git a/GPU/GPUTracking/DataTypes/TPCPadGainCalib.cxx b/GPU/GPUTracking/DataTypes/TPCPadGainCalib.cxx index 54125eb324bd1..cc925762aa5d1 100644 --- a/GPU/GPUTracking/DataTypes/TPCPadGainCalib.cxx +++ b/GPU/GPUTracking/DataTypes/TPCPadGainCalib.cxx @@ -47,7 +47,7 @@ TPCPadGainCalib::TPCPadGainCalib(const o2::tpc::CalDet& gainMap, const fl void TPCPadGainCalib::setFromMap(const o2::tpc::CalDet& gainMap, const bool inv) { for (int32_t sector = 0; sector < o2::tpc::constants::MAXSECTOR; sector++) { - for (int32_t p = 0; p < TPC_REAL_PADS_IN_SECTOR; p++) { + for (int32_t p = 0; p < tpccf::TPC_REAL_PADS_IN_SECTOR; p++) { const float gainVal = gainMap.getValue(sector, p); inv ? mGainCorrection[sector].set(p, (gainVal > 1.e-5f) ? 1.f / gainVal : 1.f) : mGainCorrection[sector].set(p, gainVal); } diff --git a/GPU/GPUTracking/DataTypes/TPCPadGainCalib.h b/GPU/GPUTracking/DataTypes/TPCPadGainCalib.h index c6fd0b58f36dc..b262060cba70e 100644 --- a/GPU/GPUTracking/DataTypes/TPCPadGainCalib.h +++ b/GPU/GPUTracking/DataTypes/TPCPadGainCalib.h @@ -123,13 +123,13 @@ struct TPCPadGainCalib { GPUd() void reset() { - for (uint16_t p = 0; p < TPC_REAL_PADS_IN_SECTOR; p++) { + for (uint16_t p = 0; p < tpccf::TPC_REAL_PADS_IN_SECTOR; p++) { set(p, 1.0f); } } private: - T mGainCorrection[TPC_REAL_PADS_IN_SECTOR]; + T mGainCorrection[tpccf::TPC_REAL_PADS_IN_SECTOR]; GPUd() T pack(float f) const { diff --git a/GPU/GPUTracking/DataTypes/TPCZSLinkMapping.cxx b/GPU/GPUTracking/DataTypes/TPCZSLinkMapping.cxx index 88cf0d44ad7c1..623c7a50d91fe 100644 --- a/GPU/GPUTracking/DataTypes/TPCZSLinkMapping.cxx +++ b/GPU/GPUTracking/DataTypes/TPCZSLinkMapping.cxx @@ -26,12 +26,12 @@ TPCZSLinkMapping::TPCZSLinkMapping(o2::tpc::Mapper& mapper) { #ifndef GPUCA_STANDALONE const auto& fecToGlobalPad = mapper.getMapFECIDGlobalPad(); - assert(fecToGlobalPad.size() == TPC_FEC_IDS_IN_SECTOR); + assert(fecToGlobalPad.size() == tpccf::TPC_FEC_IDS_IN_SECTOR); const auto& globalPadToPadPos = mapper.getMapGlobalPadToPadPos(); - assert(globalPadToPadPos.size() == TPC_REAL_PADS_IN_SECTOR); + assert(globalPadToPadPos.size() == tpccf::TPC_REAL_PADS_IN_SECTOR); - for (size_t i = 0; i < TPC_FEC_IDS_IN_SECTOR; i++) { + for (size_t i = 0; i < tpccf::TPC_FEC_IDS_IN_SECTOR; i++) { FECIDToPadPos[i] = globalPadToPadPos[fecToGlobalPad[i]]; } #endif diff --git a/GPU/GPUTracking/DataTypes/TPCZSLinkMapping.h b/GPU/GPUTracking/DataTypes/TPCZSLinkMapping.h index b698c93d9d87f..13e35c983883f 100644 --- a/GPU/GPUTracking/DataTypes/TPCZSLinkMapping.h +++ b/GPU/GPUTracking/DataTypes/TPCZSLinkMapping.h @@ -34,7 +34,7 @@ struct TPCZSLinkMapping { TPCZSLinkMapping(o2::tpc::Mapper& mapper); #endif #ifndef GPUCA_RUN2 - o2::tpc::PadPos FECIDToPadPos[TPC_FEC_IDS_IN_SECTOR]; + o2::tpc::PadPos FECIDToPadPos[tpccf::TPC_FEC_IDS_IN_SECTOR]; #endif }; diff --git a/GPU/GPUTracking/Definitions/GPUSettingsList.template b/GPU/GPUTracking/Definitions/GPUSettingsList.template index 94b25b32cf734..6e0927c017b9f 100644 --- a/GPU/GPUTracking/Definitions/GPUSettingsList.template +++ b/GPU/GPUTracking/Definitions/GPUSettingsList.template @@ -103,6 +103,8 @@ AddOptionRTC(trackletMinSharedNormFactor, float, 0.f, "", 0, "Max shared defined AddOptionRTC(trackFitMinHitsMaxQPtIncrease, float, 0.2f, "", 0, "For the QPt-dependent minimum number of hits of the track fit, abs(QPt) is increased by 1 sigma, but at most by this fraction (0 = use fitted QPt)") AddOptionRTC(rebuildTrackMaxSharedFraction, float, 0.1f, "", 0, "Max fraction of shared clusters for rebuilt tracks") AddOptionRTC(rebuildTrackMaxNonIntCov, float, 4.f, "", 0, "Max Err2 allowed for non-interpolated cluster attachment during rebuild") +AddOptionRTC(followExtrapolationMaxCov, float, 4.f, "", 0, "Max Err2 for following (not during rebuild) the track beyond its ends for adjacent clusters") +AddOptionRTC(followExtrapolationChi2Factor, float, 0.f, "", 0, "> 1: follow track once more after rebuild, sets factor by which chi2 window is reduced for marking adjcacent clusters") AddOptionRTC(rebuildErrorWeightFactor, float, 5.f, "", 0, "Factor for the error (distance^2) of a cluster candidate in its hit weight 1 / (1 + factor * error) during rebuild") AddOptionRTC(maxSinPhiForFitUpdate, float, 0.9396926f, "", 0, "Max abs(sinPhi) of the track to update it with a cluster in the track fit)") // default sin(70 deg = 0.9396926 AddOptionRTC(rebuildTrackMaxQPtDrift, float, 0.5f, "", 0, "Stop the track extrapolation during rebuild when QPt changed by more than this fraction of max(1, abs(QPt)) compared to before the extrapolation (0 = disabled)") @@ -156,7 +158,7 @@ AddOptionRTC(mergerNonInterpolateRejectMinNDF, uint8_t, 5, "", 0, "Minimum NDF o AddOptionRTC(rebuildTrackInFit, uint8_t, 1, "", 0, "Rebuild track completely during fit based on clusters closed to interpolated track positions, adds 2 fit iterations") AddOptionRTC(rebuildTrackInFitClusterCandidates, uint8_t, 3, "", 0, "Number of cluster candidates per row for rebuilt track") AddOptionRTC(disableRebuildAttachment, uint8_t, 0, "", 0, "Bitmask to disable certain attachment steps during track rebuid (1: current row, 2: interpolate missing row, 4: one sided interpolation, 8: original hit, 16: extrapolation)") -AddOptionRTC(disableMarkAdjacent, uint8_t, 0, "", 0, "Bitmask to disable certain steps during refit to mark adjacenrt clusters (1: current row, 2: interpolate missing rows, 4: extrapolate inwards / outwards, 8: loop following, 16 track history)") +AddOptionRTC(disableMarkAdjacent, uint8_t, 0, "", 0, "Bitmask to disable certain steps during refit to mark adjacenrt clusters (1: current row, 2: interpolate missing rows, 4: extrapolate inwards / outwards, 8: loop following, 16: track history, 32: track-following after extrapolated rebuild)") AddOptionRTC(dEdxTruncLow, uint8_t, 2, "", 0, "Low truncation threshold, fraction of 128") AddOptionRTC(dEdxTruncHigh, uint8_t, 77, "", 0, "High truncation threshold, fraction of 128") AddOptionRTC(extrapolationTracking, int8_t, 1, "", 0, "Enable Extrapolation Tracking (prolong tracks to adjacent sectors to find short segments)") @@ -340,6 +342,7 @@ AddOption(tpcSectorTrackHitsPerHit, float, 0.8, "", 0, "Scaling Factor: tpcSecto AddOption(tpcSectorTrackHitsPerHitWithRejection, float, 1.0, "", 0, "Scaling Factor: tpcSectorTrackHitsPerHitWithRejection") AddOption(tpcMergedTrackPerSectorTrack, float, 1.0, "", 0, "Scaling Factor: tpcMergedTrackPerSectorTrack") AddOption(tpcMergedTrackHitPerSectorHit, float, 1.1, "", 0, "Scaling Factor: tpcMergedTrackHitPerSectorHit") +AddOption(tpcLoopExtrDataPerMergedTrack, float, 1.0, "", 0, "Scaling Factor: tpcLoopExtrDataPerMergedTrack (entries for FollowLoopers / FollowExtrapolation), doubled if FollowExtrapolation is used") AddOptionArray(tpcCompressedUnattachedHitsBase1024, int32_t, 3, (900, 900, 500), "", 0, "Scaling Factor: tpcCompressedUnattachedHitsBase1024") AddOption(tpcDecodingClusterRatioFactor1, float, 1.5, "", 0, "Scaling Factor: for first margin of dynamic buffer allocation for attached clusters in TPC Decoding") AddOption(tpcDecodingClusterRatioFactor2, float, 3.5, "", 0, "Scaling Factor: for second margin of dynamic buffer allocation for attached clusters in TPC Decoding") @@ -354,6 +357,7 @@ BeginSubConfig(GPUSettingsProcessingDebug, debug, configStandalone.proc, "DEBUG" AddOption(memoryScalingFuzz, uint64_t, 0, "", 0, "Fuzz the memoryScalingFactor (0 disable, 1 enable, >1 set seed", def(1)) AddOption(mergerMCLabels, bool, false, "", 0, "Create MC labels for merged tracks before refit for debugging") AddOption(mergerDumpTrackNCl, bool, false, "", 0, "Dump file with nCl per merged track fit") +AddOption(tpcMergerFitOnCPUSingleThread, bool, false, "", 0, "Run the TPC merger kernels from the track fit on with 1 CPU thread, for ordered GPUCA_CADEBUG output (CPU only)") AddHelp("help", 0) EndConfig() @@ -377,7 +381,8 @@ AddOption(debugLevel, int32_t, -1, "debug", 'd', "Set debug level (-2 = silent, AddOption(allocDebugLevel, int32_t, 0, "allocDebug", 0, "Some debug output for memory allocations (without messing with normal debug level)") AddOption(debugMask, uint32_t, (1 << 18) - 1, "debugMask", 0, "Mask for debug output dumps to file") AddOption(debugLogSuffix, std::string, "", "debugSuffix", 0, "Suffix for debug log files with --debug 6") -AddOption(debugDumpChecksum, bool, false, "", 0, "When using --debug 6, log only the checksum instead of writing the full dump to a file") +AddOption(debugDumpFinal, bool, false, "", 0, "When using --debug < 6, dump the final output") +AddOption(debugDumpChecksum, bool, false, "", 0, "When using --debug 6 or debugDumpFinal, log only the checksum instead of writing the full dump to a file") AddOption(debugFileHexFloat, int32_t, -1, "", 0, "Use hex format to print floats to debug dump file") AddOption(debugCSV, std::string, "", "", 0, "CSV filename to append the benchmark results. Verbosity determined by parameter --debug") AddOption(debugMarkdown, bool, false, "", 0, "Print the results of standalone benchmarks in markdown format") @@ -515,7 +520,7 @@ AddOption(overrideNHbfPerTF, int32_t, 0, "", 0, "Overrides the number of HBF per AddOption(overrideTPCTimeBinCur, int32_t, 0, "", 0, "Overrides TPC time bin cut if > 0") AddOption(deviceType, std::string, "CPU", "", 0, "Device type, CPU | CUDA | HIP | OCL | METAL | CPUDEVICE") AddOption(forceDeviceType, bool, true, "", 0, "force device type, otherwise allows fall-back to CPU") -AddOption(synchronousProcessing, bool, false, "", 0, "Apply performance shortcuts for synchronous processing, disable unneeded steps") +AddOption(synchronousProcessing, int32_t, 0, "", 0, "0: No special settings, 1: synchronous: Apply performance shortcuts for synchronous processing, disable unneeded steps, -1: asynchronous: ignore low-pt, disable adjacent cluster search") AddOption(dump, int32_t, 0, "", 0, "Dump events for standalone benchmark: 1 = dump events, 2 = dump events and skip processing in workflow") AddOption(dumpFirst, int32_t, 0, "", 0, "First event to dump (referring to tfCounter)") AddOption(dumpLast, int32_t, -1, "", 0, "Last event to dump (-1 = all)") diff --git a/GPU/GPUTracking/Definitions/GPUSettingsListStandalone.template b/GPU/GPUTracking/Definitions/GPUSettingsListStandalone.template index bf7f1a8d24eb6..e8d5056bf38be 100644 --- a/GPU/GPUTracking/Definitions/GPUSettingsListStandalone.template +++ b/GPU/GPUTracking/Definitions/GPUSettingsListStandalone.template @@ -76,7 +76,7 @@ AddOption(overrideMaxTimebin, bool, false, "", 0, "Override max time bin setting AddOption(encodeZS, int32_t, -1, "", 0, "Zero-Suppress TPC data", def(1)) AddOption(zsFilter, int32_t, -1, "", 0, "Apply Zero-Suppression when loading digits and remove those below threshold", def(1)) AddOption(zsVersion, int32_t, 2, "", 0, "ZS Version: 1 = 10-bit ADC row based, 2 = 12-bit ADC row based, 3 = improved link based, 4 = dense link based") -AddOption(dumpEvents, bool, false, "", 0, "Dump events (after transformation such as encodeZS") +AddOption(dumpEvents, uint8_t, 0, "", 0, "Dump events (1 = input after transformation such as encodeZS, 2 = input of the asynchronous phase with --syncAsync)") AddOption(stripDumpedEvents, bool, false, "", 0, "Remove redundant inputs (e.g. digits and ZS) before dumping") AddOption(printSettings, int32_t, 0, "", 0, "Print all settings", def(1)) AddOption(testSyncAsync, bool, false, "syncAsync", 0, "Test first synchronous and then asynchronous processing") diff --git a/GPU/GPUTracking/Definitions/Parameters/GPUParameters.csv b/GPU/GPUTracking/Definitions/Parameters/GPUParameters.csv index 87336277eadbd..e4ebe7e9a6d59 100644 --- a/GPU/GPUTracking/Definitions/Parameters/GPUParameters.csv +++ b/GPU/GPUTracking/Definitions/Parameters/GPUParameters.csv @@ -31,6 +31,7 @@ GPUTPCGMMergerTrackFit_def,256,,"[192, 2]","[64, 7]",,,,,,"[32, 16]","[32, 8]"," GPUTPCGMMergerTrackFit_rebuild,256,,"[192, 2]","[64, 7]",,,,,,"[32, 16]","[32, 8]","[32, 14]","[160, 2]",,"[32, 24]",,"[64, 8]","[64, 6]","[64, 4]" GPUTPCGMMergerTrackFit_retry,256,,"[192, 2]","[64, 7]",,,,,,"[32, 16]","[32, 8]","[32, 14]","[160, 2]",,"[32, 24]",,"[64, 8]","[64, 6]","[64, 4]" GPUTPCGMMergerFollowLoopers,256,,"[256, 5]","[256, 4]",,,,,,"[256, 4]","[128, 4]","[1024, 1]",640,,"[128, 16]",,"[224, 3]","[256, 7]","[32, 64]" +GPUTPCGMMergerFollowExtrapolation,256,,"[256, 5]","[256, 4]",,,,,,"[256, 4]","[128, 4]","[1024, 1]",640,,"[128, 16]",,"[224, 3]","[256, 7]","[32, 64]" GPUTPCGMMergerSectorRefit,256,,"[64, 4]","[256, 2]",,,,,,"[32, 8]","[64, 5]","[32, 7]","[32, 7]",,"[32, 20]",,"[32, 10]","[64, 4]","[256, 8]" GPUTPCGMMergerUnpackResetIds,256,,256,256,,,,,,256,256,256,256,,256,,256,256, GPUTPCGMMergerUnpackGlobal,256,,256,256,,,,,,256,256,256,256,,256,,256,256, @@ -122,4 +123,3 @@ MERGER_INTERPOLATION_ERROR_TYPE,"""CAMath::half_t""","""float""",,,,,,,,,,,,,,,, COMP_GATHER_KERNEL,4,0,4,4,,,,,,4,4,4,4,,4,,4,4, COMP_GATHER_MODE,3,0,3,3,,,,,,3,3,3,3,,3,,3,3, CF_SCAN_WORKGROUP_SIZE,512,0,,,,,,,,224,,992,448,,1024,,,448, -MERGER_SPLIT_LOOP_INTERPOLATION,,,,,,,,,,,,,,,1,,,1, diff --git a/GPU/GPUTracking/Definitions/Parameters/gpu_param_header_generator.cmake b/GPU/GPUTracking/Definitions/Parameters/gpu_param_header_generator.cmake index c1ec6bbd53fa9..a182f3d8b3424 100644 --- a/GPU/GPUTracking/Definitions/Parameters/gpu_param_header_generator.cmake +++ b/GPU/GPUTracking/Definitions/Parameters/gpu_param_header_generator.cmake @@ -140,3 +140,46 @@ function(generate_gpu_param_header GPU_PARAM_JSON_FILES ARCH_LIST OUT_HEADER OUT file(GENERATE OUTPUT "${OUT_HEADER}" CONTENT "${TMP_HEADER}") file(GENERATE OUTPUT "${OUT_HEADER_DEVICE}" CONTENT "${TMP_HEADER_DEVICE}") endfunction() + +function(check_gpu_param_json GPU_PARAM_JSON_FILES) # Parameters in the json files must be declared in kernels.cmake, kernels with launch bounds must have them in the json files + get_property(KNOWN_PARAMS TARGET O2_GPU_KERNELS PROPERTY O2_GPU_KERNEL_PARAMS) + get_property(KNOWN_STRING_PARAMS TARGET O2_GPU_KERNELS PROPERTY O2_GPU_KERNEL_STRING_PARAMS) + list(APPEND KNOWN_PARAMS ${KNOWN_STRING_PARAMS}) + set(KNOWN_CORE_PARAMS WARP_SIZE THREAD_COUNT_DEFAULT) + set(JSON_LB_NAMES) + set(ERRORS) + foreach(GPU_PARAM_JSON_FILE IN LISTS GPU_PARAM_JSON_FILES) + file(READ "${GPU_PARAM_JSON_FILE}" JSON_CONTENT) + foreach(TYPE IN ITEMS CORE LB PAR) + string(JSON n_params ERROR_VARIABLE json_error LENGTH "${JSON_CONTENT}" "${TYPE}") + if(json_error OR n_params EQUAL 0) + continue() + endif() + math(EXPR last "${n_params} - 1") + foreach(i RANGE 0 ${last}) + string(JSON param_name MEMBER "${JSON_CONTENT}" "${TYPE}" "${i}") + if(TYPE STREQUAL "CORE") + if(NOT param_name IN_LIST KNOWN_CORE_PARAMS) + list(JOIN KNOWN_CORE_PARAMS ", " KNOWN_CORE_PARAMS_STR) + list(APPEND ERRORS "Core parameter ${param_name} in ${GPU_PARAM_JSON_FILE} unknown, allowed: ${KNOWN_CORE_PARAMS_STR}") + endif() + elseif(TYPE STREQUAL "LB") + list(APPEND JSON_LB_NAMES "${param_name}") + elseif(NOT param_name IN_LIST KNOWN_PARAMS) + list(APPEND ERRORS "Parameter ${param_name} in ${GPU_PARAM_JSON_FILE} not declared with o2_gpu_kernel_add_parameter / o2_gpu_kernel_add_string_parameter in kernels.cmake") + endif() + endforeach() + endforeach() + endforeach() + get_property(LB_KERNELS TARGET O2_GPU_KERNELS PROPERTY O2_GPU_KERNEL_NAMES_LB) + foreach(kernel IN LISTS LB_KERNELS) + string(REGEX REPLACE "[^A-Za-z0-9]+" "_" kernel_lb_name "${kernel}") + if(NOT kernel_lb_name IN_LIST JSON_LB_NAMES) + list(APPEND ERRORS "Kernel ${kernel} declared with LB in kernels.cmake, but no launch bounds ${kernel_lb_name} in ${GPU_PARAM_JSON_FILES}") + endif() + endforeach() + if(ERRORS) + list(JOIN ERRORS "\n" ERRORS) + message(FATAL_ERROR "Inconsistent GPU parameters:\n${ERRORS}") + endif() +endfunction() diff --git a/GPU/GPUTracking/Definitions/clusterFinderDefs.h b/GPU/GPUTracking/Definitions/clusterFinderDefs.h index dea7b146f9344..0b0028b0cc77b 100644 --- a/GPU/GPUTracking/Definitions/clusterFinderDefs.h +++ b/GPU/GPUTracking/Definitions/clusterFinderDefs.h @@ -15,50 +15,10 @@ #ifndef O2_GPU_CLUSTERFINDERDEFS_H #define O2_GPU_CLUSTERFINDERDEFS_H +#include "GPUCommonDef.h" #include "GPUDef.h" #include "DataFormatsTPC/Constants.h" -/* #define CHARGEMAP_TIME_MAJOR_LAYOUT */ -#define CHARGEMAP_TILING_LAYOUT - -#define SCRATCH_PAD_SEARCH_N 8 // TODO: Change all this to constexpr where possible, like in GPUDefParametersConstants.h -#define SCRATCH_PAD_COUNT_N 16 -#if defined(GPUCA_GPUCODE) && !defined(GPUCA_DEVICE_SINGLE_THREAD) -#define SCRATCH_PAD_BUILD_N 8 -#define SCRATCH_PAD_NOISE_N 8 -#else -// Double shared memory on cpu as we can't reuse the memory from other threads -#define SCRATCH_PAD_BUILD_N 16 -#define SCRATCH_PAD_NOISE_N 16 -#endif - -// Padding of 2 and 3 respectively would be enough. But this ensures that -// rows are always aligned along cache lines. Likewise for TPC_CLUSTERER_ROW_PAD_CAPACITY. -#define GPUCF_PADDING_PAD 8 -#define GPUCF_PADDING_TIME 4 -// Largest possible number of pads in a TPC row -#define TPC_CLUSTERER_ROW_PAD_CAPACITY 144 - -// Stride between rows as stored internally by the clusterizer -#define TPC_CLUSTERER_ROW_STRIDE (TPC_CLUSTERER_ROW_PAD_CAPACITY + GPUCF_PADDING_PAD) -// Number of pads in a sector as stored internally by the clusterizer. -// This includes fake pads for constant strides between rows -#define TPC_CLUSTERER_STRIDED_PAD_COUNT (o2::tpc::constants::MAXGLOBALPADROW * TPC_CLUSTERER_ROW_STRIDE + GPUCF_PADDING_PAD) -// Real of number of pads in a sector -#define TPC_REAL_PADS_IN_SECTOR 14560 -#define TPC_FEC_IDS_IN_SECTOR 23296 -#define TPC_MAX_FRAGMENT_LEN_GPU 4000 -#define TPC_MAX_FRAGMENT_LEN_HOST 1000 -#define TPC_MAX_FRAGMENT_LEN_PADDED(size) ((size) + 2 * GPUCF_PADDING_TIME) - -#ifdef GPUCA_GPUCODE -#define CPU_ONLY(x) -#define CPU_PTR(x) nullptr -#else -#define CPU_ONLY(x) x -#define CPU_PTR(x) x -#endif - namespace o2::gpu::tpccf { @@ -77,6 +37,42 @@ using Delta2 = short2; using local_id = short2; +static GPUglobalconstexpr() int32_t CHARGEMAP_TILING_LAYOUT = 1; // Layout of the charge map: 1 = tiling layout, 0 = linear layout + +static GPUglobalconstexpr() uint32_t SCRATCH_PAD_SEARCH_N = 8; +static GPUglobalconstexpr() uint32_t SCRATCH_PAD_COUNT_N = 16; +#if defined(GPUCA_GPUCODE) && !defined(GPUCA_DEVICE_SINGLE_THREAD) +static GPUglobalconstexpr() uint32_t SCRATCH_PAD_BUILD_N = 8; +static GPUglobalconstexpr() uint32_t SCRATCH_PAD_NOISE_N = 8; +#else +// Double shared memory on cpu as we can't reuse the memory from other threads +static GPUglobalconstexpr() uint32_t SCRATCH_PAD_BUILD_N = 16; +static GPUglobalconstexpr() uint32_t SCRATCH_PAD_NOISE_N = 16; +#endif + +// Padding of 2 and 3 respectively would be enough. But this ensures that +// rows are always aligned along cache lines. Likewise for TPC_CLUSTERER_ROW_PAD_CAPACITY. +static GPUglobalconstexpr() int32_t GPUCF_PADDING_PAD = 8; +static GPUglobalconstexpr() int32_t GPUCF_PADDING_TIME = 4; +// Largest possible number of pads in a TPC row +static GPUglobalconstexpr() int32_t TPC_CLUSTERER_ROW_PAD_CAPACITY = 144; + +// Stride between rows as stored internally by the clusterizer +static GPUglobalconstexpr() int32_t TPC_CLUSTERER_ROW_STRIDE = TPC_CLUSTERER_ROW_PAD_CAPACITY + GPUCF_PADDING_PAD; +// Number of pads in a sector as stored internally by the clusterizer. +// This includes fake pads for constant strides between rows +static GPUglobalconstexpr() int32_t TPC_CLUSTERER_STRIDED_PAD_COUNT = o2::tpc::constants::MAXGLOBALPADROW * TPC_CLUSTERER_ROW_STRIDE + GPUCF_PADDING_PAD; +// Real of number of pads in a sector +static GPUglobalconstexpr() int32_t TPC_REAL_PADS_IN_SECTOR = 14560; +static GPUglobalconstexpr() int32_t TPC_FEC_IDS_IN_SECTOR = 23296; +static GPUglobalconstexpr() int32_t TPC_MAX_FRAGMENT_LEN_GPU = 4000; +static GPUglobalconstexpr() int32_t TPC_MAX_FRAGMENT_LEN_HOST = 1000; +template +constexpr GPUhdi() T TPC_MAX_FRAGMENT_LEN_PADDED(T size) +{ + return size + 2 * GPUCF_PADDING_TIME; +} + } // namespace o2::gpu::tpccf #endif diff --git a/GPU/GPUTracking/Global/GPUChainTracking.cxx b/GPU/GPUTracking/Global/GPUChainTracking.cxx index e2b896f95c01d..16db9a04f9fab 100644 --- a/GPU/GPUTracking/Global/GPUChainTracking.cxx +++ b/GPU/GPUTracking/Global/GPUChainTracking.cxx @@ -279,6 +279,10 @@ bool GPUChainTracking::ValidateSettings() GPUError("Clusterizer and merger Sanity checks only supported when not running on GPU"); return false; } + if (mRec->IsGPU() && GetProcessingSettings().debug.tpcMergerFitOnCPUSingleThread) { + GPUError("tpcMergerFitOnCPUSingleThread only supported when not running on GPU"); + return false; + } if (GetProcessingSettings().tpcWriteClustersAfterRejection && (mRec->IsGPU() || param().rec.tpc.compressionTypeMask || !(GetRecoSteps() & gpudatatypes::RecoStep::TPCCompression))) { GPUError("tpcWriteClustersAfterRejection requires compressionTypeMask = 0, no GPU usage, and compression enabled"); return false; @@ -386,7 +390,7 @@ int32_t GPUChainTracking::Init() TransferMemoryResourceLinkToGPU(RecoStep::NoRecoStep, mInputsHost->mResourceErrorCodes); } - if (GetProcessingSettings().debugLevel >= 6) { + if (GetProcessingSettings().debugLevel >= 6 || GetProcessingSettings().debugDumpFinal) { std::string filename = std::string(mRec->IsGPU() ? "GPU" : "CPU") + (mRec->slaveId() != -1 ? (std::string("_slave") + std::to_string(mRec->slaveId())) : std::string(mRec->slavesExist() ? "_master" : "")) + GetProcessingSettings().debugLogSuffix + ".out"; bool hashOnly = GetProcessingSettings().debugDumpChecksum; @@ -485,7 +489,7 @@ int32_t GPUChainTracking::Finalize() GetQA()->UpdateChain(this); GetQA()->DrawQAHistograms(); } - if (GetProcessingSettings().debugLevel >= 6) { + if (GetProcessingSettings().debugLevel >= 6 || GetProcessingSettings().debugDumpFinal) { mDebugFile->flush(); mDebugFileBuffer.close(); @@ -698,7 +702,7 @@ int32_t GPUChainTracking::RunChain() if (needQA) { mFractionalQAEnabled = GetProcessingSettings().qcRunFraction == 100.f || (uint32_t)(rand() % 10000) < (uint32_t)(GetProcessingSettings().qcRunFraction * 100); } - if (GetProcessingSettings().debugLevel >= 6) { + if (GetProcessingSettings().debugLevel >= 6 || GetProcessingSettings().debugDumpFinal) { *mDebugFile << "\n\nProcessing event " << mRec->getNEventsProcessed() << std::endl; } DoQueuedUpdates(0); @@ -807,6 +811,10 @@ int32_t GPUChainTracking::RunChainFinalize() mCompressionStatistics->RunStatistics(mIOPtrs.clustersNative, &c, param(), GetProcessingSettings().runCompressionStatistics >= 2); } + if (GetProcessingSettings().debugDumpFinal && GetProcessingSettings().debugLevel < 6) { // With debugLevel >= 6, the full dump contains the outputs already + DumpFinalOutput(); + } + if (GetProcessingSettings().outputSanityCheck) { OutputSanityCheck(); } @@ -1021,7 +1029,8 @@ void GPUChainTracking::ApplySyncSettings(GPUSettingsProcessing& proc, GPUSetting } if (syncMode) { rec.useMatLUT = false; - rec.tpc.rebuildTrackMaxNonIntCov = 0.f; // TODO: Check if this yields a performance benefit + // rec.tpc.followExtrapolationChi2Factor = 2; // TODO: might want to retest with future tracking versions + rec.tpc.rebuildTrackMaxNonIntCov = 0.f; // TODO: Need to check before data taking the performacne with and without (extrapolation tracking v.s. only track following and attaching adjacent) } else if (asyncMode) { rec.useMatLUT = true; } @@ -1036,4 +1045,8 @@ void GPUChainTracking::ApplySyncSettings(GPUSettingsProcessing& proc, GPUSetting } else if (asyncMode) { proc.tpcDownscaledEdx = 0; } + if (asyncMode) { + rec.tpc.disableMarkAdjacent = 0xFF; + rec.maxTrackQPtB5 = CAMath::Min(rec.maxTrackQPtB5, rec.tpc.rejectQPtB5 * 2.f); // Factor 2 since seeds Pt can be wrong + } } diff --git a/GPU/GPUTracking/Global/GPUChainTracking.h b/GPU/GPUTracking/Global/GPUChainTracking.h index 87723cdddd088..883ac3818b730 100644 --- a/GPU/GPUTracking/Global/GPUChainTracking.h +++ b/GPU/GPUTracking/Global/GPUChainTracking.h @@ -243,6 +243,7 @@ class GPUChainTracking : public GPUChain void PrepareKernelDebugOutput(); void PrintKernelDebugOutput(); void PrintOutputStat(); + void DumpFinalOutput(); static void DumpClusters(std::ostream& out, const o2::tpc::ClusterNativeAccess* clusters); static void DebugSortCompressedClusters(o2::tpc::CompressedClustersFlat* cls); void DoDebugRawDump(); diff --git a/GPU/GPUTracking/Global/GPUChainTrackingClusterizer.cxx b/GPU/GPUTracking/Global/GPUChainTrackingClusterizer.cxx index 50324caeab3fc..5de5d1dae642b 100644 --- a/GPU/GPUTracking/Global/GPUChainTrackingClusterizer.cxx +++ b/GPU/GPUTracking/Global/GPUChainTrackingClusterizer.cxx @@ -1041,7 +1041,7 @@ int32_t GPUChainTracking::RunTPCClusterizer(bool synchronizeOutput) runKernel({GetGridAutoStep(lane, RecoStep::TPCClusterFinding)}, clustererShadow.mPchargeMap, TPCMapMemoryLayout::items(GetProcessingSettings().overrideClusterizerFragmentLen) * sizeof(ChargeMapType)); runKernel({GetGridAutoStep(lane, RecoStep::TPCClusterFinding)}, clustererShadow.mPpeakMap, TPCMapMemoryLayout::items(GetProcessingSettings().overrideClusterizerFragmentLen) * sizeof(PeakMapType)); if (frag.index == 0) { - runKernel({GetGridAutoStep(lane, RecoStep::TPCClusterFinding)}, clustererShadow.mPpadIsNoisy, TPC_CLUSTERER_STRIDED_PAD_COUNT * sizeof(*clustererShadow.mPpadIsNoisy)); + runKernel({GetGridAutoStep(lane, RecoStep::TPCClusterFinding)}, clustererShadow.mPpadIsNoisy, tpccf::TPC_CLUSTERER_STRIDED_PAD_COUNT * sizeof(*clustererShadow.mPpadIsNoisy)); } DoDebugAndDump(RecoStep::TPCClusterFinding, GPUChainTrackingDebugFlags::TPCClustererZeroedCharges, clusterer, &GPUTPCClusterFinder::DumpChargeMap, *mDebugFile, "Zeroed Charges"); @@ -1155,7 +1155,7 @@ int32_t GPUChainTracking::RunTPCClusterizer(bool synchronizeOutput) const int32_t nBlocks = GPUTPCGeometry::NROWS; runKernel({GetGridBlk(nBlocks, lane), {iSector}}); - getKernelTimer(RecoStep::TPCClusterFinding, iSector, TPC_REAL_PADS_IN_SECTOR * frag.lengthWithoutOverlap() * sizeof(PackedCharge), false); + getKernelTimer(RecoStep::TPCClusterFinding, iSector, tpccf::TPC_REAL_PADS_IN_SECTOR * frag.lengthWithoutOverlap() * sizeof(PackedCharge), false); } DoDebugAndDump(RecoStep::TPCClusterFinding, GPUChainTrackingDebugFlags::TPCClustererDigits, clusterer, &GPUTPCClusterFinder::DumpDigits, *mDebugFile); @@ -1510,7 +1510,7 @@ int32_t GPUChainTracking::RunTPCClusterizer(bool synchronizeOutput) if (GetProcessingSettings().debugLevel >= 3) { GPUInfo("%zu trigger words found%s", mTriggerBuffer->triggers.size(), storeTriggers ? ", storing" : ""); } - if (GetProcessingSettings().debugLevel >= 6) { + if (GetProcessingSettings().debugLevel >= 6 || (GetProcessingSettings().debugDumpFinal && storeTriggers)) { std::vector sorted(mTriggerBuffer->triggers.begin(), mTriggerBuffer->triggers.end()); std::sort(sorted.begin(), sorted.end(), [](const auto& a, const auto& b) { return a.orbit != b.orbit ? a.orbit < b.orbit : memcmp(&a.triggerWord, &b.triggerWord, sizeof(a.triggerWord)) < 0; }); *mDebugFile << "\n\nTPC Trigger Words: " << sorted.size() << "\n"; diff --git a/GPU/GPUTracking/Global/GPUChainTrackingDebugAndProfiling.cxx b/GPU/GPUTracking/Global/GPUChainTrackingDebugAndProfiling.cxx index 15061ada83206..aaf83055abac8 100644 --- a/GPU/GPUTracking/Global/GPUChainTrackingDebugAndProfiling.cxx +++ b/GPU/GPUTracking/Global/GPUChainTrackingDebugAndProfiling.cxx @@ -266,6 +266,31 @@ void GPUChainTracking::PrintOutputStat() GPUInfo("Output Tracks (%s): %d - Clusters: %d / %d / %d / %d / %d (attached / total / compressed / fitted / adjacent)%s", outputType, nTracks, nAttachedClusters, nCls, nCompressedClusters, nAttachedClustersFitted, nAdjacentClusters, trdText); } +void GPUChainTracking::DumpFinalOutput() +{ + std::ostream& out = *mDebugFile; + out << "\n\nFinal Output\n"; + if (mIOPtrs.clustersNative) { + DumpClusters(out, mIOPtrs.clustersNative); + } + if (mIOPtrs.mergedTracks && GetProcessingSettings().createO2Output <= 1) { + processors()->tpcMerger.DumpFinal(out); + } + if (mIOPtrs.outputTracksTPCO2 && GetProcessingSettings().createO2Output) { + processors()->tpcMerger.DumpFinalO2(out); + } + if (mIOPtrs.mergedTrackHitStates && GetProcessingSettings().outputSharedClusterMap && mIOPtrs.clustersNative) { + out << "\nTPC Shared Cluster Map\n"; + for (uint32_t i = 0; i < mIOPtrs.clustersNative->nClustersTotal; i++) { + out << (int32_t)mIOPtrs.mergedTrackHitStates[i] << (i % 100 == 99 ? "\n" : " "); + } + out << "\n"; + } + if ((GetRecoSteps() & RecoStep::TPCCompression) && mIOPtrs.tpcCompressedClusters) { + processors()->tpcCompressor.DumpCompressedClusters(out); + } +} + void GPUChainTracking::OutputSanityCheck() { size_t nErrors = 0; diff --git a/GPU/GPUTracking/Global/GPUChainTrackingMerger.cxx b/GPU/GPUTracking/Global/GPUChainTrackingMerger.cxx index 798689feb5805..1e6956625104e 100644 --- a/GPU/GPUTracking/Global/GPUChainTrackingMerger.cxx +++ b/GPU/GPUTracking/Global/GPUChainTrackingMerger.cxx @@ -275,7 +275,9 @@ int32_t GPUChainTracking::RunTPCTrackingMerger(bool synchronizeOutput) runKernel({{numBlocks, -ThreadCount(), 0, deviceType, RecoStep::TPCMerging}}, MergerShadow.TrackRebuildHelperRow(), nRebuildRows * sizeof(*MergerShadow.TrackRebuildHelperRow())); } } - // mRec->SetNActiveThreads(1); // For GPUTPCGMTrackParam:: GPUCA_CADEBUG: run the host kernels from here on with 1 thread, reset below + if (GetProcessingSettings().debug.tpcMergerFitOnCPUSingleThread) { + mRec->SetNActiveThreads(1); // For GPUTPCGMTrackParam:: GPUCA_CADEBUG: run the host kernels from here on with 1 thread, reset below + } runKernel(doGPU ? GetGrid(Merger.NMergedTracks(), 0) : GetGridAuto(0)); if (param().rec.tpc.rebuildTrackInFit) { runKernel({{numBlocks, -ThreadCount(), 0, deviceType, RecoStep::TPCMerging}}, MergerShadow.HitWeights(), Merger.NClusters() * sizeof(*MergerShadow.HitWeights())); @@ -299,10 +301,22 @@ int32_t GPUChainTracking::RunTPCTrackingMerger(bool synchronizeOutput) mRec->PopNonPersistentMemory(RecoStep::TPCMerging, qStr2Tag("TPCREBLD")); } + const bool followExtrapolation = GPUTPCGMMerger::FollowExtrapolationEnabled(param()); + const bool followExtrapolationStream = followExtrapolation && doGPU && mRec->NStreams() >= 2; + if (followExtrapolationStream) { + RecordMarker(&mEvents->single, 0); + } runKernel(GetGridAuto(0)); + if (followExtrapolation) { + runKernel({GetGridAuto(followExtrapolationStream ? 1 : 0), krnlRunRangeNone, {followExtrapolationStream ? &mEvents->init : nullptr, followExtrapolationStream ? &mEvents->single : nullptr}}); + } DoDebugAndDump(RecoStep::TPCMerging, GPUChainTrackingDebugFlags::TPCMergingRefit, Merger, &GPUTPCGMMerger::DumpRefit, *mDebugFile); - runKernel(GetGridAuto(0, deviceType)); + runKernel({GetGridAuto(0, deviceType), krnlRunRangeNone, {nullptr, followExtrapolationStream ? &mEvents->init : nullptr}}); + if (followExtrapolationStream) { + ReleaseEvent(mEvents->single); + ReleaseEvent(mEvents->init); + } runKernel(GetGridAuto(0, deviceType)); runKernel(GetGridAuto(0, deviceType)); if (param().rec.tpc.mergeLoopersAfterburner) { @@ -351,7 +365,9 @@ int32_t GPUChainTracking::RunTPCTrackingMerger(bool synchronizeOutput) TransferMemoryResourcesToHost(RecoStep::TPCMerging, &Merger, -1, true); } DoDebugMergerNClDump(Merger); - // mRec->SetNActiveThreads(-1); + if (GetProcessingSettings().debug.tpcMergerFitOnCPUSingleThread) { + mRec->SetNActiveThreads(-1); + } mRec->ReturnVolatileDeviceMemory(); mRec->PopNonPersistentMemory(RecoStep::TPCMerging, qStr2Tag("TPCMERGE")); @@ -392,6 +408,7 @@ int32_t GPUChainTracking::RunTPCTrackingMerger(bool synchronizeOutput) TransferMemoryResourceLinkToHost(RecoStep::TPCMerging, Merger.MemoryResOutputO2Clus(), outputStream); ReleaseEvent(mEvents->single); } + DoDebugAndDump(RecoStep::TPCMerging, GPUChainTrackingDebugFlags::TPCMergingRefit, doGPU, Merger, &GPUTPCGMMerger::DumpFinalO2, *mDebugFile); mRec->PopNonPersistentMemory(RecoStep::TPCMerging, qStr2Tag("TPCMERG2")); } #endif diff --git a/GPU/GPUTracking/Interface/GPUO2Interface.cxx b/GPU/GPUTracking/Interface/GPUO2Interface.cxx index 6460d5949e1a8..a82a1919aabde 100644 --- a/GPU/GPUTracking/Interface/GPUO2Interface.cxx +++ b/GPU/GPUTracking/Interface/GPUO2Interface.cxx @@ -278,7 +278,7 @@ void GPUO2Interface::UseGPUPolynomialFieldInPropagator(o2::base::Propagator* pro prop->setGPUField(&mCtx[0].mRec->GetParam().polynomialField); } -void GPUO2Interface::ApplySyncSettings(GPUSettingsProcessing& proc, GPUSettingsRec& rec, gpudatatypes::RecoStepField& steps, bool syncMode, int32_t dEdxMode) +void GPUO2Interface::ApplySyncSettings(GPUSettingsProcessing& proc, GPUSettingsRec& rec, gpudatatypes::RecoStepField& steps, bool syncMode, bool asyncMode, int32_t dEdxMode) { - GPUChainTracking::ApplySyncSettings(proc, rec, steps, syncMode, false, dEdxMode); + GPUChainTracking::ApplySyncSettings(proc, rec, steps, syncMode, asyncMode, dEdxMode); } diff --git a/GPU/GPUTracking/Interface/GPUO2Interface.h b/GPU/GPUTracking/Interface/GPUO2Interface.h index eed7c119f5328..34cd96e1442e5 100644 --- a/GPU/GPUTracking/Interface/GPUO2Interface.h +++ b/GPU/GPUTracking/Interface/GPUO2Interface.h @@ -84,7 +84,7 @@ class GPUO2Interface // Updates all calibration objects that are != nullptr in newCalib int32_t UpdateCalibration(const GPUCalibObjectsConst& newCalib, const GPUNewCalibValues& newVals, uint32_t iThread = 0); - static void ApplySyncSettings(GPUSettingsProcessing& proc, GPUSettingsRec& rec, gpudatatypes::RecoStepField& steps, bool syncMode, int32_t dEdxMode = -2); + static void ApplySyncSettings(GPUSettingsProcessing& proc, GPUSettingsRec& rec, gpudatatypes::RecoStepField& steps, bool syncMode, bool asyncMode, int32_t dEdxMode = -2); int32_t registerMemoryForGPU(const void* ptr, size_t size); int32_t unregisterMemoryForGPU(const void* ptr); diff --git a/GPU/GPUTracking/Merger/GPUTPCGMMerger.cxx b/GPU/GPUTracking/Merger/GPUTPCGMMerger.cxx index 9f57b08e5263e..2f0a5eecae5cb 100644 --- a/GPU/GPUTracking/Merger/GPUTPCGMMerger.cxx +++ b/GPU/GPUTracking/Merger/GPUTPCGMMerger.cxx @@ -406,7 +406,7 @@ void* GPUTPCGMMerger::SetPointersMerger(void* mem) computePointerWithAlignment(mem, mTrackSort, mNMaxTracks); memMax = (void*)std::max((size_t)mem, (size_t)memMax); mem = memBase; - computePointerWithAlignment(mem, mLoopData, mNMaxTracks); // GPUTPCGMMergerTrackFit - GPUTPCGMMergerFollowLoopers, Reducing mNMaxTracks does not save memory, other parts are larger anyway + computePointerWithAlignment(mem, mLoopAndExtData, mNMaxLoopExtrData); // GPUTPCGMMergerTrackFit - GPUTPCGMMergerFollowLoopers / GPUTPCGMMergerFollowExtrapolation, Reducing mNMaxLoopExtrData does not save memory, other parts are larger anyway if (mRec->GetParam().rec.tpc.rebuildTrackInFit) { computePointerWithAlignment(mem, mSharedCount2, mNClusters); computePointerWithAlignment(mem, mHitWeights, mNClusters); @@ -552,6 +552,9 @@ void GPUTPCGMMerger::SetMaxData(const GPUTrackingInOutPointers& io) } else { mNMaxTracks = mRec->MemoryScalers()->NTPCMergedTracks(mNTotalSectorTracks); } + mNMaxLoopExtrData = !(Param().rec.tpc.disableMarkAdjacent & 4) && !(Param().rec.tpc.disableMarkAdjacent & 8) + ? mRec->MemoryScalers()->NTPCLoopExtrData(mNMaxTracks, FollowExtrapolationEnabled(Param())) + : 0; if (io.clustersNative) { mNClusters = io.clustersNative->nClustersTotal; } else if (mRec->GetRecoSteps() & gpudatatypes::RecoStep::TPCSectorTracking) { @@ -608,6 +611,16 @@ void GPUTPCGMMerger::CreateMCLabels(int32_t nBlocks, int32_t nThreads, int32_t i #endif // GPUCA_GPUCODE +GPUd() bool GPUTPCGMMerger::FollowExtrapolationEnabled(const GPUParam& param) +{ + return (!FollowExtrapolationAfterRebuild(param) || (param.rec.tpc.mergerInterpolateErrors && param.rec.tpc.followExtrapolationChi2Factor > 0 && !(param.rec.tpc.disableMarkAdjacent & 32))) && !(param.rec.tpc.disableMarkAdjacent & 4); // Without the extrapolation of the rebuild, or in the 5-way fit where it marks no adjacent clusters +} + +GPUd() bool GPUTPCGMMerger::FollowExtrapolationAfterRebuild(const GPUParam& param) +{ + return param.rec.tpc.rebuildTrackInFit && param.rec.tpc.rebuildTrackMaxNonIntCov > 0; +} + GPUd() void GPUTPCGMMerger::ClearTrackLinks(int32_t nBlocks, int32_t nThreads, int32_t iBlock, int32_t iThread, bool output) { const int32_t n = output ? mMemory->nMergedTracks : mMemory->nUnpackedTracks; diff --git a/GPU/GPUTracking/Merger/GPUTPCGMMerger.h b/GPU/GPUTracking/Merger/GPUTPCGMMerger.h index 77b0fc8ddbbae..0d3bf669b6cee 100644 --- a/GPU/GPUTracking/Merger/GPUTPCGMMerger.h +++ b/GPU/GPUTracking/Merger/GPUTPCGMMerger.h @@ -48,7 +48,7 @@ class GPUTPCGMTrackParam; class GPUTPCTracker; class GPUChainTracking; class GPUTPCGMPolynomialField; -struct GPUTPCGMLoopData; +struct GPUTPCGMLoopAndExtData; namespace internal { struct MergeLooperParam; @@ -70,6 +70,7 @@ class GPUTPCGMMerger : public GPUProcessor struct memory { GPUAtomic(uint32_t) nRetryRefit; GPUAtomic(uint32_t) nLoopData; + GPUAtomic(uint32_t) nFollowExtrapolationData; GPUAtomic(uint32_t) nUnpackedTracks; GPUAtomic(uint32_t) nUnpackedTracksGlobal; GPUAtomic(uint32_t) nMergedTracks; @@ -133,6 +134,9 @@ class GPUTPCGMMerger : public GPUProcessor GPUhdi() uint32_t NSectorHits() const { return mNSectorHits; } GPUhdi() uint32_t NClusters() const { return mNClusters; } GPUhdi() uint32_t NMaxTracks() const { return mNMaxTracks; } + GPUhdi() uint32_t NMaxLoopExtrData() const { return mNMaxLoopExtrData; } + GPUd() static bool FollowExtrapolationEnabled(const GPUParam& param); + GPUd() static bool FollowExtrapolationAfterRebuild(const GPUParam& param); GPUhdi() uint32_t NMaxMergedTrackClusters() const { return mNMaxMergedTrackClusters; } GPUhdi() uint32_t NMergedTrackClusters() const { return mMemory->nMergedTrackClusters; } GPUhdi() const GPUTPCGMMergedTrackHit* Clusters() const { return mClusters; } @@ -162,7 +166,7 @@ class GPUTPCGMMerger : public GPUProcessor GPUhdi() uint32_t* TrackOrderProcess() const { return mTrackOrderProcess; } GPUhdi() uint32_t* RetryRefitIds() const { return mRetryRefitIds; } GPUhdi() uint8_t* ClusterStateExt() const { return mClusterStateExt; } - GPUhdi() GPUTPCGMLoopData* LoopData() const { return mLoopData; } + GPUhdi() GPUTPCGMLoopAndExtData* LoopAndExtData() const { return mLoopAndExtData; } GPUhdi() memory* Memory() const { return mMemory; } GPUhdi() GPUAtomic(uint32_t) * TmpCounter() { return mMemory->tmpCounter; } GPUhdi() uint2* ClusRefTmp() { return mClusRefTmp; } @@ -250,6 +254,7 @@ class GPUTPCGMMerger : public GPUProcessor void DumpFitPrepare(std::ostream& out) const; void DumpRefit(std::ostream& out) const; void DumpFinal(std::ostream& out) const; + void DumpFinalO2(std::ostream& out) const; void DumpLoopers(std::ostream& out) const; void DumpInterpolatedHits(std::ostream& out) const; void DumpRebuiltTracks(std::ostream& out) const; @@ -296,6 +301,7 @@ class GPUTPCGMMerger : public GPUProcessor uint32_t mNTotalSectorTracks = 0; // maximum number of incoming sector tracks uint32_t mNMaxTracks = 0; // maximum number of output tracks + uint32_t mNMaxLoopExtrData = 0; // maximum number of LoopAndExtData entries uint32_t mNRebuildTrackRow = 0; // number of rows allocated for the rebuild uint32_t mNMaxSingleSectorTracks = 0; // max N tracks in one sector uint32_t mNMaxMergedTrackClusters = 0; // max number of clusters in output tracks (double-counting shared clusters) @@ -347,7 +353,7 @@ class GPUTPCGMMerger : public GPUProcessor gputpcgmmergertypes::GPUTPCGMBorderRange* mBorderRange[NSECTORS]; // memory for border tracks memory* mMemory = nullptr; uint32_t* mRetryRefitIds = nullptr; - GPUTPCGMLoopData* mLoopData = nullptr; + GPUTPCGMLoopAndExtData* mLoopAndExtData = nullptr; }; } // namespace o2::gpu diff --git a/GPU/GPUTracking/Merger/GPUTPCGMMergerDump.cxx b/GPU/GPUTracking/Merger/GPUTPCGMMergerDump.cxx index 496d70b745bb3..34d2256332ecf 100644 --- a/GPU/GPUTracking/Merger/GPUTPCGMMergerDump.cxx +++ b/GPU/GPUTracking/Merger/GPUTPCGMMergerDump.cxx @@ -273,6 +273,35 @@ void GPUTPCGMMerger::DumpFinal(std::ostream& out) const out << "\n"; } +void GPUTPCGMMerger::DumpFinalO2(std::ostream& out) const +{ + out << "\nTPC O2 Tracks: " << mMemory->nO2Tracks << "\n"; + for (uint32_t i = 0; i < mMemory->nO2Tracks; i++) { + const auto& trk = mOutputTracksTPCO2[i]; + out << "Track " << i << ": X " << trk.getX() << " Alpha " << trk.getAlpha() << " Par"; + for (int32_t j = 0; j < 5; j++) { + out << " " << trk.getParam(j); + } + out << " Cov"; + for (int32_t j = 0; j < 15; j++) { + out << " " << trk.getCov()[j]; + } + const auto& outer = trk.getOuterParam(); + out << " - Outer X " << outer.getX() << " Alpha " << outer.getAlpha() << " Par"; + for (int32_t j = 0; j < 5; j++) { + out << " " << outer.getParam(j); + } + out << " - Time0 " << trk.getTime0() << " DeltaTBwd " << trk.getDeltaTBwd() << " DeltaTFwd " << trk.getDeltaTFwd() << " Chi2 " << trk.getChi2() << " Flags " << trk.getFlags() << " dEdx " << trk.getdEdx().dEdxTotTPC << " " << trk.getdEdx().dEdxMaxTPC << " - " << trk.getNClusters() << " Clusters:"; + for (int32_t j = 0; j < trk.getNClusters(); j++) { + uint8_t sector, row; + uint32_t cl; + trk.getClusterReference(mOutputClusRefsTPCO2, j, sector, row, cl); + out << " " << (int32_t)sector << "/" << (int32_t)row << "/" << cl; + } + out << "\n"; + } +} + void GPUTPCGMMerger::DumpInterpolatedHits(std::ostream& out) const { out << "\nTPC Merger Interpolated Hits\n"; diff --git a/GPU/GPUTracking/Merger/GPUTPCGMMergerGPU.cxx b/GPU/GPUTracking/Merger/GPUTPCGMMergerGPU.cxx index 1a54ba4edb365..18e33659463e6 100644 --- a/GPU/GPUTracking/Merger/GPUTPCGMMergerGPU.cxx +++ b/GPU/GPUTracking/Merger/GPUTPCGMMergerGPU.cxx @@ -42,14 +42,37 @@ template void GPUTPCGMMergerTrackFit::Thread(in template void GPUTPCGMMergerTrackFit::Thread(int32_t nBlocks, int32_t nThreads, int32_t iBlock, int32_t iThread, GPUsharedref() GPUSharedMemory& smem, processorType& merger); #endif +GPUdi() static bool CheckLoopAndExtDataOverflow(const GPUTPCGMMerger& GPUrestrict() merger, int32_t iBlock, int32_t iThread) +{ + const uint32_t n = merger.Memory()->nLoopData + merger.Memory()->nFollowExtrapolationData; + if (n > merger.NMaxLoopExtrData() && iBlock == 0 && iThread == 0) { + merger.raiseError(GPUErrors::ERROR_MERGER_LOOPER_OVERFLOW, n, merger.NMaxLoopExtrData(), 3); + } + return n > merger.NMaxLoopExtrData(); +} + template <> GPUdii() void GPUTPCGMMergerFollowLoopers::Thread<0>(int32_t nBlocks, int32_t nThreads, int32_t iBlock, int32_t iThread, GPUsharedref() GPUSharedMemory& smem, processorType& GPUrestrict() merger) { + if (CheckLoopAndExtDataOverflow(merger, iBlock, iThread)) { + return; + } GPUCA_TBB_KERNEL_LOOP(merger.GetRec(), uint32_t, i, merger.Memory()->nLoopData, { GPUTPCGMTrackParam::PropagateLooper(merger, i); }); } +template <> +GPUdii() void GPUTPCGMMergerFollowExtrapolation::Thread<0>(int32_t nBlocks, int32_t nThreads, int32_t iBlock, int32_t iThread, GPUsharedref() GPUSharedMemory& smem, processorType& GPUrestrict() merger) +{ + if (CheckLoopAndExtDataOverflow(merger, iBlock, iThread)) { + return; + } + GPUCA_TBB_KERNEL_LOOP(merger.GetRec(), uint32_t, i, merger.Memory()->nFollowExtrapolationData, { + GPUTPCGMTrackParam::FollowExtrapolation(merger, i); + }); +} + template <> GPUdii() void GPUTPCGMMergerUnpackResetIds::Thread<0>(int32_t nBlocks, int32_t nThreads, int32_t iBlock, int32_t iThread, GPUsharedref() GPUSharedMemory& smem, processorType& GPUrestrict() merger, int32_t iSector) { diff --git a/GPU/GPUTracking/Merger/GPUTPCGMMergerGPU.h b/GPU/GPUTracking/Merger/GPUTPCGMMergerGPU.h index 72300566a3d90..63ac9589bd250 100644 --- a/GPU/GPUTracking/Merger/GPUTPCGMMergerGPU.h +++ b/GPU/GPUTracking/Merger/GPUTPCGMMergerGPU.h @@ -49,6 +49,13 @@ class GPUTPCGMMergerFollowLoopers : public GPUTPCGMMergerGeneral GPUd() static void Thread(int32_t nBlocks, int32_t nThreads, int32_t iBlock, int32_t iThread, GPUsharedref() GPUSharedMemory& smem, processorType& merger); }; +class GPUTPCGMMergerFollowExtrapolation : public GPUTPCGMMergerGeneral +{ + public: + template + GPUd() static void Thread(int32_t nBlocks, int32_t nThreads, int32_t iBlock, int32_t iThread, GPUsharedref() GPUSharedMemory& smem, processorType& merger); +}; + class GPUTPCGMMergerSectorRefit : public GPUTPCGMMergerGeneral { public: diff --git a/GPU/GPUTracking/Merger/GPUTPCGMTrackParam.cxx b/GPU/GPUTracking/Merger/GPUTPCGMTrackParam.cxx index e42750e3c4712..04b9b3570175a 100644 --- a/GPU/GPUTracking/Merger/GPUTPCGMTrackParam.cxx +++ b/GPU/GPUTracking/Merger/GPUTPCGMTrackParam.cxx @@ -47,6 +47,9 @@ static thread_local bool CADEBUG_CONDITION = true; #ifndef GPUCA_GPUCODE #include "SimulationDataFormat/ConstMCTruthContainer.h" #include "SimulationDataFormat/MCCompLabel.h" +#ifdef DEBUG_REBUILD_MC +#include "GPUQAHelper.h" +#endif #endif #ifndef GPUCA_GPUCODE_DEVICE @@ -57,6 +60,12 @@ static thread_local bool CADEBUG_CONDITION = true; using namespace o2::gpu; using namespace o2::tpc; +struct GPUTPCGMTrackParam::ExtrapolationState { + float segmentStartChi2, lastFoundX, lastFoundAlpha; + uint8_t lastGoodRow, lastExtrapolateRow, lastFoundRow, consecGoodRows, segmentRows; + bool revert; +}; + template GPUd() bool GPUTPCGMTrackParam::Fit(GPUTPCGMMerger& GPUrestrict() merger, GPUTPCGMMergerRebuildTmp* tmpRows, int32_t iTrk, int32_t& GPUrestrict() N, int32_t& GPUrestrict() NTolerated, float& GPUrestrict() Alpha, GPUTPCGMMergedTrack& GPUrestrict() track) { @@ -164,7 +173,7 @@ GPUd() bool GPUTPCGMTrackParam::Fit(GPUTPCGMMerger& GPUrestrict() merger, GPUTPC // TODO: Check about tracks who have clusters in the same row multiple times in different sectors const auto& cluster = clusters[ihit]; - CADEBUG(printf("\tSector %2d %11sTrack Alpha %8.3f %s, X %8.3f - Y %8.3f, Z %8.3f - QPt %7.2f (%7.2f), SP %5.2f (%5.2f) %28s --- Cov sY %8.3f sZ %8.3f sSP %8.3f sPt %8.3f - YPt %8.3f\n", (int32_t)cluster.sector, "", prop.GetAlpha(), (CAMath::Abs(prop.GetAlpha() - clAlpha) < 0.01 ? " " : " R!"), mX, mP[0], mP[1], mP[4], prop.GetQPt0(), mP[2], prop.GetSinPhi0(), "", sqrtf(mC[0]), sqrtf(mC[2]), sqrtf(mC[5]), sqrtf(mC[14]), mC[10])); + CADEBUG(printf("\tSector %2d %11sTrack Alpha %8.3f %s, X %8.3f - Y %8.3f, Z %8.3f - QPt %7.2f (%7.2f), SP %5.2f (%5.2f) %28s --- Cov sY %8.3f sZ %8.3f sSP %8.3f sPt %8.3f - YPt %8.3f\n", (int32_t)cluster.sector, "", prop.GetAlpha(), (CAMath::Abs(prop.GetAlpha() - clAlpha) < 0.01 ? " " : " R!"), mX, mP[0], mP[1], mP[4], prop.GetQPt0(), mP[2], prop.GetSinPhi0(), "", sqrtf(CAMath::Max(0.f, mC[0])), sqrtf(CAMath::Max(0.f, mC[2])), sqrtf(CAMath::Max(0.f, mC[5])), sqrtf(CAMath::Max(0.f, mC[14])), mC[10])); CADEBUG(printf("\tHit %3d/%3d Row %3d: Cluster Alpha %8.3f %3d, X %8.3f - Y %8.3f, Z %8.3f (Missed %d, %d)\n", ihit, maxN, (int32_t)clusters[ihit].row, clAlpha, (int32_t)clusters[ihit].sector, xx, yy, zz, nMissed, nMissedHard)); const int32_t rowGap = lastPropagateRow == 255 ? 0 : CAMath::Max(0, CAMath::Abs(cluster.row - lastPropagateRow) - 1); @@ -216,17 +225,17 @@ GPUd() bool GPUTPCGMTrackParam::Fit(GPUTPCGMMerger& GPUrestrict() merger, GPUTPC nMissedHard++; NTolerated++; MarkAdjacentSearch(param, iWay, inter); - if (param.rec.tpc.rebuildTrackInFit && iWay == wayRebuildStart + 1 && param.rec.tpc.rebuildTrackMaxNonIntCov > 0 && !(param.rec.tpc.disableRebuildAttachment & 4)) { + if (param.rec.tpc.rebuildTrackInFit && iWay == wayRebuildStart + 1 && (param.rec.tpc.rebuildTrackMaxNonIntCov > 0 ? !(param.rec.tpc.disableRebuildAttachment & 4) : adjacentInRebuild)) { // With maxNonIntCov 0 no one-sided candidates, only the adjacent search at the interpolated position FindBestInterpolatedHit(merger, tmpRows, inter, cluster.sector, cluster.row, deltaZ, sumInvSqrtCharge, nAvgCharge, prop, iTrk, true, adjacentInRebuild && !(param.rec.tpc.disableMarkAdjacent & 1) ? adjacentLeg : 0); } continue; } // clang-format off CADEBUG(if (!CheckCov()){printf("INVALID COV AFTER PROPAGATE!!!\n");}); - CADEBUG(printf("\t%21sPropaga Alpha %8.3f , X %8.3f - Y %8.3f, Z %8.3f - QPt %7.2f (%7.2f), SP %5.2f (%5.2f) --- Res %8.3f %8.3f --- Cov sY %8.3f sZ %8.3f sSP %8.3f sPt %8.3f - YPt %8.3f - PErr %d\n", "", prop.GetAlpha(), mX, mP[0], mP[1], mP[4], prop.GetQPt0(), mP[2], prop.GetSinPhi0(), mP[0] - yy, mP[1] - zz, sqrtf(mC[0]), sqrtf(mC[2]), sqrtf(mC[5]), sqrtf(mC[14]), mC[10], retValProp)); + CADEBUG(printf("\t%21sPropaga Alpha %8.3f , X %8.3f - Y %8.3f, Z %8.3f - QPt %7.2f (%7.2f), SP %5.2f (%5.2f) --- Res %8.3f %8.3f --- Cov sY %8.3f sZ %8.3f sSP %8.3f sPt %8.3f - YPt %8.3f - PErr %d\n", "", prop.GetAlpha(), mX, mP[0], mP[1], mP[4], prop.GetQPt0(), mP[2], prop.GetSinPhi0(), mP[0] - yy, mP[1] - zz, sqrtf(CAMath::Max(0.f, mC[0])), sqrtf(CAMath::Max(0.f, mC[2])), sqrtf(CAMath::Max(0.f, mC[5])), sqrtf(CAMath::Max(0.f, mC[14])), mC[10], retValProp)); // clang-format on if (mNDF >= 0 && (mC[0] > param.rec.tpc.trackFitCovLimit || mC[2] > param.rec.tpc.trackFitCovLimit)) { - if (param.rec.tpc.rebuildTrackInFit && iWay == wayRebuildStart + 1 && param.rec.tpc.rebuildTrackMaxNonIntCov > 0 && !(param.rec.tpc.disableRebuildAttachment & 4)) { + if (param.rec.tpc.rebuildTrackInFit && iWay == wayRebuildStart + 1 && (param.rec.tpc.rebuildTrackMaxNonIntCov > 0 ? !(param.rec.tpc.disableRebuildAttachment & 4) : adjacentInRebuild)) { // With maxNonIntCov 0 no one-sided candidates, only the adjacent search at the interpolated position InterpolateMissingRows(merger, tmpRows, interpolation, clusters, ihit, interpolationIndex, cluster.row, deltaZ, sumInvSqrtCharge, nAvgCharge, prop, iTrk, adjacentInRebuild && !(param.rec.tpc.disableMarkAdjacent & 1) ? adjacentLeg : 0); } MarkAdjacentSearch(param, iWay, inter); @@ -318,7 +327,7 @@ GPUd() bool GPUTPCGMTrackParam::Fit(GPUTPCGMMerger& GPUrestrict() merger, GPUTPC } } } else if (retValHit == 1) { - if (param.rec.tpc.rebuildTrackInFit && iWay == wayRebuildStart + 1 && param.rec.tpc.rebuildTrackMaxNonIntCov > 0 && !(param.rec.tpc.disableRebuildAttachment & 4)) { + if (param.rec.tpc.rebuildTrackInFit && iWay == wayRebuildStart + 1 && (param.rec.tpc.rebuildTrackMaxNonIntCov > 0 ? !(param.rec.tpc.disableRebuildAttachment & 4) : adjacentInRebuild)) { // With maxNonIntCov 0 no one-sided candidates, only the adjacent search at the interpolated position InterpolateMissingRows(merger, tmpRows, interpolation, clusters, ihit + wayDirection, interpolationIndex + wayDirection, cluster.row, deltaZ, sumInvSqrtCharge, nAvgCharge, prop, iTrk, adjacentInRebuild && !(param.rec.tpc.disableMarkAdjacent & 1) ? adjacentLeg : 0); } fitBroken = true; @@ -338,158 +347,38 @@ GPUd() bool GPUTPCGMTrackParam::Fit(GPUTPCGMMerger& GPUrestrict() merger, GPUTPC const int32_t up = ((clusters[0].row < clusters[maxN - 1].row) ^ (iWay & 1)) ? 1 : -1; int32_t sector = lastSector; CADEBUG(if (merger.MergedTrackMC()) printf("Extrapolate Start Track %d - sector %2d row %3d %s - fake %d\n", iTrk, sector, (int32_t)lastPropagateRow, up == 1 ? "upwards" : "downwards", (int)merger.MergedTrackMC()[iTrk].isFake())); - uint8_t rowGapActive = 0, rowGapTotal = 0, missingRowsTotal = 0; - uint8_t lastGoodRow = lastPropagateRow, lastExtrapolateRow = lastPropagateRow, lastFoundRow = lastPropagateRow; - uint8_t consecGoodRows = ihitStart == ((iWay & 1) ? 0 : maxN - 1) ? param.rec.tpc.rebuildTrackExtrMinConsecGoodRows : 0, consecGoodRowsMissing = 0, segmentRows = 0; // Continue the track directly only if its last hit was accepted in the fit - float segmentStartChi2 = mChi2; + ExtrapolationState es; + es.lastGoodRow = es.lastExtrapolateRow = es.lastFoundRow = lastPropagateRow; + es.consecGoodRows = ihitStart == ((iWay & 1) ? 0 : maxN - 1) ? param.rec.tpc.rebuildTrackExtrMinConsecGoodRows : 0; // Continue the track directly only if its last hit was accepted in the fit + es.segmentRows = 0; + es.segmentStartChi2 = mChi2; + es.lastFoundX = es.lastFoundAlpha = 0.f; + es.revert = false; const float qPtStart = mP[4], alphaStart = prop.GetAlpha(); const GPUTPCGMTrackParam paramStart = *this; // To revert to if the extrapolation fails - float lastFoundX = 0.f, lastFoundAlpha = 0.f; - bool revert = false; prop.SetTrack(this, prop.GetAlpha()); - uint32_t iExtrapolatedRow = lastPropagateRow + up; - for (; iExtrapolatedRow < GPUTPCGeometry::NROWS && merger.RebuildRowInRange(iTrk, iExtrapolatedRow, tmpRows); iExtrapolatedRow += up) { // uint8_t implies > 0! // TODO: Try to reduce some variables to int8/uint8 to save registers - bool fail = false; - for (int32_t iAttempt = 0; iAttempt < 2; iAttempt++) { - float tmpX, tmpY, tmpZ; - if (prop.GetPropagatedYZ(GPUTPCGeometry::Row2X(iExtrapolatedRow), tmpY, tmpZ)) { - fail = revert = true; - break; - } - merger.GetConstantMem()->calibObjects.fastTransform->InverseTransformYZtoX(sector, iExtrapolatedRow, tmpY, tmpZ, tmpX); - if (prop.PropagateToXAlpha(tmpX, param.Alpha(sector), inFlyDirection)) { - fail = revert = true; - break; - } - if (CAMath::Abs(mP[2]) > maxSinForUpdate || CAMath::Abs(prop.GetSinPhi0()) >= maxSinForUpdate || mC[0] >= param.rec.tpc.rebuildTrackMaxNonIntCov || mC[2] >= param.rec.tpc.rebuildTrackMaxNonIntCov) { // No further clusters can be attached to the fit - fail = true; - break; - } - if (CAMath::Abs(mP[0]) > CAMath::Abs(mX) * CAMath::Tan(GPUTPCGeometry::kSectAngle() / 2.f) + 0.1f) { - if (iAttempt) { - fail = true; - break; - } - const int32_t sectorSide = sector >= (int8_t)(GPUTPCGeometry::NSECTORS / 2) ? (GPUTPCGeometry::NSECTORS / 2) : 0; - if (mP[0] > 0) { - if (++sector >= sectorSide + 18) { - sector -= 18; - } - } else { - if (--sector < sectorSide) { - sector += 18; - } - } - if (prop.RotateToAlpha(param.Alpha(sector))) { // GetPropagatedYZ / InverseTransformYZtoX of the next attempt need Y in the frame of the new sector - fail = revert = true; - break; - } - } - } - if (fail) { - break; - } - CADEBUG(printf("\tExtrapol. Sec %2d Row %3d Propaga Alpha %8.3f , X %8.3f - Y %8.3f, Z %8.3f - QPt %7.2f (%7.2f), SP %5.2f (%5.2f) --- Cov sY %8.3f sZ %8.3f sSP %8.3f sPt %8.3f - YPt %8.3f\n", sector, iExtrapolatedRow, prop.GetAlpha(), mX, mP[0], mP[1], mP[4], prop.GetQPt0(), mP[2], prop.GetSinPhi0(), sqrtf(mC[0]), sqrtf(mC[2]), sqrtf(mC[5]), sqrtf(mC[14]), mC[10])); - gputpcgmmergertypes::InterpolationErrorHit inter; - inter.markInvalid(); - float uncorrectedY = FindBestInterpolatedHit(merger, tmpRows, inter, sector, iExtrapolatedRow, deltaZ, sumInvSqrtCharge, nAvgCharge, prop, iTrk, false, adjacentInRebuild && !(param.rec.tpc.disableMarkAdjacent & 4) ? adjacentLeg : 0, true); - auto& candidate = merger.ClusterCandidates(iTrk, iExtrapolatedRow, tmpRows)[0]; - bool found = candidate.hasCluster(); - if (found) { - lastExtrapolateRow = iExtrapolatedRow; -#if defined(DEBUG_REBUILD_MC) && !defined(GPUCA_GPUCODE) - if (merger.MergedTrackMC() && merger.GetConstantMem()->ioPtrs.clustersNative->clustersMCTruth) { - int32_t labelCorrect = GPUTPCTrkLblSearch(merger.GetConstantMem()->ioPtrs.clustersNative->clustersMCTruth->getLabels(merger.CandidateClusterId(candidate, iExtrapolatedRow)), merger.MergedTrackMC()[iTrk]); - CADEBUG(printf("\t%21sLabel correct: %d\n", "", labelCorrect)); - } -#endif - float err2Y, err2Z, xx, yy, zz; - const ClusterNative& GPUrestrict() cl = merger.GetConstantMem()->ioPtrs.clustersNative->clustersLinear[merger.CandidateClusterId(candidate, iExtrapolatedRow)]; - merger.GetConstantMem()->calibObjects.fastTransform->Transform(sector, iExtrapolatedRow, cl.getPad(), cl.getTime(), xx, yy, zz, mTOffset); - if (prop.PropagateToXAlpha(xx, prop.GetAlpha(), inFlyDirection)) { - merger.TrackRebuildHelperRow(iTrk, iExtrapolatedRow, tmpRows).setBest(GPUTPCGMMerger::trackRebuildHelperRow::bestRowRemoved); - revert = true; - break; - } - const float time = cl.getTime(); - const float invSqrtCharge = CAMath::InvSqrt(cl.qMax); - const float invCharge = 1.f / cl.qMax; - float invAvgCharge = (sumInvSqrtCharge += invSqrtCharge) / ++nAvgCharge; - invAvgCharge *= invAvgCharge; - const uint8_t clusterState = cl.getFlags(); - prop.GetErr2(err2Y, err2Z, param, zz, iExtrapolatedRow, clusterState, sector, time, invAvgCharge, invCharge); - CADEBUG(printf("\t%21sResiduals %8.3f %8.3f --- Errors %8.3f %8.3f\n", "", yy - mP[0], zz - mP[1], CAMath::Sqrt(err2Y), CAMath::Sqrt(err2Z))); - if (consecGoodRows == 0) { // New segment - segmentStartChi2 = mChi2; - segmentRows = 0; - } - int32_t retValUpd = prop.Update(yy, zz, iExtrapolatedRow, param, clusterState, true, refit, err2Y, err2Z); - CADEBUG(printf("\tExtrapol. Sec %2d Row %3d Fit Alpha %8.3f , X %8.3f - Y %8.3f, Z %8.3f - QPt %7.2f (%7.2f), SP %5.2f (%5.2f), DzDs %5.2f %16s --- Cov sY %8.3f sZ %8.3f sSP %8.3f sPt %8.3f - YPt %8.3f - FErr %d\n", sector, iExtrapolatedRow, prop.GetAlpha(), mX, mP[0], mP[1], mP[4], prop.GetQPt0(), mP[2], prop.GetSinPhi0(), mP[3], "", sqrtf(mC[0]), sqrtf(mC[2]), sqrtf(mC[5]), sqrtf(mC[14]), mC[10], retValUpd)); - if (retValUpd == 0 && param.rec.tpc.rebuildTrackMaxQPtDrift > 0 && CAMath::Abs(mP[4] - qPtStart) > param.rec.tpc.rebuildTrackMaxQPtDrift * CAMath::Max(1.f, CAMath::Abs(qPtStart))) { // Track changed too much, probably following something else - merger.TrackRebuildHelperRow(iTrk, iExtrapolatedRow, tmpRows).setBest(GPUTPCGMMerger::trackRebuildHelperRow::bestRowRemoved); - revert = true; // The rejected cluster is already in the fit - break; - } - if (retValUpd != 0) { - merger.TrackRebuildHelperRow(iTrk, iExtrapolatedRow, tmpRows).setBest(GPUTPCGMMerger::trackRebuildHelperRow::bestRowRemoved); - if (retValUpd < GPUTPCGMPropagator::updateErrorClusterRejected) { - revert = true; - break; - } - found = false; // Cluster rejected by chi2, handle as missing row - } else { - segmentRows++; - } - } - if (found) { - lastFoundRow = iExtrapolatedRow; - lastFoundX = mX; - lastFoundAlpha = prop.GetAlpha(); - if (++consecGoodRows >= param.rec.tpc.rebuildTrackExtrMinConsecGoodRows) { - if (param.rec.tpc.rebuildTrackExtrMaxAvgChi2 <= 0 || mChi2 - segmentStartChi2 <= param.rec.tpc.rebuildTrackExtrMaxAvgChi2 * segmentRows) { - lastGoodRow = iExtrapolatedRow; // TODO: Could optionally store the track state here, and revert to the good state in case we reject further clusters - } - consecGoodRowsMissing = 0; - } - rowGapActive = rowGapTotal = 0; - } else { - if (++missingRowsTotal > param.rec.tpc.rebuildTrackExtrMaxMissingRows) { - break; - } - if (++rowGapTotal > param.rec.tpc.trackFollowingMaxRowGap) { - consecGoodRows = consecGoodRowsMissing = 0; - } - uint32_t pad = CAMath::Float2UIntRn(GPUTPCGeometry::LinearY2Pad(sector, iExtrapolatedRow, uncorrectedY)); - if (pad < GPUTPCGeometry::NPads(iExtrapolatedRow) && (!merger.GetConstantMem()->calibObjects.dEdxCalibContainer || !merger.GetConstantMem()->calibObjects.dEdxCalibContainer->isDead(sector, iExtrapolatedRow, pad))) { - if (rowGapActive++ >= param.rec.tpc.trackFollowingMaxRowGap) { - break; - } - if (consecGoodRowsMissing++ >= param.rec.tpc.rebuildTrackExtrConsecGoodRowsMaxGap) { - consecGoodRows = consecGoodRowsMissing = 0; - } - } - } - } - if (iExtrapolatedRow >= GPUTPCGeometry::NROWS && consecGoodRows >= param.rec.tpc.rebuildTrackExtrMinConsecGoodRowsEdge && (param.rec.tpc.rebuildTrackExtrMaxAvgChi2 <= 0 || mChi2 - segmentStartChi2 <= param.rec.tpc.rebuildTrackExtrMaxAvgChi2 * segmentRows)) { // Reached the inner / outer end of the TPC, a shorter last segment is sufficient - lastGoodRow = lastFoundRow; - } - if (lastGoodRow != lastExtrapolateRow) { - for (int32_t iRow = lastGoodRow + up; iRow != lastExtrapolateRow + up; iRow += up) { - merger.TrackRebuildHelperRow(iTrk, iRow, tmpRows).setBest(GPUTPCGMMerger::trackRebuildHelperRow::bestRowRemoved); - } - } + const uint32_t iExtrapolatedRow = ExtrapolateRows(merger, tmpRows, prop, es, sector, lastPropagateRow, up, inFlyDirection, refit, sumInvSqrtCharge, nAvgCharge, deltaZ, iTrk, adjacentInRebuild && !(param.rec.tpc.disableMarkAdjacent & 4) ? adjacentLeg : 0, param.rec.tpc.rebuildTrackMaxNonIntCov, qPtStart); + const uint8_t lastGoodRow = es.lastGoodRow, lastFoundRow = es.lastFoundRow; + const float lastFoundX = es.lastFoundX, lastFoundAlpha = es.lastFoundAlpha; + const bool revert = es.revert; if (finalOutInFit && !(param.rec.tpc.disableMarkAdjacent & 8) && iExtrapolatedRow < GPUTPCGeometry::NROWS) { // Continue the looper following from where the extrapolation stopped StoreLoopPropagation(merger, sector, iExtrapolatedRow, iTrk, up == 1, prop.GetAlpha()); CADEBUG(printf("\t\tSTORING %d extrapolated row %d sector %d out %d\n", iTrk, (int)iExtrapolatedRow, sector, up == 1)); } const int32_t rowsMoved = CAMath::Abs((int32_t)(iExtrapolatedRow < GPUTPCGeometry::NROWS ? iExtrapolatedRow : iExtrapolatedRow - up) - (int32_t)lastGoodRow); - if (revert || lastGoodRow == lastPropagateRow || lastFoundRow != lastGoodRow || (iWay == wayRebuildStart && sector != lastSector) || rowsMoved > param.rec.tpc.rebuildTrackExtrMaxRowsBack || (rowsMoved && prop.PropagateToXAlpha(lastFoundX, lastFoundAlpha, !inFlyDirection))) { // Failure, nothing accepted, rejected clusters in the fit, sector changed before the next way goes back, or too far from the last accepted cluster to go back to it - *this = paramStart; + if (revert || lastGoodRow == lastPropagateRow || lastFoundRow != lastGoodRow || (iWay == wayRebuildStart && sector != lastSector) || rowsMoved > param.rec.tpc.rebuildTrackExtrMaxRowsBack || (rowsMoved && prop.PropagateToXAlpha(lastFoundX, lastFoundAlpha, !inFlyDirection))) { + *this = paramStart; // Failure, nothing accepted, rejected clusters in the fit, sector changed before the next way goes back, or too far from the last accepted cluster to go back to it prop.SetTrack(this, alphaStart); } - } else if (finalOutInFit && !(param.rec.tpc.disableMarkAdjacent & 8) && lastUpdateRow != 255 && !retryAttempt) { - StoreLoopPropagation(merger, lastSector, lastUpdateRow, iTrk, lastUpdateRow > clusters[(iWay & 1) ? (maxN - 1) : 0].row, prop.GetAlpha()); - CADEBUG(printf("\t\tSTORING %d lastUpdateRow %d row %d out %d\n", iTrk, (int)lastUpdateRow, (int)clusters[(iWay & 1) ? (maxN - 1) : 0].row, lastUpdateRow > clusters[(iWay & 1) ? (maxN - 1) : 0].row)); + } else if (finalOutInFit && lastUpdateRow != 255 && !retryAttempt) { + int32_t loopStored = -1; // Not attempted: handle like no looper + if (!(param.rec.tpc.disableMarkAdjacent & 8)) { + loopStored = StoreLoopPropagation(merger, lastSector, lastUpdateRow, iTrk, lastUpdateRow > clusters[(iWay & 1) ? (maxN - 1) : 0].row, prop.GetAlpha()); + CADEBUG(printf("\t\tSTORING %d lastUpdateRow %d row %d out %d\n", iTrk, (int)lastUpdateRow, (int)clusters[(iWay & 1) ? (maxN - 1) : 0].row, lastUpdateRow > clusters[(iWay & 1) ? (maxN - 1) : 0].row)); + } + if (loopStored == -1 && GPUTPCGMMerger::FollowExtrapolationEnabled(param) && !fitBroken && CAMath::Abs(mP[2]) < maxSinForUpdate && mNDF > (int32_t)param.rec.tpc.rebuildTrackNonIntMinNDF && (!GPUTPCGMMerger::FollowExtrapolationAfterRebuild(param) || (track.Leg() == 0 && CAMath::Abs(GetQPt() * param.qptB5Scaler) <= param.rec.tpc.rejectQPtB5))) { + StoreFollowExtrapolation(merger, lastSector, lastPropagateRow, iTrk, (clusters[0].row < clusters[maxN - 1].row) ^ (iWay & 1), prop.GetAlpha()); // Follow the track beyond its end for adjacent clusters (same conditions as for the extrapolation), in the 5-way fit only to protect clusters, i.e. for good legs of tracks not rejected by rejectQPtB5 + } } if (param.rec.tpc.rebuildTrackInFit && iWay == wayRebuildStart + 1) { @@ -652,7 +541,7 @@ GPUdii() int32_t GPUTPCGMTrackParam::FitHit(GPUTPCGMMerger& GPUrestrict() merger } // clang-format off CADEBUG(if (!CheckCov()) GPUError("INVALID COV AFTER UPDATE!!!")); - CADEBUG(printf("\t%21sFit Alpha %8.3f , X %8.3f - Y %8.3f, Z %8.3f - QPt %7.2f (%7.2f), SP %5.2f (%5.2f), DzDs %5.2f %16s --- Cov sY %8.3f sZ %8.3f sSP %8.3f sPt %8.3f - YPt %8.3f - FErr %d %d\n", "", prop.GetAlpha(), mX, mP[0], mP[1], mP[4], prop.GetQPt0(), mP[2], prop.GetSinPhi0(), mP[3], "", sqrtf(mC[0]), sqrtf(mC[2]), sqrtf(mC[5]), sqrtf(mC[14]), mC[10], retValUpd, retValInt)); + CADEBUG(printf("\t%21sFit Alpha %8.3f , X %8.3f - Y %8.3f, Z %8.3f - QPt %7.2f (%7.2f), SP %5.2f (%5.2f), DzDs %5.2f %16s --- Cov sY %8.3f sZ %8.3f sSP %8.3f sPt %8.3f - YPt %8.3f - FErr %d %d\n", "", prop.GetAlpha(), mX, mP[0], mP[1], mP[4], prop.GetQPt0(), mP[2], prop.GetSinPhi0(), mP[3], "", sqrtf(CAMath::Max(0.f, mC[0])), sqrtf(CAMath::Max(0.f, mC[2])), sqrtf(CAMath::Max(0.f, mC[5])), sqrtf(CAMath::Max(0.f, mC[14])), mC[10], retValUpd, retValInt)); // clang-format on ConstrainSinPhi(); // TODO: Limit using ConstrainSinPhi everywhere! @@ -751,7 +640,171 @@ GPUd() int32_t GPUTPCGMTrackParam::InterpolateReject(const GPUTPCGMMerger& GPUre return 0; } -GPUdii() float GPUTPCGMTrackParam::FindBestInterpolatedHit(GPUTPCGMMerger& GPUrestrict() merger, GPUTPCGMMergerRebuildTmp* tmpRows, gputpcgmmergertypes::InterpolationErrorHit& GPUrestrict() inter, const uint8_t sector, const uint8_t row, const float deltaZ, const float sumInvSqrtCharge, const int nAvgCharge, const GPUTPCGMPropagator& GPUrestrict() prop, const int32_t iTrk, bool interOnly, int8_t doAttach, bool extrapolation) +template +GPUdi() uint32_t GPUTPCGMTrackParam::ExtrapolateRows(GPUTPCGMMerger& GPUrestrict() merger, GPUTPCGMMergerRebuildTmp* tmpRows, GPUTPCGMPropagator& GPUrestrict() prop, ExtrapolationState& GPUrestrict() s, int32_t& GPUrestrict() sector, const uint8_t startRow, const int32_t up, const bool inFlyDirection, const bool refit, float& GPUrestrict() sumInvSqrtCharge, int32_t& GPUrestrict() nAvgCharge, const float deltaZ, const int32_t iTrk, const int8_t doAttach, const float maxCov, const float qPtStart) +{ + const GPUParam& GPUrestrict() param = merger.Param(); + const float maxSinForUpdate = param.rec.tpc.maxSinPhiForFitUpdate; + uint8_t &lastGoodRow = s.lastGoodRow, &lastExtrapolateRow = s.lastExtrapolateRow, &lastFoundRow = s.lastFoundRow, &consecGoodRows = s.consecGoodRows, &segmentRows = s.segmentRows; + float &segmentStartChi2 = s.segmentStartChi2, &lastFoundX = s.lastFoundX, &lastFoundAlpha = s.lastFoundAlpha; + bool& revert = s.revert; + uint8_t rowGapActive = 0, rowGapTotal = 0, missingRowsTotal = 0, consecGoodRowsMissing = 0; + uint32_t iExtrapolatedRow = startRow + up; // uint8_t implies > 0! // TODO: Try to reduce some variables to int8/uint8 to save registers + for (; iExtrapolatedRow < GPUTPCGeometry::NROWS && (followOnly || merger.RebuildRowInRange(iTrk, iExtrapolatedRow, tmpRows)); iExtrapolatedRow += up) { + bool fail = false; + for (int32_t iAttempt = 0; iAttempt < 2; iAttempt++) { + float tmpX, tmpY, tmpZ; + if (prop.GetPropagatedYZ(GPUTPCGeometry::Row2X(iExtrapolatedRow), tmpY, tmpZ)) { + fail = revert = true; + break; + } + merger.GetConstantMem()->calibObjects.fastTransform->InverseTransformYZtoX(sector, iExtrapolatedRow, tmpY, tmpZ, tmpX); + if (prop.PropagateToXAlpha(tmpX, param.Alpha(sector), inFlyDirection)) { + fail = revert = true; + break; + } + if (CAMath::Abs(mP[2]) > maxSinForUpdate || CAMath::Abs(prop.GetSinPhi0()) >= maxSinForUpdate || mC[0] >= maxCov || mC[2] >= maxCov) { // No further clusters can be attached to the fit + fail = true; + break; + } + if (CAMath::Abs(mP[0]) > CAMath::Abs(mX) * CAMath::Tan(GPUTPCGeometry::kSectAngle() / 2.f) + 0.1f) { + if (iAttempt) { + fail = true; + break; + } + const int32_t sectorSide = sector >= (int8_t)(GPUTPCGeometry::NSECTORS / 2) ? (GPUTPCGeometry::NSECTORS / 2) : 0; + if (mP[0] > 0) { + if (++sector >= sectorSide + 18) { + sector -= 18; + } + } else { + if (--sector < sectorSide) { + sector += 18; + } + } + if (prop.RotateToAlpha(param.Alpha(sector))) { // GetPropagatedYZ / InverseTransformYZtoX of the next attempt need Y in the frame of the new sector + fail = revert = true; + break; + } + } + } + if (fail) { + break; + } + CADEBUG(printf("\tExtrapol. Sec %2d Row %3d Propaga Alpha %8.3f , X %8.3f - Y %8.3f, Z %8.3f - QPt %7.2f (%7.2f), SP %5.2f (%5.2f) --- Cov sY %8.3f sZ %8.3f sSP %8.3f sPt %8.3f - YPt %8.3f\n", sector, iExtrapolatedRow, prop.GetAlpha(), mX, mP[0], mP[1], mP[4], prop.GetQPt0(), mP[2], prop.GetSinPhi0(), sqrtf(CAMath::Max(0.f, mC[0])), sqrtf(CAMath::Max(0.f, mC[2])), sqrtf(CAMath::Max(0.f, mC[5])), sqrtf(CAMath::Max(0.f, mC[14])), mC[10])); + gputpcgmmergertypes::InterpolationErrorHit inter; + inter.markInvalid(); + float uncorrectedY; + const auto candidate = [&]() { + if constexpr (followOnly) { + GPUTPCGMMerger::trackRebuildHelperCandidate followCandidate{}; // Value 0: empty + uncorrectedY = FindBestInterpolatedHit(merger, tmpRows, inter, sector, iExtrapolatedRow, deltaZ, 0.f, 0, prop, iTrk, false, doAttach, true, &followCandidate); + return followCandidate; + } else { + uncorrectedY = FindBestInterpolatedHit(merger, tmpRows, inter, sector, iExtrapolatedRow, deltaZ, sumInvSqrtCharge, nAvgCharge, prop, iTrk, false, doAttach, true); + return *merger.ClusterCandidates(iTrk, iExtrapolatedRow, tmpRows); + } + }(); + bool found = candidate.hasCluster(); + if (found) { + lastExtrapolateRow = iExtrapolatedRow; +#if defined(DEBUG_REBUILD_MC) && !defined(GPUCA_GPUCODE) + if (merger.MergedTrackMC() && merger.GetConstantMem()->ioPtrs.clustersNative->clustersMCTruth) { + int32_t labelCorrect = GPUTPCTrkLblSearch(merger.GetConstantMem()->ioPtrs.clustersNative->clustersMCTruth->getLabels(merger.CandidateClusterId(candidate, iExtrapolatedRow)), merger.MergedTrackMC()[iTrk]); + CADEBUG(printf("\t%21sLabel correct: %d\n", "", labelCorrect)); + } +#endif + float err2Y, err2Z, xx, yy, zz; + const ClusterNative& GPUrestrict() cl = merger.GetConstantMem()->ioPtrs.clustersNative->clustersLinear[merger.CandidateClusterId(candidate, iExtrapolatedRow)]; + merger.GetConstantMem()->calibObjects.fastTransform->Transform(sector, iExtrapolatedRow, cl.getPad(), cl.getTime(), xx, yy, zz, mTOffset); + if (prop.PropagateToXAlpha(xx, prop.GetAlpha(), inFlyDirection)) { + if constexpr (!followOnly) { + merger.TrackRebuildHelperRow(iTrk, iExtrapolatedRow, tmpRows).setBest(GPUTPCGMMerger::trackRebuildHelperRow::bestRowRemoved); + } + revert = true; + break; + } + const float time = cl.getTime(); + const float invSqrtCharge = CAMath::InvSqrt(cl.qMax); + const float invCharge = 1.f / cl.qMax; + float invAvgCharge = 0.f; + if constexpr (!followOnly) { + invAvgCharge = (sumInvSqrtCharge += invSqrtCharge) / ++nAvgCharge; + invAvgCharge *= invAvgCharge; + } + const uint8_t clusterState = cl.getFlags(); + prop.GetErr2(err2Y, err2Z, param, zz, iExtrapolatedRow, clusterState, sector, time, invAvgCharge, invCharge); + CADEBUG(printf("\t%21sResiduals %8.3f %8.3f --- Errors %8.3f %8.3f\n", "", yy - mP[0], zz - mP[1], CAMath::Sqrt(err2Y), CAMath::Sqrt(err2Z))); + if (consecGoodRows == 0) { // New segment + segmentStartChi2 = mChi2; + segmentRows = 0; + } + int32_t retValUpd = prop.Update(yy, zz, iExtrapolatedRow, param, clusterState, true, refit, err2Y, err2Z); + CADEBUG(printf("\tExtrapol. Sec %2d Row %3d Fit Alpha %8.3f , X %8.3f - Y %8.3f, Z %8.3f - QPt %7.2f (%7.2f), SP %5.2f (%5.2f), DzDs %5.2f %16s --- Cov sY %8.3f sZ %8.3f sSP %8.3f sPt %8.3f - YPt %8.3f - FErr %d\n", sector, iExtrapolatedRow, prop.GetAlpha(), mX, mP[0], mP[1], mP[4], prop.GetQPt0(), mP[2], prop.GetSinPhi0(), mP[3], "", sqrtf(CAMath::Max(0.f, mC[0])), sqrtf(CAMath::Max(0.f, mC[2])), sqrtf(CAMath::Max(0.f, mC[5])), sqrtf(CAMath::Max(0.f, mC[14])), mC[10], retValUpd)); + if (retValUpd == 0 && param.rec.tpc.rebuildTrackMaxQPtDrift > 0 && CAMath::Abs(mP[4] - qPtStart) > param.rec.tpc.rebuildTrackMaxQPtDrift * CAMath::Max(1.f, CAMath::Abs(qPtStart))) { // Track changed too much, probably following something else + if constexpr (!followOnly) { + merger.TrackRebuildHelperRow(iTrk, iExtrapolatedRow, tmpRows).setBest(GPUTPCGMMerger::trackRebuildHelperRow::bestRowRemoved); + } + revert = true; // The rejected cluster is already in the fit + break; + } + if (retValUpd != 0) { + if constexpr (!followOnly) { + merger.TrackRebuildHelperRow(iTrk, iExtrapolatedRow, tmpRows).setBest(GPUTPCGMMerger::trackRebuildHelperRow::bestRowRemoved); + } + if (retValUpd < GPUTPCGMPropagator::updateErrorClusterRejected) { + revert = true; + break; + } + found = false; // Cluster rejected by chi2, handle as missing row + } else { + segmentRows++; + } + } + if (found) { + lastFoundRow = iExtrapolatedRow; + lastFoundX = mX; + lastFoundAlpha = prop.GetAlpha(); + if (++consecGoodRows >= param.rec.tpc.rebuildTrackExtrMinConsecGoodRows) { + if (param.rec.tpc.rebuildTrackExtrMaxAvgChi2 <= 0 || mChi2 - segmentStartChi2 <= param.rec.tpc.rebuildTrackExtrMaxAvgChi2 * segmentRows) { + lastGoodRow = iExtrapolatedRow; // TODO: Could optionally store the track state here, and revert to the good state in case we reject further clusters + } + consecGoodRowsMissing = 0; + } + rowGapActive = rowGapTotal = 0; + } else { + if (++missingRowsTotal > param.rec.tpc.rebuildTrackExtrMaxMissingRows) { + break; + } + if (++rowGapTotal > param.rec.tpc.trackFollowingMaxRowGap) { + consecGoodRows = consecGoodRowsMissing = 0; + } + uint32_t pad = CAMath::Float2UIntRn(GPUTPCGeometry::LinearY2Pad(sector, iExtrapolatedRow, uncorrectedY)); + if (pad < GPUTPCGeometry::NPads(iExtrapolatedRow) && (!merger.GetConstantMem()->calibObjects.dEdxCalibContainer || !merger.GetConstantMem()->calibObjects.dEdxCalibContainer->isDead(sector, iExtrapolatedRow, pad))) { + if (rowGapActive++ >= param.rec.tpc.trackFollowingMaxRowGap) { + break; + } + if (consecGoodRowsMissing++ >= param.rec.tpc.rebuildTrackExtrConsecGoodRowsMaxGap) { + consecGoodRows = consecGoodRowsMissing = 0; + } + } + } + } + if (iExtrapolatedRow >= GPUTPCGeometry::NROWS && consecGoodRows >= param.rec.tpc.rebuildTrackExtrMinConsecGoodRowsEdge && (param.rec.tpc.rebuildTrackExtrMaxAvgChi2 <= 0 || mChi2 - segmentStartChi2 <= param.rec.tpc.rebuildTrackExtrMaxAvgChi2 * segmentRows)) { // Reached the inner / outer end of the TPC, a shorter last segment is sufficient + lastGoodRow = lastFoundRow; + } + if (lastGoodRow != lastExtrapolateRow) { + for (int32_t iRow = lastGoodRow + up; iRow != lastExtrapolateRow + up; iRow += up) { + if constexpr (!followOnly) { + merger.TrackRebuildHelperRow(iTrk, iRow, tmpRows).setBest(GPUTPCGMMerger::trackRebuildHelperRow::bestRowRemoved); + } + } + } + return iExtrapolatedRow; +} + +template +GPUdii() float GPUTPCGMTrackParam::FindBestInterpolatedHit(GPUTPCGMMerger& GPUrestrict() merger, GPUTPCGMMergerRebuildTmp* tmpRows, gputpcgmmergertypes::InterpolationErrorHit& GPUrestrict() inter, const uint8_t sector, const uint8_t row, const float deltaZ, const float sumInvSqrtCharge, const int nAvgCharge, const GPUTPCGMPropagator& GPUrestrict() prop, const int32_t iTrk, bool interOnly, int8_t doAttach, bool extrapolation, C*... followCandidate) { const GPUParam& GPUrestrict() param = merger.Param(); const GPUTPCTracker& GPUrestrict() tracker = *(merger.GetConstantMem()->tpcTrackers + sector); @@ -759,13 +812,20 @@ GPUdii() float GPUTPCGMTrackParam::FindBestInterpolatedHit(GPUTPCGMMerger& GPUre GPUglobalref() const cahit2* hits = tracker.HitData(rowData); GPUglobalref() const calink* firsthit = tracker.FirstHitInBin(rowData); float uncorrectedY = -1e6f, uncorrectedZ; - const float maxNonIntCov = param.rec.tpc.rebuildTrackMaxNonIntCov; + const float maxNonIntCov = follow ? param.rec.tpc.followExtrapolationMaxCov : param.rec.tpc.rebuildTrackMaxNonIntCov; bool useInter = inter.isValid(); if (useInter && interOnly) { // One-sided from the other direction, same limit as for the current track position useInter = (float)inter.errorY < maxNonIntCov && (float)inter.errorZ < maxNonIntCov; } const bool useCurrent = !interOnly && maxNonIntCov > 0 && mC[0] < maxNonIntCov && mC[2] < maxNonIntCov && mNDF > (int32_t)param.rec.tpc.rebuildTrackNonIntMinNDF; - if ((useInter || useCurrent) && merger.RebuildRowInRange(iTrk, row, tmpRows)) { // No candidates for rows outside of the row range of the track + if ((useInter || useCurrent) && (follow || merger.RebuildRowInRange(iTrk, row, tmpRows))) { // No candidates for rows outside of the row range of the track + GPUTPCGMMerger::trackRebuildHelperCandidate* GPUrestrict() candidates; + if constexpr (follow) { + candidates = [](auto* c, auto*...) { return c; }(followCandidate...); + } else { + candidates = merger.ClusterCandidates(iTrk, row, tmpRows); + } + const int32_t nMaxCandidates = follow ? 1 : param.rec.tpc.rebuildTrackInFitClusterCandidates; const float zOffset = param.par.continuousTracking ? merger.GetConstantMem()->calibObjects.fastTransform->convVertexTimeToZOffset(sector, mTOffset, param.continuousMaxTimeBin) : 0; const float y0 = rowData.Grid().YMin(); const float stepY = rowData.HstepY(); @@ -814,7 +874,7 @@ GPUdii() float GPUTPCGMTrackParam::FindBestInterpolatedHit(GPUTPCGMMerger& GPUre } int32_t nCandidates = 0; - while (nCandidates < param.rec.tpc.rebuildTrackInFitClusterCandidates && merger.ClusterCandidates(iTrk, row, tmpRows)[nCandidates].hasCluster()) { + while (nCandidates < nMaxCandidates && candidates[nCandidates].hasCluster()) { nCandidates++; } if (CAMath::Abs(uncorrectedY) <= rowData.getTPCMaxY()) { @@ -853,8 +913,11 @@ GPUdii() float GPUTPCGMTrackParam::FindBestInterpolatedHit(GPUTPCGMMerger& GPUre const float time = cl.getTime(); const float invSqrtCharge = CAMath::InvSqrt(cl.qMax); const float invCharge = 1.f / cl.qMax; - float invAvgCharge = (sumInvSqrtCharge + invSqrtCharge) / (nAvgCharge + 1); - invAvgCharge *= invAvgCharge; + float invAvgCharge = 0.f; + if constexpr (!follow) { + invAvgCharge = (sumInvSqrtCharge + invSqrtCharge) / (nAvgCharge + 1); + invAvgCharge *= invAvgCharge; + } if (interOnly) { GPUTPCGMPropagator::GetErr2(err2YA, err2ZA, param, sinPhiMoved, mP[3], zMoved, xMoved, yMoved, row, clflags, sector, time, invAvgCharge, invCharge, false); @@ -865,31 +928,34 @@ GPUdii() float GPUTPCGMTrackParam::FindBestInterpolatedHit(GPUTPCGMMerger& GPUre const float Jw2 = 1.f / (ImC2 + err2ZA); const float chi2Y = Jw0 * dy * dy; const float chi2Z = Jw2 * dz * dz; - bool ok = !prop.RejectCluster(chi2Y * param.rec.tpc.clusterRejectChi2TolleranceY, chi2Z * param.rec.tpc.clusterRejectChi2TolleranceZ, clflags); + const float chi2Factor = follow && GPUTPCGMMerger::FollowExtrapolationAfterRebuild(param) ? param.rec.tpc.followExtrapolationChi2Factor : 1.f; + bool ok = !prop.RejectCluster(chi2Y * param.rec.tpc.clusterRejectChi2TolleranceY * chi2Factor, chi2Z * param.rec.tpc.clusterRejectChi2TolleranceZ * chi2Factor, clflags); const float err = (param.rec.tpc.rebuildTrackCandidateErrChi2 ? (chi2Y + chi2Z) : (dy * dy + dz * dz)) * errFactor; if (ok) { int32_t insert = nCandidates; for (int32_t c = 0; c < nCandidates; c++) { - if (err < (float)merger.ClusterCandidates(iTrk, row, tmpRows)[c].error) { + if (err < (float)candidates[c].error) { insert = c; break; } } - if (insert < param.rec.tpc.rebuildTrackInFitClusterCandidates) { - for (int32_t c = CAMath::Min(nCandidates, param.rec.tpc.rebuildTrackInFitClusterCandidates - 1); c > insert; c--) { - merger.ClusterCandidates(iTrk, row, tmpRows)[c] = merger.ClusterCandidates(iTrk, row, tmpRows)[c - 1]; + if (insert < nMaxCandidates) { + if constexpr (!follow) { // Only one candidate in follow mode, nothing to shift + for (int32_t c = CAMath::Min(nCandidates, nMaxCandidates - 1); c > insert; c--) { + candidates[c] = candidates[c - 1]; + } } - merger.ClusterCandidates(iTrk, row, tmpRows)[insert].set(merger.CandidateId(idOffset + ids[ih], sector, row), sector, (CAMath::half_t)err); - nCandidates += (nCandidates < param.rec.tpc.rebuildTrackInFitClusterCandidates); + candidates[insert].set(merger.CandidateId(idOffset + ids[ih], sector, row), sector, (CAMath::half_t)err); + nCandidates += (nCandidates < nMaxCandidates); } } } } } - CADEBUG(const auto* dbgCand = merger.ClusterCandidates(iTrk, row, tmpRows); for (int dbgi = 0; dbgi < nCandidates; dbgi++) { if (dbgCand[dbgi].hasCluster()) printf("\t\t\tiTrk %d Row %d Candidate %d hit %d err %f\n", iTrk, (int)row, dbgi, merger.CandidateClusterId(dbgCand[dbgi], row), dbgCand[dbgi].error); else break; }); + CADEBUG(const auto* dbgCand = candidates; for (int dbgi = 0; dbgi < nCandidates; dbgi++) { if (dbgCand[dbgi].hasCluster()) printf("\t\t\tiTrk %d Row %d Candidate %d hit %d err %f\n", iTrk, (int)row, dbgi, merger.CandidateClusterId(dbgCand[dbgi], row), (float)dbgCand[dbgi].error); else break; }); } if (nCandidates == 0 && !interOnly) { - merger.ClusterCandidates(iTrk, row, tmpRows)[0].setNoCandidate(); + candidates[0].setNoCandidate(); } } else if (doAttach && (!interOnly || inter.isValid())) { const float y = interOnly ? (float)inter.posY : mP[0], z = interOnly ? (float)inter.posZ + deltaZ : mP[1]; @@ -1210,7 +1276,7 @@ GPUd() void GPUTPCGMTrackParam::FindAdjacentClustersUncorrectedPos(const GPUTPCG GPUdii() void GPUTPCGMTrackParam::StoreOuter(gputpcgmmergertypes::GPUTPCOuterParam* outerParam, float alpha) { - CADEBUG(printf("\t%21sStorO Alpha %8.3f , X %8.3f - Y %8.3f, Z %8.3f - QPt %7.2f, SP %5.2f --- Cov sY %8.3f sZ %8.3f sSP %8.3f sPt %8.3f\n", "", alpha, mX, mP[0], mP[1], mP[4], mP[2], sqrtf(mC[0]), sqrtf(mC[2]), sqrtf(mC[5]), sqrtf(mC[14]))); + CADEBUG(printf("\t%21sStorO Alpha %8.3f , X %8.3f - Y %8.3f, Z %8.3f - QPt %7.2f, SP %5.2f --- Cov sY %8.3f sZ %8.3f sSP %8.3f sPt %8.3f\n", "", alpha, mX, mP[0], mP[1], mP[4], mP[2], sqrtf(CAMath::Max(0.f, mC[0])), sqrtf(CAMath::Max(0.f, mC[2])), sqrtf(CAMath::Max(0.f, mC[5])), sqrtf(CAMath::Max(0.f, mC[14])))); for (int32_t i = 0; i < 5; i++) { outerParam->P[i] = mP[i]; } @@ -1221,40 +1287,88 @@ GPUdii() void GPUTPCGMTrackParam::StoreOuter(gputpcgmmergertypes::GPUTPCOuterPar outerParam->alpha = alpha; } -GPUdic(0, 1) void GPUTPCGMTrackParam::StoreLoopPropagation(const GPUTPCGMMerger& GPUrestrict() merger, int32_t sector, int32_t iRow, int32_t iTrack, bool outwards, float alpha) +GPUdic(0, 1) int32_t GPUTPCGMTrackParam::StoreLoopPropagation(const GPUTPCGMMerger& GPUrestrict() merger, int32_t sector, int32_t iRow, int32_t iTrack, bool outwards, float alpha) { if (iRow == 0 || iRow == GPUTPCGeometry::NROWS - 1) { - return; + return 0; } if (CAMath::Abs(mP[2]) >= constants::MAX_SIN_PHI) { // TODO: How can we avoid this? - return; + return 0; } if (CAMath::Abs(mP[2]) < 0.75) { - return; + return -1; } if ((mP[2] * mP[4] < 0) ^ outwards) { - return; + return -1; + } + + const uint32_t n = CAMath::AtomicAdd(&merger.Memory()->nLoopData, 1u); + if (n >= merger.NMaxLoopExtrData()) { // Overlap with the FollowExtrapolation data at the end of the array is checked in the kernels + merger.raiseError(GPUErrors::ERROR_MERGER_LOOPER_OVERFLOW, n, merger.NMaxLoopExtrData(), 1); + CAMath::AtomicExch(&merger.Memory()->nLoopData, merger.NMaxLoopExtrData()); + return 0; } + GPUTPCGMLoopAndExtData data; + data.param = *this; + data.track = iTrack; + data.alpha = alpha; + data.sector = sector; + data.row = iRow; + data.outwards = outwards; + merger.LoopAndExtData()[n] = data; + return 1; +} - uint32_t nLoopData = CAMath::AtomicAdd(&merger.Memory()->nLoopData, 1u); - if (nLoopData >= merger.NMaxTracks()) { - merger.raiseError(GPUErrors::ERROR_MERGER_LOOPER_OVERFLOW, nLoopData, merger.NMaxTracks()); - CAMath::AtomicExch(&merger.Memory()->nLoopData, merger.NMaxTracks()); +GPUd() void GPUTPCGMTrackParam::StoreFollowExtrapolation(const GPUTPCGMMerger& GPUrestrict() merger, int32_t sector, int32_t iRow, int32_t iTrack, bool outwards, float alpha) +{ + const uint32_t n = CAMath::AtomicAdd(&merger.Memory()->nFollowExtrapolationData, 1u); + if (n >= merger.NMaxLoopExtrData()) { + merger.raiseError(GPUErrors::ERROR_MERGER_LOOPER_OVERFLOW, n, merger.NMaxLoopExtrData(), 2); + CAMath::AtomicExch(&merger.Memory()->nFollowExtrapolationData, merger.NMaxLoopExtrData()); return; } - GPUTPCGMLoopData data; + GPUTPCGMLoopAndExtData& GPUrestrict() data = merger.LoopAndExtData()[merger.NMaxLoopExtrData() - 1 - n]; data.param = *this; data.track = iTrack; data.alpha = alpha; data.sector = sector; data.row = iRow; data.outwards = outwards; - merger.LoopData()[nLoopData] = data; +} + +GPUdii() void GPUTPCGMTrackParam::FollowExtrapolation(GPUTPCGMMerger& GPUrestrict() merger, int32_t idx) +{ + const GPUTPCGMLoopAndExtData& GPUrestrict() data = merger.LoopAndExtData()[merger.NMaxLoopExtrData() - merger.Memory()->nFollowExtrapolationData + idx]; + const GPUTPCGMMergedTrack& GPUrestrict() track = merger.MergedTracks()[data.track]; + if (!track.OK()) { + return; + } + const GPUParam& GPUrestrict() param = merger.Param(); + GPUTPCGMPropagator prop; // Settings as in the extrapolation of the fit, which runs in the ways before the final one + prop.SetMaterialTPC(); + prop.SetPolynomialField(¶m.polynomialField); + prop.SetMaxSinPhi(constants::MAX_SIN_PHI); + prop.SetSeedingErrors(false); + prop.SetFitInProjections(true); + prop.SetPropagateBzOnly(param.rec.fitPropagateBzOnly == -1 ? true : param.rec.fitPropagateBzOnly); + prop.SetMatLUT(nullptr); + GPUTPCGMTrackParam t = data.param; + prop.SetTrack(&t, data.alpha); + ExtrapolationState es; + es.lastGoodRow = es.lastExtrapolateRow = es.lastFoundRow = data.row; + es.consecGoodRows = param.rec.tpc.rebuildTrackExtrMinConsecGoodRows; // Assume the last hit was accepted in the fit + es.segmentRows = 0; + es.segmentStartChi2 = t.mChi2; + es.lastFoundX = es.lastFoundAlpha = 0.f; + es.revert = false; + int32_t sector = data.sector, nAvgCharge = 0; + float sumInvSqrtCharge = 0.f; // Not used by ExtrapolateRows + t.ExtrapolateRows(merger, nullptr, prop, es, sector, data.row, data.outwards ? 1 : -1, (track.Leg() & 1) ^ data.outwards, true, sumInvSqrtCharge, nAvgCharge, 0.f, data.track, 1 + (track.Leg() == 0), param.rec.tpc.followExtrapolationMaxCov, t.mP[4]); } GPUdii() void GPUTPCGMTrackParam::PropagateLooper(const GPUTPCGMMerger& GPUrestrict() merger, int32_t loopIdx) { - GPUTPCGMLoopData& data = merger.LoopData()[loopIdx]; + const GPUTPCGMLoopAndExtData& GPUrestrict() data = merger.LoopAndExtData()[loopIdx]; if (!merger.MergedTracks()[data.track].OK()) { return; } @@ -1267,11 +1381,12 @@ GPUdii() void GPUTPCGMTrackParam::PropagateLooper(const GPUTPCGMMerger& GPUrestr prop.SetFitInProjections(true); prop.SetPropagateBzOnly(false); - prop.SetTrack(&data.param, data.alpha); + GPUTPCGMTrackParam t = data.param; // Work on a local copy, not in global memory + prop.SetTrack(&t, data.alpha); if (merger.Param().rec.tpc.looperFollowMode == 1) { - data.param.FindAdjacentClustersLooperFollow(merger, prop, data.sector, data.track, data.outwards); + t.FindAdjacentClustersLooperFollow(merger, prop, data.sector, data.track, data.outwards); } else { - data.param.FindAdjacentClustersLooperMirror(merger, data.sector, data.row, data.track, data.outwards, prop); + t.FindAdjacentClustersLooperMirror(merger, data.sector, data.row, data.track, data.outwards, prop); } } diff --git a/GPU/GPUTracking/Merger/GPUTPCGMTrackParam.h b/GPU/GPUTracking/Merger/GPUTPCGMTrackParam.h index 61a3331a79c08..591d2facf440a 100644 --- a/GPU/GPUTracking/Merger/GPUTPCGMTrackParam.h +++ b/GPU/GPUTracking/Merger/GPUTPCGMTrackParam.h @@ -160,22 +160,28 @@ class GPUTPCGMTrackParam GPUd() int32_t FitHit(GPUTPCGMMerger& merger, GPUTPCGMMergerRebuildTmp* tmpRows, const int32_t iTrk, const GPUTPCGMMergedTrack& track, const float xx, const float yy, const float zz, const uint8_t clusterState, const float clAlpha, const int32_t iWay, const bool inFlyDirection, float& deltaZ, float& lastUpdateX, GPUTPCGMMergedTrackHit* clusters, GPUTPCGMPropagator& prop, gputpcgmmergertypes::InterpolationErrorHit& inter, GPUdEdx& dEdx, GPUdEdx& dEdxAlt, float& sumInvSqrtCharge, int32_t& nAvgCharge, const int32_t ihit, const int32_t ihitMergeFirst, const bool allowChangeClusters, const bool refit, const bool finalFit, int32_t& nMissed, int32_t& nMissedHard, float uncorrectedY, bool retryAttempt); GPUd() void FitAddRow(const int32_t iRow, const uint8_t sector, const int32_t iTrk, const GPUTPCGMMergedTrack& track, GPUTPCGMPropagator& prop, const bool inFlyDirection, GPUTPCGMMerger& merger, GPUTPCGMMergerRebuildTmp* tmpRows, uint8_t* dEdxSubThresholdRow, const bool dodEdx, const bool doAttach, const uint8_t doInterpolate, gputpcgmmergertypes::InterpolationErrorHit& inter, const float deltaZ, const float sumInvSqrtCharge, const int32_t nAvgCharge); GPUd() void HandleCrossCE(const GPUParam& param, const uint8_t sector, const uint8_t& lastSector); - GPUd() static void MarkAdjacentSearch(const GPUParam& param, int32_t iWay, gputpcgmmergertypes::InterpolationErrorHit& inter); // For hits the interpolation rejection way skips + GPUd() static void MarkAdjacentSearch(const GPUParam& param, int32_t iWay, gputpcgmmergertypes::InterpolationErrorHit& inter); template GPUd() static void RefitTrack(GPUTPCGMMergedTrack& track, int32_t iTrk, GPUTPCGMMerger& merger); GPUd() void MoveToReference(GPUTPCGMPropagator& prop, const GPUParam& param, float& alpha); GPUd() void MirrorTo(GPUTPCGMPropagator& prop, float toY, float toZ, bool inFlyDirection, const GPUParam& param, uint8_t row, uint8_t clusterState, bool mirrorParameters, int8_t sector); GPUd() int32_t MergeDoubleRowClusters(int32_t& ihit, int32_t wayDirection, GPUTPCGMMergedTrackHit* clusters, const GPUTPCGMMerger& merger, GPUTPCGMPropagator& prop, float& xx, float& yy, float& zz, int32_t maxN, float clAlpha, uint8_t& clusterState, const bool markReject); - GPUd() int32_t InterpolateReject(const GPUTPCGMMerger& merger, const GPUTPCGMPropagator& prop, float posY, float posZ, int16_t clusterState, gputpcgmmergertypes::InterpolationErrorHit* inter, float err2Y, float err2Z, float deltaZ, uint8_t sector, uint8_t row, int32_t iTrk, int8_t doAttach); // doAttach: search adjacent clusters at the interpolated position (1 / 2 = good leg), marks inter as done - GPUd() float FindBestInterpolatedHit(GPUTPCGMMerger& merger, GPUTPCGMMergerRebuildTmp* tmpRows, gputpcgmmergertypes::InterpolationErrorHit& inter, const uint8_t sector, const uint8_t row, const float deltaZ, const float sumInvSqrtCharge, const int nAvgCharge, const GPUTPCGMPropagator& prop, const int32_t iTrk, bool interOnly, int8_t doAttach, bool extrapolation = false); + GPUd() int32_t InterpolateReject(const GPUTPCGMMerger& merger, const GPUTPCGMPropagator& prop, float posY, float posZ, int16_t clusterState, gputpcgmmergertypes::InterpolationErrorHit* inter, float err2Y, float err2Z, float deltaZ, uint8_t sector, uint8_t row, int32_t iTrk, int8_t doAttach); + template + GPUd() float FindBestInterpolatedHit(GPUTPCGMMerger& merger, GPUTPCGMMergerRebuildTmp* tmpRows, gputpcgmmergertypes::InterpolationErrorHit& inter, const uint8_t sector, const uint8_t row, const float deltaZ, const float sumInvSqrtCharge, const int nAvgCharge, const GPUTPCGMPropagator& prop, const int32_t iTrk, bool interOnly, int8_t doAttach, bool extrapolation = false, C*... followCandidate); + struct ExtrapolationState; + template + GPUd() uint32_t ExtrapolateRows(GPUTPCGMMerger& merger, GPUTPCGMMergerRebuildTmp* tmpRows, GPUTPCGMPropagator& prop, ExtrapolationState& s, int32_t& sector, const uint8_t startRow, const int32_t up, const bool inFlyDirection, const bool refit, float& sumInvSqrtCharge, int32_t& nAvgCharge, const float deltaZ, const int32_t iTrk, const int8_t doAttach, const float maxCov, const float qPtStart); GPUd() void InterpolateMissingRows(GPUTPCGMMerger& merger, GPUTPCGMMergerRebuildTmp* tmpRows, gputpcgmmergertypes::InterpolationErrors& interpolation, GPUTPCGMMergedTrackHit* clusters, int32_t ihit, int32_t interpolationIndex, int32_t lastRow, const float deltaZ, const float sumInvSqrtCharge, const int32_t nAvgCharge, const GPUTPCGMPropagator& prop, const int32_t iTrk, const int8_t doAttach); GPUd() float FindAdjacentClusters(const GPUTPCGMMerger& GPUrestrict() merger, int32_t sector, int32_t iRow, int32_t iTrack, bool goodLeg, GPUTPCGMPropagator& prop); // Returns uncorrectedY for later use GPUd() float FindAdjacentClusters(const GPUTPCGMMerger& GPUrestrict() merger, int32_t sector, int32_t iRow, int32_t iTrack, bool goodLeg, float Y, float Z); - GPUd() void FindAdjacentClustersUncorrectedPos(const GPUTPCGMMerger& GPUrestrict() merger, int32_t sector, int32_t iRow, int32_t iTrack, bool goodLeg, float uncorrectedY, float uncorrectedZ, float Z, float err2Y, float err2Z); // err2Y / err2Z: cluster error + track error + GPUd() void FindAdjacentClustersUncorrectedPos(const GPUTPCGMMerger& GPUrestrict() merger, int32_t sector, int32_t iRow, int32_t iTrack, bool goodLeg, float uncorrectedY, float uncorrectedZ, float Z, float err2Y, float err2Z); GPUd() void FindAdjacentClustersLooperMirror(const GPUTPCGMMerger& GPUrestrict() merger, int32_t sector, int32_t iRow, const int32_t iTrack, const bool up, const GPUTPCGMPropagator& prop); GPUd() void FindAdjacentClustersLooperFollow(const GPUTPCGMMerger& GPUrestrict() merger, GPUTPCGMPropagator& prop, int32_t sector, const int32_t iTrack, const bool up); - GPUd() void StoreLoopPropagation(const GPUTPCGMMerger& GPUrestrict() merger, int32_t sector, int32_t iRow, int32_t iTrack, bool outwards, float alpha); + GPUd() int32_t StoreLoopPropagation(const GPUTPCGMMerger& GPUrestrict() merger, int32_t sector, int32_t iRow, int32_t iTrack, bool outwards, float alpha); + GPUd() void StoreFollowExtrapolation(const GPUTPCGMMerger& GPUrestrict() merger, int32_t sector, int32_t iRow, int32_t iTrack, bool outwards, float alpha); + GPUd() static void FollowExtrapolation(GPUTPCGMMerger& merger, int32_t idx); GPUd() void StoreOuter(gputpcgmmergertypes::GPUTPCOuterParam* outerParam, float alpha); GPUd() static void PropagateLooper(const GPUTPCGMMerger& merger, int32_t loopIdx); @@ -243,7 +249,7 @@ class GPUTPCGMTrackParam int32_t mNDF; // the Number of Degrees of Freedom }; -struct GPUTPCGMLoopData { +struct GPUTPCGMLoopAndExtData { // Track end for FollowLoopers (stored from the start of the array) or FollowExtrapolation (from the end) GPUTPCGMTrackParam param; uint32_t track; float alpha; diff --git a/GPU/GPUTracking/Standalone/Benchmark/standalone.cxx b/GPU/GPUTracking/Standalone/Benchmark/standalone.cxx index e22704c37d4b9..e12c948b3d6b3 100644 --- a/GPU/GPUTracking/Standalone/Benchmark/standalone.cxx +++ b/GPU/GPUTracking/Standalone/Benchmark/standalone.cxx @@ -213,6 +213,10 @@ int32_t ReadConfiguration(int argc, char** argv) printf("Cannot run asynchronous processing with double pipeline\n"); return 1; } + if (configStandalone.dumpEvents == 2 && !configStandalone.testSyncAsync) { + printf("dumpEvents 2 requires syncAsync\n"); + return 1; + } if (configStandalone.testSyncAsyncMC) { if (!configStandalone.testSyncAsync || configStandalone.QA.noMC) { printf("testSyncAsyncMC requires syncAsync and cannot be used with QA.noMC\n"); @@ -559,8 +563,6 @@ int32_t SetupReconstruction() if (recSetAsync.tpc.rejectionStrategy >= GPUSettings::RejectionStrategyB) { procSetAsync.tpcInputWithClusterRejection = 1; } - recSetAsync.tpc.disableMarkAdjacent = 0xFF; - recSetAsync.maxTrackQPtB5 = CAMath::Min(recSetAsync.maxTrackQPtB5, recSetAsync.tpc.rejectQPtB5); GPUChainTracking::ApplySyncSettings(procSetAsync, recSetAsync, stepsAsync.steps, false, true, configStandalone.rundEdx); finalizeSteps(stepsAsync, procSetAsync); recAsync->SetSettings(&grp, &recSetAsync, &procSetAsync, &stepsAsync); @@ -800,6 +802,17 @@ int32_t RunBenchmark(GPUReconstruction* recUse, GPUChainTracking* chainTrackingU if (configStandalone.testSyncAsyncMC) { chainTrackingAsync->GenerateCompressionMCLabels(*chainTracking); } + if (configStandalone.dumpEvents == 2 && iRun == 0) { + char fname[1024]; + snprintf(fname, 1024, "event.%d.dump", iEvent - configStandalone.StartEvent); + chainTrackingAsync->DumpData(fname); + if (iEvent == configStandalone.StartEvent) { + GPUSettingsGRP grpAsync = recAsync->GetGRPSettings(); // Input are the compressed clusters + grpAsync.needsClusterer = 0; + grpAsync.doCompClusterDecode = 1; + recAsync->DumpSettings("", &grpAsync); + } + } if (configStandalone.runsInit > 0 && configStandalone.proc.debugCSV.empty()) { recAsync->SetResetTimers(iRun < configStandalone.runsInit); } @@ -986,7 +999,7 @@ int32_t main(int argc, char** argv) if (LoadEvent(iEvent, 0)) { goto breakrun; } - if (configStandalone.dumpEvents) { + if (configStandalone.dumpEvents == 1) { char fname[1024]; snprintf(fname, 1024, "event.%d.dump", nEventsProcessed); chainTracking->DumpData(fname); diff --git a/GPU/GPUTracking/TPCClusterFinder/CfArray2D.h b/GPU/GPUTracking/TPCClusterFinder/CfArray2D.h index e61ec532bf7e0..dd5600a8a8cbf 100644 --- a/GPU/GPUTracking/TPCClusterFinder/CfArray2D.h +++ b/GPU/GPUTracking/TPCClusterFinder/CfArray2D.h @@ -49,7 +49,7 @@ class TilingLayout enum { Height = Grid::Height, Width = Grid::Width, - WidthInTiles = (TPC_CLUSTERER_STRIDED_PAD_COUNT + Width - 1) / Width, + WidthInTiles = (tpccf::TPC_CLUSTERER_STRIDED_PAD_COUNT + Width - 1) / Width, }; GPUdi() static tpccf::SizeT idx(const CfChargePos& p) @@ -65,7 +65,7 @@ class TilingLayout GPUd() static size_t items(size_t fragmentLen) { - return (TPC_CLUSTERER_STRIDED_PAD_COUNT + Width - 1) / Width * Width * (TPC_MAX_FRAGMENT_LEN_PADDED(fragmentLen) + Height - 1) / Height * Height; + return (tpccf::TPC_CLUSTERER_STRIDED_PAD_COUNT + Width - 1) / Width * Width * (tpccf::TPC_MAX_FRAGMENT_LEN_PADDED(fragmentLen) + Height - 1) / Height * Height; } }; @@ -74,12 +74,12 @@ class LinearLayout public: GPUdi() static tpccf::SizeT idx(const CfChargePos& p) { - return TPC_CLUSTERER_STRIDED_PAD_COUNT * p.timePadded + p.gpad; + return tpccf::TPC_CLUSTERER_STRIDED_PAD_COUNT * p.timePadded + p.gpad; } GPUd() static size_t items(size_t fragmentLen) { - return TPC_CLUSTERER_STRIDED_PAD_COUNT * TPC_MAX_FRAGMENT_LEN_PADDED(fragmentLen); + return tpccf::TPC_CLUSTERER_STRIDED_PAD_COUNT * tpccf::TPC_MAX_FRAGMENT_LEN_PADDED(fragmentLen); } }; @@ -110,13 +110,19 @@ struct GridSize<4> { }; }; -#if defined(CHARGEMAP_TILING_LAYOUT) +template +struct TPCMapMemoryLayoutSelector; template -using TPCMapMemoryLayout = TilingLayout>; -#else +struct TPCMapMemoryLayoutSelector<0, T> { + using type = LinearLayout; +}; template -using TPCMapMemoryLayout = LinearLayout; -#endif +struct TPCMapMemoryLayoutSelector<1, T> { + using type = TilingLayout>; +}; + +template +using TPCMapMemoryLayout = typename TPCMapMemoryLayoutSelector::type; template using CfArray2D = AbstractCfArray2D>; diff --git a/GPU/GPUTracking/TPCClusterFinder/CfChargePos.h b/GPU/GPUTracking/TPCClusterFinder/CfChargePos.h index 38d6c78d1bb6e..f7b02d3e421ca 100644 --- a/GPU/GPUTracking/TPCClusterFinder/CfChargePos.h +++ b/GPU/GPUTracking/TPCClusterFinder/CfChargePos.h @@ -22,7 +22,7 @@ namespace o2::gpu { -#define INVALID_TIME_BIN (-GPUCF_PADDING_TIME - 1) +#define INVALID_TIME_BIN (-o2::gpu::tpccf::GPUCF_PADDING_TIME - 1) struct CfChargePos { tpccf::GlobalPad gpad; @@ -31,11 +31,11 @@ struct CfChargePos { GPUdDefault() CfChargePos() = default; constexpr GPUhdi() CfChargePos(tpccf::Row row, tpccf::Pad pad, tpccf::TPCFragmentTime t) - : gpad(tpcGlobalPadIdx(row, pad)), timePadded(t + GPUCF_PADDING_TIME) + : gpad(tpcGlobalPadIdx(row, pad)), timePadded(t + tpccf::GPUCF_PADDING_TIME) { } #ifdef __METAL__ - constexpr GPUhdi() CfChargePos(tpccf::Row row, tpccf::Pad pad, tpccf::TPCFragmentTime t) constant : gpad(tpcGlobalPadIdx(row, pad)), timePadded(t + GPUCF_PADDING_TIME) {} + constexpr GPUhdi() CfChargePos(tpccf::Row row, tpccf::Pad pad, tpccf::TPCFragmentTime t) constant : gpad(tpcGlobalPadIdx(row, pad)), timePadded(t + tpccf::GPUCF_PADDING_TIME) {} #endif GPUdi() CfChargePos(const tpccf::GlobalPad& p, const tpccf::TPCFragmentTime& t) : gpad(p), timePadded(t) {} @@ -47,9 +47,9 @@ struct CfChargePos { GPUdi() bool valid() const { return timePadded >= 0; } - GPUdi() tpccf::Row row() const { return gpad / TPC_CLUSTERER_ROW_STRIDE; } - GPUdi() tpccf::Pad pad() const { return gpad % TPC_CLUSTERER_ROW_STRIDE - GPUCF_PADDING_PAD; } - GPUdi() tpccf::TPCFragmentTime time() const { return timePadded - GPUCF_PADDING_TIME; } + GPUdi() tpccf::Row row() const { return gpad / tpccf::TPC_CLUSTERER_ROW_STRIDE; } + GPUdi() tpccf::Pad pad() const { return gpad % tpccf::TPC_CLUSTERER_ROW_STRIDE - tpccf::GPUCF_PADDING_PAD; } + GPUdi() tpccf::TPCFragmentTime time() const { return timePadded - tpccf::GPUCF_PADDING_TIME; } GPUdi() tpccf::TPCFragmentTime globalTime() const { return timePadded; } private: @@ -57,7 +57,7 @@ struct CfChargePos { // index between 0 and TPC_NUM_OF_PADS. static constexpr GPUdi() tpccf::GlobalPad tpcGlobalPadIdx(tpccf::Row row, tpccf::Pad pad) { - return TPC_CLUSTERER_ROW_STRIDE * row + pad + GPUCF_PADDING_PAD; + return tpccf::TPC_CLUSTERER_ROW_STRIDE * row + pad + tpccf::GPUCF_PADDING_PAD; } }; diff --git a/GPU/GPUTracking/TPCClusterFinder/GPUTPCCFChargeMapFiller.cxx b/GPU/GPUTracking/TPCClusterFinder/GPUTPCCFChargeMapFiller.cxx index 85d230a00c0df..c523353471ba0 100644 --- a/GPU/GPUTracking/TPCClusterFinder/GPUTPCCFChargeMapFiller.cxx +++ b/GPU/GPUTracking/TPCClusterFinder/GPUTPCCFChargeMapFiller.cxx @@ -37,10 +37,10 @@ GPUd() void GPUTPCCFChargeMapFiller::fillIndexMapImpl(int32_t nBlocks, int32_t n if (idx >= maxDigit) { return; } - CPU_ONLY(idx += frag.digitsStart); - CPU_ONLY(tpc::Digit digit = digits[idx]); - CPU_ONLY(CfChargePos pos(digit.getRow(), digit.getPad(), frag.toLocal(digit.getTimeStamp()))); - CPU_ONLY(indexMap.safeWrite(pos, idx)); + GPUCA_IGNORE_ON_GPU(idx += frag.digitsStart); + GPUCA_IGNORE_ON_GPU(tpc::Digit digit = digits[idx]); + GPUCA_IGNORE_ON_GPU(CfChargePos pos(digit.getRow(), digit.getPad(), frag.toLocal(digit.getTimeStamp()))); + GPUCA_IGNORE_ON_GPU(indexMap.safeWrite(pos, idx)); } template <> diff --git a/GPU/GPUTracking/TPCClusterFinder/GPUTPCCFCheckPadBaseline.cxx b/GPU/GPUTracking/TPCClusterFinder/GPUTPCCFCheckPadBaseline.cxx index dabd79c5601bd..dd015f3bc61e9 100644 --- a/GPU/GPUTracking/TPCClusterFinder/GPUTPCCFCheckPadBaseline.cxx +++ b/GPU/GPUTracking/TPCClusterFinder/GPUTPCCFCheckPadBaseline.cxx @@ -840,7 +840,7 @@ GPUd() void GPUTPCCFHIPClusterizer::Thread<0>(int32_t nBlocks, int32_t nThreads, continue; } - CPU_ONLY(auto labelAcc = MCLabelAccumulator{clusterer}); + GPUCA_IGNORE_ON_GPU(auto labelAcc = MCLabelAccumulator{clusterer}); uint16_t padMin = 0xFFFF, padMax = 0; @@ -870,7 +870,7 @@ GPUd() void GPUTPCCFHIPClusterizer::Thread<0>(int32_t nBlocks, int32_t nThreads, padMin = CAMath::Min(padMin, tail->pad); padMax = CAMath::Max(padMax, tail->pad); - CPU_ONLY(labelAcc.collectTail(row, tail->pad, tail->tailStart, tail->tailEnd)); + GPUCA_IGNORE_ON_GPU(labelAcc.collectTail(row, tail->pad, tail->tailStart, tail->tailEnd)); } const float weightSum = CAMath::Max(qTot, 1.f); @@ -914,7 +914,7 @@ GPUd() void GPUTPCCFHIPClusterizer::Thread<0>(int32_t nBlocks, int32_t nThreads, index = clusterPosInRow[iTail]; } - CPU_ONLY(labelAcc.commit(row, index, clusterer.mNMaxClusterPerRow)); + GPUCA_IGNORE_ON_GPU(labelAcc.commit(row, index, clusterer.mNMaxClusterPerRow)); } } // for (uint32_t iTail = iThread + 1; iTail <= nTails; iTail += nThreads) diff --git a/GPU/GPUTracking/TPCClusterFinder/GPUTPCCFClusterizer.cxx b/GPU/GPUTracking/TPCClusterFinder/GPUTPCCFClusterizer.cxx index 15d0106e1bb22..a83ec729825e8 100644 --- a/GPU/GPUTracking/TPCClusterFinder/GPUTPCCFClusterizer.cxx +++ b/GPU/GPUTracking/TPCClusterFinder/GPUTPCCFClusterizer.cxx @@ -31,9 +31,11 @@ template <> GPUdii() void GPUTPCCFClusterizer::Thread<0>(int32_t nBlocks, int32_t nThreads, int32_t iBlock, int32_t iThread, GPUSharedMemory& smem, processorType& clusterer, int8_t onlyMC) { CfArray2D chargeMap(reinterpret_cast(clusterer.mPchargeMap)); - CPU_ONLY(MCLabelAccumulator labelAcc(clusterer)); + MCLabelAccumulator* labelPtr = nullptr; + GPUCA_IGNORE_ON_GPU(MCLabelAccumulator labelAcc(clusterer)); + GPUCA_IGNORE_ON_GPU(labelPtr = &labelAcc); tpc::ClusterNative* clusterOut = onlyMC ? nullptr : clusterer.mPclusterByRow; - GPUTPCCFClusterizer::computeClustersImpl(get_num_groups(0), get_local_size(0), get_group_id(0), get_local_id(0), clusterer, clusterer.mPmemory->frag, smem, chargeMap, clusterer.mPfilteredPeakPositions, clusterer.Param().rec, CPU_PTR(&labelAcc), clusterer.mPmemory->counters.nClusters, clusterer.mNMaxClusterPerRow, clusterer.mPclusterInRow, clusterOut, clusterer.mPclusterPosInRow, true); + GPUTPCCFClusterizer::computeClustersImpl(get_num_groups(0), get_local_size(0), get_group_id(0), get_local_id(0), clusterer, clusterer.mPmemory->frag, smem, chargeMap, clusterer.mPfilteredPeakPositions, clusterer.Param().rec, labelPtr, clusterer.mPmemory->counters.nClusters, clusterer.mNMaxClusterPerRow, clusterer.mPclusterInRow, clusterOut, clusterer.mPclusterPosInRow, true); } diff --git a/GPU/GPUTracking/TPCClusterFinder/GPUTPCCFClusterizer.h b/GPU/GPUTracking/TPCClusterFinder/GPUTPCCFClusterizer.h index b04b37bc64975..e9a3b230dd959 100644 --- a/GPU/GPUTracking/TPCClusterFinder/GPUTPCCFClusterizer.h +++ b/GPU/GPUTracking/TPCClusterFinder/GPUTPCCFClusterizer.h @@ -39,7 +39,7 @@ class GPUTPCCFClusterizer : public GPUKernelTemplate static GPUglobalconstexpr() size_t SCRATCH_PAD_WORK_GROUP_SIZE = GPUCA_GET_THREAD_COUNT(GPUCA_LB_GPUTPCCFClusterizer); struct GPUSharedMemory { CfChargePos posBcast[SCRATCH_PAD_WORK_GROUP_SIZE]; - PackedCharge buf[SCRATCH_PAD_WORK_GROUP_SIZE * SCRATCH_PAD_BUILD_N]; + PackedCharge buf[SCRATCH_PAD_WORK_GROUP_SIZE * tpccf::SCRATCH_PAD_BUILD_N]; uint8_t innerAboveThreshold[SCRATCH_PAD_WORK_GROUP_SIZE]; }; diff --git a/GPU/GPUTracking/TPCClusterFinder/GPUTPCCFClusterizer.inc b/GPU/GPUTracking/TPCClusterFinder/GPUTPCCFClusterizer.inc index b1c1aef196e37..bd575180ea18b 100644 --- a/GPU/GPUTracking/TPCClusterFinder/GPUTPCCFClusterizer.inc +++ b/GPU/GPUTracking/TPCClusterFinder/GPUTPCCFClusterizer.inc @@ -39,7 +39,7 @@ GPUdii() void GPUTPCCFClusterizer::computeClustersImpl(int32_t nBlocks, int32_t Charge charge = chargeMap[pos].unpack(); ClusterAccumulator pc; - CPU_ONLY(labelAcc->collect(pos, charge)); + GPUCA_IGNORE_ON_GPU(labelAcc->collect(pos, charge)); buildCluster( calib, @@ -90,7 +90,7 @@ GPUdii() void GPUTPCCFClusterizer::computeClustersImpl(int32_t nBlocks, int32_t rowIndex = clusterPosInRow[idx]; } - CPU_ONLY(labelAcc->commit(pos.row(), rowIndex, maxClusterPerRow)); + GPUCA_IGNORE_ON_GPU(labelAcc->commit(pos.row(), rowIndex, maxClusterPerRow)); } GPUdii() void GPUTPCCFClusterizer::updateClusterInner( @@ -112,7 +112,7 @@ GPUdii() void GPUTPCCFClusterizer::updateClusterInner( PackedCharge p = buf[N * lid + i]; Charge q = cluster->updateInner(p, d); - CPU_ONLY(labelAcc->collect(pos.delta(d), q)); + GPUCA_IGNORE_ON_GPU(labelAcc->collect(pos.delta(d), q)); aboveThreshold |= (uint8_t(q > calib.tpc.cfInnerThreshold) << i); } @@ -139,7 +139,7 @@ GPUdii() void GPUTPCCFClusterizer::updateClusterOuter( Delta2 d = cfconsts::OuterNeighbors[i]; [[maybe_unused]] Charge q = cluster->updateOuter(p, d); - CPU_ONLY(labelAcc->collect(pos.delta(d), q)); + GPUCA_IGNORE_ON_GPU(labelAcc->collect(pos.delta(d), q)); } } diff --git a/GPU/GPUTracking/TPCClusterFinder/GPUTPCCFDeconvolution.h b/GPU/GPUTracking/TPCClusterFinder/GPUTPCCFDeconvolution.h index d6a4acb7ddb3c..0f3ccfbe2cd80 100644 --- a/GPU/GPUTracking/TPCClusterFinder/GPUTPCCFDeconvolution.h +++ b/GPU/GPUTracking/TPCClusterFinder/GPUTPCCFDeconvolution.h @@ -33,7 +33,7 @@ class GPUTPCCFDeconvolution : public GPUKernelTemplate struct GPUSharedMemory : public GPUKernelTemplate::GPUSharedMemoryScan64 { CfChargePos posBcast1[SCRATCH_PAD_WORK_GROUP_SIZE]; uint8_t aboveThresholdBcast[SCRATCH_PAD_WORK_GROUP_SIZE]; - uint8_t buf[SCRATCH_PAD_WORK_GROUP_SIZE * SCRATCH_PAD_COUNT_N]; + uint8_t buf[SCRATCH_PAD_WORK_GROUP_SIZE * tpccf::SCRATCH_PAD_COUNT_N]; }; typedef GPUTPCClusterFinder processorType; diff --git a/GPU/GPUTracking/TPCClusterFinder/GPUTPCCFNoiseSuppression.h b/GPU/GPUTracking/TPCClusterFinder/GPUTPCCFNoiseSuppression.h index 9f1788cfef568..02b86398ab586 100644 --- a/GPU/GPUTracking/TPCClusterFinder/GPUTPCCFNoiseSuppression.h +++ b/GPU/GPUTracking/TPCClusterFinder/GPUTPCCFNoiseSuppression.h @@ -38,7 +38,7 @@ class GPUTPCCFNoiseSuppression : public GPUKernelTemplate struct GPUSharedMemory { CfChargePos posBcast[SCRATCH_PAD_WORK_GROUP_SIZE]; - PackedCharge buf[SCRATCH_PAD_WORK_GROUP_SIZE * SCRATCH_PAD_NOISE_N]; + PackedCharge buf[SCRATCH_PAD_WORK_GROUP_SIZE * tpccf::SCRATCH_PAD_NOISE_N]; }; typedef GPUTPCClusterFinder processorType; diff --git a/GPU/GPUTracking/TPCClusterFinder/GPUTPCCFPeakFinder.h b/GPU/GPUTracking/TPCClusterFinder/GPUTPCCFPeakFinder.h index 93727319b86a8..32db890750254 100644 --- a/GPU/GPUTracking/TPCClusterFinder/GPUTPCCFPeakFinder.h +++ b/GPU/GPUTracking/TPCClusterFinder/GPUTPCCFPeakFinder.h @@ -33,7 +33,7 @@ class GPUTPCCFPeakFinder : public GPUKernelTemplate static GPUglobalconstexpr() size_t SCRATCH_PAD_WORK_GROUP_SIZE = GPUCA_GET_THREAD_COUNT(GPUCA_LB_GPUTPCCFPeakFinder); struct GPUSharedMemory : public GPUKernelTemplate::GPUSharedMemoryScan64 { CfChargePos posBcast[SCRATCH_PAD_WORK_GROUP_SIZE]; - PackedCharge buf[SCRATCH_PAD_WORK_GROUP_SIZE * SCRATCH_PAD_SEARCH_N]; + PackedCharge buf[SCRATCH_PAD_WORK_GROUP_SIZE * tpccf::SCRATCH_PAD_SEARCH_N]; }; typedef GPUTPCClusterFinder processorType; diff --git a/GPU/GPUTracking/TPCClusterFinder/GPUTPCClusterFinder.cxx b/GPU/GPUTracking/TPCClusterFinder/GPUTPCClusterFinder.cxx index 80415dc043bf8..8c69b7b2d72b5 100644 --- a/GPU/GPUTracking/TPCClusterFinder/GPUTPCClusterFinder.cxx +++ b/GPU/GPUTracking/TPCClusterFinder/GPUTPCClusterFinder.cxx @@ -82,7 +82,7 @@ void* GPUTPCClusterFinder::SetPointersOutput(void* mem) void* GPUTPCClusterFinder::SetPointersScratch(void* mem) { - computePointerWithAlignment(mem, mPpadIsNoisy, TPC_CLUSTERER_STRIDED_PAD_COUNT); + computePointerWithAlignment(mem, mPpadIsNoisy, tpccf::TPC_CLUSTERER_STRIDED_PAD_COUNT); computePointerWithAlignment(mem, mPpositions, mNMaxDigitsFragment); computePointerWithAlignment(mem, mPpeakPositions, mNMaxPeaks); computePointerWithAlignment(mem, mPfilteredPeakPositions, mNMaxClusters); diff --git a/GPU/GPUTracking/TPCClusterFinder/GPUTPCNNClusterizerHost.cxx b/GPU/GPUTracking/TPCClusterFinder/GPUTPCNNClusterizerHost.cxx index 16dd786c1eb53..1098bbe92f2e8 100644 --- a/GPU/GPUTracking/TPCClusterFinder/GPUTPCNNClusterizerHost.cxx +++ b/GPU/GPUTracking/TPCClusterFinder/GPUTPCNNClusterizerHost.cxx @@ -110,8 +110,8 @@ void GPUTPCNNClusterizerHost::initClusterizer(const GPUSettingsProcessingNNclust clustererNN.mNnSigmoidTrafoClassThreshold = settings.nnSigmoidTrafoClassThreshold; clustererNN.mNnClusterizerUseClassification = settings.nnClusterizerUseClassification; clustererNN.mNnClusterizerSetDeconvolutionFlags = (bool)settings.nnClusterizerSetDeconvolutionFlags; - clustererNN.maxFragmentLen = maxFragmentLen == -1 ? TPC_MAX_FRAGMENT_LEN_GPU : maxFragmentLen; - clustererNN.maxAllowedTimebin = maxAllowedTimebin == -1 ? TPC_MAX_FRAGMENT_LEN_GPU : maxAllowedTimebin; + clustererNN.maxFragmentLen = maxFragmentLen == -1 ? tpccf::TPC_MAX_FRAGMENT_LEN_GPU : maxFragmentLen; + clustererNN.maxAllowedTimebin = maxAllowedTimebin == -1 ? tpccf::TPC_MAX_FRAGMENT_LEN_GPU : maxAllowedTimebin; if (clustererNN.mNnSigmoidTrafoClassThreshold) { clustererNN.mNnClassThreshold = (float)std::log(settings.nnClassThreshold / (1.f - settings.nnClassThreshold)); } else { diff --git a/GPU/GPUTracking/TPCClusterFinder/GPUTPCNNClusterizerKernels.cxx b/GPU/GPUTracking/TPCClusterFinder/GPUTPCNNClusterizerKernels.cxx index 61c71666ab862..45a9a797d8fa8 100644 --- a/GPU/GPUTracking/TPCClusterFinder/GPUTPCNNClusterizerKernels.cxx +++ b/GPU/GPUTracking/TPCClusterFinder/GPUTPCNNClusterizerKernels.cxx @@ -45,10 +45,12 @@ GPUdii() void GPUTPCNNClusterizerKernels::Thread chargeMap(reinterpret_cast(clusterer.mPchargeMap)); - CPU_ONLY(MCLabelAccumulator labelAcc(clusterer)); + MCLabelAccumulator* labelPtr = nullptr; + GPUCA_IGNORE_ON_GPU(MCLabelAccumulator labelAcc(clusterer)); + GPUCA_IGNORE_ON_GPU(labelPtr = &labelAcc); tpc::ClusterNative* clusterOut = clusterer.mPclusterByRow; int8_t isAccepted = (clustererNN.mNnClusterizerUseClassification ? (clustererNN.mOutputDataClass[CAMath::Min(glo_idx, (uint32_t)clusterer.mPmemory->counters.nClusters - 1)] > 0) : 1); - GPUTPCCFClusterizer::computeClustersImpl(get_num_groups(0), get_local_size(0), get_group_id(0), get_local_id(0), clusterer, clusterer.mPmemory->frag, smem, chargeMap, clusterer.mPfilteredPeakPositions, clusterer.Param().rec, CPU_PTR(&labelAcc), clusterer.mPmemory->counters.nClusters, clusterer.mNMaxClusterPerRow, clusterer.mPclusterInRow, clusterOut, clusterer.mPclusterPosInRow, isAccepted); + GPUTPCCFClusterizer::computeClustersImpl(get_num_groups(0), get_local_size(0), get_group_id(0), get_local_id(0), clusterer, clusterer.mPmemory->frag, smem, chargeMap, clusterer.mPfilteredPeakPositions, clusterer.Param().rec, labelPtr, clusterer.mPmemory->counters.nClusters, clusterer.mNMaxClusterPerRow, clusterer.mPclusterInRow, clusterOut, clusterer.mPclusterPosInRow, isAccepted); } template <> @@ -317,13 +319,14 @@ GPUdii() void GPUTPCNNClusterizerKernels::Thread(chargeMap[peak].unpack()); - CPU_ONLY(MCLabelAccumulator labelAccElem(clusterer)); - MCLabelAccumulator* labelAcc = CPU_PTR(&labelAccElem); + MCLabelAccumulator* labelAcc = nullptr; + GPUCA_IGNORE_ON_GPU(MCLabelAccumulator labelAccElem(clusterer)); + GPUCA_IGNORE_ON_GPU(labelAcc = &labelAccElem); if (full_glo_idx >= maxClusterNum) { if (withMC) { ClusterAccumulator dummy_pc; - CPU_ONLY(labelAcc->collect(peak, central_charge)); + GPUCA_IGNORE_ON_GPU(labelAcc->collect(peak, central_charge)); GPUTPCCFClusterizer::buildCluster( clusterer.Param().rec, chargeMap, @@ -343,7 +346,7 @@ GPUdii() void GPUTPCNNClusterizerKernels::Threadcollect(peak, central_charge)); + GPUCA_IGNORE_ON_GPU(labelAcc->collect(peak, central_charge)); GPUTPCCFClusterizer::buildCluster( clusterer.Param().rec, chargeMap, @@ -491,7 +494,7 @@ GPUdii() void GPUTPCNNClusterizerKernels::Threadcommit(peak.row(), rowIndex, clusterer.mNMaxClusterPerRow)); + GPUCA_IGNORE_ON_GPU(labelAcc->commit(peak.row(), rowIndex, clusterer.mNMaxClusterPerRow)); } template <> @@ -509,15 +512,16 @@ GPUdii() void GPUTPCNNClusterizerKernels::Threadcounters.nClusters - 1))]; float central_charge = static_cast(chargeMap[peak].unpack()); - CPU_ONLY(MCLabelAccumulator labelAccElem(clusterer)); - MCLabelAccumulator* labelAcc = CPU_PTR(&labelAccElem); + MCLabelAccumulator* labelAcc = nullptr; + GPUCA_IGNORE_ON_GPU(MCLabelAccumulator labelAccElem(clusterer)); + GPUCA_IGNORE_ON_GPU(labelAcc = &labelAccElem); tpc::ClusterNative* clusterOut = clusterer.mPclusterByRow; uint32_t full_glo_idx = glo_idx + batchStart; if (full_glo_idx >= maxClusterNum) { if (withMC) { ClusterAccumulator dummy_pc; - CPU_ONLY(labelAcc->collect(peak, central_charge)); + GPUCA_IGNORE_ON_GPU(labelAcc->collect(peak, central_charge)); GPUTPCCFClusterizer::buildCluster( clusterer.Param().rec, chargeMap, @@ -537,7 +541,7 @@ GPUdii() void GPUTPCNNClusterizerKernels::Threadcollect(peak, central_charge)); + GPUCA_IGNORE_ON_GPU(labelAcc->collect(peak, central_charge)); GPUTPCCFClusterizer::buildCluster( clusterer.Param().rec, chargeMap, @@ -608,7 +612,7 @@ GPUdii() void GPUTPCNNClusterizerKernels::Threadcommit(peak.row(), rowIndex, clusterer.mNMaxClusterPerRow)); + GPUCA_IGNORE_ON_GPU(labelAcc->commit(peak.row(), rowIndex, clusterer.mNMaxClusterPerRow)); // Cluster 2 if (dtype == 0) { @@ -660,7 +664,7 @@ GPUdii() void GPUTPCNNClusterizerKernels::Threadcommit(peak.row(), rowIndex, clusterer.mNMaxClusterPerRow)); // -> Is this needed? How to handle MC labels for split clusters? + // GPUCA_IGNORE_ON_GPU(labelAcc->commit(peak.row(), rowIndex, clusterer.mNMaxClusterPerRow)); // -> Is this needed? How to handle MC labels for split clusters? } // --------------------------------- diff --git a/GPU/GPUTracking/cmake/kernel_helpers.cmake b/GPU/GPUTracking/cmake/kernel_helpers.cmake index f19f92a45c922..31d3d3c43f187 100644 --- a/GPU/GPUTracking/cmake/kernel_helpers.cmake +++ b/GPU/GPUTracking/cmake/kernel_helpers.cmake @@ -15,6 +15,7 @@ add_custom_target(O2_GPU_KERNELS) define_property(TARGET PROPERTY O2_GPU_KERNELS) define_property(TARGET PROPERTY O2_GPU_KERNEL_NAMES) +define_property(TARGET PROPERTY O2_GPU_KERNEL_NAMES_LB) define_property(TARGET PROPERTY O2_GPU_KERNEL_INCLUDES) define_property(TARGET PROPERTY O2_GPU_KERNEL_FILES) define_property(TARGET PROPERTY O2_GPU_KERNEL_NO_FAST_MATH) @@ -82,6 +83,9 @@ function(o2_gpu_add_kernel kernel_name kernel_files) endif() set_property(TARGET O2_GPU_KERNELS APPEND PROPERTY O2_GPU_KERNELS "${TMP_PRE}${TMP_KERNEL}${TMP_POST}") set_property(TARGET O2_GPU_KERNELS APPEND PROPERTY O2_GPU_KERNEL_NAMES "${kernel_name}") + if(TMP_BOUNDS STREQUAL "_LB") + set_property(TARGET O2_GPU_KERNELS APPEND PROPERTY O2_GPU_KERNEL_NAMES_LB "${kernel_name}") + endif() set_property(TARGET O2_GPU_KERNELS APPEND PROPERTY O2_GPU_KERNEL_INCLUDES "${TMP_KERNEL_CLASS_FILE}") set_property(TARGET O2_GPU_KERNELS APPEND PROPERTY O2_GPU_KERNEL_FILES "${TMP_KERNEL_CLASS_FILE}.cxx") diff --git a/GPU/GPUTracking/kernels.cmake b/GPU/GPUTracking/kernels.cmake index 0e95c09a3ef78..8b05ab5ba2909 100644 --- a/GPU/GPUTracking/kernels.cmake +++ b/GPU/GPUTracking/kernels.cmake @@ -56,6 +56,7 @@ o2_gpu_add_kernel("GPUTPCGMMergerTrackFit, def" "GPUTP o2_gpu_add_kernel("GPUTPCGMMergerTrackFit, rebuild" "GPUTPCGMMergerGPU TPCMERGER TPCTRACKER MATLUT TPCDEDX" LB) o2_gpu_add_kernel("GPUTPCGMMergerTrackFit, retry" "GPUTPCGMMergerGPU TPCMERGER TPCTRACKER MATLUT TPCDEDX" LB) o2_gpu_add_kernel("GPUTPCGMMergerFollowLoopers" "GPUTPCGMMergerGPU TPCMERGER TPCTRACKER MATLUT" LB) +o2_gpu_add_kernel("GPUTPCGMMergerFollowExtrapolation" "GPUTPCGMMergerGPU TPCMERGER TPCTRACKER MATLUT TPCDEDX" LB) o2_gpu_add_kernel("GPUTPCGMMergerUnpackResetIds" "GPUTPCGMMergerGPU TPCMERGER" LB int32_t iSector) o2_gpu_add_kernel("GPUTPCGMMergerSectorRefit" "GPUTPCGMMergerGPU TPCMERGER MATLUT" LB int32_t iSector) o2_gpu_add_kernel("GPUTPCGMMergerUnpackGlobal" "GPUTPCGMMergerGPU TPCMERGER" LB int32_t iSector) diff --git a/GPU/Workflow/src/GPUWorkflowSpec.cxx b/GPU/Workflow/src/GPUWorkflowSpec.cxx index 15f07ead20ddd..9f2a5a5a9041e 100644 --- a/GPU/Workflow/src/GPUWorkflowSpec.cxx +++ b/GPU/Workflow/src/GPUWorkflowSpec.cxx @@ -197,7 +197,7 @@ void GPURecoWorkflowSpec::init(InitContext& ic) gpudatatypes::RecoStep::TPCMerging); mConfig->configWorkflow.outputs.set(gpudatatypes::InOutType::TPCMergedTracks); } - GPUO2Interface::ApplySyncSettings(mConfig->configProcessing, mConfig->configReconstruction, mConfig->configWorkflow.steps, mConfParam->synchronousProcessing, runTracking ? mConfParam->rundEdx : -2); + GPUO2Interface::ApplySyncSettings(mConfig->configProcessing, mConfig->configReconstruction, mConfig->configWorkflow.steps, mConfParam->synchronousProcessing > 0, mConfParam->synchronousProcessing < 0, runTracking ? mConfParam->rundEdx : -2); if (mSpecConfig.outputCompClustersRoot || mSpecConfig.outputCompClustersFlat) { mConfig->configWorkflow.steps.setBits(gpudatatypes::RecoStep::TPCCompression, true); diff --git a/prodtests/full-system-test/dpl-workflow.sh b/prodtests/full-system-test/dpl-workflow.sh index 32f1b48c0c164..6aaa5dbf7daa4 100755 --- a/prodtests/full-system-test/dpl-workflow.sh +++ b/prodtests/full-system-test/dpl-workflow.sh @@ -215,6 +215,7 @@ if [[ $SYNCMODE == 1 ]]; then has_processing_step TPC_DEDX && GPU_CONFIG_KEY+="GPU_global.rundEdx=1;" has_detector ITS && TRD_FILTER_CONFIG+=" --filter-trigrec" else + GPU_CONFIG_KEY+="GPU_global.synchronousProcessing=-1;" has_detectors_gpu TPC ITS && ITS_CONFIG_KEY+="ITSCATrackerParam.trackingMode=1;" # sets ITS gpu reco to async if [[ $IS_SIMULATED_DATA == 0 && $CTFINPUT == 1 ]]; then # Enable fixes to the MCH readout mapping for async processing of real data