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 20 kB

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