33#include <unordered_map>
43void fillBatches(
Batches &batches,
double *output,
size_t nEvents, std::size_t nBatches, std::size_t nExtraArgs)
47 batches.
nExtra = nExtraArgs;
51void fillArrays(
Batch *arrays,
VarSpan vars,
double *buffer,
double *bufferDevice, std::size_t nEvents)
53 for (
int i = 0; i < vars.size(); i++) {
54 const std::span<const double> &span = vars[i];
55 arrays[i].
_isVector = span.empty() || span.size() >= nEvents;
56 if (!arrays[i]._isVector) {
60 arrays[i].
_array = bufferDevice + i;
66 arrays[i].
_array = span.data();
71int getGridSize(std::size_t
n)
84 constexpr int maxGridSize = 84;
85 return std::min(
int(std::ceil(
double(
n) /
blockSize)), maxGridSize);
106 cudaEvent_t
event =
nullptr;
110 StreamScratch() =
default;
111 StreamScratch(StreamScratch
const &) =
delete;
112 StreamScratch &operator=(StreamScratch
const &) =
delete;
114 Slot &acquire(std::size_t
n)
119 ERRCHECK(cudaEventSynchronize(slot.event));
120 slot.inFlight =
false;
122 if (slot.capacity <
n) {
127 ERRCHECK(cudaFreeHost(slot.host));
131 ERRCHECK(cudaFree(slot.device));
132 slot.device =
nullptr;
135 const std::size_t newCapacity = std::max<std::size_t>(
n, 1024);
136 ERRCHECK(cudaMallocHost(
reinterpret_cast<void **
>(&slot.host), newCapacity));
137 ERRCHECK(cudaMalloc(
reinterpret_cast<void **
>(&slot.device), newCapacity));
138 slot.capacity = newCapacity;
140 if (slot.event ==
nullptr) {
141 ERRCHECK(cudaEventCreateWithFlags(&slot.event, cudaEventDisableTiming));
148 void release(Slot &slot, cudaStream_t stream)
150 ERRCHECK(cudaEventRecord(slot.event, stream));
151 slot.inFlight =
true;
159 struct DeferredSlot {
160 char *
host =
nullptr;
166 DeferredSlot &acquireDeferred(std::size_t
n)
172 if (slot.capacity <
n) {
177 ERRCHECK(cudaFreeHost(slot.host));
181 ERRCHECK(cudaMallocHost(
reinterpret_cast<void **
>(&slot.host),
n));
194 std::memcpy(slot.dst, slot.host, slot.nPending *
sizeof(
double));
205 for (Slot &slot :
_slots) {
207 cudaEventSynchronize(slot.event);
209 cudaEventDestroy(slot.event);
211 cudaFreeHost(slot.host);
213 cudaFree(slot.device);
217 cudaFreeHost(slot.host);
255 using namespace CudaInterface;
257 std::size_t nEvents = output.size();
259 const std::size_t memSize =
sizeof(
Batches) + vars.size() *
sizeof(
Batch) + vars.size() *
sizeof(
double) +
260 extraArgs.size() *
sizeof(
double);
264 StreamScratch::Slot &slot = streamScratch.acquire(memSize);
268 auto batches =
reinterpret_cast<Batches *
>(slot.host);
269 auto arrays =
reinterpret_cast<Batch *
>(batches + 1);
270 auto scalarBuffer =
reinterpret_cast<double *
>(arrays + vars.size());
271 auto extraArgsHost =
reinterpret_cast<double *
>(scalarBuffer + vars.size());
273 auto batchesDevice =
reinterpret_cast<Batches *
>(slot.device);
274 auto arraysDevice =
reinterpret_cast<Batch *
>(batchesDevice + 1);
275 auto scalarBufferDevice =
reinterpret_cast<double *
>(arraysDevice + vars.size());
276 auto extraArgsDevice =
reinterpret_cast<double *
>(scalarBufferDevice + vars.size());
278 fillBatches(*batches, output.data(), nEvents, vars.size(), extraArgs.size());
279 fillArrays(arrays, vars, scalarBuffer, scalarBufferDevice, nEvents);
280 batches->
args = arraysDevice;
282 if (!extraArgs.empty()) {
283 std::copy(std::cbegin(extraArgs), std::cend(extraArgs), extraArgsHost);
284 batches->
extra = extraArgsDevice;
287 copyHostToDevice(slot.host, slot.device, memSize, cfg.
cudaStream());
289 const int gridSize = getGridSize(nEvents);
301 const std::size_t nBytes = extraArgs.size() *
sizeof(
double);
302 StreamScratch::DeferredSlot &deferredSlot = streamScratch.acquireDeferred(nBytes);
303 ERRCHECK(cudaMemcpyAsync(deferredSlot.host, extraArgsDevice, nBytes, cudaMemcpyDeviceToHost, stream));
304 deferredSlot.dst = extraArgs.data();
305 deferredSlot.nPending = extraArgs.size();
308 streamScratch.release(slot, stream);
313 std::span<const double> weights, std::span<const double> offsetProbas,
314 bool logProbas)
override;
326 ERRCHECK(::cudaStreamSynchronize(*stream));
331 found->second.flushDeferred();
339 mutable std::unordered_map<CudaInterface::CudaStream *, StreamScratch>
_scratchMap;
346 const double y =
a - (carry + otherCarry);
347 const double t =
sum +
y;
350 carry = (t -
sum) -
y;
360 for (
int i = blockDim.x / 2; i > 0; i >>= 1) {
361 if (threadIdx.x < i && (threadIdx.x + i) <
n) {
362 kahanSumUpdate(shared[threadIdx.x], shared[carry_index], shared[threadIdx.x + i], shared[carry_index + i]);
368 if (threadIdx.x == 0) {
369 result[blockIdx.x] = shared[0];
370 result[blockIdx.x + gridDim.x] = shared[carry_index];
374__global__
void kahanSum(
const double *__restrict__
input,
const double *__restrict__ carries,
size_t n,
375 double *__restrict__
result,
bool nll)
377 int thIdx = threadIdx.x;
378 int gthIdx = thIdx + blockIdx.x *
blockSize;
379 int carry_index = threadIdx.x + blockDim.x;
380 const int nThreadsTotal =
blockSize * gridDim.x;
383 extern __shared__
double shared[];
388 for (
int i = gthIdx; i <
n; i += nThreadsTotal) {
391 double val = nll == 1 ? -std::log(
input[i]) :
input[i];
396 shared[carry_index] = carry;
411__global__
void nllSumKernel(
const double *__restrict__ probas,
const double *__restrict__ weights,
412 const double *__restrict__ offsetProbas,
size_t nProbas,
double scalarProba,
413 bool logProbas,
size_t nWeights,
double *__restrict__
result,
double *__restrict__ stats)
415 int thIdx = threadIdx.x;
416 int gthIdx = thIdx + blockIdx.x *
blockSize;
417 int carry_index = threadIdx.x + blockDim.x;
418 const int nThreadsTotal =
blockSize * gridDim.x;
421 extern __shared__
double shared[];
426 unsigned int nNonPositive = 0;
427 unsigned int nNaN = 0;
428 unsigned int nInfinite = 0;
430 for (
int i = gthIdx; i < nWeights; i += nThreadsTotal) {
431 const double weight = weights[i];
437 const double proba = nProbas == 1 ? scalarProba : probas[i];
440 if (std::isnan(proba)) {
443 }
else if (proba == -INFINITY) {
445 }
else if (std::isinf(proba)) {
449 }
else if (proba <= 0.0) {
452 term = std::log(proba);
453 }
else if (std::isnan(proba)) {
458 if (std::isinf(proba)) {
461 term = std::log(proba);
464 term -= std::log(offsetProbas[i]);
474 if (nNonPositive != 0)
475 atomicAdd(&stats[1],
double(nNonPositive));
477 atomicAdd(&stats[2],
double(nNaN));
479 atomicAdd(&stats[3],
double(nInfinite));
482 shared[carry_index] = carry;
494 const int gridSize = getGridSize(
n);
497 StreamScratch::Slot &slot = streamScratch.acquire(2 * gridSize *
sizeof(
double));
498 auto devOut =
reinterpret_cast<double *
>(slot.device);
499 auto hostOut =
reinterpret_cast<double *
>(slot.host);
501 kahanSum<<<gridSize, blockSize, shMemSize, stream>>>(
input,
nullptr,
n, devOut,
false);
502 kahanSum<<<1, blockSize, shMemSize, stream>>>(devOut, devOut + gridSize, gridSize, devOut,
false);
506 streamScratch.release(slot, stream);
507 ERRCHECK(cudaStreamSynchronize(stream));
512 std::span<const double> weights, std::span<const double> offsetProbas,
516 if (probas.empty()) {
519 const int gridSize = getGridSize(weights.size());
524 StreamScratch::Slot &slot = streamScratch.acquire((6 + 2 * gridSize) *
sizeof(
double));
525 auto devOut =
reinterpret_cast<double *
>(slot.device);
526 auto hostOut =
reinterpret_cast<double *
>(slot.host);
530 for (
auto span : {probas, weights, offsetProbas}) {
534 cudaPointerAttributes
attr;
535 assert(span.size() <= 1 || span.data() ==
nullptr ||
536 (cudaPointerGetAttributes(&
attr, span.data()) == cudaSuccess &&
attr.type == cudaMemoryTypeDevice));
541 ERRCHECK(cudaMemsetAsync(devOut + 2, 0, 4 *
sizeof(
double), stream));
543 nllSumKernel<<<gridSize, blockSize, shMemSize, stream>>>(
544 probas.data(), weights.data(), offsetProbas.empty() ? nullptr : offsetProbas.data(), probas.size(),
545 probas.size() == 1 ? probas[0] : 0.0, logProbas, weights.size(), devOut + 6, devOut + 2);
547 kahanSum<<<1, blockSize, shMemSize, stream>>>(devOut + 6, devOut + 6 + gridSize, gridSize, devOut, 0);
554 streamScratch.release(slot, stream);
555 ERRCHECK(cudaStreamSynchronize(stream));
563 if (hostOut[2] != 0.0) {
576class ScalarBufferContainer {
578 ScalarBufferContainer() {}
579 ScalarBufferContainer(std::size_t
size)
582 throw std::runtime_error(
"ScalarBufferContainer can only be of size 1");
585 double const *hostReadPtr()
const {
return &
_val; }
586 double const *deviceReadPtr()
const {
return &
_val; }
588 double *hostWritePtr() {
return &
_val; }
589 double *deviceWritePtr() {
return &
_val; }
591 void assignFromHost(std::span<const double>
input) {
_val =
input[0]; }
592 void assignFromDevice(std::span<const double>
input)
601class CPUBufferContainer {
605 double const *hostReadPtr()
const {
return _vec.data(); }
606 double const *deviceReadPtr()
const
608 throw std::bad_function_call();
612 double *hostWritePtr() {
return _vec.data(); }
613 double *deviceWritePtr()
615 throw std::bad_function_call();
619 void assignFromHost(std::span<const double>
input) {
_vec.assign(
input.begin(),
input.end()); }
620 void assignFromDevice(std::span<const double>
input)
629class GPUBufferContainer {
633 double const *hostReadPtr()
const
635 throw std::bad_function_call();
638 double const *deviceReadPtr()
const {
return _arr.data(); }
640 double *hostWritePtr()
const
642 throw std::bad_function_call();
645 double *deviceWritePtr()
const {
return const_cast<double *
>(
_arr.data()); }
647 void assignFromHost(std::span<const double>
input)
651 void assignFromDevice(std::span<const double>
input)
657 CudaInterface::DeviceArray<double>
_arr;
660class PinnedBufferContainer {
663 std::size_t
size()
const {
return _arr.size(); }
665 void setCudaStream(CudaInterface::CudaStream *stream) {
_cudaStream = stream; }
667 double const *hostReadPtr()
const
670 if (_lastAccess == LastAccessType::GPU_WRITE) {
676 ERRCHECK(cudaStreamSynchronize(*_cudaStream));
681 return const_cast<double *
>(
_arr.data());
683 double const *deviceReadPtr()
const
686 if (_lastAccess == LastAccessType::CPU_WRITE) {
694 double *hostWritePtr()
699 double *deviceWritePtr()
705 void assignFromHost(std::span<const double>
input) { std::copy(
input.begin(),
input.end(), hostWritePtr()); }
706 void assignFromDevice(std::span<const double>
input)
712 enum class LastAccessType {
719 CudaInterface::PinnedHostArray<double>
_arr;
725template <
class Container>
726class BufferImpl :
public AbsBuffer {
728 using Queue = std::queue<std::unique_ptr<Container>>;
730 BufferImpl(std::size_t
size, Queue &queue) :
_queue{queue}
733 _vec = std::make_unique<Container>(
size);
740 ~BufferImpl()
override {
_queue.emplace(std::move(_vec)); }
742 double const *hostReadPtr()
const override {
return _vec->hostReadPtr(); }
743 double const *deviceReadPtr()
const override {
return _vec->deviceReadPtr(); }
745 double *hostWritePtr()
override {
return _vec->hostWritePtr(); }
746 double *deviceWritePtr()
override {
return _vec->deviceWritePtr(); }
748 void assignFromHost(std::span<const double>
input)
override {
_vec->assignFromHost(
input); }
749 void assignFromDevice(std::span<const double>
input)
override {
_vec->assignFromDevice(
input); }
751 Container &vec() {
return *
_vec; }
754 std::unique_ptr<Container>
_vec;
758using ScalarBuffer = BufferImpl<ScalarBufferContainer>;
759using CPUBuffer = BufferImpl<CPUBufferContainer>;
760using GPUBuffer = BufferImpl<GPUBufferContainer>;
761using PinnedBuffer = BufferImpl<PinnedBufferContainer>;
763struct BufferQueuesMaps {
770class BufferManager :
public AbsBufferManager {
773 BufferManager() :
_queuesMaps{std::make_unique<BufferQueuesMaps>()} {}
775 std::unique_ptr<AbsBuffer> makeScalarBuffer()
override
777 return std::make_unique<ScalarBuffer>(1,
_queuesMaps->scalarBufferQueuesMap[1]);
779 std::unique_ptr<AbsBuffer> makeCpuBuffer(std::size_t
size)
override
783 std::unique_ptr<AbsBuffer> makeGpuBuffer(std::size_t
size)
override
787 std::unique_ptr<AbsBuffer> makePinnedBuffer(std::size_t
size, CudaInterface::CudaStream *stream =
nullptr)
override
790 out->vec().setCudaStream(stream);
802 return std::make_unique<BufferManager>();
std::vector< double > _vec
std::array< Slot, 64 > _slots
CudaInterface::CudaStream * _cudaStream
std::map< std::size_t, CPUBuffer::Queue > cpuBufferQueuesMap
std::map< std::size_t, ScalarBuffer::Queue > scalarBufferQueuesMap
std::vector< DeferredSlot > _deferredSlots
CudaInterface::DeviceArray< double > _arr
std::map< std::size_t, PinnedBuffer::Queue > pinnedBufferQueuesMap
LastAccessType _lastAccess
GPUBufferContainer _gpuBuffer
std::unique_ptr< BufferQueuesMaps > _queuesMaps
std::size_t _deferredCursor
std::map< std::size_t, GPUBuffer::Queue > gpuBufferQueuesMap
size_t size(const MatrixT &matrix)
retrieve the size of a square matrix
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void input
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t result
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t attr
These classes encapsulate the necessary data for the computations.
const double *__restrict _array
double *__restrict output
This class overrides some RooBatchComputeInterface functions, for the purpose of providing a cuda spe...
std::unordered_map< CudaInterface::CudaStream *, StreamScratch > _scratchMap
const std::vector< void(*)(Batches &)> _computeFunctions
CudaInterface::CudaStream * newCudaStream() const override
std::unique_ptr< AbsBufferManager > createBufferManager() const override
ReduceNLLOutput reduceNLL(RooBatchCompute::Config const &cfg, std::span< const double > probas, std::span< const double > weights, std::span< const double > offsetProbas, bool logProbas) override
Reduce the probabilities to the negative log-likelihood.
void deleteCudaStream(CudaInterface::CudaStream *stream) const override
void synchronizeCudaStream(CudaInterface::CudaStream *stream) const override
Wait until all work that was enqueued on the stream has completed.
double reduceSum(RooBatchCompute::Config const &cfg, InputArr input, size_t n) override
Return the sum of an input array.
StreamScratch & scratch(CudaInterface::CudaStream *stream)
std::string architectureName() const override
Architecture architecture() const override
void compute(RooBatchCompute::Config const &cfg, Computer computer, std::span< double > output, VarSpan vars, ArgSpan extraArgs) override
Compute multiple values using cuda kernels.
Minimal configuration struct to steer the evaluation of a single node with the RooBatchCompute librar...
CudaInterface::CudaStream * cudaStream() const
The interface which should be implemented to provide optimised computation functions for implementati...
std::vector< void(*)(Batches &)> getFunctions()
Returns a std::vector of pointers to the compute functions in this file.
static RooBatchComputeClass computeObj
Static object to trigger the constructor which overwrites the dispatch pointer.
__global__ void kahanSum(const double *__restrict__ input, const double *__restrict__ carries, size_t n, double *__restrict__ result, bool nll)
__device__ void kahanSumReduction(double *shared, size_t n, double *__restrict__ result, int carry_index)
__device__ void kahanSumUpdate(double &sum, double &carry, double a, double otherCarry)
__global__ void nllSumKernel(const double *__restrict__ probas, const double *__restrict__ weights, const double *__restrict__ offsetProbas, size_t nProbas, double scalarProba, bool logProbas, size_t nWeights, double *__restrict__ result, double *__restrict__ stats)
Computes the negative log likelihood sum with the same semantics as the CPU implementation of RooBatc...
void copyDeviceToDevice(const T *src, T *dest, std::size_t n, CudaStream *stream=nullptr)
Copies data from the CUDA device to the CUDA device.
void copyHostToDevice(const T *src, T *dest, std::size_t n, CudaStream *stream=nullptr)
Copies data from the host to the CUDA device.
void copyDeviceToHost(const T *src, T *dest, std::size_t n, CudaStream *stream=nullptr)
Copies data from the CUDA device to the host.
Namespace for dispatching RooFit computations to various backends.
R__EXTERN RooBatchComputeInterface * dispatchCUDA
std::span< double > ArgSpan
const double *__restrict InputArr
std::span< const std::span< const double > > VarSpan
std::size_t nInfiniteValues
std::size_t nNonPositiveValues
static double packFloatIntoNaN(float payload)
Pack float into mantissa of a NaN.
static float unpackNaN(double val)
If val is NaN and a this NaN has been tagged as containing a payload, unpack the float from the manti...
static uint64_t sum(uint64_t i)