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