MaCh3  2.8.0
Reference Guide
UnbinnedSplineHandler.cpp
Go to the documentation of this file.
2 
3 #ifdef MaCh3_CUDA
5 #endif
6 
7 #pragma GCC diagnostic ignored "-Wuseless-cast"
8 
9 // *****************************************
10 //Set everything to NULL or 0
12 // *****************************************
14 
15  nKnots = 0;
16  nTF1coeff = 0;
17  NEvents = 0;
18  NTF1_valid = 0;
19 
20  cpu_weights_spline_var = nullptr;
21  cpu_weights_tf1_var = nullptr;
22 
23  cpu_total_weights = nullptr;
24 }
25 
26 // *****************************************
27 UnbinnedSplineHandler::UnbinnedSplineHandler(std::vector<std::vector<TResponseFunction_red*> > &MasterSpline,
28  const std::vector<RespFuncType> &SplineType,
29  const bool SaveFlatTree,
30  const std::string& _FastSplineName,
31  const bool Use_GPU) : SplineBase(Use_GPU) {
32 // *****************************************
33  //KS: If true it will save spline monolith into huge ROOT file
34  SaveSplineFile = SaveFlatTree;
35  FastSplineName = _FastSplineName;
36  Initialise();
37 
38  // Convert the TSpline3 pointers to the reduced form and call the reduced constructor
39  PrepareForGPU(MasterSpline, SplineType);
40 }
41 
42 // *****************************************
43 // The shared initialiser from constructors of TSpline3 and TSpline3_red
44 void UnbinnedSplineHandler::PrepareForGPU(std::vector<std::vector<TResponseFunction_red*> > &MasterSpline, const std::vector<RespFuncType> &SplineType) {
45 // *****************************************
46  // Scan for the max number of knots, the number of events (number of splines), and number of parameters
47  int maxnSplines = 0;
48  ScanMasterSpline(MasterSpline,
49  NEvents,
50  _max_knots,
51  nParams,
52  maxnSplines,
54  nKnots,
55  NTF1_valid,
56  nTF1coeff,
57  SplineType);
58 
59  MACH3LOG_INFO("Found {} events", NEvents);
60  MACH3LOG_INFO("Found {} knots at max", _max_knots);
61  MACH3LOG_INFO("Found {} parameters", nParams);
62  MACH3LOG_INFO("Found {} maximum number of splines in an event", maxnSplines);
63  MACH3LOG_INFO("Found total {} knots in all splines", nKnots);
64  MACH3LOG_INFO("Number of splines = {}", NSplines_valid);
65  MACH3LOG_INFO("Found total {} coeffs in all TF1", nTF1coeff);
66  MACH3LOG_INFO("Number of TF1 = {}", NTF1_valid);
67 
68  unsigned int event_size_max = _max_knots * nParams;
69  // Declare the {x}, {y,b,c,d} arrays for all possible splines which the event has
70  // We'll filter off the flat and "disabled" (e.g. CCQE event should not have MARES spline) ones in the next for loop, but need to declare these beasts here
71 
72  // Declare the {y,b,c,d} for each knot
73  // float because GPU precision (could change to double, but will incur significant speed reduction on GPU unless you're very rich!)
74  const std::size_t totalCoefficients = static_cast<std::size_t>(nKnots) * static_cast<std::size_t>(_nCoeff_);
75  cpu_monolith->coeff_many.resize(totalCoefficients);// *4 because we store y,b,c,d parameters in this array
76  //KS: For x coeff we assume that for given dial (MAQE) spacing is identical,
77  // here we are sloppy and assume each dial has the same number of knots, not a big problem
78  cpu_monolith->coeff_x.resize(event_size_max, -999);
79 
80  //CW: With TF1 we only save the coefficients and the order of the polynomial
81  // Makes most sense to have one large monolithic array, but then it becomes impossible to tell apart a coefficient from a "number of points". So have two arrays: one of coefficients and one of number of points
82  // Let's first assume all are of _max_knots size
83  // Now declare the arrays for each point in the valid splines which the event actually has (i.e. include the splines that the event undergoes)
84  // Also make array with the number of points per spline (not per spline point!)
85  // float because GPU precision (could change to double, but will incur significant speed reduction on GPU unless you're very rich!)
87  cpu_coeff_TF1_many.resize(nTF1coeff); // *5 because this array holds a,b,c,d,e parameters
88 
89  //KS: Map keeping track how many parameters applies to each event, we keep two numbers here {number of splines per event, index where splines start for a given event}
90  cpu_nParamPerEvent.resize(2 * NEvents, -1);
91  cpu_nParamPerEvent_tf1.resize(2 * NEvents, -1);
92 
93  // Make array with the number of points per spline (not per spline point!)
95  //KS: And array which tells where each spline stars in a big monolith array, sort of knot map
98 
99  // Temporary arrays to hold the coefficients for each spline
100  // We get one x, one y, one b,... for each point, so only need to be _max_knots big
101  //KS: Some params has less splines but this is all right main array will get proper number while this temp will be deleted
102  float *x_tmp = new float[_max_knots]();
103  float *many_tmp = new float[_max_knots*_nCoeff_]();
104  float *temp_coeffs = new float[_nTF1Coeff_]();
105 
106  // Count the number of events
107  unsigned int KnotCounter = 0;
108  unsigned int TF1PointsCounter = 0;
109  unsigned int NSplinesCounter = 0;
110  unsigned int TF1sCounter = 0;
111  int ParamCounter = 0;
112  int ParamCounterGlobal = 0;
113  int ParamCounter_TF1 = 0;
114  int ParamCounterGlobalTF1 = 0;
115  // Loop over events and extract the spline coefficients
116  for(unsigned int EventCounter = 0; EventCounter < MasterSpline.size(); ++EventCounter) {
117  // Structure of MasterSpline is std::vector<std::vector<TSpline3*>>
118  // A conventional iterator to count which parameter a given spline should be applied to
119  for(unsigned int ParamNumber = 0; ParamNumber < MasterSpline[EventCounter].size(); ++ParamNumber) {
120  // If nullptr we don't have this spline for the event, so move to next spline
121  if (MasterSpline[EventCounter][ParamNumber] == nullptr) continue;
122 
123  if(SplineType[ParamNumber] == kTSpline3_red)
124  {
125  //KS: how much knots each spline has
126  int nPoints_tmp = 0;
127  // Get a pointer to the current spline for this event
128  TResponseFunction_red* TespFunc = MasterSpline[EventCounter][ParamNumber];
129  TSpline3_red* CurrSpline = static_cast<TSpline3_red*>(TespFunc);
130 
131  // If the number of knots are greater than 2 the spline is not a dummy and we should extract coefficients to load onto the GPU
132  GetSplineCoeff_SepMany(CurrSpline, nPoints_tmp, x_tmp, many_tmp);
133 
134  //KS: One knot means flat spline so ignore
135  if (nPoints_tmp == 1) continue;
136  for (int j = 0; j < _max_knots; ++j) {
137  cpu_monolith->coeff_x[ParamNumber*_max_knots + j] = x_tmp[j];
138  }
139  //KS: Contrary to X coeff we keep for other coeff only filled knots, there is no much gain for doing so for x coeff
140  for (int j = 0; j < nPoints_tmp; ++j) {
141  for (int k = 0; k < _nCoeff_; k++) {
142  cpu_monolith->coeff_many[KnotCounter*_nCoeff_ + j*_nCoeff_ + k] = many_tmp[j*_nCoeff_+k];
143  }
144  }
145  // Set the parameter number for this spline
146  cpu_monolith->paramNo_arr[NSplinesCounter] = short(ParamNumber);
147  //KS: Fill map when each spline starts
148  cpu_monolith->nKnots_arr[NSplinesCounter] = KnotCounter;
149  KnotCounter += nPoints_tmp;
150 
151  ++ParamCounter;
152  // Increment the counter for the number of good splines we have
153  ++NSplinesCounter;
154  }
155  else if (SplineType[ParamNumber] == kTF1_red)
156  {
157  // Don't actually use this ever -- we give each spline the maximum number of points found in all splines
158  int nPoints_tmp = 0;
159  // Get a pointer to the current spline for this event
160  TF1_red* CurrSpline = dynamic_cast<TF1_red*>(MasterSpline[EventCounter][ParamNumber]);
161 
162  // If the number of knots are greater than 2 the spline is not a dummy and we should extract coefficients to load onto the GPU
163  GetTF1Coeff(CurrSpline, nPoints_tmp, temp_coeffs);
164  for (int j = 0; j < _nTF1Coeff_; ++j) {
165  cpu_coeff_TF1_many[TF1PointsCounter+j] = temp_coeffs[j];
166  }
167  // Save the number of points for this spline
168  cpu_nPoints_arr[TF1sCounter] = short(nPoints_tmp);
169 
170  TF1PointsCounter += nPoints_tmp;
171  // Set the parameter number for this spline
172  cpu_paramNo_TF1_arr[TF1sCounter] = short(ParamNumber);
173  ++ParamCounter_TF1;
174  // Increment the counter for the number of good splines we have
175  ++TF1sCounter;
176  }
177  //KS: Don't delete in debug
178  #ifndef MACH3_DEBUG
179  delete MasterSpline[EventCounter][ParamNumber];
180  MasterSpline[EventCounter][ParamNumber] = nullptr;
181  #endif
182  } // End the loop over the parameters in the MasterSpline
183  cpu_nParamPerEvent[2*EventCounter] = ParamCounter;
184  cpu_nParamPerEvent[2*EventCounter+1] = ParamCounterGlobal;
185  ParamCounterGlobal += ParamCounter;
186 
187  cpu_nParamPerEvent_tf1[2*EventCounter] = ParamCounter_TF1;
188  cpu_nParamPerEvent_tf1[2*EventCounter+1] = ParamCounterGlobalTF1;
189  ParamCounterGlobalTF1 += ParamCounter_TF1;
190 
191  ParamCounter = 0;
192  ParamCounter_TF1 = 0;
193  } // End the loop over the number of events
194  delete[] many_tmp;
195  delete[] x_tmp;
196  delete[] temp_coeffs;
197 
198  int BadXCounter = 0;
199  for (unsigned int j = 0; j < event_size_max; j++) {
200  if (cpu_monolith->coeff_x[j] == -999) BadXCounter++;
201  // Perform checks that all entries have been modified from initial values
202  if (cpu_monolith->coeff_x[j] == -999 && BadXCounter < 5) {
203  MACH3LOG_WARN("***** BAD X !! *****");
204  MACH3LOG_WARN("Indicates some parameter doesn't have a single spline");
205  MACH3LOG_WARN("j = {}", j);
206  //throw MaCh3Exception(__FILE__ , __LINE__ );
207  }
208  if(BadXCounter == 5) MACH3LOG_WARN("There is more unutilised knots although I will stop spamming");
209  }
210 
211  MACH3LOG_WARN("Found in total {} BAD X", BadXCounter);
212  //KS: This is tricky as this variable use both by CPU and GPU, however if use CUDA we use cudaMallocHost
213  if (!useGPU) {
215  cpu_weights_spline_var = new float[NSplines_valid]();
216  cpu_weights_tf1_var = new float[NTF1_valid]();
217  }
218 
219  // Print some info; could probably make this to a separate function
222 
223  MoveToGPU();
224 
225  // Can pass the spline segments to the GPU instead of the values
226  // Make these here and only refill them for each loop, avoiding unnecessary new/delete on each reconfigure
227  SetupSegments();
228 }
229 
230 // *****************************************
231 // The shared initialiser from constructors of TSpline3 and TSpline3_red
233 // *****************************************
234  #ifdef MaCh3_CUDA
235  if(!useGPU) return;
236  unsigned int event_size_max = _max_knots * nParams;
237  MACH3LOG_INFO("Total size = {:.2f} MB memory on CPU to move to GPU",
238  (double(sizeof(float) * nKnots * _nCoeff_) + double(sizeof(float) * event_size_max) / 1.E6 +
239  double(sizeof(short int) * NSplines_valid)) / 1.E6);
240  MACH3LOG_INFO("Total TF1 size = {:.2f} MB memory on CPU to move to GPU",
241  double(sizeof(float) * NTF1_valid * _nTF1Coeff_) / 1.E6);
242  MACH3LOG_INFO("GPU weight array (GPU->CPU every step) = {:.2f} MB", static_cast<double>(sizeof(float)) * (NSplines_valid + NTF1_valid) / 1.0e6);
243  MACH3LOG_INFO("Since you are running Total event weight mode then GPU weight array (GPU->CPU every step) = {:.2f} MB",
244  double(sizeof(float) * NEvents) / 1.E6);
245  MACH3LOG_INFO("Parameter value array (CPU->GPU every step) = {:.4f} MB", double(sizeof(float) * nParams) / 1.E6);
246  //CW: With the new set-up we have: 1 coefficient array of size coeff_array_size, all same size
247  // 1 coefficient array of size coeff_array_size*4, holding y,b,c,d in order (y11,b11,c11,d11; y12,b12,c12,d12;...) where ynm is n = spline number, m = spline point. Should really make array so that order is (y11,b11,c11,d11; y21,b21,c21,d21;...) because it will optimise cache hits I think; try this if you have time
248  // return gpu_weights
249 
251 
252  // The gpu_XY arrays don't actually need initialising, since they are only placeholders for what we'll move onto the GPU. As long as we cudaMalloc the size of the arrays correctly there shouldn't be any problems
253  // Can probably make this a bit prettier but will do for now
254  // Could be a lot smaller of a function...
256  nKnots, // How many entries in coefficient array (*4 for the "many" array)
257  NSplines_valid, // What's the number of splines we have (also number of entries in gpu_nPoints_arr)
258  NTF1_valid,
259  event_size_max //Knots times event number of unique splines
260  );
261 
264  NEvents
265  );
266 
267  // Move number of splines and spline size to constant GPU memory; every thread does not need a copy...
268  // The implementation lives in splines/gpuSplineUtils.cu
269  // The GPU splines don't actually need declaring but is good for demonstration, kind of
270  // fixed by passing const reference
272  cpu_monolith,
273 
274  // TFI related now
277  NEvents,
280  nParams,
282  _max_knots,
283  nKnots,
284  NTF1_valid);
285 
286  // Delete all the coefficient arrays from the CPU once they are on the GPU
291  delete cpu_monolith;
292  cpu_monolith = nullptr;
293  MACH3LOG_INFO("Good GPU loading");
294  #endif
295 }
296 
297 // Need to specify template functions in header
298 // *****************************************
299 // Scan the master spline to get the maximum number of knots in any of the TSpline3*
300 void UnbinnedSplineHandler::ScanMasterSpline(std::vector<std::vector<TResponseFunction_red*> > & MasterSpline,
301  unsigned int &nEvents,
302  short int &MaxPoints,
303  short int &numParams,
304  int &nSplines,
305  unsigned int &NSplinesValid,
306  unsigned int &numKnots,
307  unsigned int &nTF1Valid,
308  unsigned int &nTF1_coeff,
309  const std::vector<RespFuncType> &SplineType) {
310 // *****************************************
311  // Need to extract: the total number of events
312  // number of parameters
313  // maximum number of knots
314  MaxPoints = 0;
315  nEvents = 0;
316  numParams = 0;
317  nSplines = 0;
318  numKnots = 0;
319  NSplinesValid = 0;
320  nTF1Valid = 0;
321  nTF1_coeff = 0;
322 
323  // Check the number of events
324  nEvents = int(MasterSpline.size());
325 
326  // Maximum number of splines one event can have (scan through and find this number)
327  int nMaxSplines_PerEvent = 0;
328 
329  //KS: We later check that each event has the same number of splines so this is fine
330  numParams = short(MasterSpline[0].size());
331  // Initialise
332  SplineInfoArray.resize(numParams);
333 
334  // Loop over each parameter
335  for(unsigned int EventCounter = 0; EventCounter < MasterSpline.size(); ++EventCounter) {
336  // Check that each event has each spline saved
337  if (numParams > 0) {
338  int TempSize = int(MasterSpline[EventCounter].size());
339  if (TempSize != numParams) {
340  MACH3LOG_ERROR("Found {} parameters for event {}", TempSize, EventCounter);
341  MACH3LOG_ERROR("but was expecting {} since that's what I found for the previous event", numParams);
342  MACH3LOG_ERROR("Somehow this event has a different number of spline parameters... Please study further!");
343  throw MaCh3Exception(__FILE__ , __LINE__ );
344  }
345  }
346  numParams = short(MasterSpline[EventCounter].size());
347 
348  int nSplines_SingleEvent = 0;
349  int nPoints = 0;
350  // Loop over each pointer
351  for(unsigned int ParamNumber = 0; ParamNumber < MasterSpline[EventCounter].size(); ++ParamNumber) {
352  if (MasterSpline[EventCounter][ParamNumber]) {
353  if(SplineType[ParamNumber] == kTSpline3_red)
354  {
355  TResponseFunction_red* TespFunc = MasterSpline[EventCounter][ParamNumber];
356  TSpline3_red* CurrSpline = dynamic_cast<TSpline3_red*>(TespFunc);
357  if(CurrSpline){
358  nPoints = CurrSpline->GetNp();
359  }
360 
361  if (nPoints > MaxPoints) {
362  MaxPoints = static_cast<short int>(nPoints);
363  }
364  numKnots += nPoints;
365  nSplines_SingleEvent++;
366 
367  // Fill the SplineInfoArray entries with information on each splinified parameter
368  if (SplineInfoArray[ParamNumber].xPts.size() == 0)
369  {
370  // Fill the number of points
371  SplineInfoArray[ParamNumber].nPts = CurrSpline->GetNp();
372 
373  // Fill the x points
374  SplineInfoArray[ParamNumber].xPts.resize(SplineInfoArray[ParamNumber].nPts);
375  for (M3::int_t k = 0; k < SplineInfoArray[ParamNumber].nPts; ++k)
376  {
377  M3::float_t xtemp = M3::float_t(-999.99);
378  M3::float_t ytemp = M3::float_t(-999.99);
379  CurrSpline->GetKnot(k, xtemp, ytemp);
380  SplineInfoArray[ParamNumber].xPts[k] = xtemp;
381  }
382  }
383  NSplinesValid++;
384  }
385  else if (SplineType[ParamNumber] == kTF1_red)
386  {
387  TResponseFunction_red* TespFunc = MasterSpline[EventCounter][ParamNumber];
388  TF1_red* CurrSpline = dynamic_cast<TF1_red*>(TespFunc);
389  nPoints = CurrSpline->GetSize();
390  nTF1_coeff += nPoints;
391  nTF1Valid++;
392  }
393  } else {
394  // If NULL we don't have this spline for the event, so move to next spline
395  continue;
396  }
397  }
398  if (nSplines_SingleEvent > nMaxSplines_PerEvent) nMaxSplines_PerEvent = nSplines_SingleEvent;
399  }
400  nSplines = nMaxSplines_PerEvent;
401 
402  int Counter = 0;
403  //KS: Sanity check that everything was set correctly
404  for (M3::int_t i = 0; i < numParams; ++i)
405  {
406  // KS: We don't find segment for TF1, so ignore this
407  if (SplineType[i] == kTF1_red) continue;
408 
409  const M3::int_t nPoints = SplineInfoArray[i].nPts;
410  const std::vector<M3::float_t>& xArray = SplineInfoArray[i].xPts;
411  if (nPoints == -999 || xArray.size() == 0) {
412  Counter++;
413  if(Counter < 5) {
414  MACH3LOG_WARN("SplineInfoArray[{}] isn't set yet", i);
415  }
416  continue;
417  //throw MaCh3Exception(__FILE__ , __LINE__ );
418  }
419  }
420  MACH3LOG_WARN("In total SplineInfoArray for {} hasn't been initialised", Counter);
421 }
422 
423 // *****************************************
424 // Load SplineFile
426  : SplineBase() {
427 // *****************************************
428  Initialise();
429  MACH3LOG_INFO("-- GPUING WITH {X} and {Y,B,C,D} arrays and master spline containing TSpline3_red");
430  // Convert the TSpline3 pointers to the reduced form and call the reduced constructor
431  LoadSplineFile(FileName);
432 }
433 
434 // *****************************************
435 // Load SplineMonolith from ROOT file
436 void UnbinnedSplineHandler::LoadSplineFile(std::string FileName) {
437 // *****************************************
438  M3::AddPath(FileName);
439  auto SplineFile = std::make_unique<TFile>(FileName.c_str(), "OPEN");
440  TTree *Settings = SplineFile->Get<TTree>("Settings");
441  TTree *Monolith_TF1 = SplineFile->Get<TTree>("Monolith_TF1");
442  TTree *EventInfo = SplineFile->Get<TTree>("EventInfo");
443  TTree *SplineTree = SplineFile->Get<TTree>("SplineTree");
444 
445  unsigned int NEvents_temp;
446  short int nParams_temp;
447  int _max_knots_temp;
448  unsigned int nKnots_temp;
449  unsigned int NSplines_valid_temp;
450  unsigned int nTF1Valid_temp;
451  unsigned int nTF1coeff_temp;
452 
453  Settings->SetBranchAddress("NEvents", &NEvents_temp);
454  Settings->SetBranchAddress("nParams", &nParams_temp);
455  Settings->SetBranchAddress("_max_knots", &_max_knots_temp);
456  Settings->SetBranchAddress("nKnots", &nKnots_temp);
457  Settings->SetBranchAddress("NSplines_valid", &NSplines_valid_temp);
458  Settings->SetBranchAddress("NTF1_valid", &nTF1Valid_temp);
459  Settings->SetBranchAddress("nTF1coeff", &nTF1coeff_temp);
460 
461  Settings->GetEntry(0);
462 
463  NEvents = NEvents_temp;
464  nParams = nParams_temp;
465  _max_knots = static_cast<short int>(_max_knots_temp);
466  nKnots = nKnots_temp;
467  NSplines_valid = NSplines_valid_temp;
468  NTF1_valid = nTF1Valid_temp;
469  nTF1coeff = nTF1coeff_temp;
470 
471  cpu_nParamPerEvent.resize(2*NEvents);
474 
475  //KS: This is tricky as this variable use both by CPU and GPU, however if use CUDA we use cudaMallocHost
476  if (!useGPU) {
478  cpu_weights_spline_var = new float[NSplines_valid]();
479  cpu_weights_tf1_var = new float[NTF1_valid]();
480  }
481 
482  SplineTree->SetBranchAddress("SplineObject", &cpu_monolith);
483  SplineTree->GetEntry(0);
484 
485  float coeff_tf1 = 0.;
486  Monolith_TF1->SetBranchAddress("cpu_coeff_TF1_many", &coeff_tf1);
487  for(unsigned int i = 0; i < nTF1coeff; i++)
488  {
489  Monolith_TF1->GetEntry(i);
490  cpu_coeff_TF1_many[i] = coeff_tf1;
491  }
492 
493  unsigned int nParamPerEvent = 0;
494  unsigned int nParamPerEvent_tf1 = 0;
495 
496  EventInfo->SetBranchAddress("cpu_nParamPerEvent", &nParamPerEvent);
497  EventInfo->SetBranchAddress("cpu_nParamPerEvent_tf1", &nParamPerEvent_tf1);
498  for(unsigned int i = 0; i < 2*NEvents; i++)
499  {
500  EventInfo->GetEntry(i);
501  cpu_nParamPerEvent[i] = nParamPerEvent;
502  cpu_nParamPerEvent_tf1[i] = nParamPerEvent_tf1;
503  }
504 
505  LoadFastSplineInfoDir(SplineFile);
506 
507  SplineFile->Close();
508 
509  // Print some info; could probably make this to a separate function
511 
512  MoveToGPU();
513 
514  SetupSegments();
515 }
516 
517 // *****************************************
518 // Save SplineMonolith into ROOT file
519 void UnbinnedSplineHandler::PrepareSplineFile(std::string FileName) {
520 // *****************************************
521  M3::AddPath(FileName);
522 
523  auto SplineFile = std::make_unique<TFile>(FileName.c_str(), "recreate");
524  TTree *Settings = new TTree("Settings", "Settings");
525  TTree *Monolith_TF1 = new TTree("Monolith_TF1", "Monolith_TF1");
526  TTree *XKnots = new TTree("XKnots", "XKnots");
527  TTree *EventInfo = new TTree("EventInfo", "EventInfo");
528 
529  unsigned int NEvents_temp = NEvents;
530  short int nParams_temp = nParams;
531  int _max_knots_temp = _max_knots;
532  unsigned int nKnots_temp = nKnots;
533  unsigned int NSplines_valid_temp = NSplines_valid;
534  unsigned int nTF1Valid_temp = NTF1_valid;
535  unsigned int nTF1coeff_temp = nTF1coeff;
536 
537  Settings->Branch("NEvents", &NEvents_temp, "NEvents/i");
538  Settings->Branch("nParams", &nParams_temp, "nParams/S");
539  Settings->Branch("_max_knots", &_max_knots_temp, "_max_knots/I");
540  Settings->Branch("nKnots", &nKnots_temp, "nKnots/i");
541  Settings->Branch("NSplines_valid", &NSplines_valid_temp, "NSplines_valid/i");
542  Settings->Branch("NTF1_valid", &nTF1Valid_temp, "NTF1_valid/i");
543  Settings->Branch("nTF1coeff", &nTF1coeff_temp, "nTF1coeff/i");
544 
545  Settings->Fill();
546 
547  SplineFile->cd();
548  Settings->Write();
549 
550  TTree *SplineTree = new TTree("SplineTree", "SplineTree");
551  // Create a branch for the SplineMonoStruct object
552  SplineTree->Branch("SplineObject", &cpu_monolith);
553  SplineTree->Fill();
554  SplineTree->Write();
555  delete SplineTree;
556 
557  float coeff_tf1 = 0.;
558  Monolith_TF1->Branch("cpu_coeff_TF1_many", &coeff_tf1, "cpu_coeff_TF1_many/F");
559  for(unsigned int i = 0; i < nTF1coeff; i++)
560  {
561  coeff_tf1 = cpu_coeff_TF1_many[i];
562  Monolith_TF1->Fill();
563  }
564  SplineFile->cd();
565  Monolith_TF1->Write();
566 
567  unsigned int nParamPerEvent = 0;
568  unsigned int nParamPerEvent_tf1 = 0;
569 
570  EventInfo->Branch("cpu_nParamPerEvent", &nParamPerEvent, "cpu_nParamPerEvent/i");
571  EventInfo->Branch("cpu_nParamPerEvent_tf1", &nParamPerEvent_tf1, "cpu_nParamPerEvent_tf1/i");
572 
573  for(unsigned int i = 0; i < 2*NEvents; i++)
574  {
575  nParamPerEvent = cpu_nParamPerEvent[i];
576  nParamPerEvent_tf1 = cpu_nParamPerEvent_tf1[i];
577  EventInfo->Fill();
578  }
579  SplineFile->cd();
580  EventInfo->Write();
581 
582  PrepareFastSplineInfoDir(SplineFile);
583 
584  delete Settings;
585  delete Monolith_TF1;
586  delete XKnots;
587  delete EventInfo;
588  SplineFile->Close();
589 }
590 
591 // *****************************************
592 // Destructor
593 // Cleans up the allocated GPU memory
595 // *****************************************
596  #ifdef MaCh3_CUDA
597  if(useGPU) {
598  //KS: Since we declared them using CUDA alloc we have to free memory using also cuda functions
600  delete gpu_monolith;
601  } else
602  #endif
603  {
604  if(SplineSegments != nullptr) delete[] SplineSegments;
605  if(ParamValues != nullptr) delete[] ParamValues;
606  if(cpu_total_weights != nullptr) delete[] cpu_total_weights;
607  }
608 
609  if(cpu_weights_spline_var != nullptr) delete[] cpu_weights_spline_var;
610  if(cpu_weights_tf1_var != nullptr) delete[] cpu_weights_tf1_var;
611 
612  if(cpu_monolith != nullptr) delete cpu_monolith;
613 }
614 
615 // *****************************************
616 // Get the spline coefficients from the TSpline3 so that we can load ONLY these onto the GPU, not the whole TSpline3 object
617 // This loads up coefficients into two arrays: one x array and one yabcd array
618 // This should maximize our cache hits!
619 void UnbinnedSplineHandler::GetSplineCoeff_SepMany(TSpline3_red* &spl, int &nPoints, float *& xArray, float *& manyArray) const {
620 // *****************************************
621  // Initialise all arrays to 1.0
622  for (int i = 0; i < _max_knots; ++i) {
623  xArray[i] = 1.0;
624  for (int j = 0; j < _nCoeff_; j++) {
625  manyArray[i*_nCoeff_+j] = 1.0;
626  }
627  }
628  // Get number of points in spline
629  int Np = spl->GetNp();
630  // If spline is flat, set number of knots to 1.0,
631  // This is used later to expedite the calculations for flat splines
632  // tmpArray[0] is number of knots
633  nPoints = Np;
634  if (Np > _max_knots) {
635  MACH3LOG_ERROR("Error, number of points is greater than saved {}", _max_knots);
636  MACH3LOG_ERROR("This _WILL_ cause problems with GPU splines and _SHOULD_ be fixed!");
637  MACH3LOG_ERROR("nPoints = {}, _max_knots = {}", nPoints, _max_knots);
638  throw MaCh3Exception(__FILE__ , __LINE__ );
639  }
640 
641  // The coefficients we're writing to
642  M3::float_t x, y, b, c, d;
643  // TSpline3 can only take doubles, not floats
644  // But our GPU is slow with doubles, so need to cast to float
645  for(int i = 0; i < Np; i++) {
646  // Get the coefficients from the TSpline3 object
647  spl->GetCoeff(i, x, y, b, c, d);
648  // Write the arrays
649  xArray[i] = float(x);
650  manyArray[i*_nCoeff_] = float(y); // 4 because manyArray stores y,b,c,d
651  manyArray[i*_nCoeff_+1] = float(b);
652  manyArray[i*_nCoeff_+2] = float(c);
653  manyArray[i*_nCoeff_+3] = float(d);
654  if((xArray[i] == -999) || (manyArray[i*_nCoeff_] == -999) || (manyArray[i*_nCoeff_ +1] == -999) || (manyArray[i*_nCoeff_+2] == -999) || (manyArray[i*_nCoeff_+3] == -999)){
655  MACH3LOG_ERROR("*********** Bad params in {} ************", __func__);
656  MACH3LOG_ERROR("pre cast to float (x, y, b, c, d) = {:.2f}, {:.2f}, {:.2f}, {:.2f}, {:.2f}", x, y, b, c, d);
657  MACH3LOG_ERROR("pre cast to float (x, y, b, c, d) = {:.2f}, {:.2f}, {:.2f}, {:.2f}, {:.2f}", xArray[i], manyArray[i*_nCoeff_], manyArray[i*_nCoeff_+1], manyArray[i*_nCoeff_+2], manyArray[i*_nCoeff_+3]);
658  MACH3LOG_ERROR("This will cause problems when preparing for GPU");
659  MACH3LOG_ERROR("***************************************************************");
660  }
661  }
662 }
663 
664 
665 // *****************************************
666 // Tell the GPU to evaluate the weights
667 // Load up the two x,{y,b,c,d} arrays into memory and have GPU read them with more coalescence instead of one monolithic array
668 // This should be used when we're using separate x,y,a,b,c,d arrays
669 // Also pass the segments for the parameter along with their parameter values
670 // This avoids doing lots of binary searches on the GPU
672 // *****************************************
673  // There's a parameter mapping that goes from spline parameter to a global parameter index
674  // Find the spline segments
676  #ifdef MaCh3_CUDA
677  if (useGPU) { // GPU calculations
678  // The main call to the GPU
681  ParamValues,
683  } else
684  #endif
685  { // CPU-only calculations
686  //KS: Huge MP loop over all valid splines
688 
689  //KS: Huge MP loop over all events calculating total weight per event
691  }
692 }
693 
694 
695 //*********************************************************
697 //*********************************************************
698  #ifdef MULTITHREAD
699  //KS: Open parallel region
700  #pragma omp parallel
701  {
702  #endif
703  //KS: First we calculate
704  #ifdef MULTITHREAD
705  #pragma omp for simd nowait
706  #endif
707  for (unsigned int splineNum = 0; splineNum < NSplines_valid; ++splineNum)
708  {
709  //CW: Which Parameter we are accessing
710  const short int Param = cpu_monolith->paramNo_arr[splineNum];
711 
712  //CW: Avoids doing costly binary search on GPU
713  const short int segment = SplineSegments[Param];
714 
715  //KS: Segment for coeff_x is simply parameter*max knots + segment as each parameters has the same spacing
716  const short int segment_X = short(Param*_max_knots+segment);
717 
718  //KS: Find knot position in out monolithical structure
719  const unsigned int CurrentKnotPos = (cpu_monolith->nKnots_arr[splineNum] + segment) * _nCoeff_;
720 
721  // We've read the segment straight from CPU and is saved in segment_gpu
722  // polynomial parameters from the monolithic splineMonolith
723  const float fY = cpu_monolith->coeff_many[CurrentKnotPos];
724  const float fB = cpu_monolith->coeff_many[CurrentKnotPos + 1];
725  const float fC = cpu_monolith->coeff_many[CurrentKnotPos + 2];
726  const float fD = cpu_monolith->coeff_many[CurrentKnotPos + 3];
727  // The is the variation itself (needed to evaluate variation - stored spline point = dx)
728  const float dx = ParamValues[Param] - cpu_monolith->coeff_x[segment_X];
729 
730  //CW: Wooow, let's use some fancy intrinsic and pull down the processing time by <1% from normal multiplication! HURRAY
731  cpu_weights_spline_var[splineNum] = fmaf(dx, fmaf(dx, fmaf(dx, fD, fC), fB), fY);
732  // Or for the more "easy to read" version:
733  //cpu_weights_spline_var[splineNum] = (fY+dx*(fB+dx*(fC+dx*fD)));
734  }
735 
736  #ifdef MULTITHREAD
737  #pragma omp for simd
738  #endif
739  for (unsigned int tf1Num = 0; tf1Num < NTF1_valid; ++tf1Num)
740  {
741  // The is the variation itself (needed to evaluate variation - stored spline point = dx)
742  const float x = ParamValues[cpu_paramNo_TF1_arr[tf1Num]];
743 
744  // Read the coefficients
745  const unsigned int TF1_Index = tf1Num * _nTF1Coeff_;
746  const float a = cpu_coeff_TF1_many[TF1_Index];
747  const float b = cpu_coeff_TF1_many[TF1_Index + 1];
748 
749  cpu_weights_tf1_var[tf1Num] = fmaf(a, x, b);
750  // cpu_weights_tf1_var[tf1Num] = a*x + b;
751  //cpu_weights_tf1_var[splineNum] = 1 + a*x + b*x*x + c*x*x*x + d*x*x*x*x + e*x*x*x*x*x;
752  }
753  #ifdef MULTITHREAD
754  //KS: End parallel region
755  }
756  #endif
757 }
758 
759 //*********************************************************
760 //KS: Calc total event weight on CPU
762 //*********************************************************
763  #ifdef MULTITHREAD
764  #pragma omp parallel for
765  #endif
766  for (unsigned int EventNum = 0; EventNum < NEvents; ++EventNum)
767  {
768  float totalWeight = 1.0f; // Initialize total weight for each event
769 
770  const unsigned int Offset = 2 * EventNum;
771 
772  // Extract the parameters for the current event
773  const unsigned int startIndex = cpu_nParamPerEvent[Offset + 1];
774  const unsigned int numParams = cpu_nParamPerEvent[Offset];
775 
776  // Compute total weight for the current event
777  #ifdef MULTITHREAD
778  #pragma omp simd reduction(*:totalWeight)
779  #endif
780  for (unsigned int id = 0; id < numParams; ++id) {
781  totalWeight *= cpu_weights_spline_var[startIndex + id];
782  }
783  //Now TF1
784  // Extract the parameters for the current event
785  const unsigned int startIndex_tf1 = cpu_nParamPerEvent_tf1[Offset + 1];
786  const unsigned int numParams_tf1 = cpu_nParamPerEvent_tf1[Offset];
787 
788  // Compute total weight for the current event
789  #ifdef MULTITHREAD
790  #pragma omp simd reduction(*:totalWeight)
791  #endif
792  for (unsigned int id = 0; id < numParams_tf1; ++id) {
793  totalWeight *= cpu_weights_tf1_var[startIndex_tf1 + id];
794  }
795 
796  // Store the total weight for the current event
797  cpu_total_weights[EventNum] = static_cast<M3::float_t>(totalWeight);
798  }
799 }
800 
801 //*********************************************************
802 //KS: Print info about how much knots etc has been initialised
804 //*********************************************************
805  unsigned int event_size_max = _max_knots * nParams;
806 
807  MACH3LOG_INFO("--- INITIALISED Spline Monolith ---");
808  MACH3LOG_INFO("{} events with {} splines", NEvents, NSplines_valid);
809  MACH3LOG_INFO("On average {:.2f} splines per event ({}/{})", float(NSplines_valid)/float(NEvents), NSplines_valid, NEvents);
810  MACH3LOG_INFO("Size of x array = {:.4f} MB", double(sizeof(float)*event_size_max)/1.E6);
811  MACH3LOG_INFO("Size of coefficient (y,b,c,d) array = {:.2f} MB", double(sizeof(float)*nKnots*_nCoeff_)/1.E6);
812  MACH3LOG_INFO("Size of parameter # array = {:.2f} MB", double(sizeof(short int)*NSplines_valid)/1.E6);
813 
814  MACH3LOG_INFO("On average {:.2f} TF1 per event ({}/{})", float(NTF1_valid)/float(NEvents), NTF1_valid, NEvents);
815  MACH3LOG_INFO("Size of TF1 coefficient (a,b,c,d,e) array = {:.2f} MB", double(sizeof(float)*NTF1_valid*_nTF1Coeff_)/1.E6);
816 }
#define MACH3LOG_ERROR
Definition: MaCh3Logger.h:37
#define MACH3LOG_INFO
Definition: MaCh3Logger.h:35
#define MACH3LOG_WARN
Definition: MaCh3Logger.h:36
@ kTF1_red
Uses TF1_red for interpolation.
@ kTSpline3_red
Uses TSpline3_red for interpolation.
void CleanVector(T &)
Base case: do nothing for non-vector types.
constexpr int _nCoeff_
KS: We store coefficients {y,b,c,d} in one array one by one, this is only to define it once rather th...
Definition: SplineCommon.h:18
constexpr int _nTF1Coeff_
KS: For TF1 we store at most 5 coefficients, we could make it more flexible but for now define it her...
Definition: SplineCommon.h:20
Custom exception class used throughout MaCh3.
Base class for calculating weight from spline.
Definition: SplineBase.h:30
SplineMonolithGPU * gpu_monolith
KS: Store info about Spline monolith, this allow to obtain better step time. As all necessary informa...
Definition: SplineBase.h:120
void GetTF1Coeff(TF1_red *&spl, int &nPoints, float *&coeffs) const
CW: Gets the polynomial coefficients for TF1.
Definition: SplineBase.cpp:129
unsigned int NSplines_valid
Number of valid splines.
Definition: SplineBase.h:117
short int nParams
Number of parameters that have splines.
Definition: SplineBase.h:113
short int _max_knots
Max knots for production.
Definition: SplineBase.h:115
void FindSplineSegment()
CW:Code used in step by step reweighting, Find Spline Segment for each param.
Definition: SplineBase.cpp:58
short int * SplineSegments
Definition: SplineBase.h:109
std::vector< FastSplineInfo > SplineInfoArray
Definition: SplineBase.h:106
float * ParamValues
Store parameter values they are not in FastSplineInfo as in case of GPU we need to copy paste it to G...
Definition: SplineBase.h:111
bool useGPU
Whether to use GPU or not.
Definition: SplineBase.h:123
void LoadFastSplineInfoDir(std::unique_ptr< TFile > &SplineFile)
KS: Load preprocessed FastSplineInfo.
Definition: SplineBase.cpp:181
void PrepareFastSplineInfoDir(std::unique_ptr< TFile > &SplineFile) const
KS: Prepare Fast Spline Info within SplineFile.
Definition: SplineBase.cpp:153
void SetupSegments()
Since we find segment before actual reweight and sometimes we want to copy it to GPU we have differen...
Definition: SplineBase.cpp:208
Class responsible for calculating spline weight on GPU.
__host__ void InitGPU_SplineMonolith(unsigned int total_nknots, unsigned int n_splines, unsigned int n_tf1, int Eve_size)
Allocate memory on gpu for spline monolith.
__host__ void RunGPU_SplineMonolith_Unbinned(M3::float_t *cpu_total_weights, float *vals, short int *segment)
Run the GPU code for the separate many arrays. As in separate {x}, {y,b,c,d} arrays Pass the segment ...
__host__ void CleanupPinnedMemory(M3::float_t *cpu_total_weights, short int *segment, float *vals)
Clean up pinned variables at CPU.
__host__ void CopyToGPU_SplineMonolith_Unbinned(const SplineMonoStruct *cpu_spline_handler, const std::vector< float > &cpu_many_array_TF1, const std::vector< short int > &cpu_paramNo_arr_TF1, const int n_events, const std::vector< unsigned int > &cpu_nParamPerEvent, const std::vector< unsigned int > &cpu_nParamPerEvent_TF1, const int n_params, const unsigned int n_splines, const short int spline_size, const unsigned int total_nknots, const unsigned int n_tf1)
Copies data from CPU to GPU for the spline monolith.
__host__ void InitGPU_Unbinned_SplineMonolith(M3::float_t **cpu_total_weights, int n_events)
Allocate memory on gpu for spline monolith.
CW: A reduced TF1 class only. Only saves parameters for each TF1 and how many parameters each paramet...
int GetSize() const
Get the size.
KS: A reduced ResponseFunction Generic function used for evaluating weight.
CW: Reduced TSpline3 class.
void GetKnot(int i, M3::float_t &xtmp, M3::float_t &ytmp) const
void GetCoeff(int segment, M3::float_t &x, M3::float_t &y, M3::float_t &b, M3::float_t &c, M3::float_t &d) const
CW: Get the coefficient of a given segment.
M3::int_t GetNp() const override
CW: Get the number of points.
float * cpu_weights_tf1_var
CPU arrays to hold weight for each TF1.
float * cpu_weights_spline_var
CPU arrays to hold weight for each spline.
unsigned int nTF1coeff
Sum of all coefficients over all TF1.
unsigned int NTF1_valid
Number of valid TF1.
void ScanMasterSpline(std::vector< std::vector< TResponseFunction_red * > > &MasterSpline, unsigned int &nEvents, short int &MaxPoints, short int &numParams, int &nSplines, unsigned int &NSplinesValid, unsigned int &numKnots, unsigned int &nTF1Valid, unsigned int &nTF1_coeff, const std::vector< RespFuncType > &SplineType)
CW: Function to scan through the MasterSpline of TSpline3.
void PrepareSplineFile(std::string FileName) final
KS: Prepare spline file that can be used for fast loading.
std::vector< unsigned int > cpu_nParamPerEvent
KS: CPU map keeping track how many parameters applies to each event, we keep two numbers here {number...
void Evaluate() final
CW: This Eval should be used when using two separate x,{y,a,b,c,d} arrays to store the weights; proba...
std::vector< short int > cpu_paramNo_TF1_arr
CW: CPU array with the number of points per spline (not per spline point!)
void PrintInitialsiation() const
KS: Print info about how much knots etc has been initialised.
std::vector< unsigned int > cpu_nParamPerEvent_tf1
KS: CPU map keeping track how many parameters applies to each event, we keep two numbers here {number...
SplineMonoStruct * cpu_monolith
KS: Store info about Spline monolith, this allow to obtain better step time. As all necessary informa...
void MoveToGPU()
CW: The shared initialiser from constructors of TResponseFunction_red.
unsigned int nKnots
Sum of all knots over all splines.
void CalcSplineWeights() final
CPU based code which eval weight for each spline.
UnbinnedSplineHandler(std::vector< std::vector< TResponseFunction_red * > > &MasterSpline, const std::vector< RespFuncType > &SplineType, const bool SaveFlatTree=false, const std::string &_FastSplineName="SplineFile.root", const bool Use_GPU=true)
Constructor.
std::vector< short int > cpu_nPoints_arr
CPU arrays to hold number of points.
void PrepareForGPU(std::vector< std::vector< TResponseFunction_red * > > &MasterSpline, const std::vector< RespFuncType > &SplineType)
CW: Prepare the TSpline3_red objects for the GPU.
void Initialise()
KS: Set everything to null etc.
void LoadSplineFile(std::string FileName) final
KS: Load preprocessed spline file.
virtual ~UnbinnedSplineHandler()
Destructor for UnbinnedSplineHandler class.
std::vector< float > cpu_coeff_TF1_many
CPU arrays to hold TF1 coefficients.
void GetSplineCoeff_SepMany(TSpline3_red *&spl, int &nPoints, float *&xArray, float *&manyArray) const
CW: This loads up coefficients into two arrays: one x array and one yabcd array.
M3::float_t * cpu_total_weights
KS: This holds the total CPU weights that gets read in SampleHandler.
bool SaveSplineFile
Flag telling whether we are saving spline monolith into handy root file.
unsigned int NEvents
Number of events.
std::string FastSplineName
Name of Fast Spline to which will be saved.
void CalcTotalEventWeight()
Calc total event weight.
MaCh3 event-by-event cross-section spline code.
double float_t
Definition: Core.h:37
void AddPath(std::string &FilePath)
Prepends the MACH3 environment path to FilePath if it is not already present.
Definition: Monitor.cpp:382
int int_t
Definition: Core.h:38
Stores info about each MC event used during reweighting routine.
Definition: EventInfo.h:13
KS: Struct storing information for spline monolith.
Definition: SplineCommon.h:61
std::vector< unsigned int > nKnots_arr
KS: CPU Number of knots per spline.
Definition: SplineCommon.h:73
std::vector< float > coeff_x
KS: CPU arrays to hold X coefficient.
Definition: SplineCommon.h:67
std::vector< float > coeff_many
CPU arrays to hold other coefficients.
Definition: SplineCommon.h:70
std::vector< short int > paramNo_arr
CW: CPU array with the number of points per spline (not per spline point!)
Definition: SplineCommon.h:76