Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
Cpu.h
Go to the documentation of this file.
1// @(#)root/tmva/tmva/dnn:$Id$
2// Author: Simon Pfreundschuh 05/07/16
3
4/*************************************************************************
5 * Copyright (C) 2016, Simon Pfreundschuh *
6 * All rights reserved. *
7 * *
8 * For the licensing terms see $ROOTSYS/LICENSE. *
9 * For the list of contributors see $ROOTSYS/README/CREDITS. *
10 *************************************************************************/
11
12 //////////////////////////////////////////////////////////////////
13 // Definition of the TCpu architecture, which provides a //
14 // multi-threaded CPU implementation of the low-level interface //
15 // networks for Cpus using BLAS and Roots TThreadExecutor //
16 //////////////////////////////////////////////////////////////////
17
18#ifndef TMVA_DNN_ARCHITECTURES_CPU
19#define TMVA_DNN_ARCHITECTURES_CPU
20
21#include "TMVA/DNN/Functions.h"
23//#include "TMVA/DNN/CNN/Descriptors.h"
29
33
34#include <vector>
35#include <string>
36
37class TRandom;
38
39namespace TMVA
40{
41namespace DNN
42{
43 //class EActivationFunction;
44 struct DummyDescriptor {};
52 struct DummyDataType {};
53
55
56/** The TCpu architecture class.
57 *
58 * Low-level interface class for multi-threaded CPU architectures. Contains as
59 * public types the declaration of the scalar, matrix and data loader types
60 * for this architecture as well as the remaining functions in the low-level
61 * interface in the form of static members.
62 */
63template<typename AReal = Float_t>
64class TCpu
65{
66private:
68public:
69 using Scalar_t = AReal;
74
81
88
89 using EmptyDescriptor_t = DummyDescriptor; // Used if a descriptor is not needed in a class
90
94
101
104
106
107 static Tensor_t CreateTensor(size_t n, size_t c, size_t h, size_t w) {
108 return Tensor_t( {c,h*w,n}, GetTensorLayout());
109 }
110 static Tensor_t CreateTensor(DeviceBuffer_t buffer, size_t n, size_t c, size_t h, size_t w) {
111 return Tensor_t( buffer, {c,h*w,n}, GetTensorLayout());
112 }
113 static Tensor_t CreateTensor(size_t b, size_t t, size_t w)
114 {
115 return Tensor_t({t, w, b}, GetTensorLayout());
116 }
117 static Tensor_t CreateTensor(DeviceBuffer_t buffer, size_t b, size_t t, size_t w)
118 {
119 return Tensor_t(buffer, {t, w, b}, GetTensorLayout());
120 }
121 // create a weight tensor/matrix vector from another tensor/weight vector using the given tensor shapes
122 // this function is used by the optimizers to store intermediate weights representations
123 static void CreateWeightTensors( std::vector<Matrix_t> & newWeights, const std::vector<Matrix_t> & weights) {
124 if (!newWeights.empty()) newWeights.clear();
125 size_t n = weights.size();
126 for (size_t i = 0; i < n; ++i)
127 newWeights.emplace_back( weights[i].GetNrows(), weights[i].GetNcols());
128 }
129
130 static bool IsCudnn() { return false; }
131 //____________________________________________________________________________
132 //
133 // Architecture Initialization
134 //____________________________________________________________________________
135
136 /** Initialize CNN data/operator descriptors. Not used at the moment.*/
137
138 static void InitializeBNormDescriptors(TDescriptors * & /*descriptors*/,
139 BNormLayer_t * /*L = nullptr*/) {}
140
141 static void InitializeConvDescriptors(TDescriptors * & /*descriptors*/,
142 ConvLayer_t * /*L = nullptr*/) {}
143 static void InitializePoolDescriptors(TDescriptors * & /*descriptors*/,
144 PoolingLayer_t * /*L = nullptr*/) {}
145 static void InitializeRNNDescriptors(TDescriptors *& /*descriptors*/, GenLayer_t * /*L*/) {}
146 static void InitializeLSTMDescriptors(TDescriptors *& /*descriptors*/, GenLayer_t * /*L*/) {}
147 static void InitializeGRUDescriptors(TDescriptors *& /*descriptors*/, GenLayer_t * /*L*/) {}
148
149 static void InitializeActivationDescriptor(ActivationDescriptor_t &/*descriptors*/, EActivationFunction /*activFunc */ , double /*coef*/ = 0.0) {}
150
151 /** Release CNN data/operator descriptors. Not used at the moment.*/
152 static void ReleaseConvDescriptors(TDescriptors * & /*descriptors*/) {}
153 static void ReleasePoolDescriptors(TDescriptors * & /*descriptors*/) {}
154 static void ReleaseBNormDescriptors(TDescriptors * & /*descriptors*/) {}
155 static void ReleaseRNNDescriptors(TDescriptors *& /*descriptors*/) {}
156
157 static void InitializeConvWorkspace(TWorkspace * & /*workspace*/,
158 TDescriptors * & /*descriptors*/,
159 const DNN::CNN::TConvParams & /*params*/,
160 ConvLayer_t * /*L = nullptr*/) {}
161 static void InitializePoolDropoutWorkspace(TWorkspace * & /*workspace*/,
162 TDescriptors * & /*descriptors*/,
163 const DNN::CNN::TConvParams & /*params*/,
164 PoolingLayer_t * /*L = nullptr*/) {}
165 static void InitializeRNNWorkspace(TWorkspace *& /*workspace*/, TDescriptors *& /*descriptors*/, GenLayer_t * /*L*/) {}
166 static void InitializeLSTMWorkspace(TWorkspace *& /*workspace*/, TDescriptors *& /*descriptors*/, GenLayer_t * /*L*/){}
167 static void InitializeGRUWorkspace(TWorkspace *& /*workspace*/, TDescriptors *& /*descriptors*/, GenLayer_t * /*L*/){}
168
169 static void FreeConvWorkspace(TWorkspace * & /*workspace*/) {} ///< Only used for certain cudnn on-device memory
170 static void FreePoolDropoutWorkspace(TWorkspace * & /*workspace*/) {}
171 static void FreeRNNWorkspace(TWorkspace *& /*workspace*/) {}
172
173 static void ReleaseDescriptor(ActivationDescriptor_t & /* activationDescr */) {}
174
175 static void InitializeRNNTensors(GenLayer_t * /*layer*/) {}
176 static void InitializeLSTMTensors(GenLayer_t * /*layer*/) {}
177 static void InitializeGRUTensors(GenLayer_t * /*layer*/) {}
178
179 //____________________________________________________________________________
180 //
181 // Propagation
182 //____________________________________________________________________________
183
184 /** @name Forward Propagation
185 * Low-level functions required for the forward propagation of activations
186 * through the network.
187 */
188 ///@{
189 /** Matrix-multiply \p input with the transpose of \p weights and
190 * write the results into \p output. */
191 static void MultiplyTranspose(Matrix_t &output, const Matrix_t &input, const Matrix_t &weights);
192
193 static void MultiplyTranspose(Tensor_t &output, const Tensor_t &input, const Matrix_t &weights) {
195 MultiplyTranspose( output_matrix, input.GetMatrix(), weights);
196 //ensor_t::MatrixToTensor(output_matrix, output); // this maybe is not needed
197 }
198
199 /** Add the vectors biases row-wise to the matrix output */
200 static void AddRowWise(Matrix_t &output,const Matrix_t &biases);
201
202 static void AddRowWise(Tensor_t &output, const Matrix_t &biases) {
205 //Tensor_t::MatrixToTensor(output_matrix, output); // this maybe is not needed
206 }
207
208 /** @name Backward Propagation (Dense Layers)
209 * Low-level functions required for the forward propagation of activations
210 * through the network.
211 */
212 ///@{
213 /** Perform the complete backward propagation step. If the provided
214 * \p activationGradientsBackward matrix is not empty, compute the
215 * gradients of the objective function with respect to the activations
216 * of the previous layer (backward direction).
217 * Also compute the weight and the bias gradients. Modifies the values
218 * in \p df and thus produces only a valid result, if it is applied the
219 * first time after the corresponding forward propagation has been per-
220 * formed. */
221 static void Backward(Tensor_t & activationGradientsBackward,
222 Matrix_t & weightGradients,
223 Matrix_t & biasGradients,
224 const Tensor_t & df,
225 const Tensor_t & activationGradients,
226 const Matrix_t & weights,
227 const Tensor_t & activationBackward);
228
229
230 /** Adds a the elements in matrix B scaled by c to the elements in
231 * the matrix A. This is required for the weight update in the gradient
232 * descent step.*/
233 static void ScaleAdd(Matrix_t & A,
234 const Matrix_t & B,
235 Scalar_t beta = 1.0);
236
237 static void Copy(Matrix_t & B,
238 const Matrix_t & A);
239
240 // copy from another type of matrix
241 template<typename AMatrix_t>
242 static void CopyDiffArch(Matrix_t & B, const AMatrix_t & A);
243
244
245 /** Above functions extended to vectors */
246 static void ScaleAdd(Tensor_t & A,
247 const Tensor_t & B,
248 Scalar_t beta = 1.0);
249
250 static void Copy(Tensor_t & A,
251 const Tensor_t & B);
252
253 // copy from another tensor
254 template<typename ATensor_t>
255 static void CopyDiffArch(Tensor_t & A,
256 const ATensor_t & B);
257
258 // copy from vector of matrices of different types
259 template<typename AMatrix_t>
260 static void CopyDiffArch(std::vector<Matrix_t> & A,
261 const std::vector<AMatrix_t> & B);
262
263 ///@}
264
265 //____________________________________________________________________________
266 //
267 // Activation Functions
268 //____________________________________________________________________________
269
270 /** @name Activation Functions
271 * For each activation function, the low-level interface contains two routines.
272 * One that applies the activation function to a matrix and one that evaluate
273 * the derivatives of the activation function at the elements of a given matrix
274 * and writes the results into the result matrix.
275 */
276 ///@{
277 /* impl using Matrix */
278 /*inline void evaluate(Matrix_t &A, EActivationFunction f)
279 {
280 Tensor_t tA(A);
281 evaluate<TCpu<AReal>>(tA,f);
282 }*/
283
285 const ActivationDescriptor_t activationDescr,
286 const double coef = 0.0, const Scalar_t alpha = 1,
287 const Scalar_t beta = 0);
288
289 /** Computes the gradient of the activation function */
290 static void ActivationFunctionBackward(Tensor_t & dX, const Tensor_t & Y,
291 const Tensor_t & dY, const Tensor_t & X,
293 const ActivationDescriptor_t activationDescr,
294 const Scalar_t alpha = 1,
295 const Scalar_t beta = 0);
296
297 static void IdentityDerivative(Tensor_t & B,
298 const Tensor_t &A);
299
300 static void Relu(Tensor_t & B);
301 static void ReluDerivative(Tensor_t & B,
302 const Tensor_t & A);
303
304 static void Sigmoid(Tensor_t & B);
305 static void SigmoidDerivative(Tensor_t & B,
306 const Tensor_t & A);
307
308 static void Tanh(Tensor_t & B);
309 static void TanhDerivative(Tensor_t & B,
310 const Tensor_t & A);
311
312 // fast tanh (only when VDT is available)
313 static void FastTanh(Tensor_t &B);
314 static void FastTanhDerivative(Tensor_t &B, const Tensor_t &A);
315
316 static void SymmetricRelu(Tensor_t & B);
317 static void SymmetricReluDerivative(Tensor_t & B,
318 const Tensor_t & A);
319
320 static void SoftSign(Tensor_t & B);
321 static void SoftSignDerivative(Tensor_t & B,
322 const Tensor_t & A);
323
324 static void Gauss(Tensor_t & B);
325 static void GaussDerivative(Tensor_t & B,
326 const Tensor_t & A);
327 ///@}
328
329 //____________________________________________________________________________
330 //
331 // Loss Functions
332 //____________________________________________________________________________
333
334 /** @name Loss Functions
335 * Loss functions compute a scalar value given the \p output of the network
336 * for a given training input and the expected network prediction \p Y that
337 * quantifies the quality of the prediction. For each function also a routing
338 * that computes the gradients (suffixed by Gradients) must be provided for
339 * the starting of the backpropagation algorithm.
340 */
341 ///@{
342
343 static Scalar_t MeanSquaredError(const Matrix_t &Y, const Matrix_t &output,
344 const Matrix_t &weights);
345 static void MeanSquaredErrorGradients(Matrix_t &dY, const Matrix_t &Y,
346 const Matrix_t &output, const Matrix_t &weights);
347
348 /** Sigmoid transformation is implicitly applied, thus \p output should
349 * hold the linear activations of the last layer in the net. */
350 static Scalar_t CrossEntropy(const Matrix_t &Y, const Matrix_t &output,
351 const Matrix_t &weights);
352
353 static void CrossEntropyGradients(Matrix_t &dY, const Matrix_t &Y,
354 const Matrix_t &output, const Matrix_t &weights);
355
356 /** Softmax transformation is implicitly applied, thus \p output should
357 * hold the linear activations of the last layer in the net. */
358 static Scalar_t SoftmaxCrossEntropy(const Matrix_t &Y, const Matrix_t &output,
359 const Matrix_t &weights);
360 static void SoftmaxCrossEntropyGradients(Matrix_t &dY, const Matrix_t &Y,
361 const Matrix_t &output, const Matrix_t &weights);
362 ///@}
363
364 //____________________________________________________________________________
365 //
366 // Output Functions
367 //____________________________________________________________________________
368
369 /** @name Output Functions
370 * Output functions transform the activations \p output of the
371 * output layer in the network to a valid prediction \p YHat for
372 * the desired usage of the network, e.g. the identity function
373 * for regression or the sigmoid transformation for two-class
374 * classification.
375 */
376 ///@{
377 static void Sigmoid(Matrix_t &YHat,
378 const Matrix_t & );
379 static void Softmax(Matrix_t &YHat,
380 const Matrix_t & );
381 ///@}
382
383 //____________________________________________________________________________
384 //
385 // Regularization
386 //____________________________________________________________________________
387
388 /** @name Regularization
389 * For each regularization type two functions are required, one named
390 * <tt>`<Type>`Regularization</tt> that evaluates the corresponding
391 * regularization functional for a given weight matrix and the
392 * <tt>Add<Type>RegularizationGradients</tt>, that adds the regularization
393 * component in the gradients to the provided matrix.
394 */
395 ///@{
396
397 static Scalar_t L1Regularization(const Matrix_t & W);
399 const Matrix_t & W,
401
402 static Scalar_t L2Regularization(const Matrix_t & W);
404 const Matrix_t & W,
406 ///@}
407
408 //____________________________________________________________________________
409 //
410 // Initialization
411 //____________________________________________________________________________
412
413 /** @name Initialization
414 * For each initialization method, one function in the low-level interface
415 * is provided. The naming scheme is <p>Initialize<Type></p> for a given
416 * initialization method Type.
417 */
418 ///@{
419
420 static void InitializeGauss(Matrix_t & A);
421 static void InitializeUniform(Matrix_t & A);
422 static void InitializeIdentity(Matrix_t & A);
423 static void InitializeZero(Matrix_t & A);
424 static void InitializeZero(Tensor_t &A);
425 static void InitializeGlorotNormal(Matrix_t & A);
426 static void InitializeGlorotUniform(Matrix_t & A);
427
428 // return static instance of random generator used for initialization
429 // if generator does not exist it is created the first time with a random seed (e.g. seed = 0)
430 static TRandom & GetRandomGenerator();
431 // set random seed for the static generator
432 // if the static generator does not exists it is created
433 static void SetRandomSeed(size_t seed);
434 ///@}
435
436 //____________________________________________________________________________
437 //
438 // Dropout
439 //____________________________________________________________________________
440
441 /** @name Dropout
442 */
443 ///@{
444
445 /** Apply dropout with activation probability \p p to the given
446 * tensor \p A and scale the result by reciprocal of \p p. */
447 static void DropoutForward(Tensor_t & A,
449 TWorkspace * workspace,
450 Scalar_t p);
451
452 static void DropoutForward(Matrix_t & A, Scalar_t p) {
453 Tensor_t tA(A);
454 DropoutForward( tA, static_cast<TDescriptors *> (nullptr), static_cast<TWorkspace *> (nullptr), p );
455 }
456
457 // Only needed for cuDNN
458 static void DropoutBackward(Tensor_t & /*A */,
459 TDescriptors * /*descriptors */,
460 TWorkspace * /*workspace*/) {}
461 ///@}
462
463 //____________________________________________________________________________
464 //
465 // Batch Normalization
466 //____________________________________________________________________________
467
468 /** @name Batch Normalization Layer Propagation
469 */
470 ///@{
471
472 /** The input from each batch are normalized during training to have zero mean and unit variance
473 * and they are then scaled by two parameter, different for each input variable:
474 * - a scale factor `\gamma` gamma
475 * - an offset `\beta` beta */
476 static void BatchNormLayerForwardTraining(int axis, const Tensor_t &x, Tensor_t &y, Matrix_t &gamma, Matrix_t &beta,
477 Matrix_t &mean, Matrix_t &, Matrix_t &iVariance, Matrix_t &runningMeans,
478 Matrix_t &runningVars, Scalar_t nTrainedBatches, Scalar_t momentum,
479 Scalar_t epsilon, const TensorDescriptor_t &bnParDescriptor);
480
481
482 /** During inference the inputs are not normalized using the batch mean but the previously computed
483 * at running mean and variance */
484 static void BatchNormLayerForwardInference(int axis, const Tensor_t &x, Matrix_t &gamma, Matrix_t &beta,
485 Tensor_t &y, const Matrix_t &runningMeans,
486 const Matrix_t &runningVars, Scalar_t epsilon,
487 const TensorDescriptor_t &);
488
489 /**
490 * */
491 static void BatchNormLayerBackward(int axis, const Tensor_t &x, const Tensor_t &dy, Tensor_t &dx,
492 Matrix_t &gamma, // Matrix_t &beta, (not needed)
493 Matrix_t &dgamma, Matrix_t &dbeta, const Matrix_t &mean, const Matrix_t &variance,
494 const Matrix_t &iVariance, Scalar_t epsilon, const TensorDescriptor_t &);
495
496 // helper function for BNorm layer
497 static Tensor_t BatchNormLayerReshapeTensor(int axis, const Tensor_t &x);
498
499 ///@}
500
501 //____________________________________________________________________________
502 //
503 // Convolutional Layer Propagation
504 //____________________________________________________________________________
505
506 /** @name Forward Propagation in Convolutional Layer
507 */
508 ///@{
509
510 /** Calculate how many neurons "fit" in the output layer, given the input as well as the layer's hyperparameters.
511 */
512 static size_t calculateDimension(size_t imgDim, size_t fltDim, size_t padding, size_t stride);
513
514 /** Transform the matrix B in local view format, suitable for
515 * convolution, and store it in matrix A */
516 static void Im2col(Matrix_t &A, const Matrix_t &B, size_t imgHeight, size_t imgWidth, size_t fltHeight,
517 size_t fltWidth, size_t strideRows, size_t strideCols, size_t zeroPaddingHeight,
518 size_t zeroPaddingWidth);
519
520 static void Im2colIndices(std::vector<int> &V, const Matrix_t &B, size_t nLocalViews, size_t imgHeight,
521 size_t imgWidth, size_t fltHeight, size_t fltWidth, size_t strideRows, size_t strideCols,
522 size_t zeroPaddingHeight, size_t zeroPaddingWidth);
523 static void Im2colFast(Matrix_t &A, const Matrix_t &B, const std::vector<int> &V);
524
525 /** Rotates the matrix \p B, which is representing a weights,
526 * and stores them in the matrix \p A. */
527 static void RotateWeights(Matrix_t &A, const Matrix_t &B, size_t filterDepth, size_t filterHeight,
528 size_t filterWidth, size_t numFilters);
529
530 /** Add the biases in the Convolutional Layer. */
531 static void AddConvBiases(Matrix_t &output, const Matrix_t &biases);
532 ///@}
533
534 /** Dummy placeholder - preparation is currently only required for the CUDA architecture. */
535 static void PrepareInternals(Tensor_t &) {}
536
537 /** Forward propagation in the Convolutional layer */
538 static void ConvLayerForward(Tensor_t &output, Tensor_t &inputActivationFunc, const Tensor_t &input,
539 const Matrix_t &weights, const Matrix_t &biases, const DNN::CNN::TConvParams &params,
540 EActivationFunction activFunc, Tensor_t & /* inputPrime */,
541 const ConvDescriptors_t & /*descriptors*/, // Empty struct for cuda architecture
542 ConvWorkspace_t & /*workspace*/); // Empty struct for cuda architecture
543 // void * cudnnWorkspace = nullptr); // Remains nullptr for cuda architecture
544
545 /** @name Backward Propagation in Convolutional Layer
546 */
547 ///@{
548
549 /** Perform the complete backward propagation step in a Convolutional Layer.
550 * If the provided \p activationGradientsBackward matrix is not empty, compute the
551 * gradients of the objective function with respect to the activations
552 * of the previous layer (backward direction).
553 * Also compute the weight and the bias gradients. Modifies the values
554 * in \p df and thus produces only a valid result, if it is applied the
555 * first time after the corresponding forward propagation has been per-
556 * formed. */
557 static void
559 Tensor_t &df, Tensor_t &activationGradients, const Matrix_t &weights,
560 const Tensor_t &activationBackward, const Tensor_t &outputTensor, EActivationFunction activFunc,
561 const ConvDescriptors_t & /*descriptors*/, ConvWorkspace_t & /*workspace*/, size_t batchSize,
562 size_t inputHeight, size_t inputWidth, size_t depth, size_t height, size_t width,
563 size_t filterDepth, size_t filterHeight, size_t filterWidth, size_t nLocalViews);
564
565 /** Utility function for calculating the activation gradients of the layer
566 * before the convolutional layer. */
567 static void CalculateConvActivationGradients(Tensor_t &activationGradientsBackward, const Tensor_t &df,
568 const Matrix_t &weights, size_t batchSize, size_t inputHeight,
569 size_t inputWidth, size_t depth, size_t height, size_t width,
570 size_t filterDepth, size_t filterHeight, size_t filterWidth);
571
572 /** Utility function for calculating the weight gradients of the convolutional
573 * layer. */
574 static void CalculateConvWeightGradients(Matrix_t &weightGradients, const Tensor_t &df,
575 const Tensor_t &activations_backward, size_t batchSize, size_t inputHeight,
576 size_t inputWidth, size_t depth, size_t height, size_t width,
577 size_t filterDepth, size_t filterHeight, size_t filterWidth,
578 size_t nLocalViews);
579
580 /** Utility function for calculating the bias gradients of the convolutional
581 * layer */
582 static void CalculateConvBiasGradients(Matrix_t &biasGradients, const Tensor_t &df, size_t batchSize, size_t depth,
583 size_t nLocalViews);
584 ///@}
585
586 //____________________________________________________________________________
587 //
588 // Max Pooling Layer Propagation
589 //____________________________________________________________________________
590 /** @name Forward Propagation in Max Pooling Layer
591 */
592 ///@{
593
594 /** Downsample the matrix \p C to the matrix \p A, using max
595 * operation, such that the winning indices are stored in matrix
596 * \p B. */
597 static void Downsample(Tensor_t &A, Tensor_t &B, const Tensor_t &C, const PoolingDescriptors_t & /*descriptors*/,
598 PoolingWorkspace_t & /*workspace*/, size_t imgHeight, size_t imgWidth, size_t fltHeight,
599 size_t fltWidth, size_t strideRows, size_t strideCols);
600
601 ///@}
602
603 /** @name Backward Propagation in Max Pooling Layer
604 */
605 ///@{
606 /** Perform the complete backward propagation step in a Pooling Layer. Based on the
607 * winning indices stored in the index matrix, it just forwards the activation
608 * gradients to the previous layer. */
609 static void MaxPoolLayerBackward(Tensor_t &activationGradientsBackward, const Tensor_t &activationGradients,
610 const Tensor_t &indexMatrix, const Tensor_t & /*inputActivation*/,
611 const Tensor_t & /*outputTensor*/, const PoolingDescriptors_t & /*descriptors*/,
612 PoolingWorkspace_t & /*workspace*/, size_t imgHeight, size_t imgWidth,
613 size_t fltHeight, size_t fltWidth, size_t strideRows, size_t strideCols,
614 size_t nLocalViews);
615
616 //// Recurrent Network Functions
617
618 /** Backward pass for Recurrent Networks */
619 static Matrix_t &RecurrentLayerBackward(Matrix_t &state_gradients_backward, // BxH
621 Matrix_t &bias_gradients,
622 Matrix_t &df, // DxH
623 const Matrix_t &state, // BxH
624 const Matrix_t &weights_input, // HxD
625 const Matrix_t &weights_state, // HxH
626 const Matrix_t &input, // BxD
627 Matrix_t &input_gradient);
628
629 // dummy RNN functions
630 static void RNNForward(const Tensor_t & /* x */, const Matrix_t & /* hx */, const Matrix_t & /* cx */,
631 const Tensor_t & /* weights */, Tensor_t & /* y */, Matrix_t & /* hy */, Matrix_t & /* cy */,
632 const RNNDescriptors_t & /* descr */, RNNWorkspace_t & /* workspace */, bool /* isTraining */)
633 {
634 }
635
636 static void RNNBackward(const Tensor_t & /* x */, const Matrix_t & /* hx */, const Matrix_t & /* cx */,
637 const Tensor_t & /* y */, const Tensor_t & /* dy */, const Matrix_t & /* dhy */,
638 const Matrix_t & /* dcy */, const Tensor_t & /* weights */, Tensor_t & /* dx */,
639 Matrix_t & /* dhx */, Matrix_t & /* dcx */, Tensor_t & /* dw */,
640 const RNNDescriptors_t & /* desc */, RNNWorkspace_t & /* workspace */)
641 {
642 }
643
644 /** Backward pass for LSTM Network */
665 const TCpuMatrix<Scalar_t> & fInput,
668 const TCpuMatrix<Scalar_t> & fOutput,
681
682
683 /** Backward pass for GRU Network */
698 const TCpuMatrix<Scalar_t> & fReset,
699 const TCpuMatrix<Scalar_t> & fUpdate,
709 bool resetGateAfter);
710
711
712 ///@}
713
714 //____________________________________________________________________________
715 //
716 // Reshape Layer Propagation
717 //____________________________________________________________________________
718 /** @name Forward and Backward Propagation in Reshape Layer
719 */
720 ///@{
721
722 /** Transform the matrix \p B to a matrix with different dimensions \p A */
723 static void Reshape(Matrix_t &A, const Matrix_t &B);
724
725 /** Flattens the tensor \p B, such that each matrix, is stretched in
726 * one row, resulting with a matrix \p A. */
727 static void Flatten(Tensor_t &A, const Tensor_t &B); // size_t size, size_t nRows, size_t nCols);
728
729 /** Transforms each row of \p B to a matrix and stores it in the
730 * tensor \p B. */
731 static void Deflatten(Tensor_t &A, const Tensor_t &B); // size_t index, size_t nRows,size_t nCols);
732
733 /** Rearrage data according to time fill B x T x D out with T x B x D matrix in*/
734 static void Rearrange(Tensor_t &out, const Tensor_t &in);
735
736
737 ///@}
738
739 //____________________________________________________________________________
740 //
741 // Additional Arithmetic Functions
742 //____________________________________________________________________________
743
744 /** @name Additional Arithmetic Functions
745 *
746 * Additional arithmetic on CUDA matrices used to implement the low-level
747 * interface.
748 */
749 ///@{
750
751 /** Standard multiplication of two matrices \p A and \p B with the result being
752 * written into C.
753 */
754 static void Multiply(Matrix_t &C, const Matrix_t &A, const Matrix_t &B);
755 /** Matrix multiplication of two matrices \p A and \p B^T (transposed) with the
756 * result being written into C.
757 */
758 static void TransposeMultiply(Matrix_t &output, const Matrix_t &input, const Matrix_t &Weights, Scalar_t alpha = 1.0,
759 Scalar_t beta = 0.);
760 /** In-place Hadamard (element-wise) product of matrices \p A and \p B
761 * with the result being written into \p A.
762 */
763 static void Hadamard(Tensor_t &A, const Tensor_t &B);
764 static void Hadamard(Matrix_t &A, const Matrix_t &B);
765 // {
766 // Tensor_t tA(A);
767 // Hadamard( tA, Tensor_t(B));
768 // }
769
770 /** Sum columns of (m x n) matrix \p A and write the results into the first
771 * m elements in \p A.
772 */
773 static void SumColumns(Matrix_t &B, const Matrix_t &A, Scalar_t alpha = 1.0, Scalar_t beta = 0.);
774
775 /** Compute the sum of all elements in \p A */
776 static Scalar_t Sum(const Matrix_t &A);
777
778 /** Check two matrices for equality, taking floating point arithmetic errors into account. */
779 static bool AlmostEquals(const Matrix_t &A, const Matrix_t &B, double epsilon = 0.1);
780
781 /** Add the constant \p beta to all the elements of matrix \p A and write the
782 * result into \p A.
783 */
784 static void ConstAdd(Matrix_t &A, Scalar_t beta);
785
786 /** Multiply the constant \p beta to all the elements of matrix \p A and write the
787 * result into \p A.
788 */
789 static void ConstMult(Matrix_t &A, Scalar_t beta);
790
791 /** Reciprocal each element of the matrix \p A and write the result into
792 * \p A
793 */
794 static void ReciprocalElementWise(Matrix_t &A);
795
796 /** Square each element of the matrix \p A and write the result into
797 * \p A
798 */
799 static void SquareElementWise(Matrix_t &A);
800
801 /** Square root each element of the matrix \p A and write the result into
802 * \p A
803 */
804 static void SqrtElementWise(Matrix_t &A);
805
806 // optimizer functions
807 static void AdamUpdate(Matrix_t &A, const Matrix_t &M, const Matrix_t &V, Scalar_t alpha, Scalar_t eps);
808 static void AdamUpdateFirstMom(Matrix_t &A, const Matrix_t &B, Scalar_t beta);
809 static void AdamUpdateSecondMom(Matrix_t &A, const Matrix_t &B, Scalar_t beta);
810
811 // printing of tensor
812 static void PrintTensor(const Tensor_t &A, const std::string name = "Cpu-tensor", bool truncate = false);
813
814};
815
816//____________________________________________________________________________
817template <typename AReal>
818template <typename AMatrix_t>
820 const AMatrix_t &A)
821{
822 // copy from another architecture using the reference one
823 // this is not very efficient since creates temporary objects
824 TMatrixT<AReal> tmp = A; // this works also if A is a tensor
825 Copy(B, TCpuMatrix<AReal>(tmp) );
826}
827
828//____________________________________________________________________________
829template <typename AReal>
830template <typename ATensor_t>
832 const ATensor_t &A)
833{
834
835 R__ASSERT(A.GetSize() == B.GetSize());
836 // suppose A is of (B,D,H.W) and we want to convert to B,HW,D or (D,HW,B) in ColumnMajor format
837 for (size_t i = 0; i < A.GetFirstSize(); ++i) {
838 TMatrixT<AReal> tmpIn = A.At(i); // this convert tensor (B,D,H,W) in (D,H,W)i -> (D,HW)i
839
840 TCpuMatrix<AReal> tmpOut = B.At(i).GetMatrix(); // matrix (D,HW)
842 }
843
844 // ATensor_t tmpIn = A.Reshape({A.GetNrows(), A.GetNcols()});
845 // auto tmpOut = B.Reshape({A.GetNrows(), A.GetNcols()});
846 // Matrix_t mOut = tmpOut.GetMatrix();
847 // CopyDiffArch(mOut, tmpIn.GetMatrix());
848}
849
850// Implementation using vector of matrices for the weights
851template <typename AReal>
852template <typename AMatrix_t>
853void TCpu<AReal>::CopyDiffArch(std::vector<TCpuMatrix<AReal>> &A, const std::vector<AMatrix_t> &B)
854{
855 for (size_t i = 0; i < A.size(); ++i) {
856 CopyDiffArch(A[i], B[i]);
857 }
858}
859
860template <typename AReal>
861void TCpu<AReal>::PrintTensor(const typename TCpu<AReal>::Tensor_t & A, const std::string name, bool truncate )
862{
863 std::cout << name << " size = " << A.GetSize() << " shape = { ";
864 auto shape = A.GetShape();
865 for (size_t k = 0; k < shape.size()-1; ++k)
866 std::cout << shape[k] << " , ";
867 std::cout << shape.back() << " } ";
868
869 // print elements
870 // need to find way to nice printing all elements
871 std::cout << " tensor count " << A.GetBufferUseCount() << std::endl;
872 if (A.GetShape().size() == 2 ) {
873 for (size_t i = 0; i < A.GetShape()[0]; ++i) {
874 std::cout << "{ ";
875 size_t n = A.GetShape()[1];
876 if (truncate) n = std::min(n,size_t(10));
877 for (size_t j = 0; j < n; ++j) {
878 std::cout << A(i,j) << " ";
879 }
880 if (truncate && n < A.GetShape()[1]) std::cout << " ...... ";
881 std::cout << " } " << std::endl;
882 }
883 } else if (A.GetShape().size() == 3 ) {
884 for (size_t i = 0; i < A.GetFirstSize(); ++i) {
885 std::cout << "{ ";
886 for (size_t j = 0; j < A.GetHSize(); ++j) {
887 std::cout << "{ ";
888 size_t n = A.GetWSize();
889 if (truncate) n = std::min(n,size_t(10));
890 for (size_t k = 0; k < n; ++k) {
891 std::cout << A(i,j,k) << " ";
892 }
893 if (truncate && n < A.GetWSize()) std::cout << " ...... ";
894 std::cout << " } " << std::endl;
895 }
896 std::cout << " } " << std::endl;
897 }
898 }
899 else {
900 for (size_t l = 0; l < A.GetSize(); ++l) {
901 std::cout << A.GetData()[l] << " ";
902 }
903 std::cout << "\n";
904 }
905}
906
907
908
909
910} // namespace DNN
911} // namespace TMVA
912
913#endif
#define b(i)
Definition RSha256.hxx:100
#define c(i)
Definition RSha256.hxx:101
#define h(i)
Definition RSha256.hxx:106
#define X(type, name)
ROOT::Detail::TRangeCast< T, true > TRangeDynCast
TRangeDynCast is an adapter class that allows the typed iteration through a TCollection.
#define R__ASSERT(e)
Checks condition e and reports a fatal error if it's false.
Definition TError.h:130
winID h TVirtualViewer3D TVirtualGLPainter p
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void input
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 height
char name[80]
Definition TGX11.cxx:142
Generic Max Pooling Layer class.
The TCpuMatrix class.
Definition CpuMatrix.h:86
size_t GetBufferUseCount() const
Definition CpuTensor.h:397
size_t GetWSize() const
Definition CpuTensor.h:274
std::size_t GetSize() const
Definition CpuTensor.h:204
const Shape_t & GetShape() const
Definition CpuTensor.h:205
TCpuMatrix< AFloat > GetMatrix() const
Definition CpuTensor.h:294
size_t GetFirstSize() const
Definition CpuTensor.h:252
size_t GetHSize() const
Definition CpuTensor.h:265
The TCpu architecture class.
Definition Cpu.h:65
static void CalculateConvBiasGradients(Matrix_t &biasGradients, const Tensor_t &df, size_t batchSize, size_t depth, size_t nLocalViews)
Utility function for calculating the bias gradients of the convolutional layer.
static void Deflatten(Tensor_t &A, const Tensor_t &B)
Transforms each row of B to a matrix and stores it in the tensor B.
static void FastTanh(Tensor_t &B)
static void TransposeMultiply(Matrix_t &output, const Matrix_t &input, const Matrix_t &Weights, Scalar_t alpha=1.0, Scalar_t beta=0.)
Matrix multiplication of two matrices A and B^T (transposed) with the result being written into C.
static TRandom * fgRandomGen
Definition Cpu.h:67
static Tensor_t CreateTensor(DeviceBuffer_t buffer, size_t n, size_t c, size_t h, size_t w)
Definition Cpu.h:110
CNN::TCNNWorkspace< PoolingLayer_t > PoolingWorkspace_t
Definition Cpu.h:100
static Scalar_t L1Regularization(const Matrix_t &W)
static void MaxPoolLayerBackward(Tensor_t &activationGradientsBackward, const Tensor_t &activationGradients, const Tensor_t &indexMatrix, const Tensor_t &, const Tensor_t &, const PoolingDescriptors_t &, PoolingWorkspace_t &, size_t imgHeight, size_t imgWidth, size_t fltHeight, size_t fltWidth, size_t strideRows, size_t strideCols, size_t nLocalViews)
Perform the complete backward propagation step in a Pooling Layer.
static void ScaleAdd(Matrix_t &A, const Matrix_t &B, Scalar_t beta=1.0)
Adds a the elements in matrix B scaled by c to the elements in the matrix A.
static void AddL1RegularizationGradients(Matrix_t &A, const Matrix_t &W, Scalar_t weightDecay)
static void InitializeLSTMTensors(GenLayer_t *)
Definition Cpu.h:176
static void AddRowWise(Tensor_t &output, const Matrix_t &biases)
Definition Cpu.h:202
static void ConstAdd(Matrix_t &A, Scalar_t beta)
Add the constant beta to all the elements of matrix A and write the result into A.
DummyDescriptor TensorDescriptor_t
Definition Cpu.h:80
CNN::TCNNDescriptors< PoolingLayer_t > PoolingDescriptors_t
Definition Cpu.h:99
static void SumColumns(Matrix_t &B, const Matrix_t &A, Scalar_t alpha=1.0, Scalar_t beta=0.)
Sum columns of (m x n) matrix A and write the results into the first m elements in A.
static void Sigmoid(Tensor_t &B)
static void ConvLayerForward(Tensor_t &output, Tensor_t &inputActivationFunc, const Tensor_t &input, const Matrix_t &weights, const Matrix_t &biases, const DNN::CNN::TConvParams &params, EActivationFunction activFunc, Tensor_t &, const ConvDescriptors_t &, ConvWorkspace_t &)
Forward propagation in the Convolutional layer.
static Tensor_t CreateTensor(DeviceBuffer_t buffer, size_t b, size_t t, size_t w)
Definition Cpu.h:117
static void DropoutBackward(Tensor_t &, TDescriptors *, TWorkspace *)
Definition Cpu.h:458
static Scalar_t Sum(const Matrix_t &A)
Compute the sum of all elements in A.
static void InitializeLSTMWorkspace(TWorkspace *&, TDescriptors *&, GenLayer_t *)
Definition Cpu.h:166
CNN::TCNNWorkspace< ConvLayer_t > ConvWorkspace_t
Definition Cpu.h:97
static void Sigmoid(Matrix_t &YHat, const Matrix_t &)
CNN::TCNNDescriptors< ConvLayer_t > ConvDescriptors_t
Definition Cpu.h:96
TCpuTensor< AReal > Tensor_t
Definition Cpu.h:70
static void SymmetricReluDerivative(Tensor_t &B, const Tensor_t &A)
static void InitializeBNormDescriptors(TDescriptors *&, BNormLayer_t *)
Initialize CNN data/operator descriptors.
Definition Cpu.h:138
static bool AlmostEquals(const Matrix_t &A, const Matrix_t &B, double epsilon=0.1)
Check two matrices for equality, taking floating point arithmetic errors into account.
static void Hadamard(Tensor_t &A, const Tensor_t &B)
In-place Hadamard (element-wise) product of matrices A and B with the result being written into A.
static void InitializeIdentity(Matrix_t &A)
static void ReleasePoolDescriptors(TDescriptors *&)
Definition Cpu.h:153
static void InitializePoolDropoutWorkspace(TWorkspace *&, TDescriptors *&, const DNN::CNN::TConvParams &, PoolingLayer_t *)
Definition Cpu.h:161
static void Im2colFast(Matrix_t &A, const Matrix_t &B, const std::vector< int > &V)
static TMVA::DNN::MemoryLayout GetTensorLayout()
Definition Cpu.h:105
static void SqrtElementWise(Matrix_t &A)
Square root each element of the matrix A and write the result into A.
static void AddRowWise(Matrix_t &output, const Matrix_t &biases)
Add the vectors biases row-wise to the matrix output.
static void SoftmaxCrossEntropyGradients(Matrix_t &dY, const Matrix_t &Y, const Matrix_t &output, const Matrix_t &weights)
static void InitializeGRUDescriptors(TDescriptors *&, GenLayer_t *)
Definition Cpu.h:147
static void SymmetricRelu(Tensor_t &B)
static void PrintTensor(const Tensor_t &A, const std::string name="Cpu-tensor", bool truncate=false)
Definition Cpu.h:861
static TRandom & GetRandomGenerator()
static void MultiplyTranspose(Tensor_t &output, const Tensor_t &input, const Matrix_t &weights)
Definition Cpu.h:193
static void DropoutForward(Tensor_t &A, TDescriptors *descriptors, TWorkspace *workspace, Scalar_t p)
Apply dropout with activation probability p to the given tensor A and scale the result by reciprocal ...
static void FreePoolDropoutWorkspace(TWorkspace *&)
Definition Cpu.h:170
static Tensor_t CreateTensor(size_t b, size_t t, size_t w)
Definition Cpu.h:113
static void Softmax(Matrix_t &YHat, const Matrix_t &)
static void CalculateConvActivationGradients(Tensor_t &activationGradientsBackward, const Tensor_t &df, const Matrix_t &weights, size_t batchSize, size_t inputHeight, size_t inputWidth, size_t depth, size_t height, size_t width, size_t filterDepth, size_t filterHeight, size_t filterWidth)
Utility function for calculating the activation gradients of the layer before the convolutional layer...
static void TanhDerivative(Tensor_t &B, const Tensor_t &A)
static void InitializeGRUWorkspace(TWorkspace *&, TDescriptors *&, GenLayer_t *)
Definition Cpu.h:167
static void BatchNormLayerForwardTraining(int axis, const Tensor_t &x, Tensor_t &y, Matrix_t &gamma, Matrix_t &beta, Matrix_t &mean, Matrix_t &, Matrix_t &iVariance, Matrix_t &runningMeans, Matrix_t &runningVars, Scalar_t nTrainedBatches, Scalar_t momentum, Scalar_t epsilon, const TensorDescriptor_t &bnParDescriptor)
The input from each batch are normalized during training to have zero mean and unit variance and they...
static void Multiply(Matrix_t &C, const Matrix_t &A, const Matrix_t &B)
Standard multiplication of two matrices A and B with the result being written into C.
static void Backward(Tensor_t &activationGradientsBackward, Matrix_t &weightGradients, Matrix_t &biasGradients, const Tensor_t &df, const Tensor_t &activationGradients, const Matrix_t &weights, const Tensor_t &activationBackward)
Perform the complete backward propagation step.
static void InitializeUniform(Matrix_t &A)
static void ActivationFunctionForward(Tensor_t &X, EActivationFunction activFunct, const ActivationDescriptor_t activationDescr, const double coef=0.0, const Scalar_t alpha=1, const Scalar_t beta=0)
static void SoftSignDerivative(Tensor_t &B, const Tensor_t &A)
static void AdamUpdateSecondMom(Matrix_t &A, const Matrix_t &B, Scalar_t beta)
static void Copy(Matrix_t &B, const Matrix_t &A)
static void ReleaseBNormDescriptors(TDescriptors *&)
Definition Cpu.h:154
static void SetRandomSeed(size_t seed)
static void FreeConvWorkspace(TWorkspace *&)
Only used for certain cudnn on-device memory.
Definition Cpu.h:169
static Matrix_t & LSTMLayerBackward(TCpuMatrix< Scalar_t > &state_gradients_backward, TCpuMatrix< Scalar_t > &cell_gradients_backward, TCpuMatrix< Scalar_t > &input_weight_gradients, TCpuMatrix< Scalar_t > &forget_weight_gradients, TCpuMatrix< Scalar_t > &candidate_weight_gradients, TCpuMatrix< Scalar_t > &output_weight_gradients, TCpuMatrix< Scalar_t > &input_state_weight_gradients, TCpuMatrix< Scalar_t > &forget_state_weight_gradients, TCpuMatrix< Scalar_t > &candidate_state_weight_gradients, TCpuMatrix< Scalar_t > &output_state_weight_gradients, TCpuMatrix< Scalar_t > &input_bias_gradients, TCpuMatrix< Scalar_t > &forget_bias_gradients, TCpuMatrix< Scalar_t > &candidate_bias_gradients, TCpuMatrix< Scalar_t > &output_bias_gradients, TCpuMatrix< Scalar_t > &di, TCpuMatrix< Scalar_t > &df, TCpuMatrix< Scalar_t > &dc, TCpuMatrix< Scalar_t > &dout, const TCpuMatrix< Scalar_t > &precStateActivations, const TCpuMatrix< Scalar_t > &precCellActivations, const TCpuMatrix< Scalar_t > &fInput, const TCpuMatrix< Scalar_t > &fForget, const TCpuMatrix< Scalar_t > &fCandidate, const TCpuMatrix< Scalar_t > &fOutput, const TCpuMatrix< Scalar_t > &weights_input, const TCpuMatrix< Scalar_t > &weights_forget, const TCpuMatrix< Scalar_t > &weights_candidate, const TCpuMatrix< Scalar_t > &weights_output, const TCpuMatrix< Scalar_t > &weights_input_state, const TCpuMatrix< Scalar_t > &weights_forget_state, const TCpuMatrix< Scalar_t > &weights_candidate_state, const TCpuMatrix< Scalar_t > &weights_output_state, const TCpuMatrix< Scalar_t > &input, TCpuMatrix< Scalar_t > &input_gradient, TCpuMatrix< Scalar_t > &cell_gradient, TCpuMatrix< Scalar_t > &cell_tanh)
Backward pass for LSTM Network.
static Scalar_t L2Regularization(const Matrix_t &W)
static void CreateWeightTensors(std::vector< Matrix_t > &newWeights, const std::vector< Matrix_t > &weights)
Definition Cpu.h:123
static void AddL2RegularizationGradients(Matrix_t &A, const Matrix_t &W, Scalar_t weightDecay)
static void InitializeGauss(Matrix_t &A)
static void Reshape(Matrix_t &A, const Matrix_t &B)
Transform the matrix B to a matrix with different dimensions A.
static void IdentityDerivative(Tensor_t &B, const Tensor_t &A)
static Matrix_t & RecurrentLayerBackward(Matrix_t &state_gradients_backward, Matrix_t &input_weight_gradients, Matrix_t &state_weight_gradients, Matrix_t &bias_gradients, Matrix_t &df, const Matrix_t &state, const Matrix_t &weights_input, const Matrix_t &weights_state, const Matrix_t &input, Matrix_t &input_gradient)
Backward pass for Recurrent Networks.
static void Rearrange(Tensor_t &out, const Tensor_t &in)
Rearrage data according to time fill B x T x D out with T x B x D matrix in.
static void MultiplyTranspose(Matrix_t &output, const Matrix_t &input, const Matrix_t &weights)
Matrix-multiply input with the transpose of weights and write the results into output.
static void CrossEntropyGradients(Matrix_t &dY, const Matrix_t &Y, const Matrix_t &output, const Matrix_t &weights)
static void InitializeGRUTensors(GenLayer_t *)
Definition Cpu.h:177
static void InitializeRNNDescriptors(TDescriptors *&, GenLayer_t *)
Definition Cpu.h:145
static Matrix_t & GRULayerBackward(TCpuMatrix< Scalar_t > &state_gradients_backward, TCpuMatrix< Scalar_t > &reset_weight_gradients, TCpuMatrix< Scalar_t > &update_weight_gradients, TCpuMatrix< Scalar_t > &candidate_weight_gradients, TCpuMatrix< Scalar_t > &reset_state_weight_gradients, TCpuMatrix< Scalar_t > &update_state_weight_gradients, TCpuMatrix< Scalar_t > &candidate_state_weight_gradients, TCpuMatrix< Scalar_t > &reset_bias_gradients, TCpuMatrix< Scalar_t > &update_bias_gradients, TCpuMatrix< Scalar_t > &candidate_bias_gradients, TCpuMatrix< Scalar_t > &dr, TCpuMatrix< Scalar_t > &du, TCpuMatrix< Scalar_t > &dc, const TCpuMatrix< Scalar_t > &precStateActivations, const TCpuMatrix< Scalar_t > &fReset, const TCpuMatrix< Scalar_t > &fUpdate, const TCpuMatrix< Scalar_t > &fCandidate, const TCpuMatrix< Scalar_t > &weights_reset, const TCpuMatrix< Scalar_t > &weights_update, const TCpuMatrix< Scalar_t > &weights_candidate, const TCpuMatrix< Scalar_t > &weights_reset_state, const TCpuMatrix< Scalar_t > &weights_update_state, const TCpuMatrix< Scalar_t > &weights_candidate_state, const TCpuMatrix< Scalar_t > &input, TCpuMatrix< Scalar_t > &input_gradient, bool resetGateAfter)
Backward pass for GRU Network.
static void RNNBackward(const Tensor_t &, const Matrix_t &, const Matrix_t &, const Tensor_t &, const Tensor_t &, const Matrix_t &, const Matrix_t &, const Tensor_t &, Tensor_t &, Matrix_t &, Matrix_t &, Tensor_t &, const RNNDescriptors_t &, RNNWorkspace_t &)
Definition Cpu.h:636
static void CalculateConvWeightGradients(Matrix_t &weightGradients, const Tensor_t &df, const Tensor_t &activations_backward, size_t batchSize, size_t inputHeight, size_t inputWidth, size_t depth, size_t height, size_t width, size_t filterDepth, size_t filterHeight, size_t filterWidth, size_t nLocalViews)
Utility function for calculating the weight gradients of the convolutional layer.
static size_t calculateDimension(size_t imgDim, size_t fltDim, size_t padding, size_t stride)
Calculate how many neurons "fit" in the output layer, given the input as well as the layer's hyperpar...
static void BatchNormLayerBackward(int axis, const Tensor_t &x, const Tensor_t &dy, Tensor_t &dx, Matrix_t &gamma, Matrix_t &dgamma, Matrix_t &dbeta, const Matrix_t &mean, const Matrix_t &variance, const Matrix_t &iVariance, Scalar_t epsilon, const TensorDescriptor_t &)
static void InitializeConvWorkspace(TWorkspace *&, TDescriptors *&, const DNN::CNN::TConvParams &, ConvLayer_t *)
Definition Cpu.h:157
static void ConvLayerBackward(Tensor_t &activationGradientsBackward, Matrix_t &weightGradients, Matrix_t &biasGradients, Tensor_t &df, Tensor_t &activationGradients, const Matrix_t &weights, const Tensor_t &activationBackward, const Tensor_t &outputTensor, EActivationFunction activFunc, const ConvDescriptors_t &, ConvWorkspace_t &, size_t batchSize, size_t inputHeight, size_t inputWidth, size_t depth, size_t height, size_t width, size_t filterDepth, size_t filterHeight, size_t filterWidth, size_t nLocalViews)
Perform the complete backward propagation step in a Convolutional Layer.
static void InitializePoolDescriptors(TDescriptors *&, PoolingLayer_t *)
Definition Cpu.h:143
static void InitializeZero(Matrix_t &A)
static Tensor_t BatchNormLayerReshapeTensor(int axis, const Tensor_t &x)
static void PrepareInternals(Tensor_t &)
Dummy placeholder - preparation is currently only required for the CUDA architecture.
Definition Cpu.h:535
static void MeanSquaredErrorGradients(Matrix_t &dY, const Matrix_t &Y, const Matrix_t &output, const Matrix_t &weights)
static Scalar_t MeanSquaredError(const Matrix_t &Y, const Matrix_t &output, const Matrix_t &weights)
static void InitializeGlorotUniform(Matrix_t &A)
Sample from a uniform distribution in range [ -lim,+lim] where lim = sqrt(6/N_in+N_out).
static void Relu(Tensor_t &B)
static void ActivationFunctionBackward(Tensor_t &dX, const Tensor_t &Y, const Tensor_t &dY, const Tensor_t &X, EActivationFunction activFunct, const ActivationDescriptor_t activationDescr, const Scalar_t alpha=1, const Scalar_t beta=0)
Computes the gradient of the activation function.
static void SquareElementWise(Matrix_t &A)
Square each element of the matrix A and write the result into A.
static void Im2colIndices(std::vector< int > &V, const Matrix_t &B, size_t nLocalViews, size_t imgHeight, size_t imgWidth, size_t fltHeight, size_t fltWidth, size_t strideRows, size_t strideCols, size_t zeroPaddingHeight, size_t zeroPaddingWidth)
static void Flatten(Tensor_t &A, const Tensor_t &B)
Flattens the tensor B, such that each matrix, is stretched in one row, resulting with a matrix A.
static void AddConvBiases(Matrix_t &output, const Matrix_t &biases)
Add the biases in the Convolutional Layer.
static Scalar_t CrossEntropy(const Matrix_t &Y, const Matrix_t &output, const Matrix_t &weights)
Sigmoid transformation is implicitly applied, thus output should hold the linear activations of the l...
static void InitializeRNNTensors(GenLayer_t *)
Definition Cpu.h:175
static void Im2col(Matrix_t &A, const Matrix_t &B, size_t imgHeight, size_t imgWidth, size_t fltHeight, size_t fltWidth, size_t strideRows, size_t strideCols, size_t zeroPaddingHeight, size_t zeroPaddingWidth)
Transform the matrix B in local view format, suitable for convolution, and store it in matrix A.
static void ReleaseConvDescriptors(TDescriptors *&)
Release CNN data/operator descriptors.
Definition Cpu.h:152
static void InitializeRNNWorkspace(TWorkspace *&, TDescriptors *&, GenLayer_t *)
Definition Cpu.h:165
static Tensor_t CreateTensor(size_t n, size_t c, size_t h, size_t w)
Definition Cpu.h:107
static void InitializeGlorotNormal(Matrix_t &A)
Truncated normal initialization (Glorot, called also Xavier normal) The values are sample with a norm...
static void InitializeLSTMDescriptors(TDescriptors *&, GenLayer_t *)
Definition Cpu.h:146
static void FreeRNNWorkspace(TWorkspace *&)
Definition Cpu.h:171
static void GaussDerivative(Tensor_t &B, const Tensor_t &A)
static void BatchNormLayerForwardInference(int axis, const Tensor_t &x, Matrix_t &gamma, Matrix_t &beta, Tensor_t &y, const Matrix_t &runningMeans, const Matrix_t &runningVars, Scalar_t epsilon, const TensorDescriptor_t &)
During inference the inputs are not normalized using the batch mean but the previously computed at ru...
static void AdamUpdateFirstMom(Matrix_t &A, const Matrix_t &B, Scalar_t beta)
static void DropoutForward(Matrix_t &A, Scalar_t p)
Definition Cpu.h:452
static void Downsample(Tensor_t &A, Tensor_t &B, const Tensor_t &C, const PoolingDescriptors_t &, PoolingWorkspace_t &, size_t imgHeight, size_t imgWidth, size_t fltHeight, size_t fltWidth, size_t strideRows, size_t strideCols)
Downsample the matrix C to the matrix A, using max operation, such that the winning indices are store...
static void InitializeConvDescriptors(TDescriptors *&, ConvLayer_t *)
Definition Cpu.h:141
static bool IsCudnn()
Definition Cpu.h:130
static void ConstMult(Matrix_t &A, Scalar_t beta)
Multiply the constant beta to all the elements of matrix A and write the result into A.
static void SigmoidDerivative(Tensor_t &B, const Tensor_t &A)
static void RNNForward(const Tensor_t &, const Matrix_t &, const Matrix_t &, const Tensor_t &, Tensor_t &, Matrix_t &, Matrix_t &, const RNNDescriptors_t &, RNNWorkspace_t &, bool)
Definition Cpu.h:630
static void CopyDiffArch(Matrix_t &B, const AMatrix_t &A)
Definition Cpu.h:819
static Scalar_t SoftmaxCrossEntropy(const Matrix_t &Y, const Matrix_t &output, const Matrix_t &weights)
Softmax transformation is implicitly applied, thus output should hold the linear activations of the l...
static void InitializeZero(Tensor_t &A)
static void FastTanhDerivative(Tensor_t &B, const Tensor_t &A)
static void InitializeActivationDescriptor(ActivationDescriptor_t &, EActivationFunction, double=0.0)
Definition Cpu.h:149
static void ReleaseDescriptor(ActivationDescriptor_t &)
Definition Cpu.h:173
static void ReleaseRNNDescriptors(TDescriptors *&)
Definition Cpu.h:155
static void RotateWeights(Matrix_t &A, const Matrix_t &B, size_t filterDepth, size_t filterHeight, size_t filterWidth, size_t numFilters)
Rotates the matrix B, which is representing a weights, and stores them in the matrix A.
static void ReluDerivative(Tensor_t &B, const Tensor_t &A)
static void ReciprocalElementWise(Matrix_t &A)
Reciprocal each element of the matrix A and write the result into A.
static void AdamUpdate(Matrix_t &A, const Matrix_t &M, const Matrix_t &V, Scalar_t alpha, Scalar_t eps)
Adam updates.
This is the base class for the ROOT Random number generators.
Definition TRandom.h:28
Double_t y[n]
Definition legend1.C:17
Double_t x[n]
Definition legend1.C:17
const Int_t n
Definition legend1.C:16
std::shared_ptr< std::function< double(double)> > Tanh
Definition NeuralNet.cxx:29
double weightDecay(double error, ItWeight itWeight, ItWeight itWeightEnd, double factorWeightDecay, EnumRegularization eRegularization)
compute the weight decay for regularization (L1 or L2)
MemoryLayout
Memory layout type (row- or column-major storage of the tensor elements)
Definition CpuTensor.h:37
EActivationFunction
Enum that represents layer activation functions.
Definition Functions.h:32
std::shared_ptr< std::function< double(double)> > Gauss
Definition NeuralNet.cxx:12
std::shared_ptr< std::function< double(double)> > SoftSign
Definition NeuralNet.cxx:32
create variable transformations
TLine l
Definition textangle.C:4