Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
RooBatchCompute.cu
Go to the documentation of this file.
1/*
2 * Project: RooFit
3 * Authors:
4 * Emmanouil Michalainas, CERN, September 2020
5 *
6 * Copyright (c) 2021, CERN
7 *
8 * Redistribution and use in source and binary forms,
9 * with or without modification, are permitted according to the terms
10 * listed in LICENSE (http://roofit.sourceforge.net/license.txt)
11 */
12
13/**
14\file RooBatchCompute.cu
15\class RbcClass
16\ingroup roofit_dev_docs_batchcompute
17
18This file contains the code for cuda computations using the RooBatchCompute library.
19**/
20
21#include "RooBatchCompute.h"
22#include "RooNaNPacker.h"
23#include "Batches.h"
24#include "CudaInterface.h"
25
26#include <algorithm>
27#include <array>
28#include <cassert>
29#include <cstring>
30#include <functional>
31#include <map>
32#include <queue>
33#include <unordered_map>
34#include <vector>
35
36namespace RooBatchCompute {
37namespace CUDA {
38
39constexpr int blockSize = 512;
40
41namespace {
42
43void fillBatches(Batches &batches, double *output, size_t nEvents, std::size_t nBatches, std::size_t nExtraArgs)
44{
45 batches.nEvents = nEvents;
46 batches.nBatches = nBatches;
47 batches.nExtra = nExtraArgs;
48 batches.output = output;
49}
50
51void fillArrays(Batch *arrays, VarSpan vars, double *buffer, double *bufferDevice, std::size_t nEvents)
52{
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) {
57 // In the scalar case, the value is not on the GPU yet, so we have to
58 // copy the value to the GPU buffer.
59 buffer[i] = span[0];
60 arrays[i]._array = bufferDevice + i;
61 } else {
62 // In the vector input cases, they are already on the GPU, so we can
63 // fill be buffer with some dummy value and set the input span
64 // directly.
65 buffer[i] = 0.0;
66 arrays[i]._array = span.data();
67 }
68 }
69}
70
71int getGridSize(std::size_t n)
72{
73 // The grid size should be not larger than the order of number of streaming
74 // multiprocessors (SMs) in an Nvidia GPU. The number 84 was chosen because
75 // the developers were using an Nvidia RTX A4500, which has 46 SMs. This was
76 // multiplied by a factor of 1.5, as recommended by stackoverflow.
77 //
78 // But when there are not enough elements to load the GPU, the number should
79 // be lower: that's why there is the std::ceil().
80 //
81 // Note: for grid sizes larger than 512, the Kahan summation kernels give
82 // wrong results. This problem is not understood, but also not really worth
83 // investigating further, as that number is unreasonably large anyway.
84 constexpr int maxGridSize = 84;
85 return std::min(int(std::ceil(double(n) / blockSize)), maxGridSize);
86}
87
88/// Scratch memory attached to a CUDA stream, used for staging small
89/// per-kernel-launch data like the Batches descriptor and reduction results.
90///
91/// The slots form a ring: acquire() returns the next slot, waiting for the
92/// completion of the work that was previously enqueued from that slot if it
93/// is still in flight (which is rare, given the depth of the ring). Each slot
94/// pairs a pinned host buffer with a device buffer of the same capacity, so
95/// staging copies are truly asynchronous and no cudaMalloc()/cudaFree() calls
96/// happen in the evaluation hot loop.
97///
98/// Like the rest of the RooBatchCompute library, this class is not
99/// thread-safe: RooFit evaluates on a single thread per process.
100class StreamScratch {
101public:
102 struct Slot {
103 char *host = nullptr; // pinned host memory
104 char *device = nullptr;
105 std::size_t capacity = 0;
106 cudaEvent_t event = nullptr; // recorded after the last enqueued use
107 bool inFlight = false;
108 };
109
110 StreamScratch() = default;
111 StreamScratch(StreamScratch const &) = delete;
112 StreamScratch &operator=(StreamScratch const &) = delete;
113
114 Slot &acquire(std::size_t n)
115 {
116 Slot &slot = _slots[_next];
117 _next = (_next + 1) % _slots.size();
118 if (slot.inFlight) {
119 ERRCHECK(cudaEventSynchronize(slot.event));
120 slot.inFlight = false;
121 }
122 if (slot.capacity < n) {
123 // Reset the slot state before reallocating, so that a throwing
124 // allocation can't leave dangling pointers with a stale capacity
125 // behind (which would lead to a double free later).
126 if (slot.host) {
127 ERRCHECK(cudaFreeHost(slot.host));
128 slot.host = nullptr;
129 }
130 if (slot.device) {
131 ERRCHECK(cudaFree(slot.device));
132 slot.device = nullptr;
133 }
134 slot.capacity = 0;
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;
139 }
140 if (slot.event == nullptr) {
141 ERRCHECK(cudaEventCreateWithFlags(&slot.event, cudaEventDisableTiming));
142 }
143 return slot;
144 }
145
146 /// Mark the last enqueued use of the slot on the stream. The slot will not
147 /// be handed out again before that work has completed.
148 void release(Slot &slot, cudaStream_t stream)
149 {
150 ERRCHECK(cudaEventRecord(slot.event, stream));
151 slot.inFlight = true;
152 }
153
154 /// A persistent slot for a deferred device-to-host readback: an
155 /// asynchronous copy delivers device results (e.g. evaluation error
156 /// counters) into the pinned host buffer, and flushDeferred() forwards
157 /// them to the destination in the caller's memory once the stream was
158 /// synchronized. Slots stay valid from acquireDeferred() until the flush.
159 struct DeferredSlot {
160 char *host = nullptr; // pinned host memory
161 std::size_t capacity = 0;
162 double *dst = nullptr;
163 std::size_t nPending = 0;
164 };
165
166 DeferredSlot &acquireDeferred(std::size_t n)
167 {
168 if (_deferredCursor == _deferredSlots.size()) {
169 _deferredSlots.emplace_back();
170 }
171 DeferredSlot &slot = _deferredSlots[_deferredCursor++];
172 if (slot.capacity < n) {
173 // The slot is idle here: its previous use ended with the flush after
174 // a stream synchronization. Reset the state before reallocating for
175 // exception safety, like in acquire().
176 if (slot.host) {
177 ERRCHECK(cudaFreeHost(slot.host));
178 slot.host = nullptr;
179 }
180 slot.capacity = 0;
181 ERRCHECK(cudaMallocHost(reinterpret_cast<void **>(&slot.host), n));
182 slot.capacity = n;
183 }
184 return slot;
185 }
186
187 /// Copy the completed readbacks to their destinations. Must only be
188 /// called after the stream was synchronized.
189 void flushDeferred()
190 {
191 for (std::size_t i = 0; i < _deferredCursor; ++i) {
192 DeferredSlot &slot = _deferredSlots[i];
193 if (slot.dst) {
194 std::memcpy(slot.dst, slot.host, slot.nPending * sizeof(double));
195 slot.dst = nullptr;
196 slot.nPending = 0;
197 }
198 }
199 _deferredCursor = 0;
200 }
201
202 ~StreamScratch()
203 {
204 // Don't use ERRCHECK here: throwing from a destructor would terminate.
205 for (Slot &slot : _slots) {
206 if (slot.inFlight)
207 cudaEventSynchronize(slot.event);
208 if (slot.event)
209 cudaEventDestroy(slot.event);
210 if (slot.host)
211 cudaFreeHost(slot.host);
212 if (slot.device)
213 cudaFree(slot.device);
214 }
215 for (DeferredSlot &slot : _deferredSlots) {
216 if (slot.host)
217 cudaFreeHost(slot.host);
218 }
219 }
220
221private:
222 std::array<Slot, 64> _slots;
223 std::size_t _next = 0;
224 std::vector<DeferredSlot> _deferredSlots;
225 std::size_t _deferredCursor = 0;
226};
227
228} // namespace
229
230std::vector<void (*)(Batches &)> getFunctions();
231
232/// This class overrides some RooBatchComputeInterface functions, for the
233/// purpose of providing a cuda specific implementation of the library.
235
236public:
238 {
239 dispatchCUDA = this; // Set the dispatch pointer to this instance of the library upon loading
240 }
241
242 Architecture architecture() const override { return Architecture::CUDA; }
243 std::string architectureName() const override { return "cuda"; }
244
245 /** Compute multiple values using cuda kernels.
246 This method creates a Batches object and passes it to the correct compute function.
247 The compute function is launched as a cuda kernel.
248 \param computer An enum specifying the compute function to be used.
249 \param output The array where the computation results are stored.
250 \param vars A std::span containing pointers to the variables involved in the computation.
251 \param extraArgs An optional std::span containing extra double values that may participate in the computation. **/
252 void compute(RooBatchCompute::Config const &cfg, Computer computer, std::span<double> output, VarSpan vars,
253 ArgSpan extraArgs) override
254 {
255 using namespace CudaInterface;
256
257 std::size_t nEvents = output.size();
258
259 const std::size_t memSize = sizeof(Batches) + vars.size() * sizeof(Batch) + vars.size() * sizeof(double) +
260 extraArgs.size() * sizeof(double);
261
262 cudaStream_t stream = *cfg.cudaStream();
263 StreamScratch &streamScratch = scratch(cfg.cudaStream());
264 StreamScratch::Slot &slot = streamScratch.acquire(memSize);
265
266 // The staging area has the same layout in the pinned host buffer and in
267 // the device buffer, so it can be uploaded with a single copy.
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());
272
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());
277
278 fillBatches(*batches, output.data(), nEvents, vars.size(), extraArgs.size());
279 fillArrays(arrays, vars, scalarBuffer, scalarBufferDevice, nEvents);
280 batches->args = arraysDevice;
281
282 if (!extraArgs.empty()) {
283 std::copy(std::cbegin(extraArgs), std::cend(extraArgs), extraArgsHost);
284 batches->extra = extraArgsDevice;
285 }
286
287 copyHostToDevice(slot.host, slot.device, memSize, cfg.cudaStream());
288
289 const int gridSize = getGridSize(nEvents);
290 _computeFunctions[computer]<<<gridSize, blockSize, 0, stream>>>(*batchesDevice);
291
292 // Only the NormalizedPdf and LogNormalizedPdf computers mutate their
293 // extra args: they use them as output parameters for the evaluation
294 // error counts. Instead of synchronizing the stream to read the counters
295 // back immediately, the readback is deferred to avoid stalling the
296 // pipeline: an asynchronous copy delivers them into a persistent pinned
297 // buffer, and the next synchronizeCudaStream() call forwards them to the
298 // caller's span. The caller's memory therefore has to stay valid until
299 // then.
300 if ((computer == NormalizedPdf || computer == LogNormalizedPdf) && !extraArgs.empty()) {
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();
306 }
307
308 streamScratch.release(slot, stream);
309 }
310 /// Return the sum of an input array
311 double reduceSum(RooBatchCompute::Config const &cfg, InputArr input, size_t n) override;
312 ReduceNLLOutput reduceNLL(RooBatchCompute::Config const &cfg, std::span<const double> probas,
313 std::span<const double> weights, std::span<const double> offsetProbas,
314 bool logProbas) override;
315
316 std::unique_ptr<AbsBufferManager> createBufferManager() const override;
317
319 void deleteCudaStream(CudaInterface::CudaStream *stream) const override
320 {
321 _scratchMap.erase(stream);
322 delete stream;
323 }
325 {
326 ERRCHECK(::cudaStreamSynchronize(*stream));
327 // Deliver deferred readbacks (e.g. the evaluation error counters from
328 // compute()) that have completed with the synchronization.
329 auto found = _scratchMap.find(stream);
330 if (found != _scratchMap.end()) {
331 found->second.flushDeferred();
332 }
333 }
334
335private:
336 StreamScratch &scratch(CudaInterface::CudaStream *stream) { return _scratchMap[stream]; }
337
338 const std::vector<void (*)(Batches &)> _computeFunctions;
339 mutable std::unordered_map<CudaInterface::CudaStream *, StreamScratch> _scratchMap;
340
341}; // End class RooBatchComputeClass
342
343inline __device__ void kahanSumUpdate(double &sum, double &carry, double a, double otherCarry)
344{
345 // c is zero the first time around. Then is done a summation as the c variable is NEGATIVE
346 const double y = a - (carry + otherCarry);
347 const double t = sum + y; // Alas, sum is big, y small, so low-order digits of y are lost.
348
349 // (t - sum) cancels the high-order part of y; subtracting y recovers NEGATIVE (low part of y)
350 carry = (t - sum) - y;
351
352 // Algebraically, c should always be zero. Beware overly-aggressive optimizing compilers!
353 sum = t;
354}
355
356// This is the same implementation of the ROOT::Math::KahanSum::operator+=(KahanSum) but in GPU
357inline __device__ void kahanSumReduction(double *shared, size_t n, double *__restrict__ result, int carry_index)
358{
359 // Stride in first iteration = half of the block dim. Then the half of the half...
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]);
363 }
364 __syncthreads();
365 } // Next time around, the lost low part will be added to y in a fresh attempt.
366 // Wait until all threads of the block have finished its work
367
368 if (threadIdx.x == 0) {
369 result[blockIdx.x] = shared[0];
370 result[blockIdx.x + gridDim.x] = shared[carry_index];
371 }
372}
373
374__global__ void kahanSum(const double *__restrict__ input, const double *__restrict__ carries, size_t n,
375 double *__restrict__ result, bool nll)
376{
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;
381
382 // The first half of the shared memory is for storing the summation and the second half for the carry or compensation
383 extern __shared__ double shared[];
384
385 double sum = 0.0;
386 double carry = 0.0;
387
388 for (int i = gthIdx; i < n; i += nThreadsTotal) {
389 // Note: it does not make sense to use the nll option and provide at the
390 // same time external carries.
391 double val = nll == 1 ? -std::log(input[i]) : input[i];
392 kahanSumUpdate(sum, carry, val, carries ? carries[i] : 0.0);
393 }
394
395 shared[thIdx] = sum;
396 shared[carry_index] = carry;
397
398 // Wait until all threads in each block have loaded their elements
399 __syncthreads();
400
401 kahanSumReduction(shared, n, result, carry_index);
402}
403
404/// Computes the negative log likelihood sum with the same semantics as the
405/// CPU implementation of RooBatchComputeInterface::reduceNLL(): zero-weight
406/// events are skipped, and evaluation problems are counted and accumulated
407/// into a "badness" value that the host can pack into a NaN for the error
408/// recovery in the minimizer. The `stats` output has the layout
409/// [badness, nNonPositive, nNaN, nInfinite] and must be zero-initialized.
410/// With `logProbas`, the probabilities are given as logarithms.
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)
414{
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;
419
420 // The first half of the shared memory is for storing the summation and the second half for the carry or compensation
421 extern __shared__ double shared[];
422
423 double sum = 0.0;
424 double carry = 0.0;
425 double badness = 0.0;
426 unsigned int nNonPositive = 0;
427 unsigned int nNaN = 0;
428 unsigned int nInfinite = 0;
429
430 for (int i = gthIdx; i < nWeights; i += nThreadsTotal) {
431 const double weight = weights[i];
432 // Zero-weight events don't contribute to the likelihood. Skipping them
433 // also avoids 0 * inf = NaN for zero probabilities.
434 if (weight == 0.0) {
435 continue;
436 }
437 const double proba = nProbas == 1 ? scalarProba : probas[i];
438 double term;
439 if (logProbas) {
440 if (std::isnan(proba)) {
441 ++nNaN;
443 } else if (proba == -INFINITY) {
444 ++nNonPositive;
445 } else if (std::isinf(proba)) {
446 ++nInfinite;
447 }
448 term = proba;
449 } else if (proba <= 0.0) {
450 ++nNonPositive;
451 badness += -proba;
452 term = std::log(proba);
453 } else if (std::isnan(proba)) {
454 ++nNaN;
456 term = proba;
457 } else {
458 if (std::isinf(proba)) {
459 ++nInfinite;
460 }
461 term = std::log(proba);
462 }
463 if (offsetProbas)
464 term -= std::log(offsetProbas[i]);
465 term *= -weight;
466 kahanSumUpdate(sum, carry, term, 0.0);
467 }
468
469 // Accumulate the evaluation error statistics over the whole grid. These
470 // atomics are on the rare path: they are only executed by threads that
471 // actually encountered problematic values.
472 if (badness != 0.0)
473 atomicAdd(&stats[0], badness);
474 if (nNonPositive != 0)
475 atomicAdd(&stats[1], double(nNonPositive));
476 if (nNaN != 0)
477 atomicAdd(&stats[2], double(nNaN));
478 if (nInfinite != 0)
479 atomicAdd(&stats[3], double(nInfinite));
480
481 shared[thIdx] = sum;
482 shared[carry_index] = carry;
483
484 // Wait until all threads in each block have loaded their elements
485 __syncthreads();
486
487 kahanSumReduction(shared, nWeights, result, carry_index);
488}
489
491{
492 if (n == 0)
493 return 0.0;
494 const int gridSize = getGridSize(n);
495 cudaStream_t stream = *cfg.cudaStream();
496 StreamScratch &streamScratch = scratch(cfg.cudaStream());
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);
500 constexpr int shMemSize = 2 * blockSize * sizeof(double);
501 kahanSum<<<gridSize, blockSize, shMemSize, stream>>>(input, nullptr, n, devOut, false);
502 kahanSum<<<1, blockSize, shMemSize, stream>>>(devOut, devOut + gridSize, gridSize, devOut, false);
503 CudaInterface::copyDeviceToHost(devOut, hostOut, 1, cfg.cudaStream());
504 // Release right after the last enqueued use of the slot, so that the slot
505 // is protected by its event even if the synchronization below throws.
506 streamScratch.release(slot, stream);
507 ERRCHECK(cudaStreamSynchronize(stream));
508 return hostOut[0];
509}
510
512 std::span<const double> weights, std::span<const double> offsetProbas,
513 bool logProbas)
514{
515 ReduceNLLOutput out;
516 if (probas.empty()) {
517 return out;
518 }
519 const int gridSize = getGridSize(weights.size());
520 cudaStream_t stream = *cfg.cudaStream();
521 // Layout of the scratch buffer: [sum, carry, badness, nNonPositive, nNaN,
522 // nInfinite, partial sums (gridSize), partial carries (gridSize)].
523 StreamScratch &streamScratch = scratch(cfg.cudaStream());
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);
527 constexpr int shMemSize = 2 * blockSize * sizeof(double);
528
529#ifndef NDEBUG
530 for (auto span : {probas, weights, offsetProbas}) {
531 // Scalar spans can point to host memory (e.g. the scalar buffer of an
532 // observable-independent pdf), so only spans with more than one element
533 // are required to be on the device.
534 cudaPointerAttributes attr;
535 assert(span.size() <= 1 || span.data() == nullptr ||
536 (cudaPointerGetAttributes(&attr, span.data()) == cudaSuccess && attr.type == cudaMemoryTypeDevice));
537 }
538#endif
539
540 // Zero-initialize the evaluation error statistics for the atomic updates.
541 ERRCHECK(cudaMemsetAsync(devOut + 2, 0, 4 * sizeof(double), stream));
542
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);
546
547 kahanSum<<<1, blockSize, shMemSize, stream>>>(devOut + 6, devOut + 6 + gridSize, gridSize, devOut, 0);
548
549 // The sum, its Kahan carry, and the evaluation error statistics are
550 // adjacent in the output buffer, so they can be read back in a single copy.
551 CudaInterface::copyDeviceToHost(devOut, hostOut, 6, cfg.cudaStream());
552 // Release right after the last enqueued use of the slot, so that the slot
553 // is protected by its event even if the synchronization below throws.
554 streamScratch.release(slot, stream);
555 ERRCHECK(cudaStreamSynchronize(stream));
556
557 out.nllSum = hostOut[0];
558 out.nllSumCarry = hostOut[1];
559 out.nNonPositiveValues = hostOut[3];
560 out.nNaNValues = hostOut[4];
561 out.nInfiniteValues = hostOut[5];
562
563 if (hostOut[2] != 0.0) {
564 // Some events had evaluation errors: return the accumulated "badness"
565 // of the errors packed into a NaN, like the CPU implementation, so the
566 // minimizer can use it to recover.
567 out.nllSum = RooNaNPacker::packFloatIntoNaN(hostOut[2]);
568 out.nllSumCarry = 0.0;
569 }
570
571 return out;
572}
573
574namespace {
575
576class ScalarBufferContainer {
577public:
578 ScalarBufferContainer() {}
579 ScalarBufferContainer(std::size_t size)
580 {
581 if (size != 1)
582 throw std::runtime_error("ScalarBufferContainer can only be of size 1");
583 }
584
585 double const *hostReadPtr() const { return &_val; }
586 double const *deviceReadPtr() const { return &_val; }
587
588 double *hostWritePtr() { return &_val; }
589 double *deviceWritePtr() { return &_val; }
590
591 void assignFromHost(std::span<const double> input) { _val = input[0]; }
592 void assignFromDevice(std::span<const double> input)
593 {
594 CudaInterface::copyDeviceToHost(input.data(), &_val, input.size(), nullptr);
595 }
596
597private:
598 double _val;
599};
600
601class CPUBufferContainer {
602public:
603 CPUBufferContainer(std::size_t size) : _vec(size) {}
604
605 double const *hostReadPtr() const { return _vec.data(); }
606 double const *deviceReadPtr() const
607 {
608 throw std::bad_function_call();
609 return nullptr;
610 }
611
612 double *hostWritePtr() { return _vec.data(); }
613 double *deviceWritePtr()
614 {
615 throw std::bad_function_call();
616 return nullptr;
617 }
618
619 void assignFromHost(std::span<const double> input) { _vec.assign(input.begin(), input.end()); }
620 void assignFromDevice(std::span<const double> input)
621 {
622 CudaInterface::copyDeviceToHost(input.data(), _vec.data(), input.size(), nullptr);
623 }
624
625private:
626 std::vector<double> _vec;
627};
628
629class GPUBufferContainer {
630public:
631 GPUBufferContainer(std::size_t size) : _arr(size) {}
632
633 double const *hostReadPtr() const
634 {
635 throw std::bad_function_call();
636 return nullptr;
637 }
638 double const *deviceReadPtr() const { return _arr.data(); }
639
640 double *hostWritePtr() const
641 {
642 throw std::bad_function_call();
643 return nullptr;
644 }
645 double *deviceWritePtr() const { return const_cast<double *>(_arr.data()); }
646
647 void assignFromHost(std::span<const double> input)
648 {
649 CudaInterface::copyHostToDevice(input.data(), deviceWritePtr(), input.size(), nullptr);
650 }
651 void assignFromDevice(std::span<const double> input)
652 {
653 CudaInterface::copyDeviceToDevice(input.data(), deviceWritePtr(), input.size(), nullptr);
654 }
655
656private:
657 CudaInterface::DeviceArray<double> _arr;
658};
659
660class PinnedBufferContainer {
661public:
662 PinnedBufferContainer(std::size_t size) : _arr{size}, _gpuBuffer{size} {}
663 std::size_t size() const { return _arr.size(); }
664
665 void setCudaStream(CudaInterface::CudaStream *stream) { _cudaStream = stream; }
666
667 double const *hostReadPtr() const
668 {
669
670 if (_lastAccess == LastAccessType::GPU_WRITE) {
671 CudaInterface::copyDeviceToHost(_gpuBuffer.deviceReadPtr(), const_cast<double *>(_arr.data()), size(),
672 _cudaStream);
673 // The copy is asynchronous, and the caller reads the host memory
674 // right away, so the stream needs to be synchronized here.
675 if (_cudaStream) {
676 ERRCHECK(cudaStreamSynchronize(*_cudaStream));
677 }
678 }
679
680 _lastAccess = LastAccessType::CPU_READ;
681 return const_cast<double *>(_arr.data());
682 }
683 double const *deviceReadPtr() const
684 {
685
686 if (_lastAccess == LastAccessType::CPU_WRITE) {
687 CudaInterface::copyHostToDevice(_arr.data(), _gpuBuffer.deviceWritePtr(), size(), _cudaStream);
688 }
689
690 _lastAccess = LastAccessType::GPU_READ;
691 return _gpuBuffer.deviceReadPtr();
692 }
693
694 double *hostWritePtr()
695 {
696 _lastAccess = LastAccessType::CPU_WRITE;
697 return _arr.data();
698 }
699 double *deviceWritePtr()
700 {
701 _lastAccess = LastAccessType::GPU_WRITE;
702 return _gpuBuffer.deviceWritePtr();
703 }
704
705 void assignFromHost(std::span<const double> input) { std::copy(input.begin(), input.end(), hostWritePtr()); }
706 void assignFromDevice(std::span<const double> input)
707 {
708 CudaInterface::copyDeviceToDevice(input.data(), deviceWritePtr(), input.size(), _cudaStream);
709 }
710
711private:
712 enum class LastAccessType {
713 CPU_READ,
714 GPU_READ,
715 CPU_WRITE,
716 GPU_WRITE
717 };
718
719 CudaInterface::PinnedHostArray<double> _arr;
720 GPUBufferContainer _gpuBuffer;
721 CudaInterface::CudaStream *_cudaStream = nullptr;
722 mutable LastAccessType _lastAccess = LastAccessType::CPU_READ;
723};
724
725template <class Container>
726class BufferImpl : public AbsBuffer {
727public:
728 using Queue = std::queue<std::unique_ptr<Container>>;
729
730 BufferImpl(std::size_t size, Queue &queue) : _queue{queue}
731 {
732 if (_queue.empty()) {
733 _vec = std::make_unique<Container>(size);
734 } else {
735 _vec = std::move(_queue.front());
736 _queue.pop();
737 }
738 }
739
740 ~BufferImpl() override { _queue.emplace(std::move(_vec)); }
741
742 double const *hostReadPtr() const override { return _vec->hostReadPtr(); }
743 double const *deviceReadPtr() const override { return _vec->deviceReadPtr(); }
744
745 double *hostWritePtr() override { return _vec->hostWritePtr(); }
746 double *deviceWritePtr() override { return _vec->deviceWritePtr(); }
747
748 void assignFromHost(std::span<const double> input) override { _vec->assignFromHost(input); }
749 void assignFromDevice(std::span<const double> input) override { _vec->assignFromDevice(input); }
750
751 Container &vec() { return *_vec; }
752
753private:
754 std::unique_ptr<Container> _vec;
755 Queue &_queue;
756};
757
758using ScalarBuffer = BufferImpl<ScalarBufferContainer>;
759using CPUBuffer = BufferImpl<CPUBufferContainer>;
760using GPUBuffer = BufferImpl<GPUBufferContainer>;
761using PinnedBuffer = BufferImpl<PinnedBufferContainer>;
762
763struct BufferQueuesMaps {
764 std::map<std::size_t, ScalarBuffer::Queue> scalarBufferQueuesMap;
765 std::map<std::size_t, CPUBuffer::Queue> cpuBufferQueuesMap;
766 std::map<std::size_t, GPUBuffer::Queue> gpuBufferQueuesMap;
767 std::map<std::size_t, PinnedBuffer::Queue> pinnedBufferQueuesMap;
768};
769
770class BufferManager : public AbsBufferManager {
771
772public:
773 BufferManager() : _queuesMaps{std::make_unique<BufferQueuesMaps>()} {}
774
775 std::unique_ptr<AbsBuffer> makeScalarBuffer() override
776 {
777 return std::make_unique<ScalarBuffer>(1, _queuesMaps->scalarBufferQueuesMap[1]);
778 }
779 std::unique_ptr<AbsBuffer> makeCpuBuffer(std::size_t size) override
780 {
781 return std::make_unique<CPUBuffer>(size, _queuesMaps->cpuBufferQueuesMap[size]);
782 }
783 std::unique_ptr<AbsBuffer> makeGpuBuffer(std::size_t size) override
784 {
785 return std::make_unique<GPUBuffer>(size, _queuesMaps->gpuBufferQueuesMap[size]);
786 }
787 std::unique_ptr<AbsBuffer> makePinnedBuffer(std::size_t size, CudaInterface::CudaStream *stream = nullptr) override
788 {
789 auto out = std::make_unique<PinnedBuffer>(size, _queuesMaps->pinnedBufferQueuesMap[size]);
790 out->vec().setCudaStream(stream);
791 return out;
792 }
793
794private:
795 std::unique_ptr<BufferQueuesMaps> _queuesMaps;
796};
797
798} // namespace
799
800std::unique_ptr<AbsBufferManager> RooBatchComputeClass::createBufferManager() const
801{
802 return std::make_unique<BufferManager>();
803}
804
805/// Static object to trigger the constructor which overwrites the dispatch pointer.
807
808} // End namespace CUDA
809} // End namespace RooBatchCompute
#define a(i)
Definition RSha256.hxx:99
std::vector< double > _vec
std::array< Slot, 64 > _slots
char * host
double _val
CudaInterface::CudaStream * _cudaStream
std::map< std::size_t, CPUBuffer::Queue > cpuBufferQueuesMap
std::map< std::size_t, ScalarBuffer::Queue > scalarBufferQueuesMap
double * dst
std::vector< DeferredSlot > _deferredSlots
Queue & _queue
bool inFlight
std::size_t nPending
CudaInterface::DeviceArray< double > _arr
std::size_t capacity
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
std::size_t _next
char * device
double badness
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
Definition Batches.h:32
std::size_t nEvents
Definition Batches.h:46
double *__restrict output
Definition Batches.h:49
std::size_t nBatches
Definition Batches.h:47
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...
Double_t y[n]
Definition legend1.C:17
const Int_t n
Definition legend1.C:16
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
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)
Definition Factory.cxx:2335