PageRenderTime 52ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 1ms

/tensorflow/python/framework/python_op_gen.cc

https://gitlab.com/hrishikeshvganu/tensorflow
C++ | 747 lines | 618 code | 64 blank | 65 comment | 189 complexity | 084c97f939c9fcd7a1e6a527e9e77708 MD5 | raw file
  1. /* Copyright 2015 Google Inc. All Rights Reserved.
  2. Licensed under the Apache License, Version 2.0 (the "License");
  3. you may not use this file except in compliance with the License.
  4. You may obtain a copy of the License at
  5. http://www.apache.org/licenses/LICENSE-2.0
  6. Unless required by applicable law or agreed to in writing, software
  7. distributed under the License is distributed on an "AS IS" BASIS,
  8. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. See the License for the specific language governing permissions and
  10. limitations under the License.
  11. ==============================================================================*/
  12. #include "tensorflow/python/framework/python_op_gen.h"
  13. #include <stdio.h>
  14. #include <sstream>
  15. #include <unordered_map>
  16. #include "tensorflow/core/framework/attr_value.pb.h"
  17. #include "tensorflow/core/framework/op.h"
  18. #include "tensorflow/core/framework/op_def.pb.h"
  19. #include "tensorflow/core/framework/op_def_util.h"
  20. #include "tensorflow/core/framework/op_gen_lib.h"
  21. #include "tensorflow/core/framework/types.h"
  22. #include "tensorflow/core/framework/types.pb.h"
  23. #include "tensorflow/core/lib/gtl/map_util.h"
  24. #include "tensorflow/core/lib/gtl/stl_util.h"
  25. #include "tensorflow/core/lib/strings/str_util.h"
  26. #include "tensorflow/core/lib/strings/strcat.h"
  27. #include "tensorflow/core/lib/strings/stringprintf.h"
  28. #include "tensorflow/core/platform/logging.h"
  29. #include "tensorflow/core/platform/macros.h"
  30. #include "tensorflow/core/platform/types.h"
  31. namespace tensorflow {
  32. namespace {
  33. const int kRightMargin = 78;
  34. bool IsPythonReserved(const string& s) {
  35. static const std::set<string>* const kPythonReserved = new std::set<string>(
  36. {// Keywords in Python, from:
  37. // import keyword
  38. // print keyword.kwlist
  39. "and", "as", "assert", "break", "class", "continue", "def", "del",
  40. "elif", "else", "except", "exec", "finally", "for", "from", "global",
  41. "if", "import", "in", "is", "lambda", "not", "or", "pass", "print",
  42. "raise", "return", "try", "while", "with", "yield",
  43. // Built-in functions and types in Python, from:
  44. // [x for x in dir(__builtins__) if not x[0].islower()]
  45. "ArithmeticError", "AssertionError", "AttributeError", "BaseException",
  46. "BufferError", "BytesWarning", "DeprecationWarning", "EOFError",
  47. "Ellipsis", "EnvironmentError", "Exception", "False",
  48. "FloatingPointError", "FutureWarning", "GeneratorExit", "IOError",
  49. "ImportError", "ImportWarning", "IndentationError", "IndexError",
  50. "KeyError", "KeyboardInterrupt", "LookupError", "MemoryError",
  51. "NameError", "None", "NotImplemented", "NotImplementedError", "OSError",
  52. "OverflowError", "PendingDeprecationWarning", "ReferenceError",
  53. "RuntimeError", "RuntimeWarning", "StandardError", "StopIteration",
  54. "SyntaxError", "SyntaxWarning", "SystemError", "SystemExit", "TabError",
  55. "True", "TypeError", "UnboundLocalError", "UnicodeDecodeError",
  56. "UnicodeEncodeError", "UnicodeError", "UnicodeTranslateError",
  57. "UnicodeWarning", "UserWarning", "ValueError", "Warning",
  58. "ZeroDivisionError", "__debug__", "__doc__", "__import__", "__name__",
  59. "__package__",
  60. // Imports and symbols used in the generated code:
  61. "_op_def_lib", "text_format", "op_def_pb2", "op_def_library", "ops"});
  62. return kPythonReserved->count(s) > 0;
  63. }
  64. // Add a _ to the end of s if necessary to avoid a Python keyword or built-in.
  65. string AvoidPythonReserved(const string& s) {
  66. if (IsPythonReserved(s)) return strings::StrCat(s, "_");
  67. return s;
  68. }
  69. // Indent the first line by "initial" spaces and all following lines
  70. // by "rest" spaces.
  71. string Indent(int initial, int rest, StringPiece in) {
  72. // TODO(josh11b): Also word-wrapping?
  73. string copy(in.data(), in.size());
  74. str_util::StripTrailingWhitespace(&copy);
  75. std::vector<string> v = str_util::Split(copy, '\n');
  76. string result;
  77. bool first = true;
  78. for (const string& line : v) {
  79. if (first) {
  80. result = strings::StrCat(Spaces(initial), line, "\n");
  81. first = false;
  82. } else {
  83. if (line.empty()) {
  84. strings::StrAppend(&result, "\n");
  85. } else {
  86. strings::StrAppend(&result, Spaces(rest), line, "\n");
  87. }
  88. }
  89. }
  90. return result;
  91. }
  92. // Adds append to *dest, with a space if the first line will be <= width,
  93. // or a newline otherwise.
  94. void AppendWithinWidth(string* dest, StringPiece append, int width) {
  95. auto first_line = append.find('\n');
  96. if (first_line == string::npos) first_line = append.size();
  97. if (dest->size() + first_line + 1 /* space */ > static_cast<size_t>(width)) {
  98. strings::StrAppend(dest, "\n", append);
  99. } else {
  100. strings::StrAppend(dest, " ", append);
  101. }
  102. }
  103. // Like DataTypeString() but uses the Python names for the
  104. // float types.
  105. string PythonDataTypeString(DataType dtype) {
  106. switch (dtype) {
  107. case DT_FLOAT:
  108. return "float32";
  109. case DT_DOUBLE:
  110. return "float64";
  111. default:
  112. return DataTypeString(dtype);
  113. }
  114. }
  115. string TypeString(DataType dtype, bool ref) {
  116. if (ref) {
  117. return strings::StrCat("mutable `", PythonDataTypeString(dtype), "`");
  118. } else {
  119. return strings::StrCat("`", PythonDataTypeString(dtype), "`");
  120. }
  121. }
  122. string TypeListString(const AttrValue& value) {
  123. string ret;
  124. for (int t : value.list().type()) {
  125. if (!ret.empty()) strings::StrAppend(&ret, ", ");
  126. DataType dtype = static_cast<DataType>(t);
  127. if (IsRefType(dtype)) {
  128. strings::StrAppend(&ret, PythonDataTypeString(RemoveRefType(dtype)),
  129. " mutable");
  130. } else {
  131. strings::StrAppend(&ret, "`", PythonDataTypeString(dtype), "`");
  132. }
  133. }
  134. return ret;
  135. }
  136. string SingleTensorName(DataType dtype, bool is_ref) {
  137. const string type_str = TypeString(dtype, is_ref);
  138. return strings::StrCat("A `Tensor` of type ", type_str, ".");
  139. }
  140. const char kUnknownTensorType[] = {"A `Tensor`."};
  141. string ArgTypeName(const OpDef& op_def, const OpDef::ArgDef& arg,
  142. const std::unordered_map<string, string>& inferred_attrs,
  143. bool is_output) {
  144. if (!arg.number_attr().empty()) {
  145. // N Tensors with the same type
  146. const string* original_arg =
  147. gtl::FindOrNull(inferred_attrs, arg.number_attr());
  148. string prefix;
  149. if (original_arg == nullptr) {
  150. prefix = strings::StrCat("A list of `", arg.number_attr(), "`");
  151. } else if (*original_arg == arg.name()) {
  152. const OpDef::AttrDef* attr = FindAttr(arg.number_attr(), op_def);
  153. if (attr->has_minimum() && attr->minimum() > 0) {
  154. prefix = strings::StrCat("A list of at least ", attr->minimum());
  155. } else {
  156. prefix = "A list of";
  157. }
  158. } else {
  159. prefix = strings::StrCat(
  160. "A list with the same number of `Tensor` objects as `",
  161. AvoidPythonReserved(*original_arg), "` of");
  162. }
  163. if (arg.type() != DT_INVALID) {
  164. return strings::StrCat(prefix, " `Tensor` objects of type ",
  165. TypeString(arg.type(), arg.is_ref()), ".");
  166. } else {
  167. original_arg = gtl::FindOrNull(inferred_attrs, arg.type_attr());
  168. if (arg.is_ref()) {
  169. strings::StrAppend(&prefix, " mutable");
  170. }
  171. if (original_arg == nullptr) {
  172. return strings::StrCat(prefix, " `Tensor` objects of type ",
  173. arg.type_attr(), ".");
  174. } else if (*original_arg == arg.name()) {
  175. const OpDef::AttrDef* attr = FindAttr(arg.type_attr(), op_def);
  176. if (attr->has_allowed_values()) {
  177. return strings::StrCat(prefix,
  178. " `Tensor` objects of the same type in: ",
  179. TypeListString(attr->allowed_values()), ".");
  180. } else {
  181. return strings::StrCat(prefix, " `Tensor` objects of the same type.");
  182. }
  183. } else {
  184. return strings::StrCat(prefix, " `Tensor` objects of the same type as ",
  185. AvoidPythonReserved(*original_arg), ".");
  186. }
  187. }
  188. } else if (!arg.type_attr().empty() || !arg.type_list_attr().empty()) {
  189. const bool is_list = !arg.type_list_attr().empty();
  190. const string attr_name = is_list ? arg.type_list_attr() : arg.type_attr();
  191. const OpDef::AttrDef* attr = FindAttr(attr_name, op_def);
  192. const string mutable_str = arg.is_ref() ? "mutable " : "";
  193. const string prefix =
  194. is_list ? strings::StrCat("A list of ", mutable_str, "`Tensor` objects")
  195. : strings::StrCat("A ", mutable_str, "`Tensor`");
  196. const string* original_arg = gtl::FindOrNull(inferred_attrs, attr_name);
  197. if (original_arg == nullptr) {
  198. return strings::StrCat(prefix, " of type `", attr_name, "`.");
  199. } else if (*original_arg == arg.name()) {
  200. if (attr->has_allowed_values()) {
  201. if (is_list) {
  202. return strings::StrCat(prefix, " with types from: ",
  203. TypeListString(attr->allowed_values()), ".");
  204. } else {
  205. return strings::StrCat(
  206. prefix, is_output ? ". Has one of the following types: "
  207. : ". Must be one of the following types: ",
  208. TypeListString(attr->allowed_values()), ".");
  209. }
  210. } else {
  211. return strings::StrCat(prefix, ".");
  212. }
  213. } else {
  214. return strings::StrCat(prefix,
  215. is_output ? ". Has the same type as `"
  216. : ". Must have the same type as `",
  217. AvoidPythonReserved(*original_arg), "`.");
  218. }
  219. } else {
  220. return SingleTensorName(arg.type(), arg.is_ref());
  221. }
  222. }
  223. static string GetReturns(const OpDef& op_def,
  224. const std::vector<string>& output_type_string) {
  225. string result;
  226. DCHECK_EQ(op_def.output_arg_size(), output_type_string.size());
  227. const int num_outs = op_def.output_arg_size();
  228. strings::Appendf(&result, "\n Returns:\n");
  229. if (num_outs == 0) {
  230. strings::Appendf(&result, " The created Operation.\n");
  231. } else {
  232. if (num_outs == 1) {
  233. StringPiece description = op_def.output_arg(0).description();
  234. if (ConsumeEquals(&description)) { // Skip the generated type info.
  235. strings::Appendf(&result, "%s", Indent(4, 4, description).c_str());
  236. } else {
  237. // Special case of one output, don't use the name of the output unless
  238. // there is no description.
  239. string desc = output_type_string.empty() ? kUnknownTensorType
  240. : output_type_string[0];
  241. if (desc == kUnknownTensorType) {
  242. // Special case where we don't understand how the output tensor type
  243. // depends on the input tensor types, just use the output arg
  244. // description if we can.
  245. if (!description.empty()) {
  246. desc = op_def.output_arg(0).description();
  247. } else if (!op_def.output_arg(0).name().empty()) {
  248. desc = strings::StrCat(" The ", op_def.output_arg(0).name(),
  249. " `Tensor`.");
  250. }
  251. } else if (!description.empty()) {
  252. AppendWithinWidth(&desc, description, kRightMargin - 4 /* indent */);
  253. }
  254. strings::Appendf(&result, "%s", Indent(4, 4, desc).c_str());
  255. }
  256. } else {
  257. std::vector<string> out_names(num_outs);
  258. for (int i = 0; i < num_outs; ++i) {
  259. if (!op_def.output_arg(i).name().empty()) {
  260. out_names[i] = op_def.output_arg(i).name();
  261. } else {
  262. out_names[i] = strings::StrCat("output", i);
  263. }
  264. }
  265. strings::Appendf(&result, " A tuple of `Tensor` objects (%s).\n",
  266. str_util::Join(out_names, ", ").c_str());
  267. for (int i = 0; i < num_outs; ++i) {
  268. string desc = strings::StrCat(out_names[i], ": ");
  269. StringPiece description = op_def.output_arg(i).description();
  270. if (ConsumeEquals(&description)) { // Skip the generated type info.
  271. strings::StrAppend(&desc, description);
  272. } else {
  273. const string type = static_cast<size_t>(i) < output_type_string.size()
  274. ? output_type_string[i]
  275. : kUnknownTensorType;
  276. if (!description.empty()) {
  277. if (type == kUnknownTensorType) {
  278. // Special case where we don't understand how the output tensor
  279. // type depends on the input tensor types, so we just use the
  280. // output arg description.
  281. strings::StrAppend(&desc, description);
  282. } else {
  283. strings::StrAppend(&desc, type, " ", description);
  284. }
  285. } else {
  286. strings::StrAppend(&desc, type);
  287. }
  288. }
  289. strings::Appendf(&result, "%s", Indent(4, 6, desc).c_str());
  290. }
  291. }
  292. }
  293. return result;
  294. }
  295. string StringToPython(const string& str) {
  296. return strings::StrCat("\"", str_util::CEscape(str), "\"");
  297. }
  298. string DataTypeToPython(DataType dtype) {
  299. return strings::StrCat("tf.", PythonDataTypeString(dtype));
  300. }
  301. string ShapeToPython(const TensorShapeProto& shape) {
  302. string python = "[";
  303. for (const auto& dim : shape.dim()) {
  304. if (python.size() > 1) strings::StrAppend(&python, ", ");
  305. if (!dim.name().empty()) {
  306. strings::StrAppend(&python, "(", StringToPython(dim.name()), ", ",
  307. dim.size(), ")");
  308. } else {
  309. strings::StrAppend(&python, dim.size());
  310. }
  311. }
  312. strings::StrAppend(&python, "]");
  313. return python;
  314. }
  315. string AttrListToPython(const AttrValue& value) {
  316. string ret;
  317. if (value.list().s_size() > 0) {
  318. for (int i = 0; i < value.list().s_size(); ++i) {
  319. if (i > 0) strings::StrAppend(&ret, ", ");
  320. strings::StrAppend(&ret, StringToPython(value.list().s(i)));
  321. }
  322. } else if (value.list().i_size() > 0) {
  323. for (int i = 0; i < value.list().i_size(); ++i) {
  324. if (i > 0) strings::StrAppend(&ret, ", ");
  325. strings::StrAppend(&ret, value.list().i(i));
  326. }
  327. } else if (value.list().f_size() > 0) {
  328. for (int i = 0; i < value.list().f_size(); ++i) {
  329. if (i > 0) strings::StrAppend(&ret, ", ");
  330. strings::StrAppend(&ret, value.list().f(i));
  331. }
  332. } else if (value.list().b_size() > 0) {
  333. for (int i = 0; i < value.list().b_size(); ++i) {
  334. if (i > 0) strings::StrAppend(&ret, ", ");
  335. strings::StrAppend(&ret, value.list().b(i) ? "True" : "False");
  336. }
  337. } else if (value.list().type_size() > 0) {
  338. for (int i = 0; i < value.list().type_size(); ++i) {
  339. if (i > 0) strings::StrAppend(&ret, ", ");
  340. strings::StrAppend(&ret, DataTypeToPython(value.list().type(i)));
  341. }
  342. } else if (value.list().shape_size() > 0) {
  343. for (int i = 0; i < value.list().shape_size(); ++i) {
  344. if (i > 0) strings::StrAppend(&ret, ", ");
  345. strings::StrAppend(&ret, ShapeToPython(value.list().shape(i)));
  346. }
  347. }
  348. return ret;
  349. }
  350. string AttrValueToPython(const string& type, const AttrValue& value) {
  351. if (type == "string") {
  352. return StringToPython(value.s());
  353. } else if (type == "int") {
  354. return strings::StrCat(value.i());
  355. } else if (type == "float") {
  356. return strings::StrCat(value.f());
  357. } else if (type == "bool") {
  358. return value.b() ? "True" : "False";
  359. } else if (type == "type") {
  360. return DataTypeToPython(value.type());
  361. } else if (type == "shape") {
  362. return ShapeToPython(value.shape());
  363. } else {
  364. return strings::StrCat("[", AttrListToPython(value), "]");
  365. }
  366. }
  367. static string GetPythonOp(const OpDef& op_def, bool is_hidden, string op_name) {
  368. string result;
  369. // Map from attr name to the first input arg it is inferred from.
  370. std::unordered_map<string, string> inferred_attrs;
  371. // This has all the input args followed by those attrs that don't have
  372. // defaults.
  373. std::vector<string> args_no_default;
  374. // The parameters with defaults (these have to be listed after those without).
  375. // No input args are included, just attrs and the graph ("g") parameter.
  376. std::vector<string> args_with_defaults;
  377. for (int i = 0; i < op_def.input_arg_size(); ++i) {
  378. const auto& arg(op_def.input_arg(i));
  379. args_no_default.push_back(arg.name());
  380. if (!arg.type_attr().empty()) {
  381. gtl::InsertIfNotPresent(&inferred_attrs, arg.type_attr(), arg.name());
  382. } else if (!arg.type_list_attr().empty()) {
  383. gtl::InsertIfNotPresent(&inferred_attrs, arg.type_list_attr(),
  384. arg.name());
  385. }
  386. if (!arg.number_attr().empty()) {
  387. gtl::InsertIfNotPresent(&inferred_attrs, arg.number_attr(), arg.name());
  388. }
  389. }
  390. for (int i = 0; i < op_def.attr_size(); ++i) {
  391. const auto& attr(op_def.attr(i));
  392. // Do not add inferred attrs to the Python function signature.
  393. if (inferred_attrs.find(attr.name()) == inferred_attrs.end()) {
  394. if (attr.has_default_value()) {
  395. args_with_defaults.push_back(attr.name());
  396. } else {
  397. args_no_default.push_back(attr.name());
  398. }
  399. }
  400. }
  401. // Save the list of attr parameters (attrs that won't be inferred),
  402. // those with defaults go at the end.
  403. std::vector<string> attrs;
  404. // Get the attrs in the order we want by taking the attrs without defaults
  405. // from the end of args_no_default, and adding args_no_default (before
  406. // "g" gets added to args_no_default, so it only has attrs).
  407. attrs.reserve(args_no_default.size() - op_def.input_arg_size() +
  408. args_with_defaults.size());
  409. attrs.insert(attrs.end(), args_no_default.begin() + op_def.input_arg_size(),
  410. args_no_default.end());
  411. attrs.insert(attrs.end(), args_with_defaults.begin(),
  412. args_with_defaults.end());
  413. std::vector<string> param_names;
  414. param_names.reserve(args_no_default.size() + args_with_defaults.size());
  415. string parameters;
  416. for (const string& name : args_no_default) {
  417. if (!parameters.empty()) strings::StrAppend(&parameters, ", ");
  418. const string param = AvoidPythonReserved(name);
  419. strings::StrAppend(&parameters, param);
  420. param_names.push_back(param);
  421. }
  422. for (const string& name : args_with_defaults) {
  423. if (!parameters.empty()) strings::StrAppend(&parameters, ", ");
  424. const string param = AvoidPythonReserved(name);
  425. strings::StrAppend(&parameters, param, "=None");
  426. param_names.push_back(param);
  427. }
  428. const bool has_args = args_no_default.size() + args_with_defaults.size() > 0;
  429. const string lower_op_name = strings::StrCat(is_hidden ? "_" : "", op_name);
  430. // Prepare the list of output names
  431. const int num_outs = op_def.output_arg_size();
  432. std::vector<string> out_names(num_outs);
  433. for (int i = 0; i < num_outs; ++i) {
  434. if (!op_def.output_arg(i).name().empty()) {
  435. out_names[i] = op_def.output_arg(i).name();
  436. } else {
  437. out_names[i] = strings::StrCat("output", i);
  438. }
  439. }
  440. string out_names_list =
  441. strings::StrCat("[\"", str_util::Join(out_names, "\", \""), "\"]");
  442. // Provide the output names as a Python list
  443. string lower_op_name_outputs =
  444. strings::StrCat("_", lower_op_name, "_outputs");
  445. const string outputs_prefix = strings::StrCat(lower_op_name_outputs, " = ");
  446. strings::Appendf(
  447. &result, "%s\n",
  448. WordWrap(outputs_prefix, out_names_list, kRightMargin).c_str());
  449. strings::Appendf(&result, "\n\n");
  450. // Prepare a NamedTuple type to hold the outputs, if there are multiple
  451. if (num_outs > 1) {
  452. const string tuple_type_prefix =
  453. strings::StrCat("_", op_def.name(), "Output = collections.namedtuple(");
  454. const string tuple_type_suffix = strings::StrCat(
  455. "\"", op_def.name(), "\", ", lower_op_name_outputs, ")");
  456. strings::Appendf(
  457. &result, "%s\n",
  458. WordWrap(tuple_type_prefix, tuple_type_suffix, kRightMargin).c_str());
  459. strings::Appendf(&result, "\n\n");
  460. }
  461. // Print: def Function(parameters):
  462. const string def_prefix = strings::StrCat("def ", lower_op_name, "(");
  463. const string def_suffix =
  464. strings::StrCat(parameters, has_args ? ", " : "", "name=None):");
  465. strings::Appendf(&result, "%s\n",
  466. WordWrap(def_prefix, def_suffix, kRightMargin).c_str());
  467. // Format the Op's descriptions so that it can be a Python docstring.
  468. string comment;
  469. if (op_def.summary().empty()) {
  470. comment = "TODO: add doc.\n";
  471. } else {
  472. comment = strings::StrCat(op_def.summary(), "\n");
  473. if (!op_def.description().empty()) {
  474. strings::StrAppend(&comment, "\n", Indent(2, 2, op_def.description()));
  475. }
  476. }
  477. strings::Appendf(&result, " r\"\"\"%s\n Args:\n", comment.c_str());
  478. // Inputs
  479. for (int i = 0; i < op_def.input_arg_size(); ++i) {
  480. const auto& arg(op_def.input_arg(i));
  481. StringPiece description = op_def.input_arg(i).description();
  482. string desc;
  483. if (ConsumeEquals(&description)) { // Skip the generated type info.
  484. desc = strings::StrCat(param_names[i], ": ");
  485. } else {
  486. desc = strings::StrCat(param_names[i], ": ",
  487. ArgTypeName(op_def, arg, inferred_attrs, false));
  488. }
  489. if (!description.empty()) {
  490. AppendWithinWidth(&desc, description, kRightMargin - 4 /* indent */);
  491. }
  492. strings::Appendf(&result, "%s", Indent(4, 6, desc).c_str());
  493. }
  494. // Attrs
  495. for (const string& name : attrs) {
  496. const auto& attr = *FindAttr(name, op_def);
  497. string desc = strings::StrCat(AvoidPythonReserved(name), ": ");
  498. static const char* const kAttrTypeName[][2] = {
  499. {"string", "`string`"},
  500. {"list(string)", "list of `strings`"},
  501. {"int", "`int`"},
  502. {"list(int)", "list of `ints`"},
  503. {"float", "`float`"},
  504. {"list(float)", "list of `floats`"},
  505. {"bool", "`bool`"},
  506. {"list(bool)", "list of `bools`"},
  507. {"type", "`tf.DType`"},
  508. {"list(type)", "list of `tf.DTypes`"},
  509. {"shape", "`tf.TensorShape` or list of `ints`"},
  510. {"list(shape)",
  511. "list of shapes (each a `tf.TensorShape` or list of `ints`)"},
  512. };
  513. for (size_t i = 0; i < TF_ARRAYSIZE(kAttrTypeName); ++i) {
  514. if (attr.type() == kAttrTypeName[i][0]) {
  515. string s;
  516. if (attr.has_default_value()) {
  517. s = strings::StrCat("optional ", kAttrTypeName[i][1]);
  518. } else {
  519. s = kAttrTypeName[i][1];
  520. }
  521. if (s[0] == 'o' || (s[0] == '`' && (s[1] == 'i' || s[1] == 'o'))) {
  522. strings::StrAppend(&desc, "An ", s);
  523. } else {
  524. strings::StrAppend(&desc, "A ", s);
  525. }
  526. break;
  527. }
  528. }
  529. if (attr.has_allowed_values()) {
  530. strings::StrAppend(&desc, " from: `",
  531. AttrListToPython(attr.allowed_values()), "`");
  532. }
  533. if (attr.has_minimum()) {
  534. if (attr.type() == "int") {
  535. strings::StrAppend(&desc, " that is `>= ", attr.minimum(), "`");
  536. } else if (attr.minimum() > 0) {
  537. strings::StrAppend(&desc, " that has length `>= ", attr.minimum(), "`");
  538. }
  539. }
  540. strings::StrAppend(&desc, ".");
  541. if (attr.has_default_value()) {
  542. strings::StrAppend(&desc, " Defaults to `",
  543. AttrValueToPython(attr.type(), attr.default_value()),
  544. "`.");
  545. }
  546. if (!attr.description().empty()) {
  547. AppendWithinWidth(&desc, attr.description(),
  548. kRightMargin - 4 /* indent */);
  549. }
  550. strings::Appendf(&result, "%s", Indent(4, 6, desc).c_str());
  551. }
  552. strings::Appendf(&result, " name: A name for the operation (optional).\n");
  553. std::vector<string> output_type_string;
  554. output_type_string.reserve(op_def.output_arg_size());
  555. for (int i = 0; i < op_def.output_arg_size(); ++i) {
  556. output_type_string.push_back(
  557. ArgTypeName(op_def, op_def.output_arg(i), inferred_attrs, true));
  558. }
  559. strings::StrAppend(&result, GetReturns(op_def, output_type_string));
  560. string return_prefix = strings::StrCat(" result = _op_def_lib.apply_op(");
  561. string return_args = strings::StrCat("\"", op_def.name(), "\", ");
  562. for (size_t i = 0; i < param_names.size(); ++i) {
  563. strings::StrAppend(&return_args, param_names[i], "=", param_names[i], ", ");
  564. }
  565. strings::StrAppend(&return_args, "name=name)");
  566. strings::Appendf(&result, " \"\"\"\n%s\n",
  567. // Wrap the arguments, and indent to the (.
  568. WordWrap(return_prefix, return_args, kRightMargin).c_str());
  569. if (num_outs <= 1) {
  570. strings::Appendf(&result, " return result\n");
  571. } else {
  572. string return_tuple =
  573. strings::StrCat(" return _", op_def.name(), "Output._make(result)\n");
  574. strings::Appendf(&result, "%s", return_tuple.c_str());
  575. }
  576. strings::Appendf(&result, "\n\n");
  577. return result;
  578. }
  579. void GenerateLowerCaseOpName(const string& str, string* result) {
  580. char joiner = '_';
  581. int last_index = str.size() - 1;
  582. for (int i = 0; i <= last_index; ++i) {
  583. char c = str[i];
  584. // Emit a joiner only if a previous-lower-to-now-upper or a
  585. // now-upper-to-next-lower transition happens.
  586. if (isupper(c) && (i > 0)) {
  587. if (islower(str[i - 1]) || ((i < last_index) && islower(str[i + 1]))) {
  588. result->push_back(joiner);
  589. }
  590. }
  591. result->push_back(tolower(c));
  592. }
  593. }
  594. } // namespace
  595. string GetPythonOps(const OpList& ops, const string& hidden_ops,
  596. bool require_shapes) {
  597. string result;
  598. // Header
  599. // TODO(josh11b): Mention the library for which wrappers are being generated.
  600. strings::Appendf(&result, R"("""Python wrappers around Brain.
  601. This file is MACHINE GENERATED! Do not edit.
  602. """
  603. import collections
  604. from google.protobuf import text_format
  605. from tensorflow.core.framework import op_def_pb2
  606. from tensorflow.python.framework import op_def_registry
  607. from tensorflow.python.framework import ops
  608. from tensorflow.python.ops import op_def_library
  609. )");
  610. std::vector<string> hidden_vec = str_util::Split(hidden_ops, ',');
  611. // We'll make a copy of ops that filters out descriptions.
  612. OpList cleaned_ops;
  613. auto out = cleaned_ops.mutable_op();
  614. out->Reserve(ops.op_size());
  615. for (const auto& op_def : ops.op()) {
  616. bool is_hidden = false;
  617. for (const string& hidden : hidden_vec) {
  618. if (op_def.name() == hidden) {
  619. is_hidden = true;
  620. break;
  621. }
  622. }
  623. // PrintPythonOp(op_def, is_hidden, op_def.name());
  624. string lower_case_name;
  625. GenerateLowerCaseOpName(op_def.name(), &lower_case_name);
  626. // When users create custom python wrappers, they may link in the
  627. // default op registry by accident, and because they can't
  628. // enumerate all 'hidden' symbols, this guard is to prevent
  629. // instantiating a python reserved word in their wrapper.
  630. if (!is_hidden && IsPythonReserved(lower_case_name)) {
  631. continue;
  632. }
  633. strings::StrAppend(&result,
  634. GetPythonOp(op_def, is_hidden, lower_case_name));
  635. if (!require_shapes) {
  636. strings::Appendf(&result, "ops.RegisterShape(\"%s\")(None)\n",
  637. op_def.name().c_str());
  638. }
  639. auto added = out->Add();
  640. *added = op_def;
  641. RemoveNonDeprecationDescriptionsFromOpDef(added);
  642. }
  643. strings::Appendf(&result, R"(def _InitOpDefLibrary():
  644. op_list = op_def_pb2.OpList()
  645. text_format.Merge(_InitOpDefLibrary.op_list_ascii, op_list)
  646. op_def_registry.register_op_list(op_list)
  647. op_def_lib = op_def_library.OpDefLibrary()
  648. op_def_lib.add_op_list(op_list)
  649. return op_def_lib
  650. _InitOpDefLibrary.op_list_ascii = """%s"""
  651. _op_def_lib = _InitOpDefLibrary()
  652. )",
  653. cleaned_ops.DebugString().c_str());
  654. return result;
  655. }
  656. void PrintPythonOps(const OpList& ops, const string& hidden_ops,
  657. bool require_shapes) {
  658. printf("%s", GetPythonOps(ops, hidden_ops, require_shapes).c_str());
  659. }
  660. string GetAllPythonOps(const char* hidden, bool require_shapes) {
  661. OpList ops;
  662. OpRegistry::Global()->Export(false, &ops);
  663. return GetPythonOps(ops, hidden, require_shapes);
  664. }
  665. string GetPythonWrappers(const char* op_wrapper_buf, size_t op_wrapper_len) {
  666. string op_list_str(op_wrapper_buf, op_wrapper_len);
  667. OpList ops;
  668. ops.ParseFromString(op_list_str);
  669. return GetPythonOps(ops, "", false);
  670. }
  671. } // namespace tensorflow