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

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

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