-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathpython_op_gen.cc
2090 lines (1895 loc) · 81.9 KB
/
python_op_gen.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 2017 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/python/framework/python_op_gen.h"
#include <float.h>
#include <stdio.h>
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <iomanip>
#include <locale>
#include <set>
#include <sstream>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>
#include "absl/strings/escaping.h"
#include "absl/strings/str_join.h"
#include "absl/strings/str_replace.h"
#include "absl/types/span.h"
#include "tensorflow/core/framework/api_def.pb.h"
#include "tensorflow/core/framework/attr_value.pb.h"
#include "tensorflow/core/framework/op.h"
#include "tensorflow/core/framework/op_def.pb.h"
#include "tensorflow/core/framework/op_def_util.h"
#include "tensorflow/core/framework/op_gen_lib.h"
#include "tensorflow/core/framework/tensor.pb.h"
#include "tensorflow/core/framework/tensor_shape.pb.h"
#include "tensorflow/core/framework/types.h"
#include "tensorflow/core/framework/types.pb.h"
#include "tensorflow/core/lib/gtl/map_util.h"
#include "tensorflow/core/lib/strings/str_util.h"
#include "tensorflow/core/lib/strings/strcat.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/macros.h"
#include "tensorflow/core/platform/strcat.h"
#include "tensorflow/core/platform/types.h"
#include "tensorflow/python/framework/python_op_gen_annotator.h"
namespace tensorflow {
namespace {
// Names specified in tf_export decorators are exported to
// TensorFlow 2.0 by default.
const int kLatestAPIExportVersion = 2;
const int kRightMargin = 78;
constexpr char kEagerFallbackSuffix[] = "_eager_fallback";
// Maps C++ dtype enum values to Python annotation types
const std::unordered_map<string, string> dtype_type{
{"_dtypes.float16", "_atypes.Float16"},
{"_dtypes.half", "_atypes.Half"},
{"_dtypes.float32", "_atypes.Float32"},
{"_dtypes.float64", "_atypes.Float64"},
{"_dtypes.bfloat16", "_atypes.BFloat16"},
{"_dtypes.complex64", "_atypes.Complex64"},
{"_dtypes.complex128", "_atypes.Complex128"},
{"_dtypes.int8", "_atypes.Int8"},
{"_dtypes.uint8", "_atypes.UInt8"},
{"_dtypes.uint16", "_atypes.UInt16"},
{"_dtypes.uint32", "_atypes.UInt32"},
{"_dtypes.uint64", "_atypes.UInt64"},
{"_dtypes.int16", "_atypes.Int16"},
{"_dtypes.int32", "_atypes.Int32"},
{"_dtypes.int64", "_atypes.Int64"},
{"_dtypes.bool", "_atypes.Bool"},
{"_dtypes.string", "_atypes.String"},
{"_dtypes.qint8", "_atypes.QInt8"},
{"_dtypes.quint8", "_atypes.QUInt8"},
{"_dtypes.qint16", "_atypes.QInt16"},
{"_dtypes.quint16", "_atypes.QUInt16"},
{"_dtypes.qint32", "_atypes.QInt32"},
{"_dtypes.resource", "_atypes.Resource"},
{"_dtypes.variant", "_atypes.Variant"}};
string AttrVarName(const string& attr_name,
std::unordered_map<string, string>* attr_expressions) {
const string var = strings::StrCat("_attr_", attr_name);
if (attr_expressions != nullptr) (*attr_expressions)[attr_name] = var;
return var;
}
void AddInferredAttr(const string& indentation, const string& attr_name,
const string& value_expression, string* result,
std::unordered_map<string, string>* attr_expressions) {
strings::StrAppend(result, indentation,
AttrVarName(attr_name, attr_expressions), " = ",
value_expression, "\n");
}
string VectorToTuple(const std::vector<string>& l) {
if (l.size() == 1) return strings::StrCat("(", l.front(), ",)");
string ret = "(";
for (int i = 0, end = l.size(); i < end; ++i) {
if (i > 0) {
strings::StrAppend(&ret, ", ");
}
strings::StrAppend(&ret, l[i]);
}
strings::StrAppend(&ret, ")");
return ret;
}
void Unflatten(const string& prefix, const std::vector<string>& output_sizes,
const string& var, string* result) {
for (int i = 0, end = output_sizes.size(); i < end; ++i) {
if (!output_sizes[i].empty()) {
strings::StrAppend(result, prefix, var, " = ");
if (i > 0) strings::StrAppend(result, var, "[:", i, "] + ");
if (i + 1 < end) {
// Special case i == 0 to avoid "0 +" in the generated code.
if (i == 0) {
strings::StrAppend(result, "[", var, "[:", output_sizes[i], "]] + ",
var, "[", output_sizes[i], ":]");
} else {
strings::StrAppend(result, "[", var, "[", i, ":", i, " + ",
output_sizes[i], "]] + ", var, "[", i, " + ",
output_sizes[i], ":]");
}
} else {
strings::StrAppend(result, "[", var, "[", i, ":]]");
}
strings::StrAppend(result, "\n");
}
}
}
string TensorPBString(const TensorProto& pb) {
// Explicitly not using ShortDebugString, because ShortDebugString should
// not be used as a format for transporting information (it's e.g. subject
// to redaction of sensitive information). There is a PrintShortTextProto
// helper, but it's not feasible to depend on that library).
std::string message_short_text;
::tensorflow::protobuf::TextFormat::Printer printer;
printer.SetSingleLineMode(true);
printer.SetExpandAny(true);
printer.PrintToString(pb, &message_short_text);
// Note: This gets used in the argument list, and so must survive naive
// word wrapping.
return strings::StrCat("\"\"\"", message_short_text, "\"\"\"");
}
// Returns true if s is a Python keyword or built-in.
bool IsPythonReserved(const string& s);
// Whether the op should be prefixed with underscore.
bool IsOpWithUnderscorePrefix(const string& s);
// Add a _ to the end of s if necessary to avoid a Python keyword or built-in.
// Also convert namespace characters ('>') to '_' because python does not
// support '>' in names
string AvoidPythonReserved(const string& s);
// Convert an AttrValue with type `type` to the Python representation for
// that value.
string AttrValueToPython(const string& type, const AttrValue& value,
const string& dtype_module = "tf.");
void GenerateLowerCaseOpName(const string& str, string* result);
string DataTypeToPython(DataType dtype, const string& dtype_module);
// Names that corresponds to a single input parameter.
class ParamNames {
public:
// Create param based on Arg.
ParamNames(const string& name, const string& rename_to) : name_(name) {
rename_to_ = AvoidPythonReserved(rename_to);
}
// Get original parameter name.
string GetName() const { return name_; }
// Get the name to rename the parameter to. Note that AvoidPythonReserved
// has already been applied.
string GetRenameTo() const { return rename_to_; }
private:
// Original parameter name.
string name_;
// API name for this parameter.
string rename_to_;
};
class GenPythonOp {
public:
GenPythonOp(
const OpDef& op_def, const ApiDef& api_def, const string& function_name,
python_op_gen_internal::GeneratedCodeAnnotator* annotator = nullptr)
: op_def_(op_def),
api_def_(api_def),
function_name_(function_name),
num_outs_(op_def.output_arg_size()),
annotator_(annotator) {
op_name_ = function_name_;
absl::ConsumePrefix(&op_name_, "_");
}
~GenPythonOp() = default;
string Code();
protected:
void AddDefLine(const string& function_name, const string& parameters);
void AddDefLine(const string& parameters);
// Format the Op's descriptions so that it can be a Python docstring.
void AddDocStringDescription();
void AddDocStringArgs();
void AddDocStringInputs();
void AddDocStringAttrs();
void AddDocStringNameArg();
void AddOutputGlobals();
void AddDocStringOutputs();
void AddBody(const string& prefix);
void AddBodyNoReturn(const string& apply_prefix);
void AddExport();
void HandleGraphMode(const string& function_setup,
const std::vector<string>& output_sizes);
string GetEagerNotAllowedError();
void ExpectListArg(const string& indentation, const string& arg_name,
string* output);
bool GetEagerFunctionSetup(const string& indentation, string* function_setup);
void GetOutputSizesAndNumOutputsExpr(std::vector<string>* output_sizes,
string* num_outputs_expr);
void AddEagerFunctionTeardown(const string& indentation,
const std::vector<string>& output_sizes,
bool execute_record_gradient);
bool AddEagerFastPathAndGraphCode(
const string& parameters, const std::vector<string>& output_sizes,
const string& eager_not_allowed_error,
const std::unordered_map<string, string>& type_annotations);
bool AddEagerFallbackCode(
const string& parameters, const std::vector<string>& output_sizes,
const string& num_outputs_expr, const string& eager_not_allowed_error,
const std::unordered_map<string, string>& type_annotations);
void AddEagerFastPathExecute();
void AddEagerInferredAttrs(const string& indentation);
void AddEagerInputCasts(const string& indentation);
void AddEagerAttrs(const string& indentation);
void AddEagerExecute(const string& indentation,
const string& num_outputs_expr);
void AddFallbackDispatch(const string& prefix);
void AddTypeBasedDispatch(const string& prefix);
void AddTypeBasedDispatcherAlias();
void AddRawOpExport(const string& parameters);
std::unordered_map<string, string> GetTypeAnnotations();
void GenerateTypeVars(
const std::unordered_map<string, string>& type_annotations);
void AddReturnTypeAnnotation(
const std::unordered_map<string, string>& type_annotations);
void AddAttrForArg(const string& attr, int arg_index) {
gtl::InsertIfNotPresent(&inferred_attrs_, attr,
op_def_.input_arg(arg_index).name());
auto iter = attr_to_args_.find(attr);
if (iter == attr_to_args_.end()) {
attr_to_args_.insert(AttrToArgMap::value_type(attr, {arg_index}));
} else {
iter->second.push_back(arg_index);
}
}
// Returns a string expression representing a flattened list of all
// the inputs given by `*input_indices` (or all inputs if
// `input_indices` is nullptr). `*output_sizes` can be used to unflatten.
string FlattenInputs(const std::vector<int>* input_indices,
std::vector<string>* output_sizes) const;
// From constructor arguments
const OpDef& op_def_;
const ApiDef& api_def_;
const string function_name_;
const int num_outs_;
python_op_gen_internal::GeneratedCodeAnnotator* annotator_ = nullptr;
// Return value from Code() is prelude_ + result_.
string prelude_; // Code before function definition
string result_; // Function definition
// Map from attr name to the first input arg it is inferred from
std::unordered_map<string, string> inferred_attrs_;
// The names of the non-inferred attrs, in parameter order
std::vector<string> attrs_;
// All parameters, including inputs & non-inferred attrs, required and those
// with defaults, except "name"
std::vector<ParamNames> param_names_;
StringPiece op_name_;
typedef std::unordered_map<string, std::vector<int>> AttrToArgMap;
AttrToArgMap attr_to_args_;
std::unordered_map<string, string> attr_expressions_;
// This has all the input args followed by those attrs that don't have
// defaults.
std::vector<ParamNames> params_no_default_;
// The parameters with defaults (these have to be listed after those without).
// No input args are included, just attrs.
std::vector<std::pair<ParamNames, string>> params_with_default_;
};
string GetEagerPythonOp(
const OpDef& op_def, const ApiDef& api_def, const string& function_name,
python_op_gen_internal::GeneratedCodeAnnotator* annotator = nullptr) {
return GenPythonOp(op_def, api_def, function_name, annotator).Code();
}
bool IsPythonReserved(const string& s) {
static const std::set<string>* const kPythonReserved = new std::set<string>(
{// Keywords in Python, from:
// import keyword
// print keyword.kwlist
"and", "as", "assert", "break", "class", "continue", "def", "del",
"elif", "else", "except", "exec", "finally", "for", "from", "global",
"if", "import", "in", "is", "lambda", "not", "or", "pass", "print",
"raise", "return", "try", "while", "with", "yield",
// Built-in functions and types in Python, from:
// [x for x in dir(__builtins__) if not x[0].islower()]
"ArithmeticError", "AssertionError", "AttributeError", "BaseException",
"BufferError", "BytesWarning", "DeprecationWarning", "EOFError",
"Ellipsis", "EnvironmentError", "Exception", "False",
"FloatingPointError", "FutureWarning", "GeneratorExit", "IOError",
"ImportError", "ImportWarning", "IndentationError", "IndexError",
"KeyError", "KeyboardInterrupt", "LookupError", "MemoryError",
"NameError", "None", "NotImplemented", "NotImplementedError", "OSError",
"OverflowError", "PendingDeprecationWarning", "ReferenceError",
"RuntimeError", "RuntimeWarning", "StandardError", "StopIteration",
"SyntaxError", "SyntaxWarning", "SystemError", "SystemExit", "TabError",
"True", "TypeError", "UnboundLocalError", "UnicodeDecodeError",
"UnicodeEncodeError", "UnicodeError", "UnicodeTranslateError",
"UnicodeWarning", "UserWarning", "ValueError", "Warning",
"ZeroDivisionError", "__debug__", "__doc__", "__import__", "__name__",
"__package__"});
return kPythonReserved->count(s) > 0;
}
bool IsOpWithUnderscorePrefix(const string& s) {
static const std::set<string>* const kUnderscoreOps = new std::set<string>(
{// Lowercase built-in functions and types in Python, from:
// [x for x in dir(__builtins__) if x[0].islower()] except "round".
// These need to be excluded so they don't conflict with actual built-in
// functions since we use '*' imports.
"abs", "all", "any", "apply", "bin", "bool", "buffer", "bytearray",
"bytes", "callable", "chr", "classmethod", "cmp", "coerce", "compile",
"complex", "copyright", "credits", "delattr", "dict", "dir", "divmod",
"enumerate", "eval", "execfile", "exit", "file", "filter", "float",
"format", "frozenset", "getattr", "globals", "hasattr", "hash", "help",
"hex", "id", "input", "int", "intern", "isinstance", "issubclass",
"iter", "len", "license", "list", "locals", "long", "map", "max",
"memoryview", "min", "next", "object", "oct", "open", "ord", "pow",
"print", "property", "quit", "range", "raw_input", "reduce", "reload",
"repr", "reversed", "set", "setattr", "slice", "sorted", "staticmethod",
"str", "sum", "super", "tuple", "type", "unichr", "unicode", "vars",
"xrange", "zip",
// These have the same name as ops defined in Python and might be used
// incorrectly depending on order of '*' imports.
// TODO(annarev): reduce usage of '*' imports and remove these from the
// list.
"fused_batch_norm", "histogram_fixed_width", "stack",
"batch_norm_with_global_normalization", "clip_by_value"});
return kUnderscoreOps->count(s) > 0;
}
string AvoidPythonReserved(const string& s) {
// Convert namespace separators ('>' characters) to joiners
string result = absl::StrReplaceAll(s, {{">", "_"}});
if (IsPythonReserved(result)) return strings::StrCat(result, "_");
return result;
}
// Indent the first line by "initial" spaces and all following lines
// by "rest" spaces.
string Indent(int initial, int rest, StringPiece in) {
// TODO(josh11b): Also word-wrapping?
string copy(in.data(), in.size());
absl::StripTrailingAsciiWhitespace(©);
std::vector<string> v = str_util::Split(copy, '\n');
string result;
bool first = true;
for (const string& line : v) {
if (first) {
result = strings::StrCat(Spaces(initial), line, "\n");
first = false;
} else {
if (line.empty()) {
strings::StrAppend(&result, "\n");
} else {
strings::StrAppend(&result, Spaces(rest), line, "\n");
}
}
}
return result;
}
// Adds append to *dest, with a space if the first line will be <= width,
// or a newline otherwise.
void AppendWithinWidth(string* dest, StringPiece append, int width) {
auto first_line = append.find('\n');
if (first_line == string::npos) first_line = append.size();
if (dest->size() + first_line + 1 /* space */ > static_cast<size_t>(width)) {
strings::StrAppend(dest, "\n", append);
} else {
strings::StrAppend(dest, " ", append);
}
}
// Like DataTypeString() but uses the Python names for the
// float types.
string PythonDataTypeString(DataType dtype) {
switch (dtype) {
case DT_FLOAT:
return "float32";
case DT_DOUBLE:
return "float64";
default:
return DataTypeString(dtype);
}
}
string TypeString(DataType dtype, bool ref) {
if (ref) {
return strings::StrCat("mutable `", PythonDataTypeString(dtype), "`");
} else {
return strings::StrCat("`", PythonDataTypeString(dtype), "`");
}
}
string TypeListString(const AttrValue& value) {
string ret;
for (int t : value.list().type()) {
if (!ret.empty()) strings::StrAppend(&ret, ", ");
DataType dtype = static_cast<DataType>(t);
if (IsRefType(dtype)) {
strings::StrAppend(&ret, PythonDataTypeString(RemoveRefType(dtype)),
" mutable");
} else {
strings::StrAppend(&ret, "`", PythonDataTypeString(dtype), "`");
}
}
return ret;
}
string SingleTensorName(DataType dtype, bool is_ref) {
const string type_str = TypeString(dtype, is_ref);
return strings::StrCat("A `Tensor` of type ", type_str, ".");
}
const char kUnknownTensorType[] = {"A `Tensor`."};
string ArgTypeName(const OpDef& op_def, const OpDef::ArgDef& arg,
const std::unordered_map<string, string>& inferred_attrs,
bool is_output) {
if (!arg.number_attr().empty()) {
// N Tensors with the same type
const string* original_arg =
gtl::FindOrNull(inferred_attrs, arg.number_attr());
string prefix;
if (original_arg == nullptr) {
prefix = strings::StrCat("A list of `", arg.number_attr(), "`");
} else if (*original_arg == arg.name()) {
const OpDef::AttrDef* attr = FindAttr(arg.number_attr(), op_def);
if (attr->has_minimum() && attr->minimum() > 0) {
prefix = strings::StrCat("A list of at least ", attr->minimum());
} else {
prefix = "A list of";
}
} else {
prefix = strings::StrCat("A list with the same length as `",
AvoidPythonReserved(*original_arg), "` of");
}
if (arg.type() != DT_INVALID) {
return strings::StrCat(prefix, " `Tensor` objects with type ",
TypeString(arg.type(), arg.is_ref()), ".");
} else {
original_arg = gtl::FindOrNull(inferred_attrs, arg.type_attr());
if (arg.is_ref()) {
strings::StrAppend(&prefix, " mutable");
}
if (original_arg == nullptr) {
return strings::StrCat(prefix, " `Tensor` objects with type `",
arg.type_attr(), "`.");
} else if (*original_arg == arg.name()) {
const OpDef::AttrDef* attr = FindAttr(arg.type_attr(), op_def);
if (attr->has_allowed_values()) {
return strings::StrCat(prefix,
" `Tensor` objects with the same type in: ",
TypeListString(attr->allowed_values()), ".");
} else {
return strings::StrCat(prefix,
" `Tensor` objects with the same type.");
}
} else {
return strings::StrCat(prefix,
" `Tensor` objects with the same type as `",
AvoidPythonReserved(*original_arg), "`.");
}
}
} else if (!arg.type_attr().empty() || !arg.type_list_attr().empty()) {
const bool is_list = !arg.type_list_attr().empty();
const string attr_name = is_list ? arg.type_list_attr() : arg.type_attr();
const OpDef::AttrDef* attr = FindAttr(attr_name, op_def);
const string mutable_str = arg.is_ref() ? "mutable " : "";
const string prefix =
is_list ? strings::StrCat("A list of ", mutable_str, "`Tensor` objects")
: strings::StrCat("A ", mutable_str, "`Tensor`");
const string* original_arg = gtl::FindOrNull(inferred_attrs, attr_name);
if (original_arg == nullptr) {
return strings::StrCat(prefix, " of type `", attr_name, "`.");
} else if (*original_arg == arg.name()) {
if (attr->has_allowed_values()) {
if (is_list) {
return strings::StrCat(prefix, " with types from: ",
TypeListString(attr->allowed_values()), ".");
} else {
return strings::StrCat(prefix,
is_output
? ". Has one of the following types: "
: ". Must be one of the following types: ",
TypeListString(attr->allowed_values()), ".");
}
} else {
return strings::StrCat(prefix, ".");
}
} else {
return strings::StrCat(prefix,
is_output ? ". Has the same type as `"
: ". Must have the same type as `",
AvoidPythonReserved(*original_arg), "`.");
}
} else {
return SingleTensorName(arg.type(), arg.is_ref());
}
}
string GetReturns(const OpDef& op_def,
const std::vector<string>& output_type_string) {
string result;
DCHECK_EQ(op_def.output_arg_size(), output_type_string.size());
const int num_outs = op_def.output_arg_size();
strings::StrAppend(&result, "\n Returns:\n");
if (num_outs == 0) {
strings::StrAppend(&result, " The created Operation.\n");
} else {
if (num_outs == 1) {
StringPiece description = op_def.output_arg(0).description();
if (ConsumeEquals(&description)) { // Skip the generated type info.
strings::StrAppend(&result, Indent(4, 4, description));
} else {
// Special case of one output, don't use the name of the output unless
// there is no description.
string desc = output_type_string.empty() ? kUnknownTensorType
: output_type_string[0];
if (desc == kUnknownTensorType) {
// Special case where we don't understand how the output tensor type
// depends on the input tensor types, just use the output arg
// description if we can.
if (!description.empty()) {
desc = op_def.output_arg(0).description();
} else if (!op_def.output_arg(0).name().empty()) {
desc = strings::StrCat(" The ", op_def.output_arg(0).name(),
" `Tensor`.");
}
} else if (!description.empty()) {
AppendWithinWidth(&desc, description, kRightMargin - 4 /* indent */);
}
strings::StrAppend(&result, Indent(4, 4, desc));
}
} else {
std::vector<string> out_names(num_outs);
for (int i = 0; i < num_outs; ++i) {
if (!op_def.output_arg(i).name().empty()) {
out_names[i] = op_def.output_arg(i).name();
} else {
out_names[i] = strings::StrCat("output", i);
}
}
strings::StrAppend(&result, " A tuple of `Tensor` objects (",
absl::StrJoin(out_names, ", "), ").\n\n");
for (int i = 0; i < num_outs; ++i) {
string desc = strings::StrCat(out_names[i], ": ");
StringPiece description = op_def.output_arg(i).description();
if (ConsumeEquals(&description)) { // Skip the generated type info.
strings::StrAppend(&desc, description);
} else {
const string type = static_cast<size_t>(i) < output_type_string.size()
? output_type_string[i]
: kUnknownTensorType;
if (!description.empty()) {
if (type == kUnknownTensorType) {
// Special case where we don't understand how the output tensor
// type depends on the input tensor types, so we just use the
// output arg description.
strings::StrAppend(&desc, description);
} else {
strings::StrAppend(&desc, type, " ", description);
}
} else {
strings::StrAppend(&desc, type);
}
}
strings::StrAppend(&result, Indent(4, 6, desc));
}
}
}
return result;
}
string StringToPython(const string& str) {
return strings::StrCat("\"", absl::CEscape(str), "\"");
}
string DataTypeToPython(DataType dtype, const string& dtype_module) {
return strings::StrCat(dtype_module, PythonDataTypeString(dtype));
}
string ShapeToPython(const TensorShapeProto& shape) {
if (shape.unknown_rank()) {
return "None";
}
string python = "[";
for (const auto& dim : shape.dim()) {
if (python.size() > 1) strings::StrAppend(&python, ", ");
if (!dim.name().empty()) {
strings::StrAppend(&python, "(", StringToPython(dim.name()), ", ",
dim.size(), ")");
} else {
strings::StrAppend(&python, dim.size());
}
}
strings::StrAppend(&python, "]");
return python;
}
string TensorToPython(const TensorProto& proto) {
return proto.ShortDebugString();
}
string AttrListToPython(const AttrValue& value,
const string& dtype_module = "tf.") {
string ret;
if (value.list().s_size() > 0) {
for (int i = 0; i < value.list().s_size(); ++i) {
if (i > 0) strings::StrAppend(&ret, ", ");
strings::StrAppend(&ret, StringToPython(value.list().s(i)));
}
} else if (value.list().i_size() > 0) {
for (int i = 0; i < value.list().i_size(); ++i) {
if (i > 0) strings::StrAppend(&ret, ", ");
strings::StrAppend(&ret, value.list().i(i));
}
} else if (value.list().f_size() > 0) {
for (int i = 0; i < value.list().f_size(); ++i) {
if (i > 0) strings::StrAppend(&ret, ", ");
strings::StrAppend(&ret, value.list().f(i));
}
} else if (value.list().b_size() > 0) {
for (int i = 0; i < value.list().b_size(); ++i) {
if (i > 0) strings::StrAppend(&ret, ", ");
strings::StrAppend(&ret, value.list().b(i) ? "True" : "False");
}
} else if (value.list().type_size() > 0) {
for (int i = 0; i < value.list().type_size(); ++i) {
if (i > 0) strings::StrAppend(&ret, ", ");
strings::StrAppend(&ret,
DataTypeToPython(value.list().type(i), dtype_module));
}
} else if (value.list().shape_size() > 0) {
for (int i = 0; i < value.list().shape_size(); ++i) {
if (i > 0) strings::StrAppend(&ret, ", ");
strings::StrAppend(&ret, ShapeToPython(value.list().shape(i)));
}
} else if (value.list().tensor_size() > 0) {
for (int i = 0; i < value.list().tensor_size(); ++i) {
if (i > 0) strings::StrAppend(&ret, ", ");
strings::StrAppend(&ret, TensorToPython(value.list().tensor(i)));
}
} else if (value.list().func_size() > 0) {
for (int i = 0; i < value.list().func_size(); ++i) {
if (i > 0) strings::StrAppend(&ret, ", ");
strings::StrAppend(&ret, StringToPython(value.list().func(i).name()));
}
}
return ret;
}
// NOTE: The return value may contain spaces (for example, it could be
// a string "foo bar" with an embedded space) and is not safe to pass
// to WordWrap().
string AttrValueToPython(const string& type, const AttrValue& value,
const string& dtype_module) {
if (type == "string") {
return StringToPython(value.s());
} else if (type == "int") {
return strings::StrCat(value.i());
} else if (type == "float") {
if (std::isnan(value.f()) || std::isinf(value.f())) {
return strings::StrCat("float('", value.f(), "')");
} else {
// Use locale-independent conversion.
static_assert(FLT_DIG < 10, "FLT_DIG is too big");
std::ostringstream s;
s.imbue(std::locale::classic());
s << std::setprecision(FLT_DIG) << value.f();
// If there is no I/O error for `std::ostringstream s` return s.str(),
// otherwise fallback to strings::StrCat(value.f()).
if (s.good()) {
return s.str();
}
return strings::StrCat(value.f());
}
} else if (type == "bool") {
return value.b() ? "True" : "False";
} else if (type == "type") {
return DataTypeToPython(value.type(), dtype_module);
} else if (type == "shape") {
return ShapeToPython(value.shape());
} else if (type == "tensor") {
return TensorToPython(value.tensor());
} else if (type == "func") {
return StringToPython(value.func().name());
} else if (absl::StartsWith(type, "list(")) {
return strings::StrCat("[", AttrListToPython(value, dtype_module), "]");
} else {
return "?";
}
}
void GenerateLowerCaseOpName(const string& str, string* result) {
const char joiner = '_';
const char namespace_separator = '>';
const int last_index = str.size() - 1;
for (int i = 0; i <= last_index; ++i) {
const char c = str[i];
// Convert namespace separators ('>' characters) to joiners
if (c == namespace_separator) {
result->push_back(joiner);
continue;
}
// Emit a joiner only if a previous-lower-to-now-upper or a
// now-upper-to-next-lower transition happens.
// (But don't emit an extra joiner if we just saw a namespace separator
if (isupper(c) && (i > 0)) {
if (islower(str[i - 1]) || ((i < last_index) && islower(str[i + 1]))) {
if (!(str[i - 1] == namespace_separator)) {
result->push_back(joiner);
}
}
}
result->push_back(tolower(c));
}
}
static void AddDelimiter(string* append_to, const string& delim) {
if (!append_to->empty()) strings::StrAppend(append_to, delim);
}
const ApiDef::Attr* FindAttr(StringPiece name, const ApiDef& api_def) {
for (int i = 0; i < api_def.attr_size(); ++i) {
if (api_def.attr(i).name() == name) {
return &api_def.attr(i);
}
}
return nullptr;
}
void GenPythonOp::AddExport() {
if (api_def_.visibility() != ApiDef::VISIBLE) {
return;
}
// Whether op should be available in latest export version.
bool op_available_in_latest =
!api_def_.deprecation_version() ||
api_def_.deprecation_version() > kLatestAPIExportVersion;
string names;
string names_v1;
string deprecated_endpoints;
for (const auto& endpoint : api_def_.endpoint()) {
string endpoint_name;
GenerateLowerCaseOpName(endpoint.name(), &endpoint_name);
if (endpoint.deprecated() || endpoint.deprecation_version() > 0) {
AddDelimiter(&deprecated_endpoints, ", ");
strings::StrAppend(&deprecated_endpoints, "'", endpoint_name, "'");
}
// Add all endpoints to TensorFlow 1.* API.
AddDelimiter(&names_v1, ", ");
strings::StrAppend(&names_v1, "'", endpoint_name, "'");
// Add non-deprecated endpoints to TensorFlow 2.* API.
if (op_available_in_latest &&
(!endpoint.deprecation_version() ||
endpoint.deprecation_version() > kLatestAPIExportVersion)) {
AddDelimiter(&names, ", ");
strings::StrAppend(&names, "'", endpoint_name, "'");
}
}
// tf_export decorator has the following format:
// @tf_export(v2_name, v2_name, v1=[v1_name, v1_name])
if (names != names_v1) {
AddDelimiter(&names, ", ");
strings::StrAppend(&names, "v1=[", names_v1, "]");
}
strings::StrAppend(&result_, "@tf_export(", names, ")\n");
// If all endpoints are deprecated, add @deprecated decorator.
if (!api_def_.deprecation_message().empty()) {
const string instructions = api_def_.deprecation_message();
strings::StrAppend(&result_, "@deprecated(None, '", instructions, "')\n");
}
// Add @deprecated_endpoints decorator.
if (!deprecated_endpoints.empty()) {
strings::StrAppend(&result_, "@deprecated_endpoints(", deprecated_endpoints,
")\n");
}
}
void GenPythonOp::AddDefLine(const string& function_name,
const string& parameters) {
strings::StrAppend(&result_, "def ", function_name, "(", parameters, "):\n");
}
void GenPythonOp::AddDefLine(const string& parameters) {
AddDefLine(function_name_, parameters);
}
void GenPythonOp::AddDocStringDescription() {
string comment;
if (api_def_.summary().empty()) {
comment = "TODO: add doc.\n";
} else {
comment = strings::StrCat(api_def_.summary(), "\n");
if (!api_def_.description().empty()) {
strings::StrAppend(&comment, "\n", Indent(2, 2, api_def_.description()));
}
}
strings::StrAppend(&result_, " r\"\"\"", comment, "\n");
}
void GenPythonOp::AddDocStringArgs() {
strings::StrAppend(&result_, " Args:\n");
}
void GenPythonOp::AddDocStringInputs() {
for (int i = 0; i < api_def_.arg_order_size(); ++i) {
const auto& arg = *FindInputArg(api_def_.arg_order(i), op_def_);
const auto& api_def_arg = *FindInputArg(api_def_.arg_order(i), api_def_);
StringPiece description = api_def_arg.description();
string desc;
if (ConsumeEquals(&description)) { // Skip the generated type info.
desc = strings::StrCat(param_names_[i].GetRenameTo(), ": ");
} else {
desc = strings::StrCat(param_names_[i].GetRenameTo(), ": ",
ArgTypeName(op_def_, arg, inferred_attrs_, false));
}
if (!description.empty()) {
AppendWithinWidth(&desc, description, kRightMargin - 4 /* indent */);
}
strings::StrAppend(&result_, Indent(4, 6, desc));
}
}
void GenPythonOp::AddDocStringAttrs() {
for (const string& name : attrs_) {
const auto& attr = *FindAttr(name, op_def_);
const auto& api_def_attr = *FindAttr(name, api_def_);
string desc =
strings::StrCat(AvoidPythonReserved(api_def_attr.rename_to()), ": ");
static const char* const kAttrTypeName[][2] = {
{"string", "`string`"},
{"list(string)", "list of `strings`"},
{"int", "`int`"},
{"list(int)", "list of `ints`"},
{"float", "`float`"},
{"list(float)", "list of `floats`"},
{"bool", "`bool`"},
{"list(bool)", "list of `bools`"},
{"type", "`tf.DType`"},
{"list(type)", "list of `tf.DTypes`"},
{"shape", "`tf.TensorShape` or list of `ints`"},
{"list(shape)",
"list of shapes (each a `tf.TensorShape` or list of `ints`)"},
{"tensor", "`tf.TensorProto`"},
{"list(tensor)", "list of `tf.TensorProto` objects"},
{"func", "function decorated with @Defun"},
{"list(func)", "list of functions decorated with @Defun"},
};
for (size_t i = 0; i < TF_ARRAYSIZE(kAttrTypeName); ++i) {
if (attr.type() == kAttrTypeName[i][0]) {
string s;
if (api_def_attr.has_default_value()) {
s = strings::StrCat("optional ", kAttrTypeName[i][1]);
} else {
s = kAttrTypeName[i][1];
}
if (s[0] == 'o' || (s[0] == '`' && (s[1] == 'i' || s[1] == 'o'))) {
strings::StrAppend(&desc, "An ", s);
} else {
strings::StrAppend(&desc, "A ", s);
}
break;
}
}
if (attr.has_allowed_values()) {
strings::StrAppend(&desc, " from: `",
AttrListToPython(attr.allowed_values()), "`");
}
if (attr.has_minimum()) {
if (attr.type() == "int") {
strings::StrAppend(&desc, " that is `>= ", attr.minimum(), "`");
} else if (attr.minimum() > 0) {
strings::StrAppend(&desc, " that has length `>= ", attr.minimum(), "`");
}
}
strings::StrAppend(&desc, ".");
if (api_def_attr.has_default_value()) {
strings::StrAppend(
&desc, " Defaults to `",
AttrValueToPython(attr.type(), api_def_attr.default_value()), "`.");
}
if (!api_def_attr.description().empty()) {
AppendWithinWidth(&desc, api_def_attr.description(),
kRightMargin - 4 /* indent */);
}
strings::StrAppend(&result_, Indent(4, 6, desc));
}
}
void GenPythonOp::AddDocStringNameArg() {
strings::StrAppend(&result_,
" name: A name for the operation (optional).\n");
}
void GenPythonOp::AddOutputGlobals() {
// Generate a namedtuple class to hold the outputs, if there are multiple.
// Example:
//
// _OpOutputs = collections.namedtuple(
// "_OpOutputs",
// "out1 out2 out3")
if (num_outs_ > 1) {
std::vector<string> out_names;
out_names.reserve(num_outs_);
for (int i = 0; i < num_outs_; ++i) {
const string out_name = !api_def_.out_arg(i).rename_to().empty()
? api_def_.out_arg(i).rename_to()
: strings::StrCat("output", i);
out_names.push_back(strings::StrCat("\"", out_name, "\""));
}
strings::StrAppend(&prelude_, "_", AvoidPythonReserved(op_def_.name()),
"Output = collections.namedtuple(\n");
strings::StrAppend(&prelude_, " \"", AvoidPythonReserved(op_def_.name()),
"\",\n");
strings::StrAppend(&prelude_, " [", absl::StrJoin(out_names, ", "),
"])");
strings::StrAppend(&prelude_, "\n\n");
}