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