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.

Operation.cs 12 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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  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.Collections;
  14. using System;
  15. using System.Collections.Generic;
  16. using System.IO;
  17. using System.Linq;
  18. using Tensorflow.Util;
  19. using static Tensorflow.Binding;
  20. namespace Tensorflow
  21. {
  22. /// <summary>
  23. /// Represents a graph node that performs computation on tensors.
  24. ///
  25. /// An `Operation` is a node in a TensorFlow `Graph` that takes zero or
  26. /// more `Tensor` objects as input, and produces zero or more `Tensor`
  27. /// objects as output. Objects of type `Operation` are created by
  28. /// calling an op constructor(such as `tf.matmul`)
  29. /// or `tf.Graph.create_op`.
  30. ///
  31. /// For example `c = tf.matmul(a, b)` creates an `Operation` of type
  32. /// "MatMul" that takes tensors `a` and `b` as input, and produces `c`
  33. /// as output.
  34. ///
  35. /// After the graph has been launched in a session, an `Operation` can
  36. /// be executed by passing it to
  37. /// `tf.Session.run`.
  38. /// `op.run()` is a shortcut for calling `tf.get_default_session().run(op)`.
  39. /// </summary>
  40. public partial class Operation : ITensorOrOperation
  41. {
  42. private readonly IntPtr _handle; // _c_op in python
  43. private readonly Graph _graph;
  44. private NodeDef _node_def;
  45. public string type => OpType;
  46. public Graph graph => _graph;
  47. public int _id => _id_value;
  48. public int _id_value { get; set; }
  49. public Operation op => this;
  50. public TF_DataType dtype => TF_DataType.DtInvalid;
  51. public virtual string name => _handle == IntPtr.Zero ? null : c_api.StringPiece(c_api.TF_OperationName(_handle));
  52. public string OpType => _handle == IntPtr.Zero ? null : c_api.StringPiece(c_api.TF_OperationOpType(_handle));
  53. public string Device => _handle == IntPtr.Zero ? null : c_api.StringPiece(c_api.TF_OperationDevice(_handle));
  54. bool _is_stateful;
  55. public OperationDescription OpDesc { get; set; }
  56. public NodeDef node_def
  57. {
  58. get
  59. {
  60. if (_node_def == null)
  61. _node_def = GetNodeDef();
  62. return _node_def;
  63. }
  64. }
  65. public Operation(IntPtr handle, Graph g = null)
  66. {
  67. if (handle == IntPtr.Zero)
  68. return;
  69. _handle = handle;
  70. _graph = g ?? ops.get_default_graph();
  71. _outputs = new Tensor[NumOutputs];
  72. for (int i = 0; i < NumOutputs; i++)
  73. _outputs[i] = new Tensor(this, i, OutputType(i));
  74. // Dict mapping op name to file and line information for op colocation
  75. // context managers.
  76. _control_flow_context = _graph._get_control_flow_context();
  77. // Note: _control_flow_post_processing() must not be called here, the caller is responsible for calling it when using this constructor.
  78. }
  79. /*public Operation(Graph g, string opType, string oper_name)
  80. {
  81. _graph = g;
  82. var _operDesc = c_api.TF_NewOperation(g, opType, oper_name);
  83. c_api.TF_SetAttrType(_operDesc, "dtype", TF_DataType.TF_INT32);
  84. lock (Locks.ProcessWide)
  85. using (var status = new Status())
  86. {
  87. _handle = c_api.TF_FinishOperation(_operDesc, status);
  88. status.Check(true);
  89. }
  90. // Dict mapping op name to file and line information for op colocation
  91. // context managers.
  92. _control_flow_context = graph._get_control_flow_context();
  93. }*/
  94. /// <summary>
  95. /// Creates an `Operation`.
  96. /// </summary>
  97. /// <param name="node_def">`node_def_pb2.NodeDef`. `NodeDef` for the `Operation`.</param>
  98. /// <param name="g">`Graph`. The parent graph.</param>
  99. /// <param name="inputs">list of `Tensor` objects. The inputs to this `Operation`.</param>
  100. /// <param name="output_types">list of `DType` objects.</param>
  101. /// <param name="control_inputs">
  102. /// list of operations or tensors from which to have a
  103. /// control dependency.
  104. /// </param>
  105. /// <param name="input_types">
  106. /// List of `DType` objects representing the
  107. /// types of the tensors accepted by the `Operation`. By default
  108. /// uses `[x.dtype.base_dtype for x in inputs]`. Operations that expect
  109. /// reference-typed inputs must specify these explicitly.
  110. /// </param>
  111. /// <param name="original_op"></param>
  112. /// <param name="op_def"></param>
  113. public Operation(NodeDef node_def, Graph g, Tensor[] inputs = null, TF_DataType[] output_types = null, ITensorOrOperation[] control_inputs = null, TF_DataType[] input_types = null, string original_op = "", OpDef op_def = null)
  114. {
  115. _graph = g;
  116. // Build the list of control inputs.
  117. var control_input_ops = new List<Operation>();
  118. if (control_inputs != null)
  119. {
  120. foreach (var c in control_inputs)
  121. {
  122. switch (c)
  123. {
  124. case Operation c1:
  125. control_input_ops.Add(c1);
  126. break;
  127. case Tensor tensor:
  128. control_input_ops.Add(tensor.op);
  129. break;
  130. // TODO: IndexedSlices don't yet exist, but once they do, this needs to be uncommented
  131. //case IndexedSlices islices:
  132. // control_input_ops.Add(islices.op);
  133. // break;
  134. default:
  135. throw new NotImplementedException($"Control input must be an Operation, a Tensor, or IndexedSlices: {c}");
  136. }
  137. }
  138. }
  139. _id_value = _graph._next_id();
  140. // Dict mapping op name to file and line information for op colocation
  141. // context managers.
  142. _control_flow_context = graph._get_control_flow_context();
  143. // This will be set by self.inputs.
  144. if (op_def == null)
  145. op_def = g.GetOpDef(node_def.Op);
  146. var grouped_inputs = _reconstruct_sequence_inputs(op_def, inputs, node_def.Attr);
  147. (_handle, OpDesc) = ops._create_c_op(g, node_def, grouped_inputs, control_input_ops.ToArray());
  148. _is_stateful = op_def.IsStateful;
  149. // Initialize self._outputs.
  150. output_types = new TF_DataType[NumOutputs];
  151. for (int i = 0; i < NumOutputs; i++)
  152. output_types[i] = OutputType(i);
  153. _outputs = new Tensor[NumOutputs];
  154. for (int i = 0; i < NumOutputs; i++)
  155. _outputs[i] = new Tensor(this, i, output_types[i]);
  156. graph._add_op(this);
  157. if (_handle != IntPtr.Zero)
  158. _control_flow_post_processing();
  159. }
  160. public void run(FeedItem[] feed_dict = null, Session session = null)
  161. {
  162. ops._run_using_default_session(this, feed_dict, graph, session);
  163. }
  164. private object[] _reconstruct_sequence_inputs(OpDef op_def, Tensor[] inputs, MapField<string, AttrValue> attrs)
  165. {
  166. var grouped_inputs = new List<object>();
  167. int i = 0;
  168. int input_len = 0;
  169. bool is_sequence = false;
  170. foreach (var input_arg in op_def.InputArg)
  171. {
  172. if (!string.IsNullOrEmpty(input_arg.NumberAttr))
  173. {
  174. input_len = (int) attrs[input_arg.NumberAttr].I;
  175. is_sequence = true;
  176. } else if (!string.IsNullOrEmpty(input_arg.TypeListAttr))
  177. {
  178. input_len = attrs[input_arg.TypeListAttr].List.Type.Count;
  179. is_sequence = true;
  180. } else
  181. {
  182. input_len = 1;
  183. is_sequence = false;
  184. }
  185. if (is_sequence)
  186. grouped_inputs.Add(inputs.Skip(i).Take(input_len).ToArray());
  187. else
  188. grouped_inputs.Add(inputs[i]);
  189. i += input_len;
  190. }
  191. return grouped_inputs.ToArray();
  192. }
  193. public T get_attr<T>(string name)
  194. => (T)get_attr(name);
  195. public virtual object get_attr(string name)
  196. {
  197. AttrValue x = null;
  198. lock (Locks.ProcessWide)
  199. {
  200. using var buf = new Buffer();
  201. c_api.TF_OperationGetAttrValueProto(_handle, name, buf.Handle, tf.status.Handle);
  202. tf.status.Check(true);
  203. x = AttrValue.Parser.ParseFrom(buf.DangerousMemoryBlock.Stream());
  204. }
  205. string oneof_value = x.ValueCase.ToString();
  206. if (string.IsNullOrEmpty(oneof_value))
  207. return null;
  208. if (oneof_value == "list")
  209. throw new NotImplementedException($"Unsupported field type in {x.ToString()}");
  210. if (oneof_value == "type")
  211. return x.Type;
  212. object result = x.GetType().GetProperty(oneof_value).GetValue(x);
  213. if (result is Google.Protobuf.ByteString byteString)
  214. return byteString.ToStringUtf8();
  215. return result;
  216. }
  217. public TF_AttrMetadata GetAttributeMetadata(string attr_name, Status s)
  218. {
  219. return c_api.TF_OperationGetAttrMetadata(_handle, attr_name, s.Handle);
  220. }
  221. private NodeDef GetNodeDef()
  222. {
  223. lock (Locks.ProcessWide)
  224. using (var s = new Status())
  225. using (var buffer = new Buffer())
  226. {
  227. c_api.TF_OperationToNodeDef(_handle, buffer.Handle, s.Handle);
  228. s.Check();
  229. return NodeDef.Parser.ParseFrom(buffer.DangerousMemoryBlock.Stream());
  230. }
  231. }
  232. /// <summary>
  233. /// Update the input to this operation at the given index.
  234. ///
  235. /// NOTE: This is for TF internal use only.Please don't use it.
  236. /// </summary>
  237. /// <param name="index">the index of the input to update.</param>
  238. /// <param name="tensor"> the Tensor to be used as the input at the given index.</param>
  239. public void _update_input(int index, Tensor tensor)
  240. {
  241. _assert_same_graph(tensor);
  242. var input = _tf_input(index);
  243. var output = tensor._as_tf_output();
  244. // Reset cached inputs.
  245. _inputs_val = null;
  246. // after the c_api call next time _inputs is accessed
  247. // the updated inputs are reloaded from the c_api
  248. lock (Locks.ProcessWide)
  249. {
  250. c_api.UpdateEdge(_graph, output, input, tf.status.Handle);
  251. //var updated_inputs = inputs;
  252. tf.status.Check();
  253. }
  254. }
  255. private void _assert_same_graph(Tensor tensor)
  256. {
  257. //TODO: implement
  258. }
  259. /// <summary>
  260. /// Create and return a new TF_Output for output_idx'th output of this op.
  261. /// </summary>
  262. public TF_Output _tf_output(int output_idx)
  263. {
  264. return new TF_Output(op, output_idx);
  265. }
  266. /// <summary>
  267. /// Create and return a new TF_Input for input_idx'th input of this op.
  268. /// </summary>
  269. public TF_Input _tf_input(int input_idx)
  270. {
  271. return new TF_Input(op, input_idx);
  272. }
  273. }
  274. }