diff --git a/GPU/GPUTracking/Base/GPUReconstruction.h b/GPU/GPUTracking/Base/GPUReconstruction.h index c94b66a9a5cc5..fe281cf5bda0f 100644 --- a/GPU/GPUTracking/Base/GPUReconstruction.h +++ b/GPU/GPUTracking/Base/GPUReconstruction.h @@ -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; @@ -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; // ... diff --git a/GPU/GPUTracking/Base/GPUReconstructionCPU.cxx b/GPU/GPUTracking/Base/GPUReconstructionCPU.cxx index dfec97fe1a158..5ecf3de1398e9 100644 --- a/GPU/GPUTracking/Base/GPUReconstructionCPU.cxx +++ b/GPU/GPUTracking/Base/GPUReconstructionCPU.cxx @@ -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>) { + return deviceProcessors ? (std::decay_t)HostPointer(a) : a; + } else { + return a; + } + }; if (nThreads > 1) { if (GetProcessingSettings().debugLevel >= 5) { GPUInfo("Running %d Threads", mThreading->activeThreads->max_concurrency()); @@ -74,7 +83,7 @@ inline void GPUReconstructionCPU::runKernelBackend(const krnlSetupTime& _xyz, co tbb::parallel_for(tbb::blocked_range(0, x.nBlocks, 1), [&](const tbb::blocked_range& r) { typename T::GPUSharedMemory smem; for (uint32_t iB = r.begin(); iB < r.end(); iB++) { - T::template Thread(x.nBlocks, 1, iB, 0, smem, T::Processor(*mHostConstantMem)[y.index], args...); + T::template Thread(x.nBlocks, 1, iB, 0, smem, T::Processor(mem)[y.index], arg(args)...); } }); }); @@ -82,9 +91,57 @@ inline void GPUReconstructionCPU::runKernelBackend(const krnlSetupTime& _xyz, co } else { for (uint32_t iB = 0; iB < x.nBlocks; iB++) { typename T::GPUSharedMemory smem; - T::template Thread(x.nBlocks, 1, iB, 0, smem, T::Processor(*mHostConstantMem)[y.index], args...); + T::template Thread(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 +{ + 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 GPUReconstructionCPU::DeviceProcessorsOnHost(const krnlSetupTime& _xyz) +{ + 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(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 <> diff --git a/GPU/GPUTracking/Base/GPUReconstructionCPU.h b/GPU/GPUTracking/Base/GPUReconstructionCPU.h index 466ad318bbe3b..9e06c6992757c 100644 --- a/GPU/GPUTracking/Base/GPUReconstructionCPU.h +++ b/GPU/GPUTracking/Base/GPUReconstructionCPU.h @@ -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 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()); } diff --git a/GPU/GPUTracking/Base/GPUReconstructionCPUKernels.h b/GPU/GPUTracking/Base/GPUReconstructionCPUKernels.h index 3e330cd82ef6c..9fbb4d2e6040d 100644 --- a/GPU/GPUTracking/Base/GPUReconstructionCPUKernels.h +++ b/GPU/GPUTracking/Base/GPUReconstructionCPUKernels.h @@ -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; diff --git a/GPU/GPUTracking/Base/metal/GPUReconstructionMetal.h b/GPU/GPUTracking/Base/metal/GPUReconstructionMetal.h index 247ae6657c01e..b016d326f6be3 100644 --- a/GPU/GPUTracking/Base/metal/GPUReconstructionMetal.h +++ b/GPU/GPUTracking/Base/metal/GPUReconstructionMetal.h @@ -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 + void RunOnHost(const krnlSetupTime& _xyz, uint32_t nBlocks, const Args&... args); private: int32_t AddKernels(); diff --git a/GPU/GPUTracking/Base/metal/GPUReconstructionMetal.mm b/GPU/GPUTracking/Base/metal/GPUReconstructionMetal.mm index 2f8a28da23922..6f1d8ee9d95cf 100644 --- a/GPU/GPUTracking/Base/metal/GPUReconstructionMetal.mm +++ b/GPU/GPUTracking/Base/metal/GPUReconstructionMetal.mm @@ -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")) { diff --git a/GPU/GPUTracking/Base/metal/GPUReconstructionMetalKernelsSpecialize.inc b/GPU/GPUTracking/Base/metal/GPUReconstructionMetalKernelsSpecialize.inc index 5f456a7ce06bb..7816b38a0a180 100644 --- a/GPU/GPUTracking/Base/metal/GPUReconstructionMetalKernelsSpecialize.inc +++ b/GPU/GPUTracking/Base/metal/GPUReconstructionMetalKernelsSpecialize.inc @@ -11,6 +11,8 @@ /// \file GPUReconstructionMetalKernelsSpecialize.inc +#include + template <> inline void GPUReconstructionMetal::runKernelBackend(const krnlSetupTime& _xyz, void* const& ptr, uint64_t const& size) { @@ -30,3 +32,21 @@ inline void GPUReconstructionMetal::runKernelBackend(const krn RecordMarker(_xyz.z.ev, _xyz.x.stream); } } + +// 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 +inline void GPUReconstructionMetal::RunOnHost(const krnlSetupTime& _xyz, uint32_t nBlocks, const Args&... args) +{ + const auto start = std::chrono::steady_clock::now(); + krnlSetupArgs argPack{{}, {{{nBlocks, 1, _xyz.x.stream, krnlDeviceType::HostOnDeviceMemory, _xyz.x.step}, _xyz.y, _xyz.z}, _xyz.t}, {args...}}; + runKernelOnHost(GetKernelNum(), &argPack); + _xyz.t = std::chrono::duration(std::chrono::steady_clock::now() - start).count(); +} + +template <> +inline void GPUReconstructionMetal::runKernelBackend(const krnlSetupTime& _xyz, int32_t const& iSector, uint8_t const& mergeMode) +{ + RunOnHost(_xyz, 1, iSector, mergeMode); +} diff --git a/GPU/GPUTracking/Definitions/Parameters/GPUParameters.csv b/GPU/GPUTracking/Definitions/Parameters/GPUParameters.csv index 87336277eadbd..4861a5d669fb8 100644 --- a/GPU/GPUTracking/Definitions/Parameters/GPUParameters.csv +++ b/GPU/GPUTracking/Definitions/Parameters/GPUParameters.csv @@ -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""",,,,,,,,,,,,,,,,, diff --git a/GPU/GPUTracking/Global/GPUChainTrackingMerger.cxx b/GPU/GPUTracking/Global/GPUChainTrackingMerger.cxx index 798689feb5805..06e3e2fe70ace 100644 --- a/GPU/GPUTracking/Global/GPUChainTrackingMerger.cxx +++ b/GPU/GPUTracking/Global/GPUChainTrackingMerger.cxx @@ -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({{nBorderTracks, -WarpSize(), 0, deviceType}}, 0); @@ -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({{1, -WarpSize(), stream, deviceType}}, range1, n1, 0); - runKernel({{1, -WarpSize(), stream, deviceType}}, range2, n2, 1); + runKernel({{1, -WarpSize(), stream, sortDeviceType}}, range1, n1, 0); + runKernel({{1, -WarpSize(), stream, sortDeviceType}}, range2, n2, 1); runKernel({GetGridAuto(stream, deviceType)}, i, mergeMode); } int32_t ne = std::min(n, mRec->NStreams()) - 1; // Stream 0 must wait for all streams, Note n > 1 @@ -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; @@ -221,7 +223,7 @@ int32_t GPUChainTracking::RunTPCTrackingMerger(bool synchronizeOutput) if (mergerSortTracks) { runKernel(GetGridAuto(0, deviceType)); CondWaitEvent(waitForTransfer, &mEvents->single); - runKernel(GetGridAuto(0, deviceType)); + runKernel(GetGridAuto(0, sortDeviceType)); } if (GetProcessingSettings().mergerSanityCheck) { Merger.CheckCollectedTracks(); @@ -239,7 +241,7 @@ int32_t GPUChainTracking::RunTPCTrackingMerger(bool synchronizeOutput) runKernel({{numBlocks, -ThreadCount(), 0, deviceType, RecoStep::TPCMerging}}, MergerShadow.ClusterAttachment(), Merger.NClusters() * sizeof(*MergerShadow.ClusterAttachment())); runKernel(GetGridAuto(0, deviceType)); CondWaitEvent(waitForTransfer, &mEvents->single); - runKernel(GetGridAuto(0, deviceType)); + runKernel(GetGridAuto(0, sortDeviceType)); runKernel(GetGridAuto(0, deviceType)); runKernel(GetGridAuto(0, deviceType)); if (doGPU && rebuildConstrainedRows == 1) { // PrepareForFit1 computed nRebuildTrackRow, needed on the host to allocate the rebuild memory, waited for below @@ -313,7 +315,7 @@ int32_t GPUChainTracking::RunTPCTrackingMerger(bool synchronizeOutput) SynchronizeStream(0); // TODO: could probably synchronize on an event after runKernel } if (param().rec.tpc.mergeLoopersAfterburner) { - runKernel(GetGridAuto(0, deviceType)); + runKernel(GetGridAuto(0, sortDeviceType)); runKernel(doGPU ? GetGrid(Merger.Memory()->nLooperMatchCandidates, 0, deviceType) : GetGridAuto(0, deviceType)); DoDebugAndDump(RecoStep::TPCMerging, GPUChainTrackingDebugFlags::TPCMergingLoopers, Merger, &GPUTPCGMMerger::DumpLoopers, *mDebugFile); } @@ -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(GetGridAuto(0, deviceType)); + runKernel(GetGridAuto(0, sortDeviceType)); mRec->ReturnVolatileDeviceMemory(); if (GetProcessingSettings().clearO2OutputFromGPU) { diff --git a/GPU/GPUTracking/kernels.cmake b/GPU/GPUTracking/kernels.cmake index 0e95c09a3ef78..22462a58d0322 100644 --- a/GPU/GPUTracking/kernels.cmake +++ b/GPU/GPUTracking/kernels.cmake @@ -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]