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.

Graph.cs 13 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
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
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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Runtime.InteropServices;
  5. using System.Text;
  6. namespace Tensorflow
  7. {
  8. /// <summary>
  9. /// TensorFlow uses a dataflow graph to represent your computation in terms of the dependencies between individual operations.
  10. /// This leads to a low-level programming model in which you first define the dataflow graph,
  11. /// then create a TensorFlow session to run parts of the graph across a set of local and remote devices.
  12. /// https://www.tensorflow.org/guide/graphs
  13. /// </summary>
  14. public partial class Graph : IPython, IDisposable
  15. {
  16. private IntPtr _handle;
  17. private Dictionary<int, ITensorOrOperation> _nodes_by_id;
  18. public Dictionary<string, ITensorOrOperation> _nodes_by_name;
  19. private Dictionary<string, int> _names_in_use;
  20. public int _version;
  21. private int _next_id_counter;
  22. private List<String> _unfetchable_ops = new List<string>();
  23. public string _name_stack = "";
  24. public string _graph_key;
  25. public Status Status { get; }
  26. /// <summary>
  27. /// True if the graph is considered "finalized". In that case no
  28. /// new operations can be added.
  29. /// </summary>
  30. private bool _finalized = false;
  31. /// <summary>
  32. /// Arbitrary collections of objects.
  33. /// </summary>
  34. private Dictionary<string, object> _collections = new Dictionary<string, object>();
  35. public Graph()
  36. {
  37. _handle = c_api.TF_NewGraph();
  38. Status = new Status();
  39. _nodes_by_id = new Dictionary<int, ITensorOrOperation>();
  40. _nodes_by_name = new Dictionary<string, ITensorOrOperation>();
  41. _names_in_use = new Dictionary<string, int>();
  42. _graph_key = $"grap-key-{ops.uid()}/";
  43. }
  44. public Graph(IntPtr handle)
  45. {
  46. _handle = handle;
  47. Status = new Status();
  48. _nodes_by_id = new Dictionary<int, ITensorOrOperation>();
  49. _nodes_by_name = new Dictionary<string, ITensorOrOperation>();
  50. _names_in_use = new Dictionary<string, int>();
  51. _graph_key = $"grap-key-{ops.uid()}/";
  52. }
  53. public ITensorOrOperation as_graph_element(object obj, bool allow_tensor = true, bool allow_operation = true)
  54. {
  55. return _as_graph_element_locked(obj, allow_tensor, allow_operation);
  56. }
  57. public Graph as_default() => ops.set_default_graph(this);
  58. private Tensor _as_graph_element(object obj)
  59. {
  60. if (obj is RefVariable var)
  61. return var._as_graph_element();
  62. return null;
  63. }
  64. private ITensorOrOperation _as_graph_element_locked(object obj, bool allow_tensor = true, bool allow_operation = true)
  65. {
  66. string types_str = "";
  67. if (allow_tensor && allow_operation)
  68. {
  69. types_str = "Tensor or Operation";
  70. }
  71. else if (allow_tensor)
  72. {
  73. types_str = "Tensor";
  74. }
  75. else if (allow_operation)
  76. {
  77. types_str = "Operation";
  78. }
  79. var temp_obj = _as_graph_element(obj);
  80. if (temp_obj != null)
  81. obj = temp_obj;
  82. // If obj appears to be a name...
  83. if (obj is string name)
  84. {
  85. if(name.Contains(":") && allow_tensor)
  86. {
  87. string op_name = name.Split(':')[0];
  88. int out_n = int.Parse(name.Split(':')[1]);
  89. if (_nodes_by_name.ContainsKey(op_name))
  90. return _nodes_by_name[op_name].outputs[out_n];
  91. }
  92. else if(!name.Contains(":") & allow_operation)
  93. {
  94. if (!_nodes_by_name.ContainsKey(name))
  95. throw new KeyError($"The name {name} refers to an Operation not in the graph.");
  96. return _nodes_by_name[name];
  97. }
  98. else if (!name.Contains(":") & !allow_operation)
  99. {
  100. throw new NotImplementedException("_as_graph_element_locked");
  101. }
  102. }
  103. if (obj is Tensor tensor && allow_tensor)
  104. {
  105. if (tensor.graph.Equals(this))
  106. {
  107. return tensor;
  108. }
  109. else
  110. {
  111. throw new Exception($"Tensor {obj} is not an element of this graph.");
  112. }
  113. }
  114. else if (obj is Operation op && allow_operation)
  115. {
  116. if (op.graph.Equals(this))
  117. {
  118. return op;
  119. }
  120. else
  121. {
  122. throw new Exception($"Operation {obj} is not an element of this graph.");
  123. }
  124. }
  125. throw new Exception($"Can not convert a {obj.GetType().Name} into a {types_str}.");
  126. }
  127. public void add_to_collection<T>(string name, T value)
  128. {
  129. _check_not_finalized();
  130. if (_collections.ContainsKey(name))
  131. (_collections[name] as List<T>).Add(value);
  132. else
  133. _collections[name] = new List<T> { value };
  134. }
  135. public void add_to_collections<T>(List<string> names, T value)
  136. {
  137. foreach (string name in names)
  138. add_to_collection(name, value);
  139. }
  140. private void _check_not_finalized()
  141. {
  142. if (_finalized)
  143. throw new RuntimeError("Graph is finalized and cannot be modified.");
  144. }
  145. public unsafe Operation create_op(string op_type, Tensor[] inputs, TF_DataType[] dtypes,
  146. TF_DataType[] input_types = null, string name = null,
  147. Dictionary<string, AttrValue> attrs = null, OpDef op_def = null)
  148. {
  149. if (inputs == null)
  150. inputs = new Tensor[0];
  151. foreach ((int idx, Tensor a) in Python.enumerate(inputs))
  152. {
  153. }
  154. if (String.IsNullOrEmpty(name))
  155. name = op_type;
  156. // If a names ends with a '/' it is a "name scope" and we use it as-is,
  157. // after removing the trailing '/'.
  158. name = name.EndsWith("/") ? ops._name_from_scope_name(name) : unique_name(name);
  159. var node_def = ops._NodeDef(op_type, name, device: "", attrs: attrs);
  160. var input_ops = inputs.Select(x => x.op).ToArray();
  161. var control_inputs = _control_dependencies_for_inputs(input_ops);
  162. var op = new Operation(node_def,
  163. this,
  164. inputs: inputs,
  165. output_types: dtypes,
  166. control_inputs: control_inputs,
  167. input_types: input_types,
  168. original_op: null,
  169. op_def: op_def);
  170. _create_op_helper(op, true);
  171. /*Console.Write($"create_op: {op_type} '{node_def.Name}'");
  172. Console.Write($", inputs: {(inputs.Length == 0 ? "empty" : String.Join(", ", inputs.Select(x => x.name)))}");
  173. Console.Write($", control_inputs: {(control_inputs.Length == 0 ? "empty" : String.Join(", ", control_inputs.Select(x => x.name)))}");
  174. Console.Write($", outputs: {(op.outputs.Length == 0 ? "empty" : String.Join(", ", op.outputs.Select(x => x.name)))}");
  175. Console.WriteLine();*/
  176. return op;
  177. }
  178. private void _create_op_helper(Operation op, bool compute_device = true)
  179. {
  180. _record_op_seen_by_control_dependencies(op);
  181. }
  182. public void _add_op(Operation op)
  183. {
  184. op._id_value = _next_id();
  185. _nodes_by_id[op._id] = op;
  186. _nodes_by_name[op.name] = op;
  187. _version = Math.Max(_version, op._id);
  188. }
  189. public int _next_id()
  190. {
  191. return ++_next_id_counter;
  192. }
  193. public bool is_fetchable<T>(T tensor_or_op)
  194. {
  195. if (tensor_or_op is Tensor)
  196. {
  197. return !_unfetchable_ops.Contains((tensor_or_op as Tensor).name); ;
  198. }
  199. else if (tensor_or_op is Operation)
  200. {
  201. return !_unfetchable_ops.Contains((tensor_or_op as Operation).name);
  202. }
  203. return false;
  204. }
  205. public string get_name_scope()
  206. {
  207. return _name_stack;
  208. }
  209. public string name_scope(string name)
  210. {
  211. string new_stack = "";
  212. if (string.IsNullOrEmpty(name))
  213. new_stack = "";
  214. else if (name.EndsWith("/"))
  215. new_stack = ops._name_from_scope_name(name);
  216. else
  217. new_stack = unique_name(name);
  218. _name_stack = new_stack;
  219. return String.IsNullOrEmpty(new_stack) ? "" : new_stack + "/";
  220. }
  221. public string unique_name(string name, bool mark_as_used = true)
  222. {
  223. if (!String.IsNullOrEmpty(_name_stack))
  224. {
  225. name = _name_stack + "/" + name;
  226. }
  227. var name_key = name.ToLower();
  228. int i = 0;
  229. if (_names_in_use.ContainsKey(name_key))
  230. {
  231. foreach (var item in _names_in_use)
  232. {
  233. if (item.Key == name_key)
  234. {
  235. i = _names_in_use[name_key];
  236. break;
  237. }
  238. i++;
  239. }
  240. }
  241. if (mark_as_used)
  242. if (_names_in_use.ContainsKey(name_key))
  243. _names_in_use[name_key]++;
  244. else
  245. _names_in_use[name_key] = i + 1;
  246. if (i > 0)
  247. {
  248. var base_name_key = name_key;
  249. // Make sure the composed name key is not already used.
  250. if (_names_in_use.ContainsKey(name_key))
  251. {
  252. name_key = $"{base_name_key}_{i}";
  253. i += 1;
  254. }
  255. if (mark_as_used)
  256. _names_in_use[name_key] = 1;
  257. name = $"{name}_{i - 1}";
  258. }
  259. return name;
  260. }
  261. public TF_Output[] ReturnOutputs(IntPtr results)
  262. {
  263. IntPtr return_output_handle = IntPtr.Zero;
  264. int num_return_outputs = 0;
  265. c_api.TF_ImportGraphDefResultsReturnOutputs(results, ref num_return_outputs, ref return_output_handle);
  266. TF_Output[] return_outputs = new TF_Output[num_return_outputs];
  267. for (int i = 0; i < num_return_outputs; i++)
  268. {
  269. var handle = return_output_handle + (Marshal.SizeOf<TF_Output>() * i);
  270. return_outputs[i] = Marshal.PtrToStructure<TF_Output>(handle);
  271. }
  272. return return_outputs;
  273. }
  274. public unsafe Operation[] ReturnOperations(IntPtr results)
  275. {
  276. TF_Operation return_oper_handle = new TF_Operation();
  277. int num_return_opers = 0;
  278. c_api.TF_ImportGraphDefResultsReturnOperations(results, ref num_return_opers, ref return_oper_handle);
  279. Operation[] return_opers = new Operation[num_return_opers];
  280. for (int i = 0; i < num_return_opers; i++)
  281. {
  282. var handle = return_oper_handle.node + Marshal.SizeOf<TF_Operation>() * i;
  283. return_opers[i] = new Operation(*(IntPtr*)handle);
  284. }
  285. return return_opers;
  286. }
  287. public Operation OperationByName(string operName)
  288. {
  289. return c_api.TF_GraphOperationByName(_handle, operName);
  290. }
  291. public ITensorOrOperation[] get_operations()
  292. {
  293. return _nodes_by_name.Values.Select(x => x).ToArray();
  294. }
  295. public string[] get_all_collection_keys()
  296. {
  297. return _collections.Keys.Where(x => !x.StartsWith("__")).ToArray();
  298. }
  299. public object get_collection(string name, string scope = "")
  300. {
  301. return _collections.ContainsKey(name) ? _collections[name] : null;
  302. }
  303. public object get_collection_ref(string name)
  304. {
  305. if (!_collections.ContainsKey(name))
  306. _collections[name] = new List<object>();
  307. return _collections[name];
  308. }
  309. public void Dispose()
  310. {
  311. c_api.TF_DeleteGraph(_handle);
  312. }
  313. public void __enter__()
  314. {
  315. }
  316. public void __exit__()
  317. {
  318. }
  319. public static implicit operator IntPtr(Graph graph)
  320. {
  321. return graph._handle;
  322. }
  323. }
  324. }

tensorflow框架的.NET版本,提供了丰富的特性和API,可以借此很方便地在.NET平台下搭建深度学习训练与推理流程。