You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

ops.cs 23 kB

4 years ago
6 years ago
4 years ago
6 years ago
6 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
6 years ago
4 years ago
4 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
5 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
4 years ago
4 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560
  1. /*****************************************************************************
  2. Copyright 2018 The TensorFlow.NET Authors. All Rights Reserved.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. ******************************************************************************/
  13. using Google.Protobuf;
  14. using Google.Protobuf.Collections;
  15. using Tensorflow.NumPy;
  16. using System;
  17. using System.Collections.Generic;
  18. using System.Linq;
  19. using System.Threading;
  20. using Tensorflow.Contexts;
  21. using Tensorflow.Eager;
  22. using Tensorflow.Graphs;
  23. using Tensorflow.Util;
  24. using static Tensorflow.Binding;
  25. namespace Tensorflow
  26. {
  27. public partial class ops
  28. {
  29. public static long tensor_id(Tensor tensor)
  30. {
  31. return tensor.Id;
  32. }
  33. public static void add_to_collection<T>(string name, T value)
  34. {
  35. var graph = tf.get_default_graph();
  36. graph.add_to_collection(name, value);
  37. }
  38. public static void add_to_collections<T>(List<string> names, T value)
  39. {
  40. var graph = tf.get_default_graph();
  41. graph.add_to_collections(names, value);
  42. }
  43. /// <summary>
  44. /// Wrapper for `Graph.get_collection()` using the default graph.
  45. /// contains many standard names for collections.
  46. /// </summary>
  47. /// <param name="key">
  48. /// The key for the collection. For example, the `GraphKeys` class
  49. /// </param>
  50. /// <param name="scope"></param>
  51. /// <returns>
  52. /// The list of values in the collection with the given `name`, or
  53. /// an empty list if no value has been added to that collection. The
  54. /// list contains the values in the order under which they were
  55. /// collected.
  56. /// </returns>
  57. public static object get_collection(string key, string scope = null)
  58. {
  59. return get_default_graph().get_collection(key, scope);
  60. }
  61. public static List<T> get_collection<T>(string key, string scope = null)
  62. {
  63. return get_default_graph().get_collection<T>(key, scope);
  64. }
  65. public static List<T> get_collection_ref<T>(string key)
  66. {
  67. return get_default_graph().get_collection_ref<T>(key);
  68. }
  69. public static Graph _get_graph_from_inputs(params object[] op_input_list)
  70. {
  71. var current_default_graph = get_default_graph();
  72. if (current_default_graph.building_function)
  73. return current_default_graph;
  74. Graph graph = null;
  75. foreach (var op_input in op_input_list)
  76. {
  77. if (op_input is Tensor op_input_tensor)
  78. graph = graph ?? op_input_tensor.graph;
  79. }
  80. return graph ?? current_default_graph;
  81. }
  82. public static Graph _get_graph_from_inputs(Tensors op_input_list)
  83. => _get_graph_from_inputs(op_input_list: op_input_list, graph: null);
  84. public static Graph _get_graph_from_inputs(Tensors op_input_list, Graph graph = null)
  85. {
  86. foreach (var op_input in op_input_list)
  87. {
  88. // Determine if this is a valid graph_element.
  89. // var graph_element = op_input;
  90. }
  91. return get_default_graph();
  92. }
  93. /// <summary>
  94. /// Converts the given `value` to a `Tensor`.
  95. /// </summary>
  96. /// <param name="value"></param>
  97. /// <param name="dtype"></param>
  98. /// <param name="name"></param>
  99. /// <returns></returns>
  100. public static Tensor convert_to_tensor(object value,
  101. TF_DataType dtype = TF_DataType.DtInvalid,
  102. string name = null,
  103. bool as_ref = false,
  104. TF_DataType preferred_dtype = TF_DataType.DtInvalid,
  105. Context ctx = null)
  106. {
  107. if (dtype == TF_DataType.DtInvalid)
  108. dtype = preferred_dtype;
  109. if (dtype == TF_DataType.DtInvalid)
  110. dtype = value.GetDataType();
  111. if (value is EagerTensor eager_tensor)
  112. {
  113. if (tf.executing_eagerly())
  114. {
  115. if (dtype != TF_DataType.DtInvalid && dtype != eager_tensor.dtype)
  116. return gen_math_ops.cast(eager_tensor, dtype.as_base_dtype(), name: name);
  117. return eager_tensor;
  118. }
  119. else
  120. {
  121. var graph = get_default_graph();
  122. if (!graph.building_function)
  123. throw new RuntimeError("Attempting to capture an EagerTensor without building a function.");
  124. return (graph as FuncGraph).capture(eager_tensor, name: name);
  125. }
  126. }
  127. // graph mode
  128. Tensor ret = value switch
  129. {
  130. NDArray nd => constant_op.constant(nd, dtype: dtype, name: name),
  131. EagerTensor tensor => tensor.dtype == TF_DataType.TF_RESOURCE
  132. ? tensor.AsPlaceholder(name: name)
  133. : tensor.AsConstant(name: name),
  134. Tensor tensor => tensor,
  135. IEnumerable<Tensor> tensors => array_ops._autopacking_helper(tensors, dtype, name == null ? "packed" : name),
  136. RefVariable varVal => varVal._TensorConversionFunction(dtype: dtype, name: name, as_ref: as_ref),
  137. ResourceVariable varVal => varVal._TensorConversionFunction(dtype: dtype, name: name, as_ref: as_ref),
  138. Axis ts => constant_op.constant(ts, dtype: dtype, name: name),
  139. Shape ts => constant_op.constant(ts.dims, dtype: dtype, name: name),
  140. string str => constant_op.constant(str, dtype: tf.@string, name: name),
  141. string[] str => constant_op.constant(str, dtype: tf.@string, name: name),
  142. IEnumerable<object> objects => array_ops._autopacking_conversion_function(objects, dtype: dtype, name: name),
  143. _ => constant_op.constant(value, dtype: dtype, name: name)
  144. };
  145. if (dtype == TF_DataType.TF_STRING)
  146. return ret;
  147. if (dtype != TF_DataType.DtInvalid && dtype.as_base_dtype() != ret.dtype.as_base_dtype())
  148. ret = gen_math_ops.cast(ret, dtype, name: name);
  149. return ret;
  150. }
  151. public static Tensor convert_to_tensor_or_composite(Tensor value, TF_DataType dtype = TF_DataType.DtInvalid, string name = null)
  152. {
  153. return internal_convert_to_tensor_or_composite(value: value, dtype: dtype, name: name, as_ref: false);
  154. }
  155. public static Tensor internal_convert_to_tensor_or_composite(Tensor value, TF_DataType dtype = TF_DataType.DtInvalid, string name = null, bool as_ref = false)
  156. => convert_to_tensor(value, dtype: dtype, name: name, as_ref: as_ref);
  157. /// <summary>
  158. /// Wrapper for `Graph.control_dependencies()` using the default graph.
  159. ///
  160. /// See `tf.Graph.control_dependencies` for more details.
  161. ///
  162. /// When eager execution is enabled, any callable object in the `control_inputs`
  163. /// list will be called.
  164. /// </summary>
  165. /// <param name="control_inputs">
  166. /// A list of `Operation` or `Tensor` objects which
  167. /// must be executed or computed before running the operations
  168. /// defined in the context.Can also be `None` to clear the control
  169. /// dependencies.If eager execution is enabled, any callable object in the
  170. /// `control_inputs` list will be called.
  171. /// </param>
  172. /// <returns>
  173. /// A context manager that specifies control dependencies for all
  174. /// operations constructed within the context.
  175. /// </returns>
  176. public static _ControlDependenciesController control_dependencies(object[] control_inputs)
  177. => get_default_graph().control_dependencies(control_inputs);
  178. /// <summary>
  179. /// Creates a TF_Operation.
  180. /// </summary>
  181. /// <param name="graph">a `Graph`.</param>
  182. /// <param name="node_def">`node_def_pb2.NodeDef` for the operation to create.</param>
  183. /// <param name="inputs">
  184. /// A list of `Tensor`s (corresponding to scalar inputs) and lists of
  185. /// `Tensor`s (corresponding to sequence inputs, e.g. "int64 * N",
  186. /// "list(int64)"). The length of the list should be equal to the number of
  187. /// inputs specified by this operation's op def.
  188. /// </param>
  189. /// <param name="control_inputs">A list of `Operation`s to set as control dependencies.</param>
  190. /// <returns>A wrapped TF_Operation*.</returns>
  191. public static (IntPtr, OperationDescription) _create_c_op(Graph graph, NodeDef node_def, Tensor[] inputs, Operation[] control_inputs,
  192. OpDef op_def = null)
  193. {
  194. if (op_def == null)
  195. op_def = graph.GetOpDef(node_def.Op);
  196. var input_tensors = _reconstruct_sequence_inputs(op_def, inputs, node_def.Attr);
  197. lock (Locks.ProcessWide)
  198. {
  199. var op_desc = graph.NewOperation(node_def.Op, node_def.Name);
  200. if (!string.IsNullOrEmpty(node_def.Device))
  201. c_api.TF_SetDevice(op_desc, node_def.Device);
  202. // Add inputs
  203. foreach (var op_input in input_tensors)
  204. {
  205. if (op_input.IsList)
  206. c_api.TF_AddInputList(op_desc, op_input.Select(x => x._as_tf_output()).ToArray(), op_input.Count());
  207. else if (op_input.Count() == 1)
  208. c_api.TF_AddInput(op_desc, op_input[0]._as_tf_output());
  209. }
  210. var status = tf.Status;
  211. // Add control inputs
  212. foreach (var control_input in control_inputs)
  213. c_api.TF_AddControlInput(op_desc, control_input);
  214. // Add attrs
  215. foreach (var attr in node_def.Attr)
  216. {
  217. var bytes = attr.Value.ToByteArray();
  218. c_api.TF_SetAttrValueProto(op_desc, attr.Key, bytes, proto_len: bytes.Length, status: status.Handle);
  219. status.Check(true);
  220. }
  221. var c_op = c_api.TF_FinishOperation(op_desc, status.Handle);
  222. status.Check(true);
  223. return (c_op, op_desc);
  224. }
  225. }
  226. public static Tensors[] _reconstruct_sequence_inputs(OpDef op_def, Tensor[] inputs, MapField<string, AttrValue> attrs)
  227. {
  228. var grouped_inputs = new List<Tensors>();
  229. int i = 0;
  230. foreach (var input_arg in op_def.InputArg)
  231. {
  232. int input_len = 1;
  233. bool is_sequence = false;
  234. if (!string.IsNullOrEmpty(input_arg.NumberAttr))
  235. {
  236. input_len = (int)attrs[input_arg.NumberAttr].I;
  237. is_sequence = true;
  238. }
  239. else if (!string.IsNullOrEmpty(input_arg.TypeListAttr))
  240. {
  241. input_len = attrs[input_arg.TypeListAttr].List.Type.Count;
  242. is_sequence = true;
  243. }
  244. if (is_sequence)
  245. {
  246. var input_tensors = new Tensors(inputs.Skip(i).Take(input_len).ToArray());
  247. input_tensors.IsList = true;
  248. grouped_inputs.Add(input_tensors);
  249. }
  250. else
  251. grouped_inputs.Add(inputs[i]);
  252. i += input_len;
  253. }
  254. return grouped_inputs.ToArray();
  255. }
  256. public static OpDef _get_op_def(Graph graph, string type)
  257. {
  258. return graph.GetOpDef(type);
  259. }
  260. public static NodeDef _NodeDef(string op_type, string name, Dictionary<string, AttrValue> attrs = null)
  261. {
  262. var node_def = new NodeDef();
  263. node_def.Op = op_type;
  264. node_def.Name = name;
  265. if (attrs != null)
  266. {
  267. foreach (var attr in attrs)
  268. node_def.Attr.Add(attr.Key, attr.Value);
  269. }
  270. return node_def;
  271. }
  272. public static string name_from_scope_name(string name)
  273. {
  274. if (name == null)
  275. return null;
  276. else if (name.EndsWith("/"))
  277. return name.Substring(0, name.Length - 1);
  278. else
  279. return name;
  280. }
  281. /// <summary>
  282. /// A context manager that lifts ops out of control-flow scopes and function-building graphs.
  283. /// </summary>
  284. /// <returns></returns>
  285. public static NameScope init_scope()
  286. {
  287. // Retrieve the active name scope: entering an `init_scope` preserves
  288. // the name scope of the current context.
  289. var default_graph = get_default_graph();
  290. var scope = default_graph.get_name_scope();
  291. if (!String.IsNullOrEmpty(scope) && !scope.EndsWith("/"))
  292. // Names that end with trailing slashes are treated by `name_scope` as
  293. // absolute.
  294. scope += "/";
  295. // inner_device_stack = default_graph._device_function_stack
  296. // var outer_context = default_graph.as_default;
  297. tf_with(ops.control_dependencies(null), delegate
  298. {
  299. // var outer_graph = get_default_graph();
  300. // outer_device_stack = None
  301. });
  302. tf.Context.ScopeName = scope;
  303. return ops.name_scope(scope);
  304. }
  305. private static int uid_number = -1;
  306. /// <summary>
  307. /// A unique (within this program execution) integer.
  308. /// Not thread safe
  309. /// </summary>
  310. /// <returns></returns>
  311. public static int uid()
  312. {
  313. return Interlocked.Increment(ref uid_number);
  314. }
  315. static int uid_number_for_function = 0;
  316. public static int uid_function()
  317. => Interlocked.Increment(ref uid_number_for_function);
  318. public static void reset_uid()
  319. {
  320. uid_number = -1;
  321. }
  322. public static void colocate_with(bool ignore_existing = false)
  323. {
  324. _colocate_with_for_gradient(null, null, ignore_existing);
  325. }
  326. public static void colocate_with(Operation op, bool ignore_existing = false)
  327. {
  328. _colocate_with_for_gradient(op, null, ignore_existing);
  329. }
  330. public static void colocate_with(Tensor tensor, bool ignore_existing = false)
  331. {
  332. _colocate_with_for_gradient(tensor.op, null, ignore_existing);
  333. }
  334. public static void colocate_with(IVariableV1 variable, bool ignore_existing = false)
  335. {
  336. _colocate_with_for_gradient(variable.AsTensor(), null, ignore_existing);
  337. }
  338. public static void _colocate_with_for_gradient(Operation op, string gradient_uid, bool ignore_existing = false)
  339. {
  340. var default_graph = get_default_graph();
  341. default_graph._colocate_with_for_gradient(op, gradient_uid, ignore_existing);
  342. }
  343. /// <summary>
  344. /// Uses the default session to evaluate one or more tensors.
  345. /// </summary>
  346. /// <param name="tensor">A single Tensor, or a list of Tensor objects.</param>
  347. /// <param name="feed_dict">
  348. /// A dictionary that maps Tensor objects (or tensor names) to lists,
  349. /// numpy ndarrays, TensorProtos, or strings.
  350. /// </param>
  351. /// <param name="graph">The graph in which the tensors are defined.</param>
  352. /// <param name="session">A different session to use to evaluate "tensors".</param>
  353. /// <returns>
  354. /// Either a single numpy ndarray if "tensors" is a single tensor; or a list
  355. /// of numpy ndarrays that each correspond to the respective element in
  356. /// "tensors".
  357. /// </returns>
  358. public static NDArray _eval_using_default_session(Tensor tensor, FeedItem[] feed_dict, Graph graph, Session session = null)
  359. {
  360. if (session == null)
  361. {
  362. session = get_default_session();
  363. if (session == null)
  364. throw new ValueError("Cannot evaluate tensor using `eval()`: No default " +
  365. "session is registered. Use `with " +
  366. "sess.as_default()` or pass an explicit session to " +
  367. "`eval(session=sess)`");
  368. if (session.graph != graph)
  369. throw new ValueError("Cannot use the default session to evaluate tensor: " +
  370. "the tensor's graph is different from the session's " +
  371. "graph. Pass an explicit session to " +
  372. "`eval(session=sess)`.");
  373. }
  374. else
  375. {
  376. if (session.graph != graph)
  377. throw new ValueError("Cannot use the default session to evaluate tensor: " +
  378. "the tensor's graph is different from the session's " +
  379. "graph. Pass an explicit session to " +
  380. "`eval(session=sess)`.");
  381. }
  382. return session.run(tensor, feed_dict);
  383. }
  384. /// <summary>
  385. /// Prepends name scope to a name.
  386. /// </summary>
  387. /// <param name="name"></param>
  388. /// <param name="import_scope"></param>
  389. /// <returns></returns>
  390. public static string prepend_name_scope(string name, string import_scope)
  391. {
  392. if (!string.IsNullOrEmpty(import_scope))
  393. {
  394. if (import_scope.EndsWith("/"))
  395. import_scope = import_scope.Substring(0, import_scope.Length - 1);
  396. return $"{import_scope}/{name}";
  397. }
  398. else
  399. return name;
  400. }
  401. public static void _run_using_default_session(Operation operation, FeedItem[] feed_dict, Graph graph, Session session)
  402. {
  403. if (session == null)
  404. {
  405. session = get_default_session();
  406. if (session == null)
  407. throw new ValueError("Cannot execute operation using `run()`: No default " +
  408. "session is registered. Use `with " +
  409. "sess.as_default():` or pass an explicit session to " +
  410. "`run(session=sess)`");
  411. }
  412. if (session.graph != graph)
  413. throw new ValueError("Cannot use the default session to execute operation: " +
  414. "the operation's graph is different from the " +
  415. "session's graph. Pass an explicit session to " +
  416. "run(session=sess).");
  417. session.run(operation, feed_dict);
  418. }
  419. public static Tensor[] convert_n_to_tensor(object[] values, TF_DataType dtype = TF_DataType.DtInvalid, string name = null)
  420. => internal_convert_n_to_tensor(values, dtype: dtype, name: name, as_ref: false);
  421. public static Tensor[] convert_n_to_tensor_or_indexed_slices(Tensor[] values, TF_DataType dtype = TF_DataType.DtInvalid, string name = null)
  422. => internal_convert_n_to_tensor_or_indexed_slices(values, dtype: dtype, name: name);
  423. public static Tensor convert_to_tensor_or_indexed_slices(Tensor value, TF_DataType dtype = TF_DataType.DtInvalid, string name = null)
  424. => internal_convert_to_tensor_or_indexed_slices(value: value, dtype: dtype, name: name, as_ref: false);
  425. public static Tensor internal_convert_to_tensor_or_indexed_slices(Tensor value, TF_DataType dtype = TF_DataType.DtInvalid, string name = null, bool as_ref = false)
  426. => value;
  427. public static Tensor[] internal_convert_n_to_tensor_or_indexed_slices(Tensor[] values, TF_DataType dtype = TF_DataType.DtInvalid, string name = null, bool as_ref = false)
  428. {
  429. var ret = new List<Tensor>();
  430. foreach (var (i, value) in enumerate(values))
  431. {
  432. if (value == null)
  433. {
  434. ret.Add(value);
  435. }
  436. else
  437. {
  438. var n = string.IsNullOrEmpty(name) ? "" : $"{name}_{i}";
  439. ret.Add(internal_convert_to_tensor_or_indexed_slices(value, dtype: dtype, name: n, as_ref: as_ref));
  440. }
  441. }
  442. return ret.ToArray();
  443. }
  444. public static Tensor[] internal_convert_n_to_tensor(object[] values, TF_DataType dtype = TF_DataType.DtInvalid,
  445. string name = null, TF_DataType preferred_dtype = TF_DataType.DtInvalid,
  446. bool as_ref = false)
  447. {
  448. var ret = new List<Tensor>();
  449. foreach ((int i, object value) in enumerate(values))
  450. {
  451. string n = string.IsNullOrEmpty(name) ? "" : $"{name}_{i}";
  452. ret.Add(convert_to_tensor(value, dtype: dtype, name: n, as_ref: as_ref, preferred_dtype: preferred_dtype));
  453. }
  454. return ret.ToArray();
  455. }
  456. public static string strip_name_scope(string name, string export_scope = "")
  457. {
  458. if (!string.IsNullOrEmpty(export_scope))
  459. {
  460. throw new NotImplementedException("ops.strip_name_scope");
  461. }
  462. else
  463. {
  464. return name;
  465. }
  466. }
  467. public static string get_name_scope()
  468. {
  469. var g = get_default_graph();
  470. return g.get_name_scope();
  471. }
  472. public static bool executing_eagerly_outside_functions()
  473. {
  474. if (tf.Context.executing_eagerly())
  475. return true;
  476. else
  477. throw new NotImplementedException("");
  478. }
  479. }
  480. }