-
Notifications
You must be signed in to change notification settings - Fork 74k
/
array_ops.cc
3455 lines (3120 loc) · 120 KB
/
array_ops.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 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.
==============================================================================*/
#include <algorithm>
#include <ostream>
#include "tensorflow/core/framework/common_shape_fns.h"
#include "tensorflow/core/framework/kernel_shape_util.h"
#include "tensorflow/core/framework/op.h"
#include "tensorflow/core/framework/shape_inference.h"
#include "tensorflow/core/framework/tensor.pb.h"
#include "tensorflow/core/framework/types.h"
#include "tensorflow/core/framework/types.pb.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/platform/types.h"
#include "tensorflow/core/util/mirror_pad_mode.h"
#include "tensorflow/core/util/padding.h"
#include "tensorflow/core/util/strided_slice_op.h"
#include "tensorflow/core/util/tensor_format.h"
namespace tensorflow {
using shape_inference::DimensionHandle;
using shape_inference::InferenceContext;
using shape_inference::ShapeHandle;
using shape_inference::UnchangedShape;
namespace {
Status GetAxisForPackAndUnpack(InferenceContext* c, int32_t rank_after_pack,
int32* axis) {
TF_RETURN_IF_ERROR(c->GetAttr("axis", axis));
if (*axis < -1 * rank_after_pack || *axis >= rank_after_pack) {
return errors::InvalidArgument("Invalid axis: ", *axis, "; must be in [",
-1 * rank_after_pack, ",", rank_after_pack,
")");
}
if (*axis < 0) *axis = (rank_after_pack + *axis);
return OkStatus();
}
template <typename T>
std::vector<int64_t> AsInt64(const Tensor* tensor, int64_t num_elements) {
std::vector<int64_t> ret(num_elements);
auto data = tensor->vec<T>();
for (int64_t i = 0; i < num_elements; ++i) {
ret[i] = data(i);
}
return ret;
}
template <typename T>
Status PadKnown(InferenceContext* c, ShapeHandle input,
const Tensor* paddings_t, int64_t num_dims) {
// paddings_t is known.
std::vector<DimensionHandle> dims(num_dims);
auto paddings_data = paddings_t->matrix<T>();
for (int64_t i = 0; i < num_dims; ++i) {
const T pad0 = paddings_data(i, 0);
const T pad1 = paddings_data(i, 1);
if (pad0 < 0 || pad1 < 0) {
return errors::InvalidArgument("Paddings must be non-negative");
}
TF_RETURN_IF_ERROR(c->Add(c->Dim(input, i), pad0 + pad1, &dims[i]));
}
c->set_output(0, c->MakeShape(dims));
return OkStatus();
}
Status PadShapeFn(InferenceContext* c) {
// Paddings is a matrix of [input_rank, 2].
ShapeHandle paddings;
TF_RETURN_IF_ERROR(c->WithRank(c->input(1), 2, &paddings));
DimensionHandle unused;
TF_RETURN_IF_ERROR(c->WithValue(c->Dim(paddings, 1), 2, &unused));
// n_dim and input.rank are equivalent.
ShapeHandle input = c->input(0);
DimensionHandle n_dim = c->Dim(paddings, 0);
if (c->ValueKnown(n_dim)) {
TF_RETURN_IF_ERROR(c->WithRank(input, c->Value(n_dim), &input));
} else if (c->RankKnown(input)) {
TF_RETURN_IF_ERROR(c->WithValue(n_dim, c->Rank(input), &n_dim));
}
const Tensor* paddings_t = c->input_tensor(1);
// paddings_t is unknown
if (paddings_t == nullptr) {
if (c->ValueKnown(n_dim)) {
// Make output with n_dim unknown dims.
c->set_output(0, c->UnknownShapeOfRank(c->Value(n_dim)));
} else {
c->set_output(0, c->UnknownShape());
}
return OkStatus();
}
const int64_t num_dims = paddings_t->shape().dim_size(0);
TF_RETURN_IF_ERROR(c->WithRank(input, num_dims, &input));
TF_RETURN_IF_ERROR(c->WithValue(n_dim, num_dims, &n_dim));
if (paddings_t->dtype() == DT_INT32) {
return PadKnown<int32>(c, input, paddings_t, num_dims);
} else {
return PadKnown<int64_t>(c, input, paddings_t, num_dims);
}
}
Status TransposeShapeFn(InferenceContext* c) {
ShapeHandle input = c->input(0);
ShapeHandle perm_shape = c->input(1);
const Tensor* perm = c->input_tensor(1);
DimensionHandle perm_elems = c->NumElements(perm_shape);
// If we don't have rank information on the input or value information on
// perm we can't return any shape information, otherwise we have enough
// information to at least find the rank of the output.
if (!c->RankKnown(input) && !c->ValueKnown(perm_elems) && perm == nullptr) {
c->set_output(0, c->UnknownShape());
return OkStatus();
}
// Find our value of the rank.
int64_t rank;
if (c->RankKnown(input)) {
rank = c->Rank(input);
} else if (c->ValueKnown(perm_elems)) {
rank = c->Value(perm_elems);
} else {
rank = perm->NumElements();
}
if (!c->RankKnown(input) && rank < 2) {
// A permutation array containing a single element is ambiguous. It could
// indicate either a scalar or a 1-dimensional array, both of which the
// transpose op returns unchanged.
c->set_output(0, input);
return OkStatus();
}
std::vector<DimensionHandle> dims;
dims.resize(rank);
TF_RETURN_IF_ERROR(c->WithRank(input, rank, &input));
// Ensure that perm is a vector and has rank elements.
TF_RETURN_IF_ERROR(c->WithRank(perm_shape, 1, &perm_shape));
TF_RETURN_IF_ERROR(c->WithValue(perm_elems, rank, &perm_elems));
// If we know the rank of the input and the value of perm, we can return
// all shape information, otherwise we can only return rank information,
// but no information for the dimensions.
if (perm != nullptr) {
std::vector<int64_t> data;
if (perm->dtype() == DT_INT32) {
data = AsInt64<int32>(perm, rank);
} else {
data = AsInt64<int64_t>(perm, rank);
}
for (int32_t i = 0; i < rank; ++i) {
int64_t in_idx = data[i];
if (in_idx >= rank || in_idx <= -rank) {
return errors::InvalidArgument("perm dim ", in_idx,
" is out of range of input rank ", rank);
}
dims[i] = c->Dim(input, in_idx);
}
} else {
for (int i = 0; i < rank; ++i) {
dims[i] = c->UnknownDim();
}
}
c->set_output(0, c->MakeShape(dims));
return OkStatus();
}
Status SetOutputShapeForReshape(InferenceContext* c) {
ShapeHandle in = c->input(0);
ShapeHandle out;
TF_RETURN_IF_ERROR(c->MakeShapeFromShapeTensor(1, &out));
if (!c->RankKnown(out)) {
// We have no information about the shape of the output.
c->set_output(0, out);
return OkStatus();
}
if (c->RankKnown(in)) {
// We don't know the number of output elements, but we can try to infer
// the missing dimension.
bool too_many_unknown = false;
int32_t out_unknown_idx = -1;
DimensionHandle known_out_elems = c->NumElements(out);
if (!c->ValueKnown(known_out_elems)) {
known_out_elems = c->MakeDim(1);
for (int32_t i = 0; i < c->Rank(out); ++i) {
DimensionHandle dim = c->Dim(out, i);
if (!c->ValueKnown(dim)) {
if (out_unknown_idx >= 0) {
too_many_unknown = true;
break;
}
out_unknown_idx = i;
} else {
TF_RETURN_IF_ERROR(
c->Multiply(known_out_elems, dim, &known_out_elems));
}
}
}
int32_t in_unknown_idx = -1;
DimensionHandle known_in_elems = c->NumElements(in);
if (!c->ValueKnown(known_in_elems)) {
known_in_elems = c->MakeDim(1);
for (int32_t i = 0; i < c->Rank(in); ++i) {
DimensionHandle dim = c->Dim(in, i);
if (!c->ValueKnown(dim)) {
if (in_unknown_idx >= 0) {
too_many_unknown = true;
break;
}
in_unknown_idx = i;
} else {
TF_RETURN_IF_ERROR(c->Multiply(known_in_elems, dim, &known_in_elems));
}
}
}
if (!too_many_unknown) {
if (in_unknown_idx < 0 && out_unknown_idx < 0) {
// Just check that the dimensions match.
if (c->Value(known_in_elems) != c->Value(known_out_elems)) {
return errors::InvalidArgument(
"Cannot reshape a tensor with ", c->DebugString(known_in_elems),
" elements to shape ", c->DebugString(out), " (",
c->DebugString(known_out_elems), " elements)");
}
} else if (in_unknown_idx < 0 && out_unknown_idx >= 0 &&
c->Value(known_out_elems) > 0) {
// Input fully known, infer the one missing output dim
DimensionHandle inferred_dim;
TF_RETURN_IF_ERROR(c->Divide(known_in_elems, c->Value(known_out_elems),
true /* evenly_divisible */,
&inferred_dim));
TF_RETURN_IF_ERROR(
c->ReplaceDim(out, out_unknown_idx, inferred_dim, &out));
} else if (in_unknown_idx >= 0 && out_unknown_idx < 0 &&
c->Value(known_in_elems) != 0) {
// Output fully known, infer the one missing input dim
DimensionHandle inferred_dim;
TF_RETURN_IF_ERROR(c->Divide(known_out_elems, c->Value(known_in_elems),
true /* evenly_divisible */,
&inferred_dim));
DimensionHandle unknown_in_dim = c->Dim(in, in_unknown_idx);
TF_RETURN_IF_ERROR(
c->Merge(unknown_in_dim, inferred_dim, &unknown_in_dim));
} else if (in_unknown_idx >= 0 && out_unknown_idx >= 0) {
// Exactly one unknown dimension in both input and output. These 2 are
// equal iff the known elements are equal.
if (c->Value(known_in_elems) == c->Value(known_out_elems)) {
DimensionHandle unknown_in_dim = c->Dim(in, in_unknown_idx);
TF_RETURN_IF_ERROR(
c->ReplaceDim(out, out_unknown_idx, unknown_in_dim, &out));
}
}
}
}
c->set_output(0, out);
return OkStatus();
}
} // namespace
REGISTER_OP("ParallelConcat")
.Input("values: N * T")
.Output("output: T")
.Attr("N: int >= 1")
.Attr("T: type")
.Attr("shape: shape")
.SetShapeFn([](InferenceContext* c) {
// Validate that the shape attr is correct.
PartialTensorShape shape;
TF_RETURN_IF_ERROR(c->GetAttr("shape", &shape));
ShapeHandle passed_shape;
TF_RETURN_IF_ERROR(
c->MakeShapeFromPartialTensorShape(shape, &passed_shape));
if (!c->FullyDefined(passed_shape)) {
return errors::InvalidArgument("shape attr must be fully defined.");
}
ShapeHandle cur;
TF_RETURN_IF_ERROR(c->ReplaceDim(
passed_shape, 0, c->MakeDim(shape_inference::DimensionOrConstant(1)),
&cur));
for (int i = 0; i < c->num_inputs(); ++i) {
if (!c->FullyDefined(c->input(i))) {
return errors::InvalidArgument(
"All input shapes must be fully defined.");
}
DimensionHandle unused;
if (!c->WithValue(c->Dim(c->input(i), 0), 1, &unused).ok()) {
return errors::InvalidArgument("Size of first dimension must be 1.");
}
TF_RETURN_WITH_CONTEXT_IF_ERROR(c->Merge(c->input(i), cur, &cur),
"From merging shape ", i,
" with other shapes.");
}
c->set_output(0, passed_shape);
return OkStatus();
});
REGISTER_OP("Pack")
.Input("values: N * T")
.Output("output: T")
.Attr("N: int >= 1")
.Attr("T: type")
.Attr("axis: int = 0")
.SetShapeFn([](InferenceContext* c) {
// Validate shapes of all inputs are compatible
ShapeHandle cur = c->input(c->num_inputs() - 1);
for (int i = c->num_inputs() - 2; i >= 0; --i) {
TF_RETURN_WITH_CONTEXT_IF_ERROR(c->Merge(c->input(i), cur, &cur),
"From merging shape ", i,
" with other shapes.");
}
if (!c->RankKnown(cur)) {
c->set_output(0, c->UnknownShape());
return OkStatus();
}
// Determine the axis that will be added, converting from negative
// axes to a positive point per negative indexing rules.
int32_t rank = c->Rank(cur);
int32_t axis;
TF_RETURN_IF_ERROR(GetAxisForPackAndUnpack(c, rank + 1, &axis));
// Copy all dimensions over, inserting a dimension of value #inputs
// at <axis>.
std::vector<DimensionHandle> dims;
int index = 0;
while (index < axis) dims.push_back(c->Dim(cur, index++));
dims.push_back(c->MakeDim(c->num_inputs()));
while (index < rank) dims.push_back(c->Dim(cur, index++));
c->set_output(0, c->MakeShape(dims));
for (int i = 0; i < c->num_inputs(); ++i) {
auto* shape_and_type = c->input_handle_shapes_and_types(i);
if (shape_and_type) {
if (!c->RelaxOutputHandleShapesAndMergeTypes(0, *shape_and_type)) {
c->set_output_handle_shapes_and_types(
0, std::vector<shape_inference::ShapeAndType>({}));
break;
}
}
}
return OkStatus();
});
REGISTER_OP("DeepCopy")
.Input("x: T")
.Output("y: T")
.Attr("T: type")
.SetIsStateful()
.SetShapeFn(UnchangedShape);
REGISTER_OP("InplaceUpdate")
.Input("x: T")
.Input("i: int32")
.Input("v: T")
.Output("y: T")
.Attr("T: type")
.SetShapeFn(UnchangedShape);
REGISTER_OP("InplaceAdd")
.Input("x: T")
.Input("i: int32")
.Input("v: T")
.Output("y: T")
.Attr("T: type")
.SetShapeFn(UnchangedShape);
REGISTER_OP("InplaceSub")
.Input("x: T")
.Input("i: int32")
.Input("v: T")
.Output("y: T")
.Attr("T: type")
.SetShapeFn(UnchangedShape);
REGISTER_OP("Empty")
.Input("shape: int32")
.Output("output: dtype")
.Attr("dtype: type")
.Attr("init: bool = false")
.SetDoNotOptimize()
.SetShapeFn([](InferenceContext* c) {
ShapeHandle out;
TF_RETURN_IF_ERROR(c->MakeShapeFromShapeTensor(0, &out));
c->set_output(0, out);
return OkStatus();
});
// --------------------------------------------------------------------------
REGISTER_OP("Unpack")
.Input("value: T")
.Output("output: num * T")
.Attr("num: int >= 0")
.Attr("T: type")
.Attr("axis: int = 0")
.SetShapeFn([](InferenceContext* c) {
ShapeHandle s = c->input(0);
ShapeHandle out;
if (c->RankKnown(s)) {
// Determine the axis that will be removed, converting from negative
// axes to a positive point per negative indexing rules.
int32_t rank = c->Rank(s);
int32_t axis;
TF_RETURN_IF_ERROR(GetAxisForPackAndUnpack(c, rank, &axis));
// The axis dim matches the number of outputs.
DimensionHandle unused;
TF_RETURN_IF_ERROR(
c->WithValue(c->Dim(s, axis), c->num_outputs(), &unused));
// Copy all dimensions, removing the <axis> dimension.
std::vector<DimensionHandle> dims;
for (int i = 0; i < rank; ++i) {
if (i != axis) dims.push_back(c->Dim(s, i));
}
out = c->MakeShape(dims);
} else {
// All outputs are the same shape, but it's not known.
out = c->UnknownShape();
}
for (int i = 0; i < c->num_outputs(); ++i) c->set_output(i, out);
return OkStatus();
});
REGISTER_OP("UnravelIndex")
.Input("indices: Tidx")
.Input("dims: Tidx")
.Output("output: Tidx")
.Attr("Tidx: {int32, int64} = DT_INT32")
.SetShapeFn([](InferenceContext* c) {
ShapeHandle indices = c->input(0);
ShapeHandle dims;
TF_RETURN_IF_ERROR(c->WithRank(c->input(1), 1, &dims));
if (c->RankKnown(indices) && c->Rank(indices) == 0) {
c->set_output(0, c->Vector(c->Dim(dims, 0)));
} else if (c->RankKnown(indices)) {
c->set_output(0, c->Matrix(c->Dim(dims, 0), c->NumElements(indices)));
} else {
c->set_output(0, c->UnknownShape());
}
return OkStatus();
});
REGISTER_OP("BroadcastTo")
.Input("input: T")
.Input("shape: Tidx")
.Output("output: T")
.Attr("T: type")
.Attr("Tidx: {int32, int64} = DT_INT32")
.SetShapeFn([](InferenceContext* c) {
ShapeHandle shape_in = c->input(1);
TF_RETURN_IF_ERROR(c->WithRank(shape_in, 1, &shape_in));
ShapeHandle out;
TF_RETURN_IF_ERROR(c->MakeShapeFromShapeTensor(1, &out));
if (!c->RankKnown(out)) {
// We have no information about the shape of the output.
c->set_output(0, out);
return OkStatus();
}
ShapeHandle in = c->input(0);
if (!c->RankKnown(in)) {
// We have no information about the shape of the input,
// nothing to do here.
c->set_output(0, out);
return OkStatus();
}
int out_rank = c->Rank(out);
TF_RETURN_IF_ERROR(c->WithRankAtMost(in, out_rank, &in));
int in_rank = c->Rank(in);
for (int i = 0; i < in_rank; ++i) {
auto in_dim = c->Dim(in, in_rank - i - 1);
if (c->Value(in_dim) > 1) {
// If the input dimension is greater than 1 then the output dimension
// must be equal to it, since we only broadcast "from left to right".
auto out_dim = c->Dim(out, out_rank - i - 1);
TF_RETURN_IF_ERROR(c->Merge(in_dim, out_dim, &out_dim));
TF_RETURN_IF_ERROR(
c->ReplaceDim(out, out_rank - i - 1, out_dim, &out));
}
}
c->set_output(0, out);
return OkStatus();
});
// --------------------------------------------------------------------------
// TODO(josh11b): Remove the >= 2 constraint, once we can rewrite the graph
// in the N == 1 case to remove the node.
REGISTER_OP("Concat")
.Input("concat_dim: int32")
.Input("values: N * T")
.Output("output: T")
.Attr("N: int >= 2")
.Attr("T: type")
.SetShapeFn([](InferenceContext* c) {
return shape_inference::ConcatShape(c, c->num_inputs() - 1);
});
REGISTER_OP("ConcatV2")
.Input("values: N * T")
.Input("axis: Tidx")
.Output("output: T")
.Attr("N: int >= 2")
.Attr("T: type")
.Attr("Tidx: {int32, int64} = DT_INT32")
.SetShapeFn(shape_inference::ConcatV2Shape);
// TODO(vivek.v.rane@intel.com): Prefix the op names with underscore if the ops
// are not to be made user-accessible.
#ifdef INTEL_MKL
REGISTER_OP("_MklConcatV2")
.Input("values: N * T")
.Input("axis: Tidx")
.Input("mkl_values: N * uint8")
.Input("mkl_axis: uint8")
.Output("output: T")
.Output("mkl_output: uint8")
.Attr("N: int >= 2")
.Attr("T: type")
.Attr("Tidx: {int32, int64} = DT_INT32")
.SetShapeFn(shape_inference::ConcatV2Shape)
.Doc(R"doc(
MKL version of ConcatV2 operator. Uses MKL DNN APIs to perform concatenation.
NOTE Do not invoke this operator directly in Python. Graph rewrite pass is
expected to invoke these operators.
)doc");
#endif
REGISTER_OP("ConcatOffset")
.Input("concat_dim: int32")
.Input("shape: N * int32")
.Output("offset: N * int32")
.Attr("N: int >= 2")
.SetShapeFn([](InferenceContext* c) {
for (int i = 1; i < c->num_inputs(); ++i) {
c->set_output(i - 1, c->input(i));
}
return OkStatus();
});
// --------------------------------------------------------------------------
REGISTER_OP("Split")
.Input("split_dim: int32")
.Input("value: T")
.Output("output: num_split * T")
.Attr("num_split: int >= 1")
.Attr("T: type")
.SetShapeFn([](InferenceContext* c) {
DimensionHandle split_dimension;
ShapeHandle input = c->input(1);
TF_RETURN_IF_ERROR(c->MakeDimForScalarInputWithNegativeIndexing(
0, c->Rank(input), &split_dimension));
int num_split = c->num_outputs();
ShapeHandle out;
if (!c->ValueKnown(split_dimension)) {
if (c->RankKnown(input)) {
out = c->UnknownShapeOfRank(c->Rank(input));
} else {
out = c->UnknownShape();
}
} else {
int64_t split_dim = c->Value(split_dimension);
TF_RETURN_IF_ERROR(c->WithRankAtLeast(input, split_dim + 1, &input));
DimensionHandle split_dim_size;
TF_RETURN_WITH_CONTEXT_IF_ERROR(
c->Divide(c->Dim(input, split_dim), num_split,
true /* evenly_divisible */, &split_dim_size),
"Number of ways to split should evenly divide the split dimension");
TF_RETURN_IF_ERROR(
c->ReplaceDim(input, split_dim, split_dim_size, &out));
}
for (int i = 0; i < num_split; ++i) c->set_output(i, out);
return OkStatus();
});
REGISTER_OP("SplitV")
.Input("value: T")
.Input("size_splits: Tlen")
.Input("split_dim: int32")
.Output("output: num_split * T")
.Attr("num_split: int >= 1")
.Attr("T: type")
.Attr("Tlen: {int32, int64} = DT_INT64")
.SetShapeFn([](InferenceContext* c) {
DimensionHandle split_dimension;
ShapeHandle input = c->input(0);
TF_RETURN_IF_ERROR(c->MakeDimForScalarInputWithNegativeIndexing(
2, c->Rank(input), &split_dimension));
int32_t num_outputs = c->num_outputs();
int32_t rank = c->Rank(input);
ShapeHandle output_shape;
const Tensor* size_splits = c->input_tensor(1);
if (rank == InferenceContext::kUnknownRank) {
// If the rank of input tensor is unknown, then return unknown shapes.
// Note that the shape of each output can be different.
for (int i = 0; i < num_outputs; ++i) {
c->set_output(i, c->UnknownShape());
}
} else if (rank == 0) {
// Throw error if input is a scalar.
return errors::InvalidArgument("Can't split scalars");
} else if (size_splits == nullptr && c->ValueKnown(split_dimension)) {
// If split dimension is known, but the sizes are unknown, then
// only the split dimension is unknown
output_shape = input;
for (int i = 0; i < num_outputs; ++i) {
TF_RETURN_IF_ERROR(c->ReplaceDim(output_shape,
c->Value(split_dimension),
c->UnknownDim(), &output_shape));
c->set_output(i, output_shape);
}
} else if (size_splits == nullptr && !c->ValueKnown(split_dimension)) {
// If split dimension or tensor containing the split sizes is unknown,
// then return unknown shapes of same rank as input. Note that each
// output shape can be different since splitv doesn't always split
// tensors evenly.
for (int i = 0; i < num_outputs; ++i) {
c->set_output(i, c->UnknownShapeOfRank(rank));
}
} else {
// Determine the output shape if split dimension and split sizes are
// known.
int64_t split_dim = c->Value(split_dimension);
TF_RETURN_IF_ERROR(c->WithRankAtLeast(input, split_dim + 1, &input));
std::vector<int64_t> data;
if (size_splits->dtype() == DT_INT32) {
data = AsInt64<int32>(size_splits, size_splits->shape().dim_size(0));
} else {
data =
AsInt64<int64_t>(size_splits, size_splits->shape().dim_size(0));
}
if (num_outputs != data.size()) {
return errors::InvalidArgument(
"Length of size_splits should be equal to num_outputs");
}
int64_t total_size = 0;
bool has_neg_one = false;
for (const auto size : data) {
if (size == -1) {
if (has_neg_one) {
return errors::InvalidArgument(
"size_splits can only have one -1");
}
has_neg_one = true;
} else {
total_size += size;
}
}
auto split_dim_size = c->Value(c->Dim(input, split_dim));
// If the sizes of the splits are known, then
// make sure that the sizes add up to the expected
// dimension size, with the possibility of a -1.
// Specify the full output shapes.
for (int i = 0; i < num_outputs; ++i) {
auto size = data[i];
if (data[i] == -1 && c->ValueKnown(split_dim_size)) {
size = split_dim_size - total_size;
}
// If we have a negative known size (either explicit, or computed
// via -1), then the split sizes are invalid.
if (size < -1 || (size == -1 && c->ValueKnown(split_dim_size))) {
return errors::InvalidArgument("Split size at index ", i,
" must be >= 0. Got: ", size);
}
TF_RETURN_IF_ERROR(
c->ReplaceDim(input, split_dim, c->MakeDim(size), &output_shape));
c->set_output(i, output_shape);
}
if (c->ValueKnown(split_dim_size)) {
if (has_neg_one ? total_size > split_dim_size
: total_size != split_dim_size) {
return errors::InvalidArgument(
"can't split axis of size ", split_dim_size,
" into pieces of size [", absl::StrJoin(data, ","), "]");
}
}
}
return OkStatus();
});
// --------------------------------------------------------------------------
REGISTER_OP("Const")
.Output("output: dtype")
.Attr("value: tensor")
.Attr("dtype: type")
.SetShapeFn([](InferenceContext* c) {
const TensorProto* proto = nullptr;
TF_RETURN_IF_ERROR(c->GetAttr("value", &proto));
TF_RETURN_IF_ERROR(TensorShape::IsValidShape(proto->tensor_shape()));
TensorShape shape(proto->tensor_shape());
std::vector<DimensionHandle> dims;
dims.reserve(shape.dims());
for (int i = 0; i < shape.dims(); ++i) {
dims.push_back(c->MakeDim(shape.dim_size(i)));
}
c->set_output(0, c->MakeShape(dims));
return OkStatus();
});
// Returns a constant tensor on the host. Useful for writing C++ tests
// and benchmarks which run on GPU but require arguments pinned to the host.
// Used by test::graph::HostConstant.
// value: Attr `value` is the tensor to return.
REGISTER_OP("HostConst")
.Output("output: dtype")
.Attr("value: tensor")
.Attr("dtype: type")
.SetShapeFn(shape_inference::UnknownShape);
// Used executing op-by-op to copy constants to the current device without
// serializing tensors as TensorProtos, after a host tensor has been
// created. Same behavior as Identity, but no gradient and potentially relaxed
// copy semantics.
REGISTER_OP("_EagerConst")
.Input("input: T")
.Output("output: T")
.Attr("T: type")
.SetShapeFn(shape_inference::UnchangedShape);
// --------------------------------------------------------------------------
// TODO(mgubin): Update the doc when the freeze_graph script supports converting
// into memmapped format.
REGISTER_OP("ImmutableConst")
.Attr("dtype: type")
.Attr("shape: shape")
.Attr("memory_region_name: string")
.Output("tensor: dtype")
.SetShapeFn(shape_inference::ExplicitShape);
REGISTER_OP("GuaranteeConst")
.Input("input: T")
.Output("output: T")
.Attr("T: type")
.SetShapeFn([](shape_inference::InferenceContext* c) {
return UnchangedShape(c);
})
// We don't want this to be optimized away.
.SetDoNotOptimize();
// --------------------------------------------------------------------------
REGISTER_OP("ZerosLike")
.Input("x: T")
.Output("y: T")
.Attr("T: type")
.SetShapeFn(shape_inference::UnchangedShape);
// --------------------------------------------------------------------------
REGISTER_OP("OnesLike")
.Input("x: T")
.Output("y: T")
.Attr(
"T: {bfloat16, half, float, double, int8, uint8, int16, uint16, int32, "
"uint32, int64, uint64, complex64, complex128, bool}")
.SetShapeFn(shape_inference::UnchangedShape);
// --------------------------------------------------------------------------
REGISTER_OP("Diag")
.Input("diagonal: T")
.Output("output: T")
.Attr(
"T: {bfloat16, half, float, double, int32, int64, complex64, "
"complex128}")
.SetShapeFn([](InferenceContext* c) {
ShapeHandle in = c->input(0);
TF_RETURN_IF_ERROR(c->WithRankAtLeast(in, 1, &in));
// Output shape is original concatenated with itself.
ShapeHandle out;
TF_RETURN_IF_ERROR(c->Concatenate(in, in, &out));
c->set_output(0, out);
return OkStatus();
});
// --------------------------------------------------------------------------
REGISTER_OP("DiagPart")
.Input("input: T")
.Output("diagonal: T")
.Attr(
"T: {bfloat16, half, float, double, int32, int64, complex64, "
"complex128}")
.SetShapeFn([](InferenceContext* c) {
ShapeHandle in = c->input(0);
if (!c->RankKnown(in)) {
c->set_output(0, c->UnknownShape());
return OkStatus();
}
// Rank must be even, and result will have rank <rank/2>.
const int32_t rank = c->Rank(in);
if ((rank % 2) != 0 || rank <= 0) {
return errors::InvalidArgument(
"Input must have even and non-zero rank, input rank is ", rank);
}
const int32_t mid = rank / 2;
// output dim[i] is the merge of in.dim[i] and in.dim[i+mid].
std::vector<DimensionHandle> dims(mid);
for (int i = 0; i < mid; ++i) {
TF_RETURN_IF_ERROR(
c->Merge(c->Dim(in, i), c->Dim(in, i + mid), &dims[i]));
}
c->set_output(0, c->MakeShape(dims));
return OkStatus();
});
// --------------------------------------------------------------------------
REGISTER_OP("MatrixDiag")
.Input("diagonal: T")
.Output("output: T")
.Attr("T: type")
.SetShapeFn([](InferenceContext* c) {
ShapeHandle in;
TF_RETURN_IF_ERROR(c->WithRankAtLeast(c->input(0), 1, &in));
if (!c->RankKnown(in)) {
c->set_output(0, c->UnknownShape());
return OkStatus();
}
const int32_t rank = c->Rank(in);
ShapeHandle out;
TF_RETURN_IF_ERROR(
c->Concatenate(in, c->Vector(c->Dim(in, rank - 1)), &out));
c->set_output(0, out);
return OkStatus();
});
REGISTER_OP("MatrixDiagV2")
.Input("diagonal: T")
.Input("k: int32")
.Input("num_rows: int32")
.Input("num_cols: int32")
.Input("padding_value: T")
.Output("output: T")
.Attr("T: type")
.SetShapeFn(shape_inference::MatrixDiagV2Shape);
REGISTER_OP("MatrixDiagV3")
.Input("diagonal: T")
.Input("k: int32")
.Input("num_rows: int32")
.Input("num_cols: int32")
.Input("padding_value: T")
.Output("output: T")
.Attr("T: type")
.Attr(
"align: {'LEFT_RIGHT', 'RIGHT_LEFT', 'LEFT_LEFT', 'RIGHT_RIGHT'} = "
"'RIGHT_LEFT'")
.SetShapeFn(shape_inference::MatrixDiagV2Shape);
// --------------------------------------------------------------------------
REGISTER_OP("MatrixSetDiag")
.Input("input: T")
.Input("diagonal: T")
.Output("output: T")
.Attr("T: type")
.SetShapeFn([](InferenceContext* c) {
ShapeHandle input;
ShapeHandle diag;
TF_RETURN_IF_ERROR(c->WithRankAtLeast(c->input(0), 2, &input));
TF_RETURN_IF_ERROR(c->WithRankAtLeast(c->input(1), 1, &diag));
if (c->RankKnown(input)) {
TF_RETURN_IF_ERROR(c->WithRank(c->input(1), c->Rank(input) - 1, &diag));
}
DimensionHandle smallest_dim;
TF_RETURN_IF_ERROR(
c->Min(c->Dim(input, -2), c->Dim(input, -1), &smallest_dim));
TF_RETURN_IF_ERROR(
c->Merge(smallest_dim, c->Dim(diag, -1), &smallest_dim));
ShapeHandle output = input;
if (c->RankKnown(diag) && !c->FullyDefined(input)) {
// Try to infer parts of shape from diag.
ShapeHandle diag_batch_shape;
TF_RETURN_IF_ERROR(c->Subshape(diag, 0, -1, &diag_batch_shape));
TF_RETURN_IF_ERROR(
c->Concatenate(diag_batch_shape, c->UnknownShapeOfRank(2), &diag));
TF_RETURN_IF_ERROR(c->Merge(input, diag, &output));
}
c->set_output(0, output);
return OkStatus();
});
REGISTER_OP("MatrixSetDiagV2")
.Input("input: T")
.Input("diagonal: T")
.Input("k: int32")
.Output("output: T")
.Attr("T: type")
.SetShapeFn(shape_inference::MatrixSetDiagV2Shape);
REGISTER_OP("MatrixSetDiagV3")
.Input("input: T")
.Input("diagonal: T")
.Input("k: int32")
.Output("output: T")
.Attr("T: type")
.Attr(
"align: {'LEFT_RIGHT', 'RIGHT_LEFT', 'LEFT_LEFT', 'RIGHT_RIGHT'} = "
"'RIGHT_LEFT'")
.SetShapeFn(shape_inference::MatrixSetDiagV2Shape);
// --------------------------------------------------------------------------
REGISTER_OP("MatrixDiagPart")
.Input("input: T")
.Output("diagonal: T")
.Attr("T: type")
.SetShapeFn([](InferenceContext* c) {
ShapeHandle in;
TF_RETURN_IF_ERROR(c->WithRankAtLeast(c->input(0), 2, &in));
if (!c->RankKnown(in)) {
c->set_output(0, c->UnknownShape());
return OkStatus();
}
const int32_t rank = c->Rank(in);
std::vector<DimensionHandle> dims;
dims.reserve(rank - 2);
for (int i = 0; i < rank - 2; ++i) dims.push_back(c->Dim(in, i));
DimensionHandle min_dim;
TF_RETURN_IF_ERROR(
c->Min(c->Dim(in, rank - 2), c->Dim(in, rank - 1), &min_dim));
dims.push_back(min_dim);
c->set_output(0, c->MakeShape(dims));
return OkStatus();
});
REGISTER_OP("MatrixDiagPartV2")
.Input("input: T")
.Input("k: int32")
.Input("padding_value: T")
.Output("diagonal: T")
.Attr("T: type")
.SetShapeFn(shape_inference::MatrixDiagPartV2Shape);
REGISTER_OP("MatrixDiagPartV3")
.Input("input: T")
.Input("k: int32")
.Input("padding_value: T")
.Output("diagonal: T")
.Attr("T: type")
.Attr(
"align: {'LEFT_RIGHT', 'RIGHT_LEFT', 'LEFT_LEFT', 'RIGHT_RIGHT'} = "
"'RIGHT_LEFT'")
.SetShapeFn(shape_inference::MatrixDiagPartV2Shape);
// --------------------------------------------------------------------------
REGISTER_OP("MatrixBandPart")
.Input("input: T")
.Input("num_lower: Tindex")
.Input("num_upper: Tindex")
.Output("band: T")
.Attr("T: type")
.Attr("Tindex: {int32, int64} = DT_INT64")
.SetShapeFn(shape_inference::UnchangedShape);
// --------------------------------------------------------------------------
REGISTER_OP("Reverse")
.Input("tensor: T")
.Input("dims: bool")
.Output("output: T")
.Attr(
"T: {uint8, int8, uint16, int16, uint32, int32, uint64, int64, bool, "
"bfloat16, half, float, double, complex64, complex128, string}")
.SetShapeFn([](InferenceContext* c) {
ShapeHandle input = c->input(0);
ShapeHandle dims;
TF_RETURN_IF_ERROR(c->WithRank(c->input(1), 1, &dims));
DimensionHandle dims_dim = c->Dim(dims, 0);
if (c->ValueKnown(dims_dim)) {
TF_RETURN_IF_ERROR(c->WithRank(input, c->Value(dims_dim), &input));
}
if (c->Rank(input) > 8) {
return errors::InvalidArgument(
"reverse does not work on tensors with more than 8 dimensions");
}
c->set_output(0, input);