Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
MethodDL.cxx
Go to the documentation of this file.
1// @(#)root/tmva/tmva/cnn:$Id$Ndl
2// Authors: Vladimir Ilievski, Lorenzo Moneta, Saurav Shekhar, Ravi Kiran
3/**********************************************************************************
4 * Project: TMVA - a Root-integrated toolkit for multivariate data analysis *
5 * Package: TMVA *
6 * Class : MethodDL *
7 * *
8 * *
9 * Description: *
10 * Deep Neural Network Method *
11 * *
12 * Authors (alphabetical): *
13 * Vladimir Ilievski <ilievski.vladimir@live.com> - CERN, Switzerland *
14 * Saurav Shekhar <sauravshekhar01@gmail.com> - ETH Zurich, Switzerland *
15 * Ravi Kiran S <sravikiran0606@gmail.com> - CERN, Switzerland *
16 * *
17 * Copyright (c) 2005-2015: *
18 * CERN, Switzerland *
19 * U. of Victoria, Canada *
20 * MPI-K Heidelberg, Germany *
21 * U. of Bonn, Germany *
22 * *
23 * Redistribution and use in source and binary forms, with or without *
24 * modification, are permitted according to the terms listed in LICENSE *
25 * (see tmva/doc/LICENSE) *
26 **********************************************************************************/
27
28/*! \class TMVA::MethodDL
29\ingroup TMVA
30Deep neural network method, with dense, convolutional and recurrent layers.
31
32\deprecated MethodDL and the classes in the TMVA::DNN namespace will be removed in ROOT 6.46. Please train neural
33networks with a dedicated machine learning library instead, and use SOFIE for inference in C++.
34*/
35
36#include "TFormula.h"
37#include "TString.h"
38#include "TMath.h"
39#include "TObjString.h"
40
41#include "TMVA/Tools.h"
42#include "TMVA/Configurable.h"
43#include "TMVA/IMethod.h"
45#include "TMVA/MethodDL.h"
46#include "TMVA/Types.h"
48#include "TMVA/DNN/Functions.h"
50#include "TMVA/DNN/SGD.h"
51#include "TMVA/DNN/Adam.h"
52#include "TMVA/DNN/Adagrad.h"
53#include "TMVA/DNN/RMSProp.h"
54#include "TMVA/DNN/Adadelta.h"
55#include "TMVA/Timer.h"
56
57#ifdef R__HAS_TMVAGPU
59#ifdef R__HAS_CUDNN
61#endif
62#endif
63
64#include <chrono>
65
66// MethodDL is deprecated, but still has to be registered until its removal in ROOT 6.46
67#ifdef _MSC_VER
68#pragma warning(disable : 4996)
69#else
70#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
71#endif
72
74
75using namespace TMVA::DNN::CNN;
76using namespace TMVA::DNN;
77
83
84
85namespace TMVA {
86
87
88////////////////////////////////////////////////////////////////////////////////
89TString fetchValueTmp(const std::map<TString, TString> &keyValueMap, TString key)
90{
91 key.ToUpper();
92 std::map<TString, TString>::const_iterator it = keyValueMap.find(key);
93 if (it == keyValueMap.end()) {
94 return TString("");
95 }
96 return it->second;
97}
98
99////////////////////////////////////////////////////////////////////////////////
100template <typename T>
101T fetchValueTmp(const std::map<TString, TString> &keyValueMap, TString key, T defaultValue);
102
103////////////////////////////////////////////////////////////////////////////////
104template <>
105int fetchValueTmp(const std::map<TString, TString> &keyValueMap, TString key, int defaultValue)
106{
107 TString value(fetchValueTmp(keyValueMap, key));
108 if (value == "") {
109 return defaultValue;
110 }
111 return value.Atoi();
112}
113
114////////////////////////////////////////////////////////////////////////////////
115template <>
116double fetchValueTmp(const std::map<TString, TString> &keyValueMap, TString key, double defaultValue)
117{
118 TString value(fetchValueTmp(keyValueMap, key));
119 if (value == "") {
120 return defaultValue;
121 }
122 return value.Atof();
123}
124
125////////////////////////////////////////////////////////////////////////////////
126template <>
127TString fetchValueTmp(const std::map<TString, TString> &keyValueMap, TString key, TString defaultValue)
128{
129 TString value(fetchValueTmp(keyValueMap, key));
130 if (value == "") {
131 return defaultValue;
132 }
133 return value;
134}
135
136////////////////////////////////////////////////////////////////////////////////
137template <>
138bool fetchValueTmp(const std::map<TString, TString> &keyValueMap, TString key, bool defaultValue)
139{
140 TString value(fetchValueTmp(keyValueMap, key));
141 if (value == "") {
142 return defaultValue;
143 }
144
145 value.ToUpper();
146 if (value == "TRUE" || value == "T" || value == "1") {
147 return true;
148 }
149
150 return false;
151}
152
153////////////////////////////////////////////////////////////////////////////////
154template <>
155std::vector<double> fetchValueTmp(const std::map<TString, TString> &keyValueMap, TString key,
156 std::vector<double> defaultValue)
157{
158 TString parseString(fetchValueTmp(keyValueMap, key));
159 if (parseString == "") {
160 return defaultValue;
161 }
162
163 parseString.ToUpper();
164 std::vector<double> values;
165
166 const TString tokenDelim("+");
167 TObjArray *tokenStrings = parseString.Tokenize(tokenDelim);
168 TIter nextToken(tokenStrings);
169 TObjString *tokenString = (TObjString *)nextToken();
170 for (; tokenString != NULL; tokenString = (TObjString *)nextToken()) {
171 std::stringstream sstr;
172 double currentValue;
173 sstr << tokenString->GetString().Data();
174 sstr >> currentValue;
175 values.push_back(currentValue);
176 }
177 return values;
178}
179
180////////////////////////////////////////////////////////////////////////////////
181void MethodDL::DeclareOptions()
182{
183 // Set default values for all option strings
184
185 DeclareOptionRef(fInputLayoutString = "0|0|0", "InputLayout", "The Layout of the input");
186
187 DeclareOptionRef(fBatchLayoutString = "0|0|0", "BatchLayout", "The Layout of the batch");
188
189 DeclareOptionRef(fLayoutString = "DENSE|(N+100)*2|SOFTSIGN,DENSE|0|LINEAR", "Layout", "Layout of the network.");
190
191 DeclareOptionRef(fErrorStrategy = "CROSSENTROPY", "ErrorStrategy", "Loss function: Mean squared error (regression)"
192 " or cross entropy (binary classification).");
193 AddPreDefVal(TString("CROSSENTROPY"));
194 AddPreDefVal(TString("SUMOFSQUARES"));
195 AddPreDefVal(TString("MUTUALEXCLUSIVE"));
196
197 DeclareOptionRef(fWeightInitializationString = "XAVIER", "WeightInitialization", "Weight initialization strategy");
198 AddPreDefVal(TString("XAVIER"));
199 AddPreDefVal(TString("XAVIERUNIFORM"));
200 AddPreDefVal(TString("GAUSS"));
201 AddPreDefVal(TString("UNIFORM"));
202 AddPreDefVal(TString("IDENTITY"));
203 AddPreDefVal(TString("ZERO"));
204
205 DeclareOptionRef(fRandomSeed = 0, "RandomSeed", "Random seed used for weight initialization and batch shuffling");
206
207 DeclareOptionRef(fNumValidationString = "20%", "ValidationSize", "Part of the training data to use for validation. "
208 "Specify as 0.2 or 20% to use a fifth of the data set as validation set. "
209 "Specify as 100 to use exactly 100 events. (Default: 20%)");
210
211 DeclareOptionRef(fArchitectureString = "CPU", "Architecture", "Which architecture to perform the training on.");
212 AddPreDefVal(TString("STANDARD")); // deprecated and not supported anymore
213 AddPreDefVal(TString("CPU"));
214 AddPreDefVal(TString("GPU"));
215 AddPreDefVal(TString("OPENCL")); // not yet implemented
216 AddPreDefVal(TString("CUDNN")); // not needed (by default GPU is now CUDNN if available)
217
218 // define training strategy separated by a separator "|"
219 DeclareOptionRef(fTrainingStrategyString = "LearningRate=1e-3,"
220 "Momentum=0.0,"
221 "ConvergenceSteps=100,"
222 "MaxEpochs=2000,"
223 "Optimizer=ADAM,"
224 "BatchSize=30,"
225 "TestRepetitions=1,"
226 "WeightDecay=0.0,"
227 "Regularization=None,"
228 "DropConfig=0.0",
229 "TrainingStrategy", "Defines the training strategies.");
230}
231
232////////////////////////////////////////////////////////////////////////////////
233void MethodDL::ProcessOptions()
234{
235
236 if (IgnoreEventsWithNegWeightsInTraining()) {
237 Log() << kINFO << "Will ignore negative events in training!" << Endl;
238 }
239
240 if (fArchitectureString == "STANDARD") {
241 Log() << kWARNING << "The STANDARD architecture is not supported anymore. "
242 "Please use Architecture=CPU or Architecture=CPU."
243 "See the TMVA Users' Guide for instructions if you "
244 "encounter problems."
245 << Endl;
246 Log() << kINFO << "We will use instead the CPU architecture" << Endl;
247 fArchitectureString = "CPU";
248 }
249 if (fArchitectureString == "OPENCL") {
250 Log() << kERROR << "The OPENCL architecture has not been implemented yet. "
251 "Please use Architecture=CPU or Architecture=CPU for the "
252 "time being. See the TMVA Users' Guide for instructions "
253 "if you encounter problems."
254 << Endl;
255 // use instead GPU
256 Log() << kINFO << "We will try using the GPU-CUDA architecture if available" << Endl;
257 fArchitectureString = "GPU";
258 }
259
260 // the architecture can now be set at runtime as an option
261
262
263 if (fArchitectureString == "GPU" || fArchitectureString == "CUDNN") {
264#ifdef R__HAS_TMVAGPU
265 Log() << kINFO << "Will now use the GPU architecture !" << Endl;
266#else // case TMVA does not support GPU
267 Log() << kERROR << "CUDA backend not enabled. Please make sure "
268 "you have CUDA installed and it was successfully "
269 "detected by CMAKE by using -Dtmva-gpu=On "
270 << Endl;
271 fArchitectureString = "CPU";
272 Log() << kINFO << "Will now use instead the CPU architecture !" << Endl;
273#endif
274 }
275
276 if (fArchitectureString == "CPU") {
277#ifdef R__HAS_TMVACPU // TMVA has CPU BLAS and IMT support
278 Log() << kINFO << "Will now use the CPU architecture with BLAS and IMT support !" << Endl;
279#else // TMVA has no CPU BLAS or IMT support
280 Log() << kINFO << "Multi-core CPU backend not enabled. For better performance, build ROOT with the "
281 "tmva-cpu option, which requires a BLAS implementation and the imt option."
282 << Endl;
283 Log() << kINFO << "Will use anyway the CPU architecture but with slower performance" << Endl;
284#endif
285 }
286
287 // Input Layout
288 ParseInputLayout();
289 ParseBatchLayout();
290
291 // Loss function and output.
292 fOutputFunction = EOutputFunction::kSigmoid;
293 if (fAnalysisType == Types::kClassification) {
294 if (fErrorStrategy == "SUMOFSQUARES") {
295 fLossFunction = ELossFunction::kMeanSquaredError;
296 }
297 if (fErrorStrategy == "CROSSENTROPY") {
298 fLossFunction = ELossFunction::kCrossEntropy;
299 }
300 fOutputFunction = EOutputFunction::kSigmoid;
301 } else if (fAnalysisType == Types::kRegression) {
302 if (fErrorStrategy != "SUMOFSQUARES") {
303 Log() << kWARNING << "For regression only SUMOFSQUARES is a valid "
304 << " neural net error function. Setting error function to "
305 << " SUMOFSQUARES now." << Endl;
306 }
307
308 fLossFunction = ELossFunction::kMeanSquaredError;
309 fOutputFunction = EOutputFunction::kIdentity;
310 } else if (fAnalysisType == Types::kMulticlass) {
311 if (fErrorStrategy == "SUMOFSQUARES") {
312 fLossFunction = ELossFunction::kMeanSquaredError;
313 }
314 if (fErrorStrategy == "CROSSENTROPY") {
315 fLossFunction = ELossFunction::kCrossEntropy;
316 }
317 if (fErrorStrategy == "MUTUALEXCLUSIVE") {
318 fLossFunction = ELossFunction::kSoftmaxCrossEntropy;
319 }
320 fOutputFunction = EOutputFunction::kSoftmax;
321 }
322
323 // Initialization
324 // the biases will be always initialized to zero
325 if (fWeightInitializationString == "XAVIER") {
326 fWeightInitialization = DNN::EInitialization::kGlorotNormal;
327 } else if (fWeightInitializationString == "XAVIERUNIFORM") {
328 fWeightInitialization = DNN::EInitialization::kGlorotUniform;
329 } else if (fWeightInitializationString == "GAUSS") {
330 fWeightInitialization = DNN::EInitialization::kGauss;
331 } else if (fWeightInitializationString == "UNIFORM") {
332 fWeightInitialization = DNN::EInitialization::kUniform;
333 } else if (fWeightInitializationString == "ZERO") {
334 fWeightInitialization = DNN::EInitialization::kZero;
335 } else if (fWeightInitializationString == "IDENTITY") {
336 fWeightInitialization = DNN::EInitialization::kIdentity;
337 } else {
338 fWeightInitialization = DNN::EInitialization::kGlorotUniform;
339 }
340
341 // Training settings.
342
343 KeyValueVector_t strategyKeyValues = ParseKeyValueString(fTrainingStrategyString, TString("|"), TString(","));
344 for (auto &block : strategyKeyValues) {
345 TTrainingSettings settings;
346
347 settings.convergenceSteps = fetchValueTmp(block, "ConvergenceSteps", 100);
348 settings.batchSize = fetchValueTmp(block, "BatchSize", 30);
349 settings.maxEpochs = fetchValueTmp(block, "MaxEpochs", 2000);
350 settings.testInterval = fetchValueTmp(block, "TestRepetitions", 7);
351 settings.weightDecay = fetchValueTmp(block, "WeightDecay", 0.0);
352 settings.learningRate = fetchValueTmp(block, "LearningRate", 1e-5);
353 settings.momentum = fetchValueTmp(block, "Momentum", 0.3);
354 settings.dropoutProbabilities = fetchValueTmp(block, "DropConfig", std::vector<Double_t>());
355
356 TString regularization = fetchValueTmp(block, "Regularization", TString("NONE"));
357 if (regularization == "L1") {
358 settings.regularization = DNN::ERegularization::kL1;
359 } else if (regularization == "L2") {
360 settings.regularization = DNN::ERegularization::kL2;
361 } else {
362 settings.regularization = DNN::ERegularization::kNone;
363 }
364
365 TString optimizer = fetchValueTmp(block, "Optimizer", TString("ADAM"));
366 settings.optimizerName = optimizer;
367 if (optimizer == "SGD") {
368 settings.optimizer = DNN::EOptimizer::kSGD;
369 } else if (optimizer == "ADAM") {
370 settings.optimizer = DNN::EOptimizer::kAdam;
371 } else if (optimizer == "ADAGRAD") {
372 settings.optimizer = DNN::EOptimizer::kAdagrad;
373 } else if (optimizer == "RMSPROP") {
374 settings.optimizer = DNN::EOptimizer::kRMSProp;
375 } else if (optimizer == "ADADELTA") {
376 settings.optimizer = DNN::EOptimizer::kAdadelta;
377 } else {
378 // Make Adam as default choice if the input string is
379 // incorrect.
380 settings.optimizer = DNN::EOptimizer::kAdam;
381 settings.optimizerName = "ADAM";
382 }
383 // check for specific optimizer parameters
384 std::vector<TString> optimParamLabels = {"_beta1", "_beta2", "_eps", "_rho"};
385 //default values
386 std::map<TString, double> defaultValues = {
387 {"ADADELTA_eps", 1.E-8}, {"ADADELTA_rho", 0.95},
388 {"ADAGRAD_eps", 1.E-8},
389 {"ADAM_beta1", 0.9}, {"ADAM_beta2", 0.999}, {"ADAM_eps", 1.E-7},
390 {"RMSPROP_eps", 1.E-7}, {"RMSPROP_rho", 0.9},
391 };
392 for (auto &pN : optimParamLabels) {
393 TString optimParamName = settings.optimizerName + pN;
394 // check if optimizer has default values for this specific parameters
395 if (defaultValues.count(optimParamName) > 0) {
396 double defValue = defaultValues[optimParamName];
397 double val = fetchValueTmp(block, optimParamName, defValue);
398 // create entry in settings for this optimizer parameter
399 settings.optimizerParams[optimParamName] = val;
400 }
401 }
402
403 fTrainingSettings.push_back(settings);
404 }
405
406 // this set fInputShape[0] = batchSize
407 this->SetBatchSize(fTrainingSettings.front().batchSize);
408
409 // case inputlayout and batch layout was not given. Use default then
410 // (1, batchsize, nvariables)
411 // fInputShape[0] -> BatchSize
412 // fInputShape[1] -> InputDepth
413 // fInputShape[2] -> InputHeight
414 // fInputShape[3] -> InputWidth
415 if (fInputShape[3] == 0 && fInputShape[2] == 0 && fInputShape[1] == 0) {
416 fInputShape[1] = 1;
417 fInputShape[2] = 1;
418 fInputShape[3] = GetNVariables();
419 }
420 // case when batch layout is not provided (all zero)
421 // batch layout can be determined by the input layout + batch size
422 // case DNN : { 1, B, W }
423 // case CNN : { B, C, H*W}
424 // case RNN : { B, T, H*W }
425
426 if (fBatchWidth == 0 && fBatchHeight == 0 && fBatchDepth == 0) {
427 // case first layer is DENSE
428 if (fInputShape[2] == 1 && fInputShape[1] == 1) {
429 // case of (1, batchsize, input features)
430 fBatchDepth = 1;
431 fBatchHeight = fTrainingSettings.front().batchSize;
432 fBatchWidth = fInputShape[3];
433 }
434 else { // more general cases (e.g. for CNN)
435 // case CONV or RNN
436 fBatchDepth = fTrainingSettings.front().batchSize;
437 fBatchHeight = fInputShape[1];
438 fBatchWidth = fInputShape[3]*fInputShape[2];
439 }
440 }
441}
442
443////////////////////////////////////////////////////////////////////////////////
444/// default initializations
445void MethodDL::Init()
446{
447 Log() << kWARNING
448 << "MethodDL is deprecated and will be removed in ROOT 6.46. Please train neural networks with a "
449 "dedicated machine learning library instead, and use SOFIE for inference in C++."
450 << Endl;
451}
452
453////////////////////////////////////////////////////////////////////////////////
454/// Parse the input layout
455void MethodDL::ParseInputLayout()
456{
457 // Define the delimiter
458 const TString delim("|");
459
460 // Get the input layout string
461 TString inputLayoutString = this->GetInputLayoutString();
462
463 // Split the input layout string
464 TObjArray *inputDimStrings = inputLayoutString.Tokenize(delim);
465 TIter nextInputDim(inputDimStrings);
466 TObjString *inputDimString = (TObjString *)nextInputDim();
467
468 // Go through every token and save its absolute value in the shape array
469 // The first token is the batch size for easy compatibility with cudnn
470 int subDim = 1;
471 std::vector<size_t> inputShape;
472 inputShape.reserve(inputLayoutString.Length()/2 + 2);
473 inputShape.push_back(0); // Will be set later by Trainingsettings, use 0 value now
474 for (; inputDimString != nullptr; inputDimString = (TObjString *)nextInputDim()) {
475 // size_t is unsigned
476 subDim = (size_t) abs(inputDimString->GetString().Atoi());
477 // Size among unused dimensions should be set to 1 for cudnn
478 //if (subDim == 0) subDim = 1;
479 inputShape.push_back(subDim);
480 }
481 // it is expected that empty Shape has at least 4 dimensions. We pad the missing one's with 1
482 // for example in case of dense layer input layouts
483 // when we will support 3D convolutions we would need to add extra 1's
484 if (inputShape.size() == 2) {
485 // case of dense layer where only width is specified
486 inputShape = {inputShape[0], 1, 1, inputShape[1]};
487 }
488 else if (inputShape.size() == 3) {
489 //e.g. case of RNN T,W -> T,1,W
490 inputShape = {inputShape[0], inputShape[1], 1, inputShape[2]};
491 }
492
493 this->SetInputShape(inputShape);
494}
495
496////////////////////////////////////////////////////////////////////////////////
497/// Parse the input layout
498void MethodDL::ParseBatchLayout()
499{
500 // Define the delimiter
501 const TString delim("|");
502
503 // Get the input layout string
504 TString batchLayoutString = this->GetBatchLayoutString();
505
506 size_t batchDepth = 0;
507 size_t batchHeight = 0;
508 size_t batchWidth = 0;
509
510 // Split the input layout string
511 TObjArray *batchDimStrings = batchLayoutString.Tokenize(delim);
512 TIter nextBatchDim(batchDimStrings);
513 TObjString *batchDimString = (TObjString *)nextBatchDim();
514 int idxToken = 0;
515
516 for (; batchDimString != nullptr; batchDimString = (TObjString *)nextBatchDim()) {
517 switch (idxToken) {
518 case 0: // input depth
519 {
520 TString strDepth(batchDimString->GetString());
521 batchDepth = (size_t)strDepth.Atoi();
522 } break;
523 case 1: // input height
524 {
525 TString strHeight(batchDimString->GetString());
526 batchHeight = (size_t)strHeight.Atoi();
527 } break;
528 case 2: // input width
529 {
530 TString strWidth(batchDimString->GetString());
531 batchWidth = (size_t)strWidth.Atoi();
532 } break;
533 }
534 ++idxToken;
535 }
536
537 this->SetBatchDepth(batchDepth);
538 this->SetBatchHeight(batchHeight);
539 this->SetBatchWidth(batchWidth);
540}
541
542////////////////////////////////////////////////////////////////////////////////
543/// Create a deep net based on the layout string
544template <typename Architecture_t, typename Layer_t>
545void MethodDL::CreateDeepNet(DNN::TDeepNet<Architecture_t, Layer_t> &deepNet,
547{
548 // Layer specification, layer details
549 const TString layerDelimiter(",");
550 const TString subDelimiter("|");
551
552 TString layoutString = this->GetLayoutString();
553
554 //std::cout << "Create Deepnet - layout string " << layoutString << "\t layers : " << deepNet.GetLayers().size() << std::endl;
555
556 // Split layers
557 TObjArray *layerStrings = layoutString.Tokenize(layerDelimiter);
558 TIter nextLayer(layerStrings);
559 TObjString *layerString = (TObjString *)nextLayer();
560
561
562 for (; layerString != nullptr; layerString = (TObjString *)nextLayer()) {
563
564 // Split layer details
565 TObjArray *subStrings = layerString->GetString().Tokenize(subDelimiter);
566 TIter nextToken(subStrings);
567 TObjString *token = (TObjString *)nextToken();
568
569 // Determine the type of the layer
570 TString strLayerType = token->GetString();
571
572
573 if (strLayerType == "DENSE") {
574 ParseDenseLayer(deepNet, nets, layerString->GetString(), subDelimiter);
575 } else if (strLayerType == "CONV") {
576 ParseConvLayer(deepNet, nets, layerString->GetString(), subDelimiter);
577 } else if (strLayerType == "MAXPOOL") {
578 ParseMaxPoolLayer(deepNet, nets, layerString->GetString(), subDelimiter);
579 } else if (strLayerType == "RESHAPE") {
580 ParseReshapeLayer(deepNet, nets, layerString->GetString(), subDelimiter);
581 } else if (strLayerType == "BNORM") {
582 ParseBatchNormLayer(deepNet, nets, layerString->GetString(), subDelimiter);
583 } else if (strLayerType == "RNN") {
584 ParseRecurrentLayer(kLayerRNN, deepNet, nets, layerString->GetString(), subDelimiter);
585 } else if (strLayerType == "LSTM") {
586 ParseRecurrentLayer(kLayerLSTM, deepNet, nets, layerString->GetString(), subDelimiter);
587 } else if (strLayerType == "GRU") {
588 ParseRecurrentLayer(kLayerGRU, deepNet, nets, layerString->GetString(), subDelimiter);
589 } else {
590 // no type of layer specified - assume is dense layer as in old DNN interface
591 ParseDenseLayer(deepNet, nets, layerString->GetString(), subDelimiter);
592 }
593 }
594}
595
596////////////////////////////////////////////////////////////////////////////////
597/// Pases the layer string and creates the appropriate dense layer
598template <typename Architecture_t, typename Layer_t>
599void MethodDL::ParseDenseLayer(DNN::TDeepNet<Architecture_t, Layer_t> &deepNet,
600 std::vector<DNN::TDeepNet<Architecture_t, Layer_t>> & /*nets*/, TString layerString,
601 TString delim)
602{
603 int width = 0;
604 EActivationFunction activationFunction = EActivationFunction::kTanh;
605
606 // this return number of input variables for the method
607 // it can be used to deduce width of dense layer if specified as N+10
608 // where N is the number of input variables
609 const size_t inputSize = GetNvar();
610
611 // Split layer details
612 TObjArray *subStrings = layerString.Tokenize(delim);
613 TIter nextToken(subStrings);
614 TObjString *token = (TObjString *)nextToken();
615
616 // loop on the tokens
617 // order of sepcifying width and activation function is not relevant
618 // both 100|TANH and TANH|100 are valid cases
619 for (; token != nullptr; token = (TObjString *)nextToken()) {
620 // try a match with the activation function
621 TString strActFnc(token->GetString());
622 // if first token defines the layer type- skip it
623 if (strActFnc =="DENSE") continue;
624
625 if (strActFnc == "RELU") {
626 activationFunction = DNN::EActivationFunction::kRelu;
627 } else if (strActFnc == "TANH") {
628 activationFunction = DNN::EActivationFunction::kTanh;
629 } else if (strActFnc == "FTANH") {
630 activationFunction = DNN::EActivationFunction::kFastTanh;
631 } else if (strActFnc == "SYMMRELU") {
632 activationFunction = DNN::EActivationFunction::kSymmRelu;
633 } else if (strActFnc == "SOFTSIGN") {
634 activationFunction = DNN::EActivationFunction::kSoftSign;
635 } else if (strActFnc == "SIGMOID") {
636 activationFunction = DNN::EActivationFunction::kSigmoid;
637 } else if (strActFnc == "LINEAR") {
638 activationFunction = DNN::EActivationFunction::kIdentity;
639 } else if (strActFnc == "GAUSS") {
640 activationFunction = DNN::EActivationFunction::kGauss;
641 } else if (width == 0) {
642 // no match found try to parse as text showing the width
643 // support for input a formula where the variable 'x' is 'N' in the string
644 // use TFormula for the evaluation
645 TString strNumNodes = strActFnc;
646 // number of nodes
647 TString strN("x");
648 strNumNodes.ReplaceAll("N", strN);
649 strNumNodes.ReplaceAll("n", strN);
650 TFormula fml("tmp", strNumNodes);
651 width = fml.Eval(inputSize);
652 }
653 }
654 // avoid zero width. assume is last layer and give width = output width
655 // Determine the number of outputs
656 size_t outputSize = 1;
657 if (fAnalysisType == Types::kRegression && GetNTargets() != 0) {
658 outputSize = GetNTargets();
659 } else if (fAnalysisType == Types::kMulticlass && DataInfo().GetNClasses() >= 2) {
660 outputSize = DataInfo().GetNClasses();
661 }
662 if (width == 0) width = outputSize;
663
664 // Add the dense layer, initialize the weights and biases and copy
665 TDenseLayer<Architecture_t> *denseLayer = deepNet.AddDenseLayer(width, activationFunction);
666 denseLayer->Initialize();
667
668 // add same layer to fNet
669 if (fBuildNet) fNet->AddDenseLayer(width, activationFunction);
670
671 //TDenseLayer<Architecture_t> *copyDenseLayer = new TDenseLayer<Architecture_t>(*denseLayer);
672
673 // add the copy to all slave nets
674 //for (size_t i = 0; i < nets.size(); i++) {
675 // nets[i].AddDenseLayer(copyDenseLayer);
676 //}
677
678 // check compatibility of added layer
679 // for a dense layer input should be 1 x 1 x DxHxW
680}
681
682////////////////////////////////////////////////////////////////////////////////
683/// Pases the layer string and creates the appropriate convolutional layer
684template <typename Architecture_t, typename Layer_t>
685void MethodDL::ParseConvLayer(DNN::TDeepNet<Architecture_t, Layer_t> &deepNet,
686 std::vector<DNN::TDeepNet<Architecture_t, Layer_t>> & /*nets*/, TString layerString,
687 TString delim)
688{
689 int depth = 0;
690 int fltHeight = 0;
691 int fltWidth = 0;
692 int strideRows = 0;
693 int strideCols = 0;
694 int zeroPadHeight = 0;
695 int zeroPadWidth = 0;
696 EActivationFunction activationFunction = EActivationFunction::kTanh;
697
698 // Split layer details
699 TObjArray *subStrings = layerString.Tokenize(delim);
700 TIter nextToken(subStrings);
701 TObjString *token = (TObjString *)nextToken();
702 int idxToken = 0;
703
704 for (; token != nullptr; token = (TObjString *)nextToken()) {
705 switch (idxToken) {
706 case 1: // depth
707 {
708 TString strDepth(token->GetString());
709 depth = strDepth.Atoi();
710 } break;
711 case 2: // filter height
712 {
713 TString strFltHeight(token->GetString());
714 fltHeight = strFltHeight.Atoi();
715 } break;
716 case 3: // filter width
717 {
718 TString strFltWidth(token->GetString());
719 fltWidth = strFltWidth.Atoi();
720 } break;
721 case 4: // stride in rows
722 {
723 TString strStrideRows(token->GetString());
724 strideRows = strStrideRows.Atoi();
725 } break;
726 case 5: // stride in cols
727 {
728 TString strStrideCols(token->GetString());
729 strideCols = strStrideCols.Atoi();
730 } break;
731 case 6: // zero padding height
732 {
733 TString strZeroPadHeight(token->GetString());
734 zeroPadHeight = strZeroPadHeight.Atoi();
735 } break;
736 case 7: // zero padding width
737 {
738 TString strZeroPadWidth(token->GetString());
739 zeroPadWidth = strZeroPadWidth.Atoi();
740 } break;
741 case 8: // activation function
742 {
743 TString strActFnc(token->GetString());
744 if (strActFnc == "RELU") {
745 activationFunction = DNN::EActivationFunction::kRelu;
746 } else if (strActFnc == "TANH") {
747 activationFunction = DNN::EActivationFunction::kTanh;
748 } else if (strActFnc == "SYMMRELU") {
749 activationFunction = DNN::EActivationFunction::kSymmRelu;
750 } else if (strActFnc == "SOFTSIGN") {
751 activationFunction = DNN::EActivationFunction::kSoftSign;
752 } else if (strActFnc == "SIGMOID") {
753 activationFunction = DNN::EActivationFunction::kSigmoid;
754 } else if (strActFnc == "LINEAR") {
755 activationFunction = DNN::EActivationFunction::kIdentity;
756 } else if (strActFnc == "GAUSS") {
757 activationFunction = DNN::EActivationFunction::kGauss;
758 }
759 } break;
760 }
761 ++idxToken;
762 }
763
764 // Add the convolutional layer, initialize the weights and biases and copy
765 TConvLayer<Architecture_t> *convLayer = deepNet.AddConvLayer(depth, fltHeight, fltWidth, strideRows, strideCols,
766 zeroPadHeight, zeroPadWidth, activationFunction);
767 convLayer->Initialize();
768
769 // Add same layer to fNet
770 if (fBuildNet) fNet->AddConvLayer(depth, fltHeight, fltWidth, strideRows, strideCols,
771 zeroPadHeight, zeroPadWidth, activationFunction);
772
773 //TConvLayer<Architecture_t> *copyConvLayer = new TConvLayer<Architecture_t>(*convLayer);
774
775 //// add the copy to all slave nets
776 //for (size_t i = 0; i < nets.size(); i++) {
777 // nets[i].AddConvLayer(copyConvLayer);
778 //}
779}
780
781////////////////////////////////////////////////////////////////////////////////
782/// Pases the layer string and creates the appropriate max pool layer
783template <typename Architecture_t, typename Layer_t>
784void MethodDL::ParseMaxPoolLayer(DNN::TDeepNet<Architecture_t, Layer_t> &deepNet,
785 std::vector<DNN::TDeepNet<Architecture_t, Layer_t>> & /*nets*/, TString layerString,
786 TString delim)
787{
788
789 int filterHeight = 0;
790 int filterWidth = 0;
791 int strideRows = 0;
792 int strideCols = 0;
793
794 // Split layer details
795 TObjArray *subStrings = layerString.Tokenize(delim);
796 TIter nextToken(subStrings);
797 TObjString *token = (TObjString *)nextToken();
798 int idxToken = 0;
799
800 for (; token != nullptr; token = (TObjString *)nextToken()) {
801 switch (idxToken) {
802 case 1: // filter height
803 {
804 TString strFrmHeight(token->GetString());
805 filterHeight = strFrmHeight.Atoi();
806 } break;
807 case 2: // filter width
808 {
809 TString strFrmWidth(token->GetString());
810 filterWidth = strFrmWidth.Atoi();
811 } break;
812 case 3: // stride in rows
813 {
814 TString strStrideRows(token->GetString());
815 strideRows = strStrideRows.Atoi();
816 } break;
817 case 4: // stride in cols
818 {
819 TString strStrideCols(token->GetString());
820 strideCols = strStrideCols.Atoi();
821 } break;
822 }
823 ++idxToken;
824 }
825
826 // Add the Max pooling layer
827 // TMaxPoolLayer<Architecture_t> *maxPoolLayer =
828 deepNet.AddMaxPoolLayer(filterHeight, filterWidth, strideRows, strideCols);
829
830 // Add the same layer to fNet
831 if (fBuildNet) fNet->AddMaxPoolLayer(filterHeight, filterWidth, strideRows, strideCols);
832
833
834 //TMaxPoolLayer<Architecture_t> *copyMaxPoolLayer = new TMaxPoolLayer<Architecture_t>(*maxPoolLayer);
835
836 //// add the copy to all slave nets
837 //for (size_t i = 0; i < nets.size(); i++) {
838 // nets[i].AddMaxPoolLayer(copyMaxPoolLayer);
839 //}
840}
841
842////////////////////////////////////////////////////////////////////////////////
843/// Pases the layer string and creates the appropriate reshape layer
844template <typename Architecture_t, typename Layer_t>
845void MethodDL::ParseReshapeLayer(DNN::TDeepNet<Architecture_t, Layer_t> &deepNet,
846 std::vector<DNN::TDeepNet<Architecture_t, Layer_t>> & /*nets*/, TString layerString,
847 TString delim)
848{
849 int depth = 0;
850 int height = 0;
851 int width = 0;
852 bool flattening = false;
853
854 // Split layer details
855 TObjArray *subStrings = layerString.Tokenize(delim);
856 TIter nextToken(subStrings);
857 TObjString *token = (TObjString *)nextToken();
858 int idxToken = 0;
859
860 for (; token != nullptr; token = (TObjString *)nextToken()) {
861 if (token->GetString() == "FLAT") idxToken=4;
862 switch (idxToken) {
863 case 1: {
864 TString strDepth(token->GetString());
865 depth = strDepth.Atoi();
866 } break;
867 case 2: // height
868 {
869 TString strHeight(token->GetString());
870 height = strHeight.Atoi();
871 } break;
872 case 3: // width
873 {
874 TString strWidth(token->GetString());
875 width = strWidth.Atoi();
876 } break;
877 case 4: // flattening
878 {
879 TString flat(token->GetString());
880 if (flat == "FLAT") {
881 flattening = true;
882 }
883 } break;
884 }
885 ++idxToken;
886 }
887
888 // Add the reshape layer
889 // TReshapeLayer<Architecture_t> *reshapeLayer =
890 deepNet.AddReshapeLayer(depth, height, width, flattening);
891
892 // Add the same layer to fNet
893 if (fBuildNet) fNet->AddReshapeLayer(depth, height, width, flattening);
894
895 //TReshapeLayer<Architecture_t> *copyReshapeLayer = new TReshapeLayer<Architecture_t>(*reshapeLayer);
896
897 //// add the copy to all slave nets
898 //for (size_t i = 0; i < nets.size(); i++) {
899 // nets[i].AddReshapeLayer(copyReshapeLayer);
900 //}
901}
902
903////////////////////////////////////////////////////////////////////////////////
904/// Pases the layer string and creates the appropriate reshape layer
905template <typename Architecture_t, typename Layer_t>
906void MethodDL::ParseBatchNormLayer(DNN::TDeepNet<Architecture_t, Layer_t> &deepNet,
907 std::vector<DNN::TDeepNet<Architecture_t, Layer_t>> & /*nets*/, TString layerString,
908 TString delim)
909{
910
911 // default values
912 double momentum = -1; //0.99;
913 double epsilon = 0.0001;
914
915 // Split layer details
916 TObjArray *subStrings = layerString.Tokenize(delim);
917 TIter nextToken(subStrings);
918 TObjString *token = (TObjString *)nextToken();
919 int idxToken = 0;
920
921 for (; token != nullptr; token = (TObjString *)nextToken()) {
922 switch (idxToken) {
923 case 1: {
924 momentum = std::atof(token->GetString().Data());
925 } break;
926 case 2: // height
927 {
928 epsilon = std::atof(token->GetString().Data());
929 } break;
930 }
931 ++idxToken;
932 }
933
934 // Add the batch norm layer
935 //
936 auto layer = deepNet.AddBatchNormLayer(momentum, epsilon);
937 layer->Initialize();
938
939 // Add the same layer to fNet
940 if (fBuildNet) fNet->AddBatchNormLayer(momentum, epsilon);
941
942}
943
944////////////////////////////////////////////////////////////////////////////////
945/// Pases the layer string and creates the appropriate rnn layer
946template <typename Architecture_t, typename Layer_t>
947void MethodDL::ParseRecurrentLayer(ERecurrentLayerType rnnType, DNN::TDeepNet<Architecture_t, Layer_t> & deepNet,
948 std::vector<DNN::TDeepNet<Architecture_t, Layer_t>> & /*nets */, TString layerString,
949 TString delim)
950{
951 // int depth = 0;
952 int stateSize = 0;
953 int inputSize = 0;
954 int timeSteps = 0;
955 bool rememberState = false;
956 bool returnSequence = false;
957 bool resetGateAfter = false;
958
959 // Split layer details
960 TObjArray *subStrings = layerString.Tokenize(delim);
961 TIter nextToken(subStrings);
962 TObjString *token = (TObjString *)nextToken();
963 int idxToken = 0;
964
965 for (; token != nullptr; token = (TObjString *)nextToken()) {
966 switch (idxToken) {
967 case 1: // state size
968 {
969 TString strstateSize(token->GetString());
970 stateSize = strstateSize.Atoi();
971 break;
972 }
973 case 2: // input size
974 {
975 TString strinputSize(token->GetString());
976 inputSize = strinputSize.Atoi();
977 break;
978 }
979 case 3: // time steps
980 {
981 TString strtimeSteps(token->GetString());
982 timeSteps = strtimeSteps.Atoi();
983 break;
984 }
985 case 4: // returnSequence (option stateful in Keras)
986 {
987 TString strrememberState(token->GetString());
988 rememberState = (bool) strrememberState.Atoi();
989 break;
990 }
991 case 5: // return full output sequence (1 or 0)
992 {
993 TString str(token->GetString());
994 returnSequence = (bool)str.Atoi();
995 break;
996 }
997 case 6: // resetGate after option (only for GRU)
998 {
999 TString str(token->GetString());
1000 resetGateAfter = (bool)str.Atoi();
1001 }
1002 }
1003 ++idxToken;
1004 }
1005
1006 // Add the recurrent layer, initialize the weights and biases and copy
1007 if (rnnType == kLayerRNN) {
1008 auto * recurrentLayer = deepNet.AddBasicRNNLayer(stateSize, inputSize, timeSteps, rememberState, returnSequence);
1009 recurrentLayer->Initialize();
1010 // Add same layer to fNet
1011 if (fBuildNet) fNet->AddBasicRNNLayer(stateSize, inputSize, timeSteps, rememberState, returnSequence);
1012 }
1013 else if (rnnType == kLayerLSTM ) {
1014 auto *recurrentLayer = deepNet.AddBasicLSTMLayer(stateSize, inputSize, timeSteps, rememberState, returnSequence);
1015 recurrentLayer->Initialize();
1016 // Add same layer to fNet
1017 if (fBuildNet)
1018 fNet->AddBasicLSTMLayer(stateSize, inputSize, timeSteps, rememberState, returnSequence);
1019 }
1020 else if (rnnType == kLayerGRU) {
1021 if (Architecture_t::IsCudnn()) resetGateAfter = true; // needed for Cudnn
1022 auto *recurrentLayer = deepNet.AddBasicGRULayer(stateSize, inputSize, timeSteps, rememberState, returnSequence, resetGateAfter);
1023 recurrentLayer->Initialize();
1024 // Add same layer to fNet
1025 if (fBuildNet)
1026 fNet->AddBasicGRULayer(stateSize, inputSize, timeSteps, rememberState, returnSequence, resetGateAfter);
1027 }
1028 else {
1029 Log() << kFATAL << "Invalid Recurrent layer type " << Endl;
1030 }
1031}
1032
1033////////////////////////////////////////////////////////////////////////////////
1034/// Standard constructor.
1035MethodDL::MethodDL(const TString &jobName, const TString &methodTitle, DataSetInfo &theData, const TString &theOption)
1036 : MethodBase(jobName, Types::kDL, methodTitle, theData, theOption), fInputShape(4,0),
1037 fBatchHeight(), fBatchWidth(), fRandomSeed(0), fWeightInitialization(),
1038 fOutputFunction(), fLossFunction(), fInputLayoutString(), fBatchLayoutString(),
1039 fLayoutString(), fErrorStrategy(), fTrainingStrategyString(), fWeightInitializationString(),
1040 fArchitectureString(), fResume(false), fBuildNet(true), fTrainingSettings(),
1041 fXInput()
1042{
1043 // Nothing to do here
1044}
1045
1046////////////////////////////////////////////////////////////////////////////////
1047/// Constructor from a weight file.
1048MethodDL::MethodDL(DataSetInfo &theData, const TString &theWeightFile)
1049 : MethodBase(Types::kDL, theData, theWeightFile), fInputShape(4,0), fBatchHeight(),
1050 fBatchWidth(), fRandomSeed(0), fWeightInitialization(), fOutputFunction(),
1051 fLossFunction(), fInputLayoutString(), fBatchLayoutString(), fLayoutString(),
1052 fErrorStrategy(), fTrainingStrategyString(), fWeightInitializationString(),
1053 fArchitectureString(), fResume(false), fBuildNet(true), fTrainingSettings(),
1054 fXInput()
1055{
1056 // Nothing to do here
1057}
1058
1059////////////////////////////////////////////////////////////////////////////////
1060/// Destructor.
1061MethodDL::~MethodDL()
1062{
1063 // Nothing to do here
1064}
1065
1066////////////////////////////////////////////////////////////////////////////////
1067/// Parse key value pairs in blocks -> return vector of blocks with map of key value pairs.
1068auto MethodDL::ParseKeyValueString(TString parseString, TString blockDelim, TString tokenDelim) -> KeyValueVector_t
1069{
1070 // remove empty spaces
1071 parseString.ReplaceAll(" ","");
1072 KeyValueVector_t blockKeyValues;
1073 const TString keyValueDelim("=");
1074
1075 TObjArray *blockStrings = parseString.Tokenize(blockDelim);
1076 TIter nextBlock(blockStrings);
1077 TObjString *blockString = (TObjString *)nextBlock();
1078
1079 for (; blockString != nullptr; blockString = (TObjString *)nextBlock()) {
1080 blockKeyValues.push_back(std::map<TString, TString>());
1081 std::map<TString, TString> &currentBlock = blockKeyValues.back();
1082
1083 TObjArray *subStrings = blockString->GetString().Tokenize(tokenDelim);
1084 TIter nextToken(subStrings);
1085 TObjString *token = (TObjString *)nextToken();
1086
1087 for (; token != nullptr; token = (TObjString *)nextToken()) {
1088 TString strKeyValue(token->GetString());
1089 int delimPos = strKeyValue.First(keyValueDelim.Data());
1090 if (delimPos <= 0) continue;
1091
1092 TString strKey = TString(strKeyValue(0, delimPos));
1093 strKey.ToUpper();
1094 TString strValue = TString(strKeyValue(delimPos + 1, strKeyValue.Length()));
1095
1096 strKey.Strip(TString::kBoth, ' ');
1097 strValue.Strip(TString::kBoth, ' ');
1098
1099 currentBlock.insert(std::make_pair(strKey, strValue));
1100 }
1101 }
1102 return blockKeyValues;
1103}
1104
1105////////////////////////////////////////////////////////////////////////////////
1106/// What kind of analysis type can handle the CNN
1107Bool_t MethodDL::HasAnalysisType(Types::EAnalysisType type, UInt_t numberClasses, UInt_t /*numberTargets*/)
1108{
1109 if (type == Types::kClassification && numberClasses == 2) return kTRUE;
1110 if (type == Types::kMulticlass) return kTRUE;
1111 if (type == Types::kRegression) return kTRUE;
1112
1113 return kFALSE;
1114}
1115
1116////////////////////////////////////////////////////////////////////////////////
1117/// Validation of the ValidationSize option. Allowed formats are 20%, 0.2 and
1118/// 100 etc.
1119/// - 20% and 0.2 selects 20% of the training set as validation data.
1120/// - 100 selects 100 events as the validation data.
1121///
1122/// @return number of samples in validation set
1123///
1124UInt_t TMVA::MethodDL::GetNumValidationSamples()
1125{
1126 Int_t nValidationSamples = 0;
1127 UInt_t trainingSetSize = GetEventCollection(Types::kTraining).size();
1128
1129 // Parsing + Validation
1130 // --------------------
1131 if (fNumValidationString.EndsWith("%")) {
1132 // Relative spec. format 20%
1133 TString intValStr = TString(fNumValidationString.Strip(TString::kTrailing, '%'));
1134
1135 if (intValStr.IsFloat()) {
1136 Double_t valSizeAsDouble = fNumValidationString.Atof() / 100.0;
1137 nValidationSamples = GetEventCollection(Types::kTraining).size() * valSizeAsDouble;
1138 } else {
1139 Log() << kFATAL << "Cannot parse number \"" << fNumValidationString
1140 << "\". Expected string like \"20%\" or \"20.0%\"." << Endl;
1141 }
1142 } else if (fNumValidationString.IsFloat()) {
1143 Double_t valSizeAsDouble = fNumValidationString.Atof();
1144
1145 if (valSizeAsDouble < 1.0) {
1146 // Relative spec. format 0.2
1147 nValidationSamples = GetEventCollection(Types::kTraining).size() * valSizeAsDouble;
1148 } else {
1149 // Absolute spec format 100 or 100.0
1150 nValidationSamples = valSizeAsDouble;
1151 }
1152 } else {
1153 Log() << kFATAL << "Cannot parse number \"" << fNumValidationString << "\". Expected string like \"0.2\" or \"100\"."
1154 << Endl;
1155 }
1156
1157 // Value validation
1158 // ----------------
1159 if (nValidationSamples < 0) {
1160 Log() << kFATAL << "Validation size \"" << fNumValidationString << "\" is negative." << Endl;
1161 }
1162
1163 if (nValidationSamples == 0) {
1164 Log() << kFATAL << "Validation size \"" << fNumValidationString << "\" is zero." << Endl;
1165 }
1166
1167 if (nValidationSamples >= (Int_t)trainingSetSize) {
1168 Log() << kFATAL << "Validation size \"" << fNumValidationString
1169 << "\" is larger than or equal in size to training set (size=\"" << trainingSetSize << "\")." << Endl;
1170 }
1171
1172 return nValidationSamples;
1173}
1174
1175
1176////////////////////////////////////////////////////////////////////////////////
1177/// Implementation of architecture specific train method
1178///
1179template <typename Architecture_t>
1180void MethodDL::TrainDeepNet()
1181{
1182
1183 using Scalar_t = typename Architecture_t::Scalar_t;
1186 using TensorDataLoader_t = TTensorDataLoader<TMVAInput_t, Architecture_t>;
1187
1188 bool debug = Log().GetMinType() == kDEBUG;
1189
1190
1191 // set the random seed for weight initialization
1192 Architecture_t::SetRandomSeed(fRandomSeed);
1193
1194 ///split training data in training and validation data
1195 // and determine the number of training and testing examples
1196
1197 size_t nValidationSamples = GetNumValidationSamples();
1198 size_t nTrainingSamples = GetEventCollection(Types::kTraining).size() - nValidationSamples;
1199
1200 const std::vector<TMVA::Event *> &allData = GetEventCollection(Types::kTraining);
1201 const std::vector<TMVA::Event *> eventCollectionTraining{allData.begin(), allData.begin() + nTrainingSamples};
1202 const std::vector<TMVA::Event *> eventCollectionValidation{allData.begin() + nTrainingSamples, allData.end()};
1203
1204 size_t trainingPhase = 1;
1205
1206 for (TTrainingSettings &settings : this->GetTrainingSettings()) {
1207
1208 size_t nThreads = 1; // FIXME threads are hard coded to 1, no use of slave threads or multi-threading
1209
1210
1211 // After the processing of the options, initialize the master deep net
1212 size_t batchSize = settings.batchSize;
1213 this->SetBatchSize(batchSize);
1214 // Should be replaced by actual implementation. No support for this now.
1215 size_t inputDepth = this->GetInputDepth();
1216 size_t inputHeight = this->GetInputHeight();
1217 size_t inputWidth = this->GetInputWidth();
1218 size_t batchDepth = this->GetBatchDepth();
1219 size_t batchHeight = this->GetBatchHeight();
1220 size_t batchWidth = this->GetBatchWidth();
1221 ELossFunction J = this->GetLossFunction();
1222 EInitialization I = this->GetWeightInitialization();
1223 ERegularization R = settings.regularization;
1224 EOptimizer O = settings.optimizer;
1225 Scalar_t weightDecay = settings.weightDecay;
1226
1227 //Batch size should be included in batch layout as well. There are two possibilities:
1228 // 1. Batch depth = batch size one will input tensorsa as (batch_size x d1 x d2)
1229 // This is case for example if first layer is a conv layer and d1 = image depth, d2 = image width x image height
1230 // 2. Batch depth = 1, batch height = batch size batxch width = dim of input features
1231 // This should be case if first layer is a Dense 1 and input tensor must be ( 1 x batch_size x input_features )
1232
1233 if (batchDepth != batchSize && batchDepth > 1) {
1234 Error("Train","Given batch depth of %zu (specified in BatchLayout) should be equal to given batch size %zu",batchDepth,batchSize);
1235 return;
1236 }
1237 if (batchDepth == 1 && batchSize > 1 && batchSize != batchHeight ) {
1238 Error("Train","Given batch height of %zu (specified in BatchLayout) should be equal to given batch size %zu",batchHeight,batchSize);
1239 return;
1240 }
1241
1242
1243 //check also that input layout compatible with batch layout
1244 bool badLayout = false;
1245 // case batch depth == batch size
1246 if (batchDepth == batchSize)
1247 badLayout = ( inputDepth * inputHeight * inputWidth != batchHeight * batchWidth ) ;
1248 // case batch Height is batch size
1249 if (batchHeight == batchSize && batchDepth == 1)
1250 badLayout |= ( inputDepth * inputHeight * inputWidth != batchWidth);
1251 if (badLayout) {
1252 Error("Train","Given input layout %zu x %zu x %zu is not compatible with batch layout %zu x %zu x %zu ",
1253 inputDepth,inputHeight,inputWidth,batchDepth,batchHeight,batchWidth);
1254 return;
1255 }
1256
1257 // check batch size is compatible with number of events
1258 if (nTrainingSamples < settings.batchSize || nValidationSamples < settings.batchSize) {
1259 Log() << kFATAL << "Number of samples in the datasets are train: ("
1260 << nTrainingSamples << ") test: (" << nValidationSamples
1261 << "). One of these is smaller than the batch size of "
1262 << settings.batchSize << ". Please increase the batch"
1263 << " size to be at least the same size as the smallest"
1264 << " of them." << Endl;
1265 }
1266
1267 DeepNet_t deepNet(batchSize, inputDepth, inputHeight, inputWidth, batchDepth, batchHeight, batchWidth, J, I, R, weightDecay);
1268
1269 // create a copy of DeepNet for evaluating but with batch size = 1
1270 // fNet is the saved network and will be with CPU or Referrence architecture
1271 if (trainingPhase == 1) {
1272 fNet = std::unique_ptr<DeepNetImpl_t>(new DeepNetImpl_t(1, inputDepth, inputHeight, inputWidth, batchDepth,
1273 batchHeight, batchWidth, J, I, R, weightDecay));
1274 fBuildNet = true;
1275 }
1276 else
1277 fBuildNet = false;
1278
1279 // Initialize the vector of slave nets
1280 std::vector<DeepNet_t> nets{};
1281 nets.reserve(nThreads);
1282 for (size_t i = 0; i < nThreads; i++) {
1283 // create a copies of the master deep net
1284 nets.push_back(deepNet);
1285 }
1286
1287
1288 // Add all appropriate layers to deepNet and (if fBuildNet is true) also to fNet
1289 CreateDeepNet(deepNet, nets);
1290
1291
1292 // set droput probabilities
1293 // use convention to store in the layer 1.- dropout probabilities
1294 std::vector<Double_t> dropoutVector(settings.dropoutProbabilities);
1295 for (auto & p : dropoutVector) {
1296 p = 1.0 - p;
1297 }
1298 deepNet.SetDropoutProbabilities(dropoutVector);
1299
1300 if (trainingPhase > 1) {
1301 // copy initial weights from fNet to deepnet
1302 for (size_t i = 0; i < deepNet.GetDepth(); ++i) {
1303 deepNet.GetLayerAt(i)->CopyParameters(*fNet->GetLayerAt(i));
1304 }
1305 }
1306
1307 // when fNet is built create also input matrix that will be used to evaluate it
1308 if (fBuildNet) {
1309 //int n1 = batchHeight;
1310 //int n2 = batchWidth;
1311 // treat case where batchHeight is the batchSize in case of first Dense layers (then we need to set to fNet batch size)
1312 //if (batchDepth == 1 && GetInputHeight() == 1 && GetInputDepth() == 1) n1 = fNet->GetBatchSize();
1313 //fXInput = TensorImpl_t(1,n1,n2);
1314 fXInput = ArchitectureImpl_t::CreateTensor(fNet->GetBatchSize(), GetInputDepth(), GetInputHeight(), GetInputWidth() );
1315 if (batchDepth == 1 && GetInputHeight() == 1 && GetInputDepth() == 1)
1316 fXInput = TensorImpl_t( fNet->GetBatchSize(), GetInputWidth() );
1317 fXInputBuffer = HostBufferImpl_t( fXInput.GetSize() );
1318
1319
1320 // create pointer to output matrix used for the predictions
1321 fYHat = std::unique_ptr<MatrixImpl_t>(new MatrixImpl_t(fNet->GetBatchSize(), fNet->GetOutputWidth() ) );
1322
1323 // print the created network
1324 Log() << "***** Deep Learning Network *****" << Endl;
1325 if (Log().GetMinType() <= kINFO)
1326 deepNet.Print();
1327 }
1328 Log() << "Using " << nTrainingSamples << " events for training and " << nValidationSamples << " for testing" << Endl;
1329
1330 // Loading the training and validation datasets
1331 TMVAInput_t trainingTuple = std::tie(eventCollectionTraining, DataInfo());
1332 TensorDataLoader_t trainingData(trainingTuple, nTrainingSamples, batchSize,
1333 {inputDepth, inputHeight, inputWidth},
1334 {deepNet.GetBatchDepth(), deepNet.GetBatchHeight(), deepNet.GetBatchWidth()} ,
1335 deepNet.GetOutputWidth(), nThreads);
1336
1337 TMVAInput_t validationTuple = std::tie(eventCollectionValidation, DataInfo());
1338 TensorDataLoader_t validationData(validationTuple, nValidationSamples, batchSize,
1339 {inputDepth, inputHeight, inputWidth},
1340 { deepNet.GetBatchDepth(),deepNet.GetBatchHeight(), deepNet.GetBatchWidth()} ,
1341 deepNet.GetOutputWidth(), nThreads);
1342
1343
1344
1345 // do an evaluation of the network to compute initial minimum test error
1346
1347 Bool_t includeRegularization = (R != DNN::ERegularization::kNone);
1348
1349 Double_t minValError = 0.0;
1350 Log() << "Compute initial loss on the validation data " << Endl;
1351 for (auto batch : validationData) {
1352 auto inputTensor = batch.GetInput();
1353 auto outputMatrix = batch.GetOutput();
1354 auto weights = batch.GetWeights();
1355
1356 //std::cout << " input use count " << inputTensor.GetBufferUseCount() << std::endl;
1357 // should we apply droput to the loss ??
1358 minValError += deepNet.Loss(inputTensor, outputMatrix, weights, false, includeRegularization);
1359 }
1360 // add Regularization term
1361 Double_t regzTerm = (includeRegularization) ? deepNet.RegularizationTerm() : 0.0;
1362 minValError /= (Double_t)(nValidationSamples / settings.batchSize);
1363 minValError += regzTerm;
1364
1365
1366 // create a pointer to base class VOptimizer
1367 std::unique_ptr<DNN::VOptimizer<Architecture_t, Layer_t, DeepNet_t>> optimizer;
1368
1369 // initialize the base class pointer with the corresponding derived class object.
1370 switch (O) {
1371
1372 case EOptimizer::kSGD:
1373 optimizer = std::unique_ptr<DNN::TSGD<Architecture_t, Layer_t, DeepNet_t>>(
1375 break;
1376
1377 case EOptimizer::kAdam: {
1378 optimizer = std::unique_ptr<DNN::TAdam<Architecture_t, Layer_t, DeepNet_t>>(
1380 deepNet, settings.learningRate, settings.optimizerParams["ADAM_beta1"],
1381 settings.optimizerParams["ADAM_beta2"], settings.optimizerParams["ADAM_eps"]));
1382 break;
1383 }
1384
1385 case EOptimizer::kAdagrad:
1386 optimizer = std::unique_ptr<DNN::TAdagrad<Architecture_t, Layer_t, DeepNet_t>>(
1388 settings.optimizerParams["ADAGRAD_eps"]));
1389 break;
1390
1391 case EOptimizer::kRMSProp:
1392 optimizer = std::unique_ptr<DNN::TRMSProp<Architecture_t, Layer_t, DeepNet_t>>(
1394 settings.optimizerParams["RMSPROP_rho"],
1395 settings.optimizerParams["RMSPROP_eps"]));
1396 break;
1397
1398 case EOptimizer::kAdadelta:
1399 optimizer = std::unique_ptr<DNN::TAdadelta<Architecture_t, Layer_t, DeepNet_t>>(
1401 settings.optimizerParams["ADADELTA_rho"],
1402 settings.optimizerParams["ADADELTA_eps"]));
1403 break;
1404 }
1405
1406
1407 // Initialize the vector of batches, one batch for one slave network
1408 std::vector<TTensorBatch<Architecture_t>> batches{};
1409
1410 bool converged = false;
1411 size_t convergenceCount = 0;
1412 size_t batchesInEpoch = nTrainingSamples / deepNet.GetBatchSize();
1413
1414 // start measuring
1415 std::chrono::time_point<std::chrono::system_clock> tstart, tend;
1416 tstart = std::chrono::system_clock::now();
1417
1418 // function building string with optimizer parameters values for logging
1419 auto optimParametersString = [&]() {
1420 TString optimParameters;
1421 for ( auto & element : settings.optimizerParams) {
1422 TString key = element.first;
1423 key.ReplaceAll(settings.optimizerName + "_", ""); // strip optimizerName_
1424 double value = element.second;
1425 if (!optimParameters.IsNull())
1426 optimParameters += ",";
1427 else
1428 optimParameters += " (";
1429 optimParameters += TString::Format("%s=%g", key.Data(), value);
1430 }
1431 if (!optimParameters.IsNull())
1432 optimParameters += ")";
1433 return optimParameters;
1434 };
1435
1436 Log() << "Training phase " << trainingPhase << " of " << this->GetTrainingSettings().size() << ": "
1437 << " Optimizer " << settings.optimizerName
1438 << optimParametersString()
1439 << " Learning rate = " << settings.learningRate << " regularization " << (char)settings.regularization
1440 << " minimum error = " << minValError << Endl;
1441 std::string separator(62, '-');
1442 Log() << separator << Endl;
1443 Log() << std::setw(10) << "Epoch"
1444 << " | " << std::setw(12) << "Train Err." << std::setw(12) << "Val. Err." << std::setw(12)
1445 << "t(s)/epoch" << std::setw(12) << "t(s)/Loss" << std::setw(12) << "nEvents/s" << std::setw(12)
1446 << "Conv. Steps" << Endl;
1447 Log() << separator << Endl;
1448
1449 // set up generator for shuffling the batches
1450 // if seed is zero we have always a different order in the batches
1451 size_t shuffleSeed = 0;
1452 if (fRandomSeed != 0) shuffleSeed = fRandomSeed + trainingPhase;
1453 RandomGenerator<TRandom3> rng(shuffleSeed);
1454
1455 // print weights before
1456 if (fBuildNet && debug) {
1457 Log() << "Initial Deep Net Weights " << Endl;
1458 auto & weights_tensor = deepNet.GetLayerAt(0)->GetWeights();
1459 for (size_t l = 0; l < weights_tensor.size(); ++l)
1460 weights_tensor[l].Print();
1461 auto & bias_tensor = deepNet.GetLayerAt(0)->GetBiases();
1462 bias_tensor[0].Print();
1463 }
1464
1465 Log() << " Start epoch iteration ..." << Endl;
1466 bool debugFirstEpoch = false;
1467 bool computeLossInTraining = true; // compute loss in training or at test time
1468 size_t nTrainEpochs = 0;
1469 while (!converged) {
1470 nTrainEpochs++;
1471 trainingData.Shuffle(rng);
1472
1473 // execute all epochs
1474 //for (size_t i = 0; i < batchesInEpoch; i += nThreads) {
1475
1476 Double_t trainingError = 0;
1477 for (size_t i = 0; i < batchesInEpoch; ++i ) {
1478 // Clean and load new batches, one batch for one slave net
1479 //batches.clear();
1480 //batches.reserve(nThreads);
1481 //for (size_t j = 0; j < nThreads; j++) {
1482 // batches.push_back(trainingData.GetTensorBatch());
1483 //}
1484 if (debugFirstEpoch) std::cout << "\n\n----- batch # " << i << "\n\n";
1485
1486 auto my_batch = trainingData.GetTensorBatch();
1487
1488 if (debugFirstEpoch)
1489 std::cout << "got batch data - doing forward \n";
1490
1491#ifdef DEBUG
1492
1493 Architecture_t::PrintTensor(my_batch.GetInput(),"input tensor",true);
1494 typename Architecture_t::Tensor_t tOut(my_batch.GetOutput());
1495 typename Architecture_t::Tensor_t tW(my_batch.GetWeights());
1496 Architecture_t::PrintTensor(tOut,"label tensor",true) ;
1497 Architecture_t::PrintTensor(tW,"weight tensor",true) ;
1498#endif
1499
1500 deepNet.Forward(my_batch.GetInput(), true);
1501 // compute also loss
1502 if (computeLossInTraining) {
1503 auto outputMatrix = my_batch.GetOutput();
1504 auto weights = my_batch.GetWeights();
1505 trainingError += deepNet.Loss(outputMatrix, weights, false);
1506 }
1507
1508 if (debugFirstEpoch)
1509 std::cout << "- doing backward \n";
1510
1511#ifdef DEBUG
1512 size_t nlayers = deepNet.GetLayers().size();
1513 for (size_t l = 0; l < nlayers; ++l) {
1514 if (deepNet.GetLayerAt(l)->GetWeights().size() > 0)
1515 Architecture_t::PrintTensor(deepNet.GetLayerAt(l)->GetWeightsAt(0),
1516 TString::Format("initial weights layer %d", l).Data());
1517
1518 Architecture_t::PrintTensor(deepNet.GetLayerAt(l)->GetOutput(),
1519 TString::Format("output tensor layer %d", l).Data());
1520 }
1521#endif
1522
1523 //Architecture_t::PrintTensor(deepNet.GetLayerAt(nlayers-1)->GetOutput(),"output tensor last layer" );
1524
1525 deepNet.Backward(my_batch.GetInput(), my_batch.GetOutput(), my_batch.GetWeights());
1526
1527 if (debugFirstEpoch)
1528 std::cout << "- doing optimizer update \n";
1529
1530 // increment optimizer step that is used in some algorithms (e.g. ADAM)
1531 optimizer->IncrementGlobalStep();
1532 optimizer->Step();
1533
1534#ifdef DEBUG
1535 std::cout << "minmimizer step - momentum " << settings.momentum << " learning rate " << optimizer->GetLearningRate() << std::endl;
1536 for (size_t l = 0; l < nlayers; ++l) {
1537 if (deepNet.GetLayerAt(l)->GetWeights().size() > 0) {
1538 Architecture_t::PrintTensor(deepNet.GetLayerAt(l)->GetWeightsAt(0),TString::Format("weights after step layer %d",l).Data());
1539 Architecture_t::PrintTensor(deepNet.GetLayerAt(l)->GetWeightGradientsAt(0),"weight gradients");
1540 }
1541 }
1542#endif
1543
1544 }
1545
1546 if (debugFirstEpoch) std::cout << "\n End batch loop - compute validation loss \n";
1547 //}
1548 debugFirstEpoch = false;
1549 if ((nTrainEpochs % settings.testInterval) == 0) {
1550
1551 std::chrono::time_point<std::chrono::system_clock> t1,t2;
1552
1553 t1 = std::chrono::system_clock::now();
1554
1555 // Compute validation error.
1556
1557
1558 Double_t valError = 0.0;
1559 bool inTraining = false;
1560 for (auto batch : validationData) {
1561 auto inputTensor = batch.GetInput();
1562 auto outputMatrix = batch.GetOutput();
1563 auto weights = batch.GetWeights();
1564 // should we apply droput to the loss ??
1565 valError += deepNet.Loss(inputTensor, outputMatrix, weights, inTraining, includeRegularization);
1566 }
1567 // normalize loss to number of batches and add regularization term
1568 Double_t regTerm = (includeRegularization) ? deepNet.RegularizationTerm() : 0.0;
1569 valError /= (Double_t)(nValidationSamples / settings.batchSize);
1570 valError += regTerm;
1571
1572 //Log the loss value
1573 fTrainHistory.AddValue("valError",nTrainEpochs,valError);
1574
1575 t2 = std::chrono::system_clock::now();
1576
1577 // checking for convergence
1578 if (valError < minValError) {
1579 convergenceCount = 0;
1580 } else {
1581 convergenceCount += settings.testInterval;
1582 }
1583
1584 // copy configuration when reached a minimum error
1585 if (valError < minValError ) {
1586 // Copy weights from deepNet to fNet
1587 Log() << std::setw(10) << nTrainEpochs
1588 << " Minimum Test error found - save the configuration " << Endl;
1589 for (size_t i = 0; i < deepNet.GetDepth(); ++i) {
1590 fNet->GetLayerAt(i)->CopyParameters(*deepNet.GetLayerAt(i));
1591 // if (i == 0 && deepNet.GetLayerAt(0)->GetWeights().size() > 1) {
1592 // Architecture_t::PrintTensor(deepNet.GetLayerAt(0)->GetWeightsAt(0), " input weights");
1593 // Architecture_t::PrintTensor(deepNet.GetLayerAt(0)->GetWeightsAt(1), " state weights");
1594 // }
1595 }
1596 // Architecture_t::PrintTensor(deepNet.GetLayerAt(1)->GetWeightsAt(0), " cudnn weights");
1597 // ArchitectureImpl_t::PrintTensor(fNet->GetLayerAt(1)->GetWeightsAt(0), " cpu weights");
1598
1599 minValError = valError;
1600 }
1601 else if ( minValError <= 0. )
1602 minValError = valError;
1603
1604 if (!computeLossInTraining) {
1605 trainingError = 0.0;
1606 // Compute training error.
1607 for (auto batch : trainingData) {
1608 auto inputTensor = batch.GetInput();
1609 auto outputMatrix = batch.GetOutput();
1610 auto weights = batch.GetWeights();
1611 trainingError += deepNet.Loss(inputTensor, outputMatrix, weights, false, false);
1612 }
1613 }
1614 // normalize loss to number of batches and add regularization term
1615 trainingError /= (Double_t)(nTrainingSamples / settings.batchSize);
1616 trainingError += regTerm;
1617
1618 //Log the loss value
1619 fTrainHistory.AddValue("trainingError",nTrainEpochs,trainingError);
1620
1621 // stop measuring
1622 tend = std::chrono::system_clock::now();
1623
1624 // Compute numerical throughput.
1625 std::chrono::duration<double> elapsed_seconds = tend - tstart;
1626 std::chrono::duration<double> elapsed1 = t1-tstart;
1627 // std::chrono::duration<double> elapsed2 = t2-tstart;
1628 // time to compute training and test errors
1629 std::chrono::duration<double> elapsed_testing = tend-t1;
1630
1631 double seconds = elapsed_seconds.count();
1632 // double nGFlops = (double)(settings.testInterval * batchesInEpoch * settings.batchSize)*1.E-9;
1633 // nGFlops *= deepnet.GetNFlops() * 1e-9;
1634 double eventTime = elapsed1.count()/( batchesInEpoch * settings.testInterval * settings.batchSize);
1635
1636 converged =
1637 convergenceCount > settings.convergenceSteps || nTrainEpochs >= settings.maxEpochs;
1638
1639
1640 Log() << std::setw(10) << nTrainEpochs << " | "
1641 << std::setw(12) << trainingError
1642 << std::setw(12) << valError
1643 << std::setw(12) << seconds / settings.testInterval
1644 << std::setw(12) << elapsed_testing.count()
1645 << std::setw(12) << 1. / eventTime
1646 << std::setw(12) << convergenceCount
1647 << Endl;
1648
1649 if (converged) {
1650 Log() << Endl;
1651 }
1652 tstart = std::chrono::system_clock::now();
1653 }
1654
1655 // if (stepCount % 10 == 0 || converged) {
1656 if (converged && debug) {
1657 Log() << "Final Deep Net Weights for phase " << trainingPhase << " epoch " << nTrainEpochs
1658 << Endl;
1659 auto & weights_tensor = deepNet.GetLayerAt(0)->GetWeights();
1660 auto & bias_tensor = deepNet.GetLayerAt(0)->GetBiases();
1661 for (size_t l = 0; l < weights_tensor.size(); ++l)
1662 weights_tensor[l].Print();
1663 bias_tensor[0].Print();
1664 }
1665
1666 }
1667
1668 trainingPhase++;
1669 } // end loop on training Phase
1670}
1671
1672////////////////////////////////////////////////////////////////////////////////
1673void MethodDL::Train()
1674{
1675 // using for training same scalar type defined for the prediction
1676 if (this->GetArchitectureString() == "GPU") {
1677#ifdef R__HAS_TMVAGPU
1678 Log() << kINFO << "Start of deep neural network training on GPU." << Endl << Endl;
1679#ifdef R__HAS_CUDNN
1680 TrainDeepNet<DNN::TCudnn<ScalarImpl_t> >();
1681#else
1682 TrainDeepNet<DNN::TCuda<ScalarImpl_t>>();
1683#endif
1684#else
1685 Log() << kFATAL << "CUDA backend not enabled. Please make sure "
1686 "you have CUDA installed and it was successfully "
1687 "detected by CMAKE."
1688 << Endl;
1689 return;
1690#endif
1691 } else if (this->GetArchitectureString() == "CPU") {
1692#ifdef R__HAS_TMVACPU
1693 // note that number of threads used for BLAS might be different
1694 // e.g use openblas_set_num_threads(num_threads) for OPENBLAS backend
1695 Log() << kINFO << "Start of deep neural network training on CPU using MT, nthreads = "
1696 << gConfig().GetNCpu() << Endl << Endl;
1697#else
1698 Log() << kINFO << "Start of deep neural network training on single thread CPU (without ROOT-MT support) " << Endl
1699 << Endl;
1700#endif
1701 TrainDeepNet<DNN::TCpu<ScalarImpl_t> >();
1702 return;
1703 }
1704 else {
1705 Log() << kFATAL << this->GetArchitectureString() <<
1706 " is not a supported architecture for TMVA::MethodDL"
1707 << Endl;
1708 }
1709
1710}
1711
1712////////////////////////////////////////////////////////////////////////////////
1713void TMVA::MethodDL::FillInputTensor()
1714{
1715 // fill the input tensor fXInput from the current Event data
1716 // with the correct shape depending on the model used
1717 // The input tensor is used for network prediction after training
1718 // using a single event. The network batch size must be equal to 1.
1719 // The architecture specified at compile time in ArchitectureImpl_t
1720 // is used. This should be the CPU architecture
1721
1722 if (!fNet || fNet->GetDepth() == 0) {
1723 Log() << kFATAL << "The network has not been trained and fNet is not built" << Endl;
1724 }
1725 if (fNet->GetBatchSize() != 1) {
1726 Log() << kFATAL << "FillINputTensor::Network batch size must be equal to 1 when doing single event predicition" << Endl;
1727 }
1728
1729 // get current event
1730 const std::vector<Float_t> &inputValues = GetEvent()->GetValues();
1731 size_t nVariables = GetEvent()->GetNVariables();
1732
1733 // for Columnlayout tensor memory layout is HWC while for rowwise is CHW
1734 if (fXInput.GetLayout() == TMVA::DNN::MemoryLayout::ColumnMajor) {
1735 R__ASSERT(fXInput.GetShape().size() < 4);
1736 size_t nc, nhw = 0;
1737 if (fXInput.GetShape().size() == 2) {
1738 nc = fXInput.GetShape()[0];
1739 if (nc != 1) {
1740 ArchitectureImpl_t::PrintTensor(fXInput);
1741 Log() << kFATAL << "First tensor dimension should be equal to batch size, i.e. = 1" << Endl;
1742 }
1743 nhw = fXInput.GetShape()[1];
1744 } else {
1745 nc = fXInput.GetCSize();
1746 nhw = fXInput.GetWSize();
1747 }
1748 if (nVariables != nc * nhw) {
1749 Log() << kFATAL << "Input Event variable dimensions are not compatible with the built network architecture"
1750 << " n-event variables " << nVariables << " expected input tensor " << nc << " x " << nhw << Endl;
1751 }
1752 for (size_t j = 0; j < nc; j++) {
1753 for (size_t k = 0; k < nhw; k++) {
1754 // note that in TMVA events images are stored as C H W while in the buffer we stored as H W C
1755 fXInputBuffer[k * nc + j] = inputValues[j * nhw + k]; // for column layout !!!
1756 }
1757 }
1758 } else {
1759 // row-wise layout
1760 assert(fXInput.GetShape().size() >= 4);
1761 size_t nc = fXInput.GetCSize();
1762 size_t nh = fXInput.GetHSize();
1763 size_t nw = fXInput.GetWSize();
1764 size_t n = nc * nh * nw;
1765 if (nVariables != n) {
1766 Log() << kFATAL << "Input Event variable dimensions are not compatible with the built network architecture"
1767 << " n-event variables " << nVariables << " expected input tensor " << nc << " x " << nh << " x " << nw
1768 << Endl;
1769 }
1770 for (size_t j = 0; j < n; j++) {
1771 // in this case TMVA event has same order as input tensor
1772 fXInputBuffer[j] = inputValues[j]; // for column layout !!!
1773 }
1774 }
1775 // copy buffer in input
1776 fXInput.GetDeviceBuffer().CopyFrom(fXInputBuffer);
1777 return;
1778}
1779
1780////////////////////////////////////////////////////////////////////////////////
1781Double_t MethodDL::GetMvaValue(Double_t * /*errLower*/, Double_t * /*errUpper*/)
1782{
1783
1784 FillInputTensor();
1785
1786 // perform the prediction
1787 fNet->Prediction(*fYHat, fXInput, fOutputFunction);
1788
1789 // return value
1790 double mvaValue = (*fYHat)(0, 0);
1791
1792 // for debugging
1793#ifdef DEBUG_MVAVALUE
1794 using Tensor_t = std::vector<MatrixImpl_t>;
1795 TMatrixF xInput(n1,n2, inputValues.data() );
1796 std::cout << "Input data - class " << GetEvent()->GetClass() << std::endl;
1797 xInput.Print();
1798 std::cout << "Output of DeepNet " << mvaValue << std::endl;
1799 auto & deepnet = *fNet;
1800 std::cout << "Loop on layers " << std::endl;
1801 for (int l = 0; l < deepnet.GetDepth(); ++l) {
1802 std::cout << "Layer " << l;
1803 const auto * layer = deepnet.GetLayerAt(l);
1804 const Tensor_t & layer_output = layer->GetOutput();
1805 layer->Print();
1806 std::cout << "DNN output " << layer_output.size() << std::endl;
1807 for (size_t i = 0; i < layer_output.size(); ++i) {
1808#ifdef R__HAS_TMVAGPU
1809 //TMatrixD m(layer_output[i].GetNrows(), layer_output[i].GetNcols() , layer_output[i].GetDataPointer() );
1810 TMatrixD m = layer_output[i];
1811#else
1812 TMatrixD m(layer_output[i].GetNrows(), layer_output[i].GetNcols() , layer_output[i].GetRawDataPointer() );
1813#endif
1814 m.Print();
1815 }
1816 const Tensor_t & layer_weights = layer->GetWeights();
1817 std::cout << "DNN weights " << layer_weights.size() << std::endl;
1818 if (layer_weights.size() > 0) {
1819 int i = 0;
1820#ifdef R__HAS_TMVAGPU
1821 TMatrixD m = layer_weights[i];
1822// TMatrixD m(layer_weights[i].GetNrows(), layer_weights[i].GetNcols() , layer_weights[i].GetDataPointer() );
1823#else
1824 TMatrixD m(layer_weights[i].GetNrows(), layer_weights[i].GetNcols() , layer_weights[i].GetRawDataPointer() );
1825#endif
1826 m.Print();
1827 }
1828 }
1829#endif
1830
1831 return (TMath::IsNaN(mvaValue)) ? -999. : mvaValue;
1832}
1833////////////////////////////////////////////////////////////////////////////////
1834/// Evaluate the DeepNet on a vector of input values stored in the TMVA Event class
1835////////////////////////////////////////////////////////////////////////////////
1836template <typename Architecture_t>
1837std::vector<Double_t> MethodDL::PredictDeepNet(Long64_t firstEvt, Long64_t lastEvt, size_t batchSize, Bool_t logProgress)
1838{
1839
1840 // Check whether the model is setup
1841 if (!fNet || fNet->GetDepth() == 0) {
1842 Log() << kFATAL << "The network has not been trained and fNet is not built"
1843 << Endl;
1844 }
1845
1846 // rebuild the networks
1847 this->SetBatchSize(batchSize);
1848 size_t inputDepth = this->GetInputDepth();
1849 size_t inputHeight = this->GetInputHeight();
1850 size_t inputWidth = this->GetInputWidth();
1851 size_t batchDepth = this->GetBatchDepth();
1852 size_t batchHeight = this->GetBatchHeight();
1853 size_t batchWidth = this->GetBatchWidth();
1854 ELossFunction J = fNet->GetLossFunction();
1855 EInitialization I = fNet->GetInitialization();
1856 ERegularization R = fNet->GetRegularization();
1857 Double_t weightDecay = fNet->GetWeightDecay();
1858
1859 using DeepNet_t = TMVA::DNN::TDeepNet<Architecture_t>;
1860 using Matrix_t = typename Architecture_t::Matrix_t;
1861 using TensorDataLoader_t = TTensorDataLoader<TMVAInput_t, Architecture_t>;
1862
1863 // create the deep neural network
1864 DeepNet_t deepNet(batchSize, inputDepth, inputHeight, inputWidth, batchDepth, batchHeight, batchWidth, J, I, R, weightDecay);
1865 std::vector<DeepNet_t> nets{};
1866 fBuildNet = false;
1867 CreateDeepNet(deepNet,nets);
1868
1869 // copy weights from the saved fNet to the built DeepNet
1870 for (size_t i = 0; i < deepNet.GetDepth(); ++i) {
1871 deepNet.GetLayerAt(i)->CopyParameters(*fNet->GetLayerAt(i));
1872 // if (i == 0 && deepNet.GetLayerAt(0)->GetWeights().size() > 1) {
1873 // Architecture_t::PrintTensor(deepNet.GetLayerAt(0)->GetWeightsAt(0), "Inference: input weights");
1874 // Architecture_t::PrintTensor(deepNet.GetLayerAt(0)->GetWeightsAt(1), "Inference: state weights");
1875 // }
1876 }
1877
1878 size_t n1 = deepNet.GetBatchHeight();
1879 size_t n2 = deepNet.GetBatchWidth();
1880 size_t n0 = deepNet.GetBatchSize();
1881 // treat case where batchHeight is the batchSize in case of first Dense layers (then we need to set to fNet batch size)
1882 if (batchDepth == 1 && GetInputHeight() == 1 && GetInputDepth() == 1) {
1883 n1 = deepNet.GetBatchSize();
1884 n0 = 1;
1885 }
1886 //this->SetBatchDepth(n0);
1887 Long64_t nEvents = lastEvt - firstEvt;
1888 TMVAInput_t testTuple = std::tie(GetEventCollection(Data()->GetCurrentType()), DataInfo());
1889 TensorDataLoader_t testData(testTuple, nEvents, batchSize, {inputDepth, inputHeight, inputWidth}, {n0, n1, n2}, deepNet.GetOutputWidth(), 1);
1890
1891
1892 // Tensor_t xInput;
1893 // for (size_t i = 0; i < n0; ++i)
1894 // xInput.emplace_back(Matrix_t(n1,n2));
1895
1896 // create pointer to output matrix used for the predictions
1897 Matrix_t yHat(deepNet.GetBatchSize(), deepNet.GetOutputWidth() );
1898
1899 // use timer
1900 Timer timer( nEvents, GetName(), kTRUE );
1901
1902 if (logProgress)
1903 Log() << kHEADER << Form("[%s] : ",DataInfo().GetName())
1904 << "Evaluation of " << GetMethodName() << " on "
1905 << (Data()->GetCurrentType() == Types::kTraining ? "training" : "testing")
1906 << " sample (" << nEvents << " events)" << Endl;
1907
1908
1909 // eventg loop
1910 std::vector<double> mvaValues(nEvents);
1911
1912
1913 for ( Long64_t ievt = firstEvt; ievt < lastEvt; ievt+=batchSize) {
1914
1915 Long64_t ievt_end = ievt + batchSize;
1916 // case of batch prediction for
1917 if (ievt_end <= lastEvt) {
1918
1919 if (ievt == firstEvt) {
1920 Data()->SetCurrentEvent(ievt);
1921 size_t nVariables = GetEvent()->GetNVariables();
1922
1923 if (n1 == batchSize && n0 == 1) {
1924 if (n2 != nVariables) {
1925 Log() << kFATAL << "Input Event variable dimensions are not compatible with the built network architecture"
1926 << " n-event variables " << nVariables << " expected input matrix " << n1 << " x " << n2
1927 << Endl;
1928 }
1929 } else {
1930 if (n1*n2 != nVariables || n0 != batchSize) {
1931 Log() << kFATAL << "Input Event variable dimensions are not compatible with the built network architecture"
1932 << " n-event variables " << nVariables << " expected input tensor " << n0 << " x " << n1 << " x " << n2
1933 << Endl;
1934 }
1935 }
1936 }
1937
1938 auto batch = testData.GetTensorBatch();
1939 auto inputTensor = batch.GetInput();
1940
1941 auto xInput = batch.GetInput();
1942 // make the prediction
1943 deepNet.Prediction(yHat, xInput, fOutputFunction);
1944 for (size_t i = 0; i < batchSize; ++i) {
1945 double value = yHat(i,0);
1946 mvaValues[ievt + i] = (TMath::IsNaN(value)) ? -999. : value;
1947 }
1948 }
1949 else {
1950 // case of remaining events: compute prediction by single event !
1951 for (Long64_t i = ievt; i < lastEvt; ++i) {
1952 Data()->SetCurrentEvent(i);
1953 mvaValues[i] = GetMvaValue();
1954 }
1955 }
1956 }
1957
1958 if (logProgress) {
1959 Log() << kINFO
1960 << "Elapsed time for evaluation of " << nEvents << " events: "
1961 << timer.GetElapsedTime() << " " << Endl;
1962 }
1963
1964 return mvaValues;
1965}
1966
1967//////////////////////////////////////////////////////////////////////////
1968/// Get the regression output values for a single event
1969//////////////////////////////////////////////////////////////////////////
1970const std::vector<Float_t> & TMVA::MethodDL::GetRegressionValues()
1971{
1972
1973 FillInputTensor ();
1974
1975 // perform the network prediction
1976 fNet->Prediction(*fYHat, fXInput, fOutputFunction);
1977
1978 size_t nTargets = DataInfo().GetNTargets();
1979 R__ASSERT(nTargets == fYHat->GetNcols());
1980
1981 std::vector<Float_t> output(nTargets);
1982 for (size_t i = 0; i < nTargets; i++)
1983 output[i] = (*fYHat)(0, i);
1984
1985 // ned to transform back output values
1986 if (fRegressionReturnVal == NULL)
1987 fRegressionReturnVal = new std::vector<Float_t>(nTargets);
1988 R__ASSERT(fRegressionReturnVal->size() == nTargets);
1989
1990 // N.B. one should cache here temporary event class
1991 Event *evT = new Event(*GetEvent());
1992 for (size_t i = 0; i < nTargets; ++i) {
1993 evT->SetTarget(i, output[i]);
1994 }
1995 const Event *evT2 = GetTransformationHandler().InverseTransform(evT);
1996 for (size_t i = 0; i < nTargets; ++i) {
1997 (*fRegressionReturnVal)[i] = evT2->GetTarget(i);
1998 }
1999 delete evT;
2000 return *fRegressionReturnVal;
2001}
2002//////////////////////////////////////////////////////////////////////////
2003/// Get the multi-class output values for a single event
2004//////////////////////////////////////////////////////////////////////////
2005const std::vector<Float_t> &TMVA::MethodDL::GetMulticlassValues()
2006{
2007
2008 FillInputTensor();
2009
2010 fNet->Prediction(*fYHat, fXInput, fOutputFunction);
2011
2012 size_t nClasses = DataInfo().GetNClasses();
2013 R__ASSERT(nClasses == fYHat->GetNcols());
2014
2015 if (fMulticlassReturnVal == NULL) {
2016 fMulticlassReturnVal = new std::vector<Float_t>(nClasses);
2017 }
2018 R__ASSERT(fMulticlassReturnVal->size() == nClasses);
2019
2020 for (size_t i = 0; i < nClasses; i++) {
2021 (*fMulticlassReturnVal)[i] = (*fYHat)(0, i);
2022 }
2023 return *fMulticlassReturnVal;
2024}
2025
2026////////////////////////////////////////////////////////////////////////////////
2027/// Evaluate the DeepNet on a vector of input values stored in the TMVA Event class
2028/// Here we will evaluate using a default batch size and the same architecture used for
2029/// Training
2030////////////////////////////////////////////////////////////////////////////////
2031std::vector<Double_t> MethodDL::GetMvaValues(Long64_t firstEvt, Long64_t lastEvt, Bool_t logProgress)
2032{
2033
2034 Long64_t nEvents = Data()->GetNEvents();
2035 if (firstEvt > lastEvt || lastEvt > nEvents) lastEvt = nEvents;
2036 if (firstEvt < 0) firstEvt = 0;
2037 nEvents = lastEvt-firstEvt;
2038
2039 // use same batch size as for training (from first strategy)
2040 size_t defaultEvalBatchSize = (fXInput.GetSize() > 1000) ? 100 : 1000;
2041 size_t batchSize = (fTrainingSettings.empty()) ? defaultEvalBatchSize : fTrainingSettings.front().batchSize;
2042 if ( size_t(nEvents) < batchSize ) batchSize = nEvents;
2043
2044 // using for training same scalar type defined for the prediction
2045 if (this->GetArchitectureString() == "GPU") {
2046#ifdef R__HAS_TMVAGPU
2047 Log() << kINFO << "Evaluate deep neural network on GPU using batches with size = " << batchSize << Endl << Endl;
2048#ifdef R__HAS_CUDNN
2049 return PredictDeepNet<DNN::TCudnn<ScalarImpl_t>>(firstEvt, lastEvt, batchSize, logProgress);
2050#else
2051 return PredictDeepNet<DNN::TCuda<ScalarImpl_t>>(firstEvt, lastEvt, batchSize, logProgress);
2052#endif
2053
2054#endif
2055 }
2056 Log() << kINFO << "Evaluate deep neural network on CPU using batches with size = " << batchSize << Endl << Endl;
2057 return PredictDeepNet<DNN::TCpu<ScalarImpl_t> >(firstEvt, lastEvt, batchSize, logProgress);
2058}
2059////////////////////////////////////////////////////////////////////////////////
2060void MethodDL::AddWeightsXMLTo(void * parent) const
2061{
2062 // Create the parent XML node with name "Weights"
2063 auto & xmlEngine = gTools().xmlengine();
2064 void* nn = xmlEngine.NewChild(parent, 0, "Weights");
2065
2066 /*! Get all necessary information, in order to be able to reconstruct the net
2067 * if we read the same XML file. */
2068
2069 // Deep Net specific info
2070 Int_t depth = fNet->GetDepth();
2071
2072 Int_t inputDepth = fNet->GetInputDepth();
2073 Int_t inputHeight = fNet->GetInputHeight();
2074 Int_t inputWidth = fNet->GetInputWidth();
2075
2076 Int_t batchSize = fNet->GetBatchSize();
2077
2078 Int_t batchDepth = fNet->GetBatchDepth();
2079 Int_t batchHeight = fNet->GetBatchHeight();
2080 Int_t batchWidth = fNet->GetBatchWidth();
2081
2082 char lossFunction = static_cast<char>(fNet->GetLossFunction());
2083 char initialization = static_cast<char>(fNet->GetInitialization());
2084 char regularization = static_cast<char>(fNet->GetRegularization());
2085
2086 Double_t weightDecay = fNet->GetWeightDecay();
2087
2088 // Method specific info (not sure these are needed)
2089 char outputFunction = static_cast<char>(this->GetOutputFunction());
2090 //char lossFunction = static_cast<char>(this->GetLossFunction());
2091
2092 // Add attributes to the parent node
2093 xmlEngine.NewAttr(nn, 0, "NetDepth", gTools().StringFromInt(depth));
2094
2095 xmlEngine.NewAttr(nn, 0, "InputDepth", gTools().StringFromInt(inputDepth));
2096 xmlEngine.NewAttr(nn, 0, "InputHeight", gTools().StringFromInt(inputHeight));
2097 xmlEngine.NewAttr(nn, 0, "InputWidth", gTools().StringFromInt(inputWidth));
2098
2099 xmlEngine.NewAttr(nn, 0, "BatchSize", gTools().StringFromInt(batchSize));
2100 xmlEngine.NewAttr(nn, 0, "BatchDepth", gTools().StringFromInt(batchDepth));
2101 xmlEngine.NewAttr(nn, 0, "BatchHeight", gTools().StringFromInt(batchHeight));
2102 xmlEngine.NewAttr(nn, 0, "BatchWidth", gTools().StringFromInt(batchWidth));
2103
2104 xmlEngine.NewAttr(nn, 0, "LossFunction", TString(lossFunction));
2105 xmlEngine.NewAttr(nn, 0, "Initialization", TString(initialization));
2106 xmlEngine.NewAttr(nn, 0, "Regularization", TString(regularization));
2107 xmlEngine.NewAttr(nn, 0, "OutputFunction", TString(outputFunction));
2108
2109 gTools().AddAttr(nn, "WeightDecay", weightDecay);
2110
2111
2112 for (Int_t i = 0; i < depth; i++)
2113 {
2114 fNet->GetLayerAt(i) -> AddWeightsXMLTo(nn);
2115 }
2116
2117
2118}
2119
2120////////////////////////////////////////////////////////////////////////////////
2121void MethodDL::ReadWeightsFromXML(void * rootXML)
2122{
2123
2124 auto netXML = gTools().GetChild(rootXML, "Weights");
2125 if (!netXML){
2126 netXML = rootXML;
2127 }
2128
2129 size_t netDepth;
2130 gTools().ReadAttr(netXML, "NetDepth", netDepth);
2131
2132 size_t inputDepth, inputHeight, inputWidth;
2133 gTools().ReadAttr(netXML, "InputDepth", inputDepth);
2134 gTools().ReadAttr(netXML, "InputHeight", inputHeight);
2135 gTools().ReadAttr(netXML, "InputWidth", inputWidth);
2136
2137 size_t batchSize, batchDepth, batchHeight, batchWidth;
2138 gTools().ReadAttr(netXML, "BatchSize", batchSize);
2139 // use always batchsize = 1
2140 //batchSize = 1;
2141 gTools().ReadAttr(netXML, "BatchDepth", batchDepth);
2142 gTools().ReadAttr(netXML, "BatchHeight", batchHeight);
2143 gTools().ReadAttr(netXML, "BatchWidth", batchWidth);
2144
2145 char lossFunctionChar;
2146 gTools().ReadAttr(netXML, "LossFunction", lossFunctionChar);
2147 char initializationChar;
2148 gTools().ReadAttr(netXML, "Initialization", initializationChar);
2149 char regularizationChar;
2150 gTools().ReadAttr(netXML, "Regularization", regularizationChar);
2151 char outputFunctionChar;
2152 gTools().ReadAttr(netXML, "OutputFunction", outputFunctionChar);
2153 double weightDecay;
2154 gTools().ReadAttr(netXML, "WeightDecay", weightDecay);
2155
2156 // create the net
2157
2158 // DeepNetCpu_t is defined in MethodDL.h
2159 this->SetInputDepth(inputDepth);
2160 this->SetInputHeight(inputHeight);
2161 this->SetInputWidth(inputWidth);
2162 this->SetBatchDepth(batchDepth);
2163 this->SetBatchHeight(batchHeight);
2164 this->SetBatchWidth(batchWidth);
2165
2166
2167
2168 fNet = std::unique_ptr<DeepNetImpl_t>(new DeepNetImpl_t(batchSize, inputDepth, inputHeight, inputWidth, batchDepth,
2169 batchHeight, batchWidth,
2170 static_cast<ELossFunction>(lossFunctionChar),
2171 static_cast<EInitialization>(initializationChar),
2172 static_cast<ERegularization>(regularizationChar),
2173 weightDecay));
2174
2175 fOutputFunction = static_cast<EOutputFunction>(outputFunctionChar);
2176
2177
2178 //size_t previousWidth = inputWidth;
2179 auto layerXML = gTools().xmlengine().GetChild(netXML);
2180
2181 // loop on the layer and add them to the network
2182 for (size_t i = 0; i < netDepth; i++) {
2183
2184 TString layerName = gTools().xmlengine().GetNodeName(layerXML);
2185
2186 // case of dense layer
2187 if (layerName == "DenseLayer") {
2188
2189 // read width and activation function and then we can create the layer
2190 size_t width = 0;
2191 gTools().ReadAttr(layerXML, "Width", width);
2192
2193 // Read activation function.
2194 TString funcString;
2195 gTools().ReadAttr(layerXML, "ActivationFunction", funcString);
2196 EActivationFunction func = static_cast<EActivationFunction>(funcString.Atoi());
2197
2198
2199 fNet->AddDenseLayer(width, func, 0.0); // no need to pass dropout probability
2200
2201 }
2202 // Convolutional Layer
2203 else if (layerName == "ConvLayer") {
2204
2205 // read width and activation function and then we can create the layer
2206 size_t depth = 0;
2207 gTools().ReadAttr(layerXML, "Depth", depth);
2208 size_t fltHeight, fltWidth = 0;
2209 size_t strideRows, strideCols = 0;
2210 size_t padHeight, padWidth = 0;
2211 gTools().ReadAttr(layerXML, "FilterHeight", fltHeight);
2212 gTools().ReadAttr(layerXML, "FilterWidth", fltWidth);
2213 gTools().ReadAttr(layerXML, "StrideRows", strideRows);
2214 gTools().ReadAttr(layerXML, "StrideCols", strideCols);
2215 gTools().ReadAttr(layerXML, "PaddingHeight", padHeight);
2216 gTools().ReadAttr(layerXML, "PaddingWidth", padWidth);
2217
2218 // Read activation function.
2219 TString funcString;
2220 gTools().ReadAttr(layerXML, "ActivationFunction", funcString);
2221 EActivationFunction actFunction = static_cast<EActivationFunction>(funcString.Atoi());
2222
2223
2224 fNet->AddConvLayer(depth, fltHeight, fltWidth, strideRows, strideCols,
2225 padHeight, padWidth, actFunction);
2226
2227 }
2228
2229 // MaxPool Layer
2230 else if (layerName == "MaxPoolLayer") {
2231
2232 // read maxpool layer info
2233 size_t filterHeight, filterWidth = 0;
2234 size_t strideRows, strideCols = 0;
2235 gTools().ReadAttr(layerXML, "FilterHeight", filterHeight);
2236 gTools().ReadAttr(layerXML, "FilterWidth", filterWidth);
2237 gTools().ReadAttr(layerXML, "StrideRows", strideRows);
2238 gTools().ReadAttr(layerXML, "StrideCols", strideCols);
2239
2240 fNet->AddMaxPoolLayer(filterHeight, filterWidth, strideRows, strideCols);
2241 }
2242 // Reshape Layer
2243 else if (layerName == "ReshapeLayer") {
2244
2245 // read reshape layer info
2246 size_t depth, height, width = 0;
2247 gTools().ReadAttr(layerXML, "Depth", depth);
2248 gTools().ReadAttr(layerXML, "Height", height);
2249 gTools().ReadAttr(layerXML, "Width", width);
2250 int flattening = 0;
2251 gTools().ReadAttr(layerXML, "Flattening",flattening );
2252
2253 fNet->AddReshapeLayer(depth, height, width, flattening);
2254
2255 }
2256 // RNN Layer
2257 else if (layerName == "RNNLayer") {
2258
2259 // read RNN layer info
2260 size_t stateSize,inputSize, timeSteps = 0;
2261 int rememberState= 0;
2262 int returnSequence = 0;
2263 gTools().ReadAttr(layerXML, "StateSize", stateSize);
2264 gTools().ReadAttr(layerXML, "InputSize", inputSize);
2265 gTools().ReadAttr(layerXML, "TimeSteps", timeSteps);
2266 gTools().ReadAttr(layerXML, "RememberState", rememberState );
2267 gTools().ReadAttr(layerXML, "ReturnSequence", returnSequence);
2268
2269 fNet->AddBasicRNNLayer(stateSize, inputSize, timeSteps, rememberState, returnSequence);
2270
2271 }
2272 // LSTM Layer
2273 else if (layerName == "LSTMLayer") {
2274
2275 // read RNN layer info
2276 size_t stateSize,inputSize, timeSteps = 0;
2277 int rememberState, returnSequence = 0;
2278 gTools().ReadAttr(layerXML, "StateSize", stateSize);
2279 gTools().ReadAttr(layerXML, "InputSize", inputSize);
2280 gTools().ReadAttr(layerXML, "TimeSteps", timeSteps);
2281 gTools().ReadAttr(layerXML, "RememberState", rememberState );
2282 gTools().ReadAttr(layerXML, "ReturnSequence", returnSequence);
2283
2284 fNet->AddBasicLSTMLayer(stateSize, inputSize, timeSteps, rememberState, returnSequence);
2285
2286 }
2287 // GRU Layer
2288 else if (layerName == "GRULayer") {
2289
2290 // read RNN layer info
2291 size_t stateSize,inputSize, timeSteps = 0;
2292 int rememberState, returnSequence, resetGateAfter = 0;
2293 gTools().ReadAttr(layerXML, "StateSize", stateSize);
2294 gTools().ReadAttr(layerXML, "InputSize", inputSize);
2295 gTools().ReadAttr(layerXML, "TimeSteps", timeSteps);
2296 gTools().ReadAttr(layerXML, "RememberState", rememberState );
2297 gTools().ReadAttr(layerXML, "ReturnSequence", returnSequence);
2298 gTools().ReadAttr(layerXML, "ResetGateAfter", resetGateAfter);
2299
2300 if (!resetGateAfter && ArchitectureImpl_t::IsCudnn())
2301 Warning("ReadWeightsFromXML",
2302 "Cannot use a reset gate after to false with CudNN - use implementation with resetgate=true");
2303
2304 fNet->AddBasicGRULayer(stateSize, inputSize, timeSteps, rememberState, returnSequence, resetGateAfter);
2305 }
2306 // BatchNorm Layer
2307 else if (layerName == "BatchNormLayer") {
2308 // use some dammy value which will be overwrittem in BatchNormLayer::ReadWeightsFromXML
2309 fNet->AddBatchNormLayer(0., 0.0);
2310 }
2311 // read weights and biases
2312 fNet->GetLayers().back()->ReadWeightsFromXML(layerXML);
2313
2314 // read next layer
2315 layerXML = gTools().GetNextChild(layerXML);
2316 }
2317
2318 fBuildNet = false;
2319 // create now the input and output matrices
2320 //int n1 = batchHeight;
2321 //int n2 = batchWidth;
2322 // treat case where batchHeight is the batchSize in case of first Dense layers (then we need to set to fNet batch size)
2323 //if (fXInput.size() > 0) fXInput.clear();
2324 //fXInput.emplace_back(MatrixImpl_t(n1,n2));
2325 fXInput = ArchitectureImpl_t::CreateTensor(fNet->GetBatchSize(), GetInputDepth(), GetInputHeight(), GetInputWidth() );
2326 if (batchDepth == 1 && GetInputHeight() == 1 && GetInputDepth() == 1)
2327 // make here a ColumnMajor tensor
2328 fXInput = TensorImpl_t(fNet->GetBatchSize(), GetInputWidth(), TMVA::DNN::MemoryLayout::ColumnMajor);
2329 fXInputBuffer = HostBufferImpl_t( fXInput.GetSize());
2330
2331 // create pointer to output matrix used for the predictions
2332 fYHat = std::unique_ptr<MatrixImpl_t>(new MatrixImpl_t(fNet->GetBatchSize(), fNet->GetOutputWidth() ) );
2333
2334
2335}
2336
2337
2338////////////////////////////////////////////////////////////////////////////////
2339void MethodDL::ReadWeightsFromStream(std::istream & /*istr*/)
2340{
2341}
2342
2343////////////////////////////////////////////////////////////////////////////////
2344const Ranking *TMVA::MethodDL::CreateRanking()
2345{
2346 // TODO
2347 return NULL;
2348}
2349
2350////////////////////////////////////////////////////////////////////////////////
2351void MethodDL::GetHelpMessage() const
2352{
2353 // TODO
2354}
2355
2356} // namespace TMVA
#define REGISTER_METHOD(CLASS)
for example
#define e(i)
Definition RSha256.hxx:103
constexpr Bool_t kFALSE
Definition RtypesCore.h:109
double Double_t
Double 8 bytes.
Definition RtypesCore.h:74
long long Long64_t
Portable signed long integer 8 bytes.
Definition RtypesCore.h:84
constexpr Bool_t kTRUE
Definition RtypesCore.h:108
#define R__ASSERT(e)
Checks condition e and reports a fatal error if it's false.
Definition TError.h:139
void Error(const char *location, const char *msgfmt,...)
Use this function in case an error occurred.
Definition TError.cxx:208
void Warning(const char *location, const char *msgfmt,...)
Use this function in warning situations.
Definition TError.cxx:252
winID h TVirtualViewer3D TVirtualGLPainter p
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void value
Option_t Option_t width
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 Int_t Int_t Window_t TString Int_t GCValues_t GetPrimarySelectionOwner GetDisplay GetScreen GetColormap GetNativeEvent const char const char dpyName wid window const char font_name cursor keysym reg const char only_if_exist regb h Point_t winding char text const char depth char const char Int_t count const char ColorStruct_t color const char Pixmap_t Pixmap_t PictureAttributes_t attr const char char ret_data h unsigned char height h Atom_t Int_t ULong_t ULong_t unsigned char prop_list Atom_t Atom_t Atom_t Time_t type
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t height
char * Form(const char *fmt,...)
Formats a string in a circular formatting buffer.
Definition TString.cxx:2571
The Formula class.
Definition TFormula.h:89
void Print(Option_t *option="") const override
Dump this line with its attributes.
Definition TLine.cxx:280
UInt_t GetNCpu()
Definition Config.h:70
Adadelta Optimizer class.
Definition Adadelta.h:45
Adagrad Optimizer class.
Definition Adagrad.h:45
Adam Optimizer class.
Definition Adam.h:45
Generic Deep Neural Network class.
Definition DeepNet.h:73
size_t GetBatchHeight() const
Definition DeepNet.h:343
void Forward(Tensor_t &input, bool applyDropout=false)
Function that executes the entire forward pass in the network.
Definition DeepNet.h:896
std::vector< Layer_t * > & GetLayers()
Definition DeepNet.h:330
size_t GetBatchSize() const
Getters.
Definition DeepNet.h:337
size_t GetDepth() const
Definition DeepNet.h:326
TBatchNormLayer< Architecture_t > * AddBatchNormLayer(Scalar_t momentum=-1, Scalar_t epsilon=0.0001)
Function for adding a Batch Normalization layer with given parameters.
Definition DeepNet.h:825
void Backward(const Tensor_t &input, const Matrix_t &groundTruth, const Matrix_t &weights)
Function that executes the entire backward pass in the network.
Definition DeepNet.h:1033
Layer_t * GetLayerAt(size_t i)
Get the layer in the vector of layers at position i.
Definition DeepNet.h:322
void Print() const
Print the Deep Net Info.
Definition DeepNet.h:1321
TBasicGRULayer< Architecture_t > * AddBasicGRULayer(size_t stateSize, size_t inputSize, size_t timeSteps, bool rememberState=false, bool returnSequence=false, bool resetGateAfter=false)
Function for adding GRU Layer in the Deep Neural Network, with given parameters.
Definition DeepNet.h:608
Scalar_t RegularizationTerm() const
Function for computing the regularizaton term to be added to the loss function
Definition DeepNet.h:1289
TDenseLayer< Architecture_t > * AddDenseLayer(size_t width, EActivationFunction f, Scalar_t dropoutProbability=1.0)
Function for adding Dense Connected Layer in the Deep Neural Network, with a given width,...
Definition DeepNet.h:740
void Prediction(Matrix_t &predictions, EOutputFunction f) const
Prediction based on activations stored in the last layer.
Definition DeepNet.h:1303
size_t GetBatchWidth() const
Definition DeepNet.h:344
TBasicLSTMLayer< Architecture_t > * AddBasicLSTMLayer(size_t stateSize, size_t inputSize, size_t timeSteps, bool rememberState=false, bool returnSequence=false)
Function for adding LSTM Layer in the Deep Neural Network, with given parameters.
Definition DeepNet.h:567
TMaxPoolLayer< Architecture_t > * AddMaxPoolLayer(size_t frameHeight, size_t frameWidth, size_t strideRows, size_t strideCols, Scalar_t dropoutProbability=1.0)
Function for adding Pooling layer in the Deep Neural Network, with a given filter height and width,...
Definition DeepNet.h:485
Scalar_t Loss(const Matrix_t &groundTruth, const Matrix_t &weights, bool includeRegularization=true) const
Function for evaluating the loss, based on the activations stored in the last layer.
Definition DeepNet.h:1263
TConvLayer< Architecture_t > * AddConvLayer(size_t depth, size_t filterHeight, size_t filterWidth, size_t strideRows, size_t strideCols, size_t paddingHeight, size_t paddingWidth, EActivationFunction f, Scalar_t dropoutProbability=1.0)
Function for adding Convolution layer in the Deep Neural Network, with a given depth,...
Definition DeepNet.h:439
size_t GetOutputWidth() const
Definition DeepNet.h:327
TReshapeLayer< Architecture_t > * AddReshapeLayer(size_t depth, size_t height, size_t width, bool flattening)
Function for adding Reshape Layer in the Deep Neural Network, with a given height and width.
Definition DeepNet.h:773
TBasicRNNLayer< Architecture_t > * AddBasicRNNLayer(size_t stateSize, size_t inputSize, size_t timeSteps, bool rememberState=false, bool returnSequence=false, EActivationFunction f=EActivationFunction::kTanh)
Function for adding Recurrent Layer in the Deep Neural Network, with given parameters.
Definition DeepNet.h:524
void SetDropoutProbabilities(const std::vector< Double_t > &probabilities)
Definition DeepNet.h:1340
size_t GetBatchDepth() const
Definition DeepNet.h:342
Generic layer class.
Definition DenseLayer.h:59
RMSProp Optimizer class.
Definition RMSProp.h:45
Stochastic Batch Gradient Descent Optimizer class.
Definition SGD.h:46
Generic General Layer class.
virtual void Initialize()
Initialize the weights and biases according to the given initialization method.
Class that contains all the data information.
Definition DataSetInfo.h:62
void SetTarget(UInt_t itgt, Float_t value)
set the target value (dimension itgt) to value
Definition Event.cxx:367
Float_t GetTarget(UInt_t itgt) const
Definition Event.h:102
Virtual base Class for all MVA method.
Definition MethodBase.h:79
Ranking for variables in method (implementation)
Definition Ranking.h:48
Timing information for training and evaluation of MVA methods.
Definition Timer.h:58
TXMLEngine & xmlengine()
Definition Tools.h:262
void ReadAttr(void *node, const char *, T &value)
read attribute from xml
Definition Tools.h:329
void * GetChild(void *parent, const char *childname=nullptr)
get child node
Definition Tools.cxx:1125
void AddAttr(void *node, const char *, const T &value, Int_t precision=16)
add attribute to xml
Definition Tools.h:347
TString StringFromInt(Long_t i)
string tools
Definition Tools.cxx:1198
void * GetNextChild(void *prevchild, const char *childname=nullptr)
XML helpers.
Definition Tools.cxx:1137
Singleton class for Global types used by TMVA.
Definition Types.h:71
@ kTraining
Definition Types.h:143
@ kFATAL
Definition Types.h:61
void Print(Option_t *option="") const override
Dump this marker with its attributes.
Definition TMarker.cxx:324
TMatrixT.
Definition TMatrixT.h:40
An array of TObjects.
Definition TObjArray.h:31
Collectable string class.
Definition TObjString.h:28
const TString & GetString() const
Definition TObjString.h:46
Basic string class.
Definition TString.h:137
Ssiz_t Length() const
Definition TString.h:426
Int_t Atoi() const
Return integer value of string.
Definition TString.cxx:2069
TSubString Strip(EStripType s=kTrailing, char c=' ') const
Return a substring of self stripped at beginning and/or end.
Definition TString.cxx:1171
Bool_t IsFloat() const
Returns kTRUE if string contains a floating point or integer number.
Definition TString.cxx:1939
const char * Data() const
Definition TString.h:385
TString & ReplaceAll(const TString &s1, const TString &s2)
Definition TString.h:714
@ kTrailing
Definition TString.h:283
@ kBoth
Definition TString.h:283
void ToUpper()
Change string to upper case.
Definition TString.cxx:1203
TObjArray * Tokenize(const TString &delim) const
This function is used to isolate sequential tokens in a TString.
Definition TString.cxx:2345
Bool_t IsNull() const
Definition TString.h:423
static TString Format(const char *fmt,...)
Static method which formats a string using a printf style format descriptor and return a TString.
Definition TString.cxx:2460
XMLNodePointer_t NewChild(XMLNodePointer_t parent, XMLNsPointer_t ns, const char *name, const char *content=nullptr)
create new child element for parent node
XMLNodePointer_t GetChild(XMLNodePointer_t xmlnode, Bool_t realnode=kTRUE)
returns first child of xmlnode
const char * GetNodeName(XMLNodePointer_t xmlnode)
returns name of xmlnode
RVec< PromoteType< T > > abs(const RVec< T > &v)
Definition RVec.hxx:1812
const Int_t n
Definition legend1.C:16
void Print(std::ostream &os, const OptionType &opt)
EOptimizer
Enum representing the optimizer used for training.
Definition Functions.h:82
EOutputFunction
Enum that represents output functions.
Definition Functions.h:46
double weightDecay(double error, ItWeight itWeight, ItWeight itWeightEnd, double factorWeightDecay, EnumRegularization eRegularization)
compute the weight decay for regularization (L1 or L2)
auto regularization(const typename Architecture_t::Matrix_t &A, ERegularization R) -> decltype(Architecture_t::L1Regularization(A))
Evaluate the regularization functional for a given weight matrix.
Definition Functions.h:238
ERegularization
Enum representing the regularization type applied for a given layer.
Definition Functions.h:65
EActivationFunction
Enum that represents layer activation functions.
Definition Functions.h:32
ELossFunction
Enum that represents objective functions for the net, i.e.
Definition Functions.h:57
std::tuple< const std::vector< Event * > &, const DataSetInfo & > TMVAInput_t
Definition DataLoader.h:39
void GetMethodName(TString &name, TKey *mkey)
Definition tmvaglob.cxx:342
create variable transformations
Config & gConfig()
Tools & gTools()
TString fetchValueTmp(const std::map< TString, TString > &keyValueMap, TString key)
Definition MethodDL.cxx:89
MsgLogger & Endl(MsgLogger &ml)
Definition MsgLogger.h:148
Bool_t IsNaN(Double_t x)
Definition TMath.h:905
Double_t Log(Double_t x)
Returns the natural logarithm of x.
Definition TMath.h:769
std::string GetName(TCppScope_t)
All of the options that can be specified in the training string.
Definition MethodDL.h:72
std::map< TString, double > optimizerParams
Definition MethodDL.h:84
DNN::EOptimizer optimizer
Definition MethodDL.h:78
DNN::ERegularization regularization
Definition MethodDL.h:77
std::vector< Double_t > dropoutProbabilities
Definition MethodDL.h:83
TMarker m
Definition textangle.C:8
TLine l
Definition textangle.C:4
auto * t1
Definition textangle.C:20