Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion GPU/GPUTracking/Base/GPUReconstruction.h
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,8 @@ class GPUReconstruction

enum class krnlDeviceType : int32_t { CPU = 0,
Device = 1,
Auto = -1 };
Auto = -1,
HostOnDeviceMemory = 2 }; // CPU code on the host, on the device memory (UNIFIED_MEM_SORT_ON_HOST)

struct deviceEvent;
struct threadContext;
Expand Down Expand Up @@ -352,6 +353,7 @@ class GPUReconstruction
size_t mHostMemoryUSSMax = 0; // Maximum USS of the process seen by QueryHostMemoryUSS
std::string mHostMemoryUSSMaxWhere; // and where it was seen
void* mDeviceMemoryBase = nullptr; // Same for device ...
void* mDeviceMemoryHostView = nullptr; // Host address of the device memory, if shared with the host at another address
void* mDeviceMemoryPermanent = nullptr; // ...
void* mDeviceMemoryPool = nullptr; // ...
void* mDeviceMemoryPoolEnd = nullptr; // ...
Expand Down
61 changes: 59 additions & 2 deletions GPU/GPUTracking/Base/GPUReconstructionCPU.cxx
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,15 @@ inline void GPUReconstructionCPU::runKernelBackend(const krnlSetupTime& _xyz, co
throw std::runtime_error("Cannot run device kernel on host with nThreads != 1");
}
int32_t nThreads = getNKernelHostThreads(false);
const auto deviceProcessors = IsGPU() && x.device == krnlDeviceType::HostOnDeviceMemory ? DeviceProcessorsOnHost(_xyz) : nullptr;
GPUConstantMem& mem = deviceProcessors ? *(GPUConstantMem*)deviceProcessors.get() : *mHostConstantMem;
auto arg = [&](const auto& a) -> decltype(auto) {
if constexpr (std::is_pointer_v<std::decay_t<decltype(a)>>) {
return deviceProcessors ? (std::decay_t<decltype(a)>)HostPointer(a) : a;
} else {
return a;
}
};
if (nThreads > 1) {
if (GetProcessingSettings().debugLevel >= 5) {
GPUInfo("Running %d Threads", mThreading->activeThreads->max_concurrency());
Expand All @@ -74,17 +83,65 @@ inline void GPUReconstructionCPU::runKernelBackend(const krnlSetupTime& _xyz, co
tbb::parallel_for(tbb::blocked_range<uint32_t>(0, x.nBlocks, 1), [&](const tbb::blocked_range<uint32_t>& r) {
typename T::GPUSharedMemory smem;
for (uint32_t iB = r.begin(); iB < r.end(); iB++) {
T::template Thread<I>(x.nBlocks, 1, iB, 0, smem, T::Processor(*mHostConstantMem)[y.index], args...);
T::template Thread<I>(x.nBlocks, 1, iB, 0, smem, T::Processor(mem)[y.index], arg(args)...);
}
});
});
});
} else {
for (uint32_t iB = 0; iB < x.nBlocks; iB++) {
typename T::GPUSharedMemory smem;
T::template Thread<I>(x.nBlocks, 1, iB, 0, smem, T::Processor(*mHostConstantMem)[y.index], args...);
T::template Thread<I>(x.nBlocks, 1, iB, 0, smem, T::Processor(mem)[y.index], arg(args)...);
}
}
if (deviceProcessors && _xyz.z.ev) {
RecordMarker(_xyz.z.ev, x.stream);
}
}

void GPUReconstructionCPU::runKernelOnHost(const int num, const void* args)
{
GPUReconstructionCPU::runKernelVirtual(num, args);
}

void* GPUReconstructionCPU::HostPointer(const void* ptr) const

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I do not like that this converts a const ptr to a non-const ptr. If you need only 1 version, input and output should have the same constness. Otherwise, please provide 2 overloads.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I suspect it's the usual address-space-part-of-the-type issue. I'll let you know.

{
const size_t offset = (const char*)ptr - (const char*)mDeviceMemoryBase;
return mDeviceMemoryHostView && offset < mDeviceMemorySize ? (char*)mDeviceMemoryHostView + offset : (void*)ptr;
}

