15#ifndef GPUCOMMONALGORITHM_H
16#define GPUCOMMONALGORITHM_H
20#if !defined(GPUCA_GPUCODE) || defined(__CPUDEVICE__)
21#ifndef GPUCA_GPUCODE_DEVICE
24#define GPUCA_ALGORITHM_STD
35 GPUd() static
void sort(T* begin, T*
end);
39 GPUd() static
void sortDeviceDynamic(T* begin, T*
end);
40 template <class T, class
S>
42 template <class T, class
S>
44 template <class T, class
S>
45 GPUd() static
void sortDeviceDynamic(T* begin, T*
end, const
S&
comp);
46#if __cplusplus >= 202002L
47 template <
class T,
class S>
52 template <class I, class
P>
57 GPUd() static
void QuickSort(I
f, I l) GPUnoexcept();
59 template <typename I, typename Cmp>
60 GPUd() static
void QuickSort(I
f, I l, Cmp
cmp) GPUnoexcept();
62 template <typename IndexType, typename I, typename Cmp>
63 GPUd() static
void QuickSortImpl(I
f, I l, Cmp
cmp) GPUnoexcept();
65 template <typename I, typename Cmp>
66 GPUd() static
void InsertionSort(I
f, I l, Cmp
cmp) GPUnoexcept();
68 template <typename I, typename Cmp>
69 GPUd() static I MedianOf3Select(I
f, I l, Cmp
cmp) GPUnoexcept();
71 template <typename I, typename T, typename Cmp>
72 GPUd() static I UnguardedPartition(I
f, I l, T piv, Cmp
cmp) GPUnoexcept();
75 GPUd() static
void IterSwap(I
a, I
b) GPUnoexcept();
78#ifndef GPUCA_ALGORITHM_STD
87template <
typename I,
typename Cmp>
95 while (it1 !=
f &&
cmp(tmp, it1[-1])) {
105template <
typename I,
typename Cmp>
106GPUdi() I GPUCommonAlgorithm::MedianOf3Select(I
f, I l, Cmp
cmp) GPUnoexcept()
108 auto m =
f + (l -
f) / 2;
115 }
else if (
cmp(*
f, *l)) {
120 }
else if (
cmp(*
f, *l)) {
122 }
else if (
cmp(*
m, *l)) {
129template <
typename I,
typename T,
typename Cmp>
130GPUdi() I GPUCommonAlgorithm::UnguardedPartition(I
f, I l, T piv, Cmp
cmp) GPUnoexcept()
133 while (
cmp(*
f, piv)) {
137 while (
cmp(piv, *l)) {
149template <
typename I,
typename Cmp>
150GPUdi()
void GPUCommonAlgorithm::QuickSort(I
f, I l, Cmp
cmp) GPUnoexcept()
152 if (l -
f <= 0xFFFF) {
153 QuickSortImpl<uint16_t>(
f, l,
cmp);
155 QuickSortImpl<uint32_t>(
f, l,
cmp);
159template <
typename IndexType,
typename I,
typename Cmp>
160GPUdi()
void GPUCommonAlgorithm::QuickSortImpl(I
f, I l, Cmp
cmp) GPUnoexcept()
172 pair
data[
sizeof(IndexType) * 8 - 4];
187 const auto it0 =
f +
s.top().first;
188 const auto it1 =
f +
s.top().second;
191 const auto piv = *MedianOf3Select(it0, it1,
cmp);
192 const auto pp = UnguardedPartition(it0, it1, piv,
cmp);
194 constexpr auto cutoff = 50u;
195 const auto lsz =
pp - it0;
196 const auto rsz = it1 -
pp;
199 s.emplace(
pp -
f, it1 -
f);
202 s.emplace(it0 -
f,
pp -
f);
206 s.emplace(it0 -
f,
pp -
f);
209 s.emplace(
pp -
f, it1 -
f);
213 InsertionSort(
f, l,
cmp);
217GPUdi()
void GPUCommonAlgorithm::QuickSort(I
f, I l) GPUnoexcept()
219 QuickSort(
f, l, [](
auto&&
x,
auto&&
y) {
return x <
y; });
227#if (((defined(__CUDACC__) && !defined(__clang__)) || defined(__HIPCC__))) && !defined(GPUCA_GPUCODE_HOSTONLY)
237GPUdi()
void GPUCommonAlgorithm::sortDeviceDynamic(T* begin, T*
end)
240 GPUCommonAlgorithm::sort(begin,
end);
242 GPUCommonAlgorithm::sortDeviceDynamic(begin,
end, [](
auto&&
x,
auto&&
y) {
return x <
y; });
246template <
class T,
class S>
247GPUdi()
void GPUCommonAlgorithm::sortDeviceDynamic(T* begin, T*
end, const
S& comp)
249 GPUCommonAlgorithm::sort(begin,
end, comp);
263#ifdef GPUCA_ALGORITHM_STD
264 std::sort(begin,
end);
266 QuickSort(begin,
end, [](
auto&&
x,
auto&&
y) {
return x <
y; });
270template <
class T,
class S>
271GPUdi()
void GPUCommonAlgorithm::sort(T* begin, T*
end, const
S& comp)
273#ifdef GPUCA_ALGORITHM_STD
274 std::sort(begin,
end, comp);
276 QuickSort(begin,
end, comp);
284 GPUCommonAlgorithm::sort(begin,
end);
290template <
class T,
class S>
293#if !defined(GPUCA_GPUCODE) || defined(GPUCA_DEVICE_SINGLE_THREAD)
294 GPUCommonAlgorithm::sort(begin,
end, comp);
295#elif defined(GPUCA_DETERMINISTIC_MODE)
297 GPUCommonAlgorithm::sort(begin,
end, comp);
309 if (!comp(begin[curPos], begin[nextPos])) {
310 IterSwap(&begin[curPos], &begin[nextPos]);
337template <
class I,
class P>
359#pragma OPENCL EXTENSION cl_khr_subgroups : enable
362GPUdi() T warp_scan_inclusive_add_FUNC(T
v)
364 return sub_group_scan_inclusive_add(
v);
369 return sub_group_scan_inclusive_add((
uint32_t)
v);
374 return sub_group_broadcast(
v,
i);
382#define warp_scan_inclusive_add(v) warp_scan_inclusive_add_FUNC(v)
383#define warp_broadcast(v, i) warp_broadcast_FUNC(v, i)
385[[nodiscard]]
GPUdi()
int32_t work_group_count(
bool pred)
387 return work_group_reduce_add((
int32_t)pred);
390#elif (defined(__CUDACC__) || defined(__HIPCC__))
393#if !defined(GPUCA_GPUCODE_COMPILEKERNELS) && !defined(GPUCA_GPUCODE_HOSTONLY)
394#if defined(__CUDACC__)
395#include <cub/cub.cuh>
396#elif defined(__HIPCC__)
397#include <hipcub/hipcub.hpp>
401#define work_group_scan_inclusive_add(v) work_group_scan_inclusive_add_FUNC(v, smem)
402template <
class T,
class S>
403GPUdi() T work_group_scan_inclusive_add_FUNC(T
v,
S& smem)
405 typename S::BlockScan(smem.cubTmpMem).InclusiveSum(
v,
v);
410#define work_group_broadcast(v, i) work_group_broadcast_FUNC(v, i, smem)
411template <
class T,
class S>
415 smem.tmpBroadcast =
v;
423#define work_group_reduce_add(v) work_group_reduce_add_FUNC(v, smem)
424template <
class T,
class S>
425GPUdi() T work_group_reduce_add_FUNC(T
v,
S& smem)
427 v =
typename S::BlockReduce(smem.cubReduceTmpMem).Sum(
v);
429 v = work_group_broadcast(
v, 0);
433#define warp_scan_inclusive_add(v) warp_scan_inclusive_add_FUNC(v, smem)
434template <
class T,
class S>
435GPUdi() T warp_scan_inclusive_add_FUNC(T
v,
S& smem)
437 typename S::WarpScan(smem.cubWarpTmpMem).InclusiveSum(
v,
v);
441#define warp_broadcast(v, i) warp_broadcast_FUNC(v, i)
446 return __shfl_sync(0xFFFFFFFF,
v,
i);
456 return __shfl_xor_sync(0xFFFFFFFF,
v, laneMask);
458 return __shfl_xor(
v, laneMask);
464template <
int32_t W
idth,
class T>
465GPUdi() T warp_reduce_add(T
v)
468 v += warp_shuffle_xor(
v,
m);
473template <
int32_t W
idth,
class T>
474GPUdi() T warp_reduce_min(T
v)
477 const T o = warp_shuffle_xor(
v,
m);
483template <
int32_t W
idth,
class T>
484GPUdi() T warp_reduce_max(T
v)
487 const T o = warp_shuffle_xor(
v,
m);
493[[nodiscard]]
GPUdi()
bool work_group_any(
bool pred)
495 return __syncthreads_or(pred);
500 return __syncthreads_count(pred);
503#elif defined(__METAL__)
514GPUdi()
auto warp_scan_inclusive_add(T
v) -> decltype(+
v)
516 return simd_prefix_inclusive_sum((
int32_t)
v);
522 return (T)simd_shuffle((
int32_t)
v, (ushort)
i);
528 return simd_shuffle_xor(
v, (ushort)laneMask);
531template <
int32_t W
idth,
class T>
532GPUdi() T warp_reduce_add(T
v)
535 v += warp_shuffle_xor(
v,
m);
540template <
int32_t W
idth,
class T>
541GPUdi() T warp_reduce_min(T
v)
544 const T o = warp_shuffle_xor(
v,
m);
550template <
int32_t W
idth,
class T>
551GPUdi() T warp_reduce_max(T
v)
554 const T o = warp_shuffle_xor(
v,
m);
560#define work_group_scan_inclusive_add(v) work_group_scan_inclusive_add_FUNC(v, smem, iThread, nThreads)
561template <
class T,
class S>
564 const int32_t iWarp = iThread / GPUCA_WARP_SIZE;
565 const int32_t nWarps = (nThreads + GPUCA_WARP_SIZE - 1) / GPUCA_WARP_SIZE;
567 if (iThread % GPUCA_WARP_SIZE == GPUCA_WARP_SIZE - 1 || iThread == nThreads - 1) {
568 smem.warpPredicateSum[iWarp] =
x;
572 const int32_t s = simd_prefix_inclusive_sum(iThread < nWarps ? smem.warpPredicateSum[iThread] : 0);
573 if (iThread < nWarps) {
574 smem.warpPredicateSum[iThread] =
s;
579 x += smem.warpPredicateSum[iWarp - 1];
585#define work_group_broadcast(v, i) work_group_broadcast_FUNC(v, i, smem, iThread)
586template <
class T,
class S>
590 smem.tmpBroadcast =
v;
598#define work_group_reduce_add(v) work_group_reduce_add_FUNC(v, smem, iThread, nThreads)
599template <
class T,
class S>
602 return work_group_broadcast_FUNC(work_group_scan_inclusive_add_FUNC(
v, smem, iThread, nThreads), nThreads - 1, smem, iThread);
605#define work_group_count(pred) ((uint32_t)work_group_reduce_add_FUNC((int32_t)(pred), smem, iThread, nThreads))
606#define work_group_any(pred) (work_group_count(pred) != 0)
612GPUdi() T work_group_scan_inclusive_add(T
v)
618GPUdi() T work_group_reduce_add(T
v)
630GPUdi() T warp_scan_inclusive_add(T
v)
641template <
int32_t W
idth,
class T>
647template <
int32_t W
idth,
class T>
648GPUdi() T warp_reduce_min(T
v)
653template <
int32_t W
idth,
class T>
654GPUdi() T warp_reduce_max(T
v)
671#ifdef GPUCA_ALGORITHM_STD
672#undef GPUCA_ALGORITHM_STD
#define get_local_size(dim)
#define get_local_id(dim)
#define GPUCA_THREAD_INFO_PROVIDE
#define GPUCA_THREAD_INFO_DECL
configStandalone Light OpenGL display display_light Apply smoothing to points Enable Z buffer Highlight links Highlight seeds Highlight sector tracks Highlight final tracks Show individual Show related Highlight grid Show only individual collision Color clusters belonging to track objects Set line Enable drawing TPC data Enable drawing TOF data Enable drawing magnetic field Set field line step count Invert colors configStandalone Heavy OpenGL display display_heavy Show tracks with ITS contribution Show tracks with TOF contribution Enable propagation of loopers Show clusters at nominal x of pad row for early transformed data Split CE tracks when they cross the central Mark clusters Mark adjacent clusters Hide rejected tracks Apply filter on tracks to be displayed Separate increase X h configStandalone Camera window renderer OpenGL display display_camera Orient the camera such that the y axis is always upwards Full Screen MultiSample Anti Downsampling Anti Enable Vertical Sync Target frame or if the backend cannot limit to the refresh Use OpenGL indirect draws to reduce number of draw calls Display h configStandalone Vulkan display display_vulkan Have uniform buffers in host accessible device memory h configStandalone Internal display display_internal Number of updates the Qt GUI may send ahead of the last one the display has before it waits for the display Opacity of the console background Number of console lines the history is shortened to this when it reaches twice the size Time in seconds an info message fades out after setInfoTime h OpenGL display display Font size Do not use Freetype for font auto
Timeframe settings Average distance in cm of events merged into Randomize distance around average distance of merged events Simulate correct bunch interactions instead of placing only the average number of events A value[n] sets TFlen for[n] collisions in Number of bunches per trainsort Number of bunch trains Instantaneous interaction rate Do not simulate border Total number of collisions to be placed in the interior of all time Do not select random but walk over array of events in stride steps h Event generator settings h configStandalone Use CPU for GPU Force usage of the specified GPU device no CPU fallback Continue processing after an error s
Timeframe settings Average distance in cm of events merged into Randomize distance around average distance of merged events Simulate correct bunch interactions instead of placing only the average number of events A value[n] sets TFlen for[n] collisions in Number of bunches per trainsort Number of bunch trains Instantaneous interaction rate Do not simulate border Total number of collisions to be placed in the interior of all time Do not select random but walk over array of events in stride steps h Event generator settings h configStandalone Use CPU for GPU Force usage of the specified GPU device no CPU fallback Continue processing after an error First event to Number of events to Number of iterations to Number of iterations to Number of initial iterations excluded from const char pp
configStandalone Reconstruction rec_tpc multiplier for the combined cluster track error during track following area in cm for the search of for z only used if decrease removal by when above this local occupancy rowx Shift of TPC revert cluster flag edge bit distance to edge exceeds this ZOffset for secondary multiple of radius max P of electron K BB bands crossing max P of electron p BB bands crossing max P of electron d BB bands crossing max P of electron t BB bands crossing min accepted dEdxMaxTPC of the track Additive extra cluster error for Y2 if edge flag set Additive extra cluster error for Y2 if single set Additive extra cluster error for Y2 if or single set Additive extra cluster error for Z2 if or single set Extra errors to add to track when crossing depending on addErrorsCECrossing Inner portion of y range in sector that is not used in searching for extrapolated track candidates factor2YS for track merging factor2K for track merging Margin in cm of Y position when rejecting edge clusters based on uncorrected track Y Max fraction of shared clusters for tracklet Except pad from cluster finding if total number of charges in a fragment is above this Except pad from cluster finding if number of consecutive charges in a fragment is above this Threshold where a timebin is considered disabling the noisy pad check for that pad Treat signal above this minimum as saturated Smoothing factor for the exponential Highly Ionising Particle tail filter Number of timebins to use for the averaging Add additional custom track errors when crossing relative as fraction of Do N fit passes in final fit of< 0:reject at max -n hits") AddOptionRTC(rejectIFCLowRadiusCluster, uint8_t, 1, "", 0, "Reject clusters that get the IFC mask error during refit") 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)") AddOptionRTC(disableRefitAttachment, uint8_t, 0, "", 0, "Bitmask to disable certain attachment steps during refit(1:attachment, 2:propagation, 4:loop following, 8:mirroring)") AddOptionRTC(rejectionStrategy, uint8_t, o2::gpu::GPUSettings::RejectionStrategyA, "", 0, "Enable rejection of TPC clusters for compression(0=no, 1=strategy A, 2=strategy B)") AddOptionRTC(mergeLoopersAfterburner, uint8_t, 1, "", 0, "Run afterburner for additional looper merging") AddOptionRTC(compressionTypeMask, uint8_t, o2::gpu::GPUSettings::CompressionFull, "", 0, "TPC Compression mode bits(1=truncate charge/width LSB, 2=differences, 4=track-model)") AddOptionRTC(compressionSortOrder, uint8_t, o2::gpu::GPUSettings::SortTime, "", 0, "Sort order of TPC compression(0=time, 1=pad, 2=Z-time-pad, 3=Z-pad-time, 4=no sorting(use incoming order))") AddOptionRTC(sigBitsCharge, uint8_t, 4, "", 0, "Number of significant bits for TPC cluster charge in compression mode 1") AddOptionRTC(sigBitsWidth, uint8_t, 3, "", 0, "Number of significant bits for TPC cluster width in compression mode 1") AddOptionRTC(dropLoopers, uint8_t, 0, "", 0, "Drop looping tracks starting from second loop") AddOptionRTC(mergerInterpolateErrors, uint8_t, 1, "", 0, "Use interpolation instead of extrapolation for chi2 based cluster rejection") AddOptionRTC(mergerInterpolateRejectAlsoOnCurrentPosition, uint8_t, 1, "", 0, "When using mergerInterpolateErrors, reject based on chi2 twice computed with interpolated and current track position starting from NDF > mergerNonInterpolateRejectMinNDF Merge tracks accross the central electrode Enable PID response Add sub threshold clusters in TPC dEdx computation OR mask of TPC flags that will reject the cluster in alternative dEdx Reject edge clusters based on uncorrected track Y during track fit Increase decrease removal by when on this number of pads from the edge h configStandalone Reconstruction rec_trd Max chi2 for TRD tracklets to be matched to a track Chi2 cut for strict matching mode Number of sigmas for ITS TPC track time error estimate Addition to search road around track prolongation along Y in cm Optimal tracklet rphi resolution in maximum chi2 per attached tracklet for TRD tracks take into account the full likelihood of the slope including exponential tails Tracks with less attached tracklets are discarded after the tracking Post trigger Pile up integration time in BCs fits all iterations but the last one in projections Use material lookup table for TPC refit Apply workarounds to avoid cyclic merge should not be needed tpc dyn configStandalone Processing proc_rtc Replace constant variables static by constexpr expressions Compile RTC in deterministic with NO_FAST_MATH flags and GPUCA_DETERMINISTIC_MODE define Use RTC to optimize GPU code h configStandalone Processing proc_rtctech Use a file lock to serialize access to the cache folder int32_t
configStandalone Reconstruction rec_tpc multiplier for the combined cluster track error during track following area in cm for the search of for z only used if decrease removal by when above this local occupancy rowx Shift of TPC revert cluster flag edge bit distance to edge exceeds this ZOffset for secondary multiple of radius max P of electron K BB bands crossing max P of electron p BB bands crossing max P of electron d BB bands crossing max P of electron t BB bands crossing min accepted dEdxMaxTPC of the track Additive extra cluster error for Y2 if edge flag set Additive extra cluster error for Y2 if single set Additive extra cluster error for Y2 if or single set Additive extra cluster error for Z2 if or single set Extra errors to add to track when crossing depending on addErrorsCECrossing Inner portion of y range in sector that is not used in searching for extrapolated track candidates factor2YS for track merging factor2K for track merging Margin in cm of Y position when rejecting edge clusters based on uncorrected track Y Max fraction of shared clusters for tracklet Except pad from cluster finding if total number of charges in a fragment is above this Except pad from cluster finding if number of consecutive charges in a fragment is above this Threshold where a timebin is considered disabling the noisy pad check for that pad Treat signal above this minimum as saturated Smoothing factor for the exponential Highly Ionising Particle tail filter Number of timebins to use for the averaging Add additional custom track errors when crossing relative as fraction of Do N fit passes in final fit of< 0:reject at max -n hits") AddOptionRTC(rejectIFCLowRadiusCluster, uint8_t, 1, "", 0, "Reject clusters that get the IFC mask error during refit") 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)") AddOptionRTC(disableRefitAttachment, uint8_t, 0, "", 0, "Bitmask to disable certain attachment steps during refit(1:attachment, 2:propagation, 4:loop following, 8:mirroring)") AddOptionRTC(rejectionStrategy, uint8_t, o2::gpu::GPUSettings::RejectionStrategyA, "", 0, "Enable rejection of TPC clusters for compression(0=no, 1=strategy A, 2=strategy B)") AddOptionRTC(mergeLoopersAfterburner, uint8_t, 1, "", 0, "Run afterburner for additional looper merging") AddOptionRTC(compressionTypeMask, uint8_t, o2::gpu::GPUSettings::CompressionFull, "", 0, "TPC Compression mode bits(1=truncate charge/width LSB, 2=differences, 4=track-model)") AddOptionRTC(compressionSortOrder, uint8_t, o2::gpu::GPUSettings::SortTime, "", 0, "Sort order of TPC compression(0=time, 1=pad, 2=Z-time-pad, 3=Z-pad-time, 4=no sorting(use incoming order))") AddOptionRTC(sigBitsCharge, uint8_t, 4, "", 0, "Number of significant bits for TPC cluster charge in compression mode 1") AddOptionRTC(sigBitsWidth, uint8_t, 3, "", 0, "Number of significant bits for TPC cluster width in compression mode 1") AddOptionRTC(dropLoopers, uint8_t, 0, "", 0, "Drop looping tracks starting from second loop") AddOptionRTC(mergerInterpolateErrors, uint8_t, 1, "", 0, "Use interpolation instead of extrapolation for chi2 based cluster rejection") AddOptionRTC(mergerInterpolateRejectAlsoOnCurrentPosition, uint8_t, 1, "", 0, "When using mergerInterpolateErrors, reject based on chi2 twice computed with interpolated and current track position starting from NDF > mergerNonInterpolateRejectMinNDF Merge tracks accross the central electrode Enable PID response Add sub threshold clusters in TPC dEdx computation OR mask of TPC flags that will reject the cluster in alternative dEdx Reject edge clusters based on uncorrected track Y during track fit Increase decrease removal by when on this number of pads from the edge h configStandalone Reconstruction rec_trd Max chi2 for TRD tracklets to be matched to a track Chi2 cut for strict matching mode Number of sigmas for ITS TPC track time error estimate Addition to search road around track prolongation along Y in cm Optimal tracklet rphi resolution in maximum chi2 per attached tracklet for TRD tracks take into account the full likelihood of the slope including exponential tails Tracks with less attached tracklets are discarded after the tracking Post trigger Pile up integration time in BCs fits all iterations but the last one in projections Use material lookup table for TPC refit Apply workarounds to avoid cyclic merge should not be needed tpc dyn configStandalone Processing proc_rtc bool
T *end GPUCA_THREAD_INFO_DECL
GPUd() static void sort(T *begin
GPUhd() static I partitionPoint(I first
GLdouble GLdouble GLdouble GLdouble top
GLboolean GLboolean GLboolean b
typedef void(APIENTRYP PFNGLCULLFACEPROC)(GLenum mode)
GLboolean GLboolean GLboolean GLboolean a
GPUCommonAlgorithm CAAlgo
Enum< T >::Iterator begin(Enum< T >)
char const *restrict const cmp