forked from tensorflow/tensorflow
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdnn.h
More file actions
1610 lines (1478 loc) · 67.6 KB
/
Copy pathdnn.h
File metadata and controls
1610 lines (1478 loc) · 67.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
// Neural Net operation support for StreamExecutor instances.
//
// This is an abstract interface for a platform to optionally support common
// neural net operations; it accommodates implementations such as the cudnn
// library operations.
#ifndef TENSORFLOW_STREAM_EXECUTOR_DNN_H_
#define TENSORFLOW_STREAM_EXECUTOR_DNN_H_
#include <functional>
#include <limits>
#include <memory>
#include "tensorflow/stream_executor/device_memory.h"
#include "tensorflow/stream_executor/lib/array_slice.h"
#include "tensorflow/stream_executor/lib/status.h"
#include "tensorflow/stream_executor/lib/statusor.h"
#include "tensorflow/stream_executor/platform/logging.h"
#include "tensorflow/stream_executor/platform/port.h"
#include "third_party/eigen3/Eigen/Core"
namespace perftools {
namespace gputools {
class Stream;
class ScratchAllocator;
namespace dnn {
// Describes how an input or output layer's data is formatted.
// Specify int64 so there's no padding in BatchDescriptor.
enum class DataLayout : int64 {
kYXDepthBatch = 0, // Same as dist_belief::DF_DEPTH_MAJOR.
kYXBatchDepth, // Same as dist_belief::DF_BATCH_MAJOR.
kBatchYXDepth, // Same as run_brain output, and tensorflow's layout.
kBatchDepthYX, // cuDNN's NCHW layout, data laid out as image, feature,
// maps, rows, columns.
};
// Specifies an index to use when accessing specific spatial dimensions.
enum class DimIndex : int {
X = 0,
Y = 1,
Z = 2,
};
// Helper functions to make methods more readable.
inline int64 GetDim(const std::vector<int64>& data, DimIndex dim) {
return data.rbegin()[static_cast<int64>(dim)];
}
inline void SetDim(std::vector<int64>* data, DimIndex dim, int64 value) {
data->rbegin()[static_cast<int64>(dim)] = value;
}
// Returns a string representation of the given data layout.
string DataLayoutString(DataLayout layout);
// Specifies a quantization for activations in a given BatchDescriptor.
enum class QuantizedActivationMode {
k8Bit = 1,
k16Bit = 2,
k32Bit = 4,
};
// Specifies the data type used by an operation.
enum class DataType {
kFloat = 0,
kDouble = 1,
kHalf = 2,
};
// A helper class to convert C/C++ types to the proper enums.
template <typename T>
struct ToDataType;
template <>
struct ToDataType<float> {
static constexpr DataType value = DataType::kFloat;
};
template <>
struct ToDataType<double> {
static constexpr DataType value = DataType::kDouble;
};
template <>
struct ToDataType<Eigen::half> {
static constexpr DataType value = DataType::kHalf;
};
// Specifies the types of a RNN model.
enum class RnnMode {
kRnnRelu = 0,
kRnnTanh = 1,
kRnnLstm = 2,
kRnnGru = 3,
};
// Specifies the input model and whether there is a linear transformation
// between the input state and the first layer hidden state.
enum class RnnInputMode {
kRnnLinearSkip = 0,
kRnnSkipInput = 1,
};
// Specifies the number of directions used in a RNN model. When bidirection
// is used, the input states and output sequence contain data for both
// directions.
enum class RnnDirectionMode {
kRnnUnidirectional = 0,
kRnnBidirectional = 1,
};
// Specifies the descriptor for a RNN model.
//
// An example use case:
// * The user first creates a model through createRnnDescriptor.
// * The user queries the size of the underlying opaque parameter buffer.
// * The user creates and initializes a parameter buffer of the proper size.
// * The user runs forward and backward operations using this RNN descriptor.
// * Once a while, user queries maintainable weights and bias regions from
// the underlying parameter buffer. They are more likely to be forward
// compatible and should used in saving and restoring a model.
// * The user releases the RNN descriptor when the model is no longer in use.
class RnnDescriptor {
public:
struct ParamsRegion {
int64 offset;
int64 size;
};
typedef std::vector<ParamsRegion> ParamsRegions;
virtual ~RnnDescriptor() {}
virtual int64 ParamsSizeInBytes() const { return -1; }
virtual ParamsRegions ParamsWeightRegions() const { return ParamsRegions(); }
virtual ParamsRegions ParamsBiasRegions() const { return ParamsRegions(); }
};
// Specifies the sequence in a RNN model.
//
// The user is responsible for releasing this descriptor when it is no longer
// in use. The destructor releases the underlying descriptors.
class RnnSequenceTensorDescriptor {
public:
virtual ~RnnSequenceTensorDescriptor() {}
};
// Specifies either the input and hidden state in a RNN model.
//
// The user is responsible for releasing this descriptor when it is no longer
// in use. The destructor releases the underlying descriptors.
class RnnStateTensorDescriptor {
public:
virtual ~RnnStateTensorDescriptor() {}
};
// Returns a string representation of the given quantization mode.
string QuantizedActivationModeString(QuantizedActivationMode mode);
// Describes the dimensions that a layer consumes/produces.
//
// This is a matrix (height, width), its "depth" (feature_map_count),
// how many of these matrices are present (count),
// and the maximum and minimum values expected in the matrix (value_max,
// value_min).
// If input is quantized, all values greater
// than value_max will be clipped to value_max and all values less than
// value_min will be clipped to value_min.
// When quantized output is dequantized no value will be greater than
// value_max or less than value_min.
//
// Uses the named argument construction form:
//
// auto input_batch_dimensions =
// BatchDescriptor().set_count(42).set_feature_map_count(7)...
//
// Details:
//
// For a convolutional layer, a single inference takes a 3-dimensional matrix
// of input and produces a 3-dimensional matrix of output. We call the three
// dimensions height, width and feature_map_count, where for an image, the
// height and width correspond to the Y and X pixel indices, respectively, and
// the feature_map_count corresponds to the RGB dimension of the input data.
// Then the count indicates how many 3D matrices are being presented to be
// processed at once; this corresponds to the neural network concept of
// minibatch size.
//
// For a fully connected layer, it's better to put the nodes of the layer in
// the feature_map_count, and leave the height and weight as degenerate (== 1).
// Count indicates how many input vectors (degenerate 3D matrices) are to be
// processed.
//
// If unspecified, value_max and value_min default to 0.0.
// If value_max == value_min the Stream will attempt to derive valid values -
// for example the output of Relu6 activation will always be in the range
// [0.0, 6.0].
//
// If unspecified, layout defaults to kYXDepthBatch.
class BatchDescriptor {
public:
// Creates a "blank" batch descriptor, which should be initialized via the
// named argument helpers.
BatchDescriptor();
explicit BatchDescriptor(int ndims);
// Clones values from 'other' for initialization.
void CloneFrom(const BatchDescriptor& other);
string ToString() const;
string ToShortString() const;
// Accessors.
int64 count() const { return count_; }
int64 feature_map_count() const { return feature_map_count_; }
int64 height() const { return GetDim(spatial_size_, DimIndex::Y); }
int64 width() const { return GetDim(spatial_size_, DimIndex::X); }
int64 spatial_dim(DimIndex dim) const { return GetDim(spatial_size_, dim); }
int ndims() const { return ndims_; }
float value_max() const { return value_max_; }
float value_min() const { return value_min_; }
DataLayout layout() const { return layout_; }
QuantizedActivationMode quantized_activation_mode() const {
return quantized_activation_mode_;
}
// Full dimensions of the underlying data, ordered according to a specific
// layout.
std::vector<int64> full_dims(const DataLayout& layout) const;
// Full strides of the underlying data, ordered according to a specific
// layout.
std::vector<int64> full_strides(const DataLayout& layout) const;
// Named-argument helpers for avoiding user error during construction.
BatchDescriptor& set_count(int64 value) {
count_ = value;
return *this;
}
BatchDescriptor& set_feature_map_count(int64 value) {
feature_map_count_ = value;
return *this;
}
BatchDescriptor& set_height(int64 value) {
SetDim(&spatial_size_, DimIndex::Y, value);
return *this;
}
BatchDescriptor& set_width(int64 value) {
SetDim(&spatial_size_, DimIndex::X, value);
return *this;
}
BatchDescriptor& set_spatial_dim(DimIndex dim, int64 value) {
SetDim(&spatial_size_, dim, value);
return *this;
}
BatchDescriptor& set_value_max(float value) {
value_max_ = value;
return *this;
}
BatchDescriptor& set_value_min(float value) {
value_min_ = value;
return *this;
}
BatchDescriptor& set_layout(DataLayout layout) {
layout_ = layout;
return *this;
}
BatchDescriptor& set_quantized_activation_mode(
QuantizedActivationMode quantized_activation_mode) {
quantized_activation_mode_ = quantized_activation_mode;
return *this;
}
// Return the number of nodes in a single feature map.
int64 NodesPerFeatureMap() const;
// Return the number of nodes across all feature maps. Note that this is not
// affected by the batch count.
int64 NodesAcrossFeatureMaps() const;
// Returns the number of elements (e.g. RGB pixel values) required to hold a
// given batch descriptor, given a no-padding assumption. Note that this is
// affected by the batch count.
int64 ElementCount() const;
// Return the number of weights required to fully connect a layer with
// dimensions given by the 'input' descriptor with a layer with dimensions
// given by the 'output' descriptor.
static int64 FullyConnectedWeightCount(const BatchDescriptor& input,
const BatchDescriptor& output);
// Return the number of biases required to fully connect to an output layer
// with dimensions given the 'output' descriptor.
static int64 FullyConnectedBiasCount(const BatchDescriptor& output);
// Return a BatchDescriptor for the output of a depth concatenation
// with the given input descriptors. The inputs should have the same
// dimensions, except possibly for feature_map_count(), though this
// function does not verify that.
static BatchDescriptor DepthConcatenateOutputDescriptor(
port::ArraySlice<dnn::BatchDescriptor> inputs);
private:
int64 count_;
int64 feature_map_count_;
// Stored as: ..., y, x.
std::vector<int64> spatial_size_;
float value_max_;
float value_min_;
DataLayout layout_;
int ndims_;
QuantizedActivationMode quantized_activation_mode_;
};
// Describes how a filter is laid out in the memory.
// Specify int64 so there's no padding in FilterDescriptor.
enum class FilterLayout : int64 {
kOutputInputYX = 0, // cuDNN's default filter layout, laid out as:
// (major) output feature maps >> input feature maps >>
// rows >> columns (minor).
kInputYXOutput, // Same as dist_belief's default filter layout.
kYXInputOutput, // Same as tensorflow's default filter layout.
};
// Returns a string representation of the given filter layout.
string FilterLayoutString(FilterLayout layout);
// Describes a filter for the convolution. This is the "window" from
// height-by-width patches of each of the feature maps in the input layer to the
// cells within the output feature map.
//
// Uses the named argument construction form:
//
// FilterDescriptor filter_dimensions;
// filter_dimensions
// .set_output_feature_map_count(42)
// .set_input_feature_map_count(7)
// ...
//
// Arguments:
// - output_feature_map_count: number of feature maps in the output layer.
// - input_feature_map_count: number of feature maps in the input layer (from
// which the filter patch is taken).
// - input_filter_height: "height" number of neurons used in the sliding window
// over the input layer.
// - input_filter_width: "width" number of neurons used in the sliding window
// over the input layer.
//
// Sometimes names like "filter input height" are referred to by synonymous
// terminology, such as "kernel y size".
//
// If unspecified, layout defaults to kOutputInputYX.
class FilterDescriptor {
public:
// By default construction, all dimensions are set to zero, so they should all
// be populated by the user via the named-argument helpers below. (See class
// comment for details.)
FilterDescriptor();
explicit FilterDescriptor(int ndims);
~FilterDescriptor();
// Named-argument helpers for avoiding user error during construction.
FilterDescriptor& set_output_feature_map_count(int64 value) {
output_feature_map_count_ = value;
return *this;
}
FilterDescriptor& set_input_feature_map_count(int64 value) {
input_feature_map_count_ = value;
return *this;
}
FilterDescriptor& set_input_filter_height(int64 value) {
SetDim(&input_filter_dims_, DimIndex::Y, value);
return *this;
}
FilterDescriptor& set_input_filter_width(int64 value) {
SetDim(&input_filter_dims_, DimIndex::X, value);
return *this;
}
FilterDescriptor& set_layout(FilterLayout layout) {
layout_ = layout;
return *this;
}
FilterDescriptor& set_spatial_dim(DimIndex dim, int64 value) {
SetDim(&input_filter_dims_, dim, value);
return *this;
}
int ndims() const { return ndims_; }
void CloneFrom(const FilterDescriptor& other);
string ToString() const;
string ToShortString() const;
// Returns the number of weights required as parameters for a convolution
// using this filter descriptor.
int64 ComputeWeightCount() const;
// Returns the number of biases required as parameters for a convolution
// using this filter descriptor.
int64 bias_count() const { return output_feature_map_count_; }
int64 output_feature_map_count() const { return output_feature_map_count_; }
int64 input_feature_map_count() const { return input_feature_map_count_; }
int64 input_filter_height() const {
return GetDim(input_filter_dims_, DimIndex::Y);
}
int64 input_filter_width() const {
return GetDim(input_filter_dims_, DimIndex::X);
}
int64 input_filter_dim(DimIndex dim) const {
return GetDim(input_filter_dims_, dim);
}
FilterLayout layout() const { return layout_; }
std::vector<int64> input_filter_dims() const { return input_filter_dims_; }
private:
int64 output_feature_map_count_;
int64 input_feature_map_count_;
// Stored as: ..., y, x.
std::vector<int64> input_filter_dims_;
int ndims_;
FilterLayout layout_;
};
// Describes a convolution.
//
// Uses the named argument construction form:
//
// ConvolutionDescriptor convolution_dimensions;
// convolution_dimensions
// .set_vertical_filter_stride(2)
// .set_horizontal_filter_stride(2)
// ...
//
// Arguments:
// - zero_padding_height: padding of the "y dimension" of the input data. Note
// that this is different from the height of the filter.
// - zero_padding_width: analogous to the height above, but in the "x
// dimension".
// - vertical_filter_stride: the convolution slides a 2-dimensional window of
// filter-height-by-filter-width over the input layer -- the center of that
// window is moved in the "y dimension" according to this stride value.
// - horizontal_filter_stride: analogous to the vertical stride above, but in
// the "x dimension".
class ConvolutionDescriptor {
public:
// By default construction, there is no zero-padding and the filter stride is
// 1x1 (centering the filter on every cell in the input layer's
// width-by-height area).
ConvolutionDescriptor();
explicit ConvolutionDescriptor(int ndims);
~ConvolutionDescriptor();
string ToString() const;
string ToShortString() const;
ConvolutionDescriptor& set_zero_padding_height(int64 value) {
SetDim(&zero_padding_, DimIndex::Y, value);
return *this;
}
ConvolutionDescriptor& set_zero_padding_width(int64 value) {
SetDim(&zero_padding_, DimIndex::X, value);
return *this;
}
ConvolutionDescriptor& set_zero_padding(DimIndex dim, int64 value) {
SetDim(&zero_padding_, dim, value);
return *this;
}
ConvolutionDescriptor& set_vertical_filter_stride(int64 value) {
SetDim(&filter_strides_, DimIndex::Y, value);
return *this;
}
ConvolutionDescriptor& set_horizontal_filter_stride(int64 value) {
SetDim(&filter_strides_, DimIndex::X, value);
return *this;
}
ConvolutionDescriptor& set_filter_stride(DimIndex dim, int64 value) {
SetDim(&filter_strides_, dim, value);
return *this;
}
int64 zero_padding_height() const {
return GetDim(zero_padding_, DimIndex::Y);
}
int64 zero_padding_width() const {
return GetDim(zero_padding_, DimIndex::X);
}
int64 vertical_filter_stride() const {
return GetDim(filter_strides_, DimIndex::Y);
}
int64 horizontal_filter_stride() const {
return GetDim(filter_strides_, DimIndex::X);
}
int zero_padding(DimIndex dim) const { return GetDim(zero_padding_, dim); }
int filter_stride(DimIndex dim) const { return GetDim(filter_strides_, dim); }
int ndims() const { return ndims_; }
std::vector<int64> strides() const { return filter_strides_; }
std::vector<int64> padding() const { return zero_padding_; }
private:
// Stored as: .. y, x.
std::vector<int64> zero_padding_;
std::vector<int64> filter_strides_;
int ndims_;
// TODO(leary) cudnn provides these fields, but need to characterize what
// their effect is -- they may be boolean rather than integral.
// int64 upscale_input_x;
// int64 upscale_input_y;
};
// A patch of values in the input can be pooled via either a max or an average
// operation.
// Specify int64 so there's no padding in PoolingDescriptor.
enum class PoolingMode : int64 {
kMaximum,
kAverage,
};
// Returns a short name for the pooling mode, e.g. "Avg".
string ShortPoolingModeString(PoolingMode mode);
// Describes a pooling operation to be enqueued onto a stream via a platform's
// DnnSupport.
//
// TODO(broune): describe how padding works and what happens if the
// window height/width is not divisible by the vertical/horizontal
// stride.
//
// Arguments:
// pooling_mode: pooling operator to use on the input patch
// window_height: height of input window
// window_width: width of input window
// vertical_stride: vertical delta for center of the input patch
// horizontal_stride: horizontal delta for center of the input patch
class PoolingDescriptor {
public:
PoolingDescriptor();
explicit PoolingDescriptor(int ndims);
PoolingDescriptor& set_pooling_mode(PoolingMode value) {
mode_ = value;
return *this;
}
PoolingDescriptor& set_window_height(int64 value) {
SetDim(&window_, DimIndex::Y, value);
return *this;
}
PoolingDescriptor& set_window_width(int64 value) {
SetDim(&window_, DimIndex::X, value);
return *this;
}
PoolingDescriptor& set_window(DimIndex dim, int64 value) {
SetDim(&window_, dim, value);
return *this;
}
PoolingDescriptor& set_vertical_padding(int64 value) {
SetDim(&padding_, DimIndex::Y, value);
return *this;
}
PoolingDescriptor& set_horizontal_padding(int64 value) {
SetDim(&padding_, DimIndex::X, value);
return *this;
}
PoolingDescriptor& set_padding(DimIndex dim, int64 value) {
SetDim(&padding_, dim, value);
return *this;
}
PoolingDescriptor& set_vertical_stride(int64 value) {
SetDim(&strides_, DimIndex::Y, value);
return *this;
}
PoolingDescriptor& set_horizontal_stride(int64 value) {
SetDim(&strides_, DimIndex::X, value);
return *this;
}
PoolingDescriptor& set_stride(DimIndex dim, int64 value) {
SetDim(&strides_, dim, value);
return *this;
}
int ndims() const { return ndims_; }
void CloneFrom(const PoolingDescriptor& other);
string ToString() const;
string ToShortString() const;
PoolingMode mode() const { return mode_; }
int64 window_height() const { return GetDim(window_, DimIndex::Y); }
int64 window_width() const { return GetDim(window_, DimIndex::X); }
int64 window(DimIndex dim) const { return GetDim(window_, dim); }
int64 vertical_padding() const { return GetDim(padding_, DimIndex::Y); }
int64 horizontal_padding() const { return GetDim(padding_, DimIndex::X); }
int64 padding(DimIndex dim) const { return GetDim(padding_, dim); }
int64 vertical_stride() const { return GetDim(strides_, DimIndex::Y); }
int64 horizontal_stride() const { return GetDim(strides_, DimIndex::X); }
int64 stride(DimIndex dim) const { return GetDim(strides_, dim); }
std::vector<int64> window() const { return window_; }
std::vector<int64> padding() const { return padding_; }
std::vector<int64> strides() const { return strides_; }
private:
PoolingMode mode_;
int ndims_;
// Stored as: ..., y, x.
std::vector<int64> window_;
std::vector<int64> padding_;
std::vector<int64> strides_;
};
typedef int64 AlgorithmType;
constexpr AlgorithmType kDefaultAlgorithm = -1;
// Describes the result from a perf experiment.
//
// Arguments:
// is_valid: indicates whether a valid measurement was obtained.
// algorithm: returns the exact algorithm that was used.
// elapsed_time_in_ms: returns the measured elapsed time in milliseconds.
class ProfileResult {
public:
bool is_valid() const { return is_valid_; }
void set_is_valid(bool val) { is_valid_ = val; }
AlgorithmType algorithm() const { return algorithm_; }
void set_algorithm(AlgorithmType val) { algorithm_ = val; }
float elapsed_time_in_ms() const { return elapsed_time_in_ms_; }
void set_elapsed_time_in_ms(float val) { elapsed_time_in_ms_ = val; }
private:
bool is_valid_ = false;
AlgorithmType algorithm_ = kDefaultAlgorithm;
float elapsed_time_in_ms_ = std::numeric_limits<float>::max();
};
// Describe the configuration for the algorithms that will used.
//
// Arguments:
// algorithm: the primary algorithm that should be used.
// algorithm_no_scratch: a secondary algorithm that should be used, if the
// the allocation for the scratch memory fails.
class AlgorithmConfig {
public:
AlgorithmConfig()
: algorithm_(kDefaultAlgorithm),
algorithm_no_scratch_(kDefaultAlgorithm) {}
explicit AlgorithmConfig(AlgorithmType algorithm)
: algorithm_(algorithm), algorithm_no_scratch_(kDefaultAlgorithm) {}
AlgorithmConfig(AlgorithmType algorithm, AlgorithmType algorithm_no_scratch)
: algorithm_(algorithm), algorithm_no_scratch_(algorithm_no_scratch) {}
AlgorithmType algorithm() const { return algorithm_; }
void set_algorithm(AlgorithmType val) { algorithm_ = val; }
AlgorithmType algorithm_no_scratch() const { return algorithm_no_scratch_; }
void set_algorithm_no_scratch(AlgorithmType val) {
algorithm_no_scratch_ = val;
}
private:
AlgorithmType algorithm_;
AlgorithmType algorithm_no_scratch_;
};
// Describes a local response normalization (LRN). LRN is used e.g. in
// dist_belief.
//
// Let V be the vector of feature maps at some (batch, y, x)
// coordinate. LRN applies independently to each vector V in the
// input, across all coordinates (batch, y, x), by mapping each V to
// another vector U of the same size using the formula
//
// U_i = V_i / ((bias + alpha * (sum_j V_j^2)) ^ beta)
//
// where the sum is taken over j in the closed range [i - range, i + range].
//
// When calculating U_i the j in the sum can extend beyond the bounds
// of V. If wrap_around is true, then V_j = V_{j mod F} where F is the
// size of V, which is the number of feature maps. If wrap_around is
// false, then V_j = 0 for j outside [0, F-1].
//
// If segment_size <= F, where F is the number of feature_maps, then
// segment_size has no effect. Otherwise, each consecutive segment of
// segment_size entries in V are normalized separately.
//
// Not all StreamExecutors allow wrap_around == true or segment_size
// != 64. Some do not implement normalization at all.
class NormalizeDescriptor {
public:
NormalizeDescriptor();
NormalizeDescriptor& set_bias(float bias) {
bias_ = bias;
return *this;
}
NormalizeDescriptor& set_range(int32 range) {
range_ = range;
return *this;
}
NormalizeDescriptor& set_alpha(float alpha) {
alpha_ = alpha;
return *this;
}
NormalizeDescriptor& set_beta(float beta) {
beta_ = beta;
return *this;
}
NormalizeDescriptor& set_wrap_around(bool wrap_around) {
wrap_around_ = wrap_around;
return *this;
}
NormalizeDescriptor& set_segment_size(int32 segment_size) {
segment_size_ = segment_size;
return *this;
}
void CloneFrom(const NormalizeDescriptor& other);
string ToString() const;
string ToShortString() const;
float bias() const { return bias_; }
int32 range() const { return range_; }
float alpha() const { return alpha_; }
float beta() const { return beta_; }
bool wrap_around() const { return wrap_around_; }
int32 segment_size() const { return segment_size_; }
private:
float bias_;
int32 range_;
float alpha_;
float beta_;
bool wrap_around_;
int32 segment_size_;
};
// Describes a kind of non-linearity (threshold-like mathematical function).
enum class ActivationMode {
kSigmoid,
// Rectified linear activation: f(x) = x < 0 ? 0 : x
kRelu,
// Rectified linear activation, where upper maximum is 6.0.
kRelu6,
// Rectified linear activation, where upper maximum specified by
// BatchDescriptor::value_max().
kReluX,
kTanh,
// Like ReluX, but passes all values in the range [-X,X].
kBandPass,
};
// Returns a string representation of the given activation mode.
string ActivationModeString(ActivationMode mode);
// Describes the operation that DoElementwiseOperation should perform on its
// inputs.
enum class ElementwiseOperation { kAdd, kMultiply };
string ElementwiseOperationString(ElementwiseOperation op);
// Suite of operations typically used for implementing Deep/Convolutional Neural
// Nets. Note: A false return value of an operation indicates the
// implementation is not available.
class DnnSupport {
public:
DnnSupport() {}
virtual ~DnnSupport() {}
virtual port::Status Init() = 0;
// Performs a single-precision forward batch normalization operation onto
// the stream.
//
// Arguments:
// stream: borrowed pointer to the stream that the batch normalization
// operation should be enqueued onto.
// x: input data.
// scale: scaling parameters.
// offset: offset parameters.
// estimated_mean: population mean estimated during training.
// Used for inference only; empty for training.
// estimated_variance: population variance estimated during traning,
// used for inference only; empty for training.
// x_desc: dimensions of the input data, which is the same as the dimensions
// of the output.
// scale_offset_desc: dimensions of scale and offset.
// epsilon: a small floating point number added to the variance of x.
// y: output data.
// batch_mean: batch mean, to be used to compute the running mean.
// batch_variance: batch variance, to be used to compute
// the running variance.
// reserve_space_1: saved mean, to be reused in the backward gradient
// computation.
// reserve_space_2: saved variance, to be reused in the backward gradient
// computation.
// is_training: Set to true for training, false for inference.
// var_to_inv_var: a function to convert the variance to inverted variance
// for cuDNN v4 forward inference.
// inv_var_to_var: a function to convert the inverted variance to
// variance for cuDNN v4 forward training, to be used for TensorFlow
// to calculate the running variance.
virtual bool DoBatchNormalizationForward(
Stream* stream, const DeviceMemory<float>& x,
const DeviceMemory<float>& scale, const DeviceMemory<float>& offset,
const DeviceMemory<float>& estimated_mean,
const DeviceMemory<float>& estimated_variance,
const dnn::BatchDescriptor& x_desc,
const dnn::BatchDescriptor& scale_offset_desc, const double epsilon,
DeviceMemory<float>* y, DeviceMemory<float>* batch_mean,
DeviceMemory<float>* batch_var, DeviceMemory<float>* reserve_space_1,
DeviceMemory<float>* reserve_space_2, bool is_training,
std::function<const DeviceMemory<float>&()> var_to_inv_var,
std::function<void()> inv_var_to_var) {
return false;
}
// Performs a single-precision backward batch normalization gradient
// computation operation onto the stream.
//
// Arguments:
// stream: borrowed pointer to the stream that the batch normalization
// gradient computation operation should be enqueued onto.
// y_backprop: gradient with regard to output y.
// x: input data.
// scale: scaling parameters.
// x_desc: dimensions of the input data, which is the same as the dimensions
// of the output.
// scale_offset_desc: dimensions of scale and offset.
// epsilon: a small floating point number added to the variance of x.
// x_backprop: gradient with respect to input x.
// scale_backprop: gradient with respect to scale.
// offset_backprop: gradient with respect to offset.
virtual bool DoBatchNormalizationBackward(
Stream* stream, const DeviceMemory<float>& y_backprop,
const DeviceMemory<float>& x, const DeviceMemory<float>& scale,
const DeviceMemory<float>& mean, const DeviceMemory<float>& variance,
const dnn::BatchDescriptor& x_desc,
const dnn::BatchDescriptor& scale_offset_desc, const double epsilon,
DeviceMemory<float>* x_backprop, DeviceMemory<float>* scale_backprop,
DeviceMemory<float>* offset_backprop) {
return false;
}
// Enqueues a single-precision convolution operation onto the stream.
//
// Arguments (all borrowed):
// stream: borrowed pointer to the stream that the 'convolve' operation
// should be enqueued onto.
// input_descriptor: dimensions of the input layer.
// input_data: un-owned device memory region which contains the
// convolution input.
// filter_descriptor: dimensions of the convolution filter.
// weights: coefficients for the convolution filter, these are multiplied
// against values in the input that the filter convolves over.
// convolution_descriptor: stride of the convolution filter.
// output_descriptor: dimensions of the output layer.
// output_data: un-owned device memory region in which to place the
// convolution result.
// scratch_allocator: un-owned, may-be-null object that may allocate scratch
// space in order to speed up the convolution operation.
// algorithm: an integer to specify which algorithm should be used for the
// operation. kDefaultAlgorithm means the system will pick an algorithm
// by default. The coding of the algorithm is be interpretted by the
// underlying implementation.
// output_profile_result: the output profile result for this call. The
// profiling is only enabled when this is not nullptr.
//
// input_descriptor, filter_descriptor, convolution_descriptor and
// output_descriptor together specify exactly how the convolution is aligned
// with the input data:
//
// * (input dimensions - filter size + 1) / filter stride == output dimensions
// corresponds to dist_belief padding = VALID, i.e. the input is not padded.
// * input dimensions / filter stride == output dimensions
// corresponds to dist_belief padding = SAME, i.e. input and output are the
// same size - this requires padding the input.
// * (input dimensions + filter size - 1) / filter stride == output dimensions
// corresponds to dist_belief padding = FULL, i.e. the output is sized so
// that if the inverse of the filter is applied to the output in VALID mode
// the result is the same size as the input - this requires even more
// padding of the input.
virtual bool DoConvolve(
Stream* stream, const dnn::BatchDescriptor& input_descriptor,
const DeviceMemory<float>& input_data,
const dnn::FilterDescriptor& filter_descriptor,
const DeviceMemory<float>& filter_data,
const dnn::ConvolutionDescriptor& convolution_descriptor,
const dnn::BatchDescriptor& output_descriptor,
DeviceMemory<float>* output_data, ScratchAllocator* scratch_allocator,
const dnn::AlgorithmConfig& algorithm_config,
ProfileResult* output_profile_result) = 0;
// Return a list of algorithms supported by the forward convolution pass.
virtual bool GetConvolveAlgorithms(
std::vector<AlgorithmType>* out_algorithms);
// Enqueues a double-precision convolution operation onto the stream.
// See DoConvolve above for argument details.
virtual bool DoConvolve(
Stream* stream, const dnn::BatchDescriptor& batch_descriptor,
const DeviceMemory<double>& input_data,
const dnn::FilterDescriptor& filter_descriptor,
const DeviceMemory<double>& filter_data,
const dnn::ConvolutionDescriptor& convolution_descriptor,
const dnn::BatchDescriptor& output_descriptor,
DeviceMemory<double>* output_data) = 0;
// Enqueues a half-precision convolution operation onto the stream.
// See DoConvolve above for argument details.
virtual bool DoConvolve(
Stream* stream, const dnn::BatchDescriptor& batch_descriptor,
const DeviceMemory<Eigen::half>& input_data,
const dnn::FilterDescriptor& filter_descriptor,
const DeviceMemory<Eigen::half>& filter_data,
const dnn::ConvolutionDescriptor& convolution_descriptor,
const dnn::BatchDescriptor& output_descriptor,
DeviceMemory<Eigen::half>* output_data,
ScratchAllocator* scratch_allocator,
const dnn::AlgorithmConfig& algorithm_config,
ProfileResult* output_profile_result) = 0;
// Variation of the above with the weight matrix split into two matrices.
// first_weights: Coefficients of the first matrix.
// second_weights: Coefficients of the second matrix.
// depth_multiplier: specifies the columns of the first matrix and rows
// of the second one - first_weights columns = depth_multiplier,
// second_weights rows = depth_multiplier *
// filter_descriptor.input_feature_map_count().
// see go/separable for documentation on separable convolutions.
virtual bool DoSeparableConvolve(
Stream* stream, const BatchDescriptor& input_descriptor,
const DeviceMemory<float>& input_data,
const FilterDescriptor& filter_descriptor, int depth_multiplier,
const DeviceMemory<float>& first_weights,
const DeviceMemory<float>& second_weights,
const ConvolutionDescriptor& convolution_descriptor,
const BatchDescriptor& output_descriptor,
DeviceMemory<float>* output_data) = 0;
// Enqueues a single-precision backward convolution (for data) operation onto
// the stream.
//
// Arguments:
// stream: borrowed pointer to the stream that the 'convolve' operation
// should be enqueued onto.
// filter_descriptor: dimensions of the convolution filter.
// filter_data: coefficients for the convolution filter.
// output_descriptor: dimensions of the output gradients, which is the same
// as the dimensions of the output.
// backward_output_data: un-owned device memory region which contains the
// backprop of the output.
// convolution_descriptor: stride of the convolution filter.
// input_descriptor: dimensions of the input layer.
// backward_input_data: un-owned device memory region in which to place the
// backprop of the input.
// scratch_allocator: un-owned, may-be-null object that may allocate scratch
// space in order to speed up the convolution operation.
virtual bool DoConvolveBackwardData(
Stream* stream, const FilterDescriptor& filter_descriptor,
const DeviceMemory<float>& filter_data,
const BatchDescriptor& output_descriptor,
DeviceMemory<float> backward_output_data,
const ConvolutionDescriptor& convolution_descriptor,
const BatchDescriptor& input_descriptor,
DeviceMemory<float>* backward_input_data,
ScratchAllocator* scratch_allocator,
const dnn::AlgorithmConfig& algorithm_config,
ProfileResult* output_profile_result) = 0;
// Return a list of algorithms supported by the backward convolution pass for
// data.
virtual bool GetConvolveBackwardDataAlgorithms(
std::vector<AlgorithmType>* out_algorithms);
virtual bool DoConvolveBackwardData(
Stream* stream, const FilterDescriptor& filter_descriptor,
const DeviceMemory<Eigen::half>& filter_data,
const BatchDescriptor& output_descriptor,
DeviceMemory<Eigen::half> backward_output_data,
const ConvolutionDescriptor& convolution_descriptor,
const BatchDescriptor& input_descriptor,
DeviceMemory<Eigen::half>* backward_input_data,
ScratchAllocator* scratch_allocator,