// A kernel run with krnlDeviceType::HostOnDeviceMemory, on a GPU sharing its memory with the host
// (UNIFIED_MEM_SORT_ON_HOST), runs the CPU code on the device processors, once the work before it in
// the stream is done: on a copy of them pointing at the host view of the device memory, with the
// host's parameters and calibration objects. The copy is their constant memory.
std::unique_ptr<char[]> GPUReconstructionCPU::DeviceProcessorsOnHost(const krnlSetupTime& _xyz)
Comment thread
ktf marked this conversation as resolved.
Resolved
{
if (_xyz.z.evList) {
StreamWaitForEvents(_xyz.x.stream, _xyz.z.evList, _xyz.z.nEvents);
}
SynchronizeStream(_xyz.x.stream);
static_assert(alignof(GPUConstantMem) <= __STDCPP_DEFAULT_NEW_ALIGNMENT__);
auto buffer = std::make_unique<char[]>(sizeof(GPUConstantMem));
GPUConstantMem* mem = (GPUConstantMem*)buffer.get();
memcpy((void*)mem, (const void*)mProcessorsShadow, sizeof(GPUConstantMem));
auto onHost = [&](const GPUProcessor* p) {
const size_t offset = (const char*)p - (const char*)mProcessorsShadow;
return offset < sizeof(GPUConstantMem) ? (GPUProcessor*)((char*)mem + offset) : nullptr;
};
for (const auto& res : mMemoryResources) {
if (GPUProcessor* p = res.PtrDevice() ? onHost(res.mProcessor->mLinkedProcessor) : nullptr) {
(p->*res.mSetPointers)(HostPointer(res.PtrDevice()));
}
}
for (const auto& proc : mProcessors) {
if (GPUProcessor* p = onHost(proc.proc->mLinkedProcessor)) {
p->mConstantMem = mem;
}
}
mem->param = param();
mem->calibObjects = processors()->calibObjects;
mem->errorCodes.setMemory((uint32_t*)HostPointer(mem->errorCodes.getErrorPtr() - 1));
return buffer;
}

template <>
Expand Down
3 changes: 3 additions & 0 deletions GPU/GPUTracking/Base/GPUReconstructionCPU.h
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,9 @@ class GPUReconstructionCPU : public GPUReconstructionProcessing::KernelInterface
virtual void RecordMarker(deviceEvent* ev, int32_t stream) {}
virtual void SynchronizeGPU() {}
virtual void ReleaseEvent(deviceEvent ev) {}
void* HostPointer(const void* ptr) const;
std::unique_ptr<char[]> DeviceProcessorsOnHost(const krnlSetupTime& _xyz);
void runKernelOnHost(const int num, const void* args); // For the kernel specializations of a backend, e.g. with HostOnDeviceMemory

