Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
RooBatchCompute.cxx
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.cxx
15\class RbcClass
16\ingroup roofit_dev_docs_batchcompute
17
18This file contains the code for cpu computations using the RooBatchCompute library.
19**/
20
21#include "RooBatchCompute.h"
22#include "RooNaNPacker.h"
23#include "Batches.h"
24
25#include <ROOT/RConfig.hxx>
26#include <RConfigure.h>
27
28#ifdef R__USE_IMT
29#include <ROOT/TSeq.hxx>
31#endif
32
33#include <Math/Util.h>
34
35#include <algorithm>
36#include <functional>
37#include <limits>
38#include <map>
39#include <memory>
40#include <mutex>
41#include <queue>
42#include <sstream>
43#include <stdexcept>
44
45#include <vector>
46
47#ifndef RF_ARCH
48#error "RF_ARCH should always be defined"
49#endif
50
51namespace RooBatchCompute {
52namespace RF_ARCH {
53
54namespace {
55
56void fillBatches(Batches &batches, double *output, size_t nEvents, std::size_t nBatches, ArgSpan extraArgs)
57{
58 batches.extra = extraArgs.data();
59 batches.nEvents = nEvents;
60 batches.nBatches = nBatches;
61 batches.nExtra = extraArgs.size();
62 batches.output = output;
63}
64
65void fillArrays(std::span<Batch> arrays, VarSpan vars, std::size_t nEvents)
66{
67 for (std::size_t i = 0; i < vars.size(); i++) {
68 arrays[i]._array = vars[i].data();
69 arrays[i]._isVector = vars[i].empty() || vars[i].size() >= nEvents;
70 }
71}
72
73inline void advance(Batches &batches, std::size_t nEvents)
74{
75 for (std::size_t i = 0; i < batches.nBatches; i++) {
76 Batch &arg = batches.args[i];
77 arg._array += arg._isVector * nEvents;
78 }
79 batches.output += nEvents;
80}
81
82/// Run one compute function over the event range [begin, begin + count).
83/// The `_isVector` flags of the inputs are determined by the total number of
84/// events, such that the same inputs are considered per-event arrays no matter
85/// how the full range is split into sub-ranges.
86void computeRange(void (*computeFn)(Batches &), double *output, std::size_t totalNEvents, VarSpan vars,
87 ArgSpan extraArgs, std::size_t begin, std::size_t count)
88{
89 std::vector<Batch> arrays(vars.size());
90 Batches batches;
91 fillBatches(batches, output, count, vars.size(), extraArgs);
92 fillArrays(arrays, vars, totalNEvents);
93 batches.args = arrays.data();
94 advance(batches, begin);
95
96 std::size_t events = count;
97 batches.nEvents = bufferSize;
98 while (events > bufferSize) {
99 computeFn(batches);
100 advance(batches, bufferSize);
101 events -= bufferSize;
102 }
103 batches.nEvents = events;
104 computeFn(batches);
105}
106
107#ifdef R__USE_IMT
108
109// The number of events per task when computing multi-threaded. The chunk
110// boundaries must not depend on the number of threads, such that also the
111// results of the multi-threaded reductions are bitwise independent of the
112// requested number of threads.
113constexpr std::size_t parallelChunkSize = 16384;
114
115// Batches with fewer events than this are always evaluated single-threaded,
116// because the scheduling overhead would exceed the gain from parallelization.
117constexpr std::size_t minParallelSize = 2 * parallelChunkSize;
118
119std::size_t numChunks(std::size_t nEvents)
120{
121 return (nEvents + parallelChunkSize - 1) / parallelChunkSize;
122}
123
124/// Get a cached executor for the given number of threads. All executors share
125/// ROOT's global thread pool: the first executor created in the process
126/// determines its size, and requests for a different number of threads later
127/// on print a warning. Sharing one pool makes sure that parallel evaluations
128/// in several fits (or on top of user-level parallelism) running at the same
129/// time don't oversubscribe the machine.
130ROOT::TThreadExecutor &executorFor(int nThreads)
131{
132 static std::mutex mutex;
133 // The map is deliberately leaked: this library is loaded with dlopen(), so
134 // there is no guaranteed destruction order between its statics and the TBB
135 // runtime underlying the executor, and destroying the thread pool after
136 // TBB tore down its scheduler can crash or hang at process exit.
137 static auto &executors = *new std::map<int, std::unique_ptr<ROOT::TThreadExecutor>>;
138 std::lock_guard<std::mutex> lock{mutex};
139 auto &executor = executors[nThreads];
140 if (!executor) {
141 executor = std::make_unique<ROOT::TThreadExecutor>(nThreads);
142 }
143 return *executor;
144}
145
146/// Call func(iChunk) in parallel, using up to nThreads threads, for the
147/// fixed-size event chunks covering [0, nEvents).
148template <class Func>
149void parallelForChunks(int nThreads, std::size_t nEvents, Func &&func)
150{
151 ROOT::TThreadExecutor &executor = executorFor(nThreads);
152 // Usually, the chunks are handed out to the threads dynamically one by one
153 // for optimal load balancing. But if the shared thread pool has more
154 // threads than requested (because something else initialized it with a
155 // higher concurrency before), the loop is instead split statically into at
156 // most nThreads tasks to still honor the requested number of threads.
157 const unsigned int nTasks = executor.GetPoolSize() > static_cast<unsigned int>(nThreads) ? nThreads : 0;
158 const ROOT::TSeq<unsigned int> chunkIndices{0u, static_cast<unsigned int>(numChunks(nEvents))};
159 executor.Foreach([&](unsigned int iChunk) { func(iChunk); }, chunkIndices, nTasks);
160}
161
162/// First event of a given fixed-size chunk.
163std::size_t chunkBegin(std::size_t iChunk)
164{
165 return iChunk * parallelChunkSize;
166}
167
168/// Number of events in a given fixed-size chunk (the last one can be shorter).
169std::size_t chunkSize(std::size_t iChunk, std::size_t nEvents)
170{
171 return std::min(parallelChunkSize, nEvents - chunkBegin(iChunk));
172}
173
174bool useParallelEvaluation(RooBatchCompute::Config const &cfg, std::size_t nEvents)
175{
176 return cfg.nThreads() > 1 && nEvents >= minParallelSize;
177}
178
179#endif // R__USE_IMT
180
181} // namespace
182
183std::vector<void (*)(Batches &)> getFunctions();
184
185/// This class overrides some RooBatchComputeInterface functions, for the
186/// purpose of providing a CPU specific implementation of the library.
188public:
190 {
191 // Set the dispatch pointer to this instance of the library upon loading
192 dispatchCPU = this;
193 }
194
195 Architecture architecture() const override { return Architecture::RF_ARCH; };
196 std::string architectureName() const override
197 {
198 // transform to lower case to match the original architecture name passed to the compiler
199 std::string out = _R_QUOTEVAL_(RF_ARCH);
200 std::transform(out.begin(), out.end(), out.begin(), [](unsigned char c) { return std::tolower(c); });
201 return out;
202 };
203
204 void compute(Config const &, Computer computer, std::span<double> output, VarSpan vars, ArgSpan extraArgs) override;
205 double reduceSum(Config const &, InputArr input, size_t n) override;
206 ReduceNLLOutput reduceNLL(Config const &, std::span<const double> probas, std::span<const double> weights,
207 std::span<const double> offsetProbas, bool logProbas) override;
208
209 std::unique_ptr<AbsBufferManager> createBufferManager() const override;
210
211 CudaInterface::CudaStream *newCudaStream() const override { throw std::bad_function_call(); }
212 void deleteCudaStream(CudaInterface::CudaStream *) const override { throw std::bad_function_call(); }
213 void synchronizeCudaStream(CudaInterface::CudaStream *) const override { throw std::bad_function_call(); }
214
215private:
216 const std::vector<void (*)(Batches &)> _computeFunctions;
217};
218
219/** Compute multiple values using optimized functions.
220This method creates a Batches object and passes it to the correct compute function.
221If the configuration requests more than one thread and the batch is large
222enough, the events are processed in fixed-size chunks by parallel tasks.
223\param cfg Configuration, steering among other things the number of threads.
224\param computer An enum specifying the compute function to be used.
225\param output The array where the computation results are stored.
226\param vars A std::span containing pointers to the variables involved in the computation.
227\param extraArgs An optional std::span containing extra double values that may participate in the computation. **/
228void RooBatchComputeClass::compute(Config const &cfg, Computer computer, std::span<double> output, VarSpan vars,
229 ArgSpan extraArgs)
230{
231 const std::size_t nEvents = output.size();
232 auto computeFn = _computeFunctions[computer];
233
234#ifdef R__USE_IMT
235 if (useParallelEvaluation(cfg, nEvents)) {
236 const std::size_t nChunks = numChunks(nEvents);
237
238 // Some compute functions use the extra arguments also as scratch space
239 // or as output parameters (e.g. for evaluation error counts), so every
240 // task works on its own copy and the differences to the original values
241 // are merged back afterwards.
242 const std::size_t nExtra = extraArgs.size();
243 std::vector<double> extraCopies(nChunks * nExtra);
244 for (std::size_t iChunk = 0; iChunk < nChunks; ++iChunk) {
245 std::copy(extraArgs.begin(), extraArgs.end(), extraCopies.begin() + iChunk * nExtra);
246 }
247
248 parallelForChunks(cfg.nThreads(), nEvents, [&](std::size_t iChunk) {
249 computeRange(computeFn, output.data(), nEvents, vars, {extraCopies.data() + iChunk * nExtra, nExtra},
250 chunkBegin(iChunk), chunkSize(iChunk, nEvents));
251 });
252
253 for (std::size_t k = 0; k < nExtra; ++k) {
254 double delta = 0.0;
255 for (std::size_t iChunk = 0; iChunk < nChunks; ++iChunk) {
256 delta += extraCopies[iChunk * nExtra + k] - extraArgs[k];
257 }
258 extraArgs[k] += delta;
259 }
260 return;
261 }
262#else
263 (void)cfg;
264#endif
265
266 computeRange(computeFn, output.data(), nEvents, vars, extraArgs, 0, nEvents);
267}
268
269namespace {
270
271inline std::pair<double, double> getLog(double prob, ReduceNLLOutput &out)
272{
273 if (prob <= 0.0) {
274 out.nNonPositiveValues++;
275 return {std::log(prob), -prob};
276 }
277
278 if (std::isinf(prob)) {
279 out.nInfiniteValues++;
280 }
281
282 if (std::isnan(prob)) {
283 out.nNaNValues++;
284 return {prob, RooNaNPacker::unpackNaN(prob)};
285 }
286
287 return {std::log(prob), 0.0};
288}
289
290/// Like getLog(), but for a probability that is already given as logarithm.
291inline std::pair<double, double> checkLog(double logProb, ReduceNLLOutput &out)
292{
293 if (std::isnan(logProb)) {
294 out.nNaNValues++;
295 return {logProb, RooNaNPacker::unpackNaN(logProb)};
296 }
297
298 if (logProb == -std::numeric_limits<double>::infinity()) {
299 out.nNonPositiveValues++;
300 } else if (std::isinf(logProb)) {
301 out.nInfiniteValues++;
302 }
303
304 return {logProb, 0.0};
305}
306
307} // namespace
308
309double RooBatchComputeClass::reduceSum(Config const &cfg, InputArr input, size_t n)
310{
311#ifdef R__USE_IMT
312 if (useParallelEvaluation(cfg, n)) {
313 const std::size_t nChunks = numChunks(n);
314 std::vector<ROOT::Math::KahanSum<double, 4u>> partials(nChunks);
315 parallelForChunks(cfg.nThreads(), n, [&](std::size_t iChunk) {
316 const std::size_t begin = chunkBegin(iChunk);
317 partials[iChunk] =
318 ROOT::Math::KahanSum<double, 4u>::Accumulate(input + begin, input + begin + chunkSize(iChunk, n));
319 });
320 // Combine the partial sums in fixed chunk order, so that the result
321 // doesn't depend on the number of threads.
323 for (auto const &partial : partials) {
324 total += partial;
325 }
326 return total.Sum();
327 }
328#else
329 (void)cfg;
330#endif
332}
333
334namespace {
335
336/// Accumulator for the negative log-likelihood reduction over one event range.
337struct NLLPartialResult {
339 double badness = 0.0;
340 ReduceNLLOutput counters;
341};
342
343/// With `LogProbas`, the probabilities are given as logarithms. It's a
344/// template parameter, so that no logarithms are evaluated speculatively.
345template <bool LogProbas>
346void reduceNLLRange(std::span<const double> probas, std::span<const double> weights,
347 std::span<const double> offsetProbas, std::size_t begin, std::size_t end, NLLPartialResult &result)
348{
349 for (std::size_t i = begin; i < end; ++i) {
350
351 if (0. == weights[i])
352 continue;
353
354 const double proba = probas.size() == 1 ? probas[0] : probas[i];
355 std::pair<double, double> logOut = LogProbas ? checkLog(proba, result.counters) : getLog(proba, result.counters);
356 double term = logOut.first;
357 result.badness += logOut.second;
358
359 if (!offsetProbas.empty()) {
360 term -= std::log(offsetProbas[i]);
361 }
362
363 term *= -weights[i];
364
365 result.nllSum.Add(term);
366 }
367}
368
369void reduceNLLRange(std::span<const double> probas, std::span<const double> weights,
370 std::span<const double> offsetProbas, bool logProbas, std::size_t begin, std::size_t end,
371 NLLPartialResult &result)
372{
373 if (logProbas) {
374 reduceNLLRange<true>(probas, weights, offsetProbas, begin, end, result);
375 } else {
376 reduceNLLRange<false>(probas, weights, offsetProbas, begin, end, result);
377 }
378}
379
380} // namespace
381
382ReduceNLLOutput RooBatchComputeClass::reduceNLL(Config const &cfg, std::span<const double> probas,
383 std::span<const double> weights, std::span<const double> offsetProbas,
384 bool logProbas)
385{
386 const std::size_t n = weights.size();
387 NLLPartialResult result;
388
389#ifdef R__USE_IMT
390 if (useParallelEvaluation(cfg, n)) {
391 const std::size_t nChunks = numChunks(n);
392 std::vector<NLLPartialResult> partials(nChunks);
393 parallelForChunks(cfg.nThreads(), n, [&](std::size_t iChunk) {
394 const std::size_t begin = chunkBegin(iChunk);
395 reduceNLLRange(probas, weights, offsetProbas, logProbas, begin, begin + chunkSize(iChunk, n),
396 partials[iChunk]);
397 });
398 // Combine the partial results in fixed chunk order, so that the result
399 // doesn't depend on the number of threads.
400 for (auto const &partial : partials) {
401 result.nllSum += partial.nllSum;
402 result.badness += partial.badness;
403 result.counters.nInfiniteValues += partial.counters.nInfiniteValues;
404 result.counters.nNonPositiveValues += partial.counters.nNonPositiveValues;
405 result.counters.nNaNValues += partial.counters.nNaNValues;
406 }
407 } else {
408 reduceNLLRange(probas, weights, offsetProbas, logProbas, 0, n, result);
409 }
410#else
411 (void)cfg;
412 reduceNLLRange(probas, weights, offsetProbas, logProbas, 0, n, result);
413#endif
414
415 ReduceNLLOutput out = result.counters;
416 out.nllSum = result.nllSum.Sum();
417 out.nllSumCarry = result.nllSum.Carry();
418
419 if (result.badness != 0.) {
420 // Some events with evaluation errors. Return "badness" of errors.
422 out.nllSumCarry = 0.0;
423 }
424
425 return out;
426}
427
428namespace {
429
430class ScalarBufferContainer {
431public:
432 ScalarBufferContainer() {}
433 ScalarBufferContainer(std::size_t size)
434 {
435 if (size != 1)
436 throw std::runtime_error("ScalarBufferContainer can only be of size 1");
437 }
438
439 double const *hostReadPtr() const { return &_val; }
440 double const *deviceReadPtr() const { return &_val; }
441
442 double *hostWritePtr() { return &_val; }
443 double *deviceWritePtr() { return &_val; }
444
445 void assignFromHost(std::span<const double> input) { _val = input[0]; }
446 void assignFromDevice(std::span<const double>) { throw std::bad_function_call(); }
447
448private:
449 double _val = 0.0;
450};
451
452class CPUBufferContainer {
453public:
454 CPUBufferContainer(std::size_t size) : _vec(size) {}
455
456 double const *hostReadPtr() const { return _vec.data(); }
457 double const *deviceReadPtr() const
458 {
459 throw std::bad_function_call();
460 return nullptr;
461 }
462
463 double *hostWritePtr() { return _vec.data(); }
464 double *deviceWritePtr()
465 {
466 throw std::bad_function_call();
467 return nullptr;
468 }
469
470 void assignFromHost(std::span<const double> input) { _vec.assign(input.begin(), input.end()); }
471 void assignFromDevice(std::span<const double>) { throw std::bad_function_call(); }
472
473private:
474 std::vector<double> _vec;
475};
476
477template <class Container>
478class BufferImpl : public AbsBuffer {
479public:
480 using Queue = std::queue<std::unique_ptr<Container>>;
481
482 BufferImpl(std::size_t size, Queue &queue) : _queue{queue}
483 {
484 if (_queue.empty()) {
485 _vec = std::make_unique<Container>(size);
486 } else {
487 _vec = std::move(_queue.front());
488 _queue.pop();
489 }
490 }
491
492 ~BufferImpl() override { _queue.emplace(std::move(_vec)); }
493
494 double const *hostReadPtr() const override { return _vec->hostReadPtr(); }
495 double const *deviceReadPtr() const override { return _vec->deviceReadPtr(); }
496
497 double *hostWritePtr() override { return _vec->hostWritePtr(); }
498 double *deviceWritePtr() override { return _vec->deviceWritePtr(); }
499
500 void assignFromHost(std::span<const double> input) override { _vec->assignFromHost(input); }
501 void assignFromDevice(std::span<const double> input) override { _vec->assignFromDevice(input); }
502
503 Container &vec() { return *_vec; }
504
505private:
506 std::unique_ptr<Container> _vec;
507 Queue &_queue;
508};
509
510using ScalarBuffer = BufferImpl<ScalarBufferContainer>;
511using CPUBuffer = BufferImpl<CPUBufferContainer>;
512
513struct BufferQueuesMaps {
514 std::map<std::size_t, ScalarBuffer::Queue> scalarBufferQueuesMap;
515 std::map<std::size_t, CPUBuffer::Queue> cpuBufferQueuesMap;
516};
517
518class BufferManager : public AbsBufferManager {
519
520public:
521 BufferManager() : _queuesMaps{std::make_unique<BufferQueuesMaps>()} {}
522
523 std::unique_ptr<AbsBuffer> makeScalarBuffer() override
524 {
525 return std::make_unique<ScalarBuffer>(1, _queuesMaps->scalarBufferQueuesMap[1]);
526 }
527 std::unique_ptr<AbsBuffer> makeCpuBuffer(std::size_t size) override
528 {
529 return std::make_unique<CPUBuffer>(size, _queuesMaps->cpuBufferQueuesMap[size]);
530 }
531 std::unique_ptr<AbsBuffer> makeGpuBuffer(std::size_t) override { throw std::bad_function_call(); }
532 std::unique_ptr<AbsBuffer> makePinnedBuffer(std::size_t, CudaInterface::CudaStream * = nullptr) override
533 {
534 throw std::bad_function_call();
535 }
536
537private:
538 std::unique_ptr<BufferQueuesMaps> _queuesMaps;
539};
540
541} // namespace
542
543std::unique_ptr<AbsBufferManager> RooBatchComputeClass::createBufferManager() const
544{
545 return std::make_unique<BufferManager>();
546}
547
548/// Static object to trigger the constructor which overwrites the dispatch pointer.
550
551} // End namespace RF_ARCH
552} // End namespace RooBatchCompute
#define RF_ARCH
#define _R_QUOTEVAL_(string)
Definition RConfig.hxx:426
#define c(i)
Definition RSha256.hxx:101
std::vector< double > _vec
double _val
std::map< std::size_t, CPUBuffer::Queue > cpuBufferQueuesMap
std::map< std::size_t, ScalarBuffer::Queue > scalarBufferQueuesMap
Queue & _queue
std::unique_ptr< BufferQueuesMaps > _queuesMaps
double badness
ROOT::Math::KahanSum< double > nllSum
ReduceNLLOutput counters
size_t size(const MatrixT &matrix)
retrieve the size of a square matrix
static unsigned int total
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
The Kahan summation is a compensated summation algorithm, which significantly reduces numerical error...
Definition Util.h:141
static KahanSum< T, N > Accumulate(Iterator begin, Iterator end, T initialValue=T{})
Iterate over a range and return an instance of a KahanSum.
Definition Util.h:230
A pseudo container class which is a generator of indices.
Definition TSeq.hxx:67
This class provides a simple interface to execute the same task multiple times in parallel threads,...
unsigned GetPoolSize() const
Returns the number of worker threads in the task arena.
void Foreach(F func, unsigned nTimes, unsigned nChunks=0)
Execute a function without arguments several times in parallel, dividing the execution in nChunks.
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
Minimal configuration struct to steer the evaluation of a single node with the RooBatchCompute librar...
This class overrides some RooBatchComputeInterface functions, for the purpose of providing a CPU spec...
void compute(Config const &, Computer computer, std::span< double > output, VarSpan vars, ArgSpan extraArgs) override
Compute multiple values using optimized functions.
const std::vector< void(*)(Batches &)> _computeFunctions
double reduceSum(Config const &, InputArr input, size_t n) override
void deleteCudaStream(CudaInterface::CudaStream *) const override
std::unique_ptr< AbsBufferManager > createBufferManager() const override
CudaInterface::CudaStream * newCudaStream() const override
void synchronizeCudaStream(CudaInterface::CudaStream *) const override
Wait until all work that was enqueued on the stream has completed.
ReduceNLLOutput reduceNLL(Config const &, 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.
The interface which should be implemented to provide optimised computation functions for implementati...
const Int_t n
Definition legend1.C:16
std::vector< void(*)(Batches &)> getFunctions()
static RooBatchComputeClass computeObj
Static object to trigger the constructor which overwrites the dispatch pointer.
Namespace for dispatching RooFit computations to various backends.
std::span< double > ArgSpan
R__EXTERN RooBatchComputeInterface * dispatchCPU
This dispatch pointer points to an implementation of the compute library, provided one has been loade...
constexpr std::size_t bufferSize
const double *__restrict InputArr
std::span< const std::span< const double > > VarSpan
void probas(TString dataset, TString fin="TMVA.root", Bool_t useTMVAStyle=kTRUE)
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...