/
common_shape_fns.cc
1395 lines (1217 loc) · 53 KB
/
common_shape_fns.cc
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 2016 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.
==============================================================================*/
#include "tensorflow/core/framework/common_shape_fns.h"
#include "tensorflow/core/framework/attr_value.pb.h"
namespace tensorflow {
Status GetWindowedOutputSizeVerboseV2(int64 input_size, int64 filter_size,
int64 dilation_rate, int64 stride,
Padding padding_type, int64* output_size,
int64* padding_before,
int64* padding_after) {
if (stride <= 0) {
return errors::InvalidArgument("Stride must be > 0, but got ", stride);
}
if (dilation_rate < 1) {
return errors::InvalidArgument("Dilation rate must be >= 1, but got ",
dilation_rate);
}
// See also the parallel implementation in GetWindowedOutputSizeFromDimsV2.
int64 effective_filter_size = (filter_size - 1) * dilation_rate + 1;
switch (padding_type) {
case Padding::VALID:
*output_size = (input_size - effective_filter_size + stride) / stride;
*padding_before = *padding_after = 0;
break;
case Padding::SAME:
*output_size = (input_size + stride - 1) / stride;
const int64 padding_needed =
std::max(0LL, (*output_size - 1) * stride + effective_filter_size -
input_size);
// For odd values of total padding, add more padding at the 'right'
// side of the given dimension.
*padding_before = padding_needed / 2;
*padding_after = padding_needed - *padding_before;
break;
}
if (*output_size < 0) {
return errors::InvalidArgument("computed output size would be negative");
}
return Status::OK();
}
Status GetWindowedOutputSizeVerbose(int64 input_size, int64 filter_size,
int64 stride, Padding padding_type,
int64* output_size, int64* padding_before,
int64* padding_after) {
return GetWindowedOutputSizeVerboseV2(input_size, filter_size,
/*dilation_rate=*/1, stride,
padding_type, output_size,
padding_before, padding_after);
}
Status GetWindowedOutputSize(int64 input_size, int64 filter_size, int64 stride,
Padding padding_type, int64* output_size,
int64* padding_size) {
int64 padding_after_unused;
return GetWindowedOutputSizeVerbose(input_size, filter_size, stride,
padding_type, output_size, padding_size,
&padding_after_unused);
}
Status GetWindowedOutputSizeV2(int64 input_size, int64 filter_size,
int64 dilation_rate, int64 stride,
Padding padding_type, int64* output_size,
int64* padding_size) {
int64 padding_after_unused;
return GetWindowedOutputSizeVerboseV2(input_size, filter_size, dilation_rate,
stride, padding_type, output_size,
padding_size, &padding_after_unused);
}
Status Get3dOutputSize(const std::array<int64, 3>& input,
const std::array<int64, 3>& window,
const std::array<int64, 3>& strides,
Padding padding_type, std::array<int64, 3>* output_ptr,
std::array<int64, 3>* padding_ptr) {
for (size_t i = 0; i < input.size(); ++i) {
TF_RETURN_IF_ERROR(GetWindowedOutputSize(input[i], window[i], strides[i],
padding_type, &(*output_ptr)[i],
&(*padding_ptr)[i]));
}
return Status::OK();
}
Status Get3dOutputSizeV2(const std::array<int64, 3>& input,
const std::array<int64, 3>& window,
const std::array<int64, 3>& dilations,
const std::array<int64, 3>& strides,
Padding padding_type, std::array<int64, 3>* output_ptr,
std::array<int64, 3>* padding_ptr) {
for (size_t i = 0; i < input.size(); ++i) {
TF_RETURN_IF_ERROR(GetWindowedOutputSizeV2(
input[i], window[i], dilations[i], strides[i], padding_type,
&(*output_ptr)[i], &(*padding_ptr)[i]));
}
return Status::OK();
}
namespace shape_inference {
// The V2 version computes windowed output size with arbitrary dilation_rate,
// while the original version only handles the cases where dilation_rates equal
// to 1.
Status GetWindowedOutputSizeFromDimsV2(
shape_inference::InferenceContext* c,
shape_inference::DimensionHandle input_size,
shape_inference::DimensionOrConstant filter_size, int64 dilation_rate,
int64 stride, Padding padding_type,
shape_inference::DimensionHandle* output_size) {
if (stride <= 0) {
return errors::InvalidArgument("Stride must be > 0, but got ", stride);
}
if (dilation_rate < 1) {
return errors::InvalidArgument("Dilation rate must be >= 1, but got ",
dilation_rate);
}
// See also the parallel implementation in GetWindowedOutputSizeVerbose.
switch (padding_type) {
case Padding::VALID:
if (dilation_rate > 1) {
DimensionHandle window_size;
TF_RETURN_IF_ERROR(
c->Subtract(c->MakeDim(filter_size), 1, &window_size));
TF_RETURN_IF_ERROR(
c->Multiply(window_size, dilation_rate, &window_size));
TF_RETURN_IF_ERROR(c->Add(window_size, 1, &window_size));
TF_RETURN_IF_ERROR(c->Subtract(input_size, window_size, output_size));
} else {
TF_RETURN_IF_ERROR(c->Subtract(input_size, filter_size, output_size));
}
TF_RETURN_IF_ERROR(c->Add(*output_size, stride, output_size));
TF_RETURN_IF_ERROR(c->Divide(*output_size, stride,
/*evenly_divisible=*/false, output_size));
break;
case Padding::SAME:
TF_RETURN_IF_ERROR(c->Add(input_size, stride - 1, output_size));
TF_RETURN_IF_ERROR(c->Divide(*output_size, stride,
/*evenly_divisible=*/false, output_size));
break;
}
return Status::OK();
}
Status GetWindowedOutputSizeFromDims(
shape_inference::InferenceContext* c,
shape_inference::DimensionHandle input_size,
shape_inference::DimensionOrConstant filter_size, int64 stride,
Padding padding_type, shape_inference::DimensionHandle* output_size) {
return GetWindowedOutputSizeFromDimsV2(c, input_size, filter_size,
/*dilation_rate=*/1, stride,
padding_type, output_size);
}
Status UnchangedShape(shape_inference::InferenceContext* c) {
c->set_output(0, c->input(0));
return Status::OK();
}
Status MatMulShape(shape_inference::InferenceContext* c) {
ShapeHandle a;
TF_RETURN_IF_ERROR(c->WithRank(c->input(0), 2, &a));
ShapeHandle b;
TF_RETURN_IF_ERROR(c->WithRank(c->input(1), 2, &b));
bool transpose_a, transpose_b;
TF_RETURN_IF_ERROR(c->GetAttr("transpose_a", &transpose_a));
TF_RETURN_IF_ERROR(c->GetAttr("transpose_b", &transpose_b));
DimensionHandle output_rows = transpose_a ? c->Dim(a, 1) : c->Dim(a, 0);
DimensionHandle output_cols = transpose_b ? c->Dim(b, 0) : c->Dim(b, 1);
// Validate that the inner shapes are compatible.
DimensionHandle inner_a = transpose_a ? c->Dim(a, 0) : c->Dim(a, 1);
DimensionHandle inner_b = transpose_b ? c->Dim(b, 1) : c->Dim(b, 0);
DimensionHandle merged;
TF_RETURN_IF_ERROR(c->Merge(inner_a, inner_b, &merged));
c->set_output(0, c->Matrix(output_rows, output_cols));
return Status::OK();
}
Status BiasAddShape(shape_inference::InferenceContext* c) {
ShapeHandle input_shape;
// Fetch the data_format attribute, which may not exist.
string data_format;
Status s = c->GetAttr("data_format", &data_format);
if (s.ok() && data_format == "NCHW") {
TF_RETURN_IF_ERROR(c->WithRankAtLeast(c->input(0), 3, &input_shape));
} else {
TF_RETURN_IF_ERROR(c->WithRankAtLeast(c->input(0), 2, &input_shape));
}
ShapeHandle bias_shape;
TF_RETURN_IF_ERROR(c->WithRank(c->input(1), 1, &bias_shape));
DimensionHandle bias_dim = c->Dim(bias_shape, 0);
// If rank unknown, return unknown shape.
if (!c->RankKnown(input_shape)) {
c->set_output(0, c->UnknownShape());
return Status::OK();
}
// Output has the same shape as the input, and matches the length of
// the bias in its bias dimension.
ShapeHandle output_shape;
if (s.ok() && data_format == "NCHW") {
// Merge the length of bias_shape into the third to last dimension
ShapeHandle first;
TF_RETURN_IF_ERROR(c->Subshape(input_shape, 0, -3, &first));
ShapeHandle last;
TF_RETURN_IF_ERROR(c->Subshape(input_shape, -2, &last));
DimensionHandle input_bias_dim = c->Dim(input_shape, -3);
DimensionHandle merged_bias_dim;
TF_RETURN_IF_ERROR(c->Merge(input_bias_dim, bias_dim, &merged_bias_dim));
ShapeHandle merged_bias = c->Vector(merged_bias_dim);
ShapeHandle temp;
TF_RETURN_IF_ERROR(c->Concatenate(first, merged_bias, &temp));
TF_RETURN_IF_ERROR(c->Concatenate(temp, last, &output_shape));
} else {
ShapeHandle all_but_bias;
TF_RETURN_IF_ERROR(c->Subshape(input_shape, 0, -1, &all_but_bias));
DimensionHandle input_bias_dim = c->Dim(input_shape, -1);
DimensionHandle merged_bias_dim;
TF_RETURN_IF_ERROR(c->Merge(input_bias_dim, bias_dim, &merged_bias_dim));
ShapeHandle merged_bias = c->Vector(merged_bias_dim);
TF_RETURN_IF_ERROR(
c->Concatenate(all_but_bias, merged_bias, &output_shape));
}
c->set_output(0, output_shape);
return Status::OK();
}
Status BiasAddGradShape(shape_inference::InferenceContext* c) {
ShapeHandle input_shape;
// Fetch the data_format attribute, which may not exist.
string data_format;
Status s = c->GetAttr("data_format", &data_format);
if (s.ok() && data_format == "NCHW") {
TF_RETURN_IF_ERROR(c->WithRankAtLeast(c->input(0), 3, &input_shape));
c->set_output(0, c->Vector(c->Dim(input_shape, -3)));
} else {
TF_RETURN_IF_ERROR(c->WithRankAtLeast(c->input(0), 2, &input_shape));
c->set_output(0, c->Vector(c->Dim(input_shape, -1)));
}
return Status::OK();
}
Status CheckFormatConstraintsOnShape(const TensorFormat tensor_format,
const ShapeHandle shape_handle,
const string& tensor_name,
shape_inference::InferenceContext* c) {
if (tensor_format == FORMAT_NCHW_VECT_C) {
// Check that the vect dim has size 4.
const int num_dims = c->Rank(shape_handle);
DimensionHandle vect_dim = c->Dim(
shape_handle, GetTensorInnerFeatureDimIndex(num_dims, tensor_format));
DimensionHandle unused_vect_dim;
TF_RETURN_IF_ERROR(c->WithValue(vect_dim, 4, &unused_vect_dim));
}
return Status::OK();
}
Status MakeShapeFromFormat(TensorFormat format, DimensionOrConstant N,
const std::vector<DimensionOrConstant>& spatial,
DimensionOrConstant C, ShapeHandle* out,
shape_inference::InferenceContext* context) {
const int num_dims = GetTensorDimsFromSpatialDims(spatial.size(), format);
std::vector<DimensionHandle> dims_actual(num_dims);
dims_actual[GetTensorBatchDimIndex(num_dims, format)] = context->MakeDim(N);
int outer_c_index = GetTensorFeatureDimIndex(num_dims, format);
dims_actual[outer_c_index] = context->MakeDim(C);
if (format == FORMAT_NCHW_VECT_C) {
dims_actual[GetTensorInnerFeatureDimIndex(num_dims, format)] =
context->MakeDim(4);
}
for (int spatial_dim = 0; spatial_dim < spatial.size(); spatial_dim++) {
dims_actual[GetTensorSpatialDimIndex(num_dims, format, spatial_dim)] =
context->MakeDim(spatial[spatial_dim]);
}
*out = context->MakeShape(dims_actual);
return Status::OK();
}
Status DimensionsFromShape(ShapeHandle shape, TensorFormat format,
DimensionHandle* batch_dim,
gtl::MutableArraySlice<DimensionHandle> spatial_dims,
DimensionHandle* filter_dim,
InferenceContext* context) {
const int32 rank = GetTensorDimsFromSpatialDims(spatial_dims.size(), format);
// Batch.
*batch_dim = context->Dim(shape, GetTensorBatchDimIndex(rank, format));
// Spatial.
for (int spatial_dim_index = 0; spatial_dim_index < spatial_dims.size();
++spatial_dim_index) {
spatial_dims[spatial_dim_index] = context->Dim(
shape, GetTensorSpatialDimIndex(rank, format, spatial_dim_index));
}
// Channel.
*filter_dim = context->Dim(shape, GetTensorFeatureDimIndex(rank, format));
if (format == FORMAT_NCHW_VECT_C) {
TF_RETURN_IF_ERROR(context->Multiply(
*filter_dim,
context->Dim(shape, GetTensorInnerFeatureDimIndex(rank, format)),
filter_dim));
}
return Status::OK();
}
Status ShapeFromDimensions(DimensionHandle batch_dim,
gtl::ArraySlice<DimensionHandle> spatial_dims,
DimensionHandle filter_dim, TensorFormat format,
InferenceContext* context, ShapeHandle* shape) {
const int32 rank = GetTensorDimsFromSpatialDims(spatial_dims.size(), format);
std::vector<DimensionHandle> out_dims(rank);
// Batch.
out_dims[tensorflow::GetTensorBatchDimIndex(rank, format)] = batch_dim;
// Spatial.
for (int spatial_dim_index = 0; spatial_dim_index < spatial_dims.size();
++spatial_dim_index) {
out_dims[tensorflow::GetTensorSpatialDimIndex(
rank, format, spatial_dim_index)] = spatial_dims[spatial_dim_index];
}
// Channel.
if (format == tensorflow::FORMAT_NCHW_VECT_C) {
// When format is NCHW_VECT_C, factor the feature map count
// into the outer feature count and the inner feature count (=4).
TF_RETURN_IF_ERROR(context->Divide(
filter_dim, 4, /*evenly_divisible=*/true,
&out_dims[tensorflow::GetTensorFeatureDimIndex(rank, format)]));
out_dims[GetTensorInnerFeatureDimIndex(rank, format)] = context->MakeDim(4);
} else {
out_dims[tensorflow::GetTensorFeatureDimIndex(rank, format)] = filter_dim;
}
*shape = context->MakeShape(out_dims);
return tensorflow::Status::OK();
}
Status Conv2DShape(shape_inference::InferenceContext* c) {
string data_format_str, filter_format_str;
if (!c->GetAttr("data_format", &data_format_str).ok()) {
data_format_str = "NHWC";
}
if (!c->GetAttr("filter_format", &filter_format_str).ok()) {
filter_format_str = "HWIO";
}
TensorFormat data_format;
if (!FormatFromString(data_format_str, &data_format)) {
return errors::InvalidArgument("Invalid data format string: ",
data_format_str);
}
FilterTensorFormat filter_format;
if (!FilterFormatFromString(filter_format_str, &filter_format)) {
return errors::InvalidArgument("Invalid filter format string: ",
filter_format_str);
}
constexpr int num_spatial_dims = 2;
const int rank = GetTensorDimsFromSpatialDims(num_spatial_dims, data_format);
ShapeHandle conv_input_shape;
TF_RETURN_IF_ERROR(c->WithRank(c->input(0), rank, &conv_input_shape));
TF_RETURN_IF_ERROR(CheckFormatConstraintsOnShape(
data_format, conv_input_shape, "conv_input", c));
// The filter rank should match the input (4 for NCHW, 5 for NCHW_VECT_C).
ShapeHandle filter_shape;
TF_RETURN_IF_ERROR(c->WithRank(c->input(1), rank, &filter_shape));
TF_RETURN_IF_ERROR(
CheckFormatConstraintsOnShape(data_format, filter_shape, "filter", c));
std::vector<int32> dilations;
TF_RETURN_IF_ERROR(c->GetAttr("dilations", &dilations));
if (dilations.size() != 4) {
return errors::InvalidArgument(
"Conv2D requires the dilation attribute to contain 4 values, but got: ",
dilations.size());
}
std::vector<int32> strides;
TF_RETURN_IF_ERROR(c->GetAttr("strides", &strides));
// strides.size() should be 4 (NCHW) even if the input is 5 (NCHW_VECT_C).
if (strides.size() != 4) {
return errors::InvalidArgument("Conv2D on data format ", data_format_str,
" requires the stride attribute to contain"
" 4 values, but got: ",
strides.size());
}
const int32 stride_rows = GetTensorDim(strides, data_format, 'H');
const int32 stride_cols = GetTensorDim(strides, data_format, 'W');
const int32 dilation_rows = GetTensorDim(dilations, data_format, 'H');
const int32 dilation_cols = GetTensorDim(dilations, data_format, 'W');
DimensionHandle batch_size_dim;
DimensionHandle input_depth_dim;
gtl::InlinedVector<DimensionHandle, 2> input_spatial_dims(2);
TF_RETURN_IF_ERROR(DimensionsFromShape(conv_input_shape, data_format,
&batch_size_dim, &input_spatial_dims,
&input_depth_dim, c));
DimensionHandle output_depth_dim = c->Dim(
filter_shape, GetFilterDimIndex<num_spatial_dims>(filter_format, 'O'));
DimensionHandle filter_rows_dim = c->Dim(
filter_shape, GetFilterDimIndex<num_spatial_dims>(filter_format, 'H'));
DimensionHandle filter_cols_dim = c->Dim(
filter_shape, GetFilterDimIndex<num_spatial_dims>(filter_format, 'W'));
DimensionHandle filter_input_depth_dim;
if (filter_format == FORMAT_OIHW_VECT_I) {
TF_RETURN_IF_ERROR(c->Multiply(
c->Dim(filter_shape,
GetFilterDimIndex<num_spatial_dims>(filter_format, 'I')),
c->Dim(filter_shape,
GetFilterTensorInnerInputChannelsDimIndex(rank, filter_format)),
&filter_input_depth_dim));
} else {
filter_input_depth_dim = c->Dim(
filter_shape, GetFilterDimIndex<num_spatial_dims>(filter_format, 'I'));
}
// Check that the input tensor and the filter tensor agree on the input
// channel count.
DimensionHandle unused;
TF_RETURN_IF_ERROR(
c->Merge(input_depth_dim, filter_input_depth_dim, &unused));
Padding padding;
TF_RETURN_IF_ERROR(c->GetAttr("padding", &padding));
DimensionHandle output_rows, output_cols;
TF_RETURN_IF_ERROR(GetWindowedOutputSizeFromDimsV2(
c, input_spatial_dims[0], filter_rows_dim, dilation_rows, stride_rows,
padding, &output_rows));
TF_RETURN_IF_ERROR(GetWindowedOutputSizeFromDimsV2(
c, input_spatial_dims[1], filter_cols_dim, dilation_cols, stride_cols,
padding, &output_cols));
ShapeHandle output_shape;
TF_RETURN_IF_ERROR(
ShapeFromDimensions(batch_size_dim, {output_rows, output_cols},
output_depth_dim, data_format, c, &output_shape));
c->set_output(0, output_shape);
return Status::OK();
}
// TODO(mjanusz): Unify all conv/pooling shape functions.
Status Conv3DShape(shape_inference::InferenceContext* c) {
ShapeHandle input_shape;
TF_RETURN_IF_ERROR(c->WithRank(c->input(0), 5, &input_shape));
ShapeHandle filter_shape;
TF_RETURN_IF_ERROR(c->WithRank(c->input(1), 5, &filter_shape));
string data_format;
Status s = c->GetAttr("data_format", &data_format);
std::vector<int32> strides;
TF_RETURN_IF_ERROR(c->GetAttr("strides", &strides));
if (strides.size() != 5) {
return errors::InvalidArgument(
"Conv3D requires the stride attribute to contain 5 values, but got: ",
strides.size());
}
int32 stride_planes, stride_rows, stride_cols;
if (s.ok() && data_format == "NCDHW") {
// Convert input_shape to NDHWC.
auto dim = [&](char dimension) {
return c->Dim(input_shape, GetTensorDimIndex<3>(FORMAT_NCHW, dimension));
};
input_shape =
c->MakeShape({{dim('N'), dim('0'), dim('1'), dim('2'), dim('C')}});
stride_planes = strides[2];
stride_cols = strides[3];
stride_rows = strides[4];
} else {
stride_planes = strides[1];
stride_rows = strides[2];
stride_cols = strides[3];
}
DimensionHandle batch_size_dim = c->Dim(input_shape, 0);
DimensionHandle in_planes_dim = c->Dim(input_shape, 1);
DimensionHandle in_rows_dim = c->Dim(input_shape, 2);
DimensionHandle in_cols_dim = c->Dim(input_shape, 3);
DimensionHandle filter_planes_dim = c->Dim(filter_shape, 0);
DimensionHandle filter_rows_dim = c->Dim(filter_shape, 1);
DimensionHandle filter_cols_dim = c->Dim(filter_shape, 2);
DimensionHandle output_depth_dim = c->Dim(filter_shape, 4);
DimensionHandle unused;
TF_RETURN_IF_ERROR(
c->Merge(c->Dim(input_shape, 4), c->Dim(filter_shape, 3), &unused));
Padding padding;
TF_RETURN_IF_ERROR(c->GetAttr("padding", &padding));
DimensionHandle output_planes, output_rows, output_cols;
TF_RETURN_IF_ERROR(
GetWindowedOutputSizeFromDims(c, in_planes_dim, filter_planes_dim,
stride_planes, padding, &output_planes));
TF_RETURN_IF_ERROR(GetWindowedOutputSizeFromDims(
c, in_rows_dim, filter_rows_dim, stride_rows, padding, &output_rows));
TF_RETURN_IF_ERROR(GetWindowedOutputSizeFromDims(
c, in_cols_dim, filter_cols_dim, stride_cols, padding, &output_cols));
ShapeHandle output_shape;
if (data_format == "NCDHW") {
output_shape = c->MakeShape({batch_size_dim, output_depth_dim,
output_planes, output_rows, output_cols});
} else {
output_shape = c->MakeShape({batch_size_dim, output_planes, output_rows,
output_cols, output_depth_dim});
}
c->set_output(0, output_shape);
return Status::OK();
}
Status DepthwiseConv2DNativeShape(shape_inference::InferenceContext* c) {
ShapeHandle input_shape;
TF_RETURN_IF_ERROR(c->WithRank(c->input(0), 4, &input_shape));
ShapeHandle filter_shape;
TF_RETURN_IF_ERROR(c->WithRank(c->input(1), 4, &filter_shape));
std::vector<int32> strides;
TF_RETURN_IF_ERROR(c->GetAttr("strides", &strides));
if (strides.size() != 4) {
return errors::InvalidArgument(
"DepthwiseConv2D requires the stride attribute to contain 4 values, "
"but got: ",
strides.size());
}
string data_format;
Status s = c->GetAttr("data_format", &data_format);
int32 stride_rows;
int32 stride_cols;
if (s.ok() && data_format == "NCHW") {
// Canonicalize input shape to NHWC so the shape inference code below can
// process it.
input_shape =
c->MakeShape({{c->Dim(input_shape, 0), c->Dim(input_shape, 2),
c->Dim(input_shape, 3), c->Dim(input_shape, 1)}});
stride_rows = strides[2];
stride_cols = strides[3];
} else {
stride_rows = strides[1];
stride_cols = strides[2];
}
DimensionHandle batch_size_dim = c->Dim(input_shape, 0);
DimensionHandle in_rows_dim = c->Dim(input_shape, 1);
DimensionHandle in_cols_dim = c->Dim(input_shape, 2);
DimensionHandle filter_rows_dim = c->Dim(filter_shape, 0);
DimensionHandle filter_cols_dim = c->Dim(filter_shape, 1);
DimensionHandle input_depth = c->Dim(filter_shape, 2);
DimensionHandle depth_multiplier = c->Dim(filter_shape, 3);
// Check that the input depths are compatible.
TF_RETURN_IF_ERROR(
c->Merge(c->Dim(input_shape, 3), input_depth, &input_depth));
DimensionHandle output_depth;
TF_RETURN_IF_ERROR(c->Multiply(input_depth, depth_multiplier, &output_depth));
Padding padding;
TF_RETURN_IF_ERROR(c->GetAttr("padding", &padding));
// TODO(mrry,shlens): Raise an error if the stride would cause
// information in the input to be ignored. This will require a change
// in the kernel implementation.
DimensionHandle output_rows, output_cols;
TF_RETURN_IF_ERROR(GetWindowedOutputSizeFromDims(
c, in_rows_dim, filter_rows_dim, stride_rows, padding, &output_rows));
TF_RETURN_IF_ERROR(GetWindowedOutputSizeFromDims(
c, in_cols_dim, filter_cols_dim, stride_cols, padding, &output_cols));
ShapeHandle output_shape;
if (data_format == "NCHW") {
output_shape =
c->MakeShape({batch_size_dim, output_depth, output_rows, output_cols});
} else {
output_shape =
c->MakeShape({batch_size_dim, output_rows, output_cols, output_depth});
}
c->set_output(0, output_shape);
return Status::OK();
}
Status AvgPoolShape(shape_inference::InferenceContext* c) {
string data_format_str;
TensorFormat data_format;
Status s = c->GetAttr("data_format", &data_format_str);
if (s.ok()) {
FormatFromString(data_format_str, &data_format);
} else {
data_format = FORMAT_NHWC;
}
const int rank = (data_format == FORMAT_NCHW_VECT_C) ? 5 : 4;
ShapeHandle input_shape;
TF_RETURN_IF_ERROR(c->WithRank(c->input(0), rank, &input_shape));
TF_RETURN_IF_ERROR(
CheckFormatConstraintsOnShape(data_format, input_shape, "input", c));
std::vector<int32> strides;
TF_RETURN_IF_ERROR(c->GetAttr("strides", &strides));
if (strides.size() != 4) {
return errors::InvalidArgument(
"AvgPool requires the stride attribute to contain 4 values, but got: ",
strides.size());
}
std::vector<int32> kernel_sizes;
TF_RETURN_IF_ERROR(c->GetAttr("ksize", &kernel_sizes));
if (kernel_sizes.size() != 4) {
return errors::InvalidArgument(
"AvgPool requires the ksize attribute to contain 4 values, but got: ",
kernel_sizes.size());
}
int32 stride_rows = GetTensorDim(strides, data_format, 'H');
int32 stride_cols = GetTensorDim(strides, data_format, 'W');
int32 kernel_rows = GetTensorDim(kernel_sizes, data_format, 'H');
int32 kernel_cols = GetTensorDim(kernel_sizes, data_format, 'W');
constexpr int num_spatial_dims = 2;
DimensionHandle batch_size_dim = c->Dim(
input_shape, GetTensorDimIndex<num_spatial_dims>(data_format, 'N'));
DimensionHandle in_rows_dim = c->Dim(
input_shape, GetTensorDimIndex<num_spatial_dims>(data_format, 'H'));
DimensionHandle in_cols_dim = c->Dim(
input_shape, GetTensorDimIndex<num_spatial_dims>(data_format, 'W'));
DimensionHandle depth_dim = c->Dim(
input_shape, GetTensorDimIndex<num_spatial_dims>(data_format, 'C'));
Padding padding;
TF_RETURN_IF_ERROR(c->GetAttr("padding", &padding));
// TODO(mrry,shlens): Raise an error if the stride would cause
// information in the input to be ignored. This will require a change
// in the kernel implementation.
DimensionHandle output_rows, output_cols;
TF_RETURN_IF_ERROR(GetWindowedOutputSizeFromDims(
c, in_rows_dim, kernel_rows, stride_rows, padding, &output_rows));
TF_RETURN_IF_ERROR(GetWindowedOutputSizeFromDims(
c, in_cols_dim, kernel_cols, stride_cols, padding, &output_cols));
ShapeHandle output_shape;
TF_RETURN_IF_ERROR(MakeShapeFromFormat(data_format, batch_size_dim,
{output_rows, output_cols}, depth_dim,
&output_shape, c));
c->set_output(0, output_shape);
return Status::OK();
}
Status FusedBatchNormShape(shape_inference::InferenceContext* c) {
ShapeHandle x;
TF_RETURN_IF_ERROR(c->WithRank(c->input(0), 4, &x));
bool is_training;
TF_RETURN_IF_ERROR(c->GetAttr("is_training", &is_training));
int number_inputs = (is_training) ? 3 : 5;
string data_format;
TF_RETURN_IF_ERROR(c->GetAttr("data_format", &data_format));
DimensionHandle channel_dim =
(data_format == "NHWC") ? c->Dim(x, 3) : c->Dim(x, 1);
// covers scale, offset, and if is_training is false, mean, variance
for (int i = 1; i < number_inputs; ++i) {
ShapeHandle vec;
TF_RETURN_IF_ERROR(c->WithRank(c->input(i), 1, &vec));
TF_RETURN_IF_ERROR(c->Merge(channel_dim, c->Dim(vec, 0), &channel_dim));
}
ShapeHandle y;
if (data_format == "NHWC") {
TF_RETURN_IF_ERROR(c->ReplaceDim(x, 3, channel_dim, &y));
} else {
TF_RETURN_IF_ERROR(c->ReplaceDim(x, 1, channel_dim, &y));
}
c->set_output(0, y);
ShapeHandle vector_shape = c->Vector(channel_dim);
c->set_output(1, vector_shape);
c->set_output(2, vector_shape);
c->set_output(3, vector_shape);
c->set_output(4, vector_shape);
return Status::OK();
}
Status FusedBatchNormGradShape(shape_inference::InferenceContext* c) {
ShapeHandle y_backprop;
TF_RETURN_IF_ERROR(c->WithRank(c->input(0), 4, &y_backprop));
ShapeHandle x;
TF_RETURN_IF_ERROR(c->WithRank(c->input(1), 4, &x));
bool is_training;
string data_format;
TF_RETURN_IF_ERROR(c->GetAttr("is_training", &is_training));
TF_RETURN_IF_ERROR(c->GetAttr("data_format", &data_format));
DimensionHandle channel_dim =
(data_format == "NHWC") ? c->Dim(y_backprop, 3) : c->Dim(y_backprop, 1);
if (data_format == "NHWC") {
TF_RETURN_IF_ERROR(c->Merge(channel_dim, c->Dim(x, 3), &channel_dim));
} else {
TF_RETURN_IF_ERROR(c->Merge(channel_dim, c->Dim(x, 1), &channel_dim));
}
// covers scale, mean (reserve_space_1), variance (reserve_space_2)
for (int i = 2; i < 5; ++i) {
ShapeHandle vec;
TF_RETURN_IF_ERROR(c->WithRank(c->input(i), 1, &vec));
TF_RETURN_IF_ERROR(c->Merge(channel_dim, c->Dim(vec, 0), &channel_dim));
}
ShapeHandle x_backprop;
if (data_format == "NHWC") {
TF_RETURN_IF_ERROR(c->ReplaceDim(y_backprop, 3, channel_dim, &x_backprop));
} else {
TF_RETURN_IF_ERROR(c->ReplaceDim(y_backprop, 1, channel_dim, &x_backprop));
}
c->set_output(0, x_backprop);
c->set_output(1, c->Vector(channel_dim));
c->set_output(2, c->Vector(channel_dim));
// Set the correct shapes for reserve_spaces
// so that gradients can be performed when
// the op is in a symbolic condition.
if (is_training) {
c->set_output(3, c->Vector(0));
c->set_output(4, c->Vector(0));
} else {
c->set_output(3, c->Vector(channel_dim));
c->set_output(4, c->Vector(channel_dim));
}
return Status::OK();
}
Status MaxPoolShape(shape_inference::InferenceContext* c) {
string data_format_str;
TensorFormat data_format;
Status s = c->GetAttr("data_format", &data_format_str);
if (s.ok()) {
FormatFromString(data_format_str, &data_format);
} else {
data_format = FORMAT_NHWC;
}
const int rank = (data_format == FORMAT_NCHW_VECT_C) ? 5 : 4;
ShapeHandle input_shape;
TF_RETURN_IF_ERROR(c->WithRank(c->input(0), rank, &input_shape));
TF_RETURN_IF_ERROR(
CheckFormatConstraintsOnShape(data_format, input_shape, "input", c));
std::vector<int32> strides;
TF_RETURN_IF_ERROR(c->GetAttr("strides", &strides));
if (strides.size() != 4) {
return errors::InvalidArgument(
"MaxPool requires the stride attribute to contain 4 values, but got: ",
strides.size());
}
std::vector<int32> kernel_sizes;
TF_RETURN_IF_ERROR(c->GetAttr("ksize", &kernel_sizes));
if (kernel_sizes.size() != 4) {
return errors::InvalidArgument(
"MaxPool requires the ksize attribute to contain 4 values, but got: ",
kernel_sizes.size());
}
int32 stride_depth = GetTensorDim(strides, data_format, 'C');
int32 stride_rows = GetTensorDim(strides, data_format, 'H');
int32 stride_cols = GetTensorDim(strides, data_format, 'W');
int32 kernel_depth = GetTensorDim(kernel_sizes, data_format, 'C');
int32 kernel_rows = GetTensorDim(kernel_sizes, data_format, 'H');
int32 kernel_cols = GetTensorDim(kernel_sizes, data_format, 'W');
constexpr int num_spatial_dims = 2;
DimensionHandle batch_size_dim = c->Dim(
input_shape, GetTensorDimIndex<num_spatial_dims>(data_format, 'N'));
DimensionHandle in_rows_dim = c->Dim(
input_shape, GetTensorDimIndex<num_spatial_dims>(data_format, 'H'));
DimensionHandle in_cols_dim = c->Dim(
input_shape, GetTensorDimIndex<num_spatial_dims>(data_format, 'W'));
DimensionHandle in_depth_dim = c->Dim(
input_shape, GetTensorDimIndex<num_spatial_dims>(data_format, 'C'));
Padding padding;
TF_RETURN_IF_ERROR(c->GetAttr("padding", &padding));
ShapeHandle output_shape;
DimensionHandle output_rows, output_cols, output_depth;
TF_RETURN_IF_ERROR(GetWindowedOutputSizeFromDims(
c, in_rows_dim, kernel_rows, stride_rows, padding, &output_rows));
TF_RETURN_IF_ERROR(GetWindowedOutputSizeFromDims(
c, in_cols_dim, kernel_cols, stride_cols, padding, &output_cols));
TF_RETURN_IF_ERROR(GetWindowedOutputSizeFromDims(
c, in_depth_dim, kernel_depth, stride_depth, padding, &output_depth));
TF_RETURN_IF_ERROR(MakeShapeFromFormat(data_format, batch_size_dim,
{output_rows, output_cols},
output_depth, &output_shape, c));
c->set_output(0, output_shape);
return Status::OK();
}
Status MaxPoolV2Shape(shape_inference::InferenceContext* c, int num_inputs) {
string data_format_str;
TensorFormat data_format;
Status s = c->GetAttr("data_format", &data_format_str);
if (s.ok()) {
FormatFromString(data_format_str, &data_format);
} else {
data_format = FORMAT_NHWC;
}
const int rank = (data_format == FORMAT_NCHW_VECT_C) ? 5 : 4;
ShapeHandle input_shape;
TF_RETURN_IF_ERROR(c->WithRank(c->input(0), rank, &input_shape));
TF_RETURN_IF_ERROR(
CheckFormatConstraintsOnShape(data_format, input_shape, "input", c));
std::vector<int32> kernel_sizes;
std::vector<int32> strides;
if (c->num_inputs() + 2 == num_inputs) {
TF_RETURN_IF_ERROR(c->GetAttr("ksize", &kernel_sizes));
TF_RETURN_IF_ERROR(c->GetAttr("strides", &strides));
} else {
// Verify shape of ksize and strides input.
ShapeHandle size;
DimensionHandle unused;
TF_RETURN_IF_ERROR(c->WithRank(c->input(c->num_inputs() - 2), 1, &size));
TF_RETURN_IF_ERROR(c->WithValue(c->Dim(size, 0), 4, &unused));
TF_RETURN_IF_ERROR(c->WithRank(c->input(c->num_inputs() - 1), 1, &size));
TF_RETURN_IF_ERROR(c->WithValue(c->Dim(size, 0), 4, &unused));
const Tensor* kernel_sizes_tensor = c->input_tensor(c->num_inputs() - 2);
if (kernel_sizes_tensor == nullptr) {
c->set_output(0, c->UnknownShape());
return Status::OK();
}
kernel_sizes.resize(kernel_sizes_tensor->shape().num_elements());
auto kernel_sizes_vec = kernel_sizes_tensor->flat<int32>();
std::copy_n(&kernel_sizes_vec(0), kernel_sizes.size(),
kernel_sizes.begin());
const Tensor* strides_tensor = c->input_tensor(c->num_inputs() - 1);
if (strides_tensor == nullptr) {
c->set_output(0, c->UnknownShape());
return Status::OK();
}
strides.resize(strides_tensor->shape().num_elements());
auto strides_vec = strides_tensor->flat<int32>();
std::copy_n(&strides_vec(0), strides.size(), strides.begin());
}
if (strides.size() != 4) {
return errors::InvalidArgument(
"MaxPool requires the stride attribute to contain 4 values, but "
"got: ",
strides.size());
}
if (kernel_sizes.size() != 4) {
return errors::InvalidArgument(
"MaxPool requires the ksize attribute to contain 4 values, but got: ",
kernel_sizes.size());
}
int32 stride_depth = GetTensorDim(strides, data_format, 'C');
int32 stride_rows = GetTensorDim(strides, data_format, 'H');
int32 stride_cols = GetTensorDim(strides, data_format, 'W');
int32 kernel_depth = GetTensorDim(kernel_sizes, data_format, 'C');
int32 kernel_rows = GetTensorDim(kernel_sizes, data_format, 'H');
int32 kernel_cols = GetTensorDim(kernel_sizes, data_format, 'W');
constexpr int num_spatial_dims = 2;
DimensionHandle batch_size_dim = c->Dim(
input_shape, GetTensorDimIndex<num_spatial_dims>(data_format, 'N'));
DimensionHandle in_rows_dim = c->Dim(
input_shape, GetTensorDimIndex<num_spatial_dims>(data_format, 'H'));
DimensionHandle in_cols_dim = c->Dim(
input_shape, GetTensorDimIndex<num_spatial_dims>(data_format, 'W'));
DimensionHandle in_depth_dim = c->Dim(
input_shape, GetTensorDimIndex<num_spatial_dims>(data_format, 'C'));
Padding padding;
TF_RETURN_IF_ERROR(c->GetAttr("padding", &padding));
ShapeHandle output_shape;
DimensionHandle output_rows, output_cols, output_depth;
TF_RETURN_IF_ERROR(GetWindowedOutputSizeFromDims(
c, in_rows_dim, kernel_rows, stride_rows, padding, &output_rows));
TF_RETURN_IF_ERROR(GetWindowedOutputSizeFromDims(
c, in_cols_dim, kernel_cols, stride_cols, padding, &output_cols));
TF_RETURN_IF_ERROR(GetWindowedOutputSizeFromDims(
c, in_depth_dim, kernel_depth, stride_depth, padding, &output_depth));
TF_RETURN_IF_ERROR(MakeShapeFromFormat(data_format, batch_size_dim,
{output_rows, output_cols},
output_depth, &output_shape, c));
c->set_output(0, output_shape);
return Status::OK();
}
Status Pool3DShape(shape_inference::InferenceContext* c) {
ShapeHandle input_shape;
TF_RETURN_IF_ERROR(c->WithRank(c->input(0), 5, &input_shape));
string data_format;
Status s = c->GetAttr("data_format", &data_format);
std::vector<int32> strides;
TF_RETURN_IF_ERROR(c->GetAttr("strides", &strides));
if (strides.size() != 5) {
return errors::InvalidArgument(
"Pool3D ops require the stride attribute to contain 5 values, but "
"got: ",
strides.size());
}
std::vector<int32> kernel_sizes;
TF_RETURN_IF_ERROR(c->GetAttr("ksize", &kernel_sizes));
if (kernel_sizes.size() != 5) {
return errors::InvalidArgument(
"Pool3D requires the ksize attribute to contain 5 values, but got: ",
kernel_sizes.size());
}
int32 stride_planes, stride_rows, stride_cols;
int32 kernel_planes, kernel_rows, kernel_cols;
if (s.ok() && data_format == "NCDHW") {
// Convert input_shape to NDHWC.
auto dim = [&](char dimension) {
return c->Dim(input_shape, GetTensorDimIndex<3>(FORMAT_NCHW, dimension));
};
input_shape =
c->MakeShape({{dim('N'), dim('0'), dim('1'), dim('2'), dim('C')}});
stride_planes = strides[2];
stride_rows = strides[3];
stride_cols = strides[4];
kernel_planes = kernel_sizes[2];
kernel_rows = kernel_sizes[3];
kernel_cols = kernel_sizes[4];
} else {
stride_planes = strides[1];
stride_rows = strides[2];
stride_cols = strides[3];
kernel_planes = kernel_sizes[1];
kernel_rows = kernel_sizes[2];
kernel_cols = kernel_sizes[3];
}
DimensionHandle batch_size_dim = c->Dim(input_shape, 0);
DimensionHandle in_planes_dim = c->Dim(input_shape, 1);
DimensionHandle in_rows_dim = c->Dim(input_shape, 2);
DimensionHandle in_cols_dim = c->Dim(input_shape, 3);
DimensionHandle output_depth_dim = c->Dim(input_shape, 4);
Padding padding;