size_t TransferMemoryResourceToGPU(GPUMemoryResource* res, int32_t stream = -1, deviceEvent* ev = nullptr, deviceEvent* evList = nullptr, int32_t nEvents = 1) { return TransferMemoryInternal(res, stream, ev, evList, nEvents, true, res->Ptr(), res->PtrDevice()); }
size_t TransferMemoryResourceToHost(GPUMemoryResource* res, int32_t stream = -1, deviceEvent* ev = nullptr, deviceEvent* evList = nullptr, int32_t nEvents = 1) { return TransferMemoryInternal(res, stream, ev, evList, nEvents, false, res->PtrDevice(), res->Ptr()); }
Expand Down
2 changes: 1 addition & 1 deletion GPU/GPUTracking/Base/GPUReconstructionCPUKernels.h
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ inline void GPUReconstructionCPU::runKernelInterface(krnlSetup&& setup, Args con
if (myStep == gpudatatypes::RecoStep::NoRecoStep) {
throw std::runtime_error("Failure running general kernel without defining RecoStep");
}
int32_t cpuFallback = IsGPU() ? (setup.x.device == krnlDeviceType::CPU ? 2 : (mRecoSteps.stepsGPUMask & myStep) != myStep) : 0;
int32_t cpuFallback = IsGPU() ? ((setup.x.device == krnlDeviceType::CPU || setup.x.device == krnlDeviceType::HostOnDeviceMemory) ? 2 : (mRecoSteps.stepsGPUMask & myStep) != myStep) : 0;
uint32_t& nThreads = setup.x.nThreads;
uint32_t& nBlocks = setup.x.nBlocks;
const uint32_t stream = setup.x.stream;
Expand Down
2 changes: 2 additions & 0 deletions GPU/GPUTracking/Base/metal/GPUReconstructionMetal.h
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,8 @@ class GPUReconstructionMetal : public GPUReconstructionProcessing::KernelInterfa
void CommitStream(int32_t stream);
void DrainStream(int32_t stream);
uint64_t EventValue(deviceEvent ev, bool next);
template <class T, int32_t I, typename... Args>
void RunOnHost(const krnlSetupTime& _xyz, uint32_t nBlocks, const Args&... args);

private:
int32_t AddKernels();
Expand Down
1 change: 1 addition & 0 deletions GPU/GPUTracking/Base/metal/GPUReconstructionMetal.mm
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,7 @@ uint32_t metalGPUCoreCount()
// The kernels reconstruct device pointers from these bases, so they must be
// the addresses the GPU sees, not the CPU-visible ones of a shared buffer.
mDeviceMemoryBase = (void*)(uintptr_t)mInternals->mem_gpu.gpuAddress;
mDeviceMemoryHostView = mInternals->mem_gpu.contents;
mDeviceMemorySize = mInternals->mem_gpu.allocatedSize - sizeof(uint32_t);
*(uint32_t*)((char*)mInternals->mem_gpu.contents + mDeviceMemorySize) = mInternals->canaryMagic;
if (getenv("GPUCA_METAL_CANARY")) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@

/// \file GPUReconstructionMetalKernelsSpecialize.inc

#include <chrono>

template <>
inline void GPUReconstructionMetal::runKernelBackend<GPUMemClean16, 0>(const krnlSetupTime& _xyz, void* const& ptr, uint64_t const& size)
{
Expand All @@ -30,3 +32,21 @@ inline void GPUReconstructionMetal::runKernelBackend<GPUMemClean16, 0>(const krn
RecordMarker(_xyz.z.ev, _xyz.x.stream);
}
}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just out of curiosity, why can't you use the HostOnDeviceMemory for this like for all the sorting?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No particular reason, just historical of how the patch came to be.

// Kernels that are a long serial chain per GPU thread, with little parallelism,
// run on the host instead, with the CPU code, on the memory shared with the
// host, as the sorts do with UNIFIED_MEM_SORT_ON_HOST.
template <class T, int32_t I, typename... Args>
inline void GPUReconstructionMetal::RunOnHost(const krnlSetupTime& _xyz, uint32_t nBlocks, const Args&... args)
{
const auto start = std::chrono::steady_clock::now();
krnlSetupArgs<T, I, Args...> argPack{{}, {{{nBlocks, 1, _xyz.x.stream, krnlDeviceType::HostOnDeviceMemory, _xyz.x.step}, _xyz.y, _xyz.z}, _xyz.t}, {args...}};
runKernelOnHost(GetKernelNum<T, I>(), &argPack);
_xyz.t = std::chrono::duration<double>(std::chrono::steady_clock::now() - start).count();
}

template <>
inline void GPUReconstructionMetal::runKernelBackend<GPUTPCGMMergerMergeBorders, 2>(const krnlSetupTime& _xyz, int32_t const& iSector, uint8_t const& mergeMode)
{
RunOnHost<GPUTPCGMMergerMergeBorders, 2>(_xyz, 1, iSector, mergeMode);
}
1 change: 1 addition & 0 deletions GPU/GPUTracking/Definitions/Parameters/GPUParameters.csv
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,7 @@ NEIGHBOURS_FINDER_UNROLL_SHARED,1,0,0,0,,,,,,1,,1,0,,1,,1,1,
TRACKLET_SELECTOR_HITS_REG_SIZE,12,0,9,27,,,,,,20,20,20,20,,20,,2,20,
ALTERNATE_BORDER_SORT,1,0,1,1,,,,,,1,1,1,1,,1,,1,1,
SORT_BEFORE_FIT,1,0,1,1,,,,,,1,1,1,1,,1,,1,1,
UNIFIED_MEM_SORT_ON_HOST,0,0,,,,,,,,,,,,,,,,,1
NO_ATOMIC_PRECHECK,0,0,1,1,,,,,,1,1,1,1,,1,,1,1,
DEDX_STORAGE_TYPE,"""CAMath::half_t""","""float""",,,,,,,,,,,,,,,,,
MERGER_INTERPOLATION_ERROR_TYPE,"""CAMath::half_t""","""float""",,,,,,,,,,,,,,,,,
Expand Down
14 changes: 8 additions & 6 deletions GPU/GPUTracking/Global/GPUChainTrackingMerger.cxx
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ void GPUChainTracking::RunTPCTrackingMerger_MergeBorderTracks(uint8_t mergeMode,
GPUTPCGMMerger& Merger = processors()->tpcMerger;
bool doGPU = GetRecoStepsGPU() & RecoStep::TPCMerging;
GPUTPCGMMerger& MergerShadow = doGPU ? processorsShadow()->tpcMerger : Merger;
const auto sortDeviceType = mRec->getGPUParameters(doGPU).par_UNIFIED_MEM_SORT_ON_HOST ? GPUReconstruction::krnlDeviceType::HostOnDeviceMemory : deviceType;
if (GetProcessingSettings().deterministicGPUReconstruction) {
uint32_t nBorderTracks = (mergeMode & GPUTPCGMMerger::mergeModes::mergeWithinSector) ? NSECTORS : (2 * NSECTORS);
runKernel<GPUTPCGlobalDebugSortKernels, GPUTPCGlobalDebugSortKernels::borderTracks>({{nBorderTracks, -WarpSize(), 0, deviceType}}, 0);
Expand All @@ -56,8 +57,8 @@ void GPUChainTracking::RunTPCTrackingMerger_MergeBorderTracks(uint8_t mergeMode,
Merger.MergeBorderTracksSetup(n1, n2, b1, b2, jSector, i, mergeMode);
gputpcgmmergertypes::GPUTPCGMBorderRange* range1 = MergerShadow.BorderRange(i);
gputpcgmmergertypes::GPUTPCGMBorderRange* range2 = MergerShadow.BorderRange(jSector) + *processors()->tpcTrackers[jSector].NTracks();
runKernel<GPUTPCGMMergerMergeBorders, 3>({{1, -WarpSize(), stream, deviceType}}, range1, n1, 0);
runKernel<GPUTPCGMMergerMergeBorders, 3>({{1, -WarpSize(), stream, deviceType}}, range2, n2, 1);
runKernel<GPUTPCGMMergerMergeBorders, 3>({{1, -WarpSize(), stream, sortDeviceType}}, range1, n1, 0);
runKernel<GPUTPCGMMergerMergeBorders, 3>({{1, -WarpSize(), stream, sortDeviceType}}, range2, n2, 1);
runKernel<GPUTPCGMMergerMergeBorders, 2>({GetGridAuto(stream, deviceType)}, i, mergeMode);
}
int32_t ne = std::min<int32_t>(n, mRec->NStreams()) - 1; // Stream 0 must wait for all streams, Note n > 1
Expand Down Expand Up @@ -94,6 +95,7 @@ int32_t GPUChainTracking::RunTPCTrackingMerger(bool synchronizeOutput)
mRec->PushNonPersistentMemory(qStr2Tag("TPCMERGE"));
bool doGPU = GetRecoStepsGPU() & RecoStep::TPCMerging;
GPUReconstruction::krnlDeviceType deviceType = doGPU ? GPUReconstruction::krnlDeviceType::Auto : GPUReconstruction::krnlDeviceType::CPU;
const auto sortDeviceType = mRec->getGPUParameters(doGPU).par_UNIFIED_MEM_SORT_ON_HOST ? GPUReconstruction::krnlDeviceType::HostOnDeviceMemory : deviceType;
uint32_t numBlocks = (!mRec->IsGPU() || doGPU) ? BlockCount() : 1;
GPUTPCGMMerger& Merger = processors()->tpcMerger;
GPUTPCGMMerger& MergerShadow = doGPU ? processorsShadow()->tpcMerger : Merger;
Expand Down Expand Up @@ -221,7 +223,7 @@ int32_t GPUChainTracking::RunTPCTrackingMerger(bool synchronizeOutput)
if (mergerSortTracks) {
runKernel<GPUTPCGMMergerSortTracksPrepare>(GetGridAuto(0, deviceType));
CondWaitEvent(waitForTransfer, &mEvents->single);
runKernel<GPUTPCGMMergerSortTracks>(GetGridAuto(0, deviceType));
runKernel<GPUTPCGMMergerSortTracks>(GetGridAuto(0, sortDeviceType));
}
if (GetProcessingSettings().mergerSanityCheck) {
Merger.CheckCollectedTracks();
Expand All @@ -239,7 +241,7 @@ int32_t GPUChainTracking::RunTPCTrackingMerger(bool synchronizeOutput)
runKernel<GPUMemClean16>({{numBlocks, -ThreadCount(), 0, deviceType, RecoStep::TPCMerging}}, MergerShadow.ClusterAttachment(), Merger.NClusters() * sizeof(*MergerShadow.ClusterAttachment()));
runKernel<GPUTPCGMMergerPrepareForFit, 0>(GetGridAuto(0, deviceType));
CondWaitEvent(waitForTransfer, &mEvents->single);
runKernel<GPUTPCGMMergerSortTracksQPt>(GetGridAuto(0, deviceType));
runKernel<GPUTPCGMMergerSortTracksQPt>(GetGridAuto(0, sortDeviceType));
runKernel<GPUTPCGMMergerPrepareForFit, 1>(GetGridAuto(0, deviceType));
runKernel<GPUTPCGMMergerPrepareForFit, 2>(GetGridAuto(0, deviceType));
if (doGPU && rebuildConstrainedRows == 1) { // PrepareForFit1 computed nRebuildTrackRow, needed on the host to allocate the rebuild memory, waited for below
Expand Down Expand Up @@ -313,7 +315,7 @@ int32_t GPUChainTracking::RunTPCTrackingMerger(bool synchronizeOutput)
SynchronizeStream(0); // TODO: could probably synchronize on an event after runKernel<GPUTPCGMMergerMergeLoopers, 1>
}
if (param().rec.tpc.mergeLoopersAfterburner) {
runKernel<GPUTPCGMMergerMergeLoopers, 1>(GetGridAuto(0, deviceType));
runKernel<GPUTPCGMMergerMergeLoopers, 1>(GetGridAuto(0, sortDeviceType));
runKernel<GPUTPCGMMergerMergeLoopers, 2>(doGPU ? GetGrid(Merger.Memory()->nLooperMatchCandidates, 0, deviceType) : GetGridAuto(0, deviceType));
DoDebugAndDump(RecoStep::TPCMerging, GPUChainTrackingDebugFlags::TPCMergingLoopers, Merger, &GPUTPCGMMerger::DumpLoopers, *mDebugFile);
}
Expand Down Expand Up @@ -371,7 +373,7 @@ int32_t GPUChainTracking::RunTPCTrackingMerger(bool synchronizeOutput)
}
TransferMemoryResourceLinkToHost(RecoStep::TPCMerging, Merger.MemoryResMemory(), 0, &mEvents->single);
SynchronizeEventAndRelease(mEvents->single, doGPU); // The CUDA / HIP specialization of the sort reads nO2Tracks on the host
runKernel<GPUTPCGMO2Output, GPUTPCGMO2Output::sort>(GetGridAuto(0, deviceType));
runKernel<GPUTPCGMO2Output, GPUTPCGMO2Output::sort>(GetGridAuto(0, sortDeviceType));
mRec->ReturnVolatileDeviceMemory();

if (GetProcessingSettings().clearO2OutputFromGPU) {
Expand Down
1 change: 1 addition & 0 deletions GPU/GPUTracking/kernels.cmake
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,7 @@ o2_gpu_kernel_add_parameter(NEIGHBOURS_FINDER_MAX_NNEIGHUP # Number o
TRACKLET_SELECTOR_HITS_REG_SIZE # Number of hits to cache in shared memory in tracklet selector
ALTERNATE_BORDER_SORT # Use alternative border sort approach [0/1]
SORT_BEFORE_FIT # Sort tracks after length to reduce warp serialization [0/1]
UNIFIED_MEM_SORT_ON_HOST # Run the sorts on the host, on the memory shared with the GPU [0/1]
NO_ATOMIC_PRECHECK # Skip atomic precheck to reduce posterior synchronization [0/1]
COMP_GATHER_KERNEL # Default kernel to use for Compression Gather Operation [0 - 4]
COMP_GATHER_MODE # TPC Compression Gather Mode [0 - 3]
Expand Down